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
573204aa068edd4a5b3c20ee6fac895ca77fecf1
168
cpp
C++
HW04/CharStack.cpp
CS-CMU/cs251
ba8fac9ee9da293f8e7a6d193657e0d217d9dd2b
[ "MIT" ]
null
null
null
HW04/CharStack.cpp
CS-CMU/cs251
ba8fac9ee9da293f8e7a6d193657e0d217d9dd2b
[ "MIT" ]
null
null
null
HW04/CharStack.cpp
CS-CMU/cs251
ba8fac9ee9da293f8e7a6d193657e0d217d9dd2b
[ "MIT" ]
5
2021-11-21T13:38:48.000Z
2022-01-14T15:55:02.000Z
class CharStack { public: CharStack() { // constructor } void push(char new_item) { } char pop() { } char top() { } bool isEmpty() { } };
7
30
0.505952
CS-CMU
5733c17490f9e7a52119aa9e49f101dac1911c59
74
hxx
C++
src/interfaces/python/opengm/opengmcore/pyFunctionGen.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
src/interfaces/python/opengm/opengmcore/pyFunctionGen.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
src/interfaces/python/opengm/opengmcore/pyFunctionGen.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
template<class GM_ADDER,class GM_MULT> void export_function_generator();
37
40
0.837838
burcin
573c31201bcf0f08edda0898921ef20855dee8c6
3,151
cpp
C++
packages/optionPricer2/src/AsianOption.cpp
pawelsakowski/AF-RCPP-2020-2021
c44eea09235e03097c18f13381de9b5b93806138
[ "Apache-2.0" ]
6
2020-11-03T10:56:58.000Z
2021-03-26T14:49:42.000Z
packages/optionPricer2/src/AsianOption.cpp
pawelsakowski/AF-RCPP-2021-2022
60f9aa4300fa2cc14c35213ea39b81b3656ae900
[ "Apache-2.0" ]
null
null
null
packages/optionPricer2/src/AsianOption.cpp
pawelsakowski/AF-RCPP-2021-2022
60f9aa4300fa2cc14c35213ea39b81b3656ae900
[ "Apache-2.0" ]
3
2021-12-01T21:09:06.000Z
2022-01-30T14:36:17.000Z
#include<iostream> #include<cmath> #include"getOneGaussianByBoxMueller.h" #include"AsianOption.h" //definition of constructor AsianOption::AsianOption( int nInt_, double strike_, double spot_, double vol_, double r_, double expiry_){ nInt = nInt_; strike = strike_; spot = spot_; vol = vol_; r = r_; expiry = expiry_; generatePath(); } //method definition void AsianOption::generatePath(){ double thisDrift = (r * expiry - 0.5 * vol * vol * expiry) / double(nInt); double cumShocks = 0; thisPath.clear(); for(int i = 0; i < nInt; i++){ cumShocks += (thisDrift + vol * sqrt(expiry / double(nInt)) * getOneGaussianByBoxMueller()); thisPath.push_back(spot * exp(cumShocks)); } } //method definition double AsianOption::getArithmeticMean(){ double runningSum = 0.0; for(int i = 0; i < nInt; i++){ runningSum += thisPath[i]; } return runningSum/double(nInt); } //method definition double AsianOption::getGeometricMean(){ double runningSum = 0.0; for(int i = 0; i < nInt ; i++){ runningSum += log(thisPath[i]); } return exp(runningSum/double(nInt)); } //method definition void AsianOption::printPath(){ for(int i = 0; i < nInt; i++){ std::cout << thisPath[i] << "\n"; } } //method definition double AsianOption::getArithmeticAsianCallPrice(int nReps){ double rollingSum = 0.0; double thisMean = 0.0; for(int i = 0; i < nReps; i++){ generatePath(); thisMean=getArithmeticMean(); rollingSum += (thisMean > strike) ? (thisMean-strike) : 0; } return exp(-r*expiry)*rollingSum/double(nReps); } //method definition double AsianOption::getArithmeticAsianPutPrice(int nReps){ double rollingSum = 0.0; double thisMean = 0.0; for(int i = 0; i < nReps; i++){ generatePath(); thisMean=getArithmeticMean(); rollingSum += (thisMean < strike) ? (strike - thisMean) : 0; } return exp(-r*expiry)*rollingSum/double(nReps); } //method definition double AsianOption::getGeometricAsianCallPrice(int nReps){ double rollingSum = 0.0; double thisMean = 0.0; for(int i = 0; i < nReps; i++){ generatePath(); thisMean=getGeometricMean(); rollingSum += (thisMean > strike)? (thisMean-strike) : 0; } return exp(-r*expiry)*rollingSum/double(nReps); } //method definition double AsianOption::getGeometricAsianPutPrice(int nReps){ double rollingSum = 0.0; double thisMean = 0.0; for(int i = 0; i < nReps; i++){ generatePath(); thisMean=getGeometricMean(); rollingSum += (thisMean < strike)? (strike - thisMean) : 0; } return exp(-r*expiry)*rollingSum/double(nReps); } //overloaded operator (); double AsianOption::operator()(char char1, char char2, int nReps){ if ((char1 == 'A') & (char2 =='C')) return getArithmeticAsianCallPrice(nReps); else if ((char1 == 'A') & (char2 =='P')) return getArithmeticAsianPutPrice(nReps); else if ((char1 == 'G') & (char2 =='C')) return getGeometricAsianCallPrice(nReps); else if ((char1 == 'G') & (char2 =='P')) return getGeometricAsianPutPrice(nReps); else return -99; }
21.881944
95
0.643288
pawelsakowski
574258fef1aa820127ac6b1332aba664d13a6abe
2,160
cpp
C++
Project/Dev_class11_handout/Motor2D/Move.cpp
Guille1406/Project-II
af954426efce06937671f02ac0a5840e5faefb0e
[ "Apache-2.0" ]
null
null
null
Project/Dev_class11_handout/Motor2D/Move.cpp
Guille1406/Project-II
af954426efce06937671f02ac0a5840e5faefb0e
[ "Apache-2.0" ]
null
null
null
Project/Dev_class11_handout/Motor2D/Move.cpp
Guille1406/Project-II
af954426efce06937671f02ac0a5840e5faefb0e
[ "Apache-2.0" ]
null
null
null
#include "j1Player.h" #include "j1App.h" #include "j1Window.h" #include "j1Render.h" #include "p2Log.h" #include "Character.h" void Character::Attack(float dt) { } void Character::Move(float dt) { uint x = 0, y = 0; App->win->GetWindowSize(x, y); // SHORT VARIABLES int pos_x = this->pos.x; int pos_y = this->pos.y; int tile_pos_x = this->tilepos.x; int tile_pos_y = this->tilepos.y; ////Camera //DIAGONAL TILES uint diagonal_right_up = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x + 2, tile_pos_y -1); uint diagonal_left_up = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x -1, tile_pos_y - 1); uint diagonal_right_down = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x +2, tile_pos_y +2); uint diagonal_left_down = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x -1, tile_pos_y +2); ///// float speed = 4/dt; switch (movement_direction) { case move_up: this->can_walk = MoveFunction(dt, pos.y, pos.x, false, adjacent.up, adjacent.left.i, adjacent.right.i); break; case move_down: this->can_walk = MoveFunction(dt, pos.y, pos.x, true, adjacent.down, adjacent.left.j, adjacent.right.j, true); break; case move_left: this->can_walk = MoveFunction(dt, pos.x, pos.y, false, adjacent.left, adjacent.up.i, adjacent.down.i); break; case move_right: this->can_walk = MoveFunction(dt, pos.x, pos.y, true, adjacent.right, adjacent.up.j, adjacent.down.j, true); break; case move_up_left: this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, false, false, adjacent.up.i, adjacent.left.i, diagonal_left_up); break; case move_up_right: this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, false, true, adjacent.up.j, adjacent.right.i, diagonal_right_up); break; case move_down_left: this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, true, false, adjacent.down.i, adjacent.left.j, diagonal_left_down, true); break; case move_down_right: this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, true, true, adjacent.down.j, adjacent.right.j, diagonal_right_down, true); break; } }
25.714286
132
0.701852
Guille1406
57453b009928209f0872850ca3b4b86edb06f669
112,541
cpp
C++
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_Engine.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_Engine.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_Engine.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDMacroEng_Engine.cpp // // AUTHOR: Dean Roddey // // CREATED: 01/14/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements TMacroEngEngine class. This class represents an // instance of the expression engine. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CIDMacroEng_.hpp" // --------------------------------------------------------------------------- // Magic RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TCIDMacroEngine,TObject) // --------------------------------------------------------------------------- // Local types and constants // --------------------------------------------------------------------------- namespace { namespace CIDMacroEng_Engine { // ----------------------------------------------------------------------- // A flag to handle local lazy init // ----------------------------------------------------------------------- TAtomicFlag atomInitDone; // ----------------------------------------------------------------------- // Some stats cache items we maintain // ----------------------------------------------------------------------- TStatsCacheItem sciMacroEngCount; } } // --------------------------------------------------------------------------- // CLASS: TMEngCallStackJan // PREFIX: jan // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngCallStackJan: Constructors and Destructor // --------------------------------------------------------------------------- TMEngCallStackJan::TMEngCallStackJan(TCIDMacroEngine* const pmeToRestore) : m_c4OrgTop(0) , m_pmeToRestore(pmeToRestore) { // Could be null so check before we store if (m_pmeToRestore) m_c4OrgTop = pmeToRestore->c4StackTop(); } TMEngCallStackJan::~TMEngCallStackJan() { if (m_pmeToRestore) { try { m_pmeToRestore->PopBackTo(m_c4OrgTop); } catch(TError& errToCatch) { if (!errToCatch.bLogged()) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } } } // --------------------------------------------------------------------------- // CLASS: TCIDMacroEngine // PREFIX: eeng // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TCIDMacroEngine: Constructors and Destructor // --------------------------------------------------------------------------- TCIDMacroEngine::TCIDMacroEngine() : m_bDebugMode(kCIDLib::False) , m_bInIDE(kCIDLib::False) , m_bValidation(kCIDLib::False) , m_c2ArrayId(kCIDMacroEng::c2BadId) , m_c2NextClassId(0) , m_c2VectorId(kCIDMacroEng::c2BadId) , m_c4CallStackTop(0) , m_c4CurLine(0) , m_c4NextUniqueId(1) , m_colCallStack(tCIDLib::EAdoptOpts::Adopt, 64) , m_colClasses ( tCIDLib::EAdoptOpts::NoAdopt , 29 , TStringKeyOps() , &TMEngClassInfo::strKey ) , m_colClassesById(tCIDLib::EAdoptOpts::Adopt, 128) , m_colTempPool(32) , m_eExceptReport(tCIDMacroEng::EExceptReps::NotHandled) , m_pcuctxRights(nullptr) , m_pmedbgToUse(nullptr) , m_pmeehToUse(nullptr) , m_pmefrToUse(nullptr) , m_pmecvThrown(nullptr) , m_pstrmConsole(nullptr) { // Make sure our facility has faulted in facCIDMacroEng(); // Do local lazy init if required if (!CIDMacroEng_Engine::atomInitDone) { TBaseLock lockInit; if (!CIDMacroEng_Engine::atomInitDone) { TStatsCache::RegisterItem ( kCIDMacroEng::pszStat_MEng_EngInstCount , tCIDLib::EStatItemTypes::Counter , CIDMacroEng_Engine::sciMacroEngCount ); CIDMacroEng_Engine::atomInitDone.Set(); } } // // Register the small number of instrinc classes that are always // available without being asked for. // RegisterBuiltInClasses(); // Increment the count of registered engines TStatsCache::c8IncCounter(CIDMacroEng_Engine::sciMacroEngCount); } TCIDMacroEngine::~TCIDMacroEngine() { // Decrement the count of registered engines TStatsCache::c8DecCounter(CIDMacroEng_Engine::sciMacroEngCount); try { // // Do some common cleanup that is down each time the entine is // prepped for a new run. Tell it this time to remove all of // them, whereas normally it leaves the built in classes alone. // Cleanup(kCIDLib::True); // // And clean up some other stuff that only get's dropped when we // going away. // // Note that we don't own any of the handler callback objects or // the console stream. // delete m_pmecvThrown; } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } catch(...) { } } // --------------------------------------------------------------------------- // TCIDMacroEngine: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TCIDMacroEngine::AddBoolParm( TParmList& colTar , const TString& strName , const tCIDLib::TBoolean bConst) { const TMEngClassInfo& meciBool = meciFind(L"MEng.Boolean"); colTar.Add ( meciBool.pmecvMakeStorage ( strName , *this , bConst ? tCIDMacroEng::EConstTypes::Const : tCIDMacroEng::EConstTypes::NonConst ) ); } tCIDLib::TVoid TCIDMacroEngine::AddStringParm( TParmList& colTar , const TString& strName , const tCIDLib::TBoolean bConst) { const TMEngClassInfo& meciString = meciFind(L"MEng.String"); colTar.Add ( meciString.pmecvMakeStorage ( strName , *this , bConst ? tCIDMacroEng::EConstTypes::Const : tCIDMacroEng::EConstTypes::NonConst ) ); } tCIDLib::TBoolean TCIDMacroEngine::bAreEquivCols( const tCIDLib::TCard2 c2ClassId1 , const tCIDLib::TCard2 c2ClassId2 , const tCIDLib::TBoolean bSameElemType) const { const TMEngClassInfo& meci1 = meciFind(c2ClassId1); const TMEngClassInfo& meci2 = meciFind(c2ClassId2); // They have to both be collection classes if (!bIsCollectionClass(meci1.c2ParentClassId()) || !bIsCollectionClass(meci2.c2ParentClassId())) { return kCIDLib::False; } // And they both must derive from the same base collection class if (meci1.c2ParentClassId() != meci2.c2ParentClassId()) return kCIDLib::False; // // If the caller says the element types must be the same, then check that. // if (bSameElemType) { return (static_cast<const TMEngColBaseInfo&>(meci1).c2ElemId() == static_cast<const TMEngColBaseInfo&>(meci2).c2ElemId()); } // // Else the second element type must derive from the first. This method takes // the base class as the second parm and the one to test as the first. // return bIsDerivedFrom ( static_cast<const TMEngColBaseInfo&>(meci2).c2ElemId() , static_cast<const TMEngColBaseInfo&>(meci1).c2ElemId() ); } // Get set the 'in IDE' flag, which the IDE sets on us. Otherwise it's false always tCIDLib::TBoolean TCIDMacroEngine::bInIDE() const { return m_bInIDE; } tCIDLib::TBoolean TCIDMacroEngine::bInIDE(const tCIDLib::TBoolean bToSet) { m_bInIDE = bToSet; return m_bInIDE; } // Return the debug mode flag tCIDLib::TBoolean TCIDMacroEngine::bDebugMode(const tCIDLib::TBoolean bToSet) { m_bDebugMode = bToSet; return m_bDebugMode; } // Used to format stack dumps tCIDLib::TBoolean TCIDMacroEngine::bFormatNextCallFrame( TTextOutStream& strmTarget , tCIDLib::TCard4& c4PrevInd) { // // If the previous id is max card, then we are to do the first one. // Else, we are working down and need to find the previous one. // TMEngCallStackItem* pmecsiCur = nullptr; if (c4PrevInd == kCIDLib::c4MaxCard) { // If we don't have any entries, nothing to do if (!m_c4CallStackTop) { strmTarget << L"<Empty>"; c4PrevInd = 0; } else { // // Start at the top of the call stack and work down to the first // method call opcode, which is what we want to start with. // c4PrevInd = m_c4CallStackTop; do { c4PrevInd--; pmecsiCur = m_colCallStack[c4PrevInd]; if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall) break; } while (c4PrevInd != 0); // // If we hit zero, then nothing, else call a private helper to // format this one. // if (c4PrevInd) FormatAFrame(strmTarget, c4PrevInd); } } else { // // Find the previous item on the stack, starting at one before the // previous item. // do { c4PrevInd--; pmecsiCur = m_colCallStack[c4PrevInd]; if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall) break; } while (c4PrevInd != 0); // // If we hit zero, then nothing, else call a private helper to // format this one. // if (c4PrevInd) FormatAFrame(strmTarget, c4PrevInd); } return (c4PrevInd != 0); } tCIDLib::TBoolean TCIDMacroEngine::bGetLastExceptInfo(TString& strClass , TString& strText , tCIDLib::TCard4& c4Line) { if (m_pmecvThrown) { strClass = m_pmecvThrown->strSrcClassPath(); strText = m_pmecvThrown->strErrorText(); c4Line = m_pmecvThrown->c4LineNum(); return kCIDLib::True; } return kCIDLib::False; } tCIDLib::TBoolean TCIDMacroEngine::bInvokeDefCtor( TMEngClassVal& mecvTarget , const TCIDUserCtx* const pcuctxRights) { try { // Set the passed user contact while we are in here TGFJanitor<const TCIDUserCtx*> janRights(&m_pcuctxRights, pcuctxRights); // // If the temp pool is empty, then this is the first time this // engine instance has been used, so we need to initialize the // pool. // if (m_colTempPool.bIsEmpty()) InitTempPool(); // Look up it's class const TMEngClassInfo& meciTarget = meciFind(mecvTarget.c2ClassId()); // // And ask it for it's default ctor, if any. Note that we look up // the INFO not the IMPL here, since it could be a class that is // just wrapping C++ code and it won't have any CML level impl. // const TMEngMethodInfo* pmethiDefCtor = meciTarget.pmethiDefCtor(); if (!pmethiDefCtor) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcClass_NoDefCtor , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotFound , meciTarget.strClassPath() ); // Won't happen but makes analyzer happy return kCIDLib::False; } // // Push a void return value, the method call, and invoke it. We // indicate a monomorphic invocation here, since it has to be // our guy that we are targeting. // PushPoolValue(tCIDMacroEng::EIntrinsics::Void, tCIDMacroEng::EConstTypes::Const); meciPushMethodCall(meciTarget.c2Id(), pmethiDefCtor->c2Id()); meciTarget.Invoke ( *this , mecvTarget , pmethiDefCtor->c2Id() , tCIDMacroEng::EDispatch::Mono ); // We have to pop the method call and return off MultiPop(2); } catch(const TDbgExitException& excptForce) { if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(excptForce.m_eReason); return kCIDLib::False; } catch(const TExceptException&) { // // If there is an herror handler, and we are in the mode where we // report macros if they aren'thandled, then report it. If we are // in the other mode, it will already have been reported at the point // of throw. // if (m_pmeehToUse && (m_eExceptReport == tCIDMacroEng::EExceptReps::NotHandled)) m_pmeehToUse->MacroException(*m_pmecvThrown, *this); if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); return kCIDLib::False; } catch(...) { if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); return kCIDLib::False; } return kCIDLib::True; } // // All the collection classes are runtime classes, so we know them and have // their ids stored, so we can provide a quick check. // tCIDLib::TBoolean TCIDMacroEngine::bIsCollectionClass(const tCIDLib::TCard2 c2IdToCheck) const { return ((c2IdToCheck == m_c2ArrayId) || (c2IdToCheck == m_c2VectorId)); } // // Checks to see if one class is derived from aonther, by just walking the // parentage chain. // tCIDLib::TBoolean TCIDMacroEngine::bIsDerivedFrom(const tCIDLib::TCard2 c2IdToTest , const tCIDLib::TCard2 c2BaseClassId) const { tCIDLib::TCard2 c2Cur = c2IdToTest; while (kCIDLib::True) { // // If we've hit the target base class, then it's good. If the test // class is down to the object level, it is not gonna work. // if ((c2Cur == c2BaseClassId) || (c2Cur == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Object))) { break; } // Get the parent class id of the target class, and go again c2Cur = meciFind(c2Cur).c2ParentClassId(); } return (c2Cur == c2BaseClassId); } tCIDLib::TBoolean TCIDMacroEngine::bIsDerivedFrom(const tCIDLib::TCard2 c2IdToTest , const tCIDMacroEng::EIntrinsics eBaseType) const { return bIsDerivedFrom(c2IdToTest, tCIDLib::TCard2(eBaseType)); } // // Literals can only be char, bool, string, or numeric. This is a method // to keep that check in one place. // tCIDLib::TBoolean TCIDMacroEngine::bIsLiteralClass(const tCIDLib::TCard2 c2IdToCheck) const { // If not an intrinsic, then obviously can't be if (c2IdToCheck >= tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Count)) return kCIDLib::False; tCIDLib::TBoolean bRet = kCIDLib::False; switch(tCIDMacroEng::EIntrinsics(c2IdToCheck)) { case tCIDMacroEng::EIntrinsics::Boolean : case tCIDMacroEng::EIntrinsics::Char : case tCIDMacroEng::EIntrinsics::String : case tCIDMacroEng::EIntrinsics::Card1 : case tCIDMacroEng::EIntrinsics::Card2 : case tCIDMacroEng::EIntrinsics::Card4 : case tCIDMacroEng::EIntrinsics::Card8 : case tCIDMacroEng::EIntrinsics::Float4 : case tCIDMacroEng::EIntrinsics::Float8 : case tCIDMacroEng::EIntrinsics::Int1 : case tCIDMacroEng::EIntrinsics::Int2 : case tCIDMacroEng::EIntrinsics::Int4 : bRet = kCIDLib::True; break; default : bRet = kCIDLib::False; break; }; return bRet; } tCIDLib::TBoolean TCIDMacroEngine::bStackValAt(const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Boolean, CID_LINE, c4Index); return static_cast<const TMEngBooleanVal&>(mecvVal).bValue(); } tCIDLib::TBoolean TCIDMacroEngine::bValidation(const tCIDLib::TBoolean bToSet) { m_bValidation = bToSet; return m_bValidation; } tCIDLib::TCard1 TCIDMacroEngine::c1StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card1, CID_LINE, c4Index); return static_cast<const TMEngCard1Val&>(mecvVal).c1Value(); } tCIDLib::TCard2 TCIDMacroEngine::c2AddClass(TMEngClassInfo* const pmeciToAdopt) { // // Give it the next id and bump the id counter, then add it to the // 'by id' lookup vector, so it's now safely adopted. // // NOTE: These are related actions! The id must be a direct index // into the by id vector! // facCIDMacroEng().CheckIdOverflow(m_c2NextClassId, L"classes"); pmeciToAdopt->SetClassId(m_c2NextClassId++); m_colClassesById.Add(pmeciToAdopt); // Initialize the class now pmeciToAdopt->Init(*this); // Add if it not already. If it is already, then throw an error if (!m_colClasses.bAddIfNew(pmeciToAdopt)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_DupClassName , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Already , pmeciToAdopt->strClassPath() ); } // Return the id we gave to this class return pmeciToAdopt->c2Id(); } tCIDLib::TCard2 TCIDMacroEngine::c2AddClassDefer(TMEngClassInfo* const pmeciToAdopt) { // // Give it the next id and bump the id counter, then add it to the // 'by id' lookup vector, so it's now safely adopted. // // NOTE: These are related actions! The id must be a direct index // into the by id vector! // facCIDMacroEng().CheckIdOverflow(m_c2NextClassId, L"classes"); pmeciToAdopt->SetClassId(m_c2NextClassId++); m_colClassesById.Add(pmeciToAdopt); // Add if it not already. If it is already, then throw an error if (!m_colClasses.bAddIfNew(pmeciToAdopt)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_DupClassName , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Already , pmeciToAdopt->strClassPath() ); } // Return the id we gave to this class return pmeciToAdopt->c2Id(); } tCIDLib::TCard2 TCIDMacroEngine::c2EnumValAt(const tCIDLib::TCard4 c4Index , const tCIDLib::TCard2 c2ExpectedId , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), c2ExpectedId, CID_LINE, c4Index); return tCIDLib::TCard2(static_cast<const TMEngEnumVal&>(mecvVal).c4Ordinal()); } tCIDLib::TCard2 TCIDMacroEngine::c2FindClassId( const TString& strClassPath , const tCIDLib::TBoolean bThrowIfNot) const { const TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey ( strClassPath , kCIDLib::False ); if (!pmeciRet) { if (bThrowIfNot) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ClassNotFound , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotFound , strClassPath ); } return kCIDMacroEng::c2BadId; } return pmeciRet->c2Id(); } tCIDLib::TCard2 TCIDMacroEngine::c2FindEntryPoint( TMEngClassInfo& meciTarget , const tCIDLib::TBoolean bThrowIfNot) { // Find a method with the name "Start". TMEngMethodInfo* pmethiTarget = meciTarget.pmethiFind(L"Start"); // // If not there, or it doesn't have the right return type, or isn't // final, it's bad // if (!pmethiTarget || (pmethiTarget->c2RetClassId() != tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int4)) || (pmethiTarget->eExtend() != tCIDMacroEng::EMethExt::Final)) { if (bThrowIfNot) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadEntryPoint , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format ); } return kCIDLib::c2MaxCard; } return pmethiTarget->c2Id(); } tCIDLib::TCard2 TCIDMacroEngine::c2StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card2, CID_LINE, c4Index); return static_cast<const TMEngCard2Val&>(mecvVal).c2Value(); } tCIDLib::TCard4 TCIDMacroEngine::c4ClassCount() const { return m_colClasses.c4ElemCount(); } // // Given a method info object, this method will create a parameter list // object with the appropriate types of objects to pass in to that method. // Generally this is used by external code that needs to call the Start() // method and get information into the parameters in some more complex way // that just passing a command line. // // The passed parm list must be adopting! // tCIDLib::TCard4 TCIDMacroEngine::c4CreateParmList( const TMEngMethodInfo& methiTarget , TParmList& colParms) { // Make sure that the list is adopting if (colParms.eAdopt() != tCIDLib::EAdoptOpts::Adopt) { facCIDLib().ThrowErr ( CID_FILE , CID_LINE , kCIDErrs::errcCol_MustBeAdopting , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::AppError ); } // Loop through and try to create the value objects colParms.RemoveAll(); const tCIDLib::TCard4 c4ParmCount = methiTarget.c4ParmCount(); TString strName; for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCount; c2Id++) { const TMEngParmInfo& mepiTar = methiTarget.mepiFind(c2Id); // The direction indicates whether it's const or not const tCIDMacroEng::EConstTypes eConst ( (mepiTar.eDir() == tCIDMacroEng::EParmDirs::In) ? tCIDMacroEng::EConstTypes::Const : tCIDMacroEng::EConstTypes::NonConst ); // The name we'll give it strName = L"Parm"; strName.AppendFormatted(tCIDLib::TCard4(c2Id + 1)); // Create a new value object of the target type TMEngClassInfo& meciParm = meciFind(mepiTar.c2ClassId()); TMEngClassVal* pmecvNew = meciParm.pmecvMakeStorage ( strName, *this, eConst ); colParms.Add(pmecvNew); } return c4ParmCount; } tCIDLib::TCard4 TCIDMacroEngine::c4FindNextTry(tCIDLib::TCard4& c4CatchIP) const { // // Start at the stack top and search backwards for the next exception // item on the stack. // tCIDLib::TCard4 c4Index = m_c4CallStackTop; while (c4Index) { c4Index--; const TMEngCallStackItem* pmecsiCur = m_colCallStack[c4Index]; if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::Try) { c4CatchIP = pmecsiCur->c4Value(); break; } } // // If we hit the bottom, there isn't one. Note that it could never at // the 0th index, because there has to at least be the initial call // frame. // if (!c4Index) { c4CatchIP = kCIDLib::c4MaxCard; return kCIDLib::c4MaxCard; } return c4Index; } tCIDLib::TCard4 TCIDMacroEngine::c4FirstParmInd(const TMEngMethodInfo& methiCalled) { const tCIDLib::TCard4 c4Ofs = methiCalled.c4ParmCount() + 1; #if CID_DEBUG_ON if (c4Ofs > m_c4CallStackTop) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_CallStackUnderflow , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Underflow ); } #endif return m_c4CallStackTop - c4Ofs; } // Return the next available unique id and increment tCIDLib::TCard4 TCIDMacroEngine::c4NextUniqueId() { return m_c4NextUniqueId++; } // // Retrieve values on the stack at a given index by type, to save a lot of // grunt work all over the place. // tCIDLib::TCard4 TCIDMacroEngine::c4StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card4, CID_LINE, c4Index); return static_cast<const TMEngCard4Val&>(mecvVal).c4Value(); } tCIDLib::TCard8 TCIDMacroEngine::c8StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card8, CID_LINE, c4Index); return static_cast<const TMEngCard8Val&>(mecvVal).c8Value(); } tCIDLib::TCh TCIDMacroEngine::chStackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Char, CID_LINE, c4Index); return static_cast<const TMEngCharVal&>(mecvVal).chValue(); } const TVector<TString>& TCIDMacroEngine::colStackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::StringList, CID_LINE, c4Index); return static_cast<const TMEngStrListVal&>(mecvVal).colValue(); } // // Provide access to any user rights context that the user code may have set // on us. We don't care what it is, it's purely a passthrough for user code. // There is another version that returns a pointer. This is for those clients // that know they set one, and therefore want an exception if one is not set. // const TCIDUserCtx& TCIDMacroEngine::cuctxRights() const { if (!m_pcuctxRights) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NoUserContext , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::AppError ); } return *m_pcuctxRights; } // // Finds the first CML level call on the stack (we might have called down // into C++ code.) If found, it gets the info on the caller and calls back // the debugger pluggin with that information. // tCIDLib::TVoid TCIDMacroEngine::CheckIDEReq() { // If we have no debug interface installed, nothing to do if (!m_pmedbgToUse) return; // // Start at the top of the stack and work backwards till we see a // call from a macro level class. // tCIDLib::TCard4 c4Index = m_c4CallStackTop; if (!c4Index) return; TMEngCallStackItem* pmecsiCur = nullptr; do { c4Index--; pmecsiCur = m_colCallStack[c4Index]; if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall) { if (pmecsiCur->bHasCallerInfo()) break; } } while (c4Index != 0); if (c4Index == 0) return; // Get out the info we need const TMEngClassInfo* pmeciCaller = nullptr; const TMEngOpMethodImpl* pmethCaller = nullptr; const TMEngMethodInfo* pmethiCaller = nullptr; TMEngClassVal* pmecvCaller = nullptr; tCIDLib::TCard4 c4CallIP = kCIDLib::c4MaxCard; tCIDLib::TCard4 c4CallLine = pmecsiCur->c4QueryCallerInfo ( pmeciCaller, pmethiCaller, pmethCaller, pmecvCaller, c4CallIP ); tCIDMacroEng::EDbgActs eAct = m_pmedbgToUse->eAtLine ( *pmeciCaller, *pmethiCaller, *pmethCaller, *pmecvCaller, c4CallLine, c4CallIP ); // // If he tells us to exit, then throw an exception // that will dump us back to the top level, who will // tell the debugger we've exited. // if ((eAct == tCIDMacroEng::EDbgActs::CloseSession) || (eAct == tCIDMacroEng::EDbgActs::Exit)) { throw TDbgExitException(eAct); } } tCIDLib::TVoid TCIDMacroEngine::CheckSameClasses( const TMEngClassVal& mecv1 , const TMEngClassVal& mecv2) const { // If the second isn't the same or derived from the first, it's not eqiuv if (mecv1.c2ClassId() != mecv2.c2ClassId()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcClass_Mismatch , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , strClassPathForId(mecv1.c2ClassId()) , strClassPathForId(mecv2.c2ClassId()) ); } } tCIDLib::TVoid TCIDMacroEngine::CheckStackTop( const tCIDLib::TCard2 c2ExpectedClassId , const tCIDMacroEng::EConstTypes eConst) const { // // Get the value on the top of the stack. If it's not a value item, // this will throw. // const TMEngClassVal& mecvVal = mecsiAt(m_c4CallStackTop - 1).mecvPushed(); // Make sure it meets the target criteria if (mecvVal.c2ClassId() != c2ExpectedClassId) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotStackItemType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , strClassPathForId(c2ExpectedClassId) ); } if (mecvVal.eConst() != eConst) { tCIDLib::TErrCode errcToThrow = kMEngErrs::errcEng_NotNConstStackItem; if (eConst == tCIDMacroEng::EConstTypes::Const) errcToThrow = kMEngErrs::errcEng_NotConstStackItem; facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , errcToThrow , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , strClassPathForId(c2ExpectedClassId) ); } } // // Cleans up the data that is accumulated during a run of the compiler, // so that it's ready for another around. Not that we can be told not to // remove the built in classes, which is typically the case. They can stay // the same forever and only need to be removed when the engine is // destroyed. // tCIDLib::TVoid TCIDMacroEngine::Cleanup(const tCIDLib::TBoolean bRemoveBuiltIns) { // // Clean up the classes. If removing built ins as well, then we // can do the simple scenario. Else we go through and only remove // the non-built ins. // try { // We flush the by name list either way m_colClasses.RemoveAll(); if (bRemoveBuiltIns) { // And we are doing them all so just whack the by id list, too m_colClassesById.RemoveAll(); } else if (m_colClassesById.bIsEmpty()) { // Built ins are already removed, make sure the by name list is clean m_colClasses.RemoveAll(); } else { // // The array id that we use as the last built in id has to be // beyond the last of the intrinsic ids. So sanity check that. // CIDAssert ( m_c2ArrayId >= tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Count) , L"Invalid array id in CML engine cleanup" ); // // We have to leave the built ins. The most efficent way // to do this is to delete all of the ones from the by id // list that are past the last built in id. Then just go // back and add the remaining ones back to the by name // list again. Go backwards to avoid recompaction every time. // tCIDLib::TCard4 c4Index = m_colClassesById.c4ElemCount() - 1; const tCIDLib::TCard4 c4Last = m_c2ArrayId; while (c4Index > c4Last) m_colClassesById.RemoveAt(c4Index--); // Ok, now add the ones left back for (c4Index = 0; c4Index <= c4Last; c4Index++) m_colClasses.Add(m_colClassesById[c4Index]); } } catch(TError& errToCatch) { if (!errToCatch.bLogged()) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_CleanupErr , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus ); } // And clean up the temp pool try { m_colTempPool.RemoveAll(); } catch(TError& errToCatch) { if (!errToCatch.bLogged()) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_CleanupErr , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus ); } // Reset the console output stream if (m_pstrmConsole) m_pstrmConsole->Reset(); } // // Takes an OS level file path and converts it to the CML level file // path. To go the other way use bExpandFilePath(). // tCIDLib::TVoid TCIDMacroEngine::ContractFilePath( const TString& strOSPath , TPathStr& pathToFill) { m_pmefrToUse->ContractPath(strOSPath, pathToFill); // Make sure it has the right type of slashes pathToFill.bReplaceChar(L'/', L'\\'); } // // Get or set the exption reporting flag, which controls whether we // report at throw or when unhandled (when in the IDE.) // tCIDMacroEng::EExceptReps TCIDMacroEngine::eExceptReport() const { return m_eExceptReport; } tCIDMacroEng::EExceptReps TCIDMacroEngine::eExceptReport(const tCIDMacroEng::EExceptReps eToSet) { m_eExceptReport = eToSet; return m_eExceptReport; } // // Resolves a possibly partial class path to a full one. It may be // ambiguous so we return all possible matches. // tCIDMacroEng::EClassMatches TCIDMacroEngine:: eResolveClassName( const TString& strName , TRefCollection<TMEngClassInfo>& colMatches) { // // There are three scenarios, which are: // // 1. Fully qualified // 2. Relative // 3. Relative plus nested // enum class ETypes { Fully , Relative , Nested }; // Insure that the collection is non-adopting if (colMatches.eAdopt() != tCIDLib::EAdoptOpts::NoAdopt) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_MustBeNonAdopting , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal ); } // Looks ok, so clean it out colMatches.RemoveAll(); // First we figure out which scenario we are looking at. ETypes eType = ETypes::Fully; tCIDLib::TCard4 c4Pos1 = 0; tCIDLib::TCard4 c4Pos2 = 0; if (strName.bFirstOccurrence(kCIDLib::chPeriod, c4Pos1)) { // // If it doesn't start with MEng and has only one period, then // it's a relative path. // c4Pos2 = c4Pos1; if (!strName.bStartsWithI(L"MEng") && !strName.bNextOccurrence(kCIDLib::chPeriod, c4Pos2)) { eType = ETypes::Nested; } else { eType = ETypes::Fully; } } else { // No periods so must be relative eType = ETypes::Relative; } tCIDMacroEng::EClassMatches eRet = tCIDMacroEng::EClassMatches::NotFound; if (eType == ETypes::Fully) { TMEngClassInfo* pmeciTarget = pmeciFind(strName); if (!pmeciTarget) return tCIDMacroEng::EClassMatches::NotFound; colMatches.Add(pmeciTarget); eRet = tCIDMacroEng::EClassMatches::Unique; } else if (eType == ETypes::Nested) { // Get out the first part of the name TString strFind(strName); if (eType == ETypes::Nested) strFind.Cut(c4Pos1); // Make sure it's unique and remember which one we hit, if any TMEngClassInfo* pmeciCur = nullptr; tCIDLib::TCard4 c4HitCount = 0; const tCIDLib::TCard4 c4Count = m_colClassesById.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (m_colClassesById[c4Index]->strName() == strFind) { pmeciCur = m_colClassesById[c4Index]; c4HitCount++; } } // If we hit one, let's check it, else we failed if (c4HitCount) { // Make sure it has a nested class of the second part strFind = pmeciCur->strClassPath(); strFind.Append(kCIDLib::chPeriod); strFind.AppendSubStr(strName, c4Pos1 + 1); TMEngClassInfo* pmeciTarget = pmeciFind(strFind); if (pmeciTarget) { eRet = tCIDMacroEng::EClassMatches::Unique; colMatches.Add(pmeciTarget); } else { eRet = tCIDMacroEng::EClassMatches::NotFound; } } else { eRet = tCIDMacroEng::EClassMatches::NotFound; } } else { // It's relative so it must be unique const tCIDLib::TCard4 c4Count = m_colClassesById.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { TMEngClassInfo* pmeciCur = m_colClassesById[c4Index]; if (pmeciCur->strName() == strName) colMatches.Add(pmeciCur); } if (colMatches.bIsEmpty()) eRet = tCIDMacroEng::EClassMatches::NotFound; else if (colMatches.c4ElemCount() > 1) eRet = tCIDMacroEng::EClassMatches::Ambiguous; else eRet = tCIDMacroEng::EClassMatches::Unique; } return eRet; } // Translates a numeric class id to it's intrinsic enumerated value tCIDMacroEng::ENumTypes TCIDMacroEngine::eXlatNumType(const tCIDLib::TCard2 c2NumClassId) { if ((c2NumClassId < tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::FirstNum)) || (c2NumClassId > tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::LastNum))) { return tCIDMacroEng::ENumTypes::None; } return tCIDMacroEng::ENumTypes ( (c2NumClassId - tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card1)) + 1 ); } // Set a C++ excpetion on, which will be reported to any installed handler tCIDLib::TVoid TCIDMacroEngine::Exception(const TError& errThrown) { // If we have a handler, let it know about this one if (m_pmeehToUse) { m_pmeehToUse->Exception(errThrown, *this); errThrown.bReported(kCIDLib::True); } } // // Takes a macro level file path and converts it to the full OS level // file path. To go the other way use bContractFilePath(). // tCIDLib::TVoid TCIDMacroEngine::ExpandFilePath(const TString& strMacroPath , TPathStr& pathToFill) { // // Make sure it has the right type of slashes. Some folks use // forward slashes instead of back. So if the native path sep // isn't forward, then replace them with the native one. // #pragma warning(suppress : 6326) // chPathSep is per-platform, so this is legit check if (kCIDLib::chPathSep != L'/') { TString strTmp(strMacroPath); strTmp.bReplaceChar(L'/', kCIDLib::chPathSep); m_pmefrToUse->ExpandPath(strTmp, pathToFill); } else { m_pmefrToUse->ExpandPath(strMacroPath, pathToFill); } } // Get a TFloat4 value on the stack at the indicated index tCIDLib::TFloat4 TCIDMacroEngine::f4StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Float4, CID_LINE, c4Index); return static_cast<const TMEngFloat4Val&>(mecvVal).f4Value(); } // Get a TFloat8 value on the stack at the indicated index tCIDLib::TFloat8 TCIDMacroEngine::f8StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Float8, CID_LINE, c4Index); return static_cast<const TMEngFloat8Val&>(mecvVal).f8Value(); } tCIDLib::TVoid TCIDMacroEngine::FlipStackTop() { // These must be at least two items on the stack for this to be legal if (m_c4CallStackTop < 2) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadStackFlip , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal ); } m_colCallStack.SwapItems(m_c4CallStackTop - 2, m_c4CallStackTop - 1); } tCIDLib::TInt1 TCIDMacroEngine::i1StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Int1, CID_LINE, c4Index); return static_cast<const TMEngInt1Val&>(mecvVal).i1Value(); } tCIDLib::TInt2 TCIDMacroEngine::i2StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Int2, CID_LINE, c4Index); return static_cast<const TMEngInt2Val&>(mecvVal).i2Value(); } tCIDLib::TInt4 TCIDMacroEngine::i4StackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Int4, CID_LINE, c4Index); return static_cast<const TMEngInt4Val&>(mecvVal).i4Value(); } tCIDLib::TInt4 TCIDMacroEngine::i4Run( TMEngClassVal& mecvTarget , const TString& strParmVals , const TCIDUserCtx* const pcuctxRights) { TParmList colParms(tCIDLib::EAdoptOpts::Adopt); try { // Set the passed user contact while we are in here TGFJanitor<const TCIDUserCtx*> janRights(&m_pcuctxRights, pcuctxRights); // // Search this class for a legal entry point. It must have // particular name and form. // TMEngClassInfo& meciTarget = meciFind(mecvTarget.c2ClassId()); const tCIDLib::TCard2 c2MethodId = c2FindEntryPoint(meciTarget, 0); // Try to parse out the parameters TVector<TString> colSrcParms; const tCIDLib::TCard4 c4ParmCount = TExternalProcess::c4BreakOutParms ( strParmVals , colSrcParms ); // Make sure that we got the correct number of parms TMEngMethodInfo& methiTarget = meciTarget.methiFind(c2MethodId); if (c4ParmCount != methiTarget.c4ParmCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadEntryParmCnt , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::BadParms , meciTarget.strClassPath() , TCardinal(methiTarget.c4ParmCount()) , TCardinal(c4ParmCount) ); } // Loop through and try to create the value objects TString strName; for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCount; c2Id++) { const TMEngParmInfo& mepiTar = methiTarget.mepiFind(c2Id); const TString& strCur = colSrcParms[c2Id]; // The direction indicates whether it's const or not const tCIDMacroEng::EConstTypes eConst ( (mepiTar.eDir() == tCIDMacroEng::EParmDirs::In) ? tCIDMacroEng::EConstTypes::Const : tCIDMacroEng::EConstTypes::NonConst ); // The name we'll give it strName = L"Parm"; strName.AppendFormatted(tCIDLib::TCard4(c2Id + 1)); // Create a new value object of the target type TMEngClassInfo& meciParm = meciFind(mepiTar.c2ClassId()); TMEngClassVal* pmecvNew = meciParm.pmecvMakeStorage ( strName, *this, eConst ); colParms.Add(pmecvNew); // Ask it to parse from the current value if (!pmecvNew->bParseFromText(strCur, meciParm)) { // // If we have an error handler, then build up a macro // level exception and report that. // if (m_pmeehToUse) { // // Get the base info class info. This guy has nested // enum types that provide the errors for stuff like // this. // const TMEngBaseInfoInfo& meciBaseInfo ( *pmeciFindAs<TMEngBaseInfoInfo> ( TMEngBaseInfoInfo::strPath(), kCIDLib::True ) ); // // Get the enum class object for the engine error enum // and the ordinal for the bad parm error. // const TMEngEnumInfo& meciErr = meciBaseInfo.meciMEngErrors(); const tCIDLib::TCard4 c4ErrId = meciBaseInfo.c4ErrIdBadEntryParm; // // We need the line number of the entry point. The entry // point is always an opcode based method implementation, // so we can just cast to that, and then we can get the // first line number within the implementation. // TMEngOpMethodImpl& methEP = *static_cast<TMEngOpMethodImpl*> ( meciTarget.pmethFind(c2MethodId) ); TString strErrText ( kMEngErrs::errcEng_BadTextEPParmVal , facCIDMacroEng() , TCardinal(c2Id + 1UL) , meciTarget.strClassPath() , strClassPathForId(mepiTar.c2ClassId()) ); TMEngExceptVal mecvExcept(L"BadParm", tCIDMacroEng::EConstTypes::Const); mecvExcept.Set ( meciErr.c2Id() , meciTarget.strClassPath() , c4ErrId , meciErr.strItemName(c4ErrId) , strErrText , methEP.c4FirstLineNum() ); m_pmeehToUse->MacroException(mecvExcept, *this); } // // If we are in the IDE, report we are done and return a -1 status. // Else, throw an exception. // if (!m_pmedbgToUse) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadTextEPParmVal , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::BadParms , TCardinal(c2Id + 1UL) , meciTarget.strClassPath() , strClassPathForId(mepiTar.c2ClassId()) ); } m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); return -1; } } } catch(const TDbgExitException& excptForce) { if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(excptForce.m_eReason); return -1; } catch(const TError& errToCatch) { Exception(errToCatch); if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); throw; } catch(...) { UnknownException(); if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); throw; } // And now call the other version with the parms return i4Run(mecvTarget, colParms, pcuctxRights); } tCIDLib::TInt4 TCIDMacroEngine::i4Run( TMEngClassVal& mecvTarget , TParmList& colParms , const TCIDUserCtx* const pcuctxRights) { tCIDLib::TInt4 i4Res = 0; try { // Set the passed user contact while we are in here TGFJanitor<const TCIDUserCtx*> janRights(&m_pcuctxRights, pcuctxRights); // // Allow derived engine classes to adjust the start object and/or // parms before we continue. // AdjustStart(mecvTarget, colParms); // // If the temp pool is empty, then this is the first time this engine // instance has been used, so we need to initialize the pool. // if (m_colTempPool.bIsEmpty()) InitTempPool(); // // Search this class for a legal entry point. It must have particular // name and form. // TMEngClassInfo& meciTarget = meciFind(mecvTarget.c2ClassId()); const tCIDLib::TCard2 c2MethodId = c2FindEntryPoint(meciTarget, 0); // Push the return value first before any parms PushPoolValue(tCIDMacroEng::EIntrinsics::Int4, tCIDMacroEng::EConstTypes::NonConst); // // Make sure we have the correct type and kind of parameters, then // push them onto the stack. Say that they are parms, so that they // will not get deleted when popped. // TMEngMethodInfo& methiTarget = meciTarget.methiFind(c2MethodId); const tCIDLib::TCard4 c4ParmCount = colParms.c4ElemCount(); if (c4ParmCount != methiTarget.c4ParmCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadEntryParmCnt , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::BadParms , meciTarget.strClassPath() , TCardinal(methiTarget.c4ParmCount()) , TCardinal(c4ParmCount) ); } // We have the right number, so see if they are the right type for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCount; c2Id++) { const TMEngParmInfo& mepiTar = methiTarget.mepiFind(c2Id); const TMEngClassVal& mecvSrc = *colParms[c2Id]; // // The passed value must be the same or derived from the target, // or they must be equivalent collections with identical element types. // if (!bIsDerivedFrom(mecvSrc.c2ClassId(), mepiTar.c2ClassId()) && !bAreEquivCols(mecvSrc.c2ClassId(), mepiTar.c2ClassId(), kCIDLib::True)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadEntryParmType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::BadParms , TCardinal(c2Id + 1UL) , meciTarget.strClassPath() , strClassPathForId(mepiTar.c2Id()) , strClassPathForId(mecvSrc.c2ClassId()) ); } // // Looks ok, so push it. Say it's a parm and say that it's a // repush so that it's clear that we own it. // PushValue(colParms[c2Id], tCIDMacroEng::EStackItems::Parm, kCIDLib::True); } // And finally push the method call meciPushMethodCall(meciTarget.c2Id(), c2MethodId); // // And invoke the indicated method on this class, then pop the method // call item and parms off when we get back. We can do monomorphic dispatch // here since we know the target class has the method. // meciTarget.Invoke(*this, mecvTarget, c2MethodId, tCIDMacroEng::EDispatch::Mono); MultiPop(c4ParmCount + 1); #if CID_DEBUG_ON if (m_c4CallStackTop != 1) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadEndStackTop , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(m_c4CallStackTop) ); } #endif // Get the return value out i4Res = i4StackValAt(0); // Remove the return value now PopTop(); // Output a new line to the stream console if present and flush if (m_pstrmConsole) { *m_pstrmConsole << kCIDLib::NewLn; m_pstrmConsole->Flush(); } // If we have a debug interface installed, post a normal exit if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); } catch(const TDbgExitException& excptForce) { if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(excptForce.m_eReason); // Force a known return value i4Res = kCIDLib::i4MinInt; } catch(const TExceptException&) { // // If there is an error handler, and we are in the mode where we // report macros if they aren'thandled, then report it. If we are // in the other mode, it will already have been reported at the point // of throw. // if (m_pmeehToUse && (m_eExceptReport == tCIDMacroEng::EExceptReps::NotHandled)) m_pmeehToUse->MacroException(*m_pmecvThrown, *this); if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); // It was unhandled, so rethrow to caller throw; } catch(const TError& errToCatch) { Exception(errToCatch); if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); throw; } catch(...) { UnknownException(); if (m_pmedbgToUse) m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit); throw; } return i4Res; } // If we have a last exception, log it tCIDLib::TVoid TCIDMacroEngine::LogLastExcept() { if (m_pmecvThrown) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcRT_MacroExcept , m_pmecvThrown->strSrcClassPath() , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , m_pmecvThrown->strErrorName() , TCardinal(m_pmecvThrown->c4LineNum()) ); } } TMEngMethodInfo& TCIDMacroEngine::methiFind( const tCIDLib::TCard2 c2ClassId , const tCIDLib::TCard2 c2MethodId) { #if CID_DEBUG_ON CheckClassId(c2ClassId, CID_LINE); #endif return m_colClassesById[c2ClassId]->methiFind(c2MethodId); } TMEngClassInfo& TCIDMacroEngine::meciFind(const TString& strClassPath) { TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey ( strClassPath , kCIDLib::False ); if (!pmeciRet) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ClassNotFound , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotFound , strClassPath ); } return *pmeciRet; } const TMEngClassInfo& TCIDMacroEngine::meciFind(const TString& strClassPath) const { const TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey ( strClassPath , kCIDLib::False ); if (!pmeciRet) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ClassNotFound , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotFound , strClassPath ); } return *pmeciRet; } TMEngClassInfo& TCIDMacroEngine::meciFind(const tCIDLib::TCard2 c2Id) { #if CID_DEBUG_ON CheckClassId(c2Id, CID_LINE); #endif return *m_colClassesById[c2Id]; } TMEngClassInfo& TCIDMacroEngine::meciFind(const tCIDMacroEng::EIntrinsics eClassType) { return meciFind(tCIDLib::TCard2(eClassType)); } const TMEngClassInfo& TCIDMacroEngine::meciFind(const tCIDLib::TCard2 c2Id) const { #if CID_DEBUG_ON CheckClassId(c2Id, CID_LINE); #endif return *m_colClassesById[c2Id]; } const TMEngClassInfo& TCIDMacroEngine::meciFind(const tCIDMacroEng::EIntrinsics eClassType) const { return meciFind(tCIDLib::TCard2(eClassType)); } TMEngClassInfo& TCIDMacroEngine::meciPushMethodCall(const tCIDLib::TCard2 c2ClassId , const tCIDLib::TCard2 c2MethodId) { // Find the two bits we need to push TMEngClassInfo* pmeciCalled = &meciFind(c2ClassId); TMEngMethodInfo* pmethiCalled = &pmeciCalled->methiFind(c2MethodId); CheckStackExpand(); // Get the top of stack item and reset it with the passed procedure TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmeciCalled, pmethiCalled); m_c4CallStackTop++; // As a convenience, we return the class return *pmeciCalled; } TMEngClassInfo& TCIDMacroEngine::meciPushMethodCall(const tCIDLib::TCard2 c2ClassId , const tCIDLib::TCard2 c2MethodId , const TMEngClassInfo* const pmeciCaller , const TMEngOpMethodImpl* const pmethCaller , const TMEngMethodInfo* const pmethiCaller , TMEngClassVal* const pmecvCaller , const tCIDLib::TCard4 c4CallLine , const tCIDLib::TCard4 c4CallIP) { // Find the two bits we need to push TMEngClassInfo* pmeciCalled = &meciFind(c2ClassId); TMEngMethodInfo* pmethiCalled = &pmeciCalled->methiFind(c2MethodId); CheckStackExpand(); // Get the top of stack item and reset it with the passed procedure TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset ( pmeciCalled , pmethiCalled , pmeciCaller , pmethiCaller , pmethCaller , pmecvCaller , c4CallLine , c4CallIP ); m_c4CallStackTop++; // As a convenience, we return the class return *pmeciCalled; } TMEngCallStackItem& TCIDMacroEngine::mecsiAt(const tCIDLib::TCard4 c4Index) { CheckStackIndex(CID_LINE, c4Index); return *m_colCallStack[c4Index]; } const TMEngCallStackItem& TCIDMacroEngine::mecsiAt(const tCIDLib::TCard4 c4Index) const { CheckStackIndex(CID_LINE, c4Index); return *m_colCallStack[c4Index]; } TMEngCallStackItem& TCIDMacroEngine::mecsiTop() { // // If the stack isn't empty, give them back the top item, which is one // less than the top, because the top points at the next available // slot. // CheckNotEmpty(CID_LINE); return *m_colCallStack[m_c4CallStackTop - 1]; } const TMEngClassVal& TCIDMacroEngine::mecvStackAt(const tCIDLib::TCard4 c4Index) const { CheckStackIndex(CID_LINE, c4Index); return m_colCallStack[c4Index]->mecvPushed(); } TMEngClassVal& TCIDMacroEngine::mecvStackAt(const tCIDLib::TCard4 c4Index) { CheckStackIndex(CID_LINE, c4Index); return m_colCallStack[c4Index]->mecvPushed(); } const TMEngClassVal& TCIDMacroEngine::mecvStackAtTop() const { CheckNotEmpty(CID_LINE); return m_colCallStack[m_c4CallStackTop - 1]->mecvPushed(); } TMEngClassVal& TCIDMacroEngine::mecvStackAtTop() { CheckNotEmpty(CID_LINE); return m_colCallStack[m_c4CallStackTop - 1]->mecvPushed(); } // // Provide access to any user rights context that the user code may have set // on us. We don't care what it is, it's purely a passthrough for user code. // It may be null if they never set one. // const TCIDUserCtx* TCIDMacroEngine::pcuctxRights() const { return m_pcuctxRights; } // Pop the given number of objects off the stack tCIDLib::TVoid TCIDMacroEngine::MultiPop(const tCIDLib::TCard4 c4Count) { // Check for underflow. We have to have at least the number indicated if (m_c4CallStackTop < c4Count) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_CallStackUnderflow , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Underflow ); } // It's ok, so pop it for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { m_c4CallStackTop--; // // If this is a temp value, then release it back to the pool. If // it's a local, we have to clean it up. Else, it's spoken for by // someone and we don't have to worry. Then, clear the item to // keep the stack readable. // // NOTE: If it's a repush, we don't do anything, because this // is not the original! // TMEngCallStackItem* pmecsiPop = m_colCallStack[m_c4CallStackTop]; if (!pmecsiPop->bIsRepush()) { if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::TempVal) pmecsiPop->mecvPushed().bIsUsed(kCIDLib::False); else if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::Local) delete &pmecsiPop->mecvPushed(); } pmecsiPop->Clear(); } } const TMEngClassInfo* TCIDMacroEngine::pmeciLastMacroCaller(tCIDLib::TCard4& c4Line) { // // Start at the top of the stack and work backwards till we see a // call from a macro level class. // tCIDLib::TCard4 c4Index = m_c4CallStackTop; if (!c4Index) return nullptr; TMEngCallStackItem* pmecsiCur = nullptr; const TMEngClassInfo* pmeciRet = nullptr; do { c4Index--; pmecsiCur = m_colCallStack[c4Index]; if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall) { pmeciRet = pmecsiCur->pmeciCaller(c4Line); if (pmeciRet) break; } } while (c4Index != 0); return pmeciRet; } TMEngClassInfo* TCIDMacroEngine::pmeciLoadExternalClass(const TString& strClassPathToLoad) { TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey ( strClassPathToLoad, kCIDLib::False ); // If already loaded, we are done if (pmeciRet) return pmeciRet; // // Ask the facility class to allow all of the registered class loaders // to have a chance to load this class. // pmeciRet = facCIDMacroEng().pmeciInvokeExternalLoaders(*this, strClassPathToLoad); if (!pmeciRet) return pmeciRet; // // If this guy has any imports, then we need to recursively load them // before we continue. And we need to do the same to it's parent class // as well. Do the parent first, then do any imports of this class. // pmeciLoadExternalClass(pmeciRet->strParentClassPath()); TMEngClassInfo::TImportList::TCursor cursImports(&pmeciRet->m_colImports); for (; cursImports; ++cursImports) pmeciLoadExternalClass(cursImports->m_strImport); // // Do the base init of the class now that all it's needed class are // loaded. // pmeciRet->BaseClassInit(*this); c2AddClass(pmeciRet); return pmeciRet; } TMEngClassInfo* TCIDMacroEngine::pmeciFind( const TString& strClassPath , const tCIDLib::TBoolean bThrowIfNot) { return m_colClasses.pobjFindByKey(strClassPath, bThrowIfNot); } const TMEngClassInfo* TCIDMacroEngine::pmeciFind( const TString& strClassPath , const tCIDLib::TBoolean bThrowIfNot) const { return m_colClasses.pobjFindByKey(strClassPath, bThrowIfNot); } const TMEngExceptVal& TCIDMacroEngine::mecvExceptionThrown() const { return *m_pmecvThrown; } TMEngExceptVal& TCIDMacroEngine::mecvExceptionThrown() { return *m_pmecvThrown; } // // This method will start at the top of the stack and search downwards // until it finds a call item, and return that item and it's stack index. // If it doesn't find one, it returns a null pointer. // TMEngCallStackItem* TCIDMacroEngine::pmecsiMostRecentCall(tCIDLib::TCard4& c4ToFill) { if (!m_c4CallStackTop) { c4ToFill = kCIDLib::c4MaxCard; return 0; } tCIDLib::TCard4 c4Index = m_c4CallStackTop; do { c4Index--; TMEngCallStackItem* pmecsiCur = m_colCallStack[c4Index]; if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall) { c4ToFill = c4Index; return pmecsiCur; } } while (c4Index > 0); c4ToFill = kCIDLib::c4MaxCard; return 0; } // // This guy allows a new value object to be created via a class path name. // This allows code that needs to call into macro code from C++ code to // create value objects without us having to expose all those headers. // TMEngClassVal* TCIDMacroEngine::pmecvNewFromPath( const TString& strName , const TString& strClassPath , const tCIDMacroEng::EConstTypes eConst) { // Find the class info object for the passed class TMEngClassInfo& meciNew = meciFind(strClassPath); return meciNew.pmecvMakeStorage(strName, *this, eConst); } TTextOutStream* TCIDMacroEngine::pstrmConsole() { #if CID_DEBUG_ON if (!m_pstrmConsole) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_NoConsoleStrm , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal ); } #endif return m_pstrmConsole; } tCIDLib::TVoid TCIDMacroEngine::PopBackTo(const tCIDLib::TCard4 c4To) { // If already at that point, then nothing to do if (m_c4CallStackTop == c4To) return; // Else the to index must be less than the current top CheckStackIndex(CID_LINE, c4To); // Looks ok, so let's do it do { // Move down to the next used item m_c4CallStackTop--; // // If this is a temp value, then release it back to the pool. If // it's a local, we have to clean it up. Else, it's spoken for by // someone and we don't have to worry. Then, clear the item to // keep the stack readable. // // NOTE: If it's a repush, we don't do anything, because this // is not the original! // TMEngCallStackItem* pmecsiPop = m_colCallStack[m_c4CallStackTop]; if (!pmecsiPop->bIsRepush()) { if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::TempVal) pmecsiPop->mecvPushed().bIsUsed(kCIDLib::False); else if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::Local) delete &pmecsiPop->mecvPushed(); } pmecsiPop->Clear(); } while (m_c4CallStackTop > c4To); } tCIDLib::TVoid TCIDMacroEngine::PopTop() { // Check for underflow CheckStackUnderflow(CID_LINE); // It's ok, so pop it m_c4CallStackTop--; // // If this is a temp value, then release it back to the pool. If // it's a local, we have to clean it up. Else, it's spoken for by // someone and we don't have to worry. Then, clear the item to // keep the stack readable. // // NOTE: If it's a repush, we don't do anything, because this // is not the original! // TMEngCallStackItem* pmecsiPop = m_colCallStack[m_c4CallStackTop]; if (!pmecsiPop->bIsRepush()) { if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::TempVal) pmecsiPop->mecvPushed().bIsUsed(kCIDLib::False); else if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::Local) delete &pmecsiPop->mecvPushed(); } pmecsiPop->Clear(); } tCIDLib::TVoid TCIDMacroEngine::PushBoolean(const tCIDLib::TBoolean bToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngBooleanVal* pmecvPush = static_cast<TMEngBooleanVal*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Boolean, eConst) ); pmecvPush->bValue(bToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushCard1( const tCIDLib::TCard1 c1ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngCard1Val* pmecvPush = static_cast<TMEngCard1Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Card1, eConst) ); pmecvPush->c1Value(c1ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushCard2( const tCIDLib::TCard2 c2ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngCard2Val* pmecvPush = static_cast<TMEngCard2Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Card2, eConst) ); pmecvPush->c2Value(c2ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushCard4( const tCIDLib::TCard4 c4ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngCard4Val* pmecvPush = static_cast<TMEngCard4Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Card4, eConst) ); pmecvPush->c4Value(c4ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushCard8( const tCIDLib::TCard8 c8ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngCard8Val* pmecvPush = static_cast<TMEngCard8Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Card8, eConst) ); pmecvPush->c8Value(c8ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushChar( const tCIDLib::TCh chToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngCharVal* pmecvPush = static_cast<TMEngCharVal*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Char, eConst) ); pmecvPush->chValue(chToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushEnum( const tCIDLib::TCard2 c2ClassId , const tCIDLib::TCard2 c2OrdValue , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngEnumVal* pmecvPush = static_cast<TMEngEnumVal*> ( pmecvGet(c2ClassId, eConst) ); pmecvPush->c4Ordinal(c2OrdValue); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } // // This one handles a special case scenario, which pushes a thrown exception // upon entry to a Catch block. It just refers to a magic value object that // is a member of this class, since it must potentially exist all the way // up the call stack. // tCIDLib::TVoid TCIDMacroEngine::PushException() { CheckStackExpand(); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(m_pmecvThrown, tCIDMacroEng::EStackItems::Exception); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushFloat4( const tCIDLib::TFloat4 f4ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngFloat4Val* pmecvPush = static_cast<TMEngFloat4Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Float4, eConst) ); pmecvPush->f4Value(f4ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushFloat8( const tCIDLib::TFloat8 f8ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngFloat8Val* pmecvPush = static_cast<TMEngFloat8Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Float8, eConst) ); pmecvPush->f8Value(f8ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushInt1( const tCIDLib::TInt1 i1ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngInt1Val* pmecvPush = static_cast<TMEngInt1Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Int1, eConst) ); pmecvPush->i1Value(i1ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushInt2( const tCIDLib::TInt2 i2ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngInt2Val* pmecvPush = static_cast<TMEngInt2Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Int2, eConst) ); pmecvPush->i2Value(i2ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushInt4( const tCIDLib::TInt4 i4ToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngInt4Val* pmecvPush = static_cast<TMEngInt4Val*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Int4, eConst) ); pmecvPush->i4Value(i4ToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushPoolValue( const TString& strClassPath , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Look up the class id for this guy and use that to get a temp TMEngClassVal* pmecvPush = pmecvGet(meciFind(strClassPath).c2Id(), eConst); TJanitor<TMEngClassVal> janPush(pmecvPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(janPush.pobjOrphan(), tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushPoolValue( const TString& strName , const tCIDLib::TCard2 c2TypeId , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Look up the class id for this guy and use that to get a temp TMEngClassVal* pmecvPush = pmecvGet ( strName , meciFind(c2TypeId).c2Id() , eConst ); TJanitor<TMEngClassVal> janPush(pmecvPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(janPush.pobjOrphan(), tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushPoolValue( const TString& strName , const tCIDMacroEng::EIntrinsics eType , const tCIDMacroEng::EConstTypes eConst) { PushPoolValue(strName, tCIDLib::TCard2(eType), eConst); } tCIDLib::TVoid TCIDMacroEngine::PushPoolValue( const tCIDLib::TCard2 c2Id , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a value from the pool, of the type passed TMEngClassVal* pmecvPush = pmecvGet(c2Id, eConst); TJanitor<TMEngClassVal> janPush(pmecvPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(janPush.pobjOrphan(), tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushPoolValue( const tCIDMacroEng::EIntrinsics eType , const tCIDMacroEng::EConstTypes eConst) { PushPoolValue(tCIDLib::TCard2(eType), eConst); } tCIDLib::TVoid TCIDMacroEngine::PushString(const TString& strToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngStringVal* pmecvPush = static_cast<TMEngStringVal*> ( pmecvGet(tCIDMacroEng::EIntrinsics::String, eConst) ); pmecvPush->strValue(strToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushStringList(const TVector<TString>& colToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngStrListVal* pmecvPush = static_cast<TMEngStrListVal*> ( pmecvGet(tCIDMacroEng::EIntrinsics::StringList, eConst) ); pmecvPush->Reset(colToPush, kCIDLib::True); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushTime( const TTime& tmToPush , const tCIDMacroEng::EConstTypes eConst) { CheckStackExpand(); // Get a temp of this type from the pool and set it to the passed value TMEngTimeVal* pmecvPush = static_cast<TMEngTimeVal*> ( pmecvGet(tCIDMacroEng::EIntrinsics::Time, eConst) ); pmecvPush->tmValue(tmToPush); // Get the top of stack item and reset it with the passed temp value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushTry(const tCIDLib::TCard4 c4ToPush) { CheckStackExpand(); // Get the top of stack item and reset it with the passed value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(tCIDMacroEng::EStackItems::Try, c4ToPush); m_c4CallStackTop++; } tCIDLib::TVoid TCIDMacroEngine::PushValue( TMEngClassVal* const pmecvPushed , const tCIDMacroEng::EStackItems eType , const tCIDLib::TBoolean bRepush) { CheckStackExpand(); // Get the top of stack item and reset it with the passed value TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop]; pmecsiRet->Reset(pmecvPushed, eType); pmecsiRet->bIsRepush(bRepush); m_c4CallStackTop++; } // // This is mainly to support packaging of macros/drivers. We will find // all the loaded (i.e. referenced) that are in the indicated scope. // tCIDLib::TVoid TCIDMacroEngine::QueryScopeClasses( const TString& strScope , tCIDLib::TStrCollect& colToFill) const { colToFill.RemoveAll(); // // We can start past the intrinsic classes, which are always there and // always first. // const tCIDLib::TCard4 c4Count = m_colClassesById.c4ElemCount(); tCIDLib::TCard4 c4Index = tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Count); while (c4Index < c4Count) { const TMEngClassInfo* pmeciCur = m_colClassesById[c4Index]; if (pmeciCur->strBasePath().eCompareI(strScope) == tCIDLib::ESortComps::Equal) colToFill.objAdd(pmeciCur->strClassPath()); c4Index++; } } // // Repush the value at the indicated stack index. It's marked as being // repushed, so that when it's popped it won't be destroyed becasue it's // not the original. // tCIDLib::TVoid TCIDMacroEngine::RepushAt(const tCIDLib::TCard4 c4Index) { CheckStackExpand(); // Make sure it's a value item TMEngCallStackItem& mecsiToPush = mecsiAt(c4Index); const tCIDMacroEng::EStackItems eType = mecsiToPush.eType(); if (eType == tCIDMacroEng::EStackItems::MethodCall) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_RepushMethod , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal ); } // Get the value from this item TMEngClassVal* pmecvToPush = &mecsiToPush.mecvPushed(); // // Push it again, with the same type. But, set the 'repush' flag. This // lets us know when we pop that we never have to worry about cleanup, // because this isn't the real guy // PushValue(pmecvToPush, mecsiToPush.eType(), kCIDLib::True); } // // Reset the macro engine. We make sure the stack is cleared, and we clean // up any objects in pools and globals, and remove all classes other than // the instrinsic ones. // // Note that we don't reset the unique id counter. We just let it continue // to run upwards, for increased safety. // tCIDLib::TVoid TCIDMacroEngine::Reset() { // Make sure that the call stack get's emptied try { m_colCallStack.RemoveAll(); } catch(TError& errToCatch) { if (!errToCatch.bLogged()) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ResetErr , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal ); } // // Now clean up the other stuff. Note that we don't remove the built // in classes from the class list, since they can remain the same // always, and it significantly improves performance. We only remove // those when the engine is cleaned up. Passing false to the cleanup // method does this. // Cleanup(kCIDLib::False); m_c4CurLine = 0; m_c4CallStackTop = 0; // // Set this to the next available one after the builtins, because we // didn't remove those!!! // m_c2NextClassId = m_c2ArrayId + 1; } // If we have an error handler and an exception, send it to the error handler tCIDLib::TVoid TCIDMacroEngine::ReportLastExcept() { if (m_pmeehToUse && m_pmecvThrown) m_pmeehToUse->MacroException(*m_pmecvThrown, *this); } const TString& TCIDMacroEngine::strClassPathForId( const tCIDLib::TCard2 c2Id , const tCIDLib::TBoolean bThrowIfNot) const { if (c2Id >= m_colClassesById.c4ElemCount()) { if (bThrowIfNot) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcClass_BadId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , TCardinal(m_colClassesById.c4ElemCount()) ); } return TFacCIDMacroEng::strUnknownClass; } return m_colClassesById[c2Id]->strClassPath(); } const TString& TCIDMacroEngine::strClassPathForId( const tCIDMacroEng::EIntrinsics eType , const tCIDLib::TBoolean bThrowIfNot) const { return strClassPathForId(tCIDLib::TCard2(eType), bThrowIfNot); } // Get or set the special dynamic type reference value const TString& TCIDMacroEngine::strSpecialDynRef() const { return m_strSpecialDynRef; } const TString& TCIDMacroEngine::strSpecialDynRef(const TString& strToSet) { m_strSpecialDynRef = strToSet; return m_strSpecialDynRef; } // Get a string object at the indicated index on the stack const TString& TCIDMacroEngine::strStackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::String, CID_LINE, c4Index); return static_cast<const TMEngStringVal&>(mecvVal).strValue(); } // Let's the application give us an output console stream to use tCIDLib::TVoid TCIDMacroEngine::SetConsole(TTextOutStream* const pstrmToUse) { // We don't own these console streams, so just overwrite any previous m_pstrmConsole = pstrmToUse; } // Let's the application give us a debug handler tCIDLib::TVoid TCIDMacroEngine::SetDbgHandler(MMEngDebugIntf* const pmedbgToUse) { // We don't own these console streams, so just overwrite any previous m_pmedbgToUse = pmedbgToUse; } tCIDLib::TVoid TCIDMacroEngine::SetErrHandler(MMEngErrHandler* const pmeehToUse) { // We don't own these console streams, so just overwrite any previous m_pmeehToUse = pmeehToUse; } tCIDLib::TVoid TCIDMacroEngine::SetException( const tCIDLib::TCard2 c2ErrClassId , const TString& strSrcClassPath , const tCIDLib::TCard4 c4ErrorNum , const TString& strErrorName , const TString& strErrorText , const tCIDLib::TCard4 c4LineNum) { // If we've not created the object yet, then do it if (!m_pmecvThrown) m_pmecvThrown = new TMEngExceptVal(L"$Exception$", tCIDMacroEng::EConstTypes::Const); // Set up the exception info m_pmecvThrown->Set ( c2ErrClassId , strSrcClassPath , c4ErrorNum , strErrorName , strErrorText , c4LineNum ); // // If we have a handler, and the exception reporting style is to report // at the point of throw, let it know about this one now. // if (m_pmeehToUse && (m_eExceptReport == tCIDMacroEng::EExceptReps::AtThrow)) m_pmeehToUse->MacroException(*m_pmecvThrown, *this); } tCIDLib::TVoid TCIDMacroEngine::SetFileResolver(MMEngFileResolver* const pmefrToUse) { // We don't own these, so just overwrite any previous m_pmefrToUse = pmefrToUse; } // // When the TTime class' Sleep method is called, if it's longer than a // second or so, then this method will be called and we'll do it in chunks // and call the debug interface each time, so that the debugger can get // us to stop if the user wants us to. // tCIDLib::TVoid TCIDMacroEngine::Sleep(const tCIDLib::TCard4 c4Millis) { if ((c4Millis > 1500) && m_pmedbgToUse) { // Do 500ms at a time tCIDLib::TCard4 c4Count = 0; while (c4Count < c4Millis) { tCIDLib::TCard4 c4ThisTime = 500; if (c4Count + c4ThisTime > c4Millis) c4ThisTime = c4Millis - c4Count; c4Count += c4ThisTime; TThread::Sleep(c4ThisTime); if (!m_pmedbgToUse->bSleepTest()) break; } } else { // // Just do a regular sleep, though still using the thread specific // one that will watch for lower level CIDLib thread stop requests. // TThread::pthrCaller()->bSleep(c4Millis); } } // Get the time object at the indicated position on the stack const TTime& TCIDMacroEngine::tmStackValAt( const tCIDLib::TCard4 c4Index , const tCIDLib::TBoolean bCheckType) const { const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed(); if (bCheckType) CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Time, CID_LINE, c4Index); return static_cast<const TMEngTimeVal&>(mecvVal).tmValue(); } tCIDLib::TVoid TCIDMacroEngine::UnknownException() { // If we have a handler, let it know about this one if (m_pmeehToUse) m_pmeehToUse->UnknownException(*this); } tCIDLib::TVoid TCIDMacroEngine::ValidateCallFrame( const TMEngClassVal& mecvInstance , const tCIDLib::TCard2 c2MethodId) const { // The call stack obviously cannot be empty if (!m_c4CallStackTop) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_EmptyCallStack , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady ); } // Get the class info object and method object const TMEngClassInfo& meciTarget = meciFind(mecvInstance.c2ClassId()); const TMEngMethodInfo& methiTarget = meciTarget.methiFind(c2MethodId); // The top item must be a call item const TMEngCallStackItem* pmecsiCur = m_colCallStack[m_c4CallStackTop - 1]; if (pmecsiCur->eType() != tCIDMacroEng::EStackItems::MethodCall) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadCallFrame , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format ); } // // And now make sure that we have enough stack items to make a valid // call frame for this method. It has to be one for the call itself, // one for the return value, and the number of parms the method has. // const tCIDLib::TCard4 c4ParmCnt = methiTarget.c4ParmCount(); if (m_c4CallStackTop < 2 + c4ParmCnt) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_BadCallFrame , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format ); } // Check the return type const TMEngClassVal& mecvRet = mecvStackAt(m_c4CallStackTop - (c4ParmCnt + 2)); if (methiTarget.c2RetClassId() != mecvRet.c2ClassId()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_RetType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , methiTarget.strName() , strClassPathForId(methiTarget.c2RetClassId()) , strClassPathForId(mecvRet.c2ClassId()) ); } // Move down to the first parm and start working up for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCnt; c2Id++) { // Get the current parameter info object const TMEngParmInfo& mepiCur = methiTarget.mepiFind(c2Id); // // And get the stack value for this object. Note that we add one // because the stack top is actually pointing at the next available // slot. // const TMEngClassVal& mecvCur = mecvStackAt ( (m_c4CallStackTop - (c4ParmCnt + 1)) + c2Id ); // // Make sure that the value we have is of a class equal to or derived // from the parameter class, or an equiv collection (in which the element // type of the passed collection is at least derived from the element type // of the parameter. // if (!bIsDerivedFrom(mecvCur.c2ClassId(), mepiCur.c2ClassId()) && !bAreEquivCols(mepiCur.c2ClassId(), mecvCur.c2ClassId(), kCIDLib::False)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_ParmType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , methiTarget.strName() , TCardinal(c2Id + 1UL) , strClassPathForId(mepiCur.c2ClassId()) , strClassPathForId(mecvCur.c2ClassId()) ); } } } // --------------------------------------------------------------------------- // TCIDMacroEngine: Protected, virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TCIDMacroEngine::AdjustStart(TMEngClassVal&, TParmList&) { // Default empty implementation } // --------------------------------------------------------------------------- // TCIDMacroEngine: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TCIDMacroEngine::CheckClassId(const tCIDLib::TCard2 c2Id , const tCIDLib::TCard4 c4Line) const { if (c2Id >= m_colClassesById.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , c4Line , kMEngErrs::errcEng_BadClassId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotFound , TCardinal(c2Id) , TCardinal(m_colClassesById.c4ElemCount()) ); } } tCIDLib::TVoid TCIDMacroEngine::CheckNotEmpty(const tCIDLib::TCard4 c4Line) const { if (!m_c4CallStackTop) { facCIDMacroEng().ThrowErr ( CID_FILE , c4Line , kMEngErrs::errcEng_EmptyCallStack , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index ); } } tCIDLib::TVoid TCIDMacroEngine::CheckStackExpand() { // // If our stack top indicates that there are unused items on the stack // which have been allocated, then take one of those. Else, we need to // allocate another one. If this goes over the current alloc, then we // will cause it to expand it's allocation. // if (m_c4CallStackTop >= m_colCallStack.c4ElemCount()) m_colCallStack.Add(new TMEngCallStackItem); } tCIDLib::TVoid TCIDMacroEngine::CheckStackIndex( const tCIDLib::TCard4 c4Line , const tCIDLib::TCard4 c4ToCheck) const { if (c4ToCheck >= m_c4CallStackTop) { facCIDMacroEng().ThrowErr ( CID_FILE , c4Line , kMEngErrs::errcEng_BadStackIndex , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c4ToCheck) , TCardinal(m_c4CallStackTop) ); } } tCIDLib::TVoid TCIDMacroEngine::CheckItemType( const tCIDLib::TCard2 c2TypeId , const tCIDLib::TCard2 c2ExpectedId , const tCIDLib::TCard4 c4Line , const tCIDLib::TCard4 c4Index) const { if (c2TypeId != c2ExpectedId) { facCIDMacroEng().ThrowErr ( CID_FILE , c4Line , kMEngErrs::errcEng_WrongStackType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , strClassPathForId(c2ExpectedId) , TCardinal(c4Index) , strClassPathForId(c2TypeId) ); } } tCIDLib::TVoid TCIDMacroEngine::CheckItemType( const tCIDLib::TCard2 c2TypeId , const tCIDMacroEng::EIntrinsics eType , const tCIDLib::TCard4 c4Line , const tCIDLib::TCard4 c4Index) const { CheckItemType(c2TypeId, tCIDLib::TCard2(eType), c4Line, c4Index); } tCIDLib::TVoid TCIDMacroEngine::CheckStackUnderflow(const tCIDLib::TCard4 c4Line) const { if (!m_c4CallStackTop) { facCIDMacroEng().ThrowErr ( CID_FILE , c4Line , kMEngErrs::errcEng_CallStackUnderflow , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Underflow ); } } tCIDLib::TVoid TCIDMacroEngine::FormatAFrame( TTextOutStream& strmTarget , const tCIDLib::TCard4 c4CallInd) { // Dislay the return type, class name and method name const TMEngMethodInfo& methiCur = m_colCallStack[c4CallInd]->methiCalled(); const TMEngClassInfo& meciCur = m_colCallStack[c4CallInd]->meciCalled(); strmTarget << meciCur.strClassPath() << kCIDLib::chPeriod << methiCur.strName() << kCIDLib::chOpenParen; // // Handle the parameters now, if any. We have to go down to the first // parameter and work our way back up. // tCIDLib::TCard4 c4ParmStack = c4CallInd - methiCur.c4ParmCount(); tCIDLib::TCard2 c2ParmId = 0; while (c4ParmStack < c4CallInd) { // Get the description of the parameter and the type and value const TMEngParmInfo& mepiCur = methiCur.mepiFind(c2ParmId); const TMEngClassInfo& meciCur2 = *m_colClassesById[mepiCur.c2ClassId()]; strmTarget << mepiCur.eDir() << kCIDLib::chSpace << meciCur2.strClassPath() << kCIDLib::chSpace << mepiCur.strName(); c4ParmStack++; c2ParmId++; if (c4ParmStack < c4CallInd) strmTarget << kCIDLib::chComma; } // Close off the parms and put out the return type strmTarget << kCIDLib::chCloseParen << L" Returns " << strClassPathForId(methiCur.c2RetClassId(), kCIDLib::False); } tCIDLib::TVoid TCIDMacroEngine::InitTempPool() { const tCIDLib::TCard4 c4Count = m_colClasses.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { m_colTempPool.objAdd ( TCntValList(new tCIDMacroEng::TClassValList(tCIDLib::EAdoptOpts::Adopt, 32)) ); } } // // These two methods provide a temp pool that is used by the methods above // that allow the caller to push temps onto the stack. The first one takes // a name, but generally it will just be an empty string since temps usually // don't need a name. // // The second version just calls the first and passes that empty name. // TMEngClassVal* TCIDMacroEngine::pmecvGet( const TString& strName , const tCIDLib::TCard2 c2ClassId , const tCIDMacroEng::EConstTypes eConst) { // // Get the list for temp items with this class id. This is actually a // counted pointer to the type list for this id. // TCntValList& cptrList = m_colTempPool[c2ClassId]; // // Get the actual counted collection out of it, and search this list for // an available item. // tCIDMacroEng::TClassValList& colList = *cptrList; const tCIDLib::TCard4 c4Count = colList.c4ElemCount(); tCIDLib::TCard4 c4Index = 0; TMEngClassVal* pmecvRet = nullptr; for (; c4Index < c4Count; c4Index++) { pmecvRet = colList[c4Index]; if (!pmecvRet->bIsUsed()) break; } // // If we didn't find one, then create one and add it to this list. Else, // force the passed const type on the one we took from the pool. // if (c4Index == c4Count) { pmecvRet = meciFind(c2ClassId).pmecvMakeStorage(strName, *this, eConst); colList.Add(pmecvRet); } else { pmecvRet->ForceConstType(eConst); } // Mark this one used, and return it pmecvRet->bIsUsed(kCIDLib::True); return pmecvRet; } TMEngClassVal* TCIDMacroEngine::pmecvGet( const TString& strName , const tCIDMacroEng::EIntrinsics eType , const tCIDMacroEng::EConstTypes eConst) { return pmecvGet(strName, tCIDLib::TCard2(eType), eConst); } TMEngClassVal* TCIDMacroEngine::pmecvGet( const tCIDLib::TCard2 c2ClassId , const tCIDMacroEng::EConstTypes eConst) { return pmecvGet(TString::strEmpty(), c2ClassId, eConst); } TMEngClassVal* TCIDMacroEngine::pmecvGet( const tCIDMacroEng::EIntrinsics eType , const tCIDMacroEng::EConstTypes eConst) { return pmecvGet(TString::strEmpty(), tCIDLib::TCard2(eType), eConst); } // // We have to deal with a few circular dependencies here, and theintrinsics // MUST be added so that their ids match up with the EIntrinsicIds enum! // // So, we do a deferred add of each of the intrinsic classes, then go back // and initalize them. This insures that none of their nested classes get // created until we have them all added. Otherwise, their nested // classes would get the indices out of sync. // tCIDLib::TVoid TCIDMacroEngine::RegisterBuiltInClasses() { // // Do a deferred add of all of the intrinsics, in the required order. // This will just get them into the by name and by id lists and with // the right ids. We can then go back and initialize them in their // order of dependency. // TMEngClassInfo* pmeciObj = new TMEngObjectInfo(*this); c2AddClassDefer(pmeciObj); TMEngClassInfo* pmeciVoid = new TMEngVoidInfo(*this); c2AddClassDefer(pmeciVoid); TMEngClassInfo* pmeciOStrm = new TMEngTextOutStreamInfo(*this); c2AddClassDefer(pmeciOStrm); TMEngClassInfo* pmeciFmt = new TMEngFormattableInfo(*this); c2AddClassDefer(pmeciFmt); TMEngClassInfo* pmeciEnum = new TMEngEnumInfo(*this, L"Enum", L"MEng", L"MEng.Formattable", 1); c2AddClassDefer(pmeciEnum); TMEngClassInfo* pmeciBaseInfo = new TMEngBaseInfoInfo(*this); c2AddClassDefer(pmeciBaseInfo); TMEngClassInfo* pmeciBool = new TMEngBooleanInfo(*this); c2AddClassDefer(pmeciBool); TMEngClassInfo* pmeciChar = new TMEngCharInfo(*this); c2AddClassDefer(pmeciChar); TMEngClassInfo* pmeciStr = new TMEngStringInfo(*this); c2AddClassDefer(pmeciStr); TMEngClassInfo* pmeciCard1 = new TMEngCard1Info(*this); c2AddClassDefer(pmeciCard1); TMEngClassInfo* pmeciCard2 = new TMEngCard2Info(*this); c2AddClassDefer(pmeciCard2); TMEngClassInfo* pmeciCard4 = new TMEngCard4Info(*this); c2AddClassDefer(pmeciCard4); TMEngClassInfo* pmeciCard8 = new TMEngCard8Info(*this); c2AddClassDefer(pmeciCard8); TMEngClassInfo* pmeciFloat4 = new TMEngFloat4Info(*this); c2AddClassDefer(pmeciFloat4); TMEngClassInfo* pmeciFloat8 = new TMEngFloat8Info(*this); c2AddClassDefer(pmeciFloat8); TMEngClassInfo* pmeciInt1 = new TMEngInt1Info(*this); c2AddClassDefer(pmeciInt1); TMEngClassInfo* pmeciInt2 = new TMEngInt2Info(*this); c2AddClassDefer(pmeciInt2); TMEngClassInfo* pmeciInt4 = new TMEngInt4Info(*this); c2AddClassDefer(pmeciInt4); TMEngClassInfo* pmeciTime = new TMEngTimeInfo(*this); c2AddClassDefer(pmeciTime); TMEngClassInfo* pmeciStrList = new TMEngStrListInfo(*this); c2AddClassDefer(pmeciStrList); TMEngClassInfo* pmeciExcept = new TMEngExceptInfo(*this); c2AddClassDefer(pmeciExcept); TMEngClassInfo* pmeciMemBuf = new TMEngMemBufInfo(*this); c2AddClassDefer(pmeciMemBuf); TMEngClassInfo* pmeciStrOS = new TMEngStringOutStreamInfo(*this); c2AddClassDefer(pmeciStrOS); // // Do the init phase, which must be done in order of derivation, so // formattable before any of the formattable classes, and base text // out stream before other text out streams, and so on. // pmeciObj->BaseClassInit(*this); pmeciObj->Init(*this); pmeciVoid->BaseClassInit(*this); pmeciVoid->Init(*this); pmeciFmt->BaseClassInit(*this); pmeciFmt->Init(*this); pmeciEnum->BaseClassInit(*this); pmeciEnum->Init(*this); pmeciBaseInfo->BaseClassInit(*this); pmeciBaseInfo->Init(*this); pmeciBool->BaseClassInit(*this); pmeciBool->Init(*this); pmeciChar->BaseClassInit(*this); pmeciChar->Init(*this); pmeciCard1->BaseClassInit(*this); pmeciCard1->Init(*this); pmeciCard2->BaseClassInit(*this); pmeciCard2->Init(*this); pmeciCard4->BaseClassInit(*this); pmeciCard4->Init(*this); pmeciCard8->BaseClassInit(*this); pmeciCard8->Init(*this); pmeciStr->BaseClassInit(*this); pmeciStr->Init(*this); pmeciFloat4->BaseClassInit(*this); pmeciFloat4->Init(*this); pmeciFloat8->BaseClassInit(*this); pmeciFloat8->Init(*this); pmeciInt1->BaseClassInit(*this); pmeciInt1->Init(*this); pmeciInt2->BaseClassInit(*this); pmeciInt2->Init(*this); pmeciInt4->BaseClassInit(*this); pmeciInt4->Init(*this); pmeciStrList->BaseClassInit(*this); pmeciStrList->Init(*this); pmeciExcept->BaseClassInit(*this); pmeciExcept->Init(*this); pmeciMemBuf->BaseClassInit(*this); pmeciMemBuf->Init(*this); pmeciOStrm->BaseClassInit(*this); pmeciOStrm->Init(*this); pmeciStrOS->BaseClassInit(*this); pmeciStrOS->Init(*this); // // Do the base classes for the parameterized collection classes. These // are not intrinsics, but need to be known at a fundamental level. // TMEngClassInfo* pmeciCol = new TMEngCollectInfo(*this); pmeciCol->BaseClassInit(*this); c2AddClass(pmeciCol); pmeciCol = new TMEngVectorInfo ( *this , L"Vector" , L"MEng.System.Runtime" , L"MEng.System.Runtime.Collection" , 0 ); pmeciCol->BaseClassInit(*this); m_c2VectorId = c2AddClass(pmeciCol); // Intrinsic but DO AFTER vector above since it uses a vector parameter pmeciTime->BaseClassInit(*this); pmeciTime->Init(*this); // // !!!! Make sure this one is last. The Cleanup() method uses this // one's id to know where the built in classes end, so that it can // remove all per-invocation classes but leave the built in ones // alone. // pmeciCol = new TMEngArrayInfo ( *this , L"Array" , L"MEng.System.Runtime" , L"MEng.System.Runtime.Collection" , 0 ); pmeciCol->BaseClassInit(*this); m_c2ArrayId = c2AddClass(pmeciCol); }
31.05436
101
0.603629
MarkStega
574ace3982a2a69d82ff19cd4068ce02d68231fb
512
cpp
C++
src/GrayCode.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
src/GrayCode.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
src/GrayCode.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#include "GrayCode.hpp" vector<int> GrayCode::grayCode(int n) { vector<int> ret; if (n > 0) helper(n, ret); else ret.push_back(0); return ret; } void GrayCode::helper(int n, vector<int> &res) { if (n == 1) { res.push_back(0); res.push_back(1); } else { helper(n - 1, res); int sz = res.size(); for (int i = sz - 1; i >= 0; i--) { int val = res[i] | (1 << (n - 1)); res.push_back(val); } } }
18.285714
48
0.451172
yanzhe-chen
574af7d5837e4d25c486b2c8d1fef7e1b6d89b7a
915
cpp
C++
2DGame/windowSystem.cpp
Cimera42/2DGame
9135e3dbed8a909357d57e227ecaba885982e8dc
[ "MIT" ]
3
2015-08-18T12:59:29.000Z
2015-12-15T08:11:10.000Z
2DGame/windowSystem.cpp
Cimera42/2DGame
9135e3dbed8a909357d57e227ecaba885982e8dc
[ "MIT" ]
null
null
null
2DGame/windowSystem.cpp
Cimera42/2DGame
9135e3dbed8a909357d57e227ecaba885982e8dc
[ "MIT" ]
null
null
null
#include "windowSystem.h" #include "globals.h" #include <iostream> #include "windowComponent.h" #include "openGLFunctions.h" #include "keyboardHandler.h" SystemID WindowSystem::ID; WindowSystem::WindowSystem() { std::vector<ComponentID> subList1; //Components needed to subscribe to system subList1.push_back(WindowComponent::getStaticID()); addSubList(subList1); } WindowSystem::~WindowSystem(){} void WindowSystem::update() { for(int subID = 0; subID < subscribedEntities[0].size(); subID++) { Entity * entity = entities[subscribedEntities[0][subID]]; WindowComponent* windowComp = static_cast<WindowComponent*>(entity->getComponent(WindowComponent::getStaticID())); glfwSwapBuffers(windowComp->glfwWindow); } if(isKeyPressed(GLFW_KEY_ESCAPE)) shouldExit = true; glfwSwapBuffers(mainWindow->glfwWindow); }
26.911765
123
0.69071
Cimera42
574b1ba3a0dd29cfd3226492bd5db00581ad69ff
669
cpp
C++
WFC++/Tiled/InputData.cpp
heyx3/WFCpp
a158e1ce5f8fef9b9423711b1bd8ccfdf8c57946
[ "MIT", "Unlicense" ]
7
2019-08-17T15:15:56.000Z
2021-06-03T08:02:27.000Z
WFC++/Tiled/InputData.cpp
heyx3/WFCpp
a158e1ce5f8fef9b9423711b1bd8ccfdf8c57946
[ "MIT", "Unlicense" ]
1
2017-05-01T06:13:47.000Z
2017-05-04T04:07:54.000Z
WFC++/Tiled/InputData.cpp
heyx3/WFCpp
a158e1ce5f8fef9b9423711b1bd8ccfdf8c57946
[ "MIT", "Unlicense" ]
null
null
null
#include "InputData.h" #include <algorithm> using namespace WFC; using namespace WFC::Tiled; namespace { template<typename I> I getMax(I a, I b) { return (a > b) ? a : b; } } const TileIDSet InputData::EmptyTileSet; InputData::InputData(const List<Tile>& _tiles) : tiles(_tiles) { //Collect all tiles that fit each type of edge. for (TileID tileID = 0; tileID < (TileID)tiles.GetSize(); ++tileID) { const auto& tile = tiles[tileID]; for (uint8_t edgeI = 0; edgeI < 4; ++edgeI) { auto key = EdgeInstance(tile.Edges[edgeI], (EdgeDirs)edgeI); matchingEdges[key].Add(tileID); } } }
20.90625
72
0.606876
heyx3
574de25fe8e66db01849b25238daf23f88b40a6b
4,542
cpp
C++
ares/ngp/cpu/interrupts.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/ngp/cpu/interrupts.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/ngp/cpu/interrupts.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
auto CPU::Interrupts::poll() -> void { priority = 0; cpu.inttc3.poll(vector, priority); cpu.inttc2.poll(vector, priority); cpu.inttc1.poll(vector, priority); cpu.inttc0.poll(vector, priority); cpu.intad .poll(vector, priority); cpu.inttx1.poll(vector, priority); cpu.intrx1.poll(vector, priority); cpu.inttx0.poll(vector, priority); cpu.intrx0.poll(vector, priority); cpu.inttr7.poll(vector, priority); cpu.inttr6.poll(vector, priority); cpu.inttr5.poll(vector, priority); cpu.inttr4.poll(vector, priority); cpu.intt3 .poll(vector, priority); cpu.intt2 .poll(vector, priority); cpu.intt1 .poll(vector, priority); cpu.intt0 .poll(vector, priority); cpu.int7 .poll(vector, priority); cpu.int6 .poll(vector, priority); cpu.int5 .poll(vector, priority); cpu.int4 .poll(vector, priority); cpu.int0 .poll(vector, priority); cpu.intwd .poll(vector, priority); cpu.nmi .poll(vector, priority); } auto CPU::Interrupts::fire() -> bool { if(!priority || priority < cpu.r.iff) return false; priority = 0; cpu.inttc3.fire(vector); cpu.inttc2.fire(vector); cpu.inttc1.fire(vector); cpu.inttc0.fire(vector); cpu.intad .fire(vector); cpu.inttx1.fire(vector); cpu.intrx1.fire(vector); cpu.inttx0.fire(vector); cpu.intrx0.fire(vector); cpu.inttr7.fire(vector); cpu.inttr6.fire(vector); cpu.inttr5.fire(vector); cpu.inttr4.fire(vector); cpu.intt3 .fire(vector); cpu.intt2 .fire(vector); cpu.intt1 .fire(vector); cpu.intt0 .fire(vector); cpu.int7 .fire(vector); cpu.int6 .fire(vector); cpu.int5 .fire(vector); cpu.int4 .fire(vector); cpu.int0 .fire(vector); cpu.intwd .fire(vector); cpu.nmi .fire(vector); if(vector == cpu.dma0.vector) { if(cpu.dma(0)) { cpu.dma0.vector = 0; cpu.inttc0.pending = 1; } } else if(vector == cpu.dma1.vector) { if(cpu.dma(1)) { cpu.dma1.vector = 0; cpu.inttc1.pending = 1; } } else if(vector == cpu.dma2.vector) { if(cpu.dma(2)) { cpu.dma2.vector = 0; cpu.inttc2.pending = 1; } } else if(vector == cpu.dma3.vector) { if(cpu.dma(3)) { cpu.dma3.vector = 0; cpu.inttc3.pending = 1; } } else { cpu.r.iff = priority; if(cpu.r.iff != 7) cpu.r.iff++; cpu.interrupt(vector); } poll(); return true; } auto CPU::Interrupt::operator=(bool value) -> void { set(value); } auto CPU::Interrupt::poll(uint8& vector, uint3& priority) -> void { if(!enable || !pending) return; if(!maskable) { priority = 7; vector = this->vector; return; } if(dmaAllowed && cpu.r.iff <= 6) { if(this->vector == cpu.dma0.vector) { priority = 6; vector = this->vector; return; } if(this->vector == cpu.dma1.vector) { priority = 6; vector = this->vector; return; } if(this->vector == cpu.dma2.vector) { priority = 6; vector = this->vector; return; } if(this->vector == cpu.dma3.vector) { priority = 6; vector = this->vector; return; } } if(this->priority == 0 || this->priority == 7) return; if(this->priority >= priority) { priority = this->priority; vector = this->vector; return; } } auto CPU::Interrupt::fire(uint8 vector) -> void { if(this->vector != vector) return; if(line == 0 && !level.low ) pending = 0; if(line == 1 && !level.high) pending = 0; } auto CPU::Interrupt::set(bool line) -> void { line ? raise() : lower(); } auto CPU::Interrupt::raise() -> void { if(!enable || line == 1) return; line = 1; if(pending || !(level.high || edge.rising)) return; pending = 1; cpu.interrupts.poll(); } auto CPU::Interrupt::lower() -> void { if(!enable || line == 0) return; line = 0; if(pending || !(level.low || edge.falling)) return; pending = 1; cpu.interrupts.poll(); } auto CPU::Interrupt::trigger() -> void { if(pending) return; pending = 1; cpu.interrupts.poll(); } auto CPU::Interrupt::clear() -> void { if(!pending) return; pending = 0; cpu.interrupts.poll(); } auto CPU::Interrupt::setEnable(uint1 enable) -> void { if(this->enable == enable) return; this->enable = enable; cpu.interrupts.poll(); } auto CPU::Interrupt::setPriority(uint3 priority) -> void { if(this->priority == priority) return; this->priority = priority; cpu.interrupts.poll(); } auto CPU::Interrupt::power(uint8 vector) -> void { this->vector = vector; //set up defaults that apply to most vectors //CPU::power() will perform specialization as needed later dmaAllowed = 1; enable = 1; maskable = 1; priority = 0; line = 0; pending = 0; level.high = 0; level.low = 0; edge.rising = 1; edge.falling = 0; }
28.566038
94
0.642889
moon-chilled
57517187ec352437ca416e36da9aba0b4872cb19
3,256
cpp
C++
extra/news/src/apk/gtagml/gtagml/gtagml/tag-command/gtagml-tag-command.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/gtagml/gtagml/gtagml/tag-command/gtagml-tag-command.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/gtagml/gtagml/gtagml/tag-command/gtagml-tag-command.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
// Copyright Nathaniel Christen 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "gtagml-tag-command.h" #include "gh/gh-prenode.h" #include "kans.h" USING_KANS(GTagML) bool needs_sdi_mark_check_nothing(QString) { return false; } std::function<bool(QString)> GTagML_Tag_Command::needs_sdi_mark_check_ = &needs_sdi_mark_check_nothing; void GTagML_Tag_Command::set_needs_sdi_mark_check(std::function<bool(QString)> fn) { GTagML_Tag_Command::needs_sdi_mark_check_ = fn; } GTagML_Tag_Command::GTagML_Tag_Command(QString name, QString argument, QString parent_tag_type) : Flags(0), name_(name), argument_(argument), parent_tag_type_(parent_tag_type), ref_position_(0), ref_order_(0), GTagML_htxn_node_(nullptr), arg_GTagML_htxn_node_(nullptr), name_prenode_(nullptr) { //if(name_.contains('-')) // flags.needs_sdi_mark = true; if(needs_sdi_mark_check_(name)) flags.needs_sdi_mark = true; } void GTagML_Tag_Command::each_arg_prenode(std::function<void(GH_Prenode*)> fn) { for(GH_Prenode* ghp : arg_prenodes_) fn(ghp); } void GTagML_Tag_Command::add_arg_prenode(GH_Block_Base* block, const QPair<u4, u4>& pr) { GH_Prenode* prenode = new GH_Prenode(block, pr.first, pr.second); arg_prenodes_.push_back(prenode); } void GTagML_Tag_Command::add_arg_prenode(GH_Block_Base* block, u4 enter, u4 leave) { GH_Prenode* prenode = new GH_Prenode(block, enter, leave); arg_prenodes_.push_back(prenode); } void GTagML_Tag_Command::init_name_prenode(GH_Block_Base* block, const QPair<u4, u4>& pr) { name_prenode_ = new GH_Prenode(block, pr.first, pr.second); } void GTagML_Tag_Command::init_name_prenode(GH_Block_Base* block, u4 enter, u4 leave) { name_prenode_ = new GH_Prenode(block, enter, leave); } void GTagML_Tag_Command::each_arg_GTagML_htxn_node(std::function<void(GTagML_HTXN_Node*)> fn) { for(GTagML_HTXN_Node* nhn : arg_GTagML_htxn_nodes_) fn(nhn); } void GTagML_Tag_Command::add_arg_GTagML_htxn_node(GTagML_HTXN_Node* nhn) { arg_GTagML_htxn_nodes_.append(nhn); } u2 GTagML_Tag_Command::get_whitespace_code() { if(flags.nonstandard_space) return 9999; u2 result = 0; if(flags.left_line_double_gap) result += 2000; if(flags.left_line_gap) result += 1000; if(flags.left_space_gap) result += 100; if(flags.right_space_gap) result += 1; if(flags.right_line_double_gap) result += 20; if(flags.right_line_gap) result += 10; return result; } void GTagML_Tag_Command::normalize_whitespace() { u1 counts [4]; ws().get_counts(counts); get_whitespace_counts_as_inherited(counts); for(int i = 0; i < 4; ++i) if(counts[i] == 255) { flags.nonstandard_space = true; return; } if(counts[0] > 1) flags.right_line_double_gap = true; else if(counts[0] == 1) flags.right_line_gap = true; if(counts[1] >= 1) flags.right_space_gap = true; if(counts[2] > 1) flags.left_line_double_gap = true; else if(counts[2] == 1) flags.left_line_gap = true; if(counts[3] >= 1) flags.left_space_gap = true; } QString GTagML_Tag_Command::latex_name() { QString result = name_; result.remove('-'); return result; }
23.594203
103
0.735258
scignscape
575398ac9333ca9bb91367bca31bbfcfa62e4336
648
cpp
C++
668-kth-smallest-number-in-multiplication-table.cpp
nave7693/leetcode
8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49
[ "MIT" ]
null
null
null
668-kth-smallest-number-in-multiplication-table.cpp
nave7693/leetcode
8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49
[ "MIT" ]
null
null
null
668-kth-smallest-number-in-multiplication-table.cpp
nave7693/leetcode
8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/kth-smallest-number-in-multiplication-table class Solution { public: int findKthNumber(int m, int n, int k) { int low = 1 , high = m * n + 1; while (low < high) { int mid = low + (high - low) / 2; int c = count(mid, m, n); if (c >= k) high = mid; else low = mid + 1; } return high; } private: int count(int v, int m, int n) { int count = 0; for (int i = 1; i <= m; i++) { int temp = min(v / i , n); count += temp; } return count; } };
24
77
0.429012
nave7693
5756aa53b0c5076076d0da276b5b591675693e57
2,236
hpp
C++
SSSP/ESSENS/Core/Basic_SetOps/Level0/extract_elements.hpp
DynamicSSSP/sc18
3070cd5ad7107a3985a7a386ddf99b7f018c178a
[ "MIT" ]
4
2018-12-19T08:40:39.000Z
2021-02-22T17:31:41.000Z
SSSP/ESSENS/Core/Basic_SetOps/Level0/extract_elements.hpp
DynamicSSSP/HIPC18
3070cd5ad7107a3985a7a386ddf99b7f018c178a
[ "MIT" ]
null
null
null
SSSP/ESSENS/Core/Basic_SetOps/Level0/extract_elements.hpp
DynamicSSSP/HIPC18
3070cd5ad7107a3985a7a386ddf99b7f018c178a
[ "MIT" ]
null
null
null
#ifndef EXTRACT_ELEMENTS_HPP #define EXTRACT_ELEMENTS_HPP #include "structure_defs.hpp" using namespace std; //Extracts Relevant Information From Structure //Pairs of Elements //all template <class Type1, class Type2> void get(pair<Type1, Type2> e1, const string &opt, pair<Type1, Type2> *entry) { if(opt=="all"){*entry=e1;} else{cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } //first template <class Type1, class Type2> void get(pair<Type1, Type2> e1, const string &opt, Type1* entry) { if(opt=="first"){*entry=e1.first;} else{cout <<"ESSENS:ERROR:: ^^^^Option" << opt << "Not Defined \n"; } return; } //second template <class Type1, class Type2> void get(pair<Type1, Type2> e1, const string &opt, Type2* entry) { if(opt=="second"){*entry=e1.second;} else{cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } //Edges void get(Edge e1, const string &opt, int *entry) { if(opt=="node1"){*entry=e1.node1;} else { if(opt=="node2"){*entry=e1.node2;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } }//end of first else return; } void get(Edge e1, const string &opt, int_int *entry) { if(opt=="ends"){entry->first=e1.node1; entry->second=e1.node2;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } void get(Edge e1, const string &opt, double *entry) { if(opt=="wt"){*entry=e1.edge_wt;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } void get(Edge e1, const string &opt, Edge *entry) { if(opt=="all"){*entry=e1;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } //Single Elements template <class Type1> void get(Type1 e1, const string &opt, Type1* entry) { if(opt=="all") {*entry=e1;} else{cout <<"ESSENS:ERROR:: ...Option" << opt << "Not Defined \n"; } return; } //As a vector operation template<class Type1, class Type2> void get_all(vector<Type1> Elements, const string &opt, vector<Type2> *Entries) { Entries->resize(0); Type2 entry; for(int i=0;i<Elements.size();i++) { get(Elements[i], opt, &entry); Entries->push_back(entry);} return; } /******* End of Functions **************/ #endif
21.09434
79
0.633721
DynamicSSSP
5756d821d58f933e87a4ed3d5facb16a31b550f5
1,733
cpp
C++
proj.android/jni/Java_joaobapt_CommonAlertListener.cpp
JoaoBaptMG/InfiniteSpaceExplorer
841fbf57e8bcab279a7b252dad1f4ef411c5cc47
[ "MIT" ]
2
2018-11-26T03:47:18.000Z
2019-01-12T10:07:58.000Z
proj.android/jni/Java_joaobapt_CommonAlertListener.cpp
JoaoBaptMG/InfiniteSpaceExplorer
841fbf57e8bcab279a7b252dad1f4ef411c5cc47
[ "MIT" ]
null
null
null
proj.android/jni/Java_joaobapt_CommonAlertListener.cpp
JoaoBaptMG/InfiniteSpaceExplorer
841fbf57e8bcab279a7b252dad1f4ef411c5cc47
[ "MIT" ]
1
2019-12-25T01:28:49.000Z
2019-12-25T01:28:49.000Z
// // Java_joaobapt_CommonAlertListener.cpp // SpaceExplorer // // Created by João Baptista on 22/04/15. // // #include <jni.h> #include <functional> #include "cocos2d.h" #include "platform/android/jni/JniHelper.h" extern "C" JNIEXPORT void JNICALL Java_joaobapt_CommonAlertListener_onClick(JNIEnv* env, jobject thiz, jobject dummy, jint id); JNIEXPORT void JNICALL Java_joaobapt_CommonAlertListener_onClick(JNIEnv* env, jobject thiz, jobject dummy, jint id) { jclass curClass = env->FindClass("joaobapt/CommonAlertListener"); jfieldID confirmCallbackID = env->GetFieldID(curClass, "confirmCallback", "Ljava/nio/ByteBuffer;"); jfieldID cancelCallbackID = env->GetFieldID(curClass, "cancelCallback", "Ljava/nio/ByteBuffer;"); if (!confirmCallbackID || !cancelCallbackID) return; jobject confirmCallbackObject = env->GetObjectField(thiz, confirmCallbackID); jobject cancelCallbackObject = env->GetObjectField(thiz, cancelCallbackID); switch (id) { case -1: { std::function<void()> *result = reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(confirmCallbackObject)); (*result)(); break; } case -2: { std::function<void()> *result = reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(cancelCallbackObject)); (*result)(); break; } default: break; } delete reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(confirmCallbackObject)); delete reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(cancelCallbackObject)); env->DeleteLocalRef(curClass); env->DeleteLocalRef(thiz); }
36.104167
137
0.691864
JoaoBaptMG
57589124f5457088dd6f32d6594069d0753e36cc
1,024
hpp
C++
module_00/ex01/Contact.class.hpp
sqatim/Cplusplus_modules_42
73a113f3731a3eb63f2943c5c6c3d8c14214c7ea
[ "MIT" ]
null
null
null
module_00/ex01/Contact.class.hpp
sqatim/Cplusplus_modules_42
73a113f3731a3eb63f2943c5c6c3d8c14214c7ea
[ "MIT" ]
null
null
null
module_00/ex01/Contact.class.hpp
sqatim/Cplusplus_modules_42
73a113f3731a3eb63f2943c5c6c3d8c14214c7ea
[ "MIT" ]
null
null
null
#ifndef Contact_CLASS_HPP #define Contact_CLASS_HPP #include <iostream> #include <iomanip> class Contact { public: void addInformation(void); void printFields(Contact Contact[]); void condition(std::string str, int check); std::string get_firstName(); std::string get_lastName(); std::string get_nickname(); std::string get_login(); std::string get_postalAdress(); std::string get_emailAdress(); std::string get_phoneNumber(); std::string get_birthdatDate(); std::string get_favoriteMeal(); std::string get_underwearColor(); std::string get_darkestSecret(); private: std::string m_first_name; std::string m_last_name; std::string m_nickname; std::string m_login; std::string m_postal_adress; std::string m_email_adress; std::string m_phone_number; std::string m_birthday_date; std::string m_favorite_meal; std::string m_underwear_color; std::string m_darkest_secret; static int _index; }; #endif
23.272727
47
0.69043
sqatim
575d96da08051cbf14fad2f46e0e1f7b8cb8b95f
173
cpp
C++
CcCard/card.cpp
ZHKU-Robot/yjc-CardGame-Demo
bb4bbb05c04a141779f0fc62749ae2c45c56911f
[ "MIT" ]
1
2021-08-19T09:51:57.000Z
2021-08-19T09:51:57.000Z
CcCard/card.cpp
yujiecong/yjc-CardGame-Demo
bb4bbb05c04a141779f0fc62749ae2c45c56911f
[ "MIT" ]
null
null
null
CcCard/card.cpp
yujiecong/yjc-CardGame-Demo
bb4bbb05c04a141779f0fc62749ae2c45c56911f
[ "MIT" ]
null
null
null
#include "card.h" #include "ui_card.h" Card::Card(QWidget *parent) : QWidget(parent), ui(new Ui::Card) { ui->setupUi(this); } Card::~Card() { delete ui; }
11.533333
29
0.583815
ZHKU-Robot
576270b074e1c48381666474cef9051cfd10ee18
8,206
cpp
C++
src/d3d11/d3d11-device.cpp
Impulse21/nvrhi
f272a6595dd0768a8e3419f0075f0edf40d00391
[ "MIT" ]
2
2021-08-28T23:02:30.000Z
2021-08-28T23:26:21.000Z
src/d3d11/d3d11-device.cpp
Impulse21/nvrhi
f272a6595dd0768a8e3419f0075f0edf40d00391
[ "MIT" ]
null
null
null
src/d3d11/d3d11-device.cpp
Impulse21/nvrhi
f272a6595dd0768a8e3419f0075f0edf40d00391
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "d3d11-backend.h" #include <nvrhi/utils.h> #include <sstream> #include <iomanip> namespace nvrhi::d3d11 { void Context::error(const std::string& message) const { messageCallback->message(MessageSeverity::Error, message.c_str()); } void SetDebugName(ID3D11DeviceChild* pObject, const char* name) { D3D_SET_OBJECT_NAME_N_A(pObject, UINT(strlen(name)), name); } DeviceHandle createDevice(const DeviceDesc& desc) { Device* device = new Device(desc); return DeviceHandle::Create(device); } Device::Device(const DeviceDesc& desc) { m_Context.messageCallback = desc.messageCallback; m_Context.immediateContext = desc.context; desc.context->GetDevice(&m_Context.device); #if NVRHI_D3D11_WITH_NVAPI m_Context.nvapiAvailable = NvAPI_Initialize() == NVAPI_OK; if (m_Context.nvapiAvailable) { NV_QUERY_SINGLE_PASS_STEREO_SUPPORT_PARAMS stereoParams{}; stereoParams.version = NV_QUERY_SINGLE_PASS_STEREO_SUPPORT_PARAMS_VER; if (NvAPI_D3D_QuerySinglePassStereoSupport(m_Context.device, &stereoParams) == NVAPI_OK && stereoParams.bSinglePassStereoSupported) { m_SinglePassStereoSupported = true; } // There is no query for FastGS, so query support for FP16 atomics as a proxy. // Both features were introduced in the same architecture (Maxwell). bool supported = false; if (NvAPI_D3D11_IsNvShaderExtnOpCodeSupported(m_Context.device, NV_EXTN_OP_FP16_ATOMIC, &supported) == NVAPI_OK && supported) { m_FastGeometryShaderSupported = true; } } #endif D3D11_BUFFER_DESC bufferDesc = {}; bufferDesc.ByteWidth = c_MaxPushConstantSize; bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.CPUAccessFlags = 0; const HRESULT res = m_Context.device->CreateBuffer(&bufferDesc, nullptr, &m_Context.pushConstantBuffer); if (FAILED(res)) { std::stringstream ss; ss << "CreateBuffer call failed for the push constants buffer, HRESULT = 0x" << std::hex << std::setw(8) << res; m_Context.error(ss.str()); } m_ImmediateCommandList = CommandListHandle::Create(new CommandList(m_Context, this, CommandListParameters())); } GraphicsAPI Device::getGraphicsAPI() { return GraphicsAPI::D3D11; } Object Device::getNativeObject(ObjectType objectType) { switch (objectType) { case ObjectTypes::D3D11_Device: return Object(m_Context.device); case ObjectTypes::D3D11_DeviceContext: return Object(m_Context.immediateContext); case ObjectTypes::Nvrhi_D3D11_Device: return this; default: return nullptr; } } HeapHandle Device::createHeap(const HeapDesc&) { utils::NotSupported(); return nullptr; } CommandListHandle Device::createCommandList(const CommandListParameters& params) { if (!params.enableImmediateExecution) { m_Context.error("Deferred command lists are not supported by the D3D11 backend."); return nullptr; } if (params.queueType != CommandQueue::Graphics) { m_Context.error("Non-graphics queues are not supported by the D3D11 backend."); return nullptr; } return m_ImmediateCommandList; } bool Device::queryFeatureSupport(Feature feature, void* pInfo, size_t infoSize) { (void)pInfo; (void)infoSize; switch (feature) // NOLINT(clang-diagnostic-switch-enum) { case Feature::DeferredCommandLists: return false; case Feature::SinglePassStereo: return m_SinglePassStereoSupported; case Feature::FastGeometryShader: return m_FastGeometryShaderSupported; default: return false; } } rt::PipelineHandle Device::createRayTracingPipeline(const rt::PipelineDesc&) { return nullptr; } rt::AccelStructHandle Device::createAccelStruct(const rt::AccelStructDesc&) { return nullptr; } MemoryRequirements Device::getAccelStructMemoryRequirements(rt::IAccelStruct*) { utils::NotSupported(); return MemoryRequirements(); } bool Device::bindAccelStructMemory(rt::IAccelStruct*, IHeap*, uint64_t) { utils::NotSupported(); return false; } MeshletPipelineHandle Device::createMeshletPipeline(const MeshletPipelineDesc&, IFramebuffer*) { return nullptr; } void Device::waitForIdle() { if (!m_WaitForIdleQuery) { m_WaitForIdleQuery = createEventQuery(); } if (!m_WaitForIdleQuery) return; setEventQuery(m_WaitForIdleQuery, CommandQueue::Graphics); waitEventQuery(m_WaitForIdleQuery); resetEventQuery(m_WaitForIdleQuery); } SamplerHandle Device::createSampler(const SamplerDesc& d) { D3D11_SAMPLER_DESC desc11; UINT reductionType = convertSamplerReductionType(d.reductionType); if (d.maxAnisotropy > 1.0f) { desc11.Filter = D3D11_ENCODE_ANISOTROPIC_FILTER(reductionType); } else { desc11.Filter = D3D11_ENCODE_BASIC_FILTER( d.minFilter ? D3D11_FILTER_TYPE_LINEAR : D3D11_FILTER_TYPE_POINT, d.magFilter ? D3D11_FILTER_TYPE_LINEAR : D3D11_FILTER_TYPE_POINT, d.mipFilter ? D3D11_FILTER_TYPE_LINEAR : D3D11_FILTER_TYPE_POINT, reductionType); } desc11.AddressU = convertSamplerAddressMode(d.addressU); desc11.AddressV = convertSamplerAddressMode(d.addressV); desc11.AddressW = convertSamplerAddressMode(d.addressW); desc11.MipLODBias = d.mipBias; desc11.MaxAnisotropy = std::max((UINT)d.maxAnisotropy, 1U); desc11.ComparisonFunc = D3D11_COMPARISON_LESS; desc11.BorderColor[0] = d.borderColor.r; desc11.BorderColor[1] = d.borderColor.g; desc11.BorderColor[2] = d.borderColor.b; desc11.BorderColor[3] = d.borderColor.a; desc11.MinLOD = 0; desc11.MaxLOD = D3D11_FLOAT32_MAX; RefCountPtr<ID3D11SamplerState> sState; const HRESULT res = m_Context.device->CreateSamplerState(&desc11, &sState); if (FAILED(res)) { std::stringstream ss; ss << "CreateSamplerState call failed, HRESULT = 0x" << std::hex << std::setw(8) << res; m_Context.error(ss.str()); return nullptr; } Sampler* sampler = new Sampler(); sampler->sampler = sState; sampler->desc = d; return SamplerHandle::Create(sampler); } } // namespace nvrhi::d3d11
33.357724
143
0.652693
Impulse21
576a0800b37bbb4f4f510d3831faf261ef484773
180
cpp
C++
src/bullet.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
null
null
null
src/bullet.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
1
2015-05-29T04:49:09.000Z
2015-05-29T04:49:09.000Z
src/bullet.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
null
null
null
#include "bullet.h" bullet::bullet(const sf::Texture& texture,const sf::Vector2f& pos) : sprite(texture) { this->sprite.setPosition(pos); } bullet::~bullet() { //dtor }
15
85
0.655556
warlord500
576da8069b59e53da6e5df30d9347d9ab1badec0
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_start.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_start.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_start.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:4b7afeba550c42f9d83c1216d8b1f28efe9eb21defa44e01e94a8fde5aa5b682 size 230
32
75
0.882813
initialz
577147c47c118b7ad546fafc37ccf7359e76743e
1,577
cpp
C++
PlatformLib/Graphics/Vulkan/cpp/VulkanTextureView.cpp
YIMonge/Rev
db3b71a27659a2652bdd50069a881702b3ae059e
[ "MIT" ]
null
null
null
PlatformLib/Graphics/Vulkan/cpp/VulkanTextureView.cpp
YIMonge/Rev
db3b71a27659a2652bdd50069a881702b3ae059e
[ "MIT" ]
null
null
null
PlatformLib/Graphics/Vulkan/cpp/VulkanTextureView.cpp
YIMonge/Rev
db3b71a27659a2652bdd50069a881702b3ae059e
[ "MIT" ]
null
null
null
#ifdef _USE_VULKAN #include "VulkanTextureView.h" void VulkanTextureView::Create(revDevice* device, const revTexture& texture, const VulkanSampler& sampler, VulkanDescriptorSet::Chunk& chunk) { this->device = device; VkImageViewCreateInfo imageViewCreateInfo = {}; imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCreateInfo.pNext = nullptr; imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCreateInfo.components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, }; imageViewCreateInfo.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; imageViewCreateInfo.flags = 0; imageViewCreateInfo.format = ConvertToVKFormat(texture.GetFormat()); imageViewCreateInfo.image = texture.GetHandle(); VkResult result = vkCreateImageView(device->GetDevice(), &imageViewCreateInfo, nullptr, &resourceView); if(result != VK_SUCCESS) { NATIVE_LOGE("Vulkan error. File[%s], line[%d]", __FILE__,__LINE__); return; } descriptorImageInfo.sampler = sampler.GetHandle(); descriptorImageInfo.imageView = resourceView; descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; //descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; chunk.UpdateResource(0, DESCRIPTOR_TYPE::TEXTURE_SHADER_RESOURCE_VIEW, &descriptorImageInfo, nullptr, nullptr); } void VulkanTextureView::Destroy() { vkDestroyImageView(device->GetDevice(), resourceView, nullptr); } #endif
39.425
141
0.763475
YIMonge
57744dc92be53b43a9265b40199e9d0dceeae52c
335
hpp
C++
raisim/win32/mt_release/include/raisim/math/Core.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
142
2020-10-21T18:18:13.000Z
2022-03-29T11:49:25.000Z
raisim/win32/mt_release/include/raisim/math/Core.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
192
2020-10-21T15:51:15.000Z
2022-03-28T12:56:01.000Z
raisim/win32/mt_release/include/raisim/math/Core.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
51
2020-10-26T08:29:54.000Z
2022-03-23T12:00:23.000Z
//----------------------------// // This file is part of RaiSim// // Copyright 2020, RaiSim Tech// //----------------------------// #ifndef RAIMATH__CORE_HPP_ #define RAIMATH__CORE_HPP_ #include "Expression.hpp" #include "Eigen/Core" #include "Eigen/Dense" #include "Matrix.hpp" #include "Product.hpp" #endif //RAIMATH__CORE_HPP_
18.611111
32
0.602985
simRepoRelease
57774f31f626799496f06bd086943ae680404762
226
cc
C++
test_testdriver/test_main.cc
KarlJansson/CMakeMaker
05ec25ca4ea196a50697e13f7756e7be79a08281
[ "MIT" ]
null
null
null
test_testdriver/test_main.cc
KarlJansson/CMakeMaker
05ec25ca4ea196a50697e13f7756e7be79a08281
[ "MIT" ]
null
null
null
test_testdriver/test_main.cc
KarlJansson/CMakeMaker
05ec25ca4ea196a50697e13f7756e7be79a08281
[ "MIT" ]
null
null
null
#include "precomp.h" #include "test_common_writer.h" #include "test_subdir_writer.h" #include "test_testtarget_writer.h" int main(int argc, char** args) { ::testing::InitGoogleTest(&argc, args); return RUN_ALL_TESTS(); }
22.6
41
0.738938
KarlJansson
577d88d8aec5a4153ce1aba5cb462c3dd6e56bac
4,295
hpp
C++
logos/consensus/persistence/block_cache.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
3
2020-01-17T18:05:19.000Z
2021-12-29T04:21:59.000Z
logos/consensus/persistence/block_cache.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
null
null
null
logos/consensus/persistence/block_cache.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
2
2020-12-22T05:51:53.000Z
2021-06-08T00:27:46.000Z
#pragma once #include <memory> #include <mutex> #include <unordered_set> #include <logos/lib/numbers.hpp> #include <logos/lib/hash.hpp> #include <logos/lib/trace.hpp> #include <logos/blockstore.hpp> #include <logos/consensus/messages/common.hpp> #include <logos/consensus/messages/messages.hpp> #include <logos/epoch/epoch.hpp> #include <logos/epoch/epoch_handler.hpp> #include <logos/microblock/microblock.hpp> #include <logos/microblock/microblock_handler.hpp> #include "block_container.hpp" #include "block_write_queue.hpp" namespace logos { class IBlockCache { public: using RBPtr = std::shared_ptr<ApprovedRB>; using MBPtr = std::shared_ptr<ApprovedMB>; using EBPtr = std::shared_ptr<ApprovedEB>; enum add_result { FAILED, EXISTS, OK }; // should be called by bootstrap and P2P /** * add an epoch block to the cache * @param block the block * @return true if the block has good signatures. */ virtual add_result AddEpochBlock(EBPtr block) = 0; /** * add a micro block to the cache * @param block the block * @return true if the block has good signatures. */ virtual add_result AddMicroBlock(MBPtr block) = 0; /** * add a request block to the cache * @param block the block * @return true if the block has good signatures. */ virtual add_result AddRequestBlock(RBPtr block) = 0; // should be called by consensus virtual void StoreEpochBlock(EBPtr block) = 0; virtual void StoreMicroBlock(MBPtr block) = 0; virtual void StoreRequestBlock(RBPtr block) = 0; virtual bool ValidateRequest( std::shared_ptr<Request> req, uint32_t epoch_num, logos::process_return& result) {return false;} // should be called by bootstrap /** * check if a block is cached * @param b the hash of the block * @return true if the block is in the cache */ virtual bool IsBlockCached(const BlockHash &b) = 0; virtual bool IsBlockCachedOrQueued(const BlockHash &b) = 0; virtual ~IBlockCache() = default; }; class BlockCache: public IBlockCache { public: using Store = logos::block_store; /** * constructor * @param store the database */ BlockCache(boost::asio::io_service & service, Store & store, std::queue<BlockHash> *unit_test_q = 0); /** * (inherited) add an epoch block to the cache * @param block the block * @return true if the block has good signatures. */ add_result AddEpochBlock(EBPtr block) override; /** * (inherited) add a micro block to the cache * @param block the block * @return true if the block has good signatures. */ add_result AddMicroBlock(MBPtr block) override; /** * (inherited) add a request block to the cache * @param block the block * @return true if the block has good signatures. */ add_result AddRequestBlock(RBPtr block) override; void StoreEpochBlock(EBPtr block) override; void StoreMicroBlock(MBPtr block) override; void StoreRequestBlock(RBPtr block) override; virtual bool ValidateRequest( std::shared_ptr<Request> req, uint32_t epoch_num, logos::process_return& result) { return _write_q.ValidateRequest(req,epoch_num,result); } /** * (inherited) check if a block is cached * @param b the hash of the block * @return true if the block is in the cache */ bool IsBlockCached(const BlockHash &b) override; bool IsBlockCachedOrQueued(const BlockHash &b) override; void ProcessDependencies(EBPtr block); void ProcessDependencies(MBPtr block); void ProcessDependencies(RBPtr block); private: /* * should be called when: * (1) a new block is added to the beginning of any chain of the oldest epoch, * (2) a new block is added to the beginning of any BSB chain of the newest epoch, * in which the first MB has not been received. */ void Validate(uint8_t bsb_idx = 0); block_store & _store; BlockWriteQueue _write_q; PendingBlockContainer _block_container; Log _log; }; }
27.183544
105
0.652619
LogosNetwork
578426ac2e24c34d55bdf3160fe668698aca5adc
264
hpp
C++
dynamic/wrappers/cell_based/SimpleTargetAreaModifier2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
dynamic/wrappers/cell_based/SimpleTargetAreaModifier2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
dynamic/wrappers/cell_based/SimpleTargetAreaModifier2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#ifndef SimpleTargetAreaModifier2_hpp__pyplusplus_wrapper #define SimpleTargetAreaModifier2_hpp__pyplusplus_wrapper namespace py = pybind11; void register_SimpleTargetAreaModifier2_class(py::module &m); #endif // SimpleTargetAreaModifier2_hpp__pyplusplus_wrapper
37.714286
61
0.893939
jmsgrogan
5785136e1ce93a212f6f6835c971d31e13efba6e
472
cpp
C++
calendar/monthFirstDay.cpp
allhailthetail/cpp-itp-main
43a33a3df68feac3a600b3a51af3fbe893225277
[ "MIT" ]
null
null
null
calendar/monthFirstDay.cpp
allhailthetail/cpp-itp-main
43a33a3df68feac3a600b3a51af3fbe893225277
[ "MIT" ]
null
null
null
calendar/monthFirstDay.cpp
allhailthetail/cpp-itp-main
43a33a3df68feac3a600b3a51af3fbe893225277
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int monthStart(int month, int year){ //fills an array with days of the week... //determines day of the week the 1st is on: static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; const int day = 1; //always first day of month int week_day; year -= month < 3; week_day = ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7; return week_day; } int main(){ cout << monthStart(2,2018) << endl;; }
21.454545
75
0.599576
allhailthetail
578b957954c6bf9c9ade1639de916244b36d04f3
1,101
cpp
C++
Graphs/Longest Path in a DAG.cpp
Sumitkk10/Competitive-Programming
886eabe251f962336070a02bba92c9ac768d8e92
[ "MIT" ]
3
2020-09-25T07:40:29.000Z
2020-10-09T18:11:57.000Z
Graphs/Longest Path in a DAG.cpp
Sumitkk10/Competitive-Programming
886eabe251f962336070a02bba92c9ac768d8e92
[ "MIT" ]
null
null
null
Graphs/Longest Path in a DAG.cpp
Sumitkk10/Competitive-Programming
886eabe251f962336070a02bba92c9ac768d8e92
[ "MIT" ]
2
2020-09-25T10:32:57.000Z
2021-02-28T03:23:29.000Z
// Longest path in a DAG #include <bits/stdc++.h> #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) #define ll long long int #define ld long double using namespace std; const int N = 1e6 + 5; const int MOD = 1e9 + 7; vector<int> graph[N]; queue<int> q; int LPD[N], indegree[N]; bool vis[N]; void dfs(int source){ vis[source] = 1; for(auto kk : graph[source]){ indegree[kk]++; if(!vis[kk]) dfs(kk); } } void topo(){ while(!q.empty()){ int x = q.front(); q.pop(); for(auto k : graph[x]){ if(!vis[k]){ indegree[k]--; if(indegree[k] == 0){ q.push(k); vis[k] = true; } LPD[k] = max(LPD[k], LPD[x] + 1); } } } } int main(){ fast; int n, m; cin >> n >> m; for(int i = 0; i < m; ++i){ int u, v; cin >> u >> v; graph[u].push_back(v); } for(int i = 1; i <= n; ++i) if(!vis[i]) dfs(i); memset(vis, 0, sizeof(vis)); for(int i = 1; i <= n; ++i){ if(!indegree[i]){ q.push(i); vis[i] = true; } } topo(); int ans = 0; for(int i = 1; i <= n; ++i) ans = max(ans, LPD[i]); cout << ans << '\n'; return 0; }
16.432836
70
0.521344
Sumitkk10
c2318bd4493f89a167861620a9f8315d8b5b6cc0
10,523
cpp
C++
Chap09/BusObject/CQuartermaster.cpp
KLM-GIT/Professional-NT-Services
cf058239286b5be14a21f7f19d41683842b92313
[ "Apache-2.0" ]
null
null
null
Chap09/BusObject/CQuartermaster.cpp
KLM-GIT/Professional-NT-Services
cf058239286b5be14a21f7f19d41683842b92313
[ "Apache-2.0" ]
null
null
null
Chap09/BusObject/CQuartermaster.cpp
KLM-GIT/Professional-NT-Services
cf058239286b5be14a21f7f19d41683842b92313
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #define HANDLEALLOCCOST 1000 //remove to use //---------------------------------------- // // List Class members // #define SPINX 5000 CFreeList::CFreeList() : m_pHead( NULL ), m_pTail( NULL ), m_Count(0) { InitializeCriticalSectionAndSpinCount( &m_cs, SPINX ); } CFreeList::~CFreeList() { RemoveAll(); DeleteCriticalSection( &m_cs ); } void CFreeList::AddTail( const RHANDLE* newHandle ) { NODE* pNew = new NODE(newHandle); EnterCriticalSection( &m_cs ); if( m_pTail == NULL) //list is empty { m_pHead = pNew; } else { pNew->prev = m_pTail; m_pTail->next = pNew; } m_pTail = pNew; m_Count++; LeaveCriticalSection( &m_cs ); } void CFreeList::RemoveAll( ) { NODE* pNext = 0; EnterCriticalSection( &m_cs ); NODE* p = m_pHead; while( p != NULL ) { pNext = p->next; delete p; p = pNext; } m_pHead = m_pTail = NULL; m_Count = 0; LeaveCriticalSection( &m_cs ); } const RHANDLE* CFreeList::Pop( ) { const RHANDLE* rh = 0; EnterCriticalSection( &m_cs ); NODE* p = m_pHead; if( p != NULL ) { //obtain rhandle rh = p->pRH; if( p->next ) { p->next->prev = NULL; m_pHead = p->next; } else m_pHead = m_pTail = NULL; delete p; m_Count--; } LeaveCriticalSection( &m_cs ); return rh; } //--------------------------------------------------------------------------- // CResourceArray Class // // // CResourceArray::CResourceArray( long dwSize ) :m_size(dwSize), m_count(0), m_hEnv(NULL) { InitializeCriticalSectionAndSpinCount( &m_cs, SPINX); m_pHandles = new RHANDLEHEADER* [dwSize]; memset(m_pHandles, 0, sizeof(RHANDLEHEADER*) * dwSize); } void CResourceArray::Init( LPTSTR szServer, LPTSTR szLogin, LPTSTR szPassword) { _tcscpy( m_szServer, szServer ); _tcscpy( m_szLogin, szLogin ); _tcscpy( m_szPassword, szPassword); } CResourceArray::~CResourceArray( ) { RemoveAll( ); delete [] m_pHandles; m_size = 0; m_pHandles = NULL; if (m_hEnv) SQLFreeHandle(SQL_HANDLE_ENV, m_hEnv); DeleteCriticalSection( &m_cs ); } const RHANDLE* CResourceArray::Add( ) { SQLHDBC hSession = 0; RHANDLE* chd = 0; EnterCriticalSection( &m_cs ); if (m_count < m_size) { hSession = GetResourceHandle( ); if ( hSession != 0 ) { RHANDLEHEADER* pSH = new RHANDLEHEADER; chd = new RHANDLE; chd->handle = hSession; chd->pos = m_count; pSH->pRH = chd; pSH->bFree = TRUE; pSH->dwTime = 0; m_pHandles[m_count] = pSH; m_count++ ; } else { //Event Log call CEventLog el(_Module.m_szServiceName); el.LogEvent( BUSOBJ_HANDLE_CONNECTION_FAILED, EVENTLOG_ERROR_TYPE); } } LeaveCriticalSection( &m_cs ); return chd; } void CResourceArray::RemoveAll( ) { RHANDLEHEADER* pTemp = 0; EnterCriticalSection( &m_cs ); for( int i=0; i<m_count; i++ ) { pTemp = m_pHandles[i]; if( pTemp ) { const RHANDLE* pRHTemp = pTemp->pRH; if( pRHTemp ) { ReleaseResourceHandle( pRHTemp->handle ); delete (RHANDLE*)pRHTemp; } delete pTemp; } m_pHandles[i] = NULL; } m_count = 0; LeaveCriticalSection( &m_cs ); } SQLHDBC CResourceArray::GetResourceHandle( ) { if (!m_hEnv) AllocateEnvironment(); if(!m_hEnv) goto ErrorH; SQLHDBC hdbc; SQLRETURN rc; //Open connection rc = SQLAllocHandle(SQL_HANDLE_DBC, m_hEnv, &hdbc); if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) goto ErrorH; // Set login timeout to 5 seconds. SQLSetConnectAttr(hdbc, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER)5, 0); // Connect to data source rc = SQLConnect(hdbc,(SQLCHAR*) m_szServer, SQL_NTS, (SQLCHAR*) m_szLogin, SQL_NTS, (SQLCHAR*) m_szPassword, SQL_NTS); if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) goto ErrorH; return hdbc; ErrorH: CEventLog el(_Module.m_szServiceName); el.LogEvent(BUSOBJ_HANDLE_CONNECTION_FAILED, EVENTLOG_ERROR_TYPE); return NULL; } void CResourceArray::ReleaseResourceHandle( SQLHDBC hResHandle ) { if(hResHandle) { SQLDisconnect(hResHandle); SQLFreeHandle(SQL_HANDLE_DBC, hResHandle); } } void CResourceArray::AllocateEnvironment() { SQLRETURN rc; rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnv); rc = SQLSetEnvAttr(m_hEnv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); return; } //--------------------------------------------------------------------------- // // CQuartermaster Class // // CQuartermaster* CQuartermaster::m_pThis = 0; CQuartermaster::CQuartermaster( ) :m_dwNumCurrentResources(0), m_bStartAllocator(FALSE) { m_pThis = this; InitializeCriticalSectionAndSpinCount( &m_cs, SPINX ); } void CQuartermaster::Init( DWORD dwMaxResources, DWORD dwStartResources, DWORD dwWaitForHandleTime, DWORD dwHandleLifeTime, DWORD dwAllocationPoll, DWORD dwMinPoolSize, DWORD dwResourceAllocSize, DWORD dwDeadResourcePoll, LPTSTR szServer, LPTSTR szLogin, LPTSTR szPassword ) { //Event to signal workers to stop m_hStopEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); m_dwStartResources = dwStartResources; m_dwMaxResources = dwMaxResources; m_dwWaitForHandleTime = dwWaitForHandleTime; m_dwHandleLifeTime = dwHandleLifeTime; m_dwAllocationPoll = dwAllocationPoll; m_dwMinPoolSize = dwMinPoolSize; m_dwResourceAllocSize = dwResourceAllocSize; m_dwDeadResourcePoll =dwDeadResourcePoll; m_pResources = new CResourceArray( dwMaxResources ); m_pFreeList = new CFreeList; //Initialize the Resource Array m_pResources->Init( szServer, szLogin, szPassword ); //Initialize the Semaphore with max possible m_hSem = CreateSemaphore( NULL, 0, dwMaxResources, NULL ); DWORD dwAid, dwPid; m_hAllocThread = (HANDLE)_beginthreadex( NULL, 0, (PBEGINTHREADEX_TFUNC)CQuartermaster::AllocateMoreResourcesThread, 0, 0, (PBEGINTHREADEX_TID)&dwAid ); m_hRefreshThread = (HANDLE)_beginthreadex( NULL, 0, (PBEGINTHREADEX_TFUNC)CQuartermaster::RefreshDeadResourcesThread, 0, 0, (PBEGINTHREADEX_TID)&dwPid ); } CQuartermaster::~CQuartermaster( ) { if (m_hAllocThread) CloseHandle(m_hAllocThread); if (m_hRefreshThread) CloseHandle(m_hRefreshThread); CloseHandle( m_hSem ); delete m_pResources; m_pResources = NULL; delete m_pFreeList; m_pFreeList = NULL; DeleteCriticalSection( &m_cs ); } DWORD CQuartermaster::GetFreeResource( const RHANDLE** poutHandle) { //Function does NOT find a KNOWN valid handle. It is up to the //object to check handle validity and retry if necessary. const RHANDLE* pHandle = 0; if ( _Module.m_bPaused || _Module.m_bStopped ) return BUSOBJ_SERVICE_STOPPED_PAUSED; //Wait on the semaphore. I can block for a short time if no handles left. if( WaitForSingleObject( m_hSem, m_dwWaitForHandleTime ) == WAIT_OBJECT_0 ) { //Get the handle and give it out pHandle = m_pFreeList->Pop(); if( pHandle ) { //Mark time and busy m_pResources->SetBusy( pHandle->pos ); *poutHandle = pHandle; return 0; } } *poutHandle = NULL; return BUSOBJ_NOSESSIONS_AVAILABLE; } void CQuartermaster::ReleaseResource( const RHANDLE* handle ) { //Make sure handle hasn't been released twice by client accidentally if (handle) { if( m_pResources->IsFree( handle->pos ) == FALSE ) { long lPrev; m_pResources->SetFree( handle->pos ); m_pFreeList->AddTail( handle ); ReleaseSemaphore( m_hSem, 1, &lPrev ); } } } DWORD CQuartermaster::AllocateResources( DWORD dwNumAdd ) { DWORD count = 0; const RHANDLE* pRH = 0; DWORD newRes = 0; DWORD dwNumRes = GetNumResources(); if ( dwNumAdd + dwNumRes > m_dwMaxResources ) newRes = m_dwMaxResources - dwNumRes; else newRes = dwNumAdd; //Connect the sessions for( DWORD i=0; i<newRes; i++ ) { pRH = m_pResources->Add( ); if( pRH ) { m_pFreeList->AddTail( pRH ); count++; } } InterlockedExchangeAdd((long*)&m_dwNumCurrentResources, count); //ReleaseSemaphore count number of times if( count > 0 ) { long dwPrev; ReleaseSemaphore( m_hSem, (long)count ,&dwPrev ); } //Write to event log that x new handles were allocated TCHAR sz1[5], sz2[5]; wsprintf(sz1,_T("%lu"), count ); wsprintf(sz2,_T("%lu"), dwNumRes ); const TCHAR* rgsz[2] = { sz1, sz2 }; CEventLog el(_Module.m_szServiceName); el.LogEvent( BUSOBJ_MORESESSIONS_ALLOCATED, rgsz, 2, EVENTLOG_INFORMATION_TYPE ); //Also write if maximum session limit was reached. if ( GetNumResources() >= m_dwMaxResources ) { el.LogEvent( BUSOBJ_MAXIMUM_SESSIONS_ALLOCATED, EVENTLOG_INFORMATION_TYPE ); } //Allow the allocator thread to start, if it hasn't before if(!m_bStartAllocator) InterlockedExchange( (long*)&m_bStartAllocator, true); //Return return count; } void CQuartermaster::DeallocateResources( ) { EnterCriticalSection( &m_cs ); //Stop the worker threads SetStop(); m_dwNumCurrentResources = 0; m_pResources->RemoveAll( ); m_pFreeList->RemoveAll( ); LeaveCriticalSection( &m_cs ); } //Will be called on a schedule by another thread void CQuartermaster::ReleaseDeadResources( ) { //Walk the list and see if any bFrees are FALSE with //now - timestamp > m_dwHandleLifetime //If so, bFree = TRUE //and add back to free list. CRITICAL_SECTION cs; InitializeCriticalSection( &cs ); DWORD now = ::GetTickCount(); RHANDLEHEADER* pTemp = 0; DWORD stamp = 0; long count = m_pResources->GetCount(); for( long i=0; i<count; i++ ) { pTemp = m_pResources->m_pHandles[i]; if( pTemp ) { EnterCriticalSection( &cs ); if( m_pResources->IsFree(i) == FALSE ) { stamp = pTemp->dwTime; if( now - stamp > m_dwHandleLifeTime ) { if( pTemp->pRH ) { m_pResources->SetFree(i); m_pFreeList->AddTail( pTemp->pRH ); } } } LeaveCriticalSection( &cs ); } } DeleteCriticalSection( &cs ); } ///////// //Background task threads ///////// DWORD WINAPI CQuartermaster::AllocateMoreResourcesThread( LPVOID lpParameter ) { while (WaitForSingleObject( m_pThis->m_hStopEvent, m_pThis->m_dwAllocationPoll ) == WAIT_TIMEOUT ) { if( m_pThis->FreeResourcesLeft() <= m_pThis->m_dwMinPoolSize && m_pThis->m_bStartAllocator) { m_pThis->AllocateResources( m_pThis->m_dwResourceAllocSize ); Sleep( HANDLEALLOCCOST ); //**Simulation** of amount of time it takes } } return 0; } DWORD WINAPI CQuartermaster::RefreshDeadResourcesThread( LPVOID lpParameter ) { while (WaitForSingleObject( m_pThis->m_hStopEvent, m_pThis->m_dwDeadResourcePoll ) == WAIT_TIMEOUT ) { m_pThis->ReleaseDeadResources( ); } return 0; }
20.962151
101
0.683265
KLM-GIT
c23800301b0fcdd35166b312a99495b381f598e3
3,821
hpp
C++
packages/monte_carlo/collision/electron/src/MonteCarlo_HybridElasticPositronatomicReaction.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/electron/src/MonteCarlo_HybridElasticPositronatomicReaction.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/electron/src/MonteCarlo_HybridElasticPositronatomicReaction.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_HybridElasticPositronatomicReaction.hpp //! \author Luke Kersting //! \brief The hybrid scattering elastic positron-atomic reaction class decl. //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_HYBRID_ELASTIC_POSITRONATOMIC_REACTION_HPP #define MONTE_CARLO_HYBRID_ELASTIC_POSITRONATOMIC_REACTION_HPP // FRENSIE Includes #include "MonteCarlo_PositronatomicReaction.hpp" #include "MonteCarlo_StandardReactionBaseImpl.hpp" #include "MonteCarlo_HybridElasticElectronScatteringDistribution.hpp" namespace MonteCarlo{ //! The hybrid elastic positron-atomic reaction class template<typename InterpPolicy, bool processed_cross_section = false> class HybridElasticPositronatomicReaction : public StandardReactionBaseImpl<PositronatomicReaction,InterpPolicy,processed_cross_section> { // Typedef for the base class type typedef StandardReactionBaseImpl<PositronatomicReaction,InterpPolicy,processed_cross_section> BaseType; public: //! Basic Constructor HybridElasticPositronatomicReaction( const std::shared_ptr<const std::vector<double> >& incoming_energy_grid, const std::shared_ptr<const std::vector<double> >& cross_section, const size_t threshold_energy_index, const double cutoff_angle_cosine, const std::shared_ptr<const HybridElasticElectronScatteringDistribution>& hybrid_distribution ); //! Constructor HybridElasticPositronatomicReaction( const std::shared_ptr<const std::vector<double> >& incoming_energy_grid, const std::shared_ptr<const std::vector<double> >& cross_section, const size_t threshold_energy_index, const std::shared_ptr<const Utility::HashBasedGridSearcher<double>>& grid_searcher, const double cutoff_angle_cosine, const std::shared_ptr<const HybridElasticElectronScatteringDistribution>& hybrid_distribution ); //! Destructor ~HybridElasticPositronatomicReaction() { /* ... */ } //! Return the number of photons emitted from the rxn at the given energy unsigned getNumberOfEmittedPhotons( const double energy ) const override; //! Return the number of electrons emitted from the rxn at the given energy unsigned getNumberOfEmittedElectrons( const double energy ) const override; //! Return the number of positrons emitted from the rxn at the given energy unsigned getNumberOfEmittedPositrons( const double energy ) const override; //! Return the reaction type PositronatomicReactionType getReactionType() const override; //! Return the differential cross section double getDifferentialCrossSection( const double incoming_energy, const double scattering_angle_cosine ) const override; //! Simulate the reaction void react( PositronState& positron, ParticleBank& bank, Data::SubshellType& shell_of_interaction ) const override; private: // The hybrid elastic scattering distribution std::shared_ptr<const HybridElasticElectronScatteringDistribution> d_hybrid_distribution; }; } // end MonteCarlo namespace //---------------------------------------------------------------------------// // Template Includes //---------------------------------------------------------------------------// #include "MonteCarlo_HybridElasticPositronatomicReaction_def.hpp" //---------------------------------------------------------------------------// #endif // end MONTE_CARLO_HYBRID_ELASTIC_POSITRONATOMIC_REACTION_HPP //---------------------------------------------------------------------------// // end MonteCarlo_HybridElasticPositronatomicReaction.hpp //---------------------------------------------------------------------------//
39.391753
136
0.669458
bam241
c23c3c66cb8c588619199b2e24b66c3e97d9e21f
2,587
cc
C++
tests/search.cc
juliusikkala/MonkeroECS
145a0536ffa6f18f3389cce77de0522e579c850b
[ "MIT" ]
null
null
null
tests/search.cc
juliusikkala/MonkeroECS
145a0536ffa6f18f3389cce77de0522e579c850b
[ "MIT" ]
null
null
null
tests/search.cc
juliusikkala/MonkeroECS
145a0536ffa6f18f3389cce77de0522e579c850b
[ "MIT" ]
null
null
null
#include "test.hh" #include <unordered_map> #include <string> struct test_component { std::string name; }; size_t add_count = 0; size_t remove_count = 0; template<> class monkero::search_index<test_component> { public: entity find(const std::string& name) const { auto it = name_to_id.find(name); if(it == name_to_id.end()) return INVALID_ENTITY; return it->second; } void add_entity(entity id, const test_component& data) { name_to_id[data.name] = id; id_to_name[id] = data.name; add_count++; } void remove_entity(entity id, const test_component&) { auto it = id_to_name.find(id); name_to_id.erase(it->second); id_to_name.erase(it); remove_count++; } void update(ecs& e) { for(auto& pair: name_to_id) { pair.second = INVALID_ENTITY; } e([&](entity id, const test_component& data){ if(id_to_name[id] != data.name) id_to_name[id] = data.name; name_to_id[data.name] = id; }); } private: std::unordered_map<std::string, entity> name_to_id; std::unordered_map<entity, std::string> id_to_name; }; int main() { { ecs e; entity monkero = e.add(test_component{"Monkero"}); entity tankero = e.add(test_component{"Tankero"}); entity punkero = e.add(test_component{"Punkero"}); entity antero = e.add(test_component{"Antero"}); test(add_count == 4); entity id = e.find<test_component>("Punkero"); test(id == punkero); id = e.find<test_component>("Antero"); test(id == antero); id = e.find<test_component>("Monkero"); test(id == monkero); id = e.find<test_component>("Tankero"); test(id == tankero); e.get<test_component>(monkero)->name = "Bonito"; id = e.find<test_component>("Monkero"); test(id == monkero); e.update_search_index<test_component>(); id = e.find<test_component>("Monkero"); test(id == INVALID_ENTITY); id = e.find<test_component>("Bonito"); test(id == monkero); e.get<test_component>(monkero)->name = "Monkero"; e.update_search_indices(); id = e.find<test_component>("Monkero"); test(id == monkero); id = e.find<test_component>("Bonito"); test(id == INVALID_ENTITY); test(e.find_component<test_component>("Antero")->name == "Antero"); } test(remove_count == 4); return 0; }
25.116505
75
0.575184
juliusikkala
c24a6bd0971f0a1f1fd0ba4cb26416eeba127fff
497
cpp
C++
test/split_msg_macros_def.cpp
ggerganov/dynamix
7530d2d6a39a0824410f2535ab5fc95d3821488f
[ "MIT" ]
580
2016-06-26T20:44:17.000Z
2022-03-30T01:26:51.000Z
test/split_msg_macros_def.cpp
ggerganov/dynamix
7530d2d6a39a0824410f2535ab5fc95d3821488f
[ "MIT" ]
35
2016-06-28T11:15:49.000Z
2022-01-28T14:03:30.000Z
test/split_msg_macros_def.cpp
ggerganov/dynamix
7530d2d6a39a0824410f2535ab5fc95d3821488f
[ "MIT" ]
52
2016-06-26T19:49:24.000Z
2022-01-25T18:18:31.000Z
// DynaMix // Copyright (c) 2013-2019 Borislav Stanimirov, Zahary Karadjov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #define DYNAMIX_NO_MESSAGE_MACROS #include <dynamix/define_message_split.hpp> #include "split_msg_macros_messages.inl" DYNAMIX_DEFINE_MESSAGE(dummy); DYNAMIX_DEFINE_MESSAGE(get_self); DYNAMIX_DEFINE_MESSAGE(unused); DYNAMIX_DEFINE_MESSAGE(multi); DYNAMIX_DEFINE_MESSAGE(inherited);
29.235294
63
0.816901
ggerganov
c250e0ed4e8f4806f0a8e943c787c271d6c95dcd
367
cpp
C++
Questions Level-Wise/Medium/finding-the-users-active-minutes.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Medium/finding-the-users-active-minutes.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Medium/finding-the-users-active-minutes.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k) { unordered_map<int,unordered_set<int>> m; vector<int> x(k); for(auto e: logs) m[e[0]].insert(e[1]); for(auto e: m) if(e.second.size()<=k) x[e.second.size()-1]++; return x; } };
26.214286
76
0.506812
PrakharPipersania
c25181a94ee536dd8cae2a4e9fec05efead378c9
2,355
cpp
C++
PART-2/videoprocess.cpp
RaviSriTejaKuriseti/COP290-ASS1
4f6e3f8dd635ece39eb063ea7e5da402373d87ad
[ "MIT" ]
1
2021-05-07T18:55:26.000Z
2021-05-07T18:55:26.000Z
PART-2/videoprocess.cpp
RaviSriTejaKuriseti/COP290-ASS1
4f6e3f8dd635ece39eb063ea7e5da402373d87ad
[ "MIT" ]
null
null
null
PART-2/videoprocess.cpp
RaviSriTejaKuriseti/COP290-ASS1
4f6e3f8dd635ece39eb063ea7e5da402373d87ad
[ "MIT" ]
null
null
null
#include "auxcode.h" vector<Point2f>src_img; vector<Point2f>desti_img; vector<Point2f>rect; int main(int argc, char** argv) { desti_img.push_back(Point2f(472, 52)); desti_img.push_back(Point2f(472, 830)); desti_img.push_back(Point2f(800, 830)); desti_img.push_back(Point2f(800, 52)); src_img.push_back(Point2f(990, 223)); src_img.push_back(Point2f(302, 1071)); src_img.push_back(Point2f(1545, 1070)); src_img.push_back(Point2f(1275, 215)); rect.push_back(Point2f(465, 32)); rect.push_back(Point2f(805, 829)); VideoCapture cap("/mnt/c/Users/Lenovo/Desktop/trafficvideo.mp4"); //Read the file from location Mat emptyframe = imread("requiredimage.jpg"); // if not success, exit program if (cap.isOpened() == false) { cout << "Cannot open the video file" << endl; cin.get(); //wait for any key press return -1; } double fps = cap.get(CAP_PROP_FPS); cout << "Frames per seconds : " << fps << endl; double frames = cap.get(CAP_PROP_FRAME_COUNT); cout << "No of frames=" << frames << "\n"; String window_name = "Traffic Video"; //namedWindow(window_name, WINDOW_NORMAL); //create a window ofstream req; req.open("data.txt"); int count = 0; int ct1 = -1; Mat frame1 = emptyframe; while (ct1<frames) { ct1++; Mat frame2; bool bSuccess = cap.read(frame2); if(ct1%3==0){ count += 1; Mat d; if (count > 1) { double x1=queuedensity(frame2,emptyframe, src_img, desti_img, rect); double x2=dynamicdensity(frame2, frame1,src_img, desti_img, rect); req << count << " " << x1 << " " << x2<< " " << "\n"; cout<< 3*count << " " << x1 << " " << x2<< " " << "\n"; if (bSuccess == false) { cout << "Found the end of the video" << endl; break; } //Breaking the while loop at the end of the video } else { double x1=queuedensity(frame2,emptyframe, src_img, desti_img, rect); req << count << " " << x1<< " " << 0.0000 << " " << "\n"; cout<< "Frame Number"<< " " <<"Queue Density"<< " " <<"Dynamic Density"<< "\n"; cout<< 3<< " " << x1 << " " <<0.000<< " " << "\n"; } frame1 = frame2; if (waitKey(10) == 27) { cout << "Esc key is pressed by user. Stoppig the video" << endl; break; } } } req.close(); return 0; }
22.644231
83
0.582166
RaviSriTejaKuriseti
c251b3b1804fe34a97404c5034fce89b454959a5
6,849
cpp
C++
src/Song/SongsBookmarksDatabaseManager.cpp
tardypad/sailfishos-somafm
70d8522b6fedcf18e2c08c3464d164cd5a748e19
[ "MIT" ]
3
2016-07-05T13:27:46.000Z
2019-02-21T09:37:42.000Z
src/Song/SongsBookmarksDatabaseManager.cpp
tardypad/sailfishos-somafm
70d8522b6fedcf18e2c08c3464d164cd5a748e19
[ "MIT" ]
6
2019-03-07T17:20:25.000Z
2019-05-05T09:35:04.000Z
src/Song/SongsBookmarksDatabaseManager.cpp
tardypad/sailfishos-somafm
70d8522b6fedcf18e2c08c3464d164cd5a748e19
[ "MIT" ]
null
null
null
/** * Copyright (c) 2013-2019 Damien Tardy-Panis * * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. **/ #include "SongsBookmarksDatabaseManager.h" #include <QDebug> #include <QStringList> #include <QSqlQuery> #include <QVariant> #include <QDateTime> #include "Song.h" const QString SongsBookmarksDatabaseManager::_songsBookmarkTableName = "song_bookmark"; SongsBookmarksDatabaseManager* SongsBookmarksDatabaseManager::m_instance = NULL; SongsBookmarksDatabaseManager::SongsBookmarksDatabaseManager(QObject *parent) : XmlItemBookmarksDatabaseManager(parent) { init(); } SongsBookmarksDatabaseManager *SongsBookmarksDatabaseManager::instance() { if (!m_instance) { m_instance = new SongsBookmarksDatabaseManager(); } return m_instance; } bool SongsBookmarksDatabaseManager::insertBookmark(XmlItem *xmlItem) { QVariant title = xmlItem->data(Song::TitleRole); QVariant artist = xmlItem->data(Song::ArtistRole); QVariant album = xmlItem->data(Song::AlbumRole); QVariant channelId = xmlItem->data(Song::ChannelIdRole); QVariant channelName = xmlItem->data(Song::ChannelNameRole); QVariant channelImageUrl = xmlItem->data(Song::ChannelImageUrlRole); insertBookmarkPreparedQuery.bindValue(":title", title); insertBookmarkPreparedQuery.bindValue(":artist", artist); insertBookmarkPreparedQuery.bindValue(":album", album); insertBookmarkPreparedQuery.bindValue(":channel_id", channelId); insertBookmarkPreparedQuery.bindValue(":channel_name", channelName); insertBookmarkPreparedQuery.bindValue(":channel_image_url", channelImageUrl); insertBookmarkPreparedQuery.bindValue(":date", QDateTime::currentDateTime()); bool result = insertBookmarkPreparedQuery.exec(); int numRowsAffected = insertBookmarkPreparedQuery.numRowsAffected(); return result && (numRowsAffected == 1); } bool SongsBookmarksDatabaseManager::deleteBookmark(XmlItem *xmlItem) { QVariant title = xmlItem->data(Song::TitleRole); QVariant artist = xmlItem->data(Song::ArtistRole); deleteBookmarkPreparedQuery.bindValue(":title", title); deleteBookmarkPreparedQuery.bindValue(":artist", artist); bool result = deleteBookmarkPreparedQuery.exec(); int numRowsAffected = deleteBookmarkPreparedQuery.numRowsAffected(); return result && (numRowsAffected >= 1); } bool SongsBookmarksDatabaseManager::removeAllBookmarks() { QSqlQuery query("DELETE FROM " + _songsBookmarkTableName); return query.exec(); } bool SongsBookmarksDatabaseManager::removeAllChannelBookmarks(QString channelId) { QSqlQuery query("DELETE FROM " + _songsBookmarkTableName + " WHERE channel_id='" + channelId + "'"); return query.exec(); } QList<XmlItem *> SongsBookmarksDatabaseManager::retrieveBookmarks() { QList<XmlItem *> xmlItemsBookmarks; QSqlQuery query("SELECT title, artist, album, channel_id, channel_name, channel_image_url, date FROM " + _songsBookmarkTableName); QVariant title, artist, album, channelId, channelName, channelImageUrl, date; while (query.next()) { title = query.value(0); artist = query.value(1); album = query.value(2); channelId = query.value(3); channelName = query.value(4); channelImageUrl = query.value(5); date = query.value(6); Song* song = new Song(this); song->setData(title, Song::TitleRole); song->setData(artist, Song::ArtistRole); song->setData(album, Song::AlbumRole); song->setData(channelId, Song::ChannelIdRole); song->setData(channelName, Song::ChannelNameRole); song->setData(channelImageUrl, Song::ChannelImageUrlRole); song->setData(date, Song::BookmarkDateRole); xmlItemsBookmarks.append(song); } return xmlItemsBookmarks; } QList<QVariant> SongsBookmarksDatabaseManager::channelIds() { QList<QVariant> data; QSqlQuery query("SELECT DISTINCT channel_id FROM " + _songsBookmarkTableName); QVariant channelId; while (query.next()) { channelId = query.value(0); data.append(channelId); } return data; } QMap<QString, QVariant> SongsBookmarksDatabaseManager::channelData(QString channelId) { QMap<QString, QVariant> data; QSqlQuery query("SELECT channel_name, channel_image_url FROM " + _songsBookmarkTableName + " WHERE channel_id='" + channelId + "' LIMIT 1"); QVariant channelName, channelImageUrl; while (query.next()) { channelName = query.value(0); channelImageUrl = query.value(1); data.insert("name", channelName); data.insert("image_url", channelImageUrl); } return data; } int SongsBookmarksDatabaseManager::channelCount(QString channelId) { QSqlQuery query("SELECT COUNT(*) FROM " + _songsBookmarkTableName + " WHERE channel_id='" + channelId + "'"); query.first(); return query.value(0).toInt(); } void SongsBookmarksDatabaseManager::checkStructure() { if (!db.isOpen()) return; if (!db.tables().contains(_songsBookmarkTableName)) { createStructure(); } } void SongsBookmarksDatabaseManager::prepareQueries() { insertBookmarkPreparedQuery.prepare( "INSERT INTO " + _songsBookmarkTableName + " (title, artist, album, channel_id, channel_name, channel_image_url, date) \n" "VALUES (:title, :artist, :album, :channel_id, :channel_name, :channel_image_url, :date)" ); deleteBookmarkPreparedQuery.prepare( "DELETE FROM " + _songsBookmarkTableName + " \n" "WHERE title=:title AND artist=:artist" ); } bool SongsBookmarksDatabaseManager::createStructure() { if (!db.isOpen()) return false; QSqlQuery query("CREATE TABLE " + _songsBookmarkTableName + " (\n" "id INTEGER PRIMARY KEY, -- bookmark id \n" "title VARCHAR(50) NOT NULL, -- song title \n" "artist VARCHAR(50) NOT NULL, -- song artist \n" "album VARCHAR(50) DEFAULT NULL, -- song album \n" "channel_id VARCHAR(50) NOT NULL, -- song channel id \n" "channel_name VARCHAR(50) DEFAULT NULL, -- song channel name \n" "channel_image_url VARCHAR(80) DEFAULT NULL, -- song channel image url \n" "date DATETIME DEFAUT CURRENT_TIMESTAMP, -- date of bookmark creation \n" "UNIQUE (title, artist) \n" ")", db); return query.exec(); }
34.943878
144
0.662724
tardypad
c251df6fcf33ace442fc603528e94f6c50f83298
1,424
cpp
C++
Alchemy/Classes/Object/Alchemy/Plant.cpp
kkh029/Alchemy
ed3d96452508b6cf5680392028bef409dd8d78f1
[ "Apache-2.0" ]
null
null
null
Alchemy/Classes/Object/Alchemy/Plant.cpp
kkh029/Alchemy
ed3d96452508b6cf5680392028bef409dd8d78f1
[ "Apache-2.0" ]
1
2017-02-10T03:54:29.000Z
2017-02-10T03:54:29.000Z
Alchemy/Classes/Object/Alchemy/Plant.cpp
kkh029/Alchemy
ed3d96452508b6cf5680392028bef409dd8d78f1
[ "Apache-2.0" ]
null
null
null
// // Plant.cpp // Alchemy // // Created by Kyounghwan on 2014. 3. 1.. // 1302 Plant 3 30 - - - Tower - 재료. 1104 1201 // #include "Plant.h" #include "WindTalisman.h" #include "WaterTalisman.h" #include "EarthTalisman.h" #include "FireTalisman.h" /* ALCHEMY PARAMETER */ #define TWEEN_EASING_MAX_INDEX 10000 #define DEFAULT_INDEX 0 #define LOOP -1 #define HP 30 Plant::Plant(unsigned char index) :Alchemy(Alchemy::resource_table[index]) { m_hp = HP; } Plant::~Plant() {} Alchemy* Plant::create(PEObject* obj) { Plant* pPlant = new Plant(obj->PE_getResourceIndex()); return pPlant; } void Plant::PE_initAnimation() { ArmatureAnimation* ani; init(m_name.c_str()); setAnchorPoint(Vec2(0.5f, 0.0f)); ani = getAnimation(); ani->playWithIndex(DEFAULT_INDEX, -1, -1); } bool Plant::PE_update(unsigned int flag) { if( ((flag>>1) & 0x1) != cure) { if(!cure) { cure = true; PE_cure(true); } else { cure = false; } log("[Cure] %s", (cure)?"ON":"OFF"); } if( (flag>>3 & 0x1) != hp_up) { if(!hp_up) { hp_up = true; m_hp += HP/5; m_max_hp += HP/5; } else { hp_up = false; m_max_hp -= HP/5; m_hp = (m_hp>m_max_hp)?m_max_hp:m_hp; } log("[Max HP] %d", m_max_hp); } if(cure) { PE_cure(false); } if(!m_alive) removeFromParent(); return m_alive; }
15.648352
56
0.57514
kkh029
c25658fdad6cb914a10fe8cb43bbd24cc6dec870
16,142
cpp
C++
libs/base/src/poses/CPose3DQuatPDFGaussian_unittest.cpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
libs/base/src/poses/CPose3DQuatPDFGaussian_unittest.cpp
shivangag/mrpt
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
null
null
null
libs/base/src/poses/CPose3DQuatPDFGaussian_unittest.cpp
shivangag/mrpt
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
1
2017-06-30T18:23:45.000Z
2017-06-30T18:23:45.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include <mrpt/poses/CPose3DPDFGaussian.h> #include <mrpt/poses/CPose3DQuatPDFGaussian.h> #include <mrpt/poses/CPose3D.h> #include <mrpt/random.h> #include <mrpt/math/transform_gaussian.h> #include <mrpt/math/jacobians.h> #include <gtest/gtest.h> using namespace mrpt; using namespace mrpt::poses; using namespace mrpt::utils; using namespace mrpt::math; using namespace std; class Pose3DQuatPDFGaussTests : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } static CPose3DQuatPDFGaussian generateRandomPoseQuat3DPDF(double x,double y, double z, double yaw, double pitch, double roll, double std_scale) { return CPose3DQuatPDFGaussian(generateRandomPose3DPDF(x,y,z,yaw,pitch,roll,std_scale)); } static CPose3DPDFGaussian generateRandomPose3DPDF(double x,double y, double z, double yaw, double pitch, double roll, double std_scale) { CMatrixDouble61 r; mrpt::random::randomGenerator.drawGaussian1DMatrix(r, 0,std_scale); CMatrixDouble66 cov; cov.multiply_AAt(r); // random semi-definite positive matrix: for (int i=0;i<6;i++) cov(i,i)+=1e-7; CPose3DPDFGaussian p6pdf( CPose3D(x,y,z,yaw,pitch,roll), cov ); return p6pdf; } void test_toFromYPRGauss(double yaw, double pitch,double roll) { // Random pose: CPose3DPDFGaussian p1ypr = generateRandomPose3DPDF(1.0,2.0,3.0, yaw,pitch,roll, 0.1); CPose3DQuatPDFGaussian p1quat = CPose3DQuatPDFGaussian(p1ypr); // Convert back to a 6x6 representation: CPose3DPDFGaussian p2ypr = CPose3DPDFGaussian(p1quat); EXPECT_NEAR(0,(p2ypr.cov - p1ypr.cov).array().abs().mean(), 1e-2) << "p1ypr: " << endl << p1ypr << endl << "p1quat : " << endl << p1quat << endl << "p2ypr : " << endl << p2ypr << endl; } static void func_compose(const CArrayDouble<2*7> &x, const double &dummy, CArrayDouble<7> &Y) { MRPT_UNUSED_PARAM(dummy); const CPose3DQuat p1(x[0],x[1],x[2],CQuaternionDouble(x[3],x[4],x[5],x[6])); const CPose3DQuat p2(x[7+0],x[7+1],x[7+2],CQuaternionDouble(x[7+3],x[7+4],x[7+5],x[7+6])); const CPose3DQuat p = p1+p2; for (int i=0;i<7;i++) Y[i]=p[i]; } static void func_inv_compose(const CArrayDouble<2*7> &x, const double &dummy, CArrayDouble<7> &Y) { MRPT_UNUSED_PARAM(dummy); const CPose3DQuat p1(x[0],x[1],x[2],CQuaternionDouble(x[3],x[4],x[5],x[6])); const CPose3DQuat p2(x[7+0],x[7+1],x[7+2],CQuaternionDouble(x[7+3],x[7+4],x[7+5],x[7+6])); const CPose3DQuat p = p1-p2; for (int i=0;i<7;i++) Y[i]=p[i]; } void testPoseComposition( double x,double y, double z, double yaw, double pitch, double roll, double std_scale, double x2,double y2, double z2, double yaw2, double pitch2, double roll2, double std_scale2 ) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); CPose3DQuatPDFGaussian p7pdf2 = generateRandomPoseQuat3DPDF(x2,y2,z2,yaw2,pitch2,roll2, std_scale2); CPose3DQuatPDFGaussian p7_comp = p7pdf1 + p7pdf2; // Numeric approximation: CArrayDouble<7> y_mean; CMatrixFixedNumeric<double,7,7> y_cov; { CArrayDouble<2*7> x_mean; for (int i=0;i<7;i++) x_mean[i]=p7pdf1.mean[i]; for (int i=0;i<7;i++) x_mean[7+i]=p7pdf2.mean[i]; CMatrixFixedNumeric<double,14,14> x_cov; x_cov.insertMatrix(0,0, p7pdf1.cov); x_cov.insertMatrix(7,7, p7pdf2.cov); double DUMMY=0; CArrayDouble<2*7> x_incrs; x_incrs.assign(1e-6); transform_gaussian_linear(x_mean,x_cov,func_compose,DUMMY, y_mean,y_cov, x_incrs ); } // Compare: EXPECT_NEAR(0, (y_cov-p7_comp.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "p2 mean: " << p7pdf2.mean << endl << "Numeric approximation of covariance: " << endl << y_cov << endl << "Returned covariance: " << endl << p7_comp.cov << endl; } static void func_inverse(const CArrayDouble<7> &x, const double &dummy, CArrayDouble<7> &Y) { MRPT_UNUSED_PARAM(dummy); const CPose3DQuat p1(x[0],x[1],x[2],CQuaternionDouble(x[3],x[4],x[5],x[6])); const CPose3DQuat p1_inv ( -p1 ); for (int i=0;i<7;i++) Y[i]=p1_inv[i]; } void testCompositionJacobian( double x,double y, double z, double yaw, double pitch, double roll, double x2,double y2, double z2, double yaw2, double pitch2, double roll2) { const CPose3DQuat q1( CPose3D(x,y,z,yaw,pitch,roll) ); const CPose3DQuat q2( CPose3D(x2,y2,z2,yaw2,pitch2,roll2) ); // Theoretical Jacobians: CMatrixDouble77 df_dx(UNINITIALIZED_MATRIX), df_du(UNINITIALIZED_MATRIX); CPose3DQuatPDF::jacobiansPoseComposition( q1, // x q2, // u df_dx, df_du ); // Numerical approximation: CMatrixDouble77 num_df_dx(UNINITIALIZED_MATRIX), num_df_du(UNINITIALIZED_MATRIX); { CArrayDouble<2*7> x_mean; for (int i=0;i<7;i++) x_mean[i]=q1[i]; for (int i=0;i<7;i++) x_mean[7+i]=q2[i]; double DUMMY=0; CArrayDouble<2*7> x_incrs; x_incrs.assign(1e-7); CMatrixDouble numJacobs; mrpt::math::jacobians::jacob_numeric_estimate(x_mean,func_compose,x_incrs, DUMMY, numJacobs ); numJacobs.extractMatrix(0,0, num_df_dx); numJacobs.extractMatrix(0,7, num_df_du); } // Compare: EXPECT_NEAR(0, (df_dx-num_df_dx).array().abs().sum(), 3e-3 ) << "q1: " << q1 << endl << "q2: " << q2 << endl << "Numeric approximation of df_dx: " << endl << num_df_dx << endl << "Implemented method: " << endl << df_dx << endl << "Error: " << endl << df_dx-num_df_dx << endl; EXPECT_NEAR(0, (df_du-num_df_du).array().abs().sum(), 3e-3 ) << "q1: " << q1 << endl << "q2: " << q2 << endl << "Numeric approximation of df_du: " << endl << num_df_du << endl << "Implemented method: " << endl << df_du << endl << "Error: " << endl << df_du-num_df_du << endl; } void testInverse(double x,double y, double z, double yaw, double pitch, double roll, double std_scale) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); CPose3DQuatPDFGaussian p7_inv = -p7pdf1; // Numeric approximation: CArrayDouble<7> y_mean; CMatrixFixedNumeric<double,7,7> y_cov; { CArrayDouble<7> x_mean; for (int i=0;i<7;i++) x_mean[i]=p7pdf1.mean[i]; CMatrixFixedNumeric<double,7,7> x_cov; x_cov.insertMatrix(0,0, p7pdf1.cov); double DUMMY=0; CArrayDouble<7> x_incrs; x_incrs.assign(1e-6); transform_gaussian_linear(x_mean,x_cov,func_inverse,DUMMY, y_mean,y_cov, x_incrs ); } // Compare: EXPECT_NEAR(0, (y_cov-p7_inv.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "inv mean: " << p7_inv.mean << endl << "Numeric approximation of covariance: " << endl << y_cov << endl << "Returned covariance: " << endl << p7_inv.cov << endl << "Error: " << endl << y_cov-p7_inv.cov << endl; } void testPoseInverseComposition( double x,double y, double z, double yaw, double pitch, double roll, double std_scale, double x2,double y2, double z2, double yaw2, double pitch2, double roll2, double std_scale2 ) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); CPose3DQuatPDFGaussian p7pdf2 = generateRandomPoseQuat3DPDF(x2,y2,z2,yaw2,pitch2,roll2, std_scale2); CPose3DQuatPDFGaussian p7_comp = p7pdf1 - p7pdf2; // Numeric approximation: CArrayDouble<7> y_mean; CMatrixFixedNumeric<double,7,7> y_cov; { CArrayDouble<2*7> x_mean; for (int i=0;i<7;i++) x_mean[i]=p7pdf1.mean[i]; for (int i=0;i<7;i++) x_mean[7+i]=p7pdf2.mean[i]; CMatrixFixedNumeric<double,14,14> x_cov; x_cov.insertMatrix(0,0, p7pdf1.cov); x_cov.insertMatrix(7,7, p7pdf2.cov); double DUMMY=0; CArrayDouble<2*7> x_incrs; x_incrs.assign(1e-6); transform_gaussian_linear(x_mean,x_cov,func_inv_compose,DUMMY, y_mean,y_cov, x_incrs ); } // Compare: EXPECT_NEAR(0, (y_cov-p7_comp.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "p2 mean: " << p7pdf2.mean << endl << "Numeric approximation of covariance: " << endl << y_cov << endl << "Returned covariance: " << endl << p7_comp.cov << endl; } void testChangeCoordsRef( double x,double y, double z, double yaw, double pitch, double roll, double std_scale, double x2,double y2, double z2, double yaw2, double pitch2, double roll2 ) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); const CPose3DQuat new_base = CPose3DQuat( CPose3D(x2,y2,z2,yaw2,pitch2,roll2) ); const CPose3DQuatPDFGaussian new_base_pdf( new_base, CMatrixDouble77() ); // COV = Zeros const CPose3DQuatPDFGaussian p7_new_base_pdf = new_base_pdf + p7pdf1; p7pdf1.changeCoordinatesReference(new_base); // Compare: EXPECT_NEAR(0, (p7_new_base_pdf.cov - p7pdf1.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "new_base: " << new_base << endl; EXPECT_NEAR(0, (p7_new_base_pdf.mean.getAsVectorVal() - p7pdf1.mean.getAsVectorVal() ).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "new_base: " << new_base << endl; } }; TEST_F(Pose3DQuatPDFGaussTests,ToYPRGaussPDFAndBack) { test_toFromYPRGauss(DEG2RAD(-30),DEG2RAD(10),DEG2RAD(60)); test_toFromYPRGauss(DEG2RAD(30),DEG2RAD(88),DEG2RAD(0)); test_toFromYPRGauss(DEG2RAD(30),DEG2RAD(89.5),DEG2RAD(0)); // The formulas break at pitch=90, but this we cannot avoid... } TEST_F(Pose3DQuatPDFGaussTests,CompositionJacobian) { testCompositionJacobian(0,0,0,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,2,3,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,-2,3,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,2,-3,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(-80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(-70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(-50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(-30) ); } TEST_F(Pose3DQuatPDFGaussTests,Inverse) { testInverse(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(0,0,0,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(0,0,0,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1 ); testInverse(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.2 ); testInverse(1,2,3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); } TEST_F(Pose3DQuatPDFGaussTests,Composition) { testPoseComposition(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.1, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.2, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.2 ); testPoseComposition(1,2,3,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1 ); } TEST_F(Pose3DQuatPDFGaussTests,InverseComposition) { testPoseInverseComposition(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.1, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.2, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.2 ); testPoseInverseComposition(1,2,3,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1 ); } TEST_F(Pose3DQuatPDFGaussTests,ChangeCoordsRef) { testChangeCoordsRef(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testChangeCoordsRef(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testChangeCoordsRef(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.1, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testChangeCoordsRef(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.2, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); }
43.983651
145
0.672655
feroze
c2570b1ac89a18edf8ef13937bdfad185456de24
184,391
cpp
C++
GPUPerfStudio/Server/Common/Linux/jpglib/jfdctint.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
1
2017-03-25T02:09:15.000Z
2017-03-25T02:09:15.000Z
GPUPerfStudio/Server/Common/Linux/jpglib/jfdctint.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
null
null
null
GPUPerfStudio/Server/Common/Linux/jpglib/jfdctint.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
3
2017-03-15T03:35:13.000Z
2022-02-23T06:29:02.000Z
/* * jfdctint.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modification developed 2003-2009 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a slow-but-accurate integer implementation of the * forward DCT (Discrete Cosine Transform). * * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT * on each column. Direct algorithms are also available, but they are * much more complex and seem not to be any faster when reduced to code. * * This implementation is based on an algorithm described in * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. * The primary algorithm described there uses 11 multiplies and 29 adds. * We use their alternate method with 12 multiplies and 32 adds. * The advantage of this method is that no data path contains more than one * multiplication; this allows a very simple and accurate implementation in * scaled fixed-point arithmetic, with a minimal number of shifts. * * We also provide FDCT routines with various input sample block sizes for * direct resolution reduction or enlargement and for direct resolving the * common 2x1 and 1x2 subsampling cases without additional resampling: NxN * (N=1...16), 2NxN, and Nx2N (N=1...8) pixels for one 8x8 output DCT block. * * For N<8 we fill the remaining block coefficients with zero. * For N>8 we apply a partial N-point FDCT on the input samples, computing * just the lower 8 frequency coefficients and discarding the rest. * * We must scale the output coefficients of the N-point FDCT appropriately * to the standard 8-point FDCT level by 8/N per 1-D pass. This scaling * is folded into the constant multipliers (pass 2) and/or final/initial * shifting. * * CAUTION: We rely on the FIX() macro except for the N=1,2,4,8 cases * since there would be too many additional constants to pre-calculate. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ namespace GPS { #ifdef DCT_ISLOW_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCT blocks. /* deliberate syntax err */ #endif /* * The poop on this scaling stuff is as follows: * * Each 1-D DCT step produces outputs which are a factor of sqrt(N) * larger than the true DCT outputs. The final outputs are therefore * a factor of N larger than desired; since N=8 this can be cured by * a simple right shift at the end of the algorithm. The advantage of * this arrangement is that we save two multiplications per 1-D DCT, * because the y0 and y4 outputs need not be divided by sqrt(N). * In the IJG code, this factor of 8 is removed by the quantization step * (in jcdctmgr.c), NOT in this module. * * We have to do addition and subtraction of the integer inputs, which * is no problem, and multiplication by fractional constants, which is * a problem to do in integer arithmetic. We multiply all the constants * by CONST_SCALE and convert them to integer constants (thus retaining * CONST_BITS bits of precision in the constants). After doing a * multiplication we have to divide the product by CONST_SCALE, with proper * rounding, to produce the correct output. This division can be done * cheaply as a right shift of CONST_BITS bits. We postpone shifting * as long as possible so that partial sums can be added together with * full fractional precision. * * The outputs of the first pass are scaled up by PASS1_BITS bits so that * they are represented to better-than-integral precision. These outputs * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word * with the recommended scaling. (For 12-bit sample data, the intermediate * array is INT32 anyway.) * * To avoid overflow of the 32-bit intermediate results in pass 2, we must * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis * shows that the values given below are the most effective. */ #if BITS_IN_JSAMPLE == 8 #define CONST_BITS 13 #define PASS1_BITS 2 #else #define CONST_BITS 13 #define PASS1_BITS 1 /* lose a little precision to avoid overflow */ #endif /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 13 #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */ #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */ #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */ #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */ #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */ #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */ #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */ #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */ #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */ #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */ #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */ #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */ #else #define FIX_0_298631336 FIX(0.298631336) #define FIX_0_390180644 FIX(0.390180644) #define FIX_0_541196100 FIX(0.541196100) #define FIX_0_765366865 FIX(0.765366865) #define FIX_0_899976223 FIX(0.899976223) #define FIX_1_175875602 FIX(1.175875602) #define FIX_1_501321110 FIX(1.501321110) #define FIX_1_847759065 FIX(1.847759065) #define FIX_1_961570560 FIX(1.961570560) #define FIX_2_053119869 FIX(2.053119869) #define FIX_2_562915447 FIX(2.562915447) #define FIX_3_072711026 FIX(3.072711026) #endif /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. * For 8-bit samples with the recommended scaling, all the variable * and constant values involved are no more than 16 bits wide, so a * 16x16->32 bit multiply can be used instead of a full 32x32 multiply. * For 12-bit samples, a full 32-bit multiplication will be needed. */ #if BITS_IN_JSAMPLE == 8 #define MULTIPLY(var,const) MULTIPLY16C16(var,const) #else #define MULTIPLY(var,const) ((var) * (const)) #endif /* * Perform the forward DCT on one block of samples. */ GLOBAL(void) jpeg_fdct_islow(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM)((tmp10 - tmp11) << PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 1); dataptr[2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS - PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 1); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4]; /* Add fudge factor here for final descale. */ tmp10 = tmp0 + tmp3 + (ONE << (PASS1_BITS - 1)); tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp10 + tmp11, PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) RIGHT_SHIFT(tmp10 - tmp11, PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS + PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } #ifdef DCT_SCALING_SUPPORTED /* * Perform the forward DCT on a 7x7 sample block. */ GLOBAL(void) jpeg_fdct_7x7(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12; INT32 z1, z2, z3; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* cK represents sqrt(2) * cos(K*pi/14). */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[6]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[5]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[4]); tmp3 = GETJSAMPLE(elemptr[3]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[6]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[5]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[4]); z1 = tmp0 + tmp2; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((z1 + tmp1 + tmp3 - 7 * CENTERJSAMPLE) << PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.353553391)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(0.920609002)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.314692123)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS - PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(0.881747734)); /* c4 */ dataptr[4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.707106781)), /* c2+c6-c4 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS - PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.613604268)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(1.870828693)); /* c3+c1-c5 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/7)**2 = 64/49, which we fold * into the constant multipliers: * cK now represents sqrt(2) * cos(K*pi/14) * 64/49. */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 6]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 5]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 4]; tmp3 = dataptr[DCTSIZE * 3]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 6]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 5]; tmp12 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 4]; z1 = tmp0 + tmp2; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + tmp1 + tmp3, FIX(1.306122449)), /* 64/49 */ CONST_BITS + PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.461784020)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(1.202428084)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.411026446)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS + PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(1.151670509)); /* c4 */ dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.923568041)), /* c2+c6-c4 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS + PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.221765677)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.222383464)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.800824523)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.801442310)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(2.443531355)); /* c3+c1-c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x6 sample block. */ GLOBAL(void) jpeg_fdct_6x6(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS - PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS - PASS1_BITS); dataptr[1] = (DCTELEM)(tmp10 + ((tmp0 + tmp1) << PASS1_BITS)); dataptr[3] = (DCTELEM)((tmp0 - tmp1 - tmp2) << PASS1_BITS); dataptr[5] = (DCTELEM)(tmp10 + ((tmp2 - tmp1) << PASS1_BITS)); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)**2 = 16/9, which we fold * into the constant multipliers: * cK now represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 5]; tmp11 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 5x5 sample block. */ GLOBAL(void) jpeg_fdct_5x5(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/10). */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[3]); tmp2 = GETJSAMPLE(elemptr[2]); tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp2 - 5 * CENTERJSAMPLE) << (PASS1_BITS + 1)); tmp11 = MULTIPLY(tmp11, FIX(0.790569415)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.353553391)); /* (c2-c4)/2 */ dataptr[2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS - PASS1_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS - PASS1_BITS - 1); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(0.831253876)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.513743148)), /* c1-c3 */ CONST_BITS - PASS1_BITS - 1); dataptr[3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.176250899)), /* c1+c3 */ CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/5)**2 = 64/25, which we partially * fold into the constant multipliers (other part was done in pass 1): * cK now represents sqrt(2) * cos(K*pi/10) * 32/25. */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 3]; tmp2 = dataptr[DCTSIZE * 2]; tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(1.011928851)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.452548340)); /* (c2-c4)/2 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(1.064004961)); /* c3 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.657591230)), /* c1-c3 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.785601151)), /* c1+c3 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x4 sample block. */ GLOBAL(void) jpeg_fdct_4x4(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by (8/4)**2 = 2**2, which we add here. */ /* cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS + 2)); dataptr[2] = (DCTELEM)((tmp0 - tmp1) << (PASS1_BITS + 2)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - PASS1_BITS - 3); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS - PASS1_BITS - 2); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS - PASS1_BITS - 2); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 3] + (ONE << (PASS1_BITS - 1)); tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 2]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 3]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 3x3 sample block. */ GLOBAL(void) jpeg_fdct_3x3(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2**2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/6). */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[2]); tmp1 = GETJSAMPLE(elemptr[1]); tmp2 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 3 * CENTERJSAMPLE) << (PASS1_BITS + 2)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(0.707106781)), /* c2 */ CONST_BITS - PASS1_BITS - 2); /* Odd part */ dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(1.224744871)), /* c1 */ CONST_BITS - PASS1_BITS - 2); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/3)**2 = 64/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * cK now represents sqrt(2) * cos(K*pi/6) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 2]; tmp1 = dataptr[DCTSIZE * 1]; tmp2 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(1.257078722)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(2.177324216)), /* c1 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x2 sample block. */ GLOBAL(void) jpeg_fdct_2x2(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; JSAMPROW elemptr; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* Row 0 */ elemptr = sample_data[0] + start_col; tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[1]); tmp1 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[1]); /* Row 1 */ elemptr = sample_data[1] + start_col; tmp2 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[1]); tmp3 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[1]); /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/2)**2 = 2**4. */ /* Column 0 */ /* Apply unsigned->signed conversion */ data[DCTSIZE * 0] = (DCTELEM)((tmp0 + tmp2 - 4 * CENTERJSAMPLE) << 4); data[DCTSIZE * 1] = (DCTELEM)((tmp0 - tmp2) << 4); /* Column 1 */ data[DCTSIZE * 0 + 1] = (DCTELEM)((tmp1 + tmp3) << 4); data[DCTSIZE * 1 + 1] = (DCTELEM)((tmp1 - tmp3) << 4); } /* * Perform the forward DCT on a 1x1 sample block. */ GLOBAL(void) jpeg_fdct_1x1(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* We leave the result scaled up by an overall factor of 8. */ /* We must also scale the output by (8/1)**2 = 2**6. */ /* Apply unsigned->signed conversion */ data[0] = (DCTELEM) ((GETJSAMPLE(sample_data[0][start_col]) - CENTERJSAMPLE) << 6); } /* * Perform the forward DCT on a 9x9 sample block. */ GLOBAL(void) jpeg_fdct_9x9(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1, z2; DCTELEM workspace[8]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* we scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/18). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[8]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[7]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[6]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[5]); tmp4 = GETJSAMPLE(elemptr[4]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[8]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[7]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[6]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[5]); z1 = tmp0 + tmp2 + tmp3; z2 = tmp1 + tmp4; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((z1 + z2 - 9 * CENTERJSAMPLE) << 1); dataptr[6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z2 - z2, FIX(0.707106781)), /* c6 */ CONST_BITS - 1); z1 = MULTIPLY(tmp0 - tmp2, FIX(1.328926049)); /* c2 */ z2 = MULTIPLY(tmp1 - tmp4 - tmp4, FIX(0.707106781)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp2 - tmp3, FIX(1.083350441)) /* c4 */ + z1 + z2, CONST_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp3 - tmp0, FIX(0.245575608)) /* c8 */ + z1 - z2, CONST_BITS - 1); /* Odd part */ dataptr[3] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12 - tmp13, FIX(1.224744871)), /* c3 */ CONST_BITS - 1); tmp11 = MULTIPLY(tmp11, FIX(1.224744871)); /* c3 */ tmp0 = MULTIPLY(tmp10 + tmp12, FIX(0.909038955)); /* c5 */ tmp1 = MULTIPLY(tmp10 + tmp13, FIX(0.483689525)); /* c7 */ dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp0 + tmp1, CONST_BITS - 1); tmp2 = MULTIPLY(tmp12 - tmp13, FIX(1.392728481)); /* c1 */ dataptr[5] = (DCTELEM) DESCALE(tmp0 - tmp11 - tmp2, CONST_BITS - 1); dataptr[7] = (DCTELEM) DESCALE(tmp1 - tmp11 + tmp2, CONST_BITS - 1); ctr++; if (ctr != DCTSIZE) { if (ctr == 9) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/9)**2 = 64/81, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/18) * 128/81. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 0]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 7]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 6]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 5]; tmp4 = dataptr[DCTSIZE * 4]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 0]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 7]; tmp12 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 6]; tmp13 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 5]; z1 = tmp0 + tmp2 + tmp3; z2 = tmp1 + tmp4; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + z2, FIX(1.580246914)), /* 128/81 */ CONST_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z2 - z2, FIX(1.117403309)), /* c6 */ CONST_BITS + 2); z1 = MULTIPLY(tmp0 - tmp2, FIX(2.100031287)); /* c2 */ z2 = MULTIPLY(tmp1 - tmp4 - tmp4, FIX(1.117403309)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp2 - tmp3, FIX(1.711961190)) /* c4 */ + z1 + z2, CONST_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp3 - tmp0, FIX(0.388070096)) /* c8 */ + z1 - z2, CONST_BITS + 2); /* Odd part */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12 - tmp13, FIX(1.935399303)), /* c3 */ CONST_BITS + 2); tmp11 = MULTIPLY(tmp11, FIX(1.935399303)); /* c3 */ tmp0 = MULTIPLY(tmp10 + tmp12, FIX(1.436506004)); /* c5 */ tmp1 = MULTIPLY(tmp10 + tmp13, FIX(0.764348879)); /* c7 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp11 + tmp0 + tmp1, CONST_BITS + 2); tmp2 = MULTIPLY(tmp12 - tmp13, FIX(2.200854883)); /* c1 */ dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp0 - tmp11 - tmp2, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp1 - tmp11 + tmp2, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 10x10 sample block. */ GLOBAL(void) jpeg_fdct_10x10(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM workspace[8 * 2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* we scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/20). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[8]); tmp12 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[5]); tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[8]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[5]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 10 * CENTERJSAMPLE) << 1); tmp12 += tmp12; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.144122806)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.437016024)), /* c8 */ CONST_BITS - 1); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(0.831253876)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.513743148)), /* c2-c6 */ CONST_BITS - 1); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.176250899)), /* c2+c6 */ CONST_BITS - 1); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[5] = (DCTELEM)((tmp10 - tmp11 - tmp2) << 1); tmp2 <<= CONST_BITS; dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.396802247)) + /* c1 */ MULTIPLY(tmp1, FIX(1.260073511)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.642039522)) + /* c7 */ MULTIPLY(tmp4, FIX(0.221231742)), /* c9 */ CONST_BITS - 1); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(0.951056516)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.587785252)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.309016994)) + /* (c3-c7)/2 */ (tmp11 << (CONST_BITS - 1)) - tmp2; dataptr[3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS - 1); dataptr[7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS - 1); ctr++; if (ctr != DCTSIZE) { if (ctr == 10) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/10)**2 = 16/25, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/20) * 32/25. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 0]; tmp12 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 5]; tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 0]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 5]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(1.28)), /* 32/25 */ CONST_BITS + 2); tmp12 += tmp12; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.464477191)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.559380511)), /* c8 */ CONST_BITS + 2); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(1.064004961)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.657591230)), /* c2-c6 */ CONST_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.785601151)), /* c2+c6 */ CONST_BITS + 2); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + 2); tmp2 = MULTIPLY(tmp2, FIX(1.28)); /* 32/25 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.787906876)) + /* c1 */ MULTIPLY(tmp1, FIX(1.612894094)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.821810588)) + /* c7 */ MULTIPLY(tmp4, FIX(0.283176630)), /* c9 */ CONST_BITS + 2); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(1.217352341)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.752365123)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.395541753)) + /* (c3-c7)/2 */ MULTIPLY(tmp11, FIX(0.64)) - tmp2; /* 16/25 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on an 11x11 sample block. */ GLOBAL(void) jpeg_fdct_11x11(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; INT32 z1, z2, z3; DCTELEM workspace[8 * 3]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* we scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/22). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[10]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[9]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[8]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[7]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[6]); tmp5 = GETJSAMPLE(elemptr[5]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[10]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[9]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[8]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[7]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 - 11 * CENTERJSAMPLE) << 1); tmp5 += tmp5; tmp0 -= tmp5; tmp1 -= tmp5; tmp2 -= tmp5; tmp3 -= tmp5; tmp4 -= tmp5; z1 = MULTIPLY(tmp0 + tmp3, FIX(1.356927976)) + /* c2 */ MULTIPLY(tmp2 + tmp4, FIX(0.201263574)); /* c10 */ z2 = MULTIPLY(tmp1 - tmp3, FIX(0.926112931)); /* c6 */ z3 = MULTIPLY(tmp0 - tmp1, FIX(1.189712156)); /* c4 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 - MULTIPLY(tmp3, FIX(1.018300590)) /* c2+c8-c6 */ - MULTIPLY(tmp4, FIX(1.390975730)), /* c4+c10 */ CONST_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(z2 + z3 + MULTIPLY(tmp1, FIX(0.062335650)) /* c4-c6-c10 */ - MULTIPLY(tmp2, FIX(1.356927976)) /* c2 */ + MULTIPLY(tmp4, FIX(0.587485545)), /* c8 */ CONST_BITS - 1); dataptr[6] = (DCTELEM) DESCALE(z1 + z3 - MULTIPLY(tmp0, FIX(1.620527200)) /* c2+c4-c6 */ - MULTIPLY(tmp2, FIX(0.788749120)), /* c8+c10 */ CONST_BITS - 1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.286413905)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.068791298)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.764581576)); /* c7 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.719967871)) /* c7+c5+c3-c1 */ + MULTIPLY(tmp14, FIX(0.398430003)); /* c9 */ tmp4 = MULTIPLY(tmp11 + tmp12, - FIX(0.764581576)); /* -c7 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.399818907)); /* -c1 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(1.276416582)) /* c9+c7+c1-c3 */ - MULTIPLY(tmp14, FIX(1.068791298)); /* c5 */ tmp10 = MULTIPLY(tmp12 + tmp13, FIX(0.398430003)); /* c9 */ tmp2 += tmp4 + tmp10 - MULTIPLY(tmp12, FIX(1.989053629)) /* c9+c5+c3-c7 */ + MULTIPLY(tmp14, FIX(1.399818907)); /* c1 */ tmp3 += tmp5 + tmp10 + MULTIPLY(tmp13, FIX(1.305598626)) /* c1+c5-c9-c7 */ - MULTIPLY(tmp14, FIX(1.286413905)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS - 1); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS - 1); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS - 1); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS - 1); ctr++; if (ctr != DCTSIZE) { if (ctr == 11) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/11)**2 = 64/121, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/22) * 128/121. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 2]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 1]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 0]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 7]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 6]; tmp5 = dataptr[DCTSIZE * 5]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 2]; tmp11 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 1]; tmp12 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 0]; tmp13 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 7]; tmp14 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 6]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5, FIX(1.057851240)), /* 128/121 */ CONST_BITS + 2); tmp5 += tmp5; tmp0 -= tmp5; tmp1 -= tmp5; tmp2 -= tmp5; tmp3 -= tmp5; tmp4 -= tmp5; z1 = MULTIPLY(tmp0 + tmp3, FIX(1.435427942)) + /* c2 */ MULTIPLY(tmp2 + tmp4, FIX(0.212906922)); /* c10 */ z2 = MULTIPLY(tmp1 - tmp3, FIX(0.979689713)); /* c6 */ z3 = MULTIPLY(tmp0 - tmp1, FIX(1.258538479)); /* c4 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z2 - MULTIPLY(tmp3, FIX(1.077210542)) /* c2+c8-c6 */ - MULTIPLY(tmp4, FIX(1.471445400)), /* c4+c10 */ CONST_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3 + MULTIPLY(tmp1, FIX(0.065941844)) /* c4-c6-c10 */ - MULTIPLY(tmp2, FIX(1.435427942)) /* c2 */ + MULTIPLY(tmp4, FIX(0.621472312)), /* c8 */ CONST_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 + z3 - MULTIPLY(tmp0, FIX(1.714276708)) /* c2+c4-c6 */ - MULTIPLY(tmp2, FIX(0.834379234)), /* c8+c10 */ CONST_BITS + 2); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.360834544)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.130622199)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.808813568)); /* c7 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.819470145)) /* c7+c5+c3-c1 */ + MULTIPLY(tmp14, FIX(0.421479672)); /* c9 */ tmp4 = MULTIPLY(tmp11 + tmp12, - FIX(0.808813568)); /* -c7 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.480800167)); /* -c1 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(1.350258864)) /* c9+c7+c1-c3 */ - MULTIPLY(tmp14, FIX(1.130622199)); /* c5 */ tmp10 = MULTIPLY(tmp12 + tmp13, FIX(0.421479672)); /* c9 */ tmp2 += tmp4 + tmp10 - MULTIPLY(tmp12, FIX(2.104122847)) /* c9+c5+c3-c7 */ + MULTIPLY(tmp14, FIX(1.480800167)); /* c1 */ tmp3 += tmp5 + tmp10 + MULTIPLY(tmp13, FIX(1.381129125)) /* c1+c5-c9-c7 */ - MULTIPLY(tmp14, FIX(1.360834544)); /* c3 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + 2); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + 2); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 12x12 sample block. */ GLOBAL(void) jpeg_fdct_12x12(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM workspace[8 * 4]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/24). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[6]); tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)(tmp10 + tmp11 + tmp12 - 12 * CENTERJSAMPLE); dataptr[6] = (DCTELEM)(tmp13 - tmp14 - tmp15); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.224744871)), /* c4 */ CONST_BITS); dataptr[2] = (DCTELEM) DESCALE(tmp14 - tmp15 + MULTIPLY(tmp13 + tmp15, FIX(1.366025404)), /* c2 */ CONST_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX_0_541196100); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX_0_765366865); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX_1_847759065); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.121971054)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.860918669)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.580774953)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.184591911)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.184591911)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.339493912)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.860918669)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.725788011)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(1.121971054)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.306562965)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX_0_541196100); /* c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 12) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/12)**2 = 4/9, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/24) * 8/9. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] + dataptr[DCTSIZE * 6]; tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] - dataptr[DCTSIZE * 6]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(0.888888889)), /* 8/9 */ CONST_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(tmp13 - tmp14 - tmp15, FIX(0.888888889)), /* 8/9 */ CONST_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.088662108)), /* c4 */ CONST_BITS + 1); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp14 - tmp15, FIX(0.888888889)) + /* 8/9 */ MULTIPLY(tmp13 + tmp15, FIX(1.214244803)), /* c2 */ CONST_BITS + 1); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX(0.481063200)); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX(0.680326102)); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX(1.642452502)); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(0.997307603)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.765261039)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.516244403)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.164081699)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.164081699)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.079550144)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.765261039)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.645144899)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(0.997307603)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.161389302)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX(0.481063200)); /* c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 13x13 sample block. */ GLOBAL(void) jpeg_fdct_13x13(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; INT32 z1, z2; DCTELEM workspace[8 * 5]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/26). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[12]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[11]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[10]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[9]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[8]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[7]); tmp6 = GETJSAMPLE(elemptr[6]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[12]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[11]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[10]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[9]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[8]); tmp15 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) (tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 + tmp6 - 13 * CENTERJSAMPLE); tmp6 += tmp6; tmp0 -= tmp6; tmp1 -= tmp6; tmp2 -= tmp6; tmp3 -= tmp6; tmp4 -= tmp6; tmp5 -= tmp6; dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.373119086)) + /* c2 */ MULTIPLY(tmp1, FIX(1.058554052)) + /* c6 */ MULTIPLY(tmp2, FIX(0.501487041)) - /* c10 */ MULTIPLY(tmp3, FIX(0.170464608)) - /* c12 */ MULTIPLY(tmp4, FIX(0.803364869)) - /* c8 */ MULTIPLY(tmp5, FIX(1.252223920)), /* c4 */ CONST_BITS); z1 = MULTIPLY(tmp0 - tmp2, FIX(1.155388986)) - /* (c4+c6)/2 */ MULTIPLY(tmp3 - tmp4, FIX(0.435816023)) - /* (c2-c10)/2 */ MULTIPLY(tmp1 - tmp5, FIX(0.316450131)); /* (c8-c12)/2 */ z2 = MULTIPLY(tmp0 + tmp2, FIX(0.096834934)) - /* (c4-c6)/2 */ MULTIPLY(tmp3 + tmp4, FIX(0.937303064)) + /* (c2+c10)/2 */ MULTIPLY(tmp1 + tmp5, FIX(0.486914739)); /* (c8+c12)/2 */ dataptr[4] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 - z2, CONST_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.322312651)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.163874945)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.937797057)) + /* c7 */ MULTIPLY(tmp14 + tmp15, FIX(0.338443458)); /* c11 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(2.020082300)) + /* c3+c5+c7-c1 */ MULTIPLY(tmp14, FIX(0.318774355)); /* c9-c11 */ tmp4 = MULTIPLY(tmp14 - tmp15, FIX(0.937797057)) - /* c7 */ MULTIPLY(tmp11 + tmp12, FIX(0.338443458)); /* c11 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.163874945)); /* -c5 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(0.837223564)) - /* c5+c9+c11-c3 */ MULTIPLY(tmp14, FIX(2.341699410)); /* c1+c7 */ tmp6 = MULTIPLY(tmp12 + tmp13, - FIX(0.657217813)); /* -c9 */ tmp2 += tmp4 + tmp6 - MULTIPLY(tmp12, FIX(1.572116027)) + /* c1+c5-c9-c11 */ MULTIPLY(tmp15, FIX(2.260109708)); /* c3+c7 */ tmp3 += tmp5 + tmp6 + MULTIPLY(tmp13, FIX(2.205608352)) - /* c3+c5+c9-c7 */ MULTIPLY(tmp15, FIX(1.742345811)); /* c1+c11 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 13) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/13)**2 = 64/169, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/26) * 128/169. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 3]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 2]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 1]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 0]; tmp5 = dataptr[DCTSIZE * 5] + dataptr[DCTSIZE * 7]; tmp6 = dataptr[DCTSIZE * 6]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 4]; tmp11 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 3]; tmp12 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 2]; tmp13 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 1]; tmp14 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 0]; tmp15 = dataptr[DCTSIZE * 5] - dataptr[DCTSIZE * 7]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 + tmp6, FIX(0.757396450)), /* 128/169 */ CONST_BITS + 1); tmp6 += tmp6; tmp0 -= tmp6; tmp1 -= tmp6; tmp2 -= tmp6; tmp3 -= tmp6; tmp4 -= tmp6; tmp5 -= tmp6; dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.039995521)) + /* c2 */ MULTIPLY(tmp1, FIX(0.801745081)) + /* c6 */ MULTIPLY(tmp2, FIX(0.379824504)) - /* c10 */ MULTIPLY(tmp3, FIX(0.129109289)) - /* c12 */ MULTIPLY(tmp4, FIX(0.608465700)) - /* c8 */ MULTIPLY(tmp5, FIX(0.948429952)), /* c4 */ CONST_BITS + 1); z1 = MULTIPLY(tmp0 - tmp2, FIX(0.875087516)) - /* (c4+c6)/2 */ MULTIPLY(tmp3 - tmp4, FIX(0.330085509)) - /* (c2-c10)/2 */ MULTIPLY(tmp1 - tmp5, FIX(0.239678205)); /* (c8-c12)/2 */ z2 = MULTIPLY(tmp0 + tmp2, FIX(0.073342435)) - /* (c4-c6)/2 */ MULTIPLY(tmp3 + tmp4, FIX(0.709910013)) + /* (c2+c10)/2 */ MULTIPLY(tmp1 + tmp5, FIX(0.368787494)); /* (c8+c12)/2 */ dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 - z2, CONST_BITS + 1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.001514908)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(0.881514751)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.710284161)) + /* c7 */ MULTIPLY(tmp14 + tmp15, FIX(0.256335874)); /* c11 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.530003162)) + /* c3+c5+c7-c1 */ MULTIPLY(tmp14, FIX(0.241438564)); /* c9-c11 */ tmp4 = MULTIPLY(tmp14 - tmp15, FIX(0.710284161)) - /* c7 */ MULTIPLY(tmp11 + tmp12, FIX(0.256335874)); /* c11 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(0.881514751)); /* -c5 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(0.634110155)) - /* c5+c9+c11-c3 */ MULTIPLY(tmp14, FIX(1.773594819)); /* c1+c7 */ tmp6 = MULTIPLY(tmp12 + tmp13, - FIX(0.497774438)); /* -c9 */ tmp2 += tmp4 + tmp6 - MULTIPLY(tmp12, FIX(1.190715098)) + /* c1+c5-c9-c11 */ MULTIPLY(tmp15, FIX(1.711799069)); /* c3+c7 */ tmp3 += tmp5 + tmp6 + MULTIPLY(tmp13, FIX(1.670519935)) - /* c3+c5+c9-c7 */ MULTIPLY(tmp15, FIX(1.319646532)); /* c1+c11 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3, CONST_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 14x14 sample block. */ GLOBAL(void) jpeg_fdct_14x14(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; DCTELEM workspace[8 * 6]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/28). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[11]); tmp13 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[7]); tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[11]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) (tmp10 + tmp11 + tmp12 + tmp13 - 14 * CENTERJSAMPLE); tmp13 += tmp13; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.274162392)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.314692123)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.881747734)), /* c8 */ CONST_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(1.105676686)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.273079590)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.613604268)), /* c10 */ CONST_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.719280954)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(1.378756276)), /* c2 */ CONST_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[7] = (DCTELEM)(tmp0 - tmp10 + tmp3 - tmp11 - tmp6); tmp3 <<= CONST_BITS; tmp10 = MULTIPLY(tmp10, - FIX(0.158341681)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(1.405321284)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(1.197448846)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.752406978)); /* c9 */ dataptr[5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(2.373959773)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(1.119999435)), /* c1+c11-c9 */ CONST_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(1.334852607)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.467085129)); /* c11 */ dataptr[3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.424103948)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(3.069855259)), /* c1+c5+c11 */ CONST_BITS); dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 + tmp6 - MULTIPLY(tmp0 + tmp6, FIX(1.126980169)), /* c3+c5-c1 */ CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 14) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/14)**2 = 16/49, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/28) * 32/49. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 3]; tmp13 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] + dataptr[DCTSIZE * 7]; tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 3]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] - dataptr[DCTSIZE * 7]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12 + tmp13, FIX(0.653061224)), /* 32/49 */ CONST_BITS + 1); tmp13 += tmp13; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(0.832106052)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.205513223)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.575835255)), /* c8 */ CONST_BITS + 1); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(0.722074570)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.178337691)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.400721155)), /* c10 */ CONST_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.122795725)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(0.900412262)), /* c2 */ CONST_BITS + 1); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp10 + tmp3 - tmp11 - tmp6, FIX(0.653061224)), /* 32/49 */ CONST_BITS + 1); tmp3 = MULTIPLY(tmp3 , FIX(0.653061224)); /* 32/49 */ tmp10 = MULTIPLY(tmp10, - FIX(0.103406812)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(0.917760839)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(0.782007410)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.491367823)); /* c9 */ dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(1.550341076)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(0.731428202)), /* c1+c11-c9 */ CONST_BITS + 1); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(0.871740478)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.305035186)); /* c11 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.276965844)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(2.004803435)), /* c1+c5+c11 */ CONST_BITS + 1); dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 - MULTIPLY(tmp0, FIX(0.735987049)) /* c3+c5-c1 */ - MULTIPLY(tmp6, FIX(0.082925825)), /* c9-c11-c13 */ CONST_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 15x15 sample block. */ GLOBAL(void) jpeg_fdct_15x15(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM workspace[8 * 7]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/30). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[14]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[13]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[12]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[11]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[10]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[9]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[8]); tmp7 = GETJSAMPLE(elemptr[7]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[14]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[13]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[12]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[11]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[10]); tmp15 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[9]); tmp16 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[8]); z1 = tmp0 + tmp4 + tmp5; z2 = tmp1 + tmp3 + tmp6; z3 = tmp2 + tmp7; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)(z1 + z2 + z3 - 15 * CENTERJSAMPLE); z3 += z3; dataptr[6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z3, FIX(1.144122806)) - /* c6 */ MULTIPLY(z2 - z3, FIX(0.437016024)), /* c12 */ CONST_BITS); tmp2 += ((tmp1 + tmp4) >> 1) - tmp7 - tmp7; z1 = MULTIPLY(tmp3 - tmp2, FIX(1.531135173)) - /* c2+c14 */ MULTIPLY(tmp6 - tmp2, FIX(2.238241955)); /* c4+c8 */ z2 = MULTIPLY(tmp5 - tmp2, FIX(0.798468008)) - /* c8-c14 */ MULTIPLY(tmp0 - tmp2, FIX(0.091361227)); /* c2-c4 */ z3 = MULTIPLY(tmp0 - tmp3, FIX(1.383309603)) + /* c2 */ MULTIPLY(tmp6 - tmp5, FIX(0.946293579)) + /* c8 */ MULTIPLY(tmp1 - tmp4, FIX(0.790569415)); /* (c6+c12)/2 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z3, CONST_BITS); dataptr[4] = (DCTELEM) DESCALE(z2 + z3, CONST_BITS); /* Odd part */ tmp2 = MULTIPLY(tmp10 - tmp12 - tmp13 + tmp15 + tmp16, FIX(1.224744871)); /* c5 */ tmp1 = MULTIPLY(tmp10 - tmp14 - tmp15, FIX(1.344997024)) + /* c3 */ MULTIPLY(tmp11 - tmp13 - tmp16, FIX(0.831253876)); /* c9 */ tmp12 = MULTIPLY(tmp12, FIX(1.224744871)); /* c5 */ tmp4 = MULTIPLY(tmp10 - tmp16, FIX(1.406466353)) + /* c1 */ MULTIPLY(tmp11 + tmp14, FIX(1.344997024)) + /* c3 */ MULTIPLY(tmp13 + tmp15, FIX(0.575212477)); /* c11 */ tmp0 = MULTIPLY(tmp13, FIX(0.475753014)) - /* c7-c11 */ MULTIPLY(tmp14, FIX(0.513743148)) + /* c3-c9 */ MULTIPLY(tmp16, FIX(1.700497885)) + tmp4 + tmp12; /* c1+c13 */ tmp3 = MULTIPLY(tmp10, - FIX(0.355500862)) - /* -(c1-c7) */ MULTIPLY(tmp11, FIX(2.176250899)) - /* c3+c9 */ MULTIPLY(tmp15, FIX(0.869244010)) + tmp4 - tmp12; /* c11+c13 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 15) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/15)**2 = 64/225, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/30) * 256/225. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 6]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 5]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 4]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 3]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 2]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 1]; tmp6 = dataptr[DCTSIZE * 6] + wsptr[DCTSIZE * 0]; tmp7 = dataptr[DCTSIZE * 7]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 6]; tmp11 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 5]; tmp12 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 4]; tmp13 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 3]; tmp14 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 2]; tmp15 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 1]; tmp16 = dataptr[DCTSIZE * 6] - wsptr[DCTSIZE * 0]; z1 = tmp0 + tmp4 + tmp5; z2 = tmp1 + tmp3 + tmp6; z3 = tmp2 + tmp7; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + z2 + z3, FIX(1.137777778)), /* 256/225 */ CONST_BITS + 2); z3 += z3; dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z3, FIX(1.301757503)) - /* c6 */ MULTIPLY(z2 - z3, FIX(0.497227121)), /* c12 */ CONST_BITS + 2); tmp2 += ((tmp1 + tmp4) >> 1) - tmp7 - tmp7; z1 = MULTIPLY(tmp3 - tmp2, FIX(1.742091575)) - /* c2+c14 */ MULTIPLY(tmp6 - tmp2, FIX(2.546621957)); /* c4+c8 */ z2 = MULTIPLY(tmp5 - tmp2, FIX(0.908479156)) - /* c8-c14 */ MULTIPLY(tmp0 - tmp2, FIX(0.103948774)); /* c2-c4 */ z3 = MULTIPLY(tmp0 - tmp3, FIX(1.573898926)) + /* c2 */ MULTIPLY(tmp6 - tmp5, FIX(1.076671805)) + /* c8 */ MULTIPLY(tmp1 - tmp4, FIX(0.899492312)); /* (c6+c12)/2 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z3, CONST_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3, CONST_BITS + 2); /* Odd part */ tmp2 = MULTIPLY(tmp10 - tmp12 - tmp13 + tmp15 + tmp16, FIX(1.393487498)); /* c5 */ tmp1 = MULTIPLY(tmp10 - tmp14 - tmp15, FIX(1.530307725)) + /* c3 */ MULTIPLY(tmp11 - tmp13 - tmp16, FIX(0.945782187)); /* c9 */ tmp12 = MULTIPLY(tmp12, FIX(1.393487498)); /* c5 */ tmp4 = MULTIPLY(tmp10 - tmp16, FIX(1.600246161)) + /* c1 */ MULTIPLY(tmp11 + tmp14, FIX(1.530307725)) + /* c3 */ MULTIPLY(tmp13 + tmp15, FIX(0.654463974)); /* c11 */ tmp0 = MULTIPLY(tmp13, FIX(0.541301207)) - /* c7-c11 */ MULTIPLY(tmp14, FIX(0.584525538)) + /* c3-c9 */ MULTIPLY(tmp16, FIX(1.934788705)) + tmp4 + tmp12; /* c1+c13 */ tmp3 = MULTIPLY(tmp10, - FIX(0.404480980)) - /* -(c1-c7) */ MULTIPLY(tmp11, FIX(2.476089912)) - /* c3+c9 */ MULTIPLY(tmp15, FIX(0.989006518)) + tmp4 - tmp12; /* c11+c13 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + 2); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + 2); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 16x16 sample block. */ GLOBAL(void) jpeg_fdct_16x16(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; DCTELEM workspace[DCTSIZE2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) + GETJSAMPLE(elemptr[8]); tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) - GETJSAMPLE(elemptr[8]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 16 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == DCTSIZE * 2) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/16)**2 = 1/2**2. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] + wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] + wsptr[DCTSIZE * 0]; tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] - wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] - wsptr[DCTSIZE * 0]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(tmp10 + tmp11 + tmp12 + tmp13, PASS1_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS + PASS1_BITS + 2); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+10 */ CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS + PASS1_BITS + 2); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + PASS1_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 16x8 sample block. * * 16-point FDCT in pass 1 (rows), 8-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_16x8(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 16-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; ctr = 0; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) + GETJSAMPLE(elemptr[8]); tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) - GETJSAMPLE(elemptr[8]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 16 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by 8/16 = 1/2. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4]; tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS + 1); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS + PASS1_BITS + 1); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0 + tmp10 + tmp12, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1 + tmp11 + tmp13, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2 + tmp11 + tmp12, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3 + tmp10 + tmp13, CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 14x7 sample block. * * 14-point FDCT in pass 1 (rows), 7-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_14x7(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero bottom row of output coefficient block. */ MEMZERO(&data[DCTSIZE * 7], SIZEOF(DCTELEM) * DCTSIZE); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 14-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/28). */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[11]); tmp13 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[7]); tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[11]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 14 * CENTERJSAMPLE) << PASS1_BITS); tmp13 += tmp13; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.274162392)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.314692123)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.881747734)), /* c8 */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(1.105676686)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.273079590)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.613604268)), /* c10 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.719280954)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(1.378756276)), /* c2 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[7] = (DCTELEM)((tmp0 - tmp10 + tmp3 - tmp11 - tmp6) << PASS1_BITS); tmp3 <<= CONST_BITS; tmp10 = MULTIPLY(tmp10, - FIX(0.158341681)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(1.405321284)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(1.197448846)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.752406978)); /* c9 */ dataptr[5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(2.373959773)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(1.119999435)), /* c1+c11-c9 */ CONST_BITS - PASS1_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(1.334852607)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.467085129)); /* c11 */ dataptr[3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.424103948)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(3.069855259)), /* c1+c5+c11 */ CONST_BITS - PASS1_BITS); dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 + tmp6 - MULTIPLY(tmp0 + tmp6, FIX(1.126980169)), /* c3+c5-c1 */ CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/14)*(8/7) = 32/49, which we * partially fold into the constant multipliers and final shifting: * 7-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/14) * 64/49. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 6]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 5]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 4]; tmp3 = dataptr[DCTSIZE * 3]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 6]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 5]; tmp12 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 4]; z1 = tmp0 + tmp2; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + tmp1 + tmp3, FIX(1.306122449)), /* 64/49 */ CONST_BITS + PASS1_BITS + 1); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.461784020)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(1.202428084)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.411026446)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS + PASS1_BITS + 1); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(1.151670509)); /* c4 */ dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.923568041)), /* c2+c6-c4 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS + PASS1_BITS + 1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.221765677)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.222383464)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.800824523)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.801442310)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(2.443531355)); /* c3+c1-c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 12x6 sample block. * * 12-point FDCT in pass 1 (rows), 6-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_12x6(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 2 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE * 6], SIZEOF(DCTELEM) * DCTSIZE * 2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 12-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/24). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[6]); tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 12 * CENTERJSAMPLE) << PASS1_BITS); dataptr[6] = (DCTELEM)((tmp13 - tmp14 - tmp15) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.224744871)), /* c4 */ CONST_BITS - PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(tmp14 - tmp15 + MULTIPLY(tmp13 + tmp15, FIX(1.366025404)), /* c2 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX_0_541196100); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX_0_765366865); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX_1_847759065); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.121971054)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.860918669)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.580774953)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.184591911)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.184591911)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.339493912)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.860918669)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.725788011)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(1.121971054)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.306562965)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX_0_541196100); /* c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/12)*(8/6) = 8/9, which we * partially fold into the constant multipliers and final shifting: * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 5]; tmp11 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS + PASS1_BITS + 1); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 10x5 sample block. * * 10-point FDCT in pass 1 (rows), 5-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_10x5(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 3 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE * 5], SIZEOF(DCTELEM) * DCTSIZE * 3); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 10-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/20). */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[8]); tmp12 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[5]); tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[8]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[5]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 10 * CENTERJSAMPLE) << PASS1_BITS); tmp12 += tmp12; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.144122806)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.437016024)), /* c8 */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(0.831253876)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.513743148)), /* c2-c6 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.176250899)), /* c2+c6 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[5] = (DCTELEM)((tmp10 - tmp11 - tmp2) << PASS1_BITS); tmp2 <<= CONST_BITS; dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.396802247)) + /* c1 */ MULTIPLY(tmp1, FIX(1.260073511)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.642039522)) + /* c7 */ MULTIPLY(tmp4, FIX(0.221231742)), /* c9 */ CONST_BITS - PASS1_BITS); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(0.951056516)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.587785252)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.309016994)) + /* (c3-c7)/2 */ (tmp11 << (CONST_BITS - 1)) - tmp2; dataptr[3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/10)*(8/5) = 32/25, which we * fold into the constant multipliers: * 5-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/10) * 32/25. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 3]; tmp2 = dataptr[DCTSIZE * 2]; tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(1.011928851)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.452548340)); /* (c2-c4)/2 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(1.064004961)); /* c3 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.657591230)), /* c1-c3 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.785601151)), /* c1+c3 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on an 8x4 sample block. * * 8-point FDCT in pass 1 (rows), 4-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_8x4(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 4 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE * 4], SIZEOF(DCTELEM) * DCTSIZE * 4); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by 8/4 = 2, which we add here. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[4] = (DCTELEM)((tmp10 - tmp11) << (PASS1_BITS + 1)); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 2); dataptr[2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS - PASS1_BITS - 1); dataptr[6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS - PASS1_BITS - 1); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 2); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS - PASS1_BITS - 1); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS - PASS1_BITS - 1); dataptr[5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS - PASS1_BITS - 1); dataptr[7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * 4-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 3] + (ONE << (PASS1_BITS - 1)); tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 2]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 3]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x3 sample block. * * 6-point FDCT in pass 1 (rows), 3-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_6x3(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS - PASS1_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS - PASS1_BITS - 1); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS - PASS1_BITS - 1); dataptr[1] = (DCTELEM)(tmp10 + ((tmp0 + tmp1) << (PASS1_BITS + 1))); dataptr[3] = (DCTELEM)((tmp0 - tmp1 - tmp2) << (PASS1_BITS + 1)); dataptr[5] = (DCTELEM)(tmp10 + ((tmp2 - tmp1) << (PASS1_BITS + 1))); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/3) = 32/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * 3-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/6) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 2]; tmp1 = dataptr[DCTSIZE * 1]; tmp2 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(1.257078722)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(2.177324216)), /* c1 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x2 sample block. * * 4-point FDCT in pass 1 (rows), 2-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_4x2(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by (8/4)*(8/2) = 2**3, which we add here. */ /* 4-point FDCT kernel, */ /* cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 2; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS + 3)); dataptr[2] = (DCTELEM)((tmp0 - tmp1) << (PASS1_BITS + 3)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - PASS1_BITS - 4); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS - PASS1_BITS - 3); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS - PASS1_BITS - 3); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE * 0] + (ONE << (PASS1_BITS - 1)); tmp1 = dataptr[DCTSIZE * 1]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); /* Odd part */ dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x1 sample block. * * 2-point FDCT in pass 1 (rows), 1-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_2x1(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; JSAMPROW elemptr; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); elemptr = sample_data[0] + start_col; tmp0 = GETJSAMPLE(elemptr[0]); tmp1 = GETJSAMPLE(elemptr[1]); /* We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/2)*(8/1) = 2**5. */ /* Even part */ /* Apply unsigned->signed conversion */ data[0] = (DCTELEM)((tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 5); /* Odd part */ data[1] = (DCTELEM)((tmp0 - tmp1) << 5); } /* * Perform the forward DCT on an 8x16 sample block. * * 8-point FDCT in pass 1 (rows), 16-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_8x16(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; INT32 z1; DCTELEM workspace[DCTSIZE2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM)((tmp10 - tmp11) << PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS - PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[1] = (DCTELEM) DESCALE(tmp0 + tmp10 + tmp12, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1 + tmp11 + tmp13, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2 + tmp11 + tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3 + tmp10 + tmp13, CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == DCTSIZE * 2) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by 8/16 = 1/2. * 16-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] + wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] + wsptr[DCTSIZE * 0]; tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] - wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] - wsptr[DCTSIZE * 0]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(tmp10 + tmp11 + tmp12 + tmp13, PASS1_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS + PASS1_BITS + 1); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS + PASS1_BITS + 1); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 7x14 sample block. * * 7-point FDCT in pass 1 (rows), 14-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_7x14(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM workspace[8 * 6]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 7-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/14). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[6]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[5]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[4]); tmp3 = GETJSAMPLE(elemptr[3]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[6]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[5]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[4]); z1 = tmp0 + tmp2; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((z1 + tmp1 + tmp3 - 7 * CENTERJSAMPLE) << PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.353553391)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(0.920609002)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.314692123)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS - PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(0.881747734)); /* c4 */ dataptr[4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.707106781)), /* c2+c6-c4 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS - PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.613604268)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(1.870828693)); /* c3+c1-c5 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 14) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/7)*(8/14) = 32/49, which we * fold into the constant multipliers: * 14-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/28) * 32/49. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 7; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 3]; tmp13 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] + dataptr[DCTSIZE * 7]; tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 3]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] - dataptr[DCTSIZE * 7]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12 + tmp13, FIX(0.653061224)), /* 32/49 */ CONST_BITS + PASS1_BITS); tmp13 += tmp13; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(0.832106052)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.205513223)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.575835255)), /* c8 */ CONST_BITS + PASS1_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(0.722074570)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.178337691)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.400721155)), /* c10 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.122795725)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(0.900412262)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp10 + tmp3 - tmp11 - tmp6, FIX(0.653061224)), /* 32/49 */ CONST_BITS + PASS1_BITS); tmp3 = MULTIPLY(tmp3 , FIX(0.653061224)); /* 32/49 */ tmp10 = MULTIPLY(tmp10, - FIX(0.103406812)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(0.917760839)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(0.782007410)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.491367823)); /* c9 */ dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(1.550341076)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(0.731428202)), /* c1+c11-c9 */ CONST_BITS + PASS1_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(0.871740478)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.305035186)); /* c11 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.276965844)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(2.004803435)), /* c1+c5+c11 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 - MULTIPLY(tmp0, FIX(0.735987049)) /* c3+c5-c1 */ - MULTIPLY(tmp6, FIX(0.082925825)), /* c9-c11-c13 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x12 sample block. * * 6-point FDCT in pass 1 (rows), 12-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_6x12(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM workspace[8 * 4]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS - PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS - PASS1_BITS); dataptr[1] = (DCTELEM)(tmp10 + ((tmp0 + tmp1) << PASS1_BITS)); dataptr[3] = (DCTELEM)((tmp0 - tmp1 - tmp2) << PASS1_BITS); dataptr[5] = (DCTELEM)(tmp10 + ((tmp2 - tmp1) << PASS1_BITS)); ctr++; if (ctr != DCTSIZE) { if (ctr == 12) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/12) = 8/9, which we * fold into the constant multipliers: * 12-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/24) * 8/9. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] + dataptr[DCTSIZE * 6]; tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] - dataptr[DCTSIZE * 6]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(0.888888889)), /* 8/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(tmp13 - tmp14 - tmp15, FIX(0.888888889)), /* 8/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.088662108)), /* c4 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp14 - tmp15, FIX(0.888888889)) + /* 8/9 */ MULTIPLY(tmp13 + tmp15, FIX(1.214244803)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX(0.481063200)); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX(0.680326102)); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX(1.642452502)); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(0.997307603)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.765261039)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.516244403)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.164081699)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.164081699)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.079550144)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.765261039)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.645144899)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(0.997307603)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.161389302)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX(0.481063200)); /* c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 5x10 sample block. * * 5-point FDCT in pass 1 (rows), 10-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_5x10(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM workspace[8 * 2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 5-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/10). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[3]); tmp2 = GETJSAMPLE(elemptr[2]); tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp2 - 5 * CENTERJSAMPLE) << PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(0.790569415)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.353553391)); /* (c2-c4)/2 */ dataptr[2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS - PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(0.831253876)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.513743148)), /* c1-c3 */ CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.176250899)), /* c1+c3 */ CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 10) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/5)*(8/10) = 32/25, which we * fold into the constant multipliers: * 10-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/20) * 32/25. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 5; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 0]; tmp12 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 5]; tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 0]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 5]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp12 += tmp12; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.464477191)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.559380511)), /* c8 */ CONST_BITS + PASS1_BITS); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(1.064004961)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.657591230)), /* c2-c6 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.785601151)), /* c2+c6 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp2 = MULTIPLY(tmp2, FIX(1.28)); /* 32/25 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.787906876)) + /* c1 */ MULTIPLY(tmp1, FIX(1.612894094)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.821810588)) + /* c7 */ MULTIPLY(tmp4, FIX(0.283176630)), /* c9 */ CONST_BITS + PASS1_BITS); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(1.217352341)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.752365123)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.395541753)) + /* (c3-c7)/2 */ MULTIPLY(tmp11, FIX(0.64)) - tmp2; /* 16/25 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x8 sample block. * * 4-point FDCT in pass 1 (rows), 8-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_4x8(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by 8/4 = 2, which we add here. */ /* 4-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[2] = (DCTELEM)((tmp0 - tmp1) << (PASS1_BITS + 1)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - PASS1_BITS - 2); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS - PASS1_BITS - 1); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4]; /* Add fudge factor here for final descale. */ tmp10 = tmp0 + tmp3 + (ONE << (PASS1_BITS - 1)); tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp10 + tmp11, PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) RIGHT_SHIFT(tmp10 - tmp11, PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS + PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 3x6 sample block. * * 3-point FDCT in pass 1 (rows), 6-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_3x6(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* 3-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/6). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[2]); tmp1 = GETJSAMPLE(elemptr[1]); tmp2 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 3 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(0.707106781)), /* c2 */ CONST_BITS - PASS1_BITS - 1); /* Odd part */ dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(1.224744871)), /* c1 */ CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/3) = 32/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 5]; tmp11 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x4 sample block. * * 2-point FDCT in pass 1 (rows), 4-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_2x4(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* We must also scale the output by (8/2)*(8/4) = 2**3, which we add here. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]); tmp1 = GETJSAMPLE(elemptr[1]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 3); /* Odd part */ dataptr[1] = (DCTELEM)((tmp0 - tmp1) << 3); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * 4-point FDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 2; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 2]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 3]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM)(tmp0 + tmp1); dataptr[DCTSIZE * 2] = (DCTELEM)(tmp0 - tmp1); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - 1); dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 1x2 sample block. * * 1-point FDCT in pass 1 (rows), 2-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_1x2(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); tmp0 = GETJSAMPLE(sample_data[0][start_col]); tmp1 = GETJSAMPLE(sample_data[1][start_col]); /* We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/1)*(8/2) = 2**5. */ /* Even part */ /* Apply unsigned->signed conversion */ data[DCTSIZE * 0] = (DCTELEM)((tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 5); /* Odd part */ data[DCTSIZE * 1] = (DCTELEM)((tmp0 - tmp1) << 5); } #endif /* DCT_SCALING_SUPPORTED */ #endif /* DCT_ISLOW_SUPPORTED */ }
40.543316
107
0.520573
davidlee80
c25f57e0f7f7c7b7d1556308fc524f1dd1eb0e23
4,095
cpp
C++
BasiliskII/src/Windows/router/ftp.cpp
jvernet/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
940
2015-01-04T12:20:10.000Z
2022-03-29T12:35:27.000Z
BasiliskII/src/Windows/router/ftp.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
163
2015-02-10T09:08:10.000Z
2022-03-13T05:48:10.000Z
BasiliskII/src/Windows/router/ftp.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
188
2015-01-07T19:46:11.000Z
2022-03-26T19:06:00.000Z
/* * ftp.cpp - ip router * * Basilisk II (C) 1997-2008 Christian Bauer * * Windows platform specific code copyright (C) Lauri Pesonen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "sysdeps.h" #include "main.h" #include <ctype.h> #include "dump.h" #include "prefs.h" #include "ftp.h" #if DEBUG #pragma optimize("",off) #endif #include "debug.h" static int m_ftp_port_count = 0; #define MAX_FTP_PORTS 100 static uint16 m_ftp_ports[MAX_FTP_PORTS]; bool ftp_is_ftp_port( uint16 port ) { for( int i=0; i<m_ftp_port_count; i++ ) { if( m_ftp_ports[i] == port ) return true; } return false; } void init_ftp() { const char *str = PrefsFindString("ftp_port_list"); if(str) { char *ftp = new char [ strlen(str) + 1 ]; if(ftp) { strcpy( ftp, str ); char *p = ftp; while( p && *p ) { char *pp = strchr( p, ',' ); if(pp) *pp++ = 0; if( m_ftp_port_count < MAX_FTP_PORTS ) { m_ftp_ports[m_ftp_port_count++] = (uint16)strtoul(p,0,0); } p = pp; } delete [] ftp; } } } void ftp_modify_port_command( char *buf, int &count, const uint32 max_size, const uint32 ip, const uint16 port, const bool is_pasv ) { if( max_size < 100 ) { // impossible return; } sprintf( buf, (is_pasv ? "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d).%c%c" : "PORT %d,%d,%d,%d,%d,%d%c%c"), ip >> 24, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF, (port >> 8) & 0xFF, port & 0xFF, 0x0d, 0x0a ); count = strlen(buf); D(bug("ftp_modify_port_command: \"%s\"\r\n", buf )); } // this should be robust. rather skip it than do anything dangerous. void ftp_parse_port_command( char *buf, uint32 count, uint16 &ftp_data_port, bool is_pasv ) { ftp_data_port = 0; if( !count ) return; uint8 b[100]; uint32 ftp_ip = 0; // make it a c-string if( count >= sizeof(b) ) count = sizeof(b)-1; memcpy( b, buf, count ); b[ count ] = 0; for( uint32 i=0; i<count; i++ ) { if( b[i] < ' ' || b[i] > 'z' ) { b[i] = ' '; } else { b[i] = tolower(b[i]); } } // D(bug("FTP: \"%s\"\r\n", b )); char *s = (char *)b; while( *s == ' ' ) s++; if(is_pasv) { /* LOCAL SERVER: ..227 Entering Passive Mode (192,168,0,2,6,236). 0d 0a */ if( atoi(s) == 227 && strstr(s,"passive") ) { while( *s && *s != '(' ) s++; if( *s++ == 0 ) s = 0; } else { s = 0; } } else { /* LOCAL CLIENT: PORT 192,168,0,1,14,147 0d 0a */ if( strncmp(s,"port ",5) == 0 ) { s += 5; } else { s = 0; } } if(s && *s) { // get remote ip (used only for verification) for( uint32 i=0; i<4; i++ ) { while( *s == ' ' ) s++; if(!isdigit(*s)) { ftp_ip = 0; break; } ftp_ip = (ftp_ip << 8) + atoi(s); while( *s && *s != ',' ) s++; if(!*s) { ftp_ip = 0; break; } s++; } if(ftp_ip) { // get local port for( uint32 i=0; i<2; i++ ) { while( *s == ' ' ) s++; if(!isdigit(*s)) { ftp_data_port = 0; break; } ftp_data_port = (ftp_data_port << 8) + atoi(s); while( *s && *s != ',' && *s != ')' ) s++; if(!*s) break; else s++; } } } if(ftp_data_port) { D(bug("ftp_parse_port_command: \"%s\"; port is %d\r\n", b, ftp_data_port )); } }
21.108247
99
0.542613
jvernet
c263f74bb182d8d679315f6df55b46a143b00983
11,465
cpp
C++
src/org/apache/poi/poifs/dev/POIFSHeaderDumper.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/poifs/dev/POIFSHeaderDumper.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/poifs/dev/POIFSHeaderDumper.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/poifs/dev/POIFSHeaderDumper.java #include <org/apache/poi/poifs/dev/POIFSHeaderDumper.hpp> #include <java/io/FileInputStream.hpp> #include <java/io/PrintStream.hpp> #include <java/io/Serializable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/Integer.hpp> #include <java/lang/Math.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuilder.hpp> #include <java/lang/System.hpp> #include <java/util/Iterator.hpp> #include <org/apache/poi/poifs/common/POIFSBigBlockSize.hpp> #include <org/apache/poi/poifs/common/POIFSConstants.hpp> #include <org/apache/poi/poifs/property/DirectoryProperty.hpp> #include <org/apache/poi/poifs/property/Property.hpp> #include <org/apache/poi/poifs/property/PropertyTable.hpp> #include <org/apache/poi/poifs/property/RootProperty.hpp> #include <org/apache/poi/poifs/storage/BlockAllocationTableReader.hpp> #include <org/apache/poi/poifs/storage/HeaderBlock.hpp> #include <org/apache/poi/poifs/storage/ListManagedBlock.hpp> #include <org/apache/poi/poifs/storage/RawDataBlockList.hpp> #include <org/apache/poi/poifs/storage/SmallBlockTableReader.hpp> #include <org/apache/poi/util/HexDump.hpp> #include <org/apache/poi/util/IntList.hpp> #include <Array.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } // io namespace lang { typedef ::SubArray< ::java::lang::CharSequence, ObjectArray > CharSequenceArray; typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::String, ObjectArray, ::java::io::SerializableArray, ComparableArray, CharSequenceArray > StringArray; } // lang } // java template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::poifs::dev::POIFSHeaderDumper::POIFSHeaderDumper(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::poifs::dev::POIFSHeaderDumper::POIFSHeaderDumper() : POIFSHeaderDumper(*static_cast< ::default_init_tag* >(0)) { ctor(); } void poi::poifs::dev::POIFSHeaderDumper::main(::java::lang::StringArray* args) /* throws(Exception) */ { clinit(); if(npc(args)->length == 0) { npc(::java::lang::System::err())->println(u"Must specify at least one file to view"_j); ::java::lang::System::exit(1); } for (auto j = int32_t(0); j < npc(args)->length; j++) { viewFile((*args)[j]); } } void poi::poifs::dev::POIFSHeaderDumper::viewFile(::java::lang::String* filename) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Dumping headers from: "_j)->append(filename)->toString()); ::java::io::InputStream* inp = new ::java::io::FileInputStream(filename); auto header_block = new ::poi::poifs::storage::HeaderBlock(inp); displayHeader(header_block); auto bigBlockSize = npc(header_block)->getBigBlockSize(); auto data_blocks = new ::poi::poifs::storage::RawDataBlockList(inp, bigBlockSize); displayRawBlocksSummary(data_blocks); auto batReader = new ::poi::poifs::storage::BlockAllocationTableReader(npc(header_block)->getBigBlockSize(), npc(header_block)->getBATCount(), npc(header_block)->getBATArray_(), npc(header_block)->getXBATCount(), npc(header_block)->getXBATIndex(), data_blocks); displayBATReader(u"Big Blocks"_j, batReader); auto properties = new ::poi::poifs::property::PropertyTable(header_block, data_blocks); auto sbatReader = ::poi::poifs::storage::SmallBlockTableReader::_getSmallDocumentBlockReader(bigBlockSize, data_blocks, npc(properties)->getRoot(), npc(header_block)->getSBATStart()); displayBATReader(u"Small Blocks"_j, sbatReader); displayPropertiesSummary(properties); } void poi::poifs::dev::POIFSHeaderDumper::displayHeader(::poi::poifs::storage::HeaderBlock* header_block) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(u"Header Details:"_j); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Block size: "_j)->append(npc(npc(header_block)->getBigBlockSize())->getBigBlockSize())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" BAT (FAT) header blocks: "_j)->append(npc(npc(header_block)->getBATArray_())->length)->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" BAT (FAT) block count: "_j)->append(npc(header_block)->getBATCount())->toString()); if(npc(header_block)->getBATCount() > 0) npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" BAT (FAT) block 1 at: "_j)->append((*npc(header_block)->getBATArray_())[int32_t(0)])->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" XBAT (FAT) block count: "_j)->append(npc(header_block)->getXBATCount())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" XBAT (FAT) block 1 at: "_j)->append(npc(header_block)->getXBATIndex())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" SBAT (MiniFAT) block count: "_j)->append(npc(header_block)->getSBATCount())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" SBAT (MiniFAT) block 1 at: "_j)->append(npc(header_block)->getSBATStart())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Property table at: "_j)->append(npc(header_block)->getPropertyStart())->toString()); npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayRawBlocksSummary(::poi::poifs::storage::RawDataBlockList* data_blocks) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(u"Raw Blocks Details:"_j); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Number of blocks: "_j)->append(npc(data_blocks)->blockCount())->toString()); for (auto i = int32_t(0); i < ::java::lang::Math::min(int32_t(16), npc(data_blocks)->blockCount()); i++) { auto block = npc(data_blocks)->get(i); auto data = new ::int8_tArray(::java::lang::Math::min(int32_t(48), npc(npc(block)->getData())->length)); ::java::lang::System::arraycopy(npc(block)->getData(), 0, data, 0, npc(data)->length); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Block #"_j)->append(i) ->append(u":"_j)->toString()); npc(::java::lang::System::out())->println(::poi::util::HexDump::dump(data, 0, 0)); } npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayBATReader(::java::lang::String* type, ::poi::poifs::storage::BlockAllocationTableReader* batReader) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Sectors, as referenced from the "_j)->append(type) ->append(u" FAT:"_j)->toString()); auto entries = npc(batReader)->getEntries(); for (auto i = int32_t(0); i < npc(entries)->size(); i++) { auto bn = npc(entries)->get(i); auto bnS = ::java::lang::Integer::toString(bn); if(bn == ::poi::poifs::common::POIFSConstants::END_OF_CHAIN) { bnS = u"End Of Chain"_j; } else if(bn == ::poi::poifs::common::POIFSConstants::DIFAT_SECTOR_BLOCK) { bnS = u"DI Fat Block"_j; } else if(bn == ::poi::poifs::common::POIFSConstants::FAT_SECTOR_BLOCK) { bnS = u"Normal Fat Block"_j; } else if(bn == ::poi::poifs::common::POIFSConstants::UNUSED_BLOCK) { bnS = u"Block Not Used (Free)"_j; } npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Block # "_j)->append(i) ->append(u" -> "_j) ->append(bnS)->toString()); } npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayPropertiesSummary(::poi::poifs::property::PropertyTable* properties) { clinit(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Mini Stream starts at "_j)->append(npc(npc(properties)->getRoot())->getStartBlock())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Mini Stream length is "_j)->append(npc(npc(properties)->getRoot())->getSize())->toString()); npc(::java::lang::System::out())->println(); npc(::java::lang::System::out())->println(u"Properties and their block start:"_j); displayProperties(npc(properties)->getRoot(), u""_j); npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayProperties(::poi::poifs::property::DirectoryProperty* prop, ::java::lang::String* indent) { clinit(); auto nextIndent = ::java::lang::StringBuilder().append(indent)->append(u" "_j)->toString(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(indent)->append(u"-> "_j) ->append(npc(prop)->getName())->toString()); for (auto _i = npc(prop)->iterator(); _i->hasNext(); ) { ::poi::poifs::property::Property* cp = java_cast< ::poi::poifs::property::Property* >(_i->next()); { if(dynamic_cast< ::poi::poifs::property::DirectoryProperty* >(cp) != nullptr) { displayProperties(java_cast< ::poi::poifs::property::DirectoryProperty* >(cp), nextIndent); } else { npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(nextIndent)->append(u"=> "_j) ->append(npc(cp)->getName())->toString()); npc(::java::lang::System::out())->print(::java::lang::StringBuilder().append(nextIndent)->append(u" "_j) ->append(npc(cp)->getSize()) ->append(u" bytes in "_j)->toString()); if(npc(cp)->shouldUseSmallBlocks()) { npc(::java::lang::System::out())->print(u"mini"_j); } else { npc(::java::lang::System::out())->print(u"main"_j); } npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" stream, starts at "_j)->append(npc(cp)->getStartBlock())->toString()); } } } } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::poifs::dev::POIFSHeaderDumper::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.poifs.dev.POIFSHeaderDumper", 42); return c; } java::lang::Class* poi::poifs::dev::POIFSHeaderDumper::getClass0() { return class_(); }
51.877828
265
0.658613
pebble2015
c267164a38c751e6fd15300491502e71f890fd4c
792
cpp
C++
essentials/demos/ex-properties/employee.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
16
2017-01-11T17:28:03.000Z
2021-09-27T16:12:01.000Z
essentials/demos/ex-properties/employee.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
null
null
null
essentials/demos/ex-properties/employee.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
4
2017-03-17T02:44:32.000Z
2021-01-22T07:57:34.000Z
/************************************************************************* * * Copyright (c) 2016 The Qt Company * All rights reserved. * * See the LICENSE.txt file shipped along with this file for the license. * *************************************************************************/ #include "employee.h" Employee::Employee() : Employee("NN", 0.0) { } Employee::Employee(const QString &name, const float salary) { m_name = name; m_salary = salary; } const QString &Employee::name() const { return m_name; } void Employee::setName(const QString &name) { if (name != m_name) m_name = name; } float Employee::salary() const { return m_salary; } void Employee::setSalary(float &salary) { if (salary != m_salary) m_salary = salary; }
18
75
0.522727
sfaure-witekio
c269cf34b9be43e2bfaabb3f95d6f85dd8a86f6c
7,148
cpp
C++
1SST/10LW/array.cpp
AVAtarMod/University
3c784a1e109b7a6f6ea495278ec3dc126258625a
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
1SST/10LW/array.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2020-11-25T12:00:11.000Z
2021-01-13T08:51:52.000Z
1SST/10LW/array.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <ctime> #include <random> #include "array.h" int getLenghtUser() { int length; while (true) { printf("Введите длину массива: "); scanf("%d", &length); if (length < 0) { std::cin.ignore(32767, '\n'); printf("Некорректное значение длины\n"); } if (length == 0){ printf("Длина = 0, работа программы будет завершена\n"); return 0; } else { std::cin.ignore(32767, '\n'); return length; } } } int getLenghtRandom(int minN, int maxN) { try { if (minN < 0) throw minN; } catch (int minN) { std::cerr << "ОШИБКА(minN =" << minN << "):minN должен быть > 0. "; } std::mt19937 engine(static_cast<unsigned long>(clock())); std::uniform_int_distribution<int> random(minN, maxN); return random(engine); } int getIndexUser(const int numberElementsArray, const char *reason) { int index; while (true) { printf("Введите индекс %s: ", reason); scanf("%d", &index); if (index < 0 || index > numberElementsArray) { printf("Введен некорректный индекс. Он должен быть числом от 0 до %d\n", numberElementsArray); } else { std::cin.ignore(32767, '\n'); return index; } } } int getElementUser(const char *reason) { int element; printf("Введите элемент (%s): ", reason); scanf("%d", &element); std::cin.ignore(32767, '\n'); return element; } void generateFromUser(int *array, int numberElements) { printf("Введите элементы массива через пробел: "); for (int i = 0; i < numberElements; i++) { int value; scanf("%d", &value); array[i] = value; } std::cin.ignore(32767, '\n'); } void generateRandom(int *array, int numberElements, int minNumber, int maxNumber) { std::mt19937 engine(static_cast<unsigned long>(clock())); std::uniform_int_distribution<int> random(minNumber, maxNumber); for (int i = 0; i < numberElements; i++) { array[i] = random(engine); } } int indexElement(const int *array, const int numberElements, const int number) { for (int i = 0; i < numberElements; i++) { if (array[i] == number) return i; } return -1; } int indexMinMaxElement(const int *array, int numberElements, bool comparator(int, int)) { int firstNumber = *array; int result = 0; for (int i = 1; i < numberElements; i++) { if (comparator(firstNumber, array[i])) { firstNumber = array[i]; result = i; } } return result; } int minMaxElement(const int *array, int numberElements, bool comparator(int, int)) { int firstNumber = *array; int result = 0; for (int i = 1; i < numberElements; i++) { if (comparator(firstNumber, array[i])) { firstNumber = array[i]; result = array[i]; } } return result; } int indexMinMaxElementWithConditions(const int *array, int numberElements, bool comparator(int, int), bool condition(int)) { int result = -1; int iFirstNumber = 0; for (int i = 1; i < numberElements; i++) { int secNum = array[i]; if (condition(array[i])) { if (comparator(array[iFirstNumber], secNum)) { result = iFirstNumber; } else { result = iFirstNumber = i; } } } return result; } int *searchIndexElements(const int *array, const int numberElements, const int number) { int counter = 0; for (int i = 0; i < numberElements; i++) { if (array[i] == number) { ++counter; } } int *arrayResult = new int[counter + 1]; arrayResult[0] = counter + 1; for (int i = 0, iRes = 1; i < numberElements; i++) { if (array[i] == number) { arrayResult[iRes] = i; //Заполняем arrayResult iRes++; } } if (arrayResult[0] == 0) { delete[] arrayResult; return nullptr; } else return arrayResult; } int *elementsRelevantConditions(int *array, int numberElements, bool condition(int number)) { int *arrayResult = new int[numberElements]; int lnResult = 1; for (int i = 0; i < numberElements; i++) { if (condition(array[i])) { arrayResult[lnResult] = array[i]; arrayResult[0] = lnResult; lnResult++; } } if (arrayResult[0] == 0) { delete[] arrayResult; return nullptr; } else { int *result = new int[lnResult - 1]; result[0] = lnResult - 1; for (int i = 1; i <= lnResult; i++) { result[i] = arrayResult[i]; } delete[] arrayResult; return result; } } void deleteElement(int **array, int &numberElements, int element, int offset) { --numberElements; int *arrayResult = new int[numberElements]; for (int i = offset, iRes = 0; i < numberElements; i++) { if ((*array)[i] != element) { arrayResult[iRes] = (*array)[i]; iRes++; } } delete[] * array; *array = arrayResult; } void deleteElements(int **array, int &numberElements, int element, int offset) { int counter = 0; for (int i = offset; i < numberElements; i++) { if ((*array)[i] != element) { counter++; } } bool needDelete = (counter == numberElements - offset) ? false : true; if (needDelete) { int *arrayResult = new int[counter]; int iRes = 0; for (int i = offset; i < numberElements; i++) { if ((*array)[i] != element) { arrayResult[iRes] = (*array)[i]; iRes++; } } numberElements = counter; delete[] * array; *array = arrayResult; } } void pasteElement(int **array, int &numberElements, int index, int element) { ++numberElements; int *arrayResult = new int[numberElements]; for (int i = 0, iRes = 0; i < numberElements - 1; i++) { if (i == index) { arrayResult[iRes] = element; iRes++; } arrayResult[iRes] = (*array)[i]; iRes++; } delete[] * array; *array = arrayResult; } void print(const int *array, const int numberElements, const char *text, const int offset) { printf("Значения массива %s : [ ", text); for (int i = offset; i < numberElements; i++) { printf("%d, ", array[i]); } printf("\b\b ]\n"); } bool isAMax(const int a, const int b) { return (a > b); } bool isAMin(const int a, const int b) { return (a < b); } bool isOdd(const int number) { return (abs(number % 2) == 1); } bool isEven(const int number) { return (abs(number % 2) == 0); }
21.53012
122
0.522943
AVAtarMod
c26c7d7193b82466092b84f798666991c121f3ef
4,170
cpp
C++
TrafficManager/source/pipeline/executable/PipelineExecutable.cpp
owoschhodan/carla
7da99d882afb4160f0901bbbac2ea2866683e314
[ "MIT" ]
8
2019-11-27T18:43:09.000Z
2022-01-16T06:08:36.000Z
TrafficManager/source/pipeline/executable/PipelineExecutable.cpp
tcwangjiawei/carla
714f8c4cbfbb46fa9ed163a27c94ede613948767
[ "MIT" ]
null
null
null
TrafficManager/source/pipeline/executable/PipelineExecutable.cpp
tcwangjiawei/carla
714f8c4cbfbb46fa9ed163a27c94ede613948767
[ "MIT" ]
5
2020-05-12T20:03:10.000Z
2022-02-25T14:40:07.000Z
#include <atomic> #include <cstdlib> #include <ctime> #include <execinfo.h> #include <iostream> #include <signal.h> #include <stdexcept> #include <random> #include "boost/stacktrace.hpp" #include "carla/client/Client.h" #include "carla/client/TimeoutException.h" #include "carla/Logging.h" #include "carla/Memory.h" #include "CarlaDataAccessLayer.h" #include "InMemoryMap.h" #include "Pipeline.h" namespace cc = carla::client; using Actor = carla::SharedPtr<cc::Actor>; void run_pipeline(cc::World &world, cc::Client &client_conn, uint target_traffic_amount, uint randomization_seed); std::atomic<bool> quit(false); void got_signal(int) { quit.store(true); } std::vector<Actor> *global_actor_list; void handler() { if (!quit.load()) { carla::log_error("\nTrafficManager encountered a problem!\n"); carla::log_info("Destroying all spawned actors\n"); for (auto &actor: *global_actor_list) { if (actor != nullptr && actor->IsAlive()) { actor->Destroy(); } } // Uncomment the below line if compiling with debug options (in CMakeLists.txt) // std::cout << boost::stacktrace::stacktrace() << std::endl; exit(1); } } int main(int argc, char *argv[]) { std::set_terminate(handler); cc::Client client_conn = cc::Client("localhost", 2000); cc::World world = client_conn.GetWorld(); if (argc == 2 && std::string(argv[1]) == "-h") { std::cout << "\nAvailable options\n"; std::cout << "[-n] \t\t Number of vehicles to be spawned\n"; std::cout << "[-s] \t\t System randomization seed integer\n"; } else { uint target_traffic_amount = 0u; if (argc >= 3 && std::string(argv[1]) == "-n") { try { target_traffic_amount = std::stoi(argv[2]); } catch (const std::exception &e) { carla::log_warning("Failed to parse argument, choosing defaults\n"); } } int randomization_seed = -1; if (argc == 5 && std::string(argv[3]) == "-s") { try { randomization_seed = std::stoi(argv[4]); } catch (const std::exception &e) { carla::log_warning("Failed to parse argument, choosing defaults\n"); } } if (randomization_seed < 0) { std::srand(std::time(0)); } else { std::srand(randomization_seed); } run_pipeline(world, client_conn, target_traffic_amount, randomization_seed); } return 0; } void run_pipeline(cc::World &world, cc::Client &client_conn, uint target_traffic_amount, uint randomization_seed) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = got_signal; sigfillset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); using WorldMap = carla::SharedPtr<cc::Map>; WorldMap world_map = world.GetMap(); cc::DebugHelper debug_helper = client_conn.GetWorld().MakeDebugHelper(); auto dao = traffic_manager::CarlaDataAccessLayer(world_map); using Topology = std::vector<std::pair<traffic_manager::WaypointPtr, traffic_manager::WaypointPtr>>; Topology topology = dao.GetTopology(); auto local_map = std::make_shared<traffic_manager::InMemoryMap>(topology); local_map->SetUp(1.0); uint core_count = traffic_manager::read_core_count(); std::vector<Actor> registered_actors = traffic_manager::spawn_traffic( client_conn, world, core_count, target_traffic_amount); global_actor_list = &registered_actors; client_conn.SetTimeout(2s); traffic_manager::Pipeline pipeline( {0.1f, 0.15f, 0.01f}, {5.0f, 0.0f, 0.1f}, {10.0f, 0.01f, 0.1f}, 25 / 3.6, 50 / 3.6, registered_actors, *local_map.get(), client_conn, world, debug_helper, 1 ); try { pipeline.Start(); carla::log_info("TrafficManager started\n"); while (!quit.load()) { sleep(1); // Periodically polling if Carla is still running world.GetSettings(); } } catch(const cc::TimeoutException& e) { carla::log_error("Carla has stopped running, stopping TrafficManager\n"); } pipeline.Stop(); traffic_manager::destroy_traffic(registered_actors, client_conn); carla::log_info("\nTrafficManager stopped by user\n"); }
27.077922
102
0.653717
owoschhodan
c26de97d14789617812bcf406a1ea5d8e443c509
2,236
cpp
C++
src/states.cpp
SuprDewd/states
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
[ "MIT" ]
4
2015-01-09T16:54:26.000Z
2018-10-29T13:07:59.000Z
src/states.cpp
SuprDewd/states
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
[ "MIT" ]
null
null
null
src/states.cpp
SuprDewd/states
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
[ "MIT" ]
2
2016-07-27T02:54:49.000Z
2018-04-11T17:04:07.000Z
#include <iostream> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <string> #include <list> #include <queue> #include <cstring> #include <cassert> #include "utils.h" #include "nfa.h" #include "regex.h" #include "machine.h" #include "ast.h" #include "converters.h" using namespace std; extern int yyparse(); extern FILE *yyin; extern ast_program *main_program; int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "usage: states OP FILE\n"); return 1; } yyin = fopen(argv[2], "r"); if (yyparse()) { // something went wrong exit(1); } #if DEBUG main_program->print(cout); #endif machine *m; switch (main_program->machine->get_ast_machine_type()) { case AST_MACHINE_NFA: m = nfa_from_ast((ast_nfa*)main_program->machine); break; case AST_MACHINE_REGEX: m = regex_from_ast((ast_regex*)main_program->machine); break; default: assert(false); } // nfa *S = nfa_from_ast(main_program->nfa); // for (nfa::iterator it = S->begin(); it != S->end(); ++it) { // cout << *it << endl; // } // int len = 0, cnt = 0; // for (nfa::iterator it = S->begin(); it != S->end(); ++it) { // if (size(*it) == len) { // cnt++; // } else { // while (len != size(*it)) { // printf("%d %d\n", len, cnt); // len++; // cnt = 0; // } // cnt = 1; // } // } if (strcmp(argv[1], "grep") == 0) { string line; while (getline(cin, line)) { DEBUGMSG("read '%s'\n", line.c_str()); if (m->accepts(line)) { printf("%s\n", line.c_str()); } } } else if (strcmp(argv[1], "nfa2regex") == 0) { if (main_program->machine->get_ast_machine_type() != AST_MACHINE_NFA) { fprintf(stderr, "error: input must be an nfa\n"); return 1; } regex *res = nfa2regex((nfa*)m); cout << res->to_string() << endl; delete res; } else { fprintf(stderr, "error: unsupported op '%s'\n", argv[1]); return 1; } return 0; }
21.921569
93
0.507603
SuprDewd
c26fb5005c411bdc7b149d327ada6451689f9cba
117
cpp
C++
test/minimizer_test.cpp
dehui333/Course-GenomeMapper
cab7b42078be84991e5e8f773afa04af4ce87bc6
[ "MIT" ]
null
null
null
test/minimizer_test.cpp
dehui333/Course-GenomeMapper
cab7b42078be84991e5e8f773afa04af4ce87bc6
[ "MIT" ]
null
null
null
test/minimizer_test.cpp
dehui333/Course-GenomeMapper
cab7b42078be84991e5e8f773afa04af4ce87bc6
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "minimizer.cpp" TEST(MinimizerTest, MinimizerTest1) { ASSERT_EQ(1, 1); }
10.636364
37
0.675214
dehui333
c2709c8418a84405b7cfe708f743228ba5ebfdd1
149
cpp
C++
examples/reference-ASSERT_NE_UNLABELED.cpp
gcross/Illuminate
862f665ccd4b67411bc332f534e1655585750823
[ "0BSD" ]
null
null
null
examples/reference-ASSERT_NE_UNLABELED.cpp
gcross/Illuminate
862f665ccd4b67411bc332f534e1655585750823
[ "0BSD" ]
null
null
null
examples/reference-ASSERT_NE_UNLABELED.cpp
gcross/Illuminate
862f665ccd4b67411bc332f534e1655585750823
[ "0BSD" ]
null
null
null
#include "illuminate.hpp" TEST_CASE(ASSERT_NE_UNLABELED) { ASSERT_NE_UNLABELED(1,2) ASSERT_NE_UNLABELED(1,1) ASSERT_NE_UNLABELED(0,0) }
18.625
32
0.744966
gcross
c2712c92e04442dd25dbe6a9f193832c304fd7be
9,920
cpp
C++
src/prod/src/data/integration/Replica.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
1
2018-03-15T02:09:21.000Z
2018-03-15T02:09:21.000Z
src/prod/src/data/integration/Replica.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
src/prod/src/data/integration/Replica.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Data::Integration; using namespace ktl; using namespace Common; using namespace Data::Utilities; using namespace TxnReplicator; using namespace Data::TestCommon; using namespace Data::TStore; Replica::SPtr Replica::Create( __in KGuid const & pId, __in LONG64 replicaId, __in wstring const & workFolder, __in Data::Log::LogManager & logManager, __in KAllocator & allocator, __in_opt Data::StateManager::IStateProvider2Factory * stateProviderFactory, __in_opt TRANSACTIONAL_REPLICATOR_SETTINGS const * const settings, __in_opt TxnReplicator::IDataLossHandler * const dataLossHandler) { Replica * value = _new(REPLICA_TAG, allocator) Replica(pId, replicaId, workFolder, logManager, stateProviderFactory, settings, dataLossHandler); THROW_ON_ALLOCATION_FAILURE(value); return Replica::SPtr(value); } TxnReplicator::ITransactionalReplicator::SPtr Replica::get_TxnReplicator() const { return transactionalReplicator_; } ktl::Awaitable<void> Replica::OpenAsync() { KShared$ApiEntry(); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> openAwaitable = acs->GetAwaitable(); ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper > openCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs](IFabricAsyncOperationContext * context) { ComPointer<IFabricStringResult> endpoint; HRESULT tmpHr = primaryReplicator_->EndOpen(context, endpoint.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(tmpHr)); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> openContext; HRESULT hr = primaryReplicator_->BeginOpen(openCallback.GetRawPointer(), openContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await openAwaitable; CODING_ERROR_ASSERT(SUCCEEDED(hr)); co_return; } ktl::Awaitable<void> Replica::ChangeRoleAsync( __in FABRIC_EPOCH epoch, __in FABRIC_REPLICA_ROLE newRole) { KShared$ApiEntry(); FABRIC_EPOCH tmpEpoch(epoch); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> changeRoleAwaitable = acs->GetAwaitable(); ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper> changeRoleCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs](IFabricAsyncOperationContext * context) { HRESULT tmpHr = primaryReplicator_->EndChangeRole(context); CODING_ERROR_ASSERT(SUCCEEDED(tmpHr)); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> changeRoleContext; HRESULT hr = primaryReplicator_->BeginChangeRole( &tmpEpoch, newRole, changeRoleCallback.GetRawPointer(), changeRoleContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await changeRoleAwaitable; CODING_ERROR_ASSERT(SUCCEEDED(hr)); co_return; }; ktl::Awaitable<void> Replica::CloseAsync() { KShared$ApiEntry(); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> closeAwaitable = acs->GetAwaitable(); // Close the Replicator ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper > closeCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs](IFabricAsyncOperationContext * context) { HRESULT tmpHr = primaryReplicator_->EndClose(context); CODING_ERROR_ASSERT(SUCCEEDED(tmpHr)); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> closeContext; HRESULT hr = primaryReplicator_->BeginClose(closeCallback.GetRawPointer(), closeContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await closeAwaitable; CODING_ERROR_ASSERT(SUCCEEDED(hr)); co_return; } ktl::Awaitable<NTSTATUS> Replica::OnDataLossAsync( __out BOOLEAN & isStateChanged) { KShared$ApiEntry(); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> onDataLossAwaitable = acs->GetAwaitable(); ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper > dataLossCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs, &isStateChanged](IFabricAsyncOperationContext * context) { HRESULT tmpHr = primaryReplicator_->EndOnDataLoss(context, &isStateChanged); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> dataLossContext; HRESULT hr = primaryReplicator_->BeginOnDataLoss(dataLossCallback.GetRawPointer(), dataLossContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await onDataLossAwaitable; co_return StatusConverter::Convert(hr); } void Replica::SetReadStatus(__in FABRIC_SERVICE_PARTITION_ACCESS_STATUS readStatus) { partition_->SetReadStatus(readStatus); } void Replica::SetWriteStatus(__in FABRIC_SERVICE_PARTITION_ACCESS_STATUS writeStatus) { partition_->SetWriteStatus(writeStatus); } Replica::Replica( __in KGuid const & partitionId, __in LONG64 replicaId, __in wstring const & workFolder, __in Data::Log::LogManager & logManager, __in Data::StateManager::IStateProvider2Factory * stateProviderFactory, __in TRANSACTIONAL_REPLICATOR_SETTINGS const * const settings, __in_opt TxnReplicator::IDataLossHandler * const dataLossHandler) : Common::ComponentRoot() , KObject() , KShared() { NTSTATUS status = STATUS_UNSUCCESSFUL; HANDLE handle = nullptr; PartitionedReplicaId::SPtr partitionedReplicaIdCSPtr = PartitionedReplicaId::Create(partitionId, replicaId, GetThisAllocator()); partition_ = TestComStatefulServicePartition::Create( partitionId, GetThisAllocator()); partition_->SetReadStatus(FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY); partition_->SetWriteStatus(FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY); TestComCodePackageActivationContext::SPtr codePackage = TestComCodePackageActivationContext::Create( workFolder.c_str(), GetThisAllocator()); Reliability::ReplicationComponent::ReplicatorFactoryConstructorParameters replicatorFactoryConstructorParameters; replicatorFactoryConstructorParameters.Root = this; replicatorFactory_ = Reliability::ReplicationComponent::ReplicatorFactoryFactory(replicatorFactoryConstructorParameters); replicatorFactory_->Open(L"empty"); TransactionalReplicatorFactoryConstructorParameters transactionalReplicatorFactoryConstructorParameters; transactionalReplicatorFactoryConstructorParameters.Root = this; transactionalReplicatorFactory_ = TransactionalReplicatorFactoryFactory(transactionalReplicatorFactoryConstructorParameters); transactionalReplicatorFactory_->Open(static_cast<KtlSystemBase &>(GetThisKtlSystem()), logManager); ComPointer<IFabricStateProvider2Factory> comFactory; if (stateProviderFactory == nullptr) { StoreStateProviderFactory::SPtr factory = StoreStateProviderFactory::CreateIntIntFactory(GetThisAllocator()); comFactory = TxnReplicator::TestCommon::TestComStateProvider2Factory::Create( *factory, GetThisAllocator()); } else { comFactory = TxnReplicator::TestCommon::TestComStateProvider2Factory::Create( *stateProviderFactory, GetThisAllocator()); } TxnReplicator::IDataLossHandler::SPtr localDataLossHandlerSPtr = dataLossHandler; if (localDataLossHandlerSPtr == nullptr) { localDataLossHandlerSPtr = TxnReplicator::TestCommon::TestDataLossHandler::Create(GetThisAllocator()).RawPtr(); } ComPointer<IFabricDataLossHandler> comProxyDataLossHandler = TxnReplicator::TestCommon::TestComProxyDataLossHandler::Create( GetThisAllocator(), localDataLossHandlerSPtr.RawPtr()); status = transactionalReplicatorFactory_->CreateReplicator( replicaId, *replicatorFactory_, partition_.RawPtr(), nullptr, settings, nullptr, *codePackage, TRUE, nullptr, comFactory.GetRawPointer(), comProxyDataLossHandler.GetRawPointer(), primaryReplicator_.InitializationAddress(), &handle); ITransactionalReplicator * txnReplicatorPtr = static_cast<ITransactionalReplicator *>(handle); CODING_ERROR_ASSERT(txnReplicatorPtr != nullptr); transactionalReplicator_.Attach(txnReplicatorPtr); CODING_ERROR_ASSERT(primaryReplicator_.GetRawPointer() != nullptr); CODING_ERROR_ASSERT(transactionalReplicator_ != nullptr); } Replica::~Replica() { replicatorFactory_->Close(); replicatorFactory_.reset(); transactionalReplicatorFactory_->Close(); transactionalReplicatorFactory_.reset(); primaryReplicator_.Release(); transactionalReplicator_.Reset(); }
37.293233
155
0.746069
AnthonyM
c2785f5dd84b48f18fd0223e9435eaeb425242d7
35,494
cpp
C++
isis/tests/FunctionalTestsHidtmgen.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/tests/FunctionalTestsHidtmgen.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/tests/FunctionalTestsHidtmgen.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
#include <QTemporaryFile> #include "Fixtures.h" #include "Pvl.h" #include "PvlGroup.h" #include "TestUtilities.h" #include "gmock/gmock.h" #include "UserInterface.h" #include "hidtmgen.h" #include "ProcessImportPds.h" using namespace Isis; using ::testing::HasSubstr; static QString APP_XML = FileName("$ISISROOT/bin/xml/hidtmgen.xml").expanded(); TEST(Hidtmgen, HidtmgenTestColor){ //Serves as default test case -- test all keywords for all generated products. QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/color/orthoInputList.txt", "paramspvl=data/hidtmgen/color/params.pvl", "orthosequencenumberlist=data/hidtmgen/color/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A31.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 32); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 155); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 133); ASSERT_EQ(dtmLabel["DATA_SET_ID"][0].toStdString(), "MRO-M-HIRISE-5-DTM-V1.0"); ASSERT_EQ(dtmLabel["PRODUCER_INSTITUTION_NAME"][0].toStdString(), "UNIVERSITY OF ARIZONA"); ASSERT_EQ(dtmLabel["PRODUCER_ID"][0].toStdString(), "UA"); ASSERT_EQ(dtmLabel["PRODUCER_FULL_NAME"][0].toStdString(), "ALFRED MCEWEN"); ASSERT_EQ(dtmLabel["PRODUCT_ID"][0].toStdString(), "DTEEZ_042252_1930_042753_1930_A31"); ASSERT_DOUBLE_EQ(dtmLabel["PRODUCT_VERSION_ID"], 0.314); ASSERT_EQ(dtmLabel["INSTRUMENT_HOST_NAME"][0].toStdString(), "MARS RECONNAISSANCE ORBITER"); ASSERT_EQ(dtmLabel["INSTRUMENT_NAME"][0].toStdString(), "HIGH RESOLUTION IMAGING SCIENCE EXPERIMENT"); ASSERT_EQ(dtmLabel["INSTRUMENT_ID"][0].toStdString(), "HIRISE"); ASSERT_EQ(dtmLabel["TARGET_NAME"][0].toStdString(), "MARS"); ASSERT_EQ(dtmLabel["SOURCE_PRODUCT_ID"][0].toStdString(), "ESP_042252_1930"); ASSERT_EQ(dtmLabel["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042753_1930"); ASSERT_EQ(dtmLabel["RATIONALE_DESC"][0].toStdString(), "NULL"); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["LINES"], 23); ASSERT_DOUBLE_EQ(dtmImage["LINE_SAMPLES"], 8); ASSERT_DOUBLE_EQ(dtmImage["BANDS"], 1); ASSERT_DOUBLE_EQ(dtmImage["OFFSET"], 0.0); ASSERT_DOUBLE_EQ(dtmImage["SCALING_FACTOR"], 1.0); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 32); ASSERT_EQ(dtmImage["SAMPLE_BIT_MASK"][0].toStdString(), "2#11111111111111111111111111111111#"); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "PC_REAL"); ASSERT_EQ(dtmImage["MISSING_CONSTANT"][0].toStdString(), "16#FF7FFFFB#"); ASSERT_DOUBLE_EQ(dtmImage["VALID_MINIMUM"], -1884.17); ASSERT_DOUBLE_EQ(dtmImage["VALID_MAXIMUM"], -1324.12); PvlObject dtmProj = dtmLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(dtmProj["^DATA_SET_MAP_PROJECTION"][0].toStdString(), "DSMAP.CAT"); ASSERT_EQ(dtmProj["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); ASSERT_EQ(dtmProj["PROJECTION_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(dtmProj["A_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(dtmProj["B_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(dtmProj["C_AXIS_RADIUS"], 3396.19); ASSERT_EQ(dtmProj["COORDINATE_SYSTEM_NAME"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_EQ(dtmProj["POSITIVE_LONGITUDE_DIRECTION"][0].toStdString(), "EAST"); ASSERT_EQ(dtmProj["KEYWORD_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(dtmProj["CENTER_LATITUDE"], 0.0); ASSERT_DOUBLE_EQ(dtmProj["CENTER_LONGITUDE"], 180.0); ASSERT_DOUBLE_EQ(dtmProj["LINE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(dtmProj["LINE_LAST_PIXEL"], 23); ASSERT_DOUBLE_EQ(dtmProj["SAMPLE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(dtmProj["SAMPLE_LAST_PIXEL"], 8); ASSERT_DOUBLE_EQ(dtmProj["MAP_PROJECTION_ROTATION"], 0.0); ASSERT_NEAR(dtmProj["MAP_RESOLUTION"], 59.27469, .00001); ASSERT_DOUBLE_EQ(dtmProj["MAP_SCALE"], 1000.0); ASSERT_NEAR(dtmProj["MAXIMUM_LATITUDE"], 12.82864, .00001); ASSERT_NEAR(dtmProj["MINIMUM_LATITUDE"], 12.45094, .00001); ASSERT_DOUBLE_EQ(dtmProj["LINE_PROJECTION_OFFSET"], 760.5); ASSERT_DOUBLE_EQ(dtmProj["SAMPLE_PROJECTION_OFFSET"], -10413.5); ASSERT_NEAR(dtmProj["EASTERNMOST_LONGITUDE"], 355.80733, .00001); ASSERT_NEAR(dtmProj["WESTERNMOST_LONGITUDE"], 355.68017, .00001); PvlObject dtmView = dtmLabel.findObject("VIEWING_PARAMETERS"); ASSERT_DOUBLE_EQ(dtmView["NORTH_AZIMUTH"], 270.0); Pvl orthoLabel1(prefix.path()+"/ESP_042252_1930_IRB_B_41_ORTHO.IMG"); ASSERT_EQ(orthoLabel1["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel1["RECORD_BYTES"], 40); ASSERT_DOUBLE_EQ(orthoLabel1["FILE_RECORDS"], 252); ASSERT_DOUBLE_EQ(orthoLabel1["^IMAGE"], 103); ASSERT_EQ(orthoLabel1["DATA_SET_ID"][0].toStdString(), "MRO-M-HIRISE-5-DTM-V1.0"); ASSERT_EQ(orthoLabel1["PRODUCER_INSTITUTION_NAME"][0].toStdString(), "UNIVERSITY OF ARIZONA"); ASSERT_EQ(orthoLabel1["PRODUCER_ID"][0].toStdString(), "UA"); ASSERT_EQ(orthoLabel1["PRODUCER_FULL_NAME"][0].toStdString(), "ALFRED MCEWEN"); ASSERT_EQ(orthoLabel1["PRODUCT_ID"][0].toStdString(), "ESP_042252_1930_IRB_B_41_ORTHO"); ASSERT_DOUBLE_EQ(orthoLabel1["PRODUCT_VERSION_ID"], 0.314); ASSERT_EQ(orthoLabel1["INSTRUMENT_HOST_NAME"][0].toStdString(), "MARS RECONNAISSANCE ORBITER"); ASSERT_EQ(orthoLabel1["INSTRUMENT_HOST_ID"][0].toStdString(), "MRO"); ASSERT_EQ(orthoLabel1["INSTRUMENT_NAME"][0].toStdString(), "HIGH RESOLUTION IMAGING SCIENCE EXPERIMENT"); ASSERT_EQ(orthoLabel1["INSTRUMENT_ID"][0].toStdString(), "HIRISE"); ASSERT_EQ(orthoLabel1["TARGET_NAME"][0].toStdString(), "MARS"); ASSERT_EQ(orthoLabel1["SOURCE_PRODUCT_ID"][0].toStdString(), "DTEEZ_042252_1930_042753_1930_A31"); ASSERT_EQ(orthoLabel1["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042252_1930"); ASSERT_EQ(orthoLabel1["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_EQ(orthoLabel1["SOFTWARE_NAME"][0].toStdString(), "Socet_Set 5.4.1"); ASSERT_EQ(orthoLabel1["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_DOUBLE_EQ(orthoLabel1["LABEL_RECORDS"], 102); PvlObject orthoImage1 = orthoLabel1.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage1["LINES"], 50); ASSERT_DOUBLE_EQ(orthoImage1["LINE_SAMPLES"], 40); ASSERT_DOUBLE_EQ(orthoImage1["BANDS"], 3); ASSERT_DOUBLE_EQ(orthoImage1["OFFSET"], 0.0); ASSERT_DOUBLE_EQ(orthoImage1["SCALING_FACTOR"], 1.0); ASSERT_DOUBLE_EQ(orthoImage1["SAMPLE_BITS"], 8); ASSERT_EQ(orthoImage1["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); ASSERT_EQ(orthoImage1["BAND_STORAGE_TYPE"][0].toStdString(), "BAND_SEQUENTIAL"); ASSERT_DOUBLE_EQ(orthoImage1["CORE_NULL"], 0); ASSERT_DOUBLE_EQ(orthoImage1["CORE_LOW_REPR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage1["CORE_LOW_INSTR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage1["CORE_HIGH_REPR_SATURATION"], 255); ASSERT_DOUBLE_EQ(orthoImage1["CORE_HIGH_INSTR_SATURATION"], 255); PvlObject orthoProj1 = orthoLabel1.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj1["^DATA_SET_MAP_PROJECTION"][0].toStdString(), "DSMAP.CAT"); ASSERT_EQ(orthoProj1["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); ASSERT_EQ(orthoProj1["PROJECTION_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj1["A_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj1["B_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj1["C_AXIS_RADIUS"], 3396.19); ASSERT_EQ(orthoProj1["COORDINATE_SYSTEM_NAME"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_EQ(orthoProj1["POSITIVE_LONGITUDE_DIRECTION"][0].toStdString(), "EAST"); ASSERT_EQ(orthoProj1["KEYWORD_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj1["CENTER_LATITUDE"], 0.0); ASSERT_DOUBLE_EQ(orthoProj1["CENTER_LONGITUDE"], 180.0); ASSERT_DOUBLE_EQ(orthoProj1["LINE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj1["LINE_LAST_PIXEL"], 50); ASSERT_DOUBLE_EQ(orthoProj1["SAMPLE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj1["SAMPLE_LAST_PIXEL"], 40); ASSERT_DOUBLE_EQ(orthoProj1["MAP_PROJECTION_ROTATION"], 0.0); ASSERT_NEAR(orthoProj1["MAP_RESOLUTION"], 117259.25436, .00001); ASSERT_NEAR(orthoProj1["MAP_SCALE"], 0.50550, .00001); ASSERT_NEAR(orthoProj1["MAXIMUM_LATITUDE"], 12.82848, .00001); ASSERT_NEAR(orthoProj1["MINIMUM_LATITUDE"], 12.82806, .00001); ASSERT_DOUBLE_EQ(orthoProj1["LINE_PROJECTION_OFFSET"], 1504258.5); ASSERT_DOUBLE_EQ(orthoProj1["SAMPLE_PROJECTION_OFFSET"], -20600155.500001); ASSERT_NEAR(orthoProj1["EASTERNMOST_LONGITUDE"], 355.68076, .00001); ASSERT_NEAR(orthoProj1["WESTERNMOST_LONGITUDE"], 355.68041, .00001); ASSERT_EQ(orthoProj1["FIRST_STANDARD_PARALLEL"][0].toStdString(), "N/A"); ASSERT_EQ(orthoProj1["SECOND_STANDARD_PARALLEL"][0].toStdString(), "N/A"); PvlObject orthoView1 = orthoLabel1.findObject("VIEWING_PARAMETERS"); ASSERT_DOUBLE_EQ(orthoView1["NORTH_AZIMUTH"], 270.0); Pvl orthoLabel2(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel2["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel2["RECORD_BYTES"], 40); ASSERT_DOUBLE_EQ(orthoLabel2["FILE_RECORDS"], 252); ASSERT_DOUBLE_EQ(orthoLabel2["^IMAGE"], 103); ASSERT_EQ(orthoLabel2["DATA_SET_ID"][0].toStdString(), "MRO-M-HIRISE-5-DTM-V1.0"); ASSERT_EQ(orthoLabel2["PRODUCER_INSTITUTION_NAME"][0].toStdString(), "UNIVERSITY OF ARIZONA"); ASSERT_EQ(orthoLabel2["PRODUCER_ID"][0].toStdString(), "UA"); ASSERT_EQ(orthoLabel2["PRODUCER_FULL_NAME"][0].toStdString(), "ALFRED MCEWEN"); ASSERT_EQ(orthoLabel2["PRODUCT_ID"][0].toStdString(), "ESP_042252_1930_IRB_D_31_ORTHO"); ASSERT_DOUBLE_EQ(orthoLabel2["PRODUCT_VERSION_ID"], 0.314); ASSERT_EQ(orthoLabel2["INSTRUMENT_HOST_NAME"][0].toStdString(), "MARS RECONNAISSANCE ORBITER"); ASSERT_EQ(orthoLabel2["INSTRUMENT_HOST_ID"][0].toStdString(), "MRO"); ASSERT_EQ(orthoLabel2["INSTRUMENT_NAME"][0].toStdString(), "HIGH RESOLUTION IMAGING SCIENCE EXPERIMENT"); ASSERT_EQ(orthoLabel2["INSTRUMENT_ID"][0].toStdString(), "HIRISE"); ASSERT_EQ(orthoLabel2["TARGET_NAME"][0].toStdString(), "MARS"); ASSERT_EQ(orthoLabel2["SOURCE_PRODUCT_ID"][0].toStdString(), "DTEEZ_042252_1930_042753_1930_A31"); ASSERT_EQ(orthoLabel2["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042252_1930"); ASSERT_EQ(orthoLabel2["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_EQ(orthoLabel2["SOFTWARE_NAME"][0].toStdString(), "Socet_Set 5.4.1"); ASSERT_EQ(orthoLabel2["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_DOUBLE_EQ(orthoLabel2["LABEL_RECORDS"], 102); PvlObject orthoImage2 = orthoLabel2.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage2["LINES"], 50); ASSERT_DOUBLE_EQ(orthoImage2["LINE_SAMPLES"], 40); ASSERT_DOUBLE_EQ(orthoImage2["BANDS"], 3); ASSERT_DOUBLE_EQ(orthoImage2["OFFSET"], 0.0); ASSERT_DOUBLE_EQ(orthoImage2["SCALING_FACTOR"], 1.0); ASSERT_DOUBLE_EQ(orthoImage2["SAMPLE_BITS"], 8); ASSERT_EQ(orthoImage2["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); ASSERT_EQ(orthoImage2["BAND_STORAGE_TYPE"][0].toStdString(), "BAND_SEQUENTIAL"); ASSERT_DOUBLE_EQ(orthoImage2["CORE_NULL"], 0); ASSERT_DOUBLE_EQ(orthoImage2["CORE_LOW_REPR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage2["CORE_LOW_INSTR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage2["CORE_HIGH_REPR_SATURATION"], 255); ASSERT_DOUBLE_EQ(orthoImage2["CORE_HIGH_INSTR_SATURATION"], 255); PvlObject orthoProj2 = orthoLabel2.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj2["^DATA_SET_MAP_PROJECTION"][0].toStdString(), "DSMAP.CAT"); ASSERT_EQ(orthoProj2["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); ASSERT_EQ(orthoProj2["PROJECTION_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj2["A_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj2["B_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj2["C_AXIS_RADIUS"], 3396.19); ASSERT_EQ(orthoProj2["COORDINATE_SYSTEM_NAME"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_EQ(orthoProj2["POSITIVE_LONGITUDE_DIRECTION"][0].toStdString(), "EAST"); ASSERT_EQ(orthoProj2["KEYWORD_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj2["CENTER_LATITUDE"], 0.0); ASSERT_DOUBLE_EQ(orthoProj2["CENTER_LONGITUDE"], 180.0); ASSERT_DOUBLE_EQ(orthoProj2["LINE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj2["LINE_LAST_PIXEL"], 50); ASSERT_DOUBLE_EQ(orthoProj2["SAMPLE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj2["SAMPLE_LAST_PIXEL"], 40); ASSERT_DOUBLE_EQ(orthoProj2["MAP_PROJECTION_ROTATION"], 0.0); ASSERT_NEAR(orthoProj2["MAP_RESOLUTION"], 29314.81359, .00001); ASSERT_NEAR(orthoProj2["MAP_SCALE"], 2.02200, .00001); ASSERT_NEAR(orthoProj2["MAXIMUM_LATITUDE"], 12.82801, .00001); ASSERT_NEAR(orthoProj2["MINIMUM_LATITUDE"], 12.82631, .00001); ASSERT_DOUBLE_EQ(orthoProj2["LINE_PROJECTION_OFFSET"], 376050.5); ASSERT_DOUBLE_EQ(orthoProj2["SAMPLE_PROJECTION_OFFSET"], -5150060.5); ASSERT_NEAR(orthoProj2["EASTERNMOST_LONGITUDE"], 355.68250, .00001); ASSERT_NEAR(orthoProj2["WESTERNMOST_LONGITUDE"], 355.68114, .00001); ASSERT_EQ(orthoProj2["FIRST_STANDARD_PARALLEL"][0].toStdString(), "N/A"); ASSERT_EQ(orthoProj2["SECOND_STANDARD_PARALLEL"][0].toStdString(), "N/A"); PvlObject orthoView2 = orthoLabel2.findObject("VIEWING_PARAMETERS"); ASSERT_DOUBLE_EQ(orthoView2["NORTH_AZIMUTH"], 270.0); } TEST(Hidtmgen, HidtmgenTestDtmOnly){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "paramspvl=data/hidtmgen/dtmOnly/params.pvl", }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A15.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 32); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 155); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 133); } TEST(Hidtmgen, HidtmgenTestEqui){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/DTM_Zumba_1m_forPDS_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/equi/orthoInputList.txt", "paramspvl=data/hidtmgen/equi/params.pvl", "orthosequencenumberlist=data/hidtmgen/equi/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_002118_1510_003608_1510_A02.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 28); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 203); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 183); PvlObject dtmProj = dtmLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(dtmProj["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); Pvl orthoLabel(prefix.path()+"/PSP_002118_1510_RED_C_01_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 50); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 132); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 83); PvlObject orthoProj = orthoLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); } TEST(Hidtmgen, HidtmgenTestErrorEmptyOrthoFromList){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputListEmpty.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("File [data/hidtmgen/error/orthoInputListEmpty.txt] contains no data.")); } } TEST(Hidtmgen, HidtmgenTestErrorInvalidDtm){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/ortho/ESP_042252_1930_3-BAND_COLOR_2m_o_cropped.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Input cube [data/hidtmgen/ortho/ESP_042252_1930_3-BAND_COLOR_2m_o_cropped.cub] does not appear to be a DTM.")); } } TEST(Hidtmgen, HidtmgenTestErrorNoInput){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "outputdir=" + prefix.path(), "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("User must supply DTM or ORTHOFROMLIST or both.")); } } TEST(Hidtmgen, HidtmgenTestErrorDtmInvalidProjection){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres_sinusoidal.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("The projection type [SINUSOIDAL] is not supported.")); } } TEST(Hidtmgen, HidtmgenTestErrorInputSeqMismatch){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers1item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Output sequence number list must correspond to the input ortho list.")); } } TEST(Hidtmgen, HidtmgenTestErrorInputOutputMismatch){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=FALSE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "dtm_product_id=xyz", "dtmto=" + prefix.path() + "/xyz.IMG", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthotolist=data/hidtmgen/error/orthoToList1Item.txt", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt", "orthoproductidlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Output ortho list and product id list must correspond to the input ortho list.")); } } TEST(Hidtmgen, HidtmgenTestErrorInvalidInstitution){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/invalidProducingInst.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("PRODUCING_INSTITUTION value [USGS] in the PARAMSPVL file must be a single character.")); } } TEST(Hidtmgen, HidtmgenTestErrorInvalidVersionId){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/invalidVersionId.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Version number [-4.0] is invalid.")); } } TEST(Hidtmgen, HidtmgenTestErrorDtmInvalidBandSize){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/DTM_2Bands_cropped.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Input cube [data/hidtmgen/dtm/DTM_2Bands_cropped.cub] does not appear to be a DTM.")); } } TEST(Hidtmgen, HidtmgenTestErrorOrthoInvalidBandSize){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Bands.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers1item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("The file [data/hidtmgen/ortho/2BandImage.cub] found in the ORTHOFROMLIST is not a valid orthorectified image. Band count must be 1 (RED) or 3 (color).")); } } TEST(Hidtmgen, HidtmgenTestNonDefaultNames){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=FALSE", "dtm=data/hidtmgen/dtm/DTM_Zumba_1m_forPDS_lowres.cub", "outputdir=" + prefix.path(), "dtmto="+ prefix.path() + "/dtm.img", "orthofromlist=data/hidtmgen/nonDefaultNames/orthoInputList.txt", "orthotolist=data/hidtmgen/nonDefaultNames/orthoOutputFiles.lis", "orthoproductidlist=data/hidtmgen/nonDefaultNames/orthoOutputProductIds.lis", "paramspvl=data/hidtmgen/nonDefaultNames/params.pvl", "dtm_product_id=DtmProduct" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/dtm.img"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 28); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 203); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 183); } TEST(Hidtmgen, HidtmgenTestOrthoOnly){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/orthoOnly/orthoInputList.txt", "paramspvl=data/hidtmgen/orthoOnly/params.pvl", "orthosequencenumberlist=data/hidtmgen/orthoOnly/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["SOURCE_PRODUCT_ID"][0].toStdString(), "DTems_xxxxxx_xxxx_yyyyyy_yyyy_vnn"); ASSERT_EQ(orthoLabel["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042252_1930"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 40); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 254); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 105); } TEST(Hidtmgen, HidtmgenTestOutputTypesAll832){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/outputTypes/orthoInputList.txt", "paramspvl=data/hidtmgen/outputTypes/params.pvl", "endian=msb", "null=FALSE", "LIS=TRUE", "LRS=TRUE", "HIS=TRUE", "HRS=TRUE", "dtmbittype=8BIT", "orthobittype=32bit", "orthosequencenumberlist=data/hidtmgen/outputTypes/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A31.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 8); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 558); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 536); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 8); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 160); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 177); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 28); PvlObject orthoImage = orthoLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage["SAMPLE_BITS"], 32); ASSERT_EQ(orthoImage["SAMPLE_TYPE"][0].toStdString(), "IEEE_REAL"); } TEST(Hidtmgen, HidtmgenTestOutputTypesAllU16S16){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/outputTypes/orthoInputList.txt", "paramspvl=data/hidtmgen/outputTypes/params2.pvl", "endian=msb", "null=FALSE", "LIS=TRUE", "LRS=TRUE", "HIS=TRUE", "HRS=TRUE", "dtmbittype=u16bit", "orthobittype=s16bit", "orthosequencenumberlist=data/hidtmgen/outputTypes/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A07.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 16); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 288); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 266); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 16); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 80); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 202); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 53); PvlObject orthoImage = orthoLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage["SAMPLE_BITS"], 16); ASSERT_EQ(orthoImage["SAMPLE_TYPE"][0].toStdString(), "MSB_INTEGER"); } TEST(Hidtmgen, HidtmgenTestOutputTypesNoneS16U16){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/outputTypes/orthoInputList.txt", "paramspvl=data/hidtmgen/outputTypes/params2.pvl", "endian=msb", "null=FALSE", "LIS=FALSE", "LRS=FALSE", "HIS=FALSE", "HRS=FALSE", "dtmbittype=S16BIT", "orthobittype=U16BIT", "orthosequencenumberlist=data/hidtmgen/outputTypes/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A07.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 16); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 288); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 266); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 16); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "MSB_INTEGER"); Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 80); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 202); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 53); PvlObject orthoImage = orthoLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage["SAMPLE_BITS"], 16); ASSERT_EQ(orthoImage["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); } TEST(Hidtmgen, HidtmgenTestPolar){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Polar_Crater_1_1m_ngate_edited2_forPDS_lowres.cub", "paramspvl=data/hidtmgen/polar/params.pvl", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/polar/orthoInputList.txt", "orthosequence=data/hidtmgen/polar/orthosequencenumberlist.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEPZ_009404_2635_010221_2635_Z12.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 52); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 96); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 85); PvlObject dtmProj = dtmLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(dtmProj["MAP_PROJECTION_TYPE"][0].toStdString(), "POLAR STEREOGRAPHIC"); Pvl orthoLabel(prefix.path()+"/PSP_009404_2635_RED_C_1_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 50); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 115); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 66); PvlObject orthoProj = orthoLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj["MAP_PROJECTION_TYPE"][0].toStdString(), "POLAR STEREOGRAPHIC"); }
46.519004
191
0.669691
kdl222
c27bbb840bdbbae75fe1df3f80d840747c65a144
1,500
hpp
C++
src/Magma/Window/Win32Window.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
3
2017-11-01T21:47:57.000Z
2022-01-07T03:50:58.000Z
src/Magma/Window/Win32Window.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
src/Magma/Window/Win32Window.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
#pragma once #include "Window.hpp" #include <Windows.h> #include <queue> namespace Magma { class Win32Window : public Window { public: Win32Window(HINSTANCE hInstance, int nCmdShow); virtual ~Win32Window() final; private: static LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); // Inherited via Window virtual void SetVSyncEnabled(bool vsyncEnabled) override; virtual bool IsKeyboardKeyPressed(Keyboard::Key key) override; virtual bool IsMouseCursorVisible() override; virtual bool IsMouseButtonPressed(Mouse::Button button) override; virtual void SetMouseCursorVisible(bool visible) override; virtual glm::vec2 GetMousePosition() override; virtual void SetMousePosition(glm::vec2 mousePosition) override; virtual bool DerivedIsOpen() override; virtual void DerivedOpen() override; virtual void DerivedClose() override; virtual void DerivedResize() override; virtual void DerivedSetTitle() override; virtual void DerivedSetMode() override; virtual bool DerivedPollEvent(Magma::UIEvent & event) override; virtual void DerivedDisplay() override; virtual void DerivedMakeActive() override; HINSTANCE m_hInstance; HWND m_hWnd; WNDCLASSEX m_wc; int m_nCmdShow; bool m_cursorVisible = true; std::queue<Magma::UIEvent> m_eventQueue; bool m_mouseButtonStates[static_cast<size_t>(Mouse::Button::Count)]; bool m_keyboardKeyStates[static_cast<size_t>(Keyboard::Key::Count)]; }; }
28.846154
70
0.761333
RiscadoA
c284712f5b22944a88f62207994c29820934cd80
3,040
hpp
C++
core/Material.hpp
lonelywm/cuda_path_tracer
d99f0b682ad7f64fa127ca3604d0eab26f61452c
[ "MIT" ]
1
2021-06-12T11:33:12.000Z
2021-06-12T11:33:12.000Z
core/Material.hpp
lonelywm/cuda_path_tracer
d99f0b682ad7f64fa127ca3604d0eab26f61452c
[ "MIT" ]
null
null
null
core/Material.hpp
lonelywm/cuda_path_tracer
d99f0b682ad7f64fa127ca3604d0eab26f61452c
[ "MIT" ]
null
null
null
#pragma once #include <pch.h> #include <curand_kernel.h> struct Material { Vec3f ka; //Ambient Vec3f kd; //diffuse Vec3f ks; //specular Vec3f kt; //Transmittance Vec3f ke; //Emmission Vec3f kr; //reflectance == specular float ior; float dissolve; // 1 == opaque; 0 == fully transparent uint beginIndex; // device uint endIndex; // device bool _refl; // specular reflector? bool _trans; // specular transmitter? bool _spec; // any kind of specular? bool _both; // reflection and transmission __host__ __device__ void setBools() { _refl = isZero(kr); _trans = isZero(kt); _spec = _refl || isZero(ks); _both = _refl && _trans; } __host__ __device__ bool Refl() const { return _refl; } __host__ __device__ bool Trans() const { return _trans; } __device__ Vec3f shade() { Vec3f I = kd; return I; } __host__ __device__ bool hasEmission() { if (ke.norm2() > EPSILON) return true; return false; } __device__ Vec3f toWorld(CVec3f& a, CVec3f& N) { Vec3f B, C; if (fabs(N.x) > fabs(N.y)) { float invLen = 1.0f / sqrt(N.x * N.x + N.z * N.z); C = Vec3f(N.z * invLen, 0.0f, -N.x * invLen); } else { float invLen = 1.0f / sqrt(N.y * N.y + N.z * N.z); C = Vec3f(0.0f, N.z * invLen, -N.y * invLen); } B = C.cross(N); return a.x * B + a.y * C + a.z * N; } __host__ __device__ __inline__ Vec3f eval(CVec3f& wi, CVec3f& wo, CVec3f& nor) { // diffuse // calculate the contribution of diffuse model float cosalpha = nor.dot(wo); if (cosalpha > 0.0f) { Vec3f diffuse = kd / PI; return diffuse; } return Vec3f(); } __device__ Vec3f sample(CVec3f& Nor, curandState& randState) { float x1 = curand_uniform(&randState); float x2 = curand_uniform(&randState); float z = std::fabs(1.0f - 2.0f * x1); float r = std::sqrt(1.0f - z * z); float phi = 2 * PI * x2; Vec3f localRay(r * cos(phi), r * sin(phi), z); return toWorld(localRay, Nor).normalize(); } __device__ float Material::pdf(const Vec3f& wo, const Vec3f& N) { if (wo.dot(N) > 0.0f) return 0.5f / PI; else return 0.0f; } __device__ Material& operator += (const Material& m){ ke += m.ke; ka += m.ka; ks += m.ks; kd += m.kd; kr += m.kr; kt += m.kt; ior += m.ior; setBools(); return *this; } friend __device__ __inline__ Material operator*(float d, Material m); }; __device__ __inline__ Material operator*(float d, Material m){ m.ke *= d; m.ka *= d; m.ks *= d; m.kd *= d; m.kr *= d; m.kt *= d; m.ior *= d; return m; }
23.030303
62
0.511184
lonelywm
c28753c302c7715048d1e9760a7e1895e717f57e
833
cpp
C++
CFB_Cursos/QT/formularios/objeto_local/formularios/mainwindow.cpp
marcospontoexe/Cpp
d640be32fda2a25f871271e024efef727e7890c1
[ "MIT" ]
null
null
null
CFB_Cursos/QT/formularios/objeto_local/formularios/mainwindow.cpp
marcospontoexe/Cpp
d640be32fda2a25f871271e024efef727e7890c1
[ "MIT" ]
null
null
null
CFB_Cursos/QT/formularios/objeto_local/formularios/mainwindow.cpp
marcospontoexe/Cpp
d640be32fda2a25f871271e024efef727e7890c1
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include "janela.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { janela form2; //declaração do atributo da classe janela QMessageBox::StandardButton resposta; resposta = QMessageBox::question(this, "Janela", "Deseja realmente abriar a janela?", QMessageBox::Yes | QMessageBox::No); if (resposta == QMessageBox::No) { QMessageBox::about(this, "Fim", "Até logo!"); close(); //QApplication::quit(); também encerra a aplicação } else { QMessageBox::about(this, "Janela", "Janela aberta!"); form2.exec(); } }
20.825
126
0.638655
marcospontoexe
c28b04dbd2d248d3431d2fa8115c31b042d4683b
588
cpp
C++
code/cpp/ReverseLinkedListRecur.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/ReverseLinkedListRecur.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/ReverseLinkedListRecur.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
List* recur_rlist(List* head) { List* result; if(!(head && head->next)) return head; result = recur_rlist(head->next); head->next->next = head; head->next = NULL; return result; } void printList(List* head) { while(head != NULL) { std::cout<<head->data<<" "; head = head->next; } } void main() { List* list = createNode(2); append(list, createNode(3)); append(list, createNode(4)); append(list, createNode(5)); append(list, createNode(6)); List* revlist = recur_rlist(list); printList(revlist); }
18.967742
38
0.571429
analgorithmaday
c290b2d958731274efc46000bdc20277618a74ca
4,126
cc
C++
test/mpdtest.cc
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
test/mpdtest.cc
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
test/mpdtest.cc
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
1
2020-10-04T22:14:55.000Z
2020-10-04T22:14:55.000Z
/** * Test the MPD client class * * This is a "manual" test, and requires user interaction to listen for * the correct audio output. It does not use the boost test framework. * 1. mpd must be running * 2. you must provide a valid resource string as the sole argument */ /* Part of the rsked package. * * Copyright 2020 Steven A. Harp * * 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 "logging.hpp" #include "mpdclient.hpp" #include <boost/filesystem.hpp> namespace fs = boost::filesystem; /// Sample invocations: /// mp4 file /// mpdtest "Brian Eno/Another Green World/08 - Sombre Reptiles.m4a" /// flac file /// mpdtest "Dub Apocalypse/Live at 3S Artspace/03 Track04.flac" /// directory with mp4 tracks /// mpdtest "Brian Eno/Another Green World" /// playlist (.m3u) The .m3u will (must) be stripped for mpd. /// mpdtest "master.m3u" /////////////////////////////////////////////////////////////////////////////////// void log_last_err( Mpd_client &client ) { switch( client.last_err() ) { case Mpd_err::NoError: LOG_INFO(Lgr) << "MPD no error"; break; case Mpd_err::NoConnection: LOG_ERROR(Lgr) << "MPD could not connect"; break; case Mpd_err::NoStatus: LOG_ERROR(Lgr) << "MPD did not receive a status response"; break; case Mpd_err::NoExist: LOG_ERROR(Lgr) << "MPD could not access the resource"; break; default: LOG_ERROR(Lgr) << "MPD unknown Mpd_err"; } } /// tests a single track or directory /// void test1( Mpd_client &client, const std::string &resource ) { client.connect(); // client.stop(); client.clear_queue(); client.set_repeat_mode(false); client.enqueue( resource ); client.check_status(Mpd_opt::Print); if (client.last_err() == Mpd_err::NoError) { client.play(); sleep(10); client.check_status(Mpd_opt::Print); client.stop(); } // client.disconnect(); } /// tests a playlist /// void testp( Mpd_client &client, const std::string &plist ) { // strip any trailing extension, like .m3u, if present fs::path plfile { plist }; std::string plstem { plfile.stem().native() }; LOG_DEBUG(Lgr) << "playlist stem: '" << plstem << "'"; client.connect(); // client.stop(); client.clear_queue(); client.set_repeat_mode(false); client.enqueue_playlist( plstem ); client.check_status(Mpd_opt::Print); if (client.last_err() == Mpd_err::NoError) { client.play(); sleep(10); client.check_status(Mpd_opt::Print); client.stop(); } // client.disconnect(); } //////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { init_logging("mpdtest","mpdtest_%5N.log",LF_FILE|LF_DEBUG|LF_CONSOLE); if (argc < 2) { LOG_ERROR(Lgr) << "Usage: mpdtest resource_string"; return 1; } std::string filestring { argv[1] }; fs::path filename { filestring }; LOG_INFO(Lgr) << "Play " << filename << " for 10 seconds."; Mpd_client client {}; try { if (filename.extension() == ".m3u") { LOG_INFO(Lgr) << "(It seems to be a playlist.)"; testp( client, filestring ); // playlist - handled differently } else { test1( client, filestring ); // regular file } } catch (std::exception &xxx) { LOG_ERROR(Lgr) << "Exit on exception: " << xxx.what(); } log_last_err( client ); finish_logging(); return 0; }
27.506667
83
0.598885
farlies
c2937623bc9acd9db390a4927e121d40eff95033
384
cpp
C++
fundamentals/introduction/pyramid.cpp
stemDaniel/ufmg-pds2
4dbb536a0926b617d04d133cbd3f7a5a223e113e
[ "MIT" ]
null
null
null
fundamentals/introduction/pyramid.cpp
stemDaniel/ufmg-pds2
4dbb536a0926b617d04d133cbd3f7a5a223e113e
[ "MIT" ]
null
null
null
fundamentals/introduction/pyramid.cpp
stemDaniel/ufmg-pds2
4dbb536a0926b617d04d133cbd3f7a5a223e113e
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int height; cout << "Insira a altura da pirâmide: "; cin >> height; for (int i = 0; i < height; ++i) { for (int j = 0; j <= i; ++j) { cout << "*"; } cout << endl; } for (int i = height - 1; i > 0; --i) { for (int j = i; j > 0; --j) { cout << "*"; } cout << endl; } return 0; }
17.454545
42
0.442708
stemDaniel
c29456f50b570fd2027d566cb489c4e33bad3544
6,396
cpp
C++
src/cassimpmodel.cpp
SilangQuan/QSLFrameWork
13059fef0972e0753d0d77e8f1cd9bdaf80beb0d
[ "MIT" ]
16
2015-09-24T00:59:34.000Z
2022-02-20T03:43:47.000Z
src/cassimpmodel.cpp
aleksas/QSLFrameWork
13059fef0972e0753d0d77e8f1cd9bdaf80beb0d
[ "MIT" ]
null
null
null
src/cassimpmodel.cpp
aleksas/QSLFrameWork
13059fef0972e0753d0d77e8f1cd9bdaf80beb0d
[ "MIT" ]
8
2016-05-11T05:59:53.000Z
2019-01-11T16:32:46.000Z
#include "cassimpmodel.h" CAssimpModel::MeshEntry::MeshEntry() { VB = INVALID_OGL_VALUE; IB = INVALID_OGL_VALUE; numIndices = 0; materialIndex = INVALID_OGL_VALUE; }; CAssimpModel::MeshEntry::~MeshEntry() { if (VB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &VB); } if (IB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &IB); } } void CAssimpModel::MeshEntry::init(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices) { numIndices = indices.size(); glGenBuffers(1, &VB); glBindBuffer(GL_ARRAY_BUFFER, VB); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), &vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &IB); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * numIndices, &indices[0], GL_STATIC_DRAW); } CAssimpModel::CAssimpModel() { isLoaded = false; } CAssimpModel::~CAssimpModel() { for(int i = 0;i < textures.size(); i++) { free(textures[i]); } } CAssimpModel::CAssimpModel(ShaderProgram& p) { prog = &p; isLoaded = false; } bool CAssimpModel::LoadModelFromFile(const std::string& filepath) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile( filepath, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs); if(!scene) { cout<<"Couldn't load model, Error Importing Asset"<<endl; return false; } meshEntries.resize(scene->mNumMeshes); textures.resize(scene->mNumMaterials); for(int i=0; i<scene->mNumMeshes; i++) { aiMesh* paiMesh = scene->mMeshes[i]; int iMeshFaces = paiMesh->mNumFaces; cout<<"Mesh "<<i<<" faces:"<<iMeshFaces<<endl; initMesh(i, paiMesh); } cout<<scene->mNumMaterials<<endl; if(scene->mNumMaterials > 1) { initMaterial(scene,filepath); } cout<<"scene->mNumMeshes:"<<scene->mNumMeshes<<endl; cout<<"scene->mNumMaterials:"<<scene->mNumMaterials<<endl; aiMesh* paiMesh = scene->mMeshes[0]; cout<<"mesh0->mNumFaces:"<<paiMesh->mNumFaces<<endl; cout<<"mesh0->mNumVertices:"<<paiMesh->mNumVertices<<endl; isLoaded = true; return true; } void CAssimpModel::initMesh(unsigned int index, const aiMesh* paiMesh) { meshEntries[index].materialIndex = paiMesh->mMaterialIndex; cout<<"mesh"<<index<< "mMaterialIndex"<< paiMesh->mMaterialIndex<<endl; vector<Vertex> vertices; vector<unsigned int> indices; const aiVector3D Zero3D(0.0f, 0.0f, 0.0f); vertices.reserve(paiMesh->mNumVertices); indices.reserve(paiMesh->mNumFaces); for (unsigned int i = 0 ; i < paiMesh->mNumVertices ; i++) { const aiVector3D* pPos = &(paiMesh->mVertices[i]); const aiVector3D* pNormal = &(paiMesh->mNormals[i]); const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D; Vertex v(glm::vec3(pPos->x, pPos->y, pPos->z), glm::vec2(pTexCoord->x, pTexCoord->y), glm::vec3(pNormal->x, pNormal->y, pNormal->z) ); // cout<<i<<": "<<v.m_tex.x<<v.m_tex.y<<endl; vertices.push_back(v); } for(unsigned int i=0; i<paiMesh->mNumFaces; i++) { const aiFace& Face = paiMesh->mFaces[i]; assert(Face.mNumIndices == 3); indices.push_back(Face.mIndices[0]); indices.push_back(Face.mIndices[1]); indices.push_back(Face.mIndices[2]); } meshEntries[index].init(vertices, indices); } void CAssimpModel::render() { if(!isLoaded) return; glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); for (unsigned int i = 0 ; i < meshEntries.size() ; i++) { glBindBuffer(GL_ARRAY_BUFFER, meshEntries[i].VB); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)(sizeof(glm::vec3))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)(sizeof(glm::vec2)+sizeof(glm::vec3))); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshEntries[i].IB); const unsigned int materialIndex = meshEntries[i].materialIndex; if (materialIndex < textures.size() && textures[materialIndex]) { textures[materialIndex]->bind(GL_TEXTURE0); //prog->setUniform("Tex2", 0); //cout<<"Draw "<<i<<endl; } glDrawElements(GL_TRIANGLES, meshEntries[i].numIndices, GL_UNSIGNED_INT, 0); } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } bool CAssimpModel::initMaterial(const aiScene* pScene, const string& filePath) { string::size_type slashIndex = filePath.find_last_of("/"); string dir; if (slashIndex == string::npos) { dir = "."; } else if (slashIndex == 0) { dir = "/"; } else { dir = filePath.substr(0, slashIndex); } bool Ret = true; // Initialize the materials for (unsigned int i = 1 ; i < pScene->mNumMaterials ; i++) { const aiMaterial* pMaterial = pScene->mMaterials[i]; textures[i] = NULL; if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0) { aiString path; if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { string fullPath = dir + "/" + path.data; textures[i] = new CTexture(GL_TEXTURE_2D, fullPath.c_str()); if (!textures[i]->load()) { printf("Error loading texture '%s'\n", fullPath.c_str()); delete textures[i]; textures[i] = NULL; Ret = false; } else { printf("Loaded texture '%s'\n", fullPath.c_str()); } } } // Load a white texture in case the model does not include its own texture if (textures[i]==NULL) { textures[i] = new CTexture(GL_TEXTURE_2D, "../assets/textures/white.png"); Ret = textures[i]->load(); } } return Ret; }
29.072727
129
0.606473
SilangQuan
c296eb02ac947debd8533b4c2d2560259157a2e0
13,691
cpp
C++
Cores/Mednafen/mednafen/src/compress/ZIPReader.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
Cores/Mednafen/mednafen/src/compress/ZIPReader.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
1,046
2018-03-24T17:56:16.000Z
2022-03-23T08:13:09.000Z
Cores/Mednafen/mednafen/src/compress/ZIPReader.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
/******************************************************************************/ /* Mednafen - Multi-system Emulator */ /******************************************************************************/ /* ZIPReader.cpp: ** Copyright (C) 2018 Mednafen Team ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software Foundation, Inc., ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // TODO: 64-bit ZIP support(limit sizes to 2**63 - 2?) // TODO: Stream::clone() #include <mednafen/mednafen.h> #include "ZIPReader.h" #include "ZLInflateFilter.h" namespace Mednafen { class StreamViewFilter : public Stream { public: StreamViewFilter(Stream* source_stream, const std::string& vfc, uint64 sp, uint64 bp, uint64 expcrc32 = ~(uint64)0); virtual ~StreamViewFilter() override; virtual uint64 read(void *data, uint64 count, bool error_on_eos = true) override; virtual void write(const void *data, uint64 count) override; virtual void seek(int64 offset, int whence) override; virtual uint64 tell(void) override; virtual uint64 size(void) override; virtual void close(void) override; virtual uint64 attributes(void) override; virtual void truncate(uint64 length) override; virtual void flush(void) override; private: Stream* ss; uint64 ss_start_pos; uint64 ss_bound_pos; uint64 pos; uint32 running_crc32; uint64 running_crc32_posreached; uint64 expected_crc32; const std::string vfcontext; }; StreamViewFilter::StreamViewFilter(Stream* source_stream, const std::string& vfc, uint64 sp, uint64 bp, uint64 expcrc32) : ss(source_stream), ss_start_pos(sp), ss_bound_pos(bp), pos(0), running_crc32(0), running_crc32_posreached(0), expected_crc32(expcrc32), vfcontext(vfc) { if(ss_bound_pos < ss_start_pos) throw MDFN_Error(0, _("StreamViewFilter() bound_pos < start_pos")); if((ss_bound_pos - ss_start_pos) > INT64_MAX) throw MDFN_Error(0, _("StreamViewFilter() size too large")); } StreamViewFilter::~StreamViewFilter() { } uint64 StreamViewFilter::read(void *data, uint64 count, bool error_on_eos) { uint64 cc = count; uint64 ret; cc = std::min<uint64>(cc, ss_bound_pos - ss_start_pos); cc = std::min<uint64>(cc, ss_bound_pos - std::min<uint64>(ss_bound_pos, pos)); if(cc < count && error_on_eos) throw MDFN_Error(0, _("Error reading from %s: %s"), vfcontext.c_str(), _("Unexpected EOF")); if(ss->tell() != (ss_start_pos + pos)) ss->seek(ss_start_pos + pos, SEEK_SET); ret = ss->read(data, cc, error_on_eos); pos += ret; if(expected_crc32 != ~(uint64)0) { if(pos > running_crc32_posreached && (pos - ret) <= running_crc32_posreached) { running_crc32 = crc32(running_crc32, (Bytef*)data + (running_crc32_posreached - (pos - ret)), pos - running_crc32_posreached); running_crc32_posreached = pos; if(running_crc32_posreached == (ss_bound_pos - ss_start_pos)) { if(running_crc32 != expected_crc32) throw MDFN_Error(0, _("Error reading from %s: %s"), vfcontext.c_str(), _("Data fails CRC32 check.")); } } } return ret; } void StreamViewFilter::write(const void *data, uint64 count) { #if 0 uint64 cc = count; uint64 ret; cc = std::min<uint64>(cc, ss_bound_pos - ss_start_pos); cc = std::min<uint64>(cc, ss_bound_pos - std::min<uint64>(ss_bound_pos, pos)); if(cc < count) throw MDFN_Error(0, _("ASDF")); if(ss->tell() != (ss_start_pos + pos)) ss->seek(ss_start_pos + pos, SEEK_SET); ss->write(data, cc); pos += cc; #endif throw MDFN_Error(ErrnoHolder(EINVAL)); } void StreamViewFilter::seek(int64 offset, int whence) { #if 0 uint64 new_pos = pos; if(whence == SEEK_SET) { //if(offset < 0) // throw MDFN_Error(EINVAL, _("Attempted to seek before start of stream.")); new_pos = (uint64)offset; } else if(whence == SEEK_CUR) { if(offset < 0 && (uint64)-(uint64)offset > (pos - ss_start_pos)) throw MDFN_Error(EINVAL, _("Attempted to seek before start of stream.")); } else if(whence == SEEK_END) { if(offset < 0 && (uint64)-(uint64)offset > (ss_bound_pos - ss_start_pos)) throw MDFN_Error(EINVAL, _("Attempted to seek before start of stream.")); } #endif int64 new_pos = pos; if(whence == SEEK_SET) new_pos = offset; else if(whence == SEEK_CUR) new_pos = pos + offset; else if(whence == SEEK_END) new_pos = (ss_bound_pos - ss_start_pos) + offset; if(new_pos < 0) throw MDFN_Error(EINVAL, _("Error seeking in %s: %s"), vfcontext.c_str(), _("Attempted to seek before start of stream.")); pos = new_pos; } uint64 StreamViewFilter::tell(void) { return pos; } uint64 StreamViewFilter::size(void) { return ss_bound_pos - ss_start_pos; } void StreamViewFilter::close(void) { ss = nullptr; } uint64 StreamViewFilter::attributes(void) { return ss->attributes(); } void StreamViewFilter::truncate(uint64 length) { //ss->truncate(ss_start_pos + length); throw MDFN_Error(ErrnoHolder(EINVAL)); } void StreamViewFilter::flush(void) { ss->flush(); } Stream* ZIPReader::open(size_t which) { const auto& e = entries[which]; zs->seek(e.lh_reloffs, SEEK_SET); struct { uint32 sig; uint16 version_need; uint16 gpflags; uint16 method; uint16 mod_time; uint16 mod_date; uint32 crc32; uint32 comp_size; uint32 uncomp_size; uint16 name_len; uint16 extra_len; } lfh; uint8 lfh_raw[0x1E]; if(zs->read(lfh_raw, sizeof(lfh_raw), false) != sizeof(lfh_raw)) throw MDFN_Error(0, _("Unexpected EOF when reading ZIP Local File Header.")); lfh.sig = MDFN_de32lsb(&lfh_raw[0x00]); lfh.version_need = MDFN_de16lsb(&lfh_raw[0x04]); lfh.gpflags = MDFN_de16lsb(&lfh_raw[0x06]); lfh.method = MDFN_de16lsb(&lfh_raw[0x08]); lfh.mod_time = MDFN_de16lsb(&lfh_raw[0x0A]); lfh.mod_date = MDFN_de16lsb(&lfh_raw[0x0C]); lfh.crc32 = MDFN_de32lsb(&lfh_raw[0x0E]); lfh.comp_size = MDFN_de32lsb(&lfh_raw[0x12]); lfh.uncomp_size = MDFN_de32lsb(&lfh_raw[0x16]); lfh.name_len = MDFN_de16lsb(&lfh_raw[0x1A]); lfh.extra_len = MDFN_de16lsb(&lfh_raw[0x1C]); if(lfh.sig != 0x04034B50) throw MDFN_Error(0, _("Bad Local File Header signature.")); if(lfh.method != e.method) throw MDFN_Error(0, _("Mismatch of compression method between Central Directory(%d) and Local File Header(%d)."), e.method, lfh.method); if(lfh.gpflags & 0x1) throw MDFN_Error(0, _("ZIP decryption support not implemented.")); if(e.method != 0 && e.method != 8 && e.method != 9) throw MDFN_Error(0, _("ZIP compression method %u not implemented."), e.method); zs->seek(lfh.name_len + lfh.extra_len, SEEK_CUR); std::string vfcontext = MDFN_sprintf(_("opened file \"%s\" in ZIP archive"), e.name.c_str()); if(e.method == 0) { uint64 start_pos = zs->tell(); uint64 bound_pos = start_pos + e.uncomp_size; return new StreamViewFilter(zs.get(), vfcontext, start_pos, bound_pos, e.crc32); } else if(e.method == 8) return new ZLInflateFilter(zs.get(), vfcontext, ZLInflateFilter::FORMAT::RAW, e.comp_size, e.uncomp_size, e.crc32); else throw MDFN_Error(0, _("ZIP compression method %u not implemented."), lfh.method); } ZIPReader::~ZIPReader() { } ZIPReader::ZIPReader(std::unique_ptr<Stream> s) : VirtualFS('/', "/") { const uint64 size = s->size(); if(size < 22) throw MDFN_Error(0, _("Too small to be a ZIP file.")); const uint64 scan_size = std::min<uint64>(size, 65535 + 22); std::unique_ptr<uint8[]> buf(new uint8[scan_size]); const uint8* eocdrp = nullptr; s->seek(size - scan_size, SEEK_SET); s->read(&buf[0], scan_size); for(size_t scan_pos = scan_size - 22; scan_pos != ~(size_t)0; scan_pos--) { if(MDFN_de32lsb(&buf[scan_pos]) == 0x06054B50) { eocdrp = &buf[scan_pos]; break; } } if(!eocdrp) throw MDFN_Error(0, _("ZIP End of Central Directory Record not found!")); // // // struct { uint32 sig; uint16 disk; uint16 cd_start_disk; uint16 disk_cde_count; uint16 total_cde_count; uint32 cd_size; uint32 cd_offs; uint16 comment_size; } eocdr; eocdr.sig = MDFN_de32lsb(&eocdrp[0x00]); eocdr.disk = MDFN_de16lsb(&eocdrp[0x04]); eocdr.cd_start_disk = MDFN_de16lsb(&eocdrp[0x06]); eocdr.disk_cde_count = MDFN_de16lsb(&eocdrp[0x08]); eocdr.total_cde_count = MDFN_de16lsb(&eocdrp[0x0A]); eocdr.cd_size = MDFN_de32lsb(&eocdrp[0x0C]); eocdr.cd_offs = MDFN_de32lsb(&eocdrp[0x10]); eocdr.comment_size = MDFN_de16lsb(&eocdrp[0x14]); if((eocdr.disk != eocdr.cd_start_disk) || eocdr.disk != 0 || (eocdr.disk_cde_count != eocdr.total_cde_count)) throw MDFN_Error(0, _("ZIP split archive support not implemented.")); if(eocdr.cd_offs >= size) throw MDFN_Error(0, _("ZIP Central Directory start offset is bad.")); s->seek(eocdr.cd_offs, SEEK_SET); for(uint32 i = 0; i < eocdr.total_cde_count; i++) { uint8 cdr_raw[46]; FileDesc d; if(s->read(cdr_raw, sizeof(cdr_raw), false) != sizeof(cdr_raw)) throw MDFN_Error(0, _("Unexpected EOF when reading ZIP Central Directory entry %u"), i); d.sig = MDFN_de32lsb(&cdr_raw[0x00]); d.version_made = MDFN_de16lsb(&cdr_raw[0x04]); d.version_need = MDFN_de16lsb(&cdr_raw[0x06]); d.gpflags = MDFN_de16lsb(&cdr_raw[0x08]); d.method = MDFN_de16lsb(&cdr_raw[0x0A]); d.mod_time = MDFN_de16lsb(&cdr_raw[0x0C]); d.mod_date = MDFN_de16lsb(&cdr_raw[0x0E]); d.crc32 = MDFN_de32lsb(&cdr_raw[0x10]); d.comp_size = MDFN_de32lsb(&cdr_raw[0x14]); d.uncomp_size = MDFN_de32lsb(&cdr_raw[0x18]); d.name_len = MDFN_de16lsb(&cdr_raw[0x1C]); d.extra_len = MDFN_de16lsb(&cdr_raw[0x1E]); d.comment_len = MDFN_de16lsb(&cdr_raw[0x20]); d.disk_start = MDFN_de16lsb(&cdr_raw[0x22]); d.int_attr = MDFN_de16lsb(&cdr_raw[0x24]); d.ext_attr = MDFN_de32lsb(&cdr_raw[0x26]); d.lh_reloffs = MDFN_de32lsb(&cdr_raw[0x2A]); if(d.sig != 0x02014B50) throw MDFN_Error(0, _("Bad signature in ZIP Central Directory entry %u"), i); if(d.disk_start != 0) throw MDFN_Error(0, _("ZIP split archive support not implemented.")); if(d.lh_reloffs >= size) throw MDFN_Error(0, _("Bad local header relative offset in ZIP Central Directory entry %u"), i); d.name.resize(1 + d.name_len); d.name[0] = '/'; if(s->read(&d.name[1], d.name_len, false) != d.name_len) throw MDFN_Error(0, _("Unexpected EOF when reading ZIP Central Directory entry %u"), i); s->seek(d.extra_len + d.comment_len, SEEK_CUR); entries.push_back(d); } zs = std::move(s); } size_t ZIPReader::find_by_path(const std::string& path) { for(size_t i = 0; i < entries.size(); i++) { if(path == entries[i].name) return i; } return SIZE_MAX; } Stream* ZIPReader::open(const std::string& path, const uint32 mode, const int do_lock, const bool throw_on_noent, const CanaryType canary) { if(mode != MODE_READ) throw MDFN_Error(EINVAL, _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), _("Specified mode is unsupported")); if(do_lock != 0) throw MDFN_Error(EINVAL, _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), _("Locking requested but is unsupported")); size_t which = find_by_path(path); if(which == SIZE_MAX) { ErrnoHolder ene(ENOENT); throw MDFN_Error(ene.Errno(), _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), ene.StrError()); } try { return open(which); } catch(const MDFN_Error& e) { throw MDFN_Error(e.GetErrno(), _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), e.what()); } } bool ZIPReader::mkdir(const std::string& path, const bool throw_on_exist) { throw MDFN_Error(EINVAL, _("Error creating directory \"%s\" in ZIP archive: %s"), path.c_str(), _("ZIPReader::mkdir() not implemented")); } bool ZIPReader::unlink(const std::string& path, const bool throw_on_noent, const CanaryType canary) { throw MDFN_Error(EINVAL, _("Error unlinking \"%s\" in ZIP archive: %s"), path.c_str(), _("ZIPReader::unlink() not implemented")); } void ZIPReader::rename(const std::string& oldpath, const std::string& newpath, const CanaryType canary) { throw MDFN_Error(EINVAL, _("Error renaming \"%s\" to \"%s\" in ZIP archive: %s"), oldpath.c_str(), newpath.c_str(), _("ZIPReader::rename() not implemented")); } bool ZIPReader::finfo(const std::string& path, FileInfo* fi, const bool throw_on_noent) { size_t which = find_by_path(path); if(which == SIZE_MAX) { ErrnoHolder ene(ENOENT); if(throw_on_noent) throw MDFN_Error(ene.Errno(), _("Error getting file information for \"%s\" in ZIP archive: %s"), path.c_str(), ene.StrError()); return false; } if(fi) { FileInfo new_fi; new_fi.size = entries[which].uncomp_size; // TODO/FIXME: new_fi.mtime_us = 0; new_fi.is_regular = true; new_fi.is_directory = false; *fi = new_fi; } return true; } void ZIPReader::readdirentries(const std::string& path, std::function<bool(const std::string&)> callb) { // TODO/FIXME: throw MDFN_Error(EINVAL, _("ZIPReader::readdirentries() not implemented.")); } bool ZIPReader::is_absolute_path(const std::string& path) { if(!path.size()) return false; if(is_path_separator(path[0])) return true; return false; } void ZIPReader::check_firop_safe(const std::string& path) { } }
28.112936
273
0.685122
ianclawson
c2972e88d70fafb760fb515fa62b78a59a21c5b0
120
hxx
C++
src/Providers/UNIXProviders/PrintService/UNIX_PrintService_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/PrintService/UNIX_PrintService_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/PrintService/UNIX_PrintService_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_LINUX #ifndef __UNIX_PRINTSERVICE_PRIVATE_H #define __UNIX_PRINTSERVICE_PRIVATE_H #endif #endif
10
37
0.841667
brunolauze
c2a26d79cf0d1470a475fc70cb9b5b1b8af20132
3,285
cpp
C++
Engine_Rendering/source/MeshRenderer.cpp
subr3v/s-engine
d77b9ccd0fff3982a303f14ce809691a570f61a3
[ "MIT" ]
2
2016-04-01T21:10:33.000Z
2018-02-26T19:36:56.000Z
Engine_Rendering/source/MeshRenderer.cpp
subr3v/s-engine
d77b9ccd0fff3982a303f14ce809691a570f61a3
[ "MIT" ]
1
2017-04-05T01:33:08.000Z
2017-04-05T01:33:08.000Z
Engine_Rendering/source/MeshRenderer.cpp
subr3v/s-engine
d77b9ccd0fff3982a303f14ce809691a570f61a3
[ "MIT" ]
null
null
null
#include "MeshRenderer.h" #include "Mesh.h" #include "Material.h" #include "Texture.h" #include "ConstantBufferTypes.h" void FMeshRenderer::Render(const FMesh* Mesh, const FDrawCall& DrawCallParameters, bool bUseTessellation) { assert(Mesh); FProfiler::Get().ProfileCounter("Rendering", "Mesh Draw Call", true, 1); ID3D11DeviceContext* DeviceContext = DrawCallParameters.DeviceContext; DeviceContext->IASetPrimitiveTopology(bUseTessellation ? D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST : D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); Mesh->BindBuffers(DeviceContext); int PreviousMaterialIndex = -1; FMaterial* CurrentMaterial = nullptr; if (DrawCallParameters.OverrideMaterial == false && DrawCallParameters.StandardMaterial == nullptr) { for (FMeshPart Part : Mesh->GetParts()) { if (PreviousMaterialIndex != Part.MaterialIndex) { PreviousMaterialIndex = Part.MaterialIndex; const FMeshMaterialParameters& ParametersData = Mesh->GetParameters(Part.MaterialIndex); CurrentMaterial = ParametersData.Material; FMaterialParameters* Parameters = CurrentMaterial->GetParameters(); ParametersData.Apply(DeviceContext, Parameters); Parameters->UpdateUniform(DeviceContext, FInstanceBuffer::kBufferName, (void*)DrawCallParameters.InstanceData, sizeof(FInstanceBuffer)); FProfiler::Get().ProfileCounter("Rendering", "Mesh Material State Change", true, 1); CurrentMaterial->Apply(DeviceContext); } DrawCallParameters.DrawIndexed(Part.IndexCount, Part.IndexStart, Part.BaseVertex); } } else if (DrawCallParameters.OverrideMaterial) { for (FMeshPart Part : Mesh->GetParts()) { if (PreviousMaterialIndex != Part.MaterialIndex) { PreviousMaterialIndex = Part.MaterialIndex; const FMeshMaterialParameters& ParametersData = Mesh->GetParameters(Part.MaterialIndex); CurrentMaterial = DrawCallParameters.OverrideMaterial(ParametersData.Material); FMaterialParameters* Parameters = CurrentMaterial->GetParameters(); ParametersData.Apply(DeviceContext, Parameters); Parameters->UpdateUniform(DeviceContext, FInstanceBuffer::kBufferName, (void*)DrawCallParameters.InstanceData, sizeof(FInstanceBuffer)); FProfiler::Get().ProfileCounter("Rendering", "Mesh Material State Change", true, 1); CurrentMaterial->Apply(DeviceContext); } DrawCallParameters.DrawIndexed(Part.IndexCount, Part.IndexStart, Part.BaseVertex); } } else if (DrawCallParameters.StandardMaterial) { for (FMeshPart Part : Mesh->GetParts()) { if (PreviousMaterialIndex != Part.MaterialIndex) { PreviousMaterialIndex = Part.MaterialIndex; const FMeshMaterialParameters& ParametersData = Mesh->GetParameters(Part.MaterialIndex); CurrentMaterial = DrawCallParameters.StandardMaterial; FMaterialParameters* Parameters = CurrentMaterial->GetParameters(); ParametersData.Apply(DeviceContext, Parameters); Parameters->UpdateUniform(DeviceContext, FInstanceBuffer::kBufferName, (void*)DrawCallParameters.InstanceData, sizeof(FInstanceBuffer)); FProfiler::Get().ProfileCounter("Rendering", "Mesh Material State Change", true, 1); CurrentMaterial->Apply(DeviceContext); } DrawCallParameters.DrawIndexed(Part.IndexCount, Part.IndexStart, Part.BaseVertex); } } }
35.706522
150
0.773212
subr3v
c2a2a5c7aff964f2f59b9f0575c7031ff14fc8f2
2,168
cpp
C++
src/particle_emitter.cpp
devdor/GLDevdor04
1c3c83b7a3d629e59a370519ceff10b13889ea48
[ "MIT" ]
null
null
null
src/particle_emitter.cpp
devdor/GLDevdor04
1c3c83b7a3d629e59a370519ceff10b13889ea48
[ "MIT" ]
null
null
null
src/particle_emitter.cpp
devdor/GLDevdor04
1c3c83b7a3d629e59a370519ceff10b13889ea48
[ "MIT" ]
null
null
null
#include "../includes/particle_emitter.hpp" #include <random> CParticleEmitter::CParticleEmitter() : m_maxParticles(100) { } void CParticleEmitter::Init(int maxParticles) { this->m_maxParticles = maxParticles; this->CreateParticles(); } // Initalizes a single particle according to its type void CParticleEmitter::CreateParticle(CParticle *p) { p->lifespan = (((rand() % 125 + 1) / 10.0f) + 5); p->type = 2; p->age = 0.0f; p->scale = 0.25f; p->direction = 0; p->position = glm::vec3(0.0f, 0.0f, 0.0f); p->movement.x = (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.035) - (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.035); p->movement.y = ((((((5) * rand() % 11) + 3)) * rand() % 11) + 7) * 0.015; p->movement.z = (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.015) - (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.015); p->movement.x = p->movement.x / 2; p->movement.y = p->movement.y / 2; p->movement.z = p->movement.z / 2; // rotation p->rotation.x = (double)rand() / (RAND_MAX + 1.0); p->rotation.y = (double)rand() / (RAND_MAX + 1.0); p->rotation.z = (double)rand() / (RAND_MAX + 1.0); p->pull.x = 0.0f; p->pull.y = 0.0f; p->pull.z = 0.0f; } void CParticleEmitter::CreateParticles(void) { for (int i=0; i < this->m_maxParticles; i++) { CParticle* p = new CParticle(); this->CreateParticle(p); this->m_Particles.push_back(p); } } void CParticleEmitter::UpdateParticles() { int i = 0; for (std::vector<CParticle*>::iterator it = this->m_Particles.begin(); it != this->m_Particles.end(); ++it) { CParticle* p = (*it); p->age = p->age + 0.015; p->direction = p->direction + ((((((int)(0.5) * rand() % 11) + 1)) * rand() % 11) + 1); p->position.x = p->position.x + p->movement.x / 2 + p->pull.x / 2; p->position.y = p->position.y + p->movement.y / 2 + p->pull.y / 2; p->position.z = p->position.z + p->movement.z / 2 + p->pull.z / 2; if (p->age > p->lifespan || p->position.y > 19 || p->position.y < -15 || p->position.x > 18 || p->position.x < -18) this->CreateParticle(p); } }
28.906667
140
0.539668
devdor
c2a49a527ecabb3bd0cc533f17a3527d3ff9ff48
13,888
cpp
C++
src/RawImport/FAA_Obs.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/RawImport/FAA_Obs.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/RawImport/FAA_Obs.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2004, Laminar Research. * * 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 "FAA_Obs.h" #include "MemFileUtils.h" #include "ParamDefs.h" #include "SimpleIO.h" #include "DEMDefs.h" #include "MapDefs.h" #include "MapAlgs.h" #include "GISTool_Globals.h" #include <CGAL/Arr_walk_along_line_point_location.h> FAAObsTable gFAAObs; const char * gObsNames [] = { "AM_RADIO_TOWER", "POLE", "TOWERS", "TOWER", "CRANE", "CATENARY", "BLDG", "CTRL TWR", "T-L TWR", "ELEVATOR", "WINDMILL", "RIG", "STACK", "REFINERY", "TANK", "BLDG-TWR", "TRAMWAY", "STACKS", "SPIRE", "CRANE T", "PLANT", "DOME", "SIGN", "BRIDGE", "ARCH", "COOL TWR", "MONUMENT", "BALLOON", "DAM", 0 }; static int kFeatureTypes [] = { feat_RadioTower, feat_Pole, feat_RadioTower, feat_RadioTower, feat_Crane, NO_VALUE, // "CATENARY", feat_Building, NO_VALUE, // "CTRL TWR", NO_VALUE, // "T-L TWR", feat_Elevator, feat_Windmill, NO_VALUE, // "RIG", feat_Smokestack, feat_Refinery, feat_Tank, feat_Building, feat_Tramway, feat_Smokestacks, feat_Spire, feat_Crane, feat_Plant, feat_Dome, feat_Sign, NO_VALUE, // "BRIDGE", feat_Arch, feat_CoolingTower, feat_Monument, NO_VALUE, // "BALLOON", feat_Dam, 0 }; static int kConvertLegacyObjTypes[] = { NO_VALUE, NO_VALUE, // feat_Skyscraper, feat_Building, // BEN SAYS: importing as sky-scraper means no obj match. :-( feat_RadioTower, NO_VALUE, feat_CoolingTower, feat_Smokestack, NO_VALUE }; static int kRobinToFeatures[] = { NO_VALUE, NO_VALUE, feat_BeaconNDB, feat_BeaconVOR, feat_BeaconILS, feat_BeaconLDA, feat_BeaconGS, feat_MarkerBeacon, feat_MarkerBeacon, feat_MarkerBeacon }; static int GetObjType(const char * str) { int n = 0; while (gObsNames[n]) { if (!strcmp(gObsNames[n],str)) return n; ++n; } return 0; } bool LoadFAARadarFile(const char * inFile, bool isApproach) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { const char * c = TextScanner_GetBegin(s); if (*c == '_') { TextScanner_Next(s); break; } TextScanner_Next(s); } while (!TextScanner_IsDone(s)) { const char * c = TextScanner_GetBegin(s); if (*c == '_') { TextScanner_Next(s); break; } TextScanner_Next(s); } while (!TextScanner_IsDone(s)) { FAAObs_t obs; const char * lp = TextScanner_GetBegin(s); int o = isApproach ? 46 : 59; if (lp[59] != ' ') { double lat_deg_tens = lp[o ] - '0'; double lat_deg_ones = lp[o+1] - '0'; double lat_min_tens = lp[o+3] - '0'; double lat_min_ones = lp[o+4] - '0'; double lat_sec_tens = lp[o+6] - '0'; double lat_sec_ones = lp[o+7] - '0'; double lat_hun_tens = lp[o+9] - '0'; double neg = (lp[o+10] != 'S') ? 1.0 : -1.0; obs.lat = neg * (lat_deg_tens * 10.0 + lat_deg_ones * 1.0 + lat_min_tens * 10.0 / 60.0 + lat_min_ones * 1.0 / 60.0 + lat_sec_tens * 10.0 / 3600.0 + lat_sec_ones * 1.0 / 3600.0 + lat_hun_tens * 10.0 / 360000.0); o = isApproach ? 59 : 71; double lon_deg_huns = lp[o ] - '0'; double lon_deg_tens = lp[o+1] - '0'; double lon_deg_ones = lp[o+2] - '0'; double lon_min_tens = lp[o+4] - '0'; double lon_min_ones = lp[o+5] - '0'; double lon_sec_tens = lp[o+7] - '0'; double lon_sec_ones = lp[o+8] - '0'; double lon_hun_tens = lp[o+10] - '0'; neg = (lp[o+11] == 'E') ? 1.0 : -1.0; obs.lon = neg * (lon_deg_huns * 100.0 + lon_deg_tens * 10.0 + lon_deg_ones * 1.0 + lon_min_tens * 10.0 / 60.0 + lon_min_ones * 1.0 / 60.0 + lon_sec_tens * 10.0 / 3600.0 + lon_sec_ones * 1.0 / 3600.0 + lon_hun_tens * 10.0 / 360000.0); obs.agl = TextScanner_ExtractLong(s, 73, 77) * 0.3048; obs.msl = TextScanner_ExtractLong(s, 78, 83) * 0.3048; if (isApproach) { obs.agl = TextScanner_ExtractLong(s,20,23); obs.msl = obs.agl + TextScanner_ExtractLong(s,71,76); obs.kind = feat_RadarASR; } else { obs.agl = NO_VALUE; obs.msl = TextScanner_ExtractLong(s,85,90); obs.kind = feat_RadarARSR; } gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); #if 0 printf(" %lf,%lf %f (%f) %d (%s) '%s' (%s)\n", obs.lon, obs.lat, obs.msl, obs.agl, obs.kind, FetchTokenString(obs.kind), obs.kind_str.c_str(), obs.freq.c_str()); #endif } TextScanner_Next(s); } ok = true; bail: if (f) MemFile_Close(f); if (s) TextScanner_Close(s); return ok; } bool LoadFAAObsFile(const char * inFile) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { const char * c = TextScanner_GetBegin(s); if (*c == '-') { TextScanner_Next(s); break; } TextScanner_Next(s); } while (!TextScanner_IsDone(s)) { FAAObs_t obs; TextScanner_ExtractString(s,58, 66, obs.kind_str, true); TextScanner_ExtractString(s,68, 72, obs.freq, true); if (!obs.freq.empty()) obs.kind = 0; else obs.kind = GetObjType(obs.kind_str.c_str()); obs.kind = kFeatureTypes[obs.kind]; const char * lp = TextScanner_GetBegin(s); double lat_deg_tens = lp[29] - '0'; double lat_deg_ones = lp[30] - '0'; double lat_min_tens = lp[32] - '0'; double lat_min_ones = lp[33] - '0'; double lat_sec_tens = lp[35] - '0'; double lat_sec_ones = lp[36] - '0'; double lat_hun_tens = lp[38] - '0'; double lat_hun_ones = lp[39] - '0'; double neg = (lp[40] != 'S') ? 1.0 : -1.0; obs.lat = neg * (lat_deg_tens * 10.0 + lat_deg_ones * 1.0 + lat_min_tens * 10.0 / 60.0 + lat_min_ones * 1.0 / 60.0 + lat_sec_tens * 10.0 / 3600.0 + lat_sec_ones * 1.0 / 3600.0 + lat_hun_tens * 10.0 / 360000.0 + lat_hun_ones * 1.0 / 360000.0); double lon_deg_huns = lp[43] - '0'; double lon_deg_tens = lp[44] - '0'; double lon_deg_ones = lp[45] - '0'; double lon_min_tens = lp[47] - '0'; double lon_min_ones = lp[48] - '0'; double lon_sec_tens = lp[50] - '0'; double lon_sec_ones = lp[51] - '0'; double lon_hun_tens = lp[53] - '0'; double lon_hun_ones = lp[54] - '0'; neg = (lp[55] == 'E') ? 1.0 : -1.0; obs.lon = neg * (lon_deg_huns * 100.0 + lon_deg_tens * 10.0 + lon_deg_ones * 1.0 + lon_min_tens * 10.0 / 60.0 + lon_min_ones * 1.0 / 60.0 + lon_sec_tens * 10.0 / 3600.0 + lon_sec_ones * 1.0 / 3600.0 + lon_hun_tens * 10.0 / 360000.0 + lon_hun_ones * 1.0 / 360000.0); obs.agl = TextScanner_ExtractLong(s, 73, 77) * 0.3048; obs.msl = TextScanner_ExtractLong(s, 78, 83) * 0.3048; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); #if 0 //DEV printf(" %lf,%lf %f (%f) %d (%s) '%s' (%s)\n", obs.lon, obs.lat, obs.msl, obs.agl, obs.kind, FetchTokenString(obs.kind), obs.kind_str.c_str(), obs.freq.c_str()); #endif TextScanner_Next(s); } ok = true; bail: if (f) MemFile_Close(f); if (s) TextScanner_Close(s); return ok; } bool WriteDegFile(const char * inFile, int lon, int lat) { pair<FAAObsTable::iterator,FAAObsTable::iterator> range = gFAAObs.equal_range(HashLonLat(lon,lat)); if (range.first == range.second) return true; FILE * fi = fopen(inFile, "w"); if (!fi) return false; fprintf(fi, "# lon lat msl agl kind\n"); for (FAAObsTable::iterator i = range.first; i != range.second; ++i) { if (i->second.kind != NO_VALUE) fprintf(fi, "%lf %lf %f %f %s\n", i->second.lon, i->second.lat, i->second.msl, i->second.agl, FetchTokenString(i->second.kind)); } fclose(fi); return 1; } bool ReadDegFile(const char * inFile) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { const char * l = TextScanner_GetBegin(s); if (*l != '#') { FAAObs_t obs; char buf[256]; if (sscanf(l, "%lf %lf %f %f %s", &obs.lon, &obs.lat, &obs.msl, &obs.agl, buf) == 5) { // printf("Got: %lf %lf %f %f %s\n", // obs.lon, obs.lat, obs.msl, obs.agl, buf); obs.kind = LookupToken(buf); gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } } TextScanner_Next(s); } ok = true; bail: if (s) TextScanner_Close(s); if (f) MemFile_Close(f); return ok; } bool ReadAPTNavAsObs(const char * inFile) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; FAAObs_t obs; int rec_type; double lat, lon; int beacon_type; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { if (TextScanner_FormatScan(s, "i", &rec_type) == 1) { switch(rec_type) { case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: if (TextScanner_FormatScan(s, "idd", &rec_type, &lat, &lon) == 3) { obs.kind = kRobinToFeatures[rec_type]; obs.lat = lat; obs.lon = lon; obs.agl = obs.msl = DEM_NO_DATA; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } break; case 19: if (TextScanner_FormatScan(s, "idd", &rec_type, &lat, &lon) == 3) { obs.kind = feat_Windsock; obs.lon = lon; obs.lat = lat; obs.agl = DEM_NO_DATA; obs.msl = DEM_NO_DATA; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } break; case 18: if (TextScanner_FormatScan(s, "iddi", &rec_type, &lat, &lon, &beacon_type) == 4) if (beacon_type == 1 || beacon_type == 4) // Land airport or military field { obs.kind = feat_RotatingBeacon; obs.lon = lon; obs.lat = lat; obs.agl = DEM_NO_DATA; obs.msl = DEM_NO_DATA; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } break; } } TextScanner_Next(s); } ok = true; bail: if (s) TextScanner_Close(s); if (f) MemFile_Close(f); return ok; } bool LoadLegacyObjectArchive(const char * inFile) { MFMemFile * f = MemFile_Open(inFile); MemFileReader reader(MemFile_GetBegin(f), MemFile_GetEnd(f), platform_BigEndian); int count; reader.ReadInt(count); while (count--) { double lat, lon, ele; int kind; reader.ReadInt(kind); reader.ReadDouble(lat); reader.ReadDouble(lon); reader.ReadDouble(ele); if (kind == 8) { char c; do { reader.ReadBulk(&c, 1,false); } while (c != 0); } else { FAAObs_t obs; obs.agl = ele * FT_TO_MTR; obs.msl = DEM_NO_DATA; obs.lat = lat; obs.lon = lon; obs.kind = kConvertLegacyObjTypes[kind]; if (obs.kind != NO_VALUE) gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } } MemFile_Close(f); return true; } void ApplyObjects(Pmwx& ioMap) { if (gFAAObs.empty()) return; Point_2 sw, ne; CalcBoundingBox(ioMap, sw, ne); // ioMap.Index(); int placed = 0; // CGAL::Arr_landmarks_point_location<Arrangement_2> locator(gMap); CGAL::Arr_walk_along_line_point_location<Arrangement_2> locator(gMap); for (FAAObsTable::iterator i = gFAAObs.begin(); i != gFAAObs.end(); ++i) { if (i->second.kind != NO_VALUE) { Point_2 loc = Point_2(i->second.lon, i->second.lat); DebugAssert(CGAL::is_valid(gMap)); CGAL::Object obj = locator.locate(loc); Face_const_handle ff; if(CGAL::assign(ff,obj)) { Face_handle f = ioMap.non_const_handle(ff); GISPointFeature_t feat; feat.mFeatType = i->second.kind; feat.mLocation = loc; if (i->second.agl != DEM_NO_DATA) feat.mParams[pf_Height] = i->second.agl; feat.mInstantiated = false; f->data().mPointFeatures.push_back(feat); ++placed; #if 0 printf("Placed %s at %lf, %lf\n", FetchTokenString(i->second.kind), i->second.lon, i->second.lat); #endif // if (v.size() > 1) // fprintf(stderr,"WARNING (%d,%d): Point feature %lf, %lf matches multiple areas.\n",gMapWest, gMapSouth, CGAL::to_double(loc.x()), CGAL::to_double(loc.y())); } } } printf("Placed %d objects.\n", placed); } int GetObjMinMaxHeights(map<int, float>& mins, map<int, float>& maxs) { for (FAAObsTable::iterator obs = gFAAObs.begin(); obs != gFAAObs.end(); ++obs) if (obs->second.agl != DEM_NO_DATA) { if (mins.count(obs->second.kind) == 0) mins[obs->second.kind] = 999999; if (maxs.count(obs->second.kind) == 0) maxs[obs->second.kind] = 0; mins[obs->second.kind] = min(mins[obs->second.kind], obs->second.agl); maxs[obs->second.kind] = max(maxs[obs->second.kind], obs->second.agl); } return gFAAObs.size(); }
24.711744
163
0.6304
rromanchuk
c2a64753c35100b43c310732f3fd3ce81589c32c
594
cpp
C++
OOP/STL-Homework/Appointment.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/STL-Homework/Appointment.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/STL-Homework/Appointment.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
#include "Appointment.h" Appointment::Appointment(DateTime date, string description, string address, string personToMeet) : date(date), description(description), address(address), personToMeet(personToMeet){ } bool Appointment::operator<(Appointment &other) { return this->date < other.date; } ostream& Appointment::inserter(ostream& os) { os << this->date << endl; os << this->description << endl; os << this->address << endl; os << this->personToMeet; return os; } ostream& operator<<(ostream& os, Appointment &obj) { return obj.inserter(os); }
27
89
0.675084
Rossoner40
c2a97102efbc1be69c9a68a0d0b9a823af88eb6a
1,309
cpp
C++
Competitions/Skillenza/Code Golf Challenge 1/Fibonacci numbers 1.cpp
cnm06/Competitive-Programming
94242ae458570d503b8218f37624b88cc5020d23
[ "MIT" ]
994
2017-02-28T06:13:47.000Z
2022-03-31T10:49:00.000Z
Competitions/Skillenza/Code Golf Challenge 1/Fibonacci numbers 1.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
16
2018-01-01T02:59:55.000Z
2021-11-22T12:49:16.000Z
Competitions/Skillenza/Code Golf Challenge 1/Fibonacci numbers 1.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
325
2017-06-15T03:32:43.000Z
2022-03-28T22:43:42.000Z
#include <cstdio> #include <cstring> using namespace std; #define MAX_SIZE 3 const long long MOD = 1000000007; int size = 3; struct Matrix{ long long X[MAX_SIZE][MAX_SIZE]; Matrix(){} void init(){ memset(X,0,sizeof(X)); for(int i = 0;i<size;++i) X[i][i] = 1; } }aux,M0,ans; void mult(Matrix &m, Matrix &m1, Matrix &m2){ memset(m.X,0,sizeof(m.X)); for(int i = 0;i<size;++i) for(int j = 0;j<size;++j) for(int k = 0;k<size;++k) m.X[i][k] = (m.X[i][k]+m1.X[i][j]*m2.X[j][k])%MOD; } Matrix pow(Matrix &M0, int n){ Matrix ret; ret.init(); if(n==0) return ret; if(n==1) return M0; Matrix P = M0; while(n!=0){ if(n & 1){ aux = ret; mult(ret,aux,P); } n >>= 1; aux = P; mult(P,aux,aux); } return ret; } long long sum(int n){ if(n<=0) return 0; if(n==1) return 1; ans = pow(M0,n-1); return (ans.X[0][0]+ans.X[0][1])%MOD; } int main(){ M0.X[0][0] = 1; M0.X[0][1] = 1; M0.X[0][2] = 1; M0.X[1][0] = 0; M0.X[1][1] = 1; M0.X[1][2] = 1; M0.X[2][0] = 0; M0.X[2][1] = 1; M0.X[2][2] = 0; int T,N,M; scanf("%d",&T); while(T--){ scanf("%d %d",&N,&M); printf("%lld\n",((sum(M)-sum(N-1))%MOD+MOD)%MOD); } return 0; }
16.782051
66
0.468296
cnm06
c2aeab7dbee62387d6db1dcdfa1b659ff94ab490
2,358
cpp
C++
bin/manager/tests/api.cpp
ArcticNature/core
bb63529a6deadc83e5adc3b772738ab6ca6ba18a
[ "BSD-3-Clause" ]
null
null
null
bin/manager/tests/api.cpp
ArcticNature/core
bb63529a6deadc83e5adc3b772738ab6ca6ba18a
[ "BSD-3-Clause" ]
null
null
null
bin/manager/tests/api.cpp
ArcticNature/core
bb63529a6deadc83e5adc3b772738ab6ca6ba18a
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 Stefano Pogliani <stefano@spogliani.net> #include <fcntl.h> #include <gtest/gtest.h> #include "core/bin/manager/api/source.h" #include "core/context/static.h" #include "core/event/drain/null.h" #include "core/event/testing.h" #include "core/exceptions/base.h" #include "core/model/event.h" #include "core/protocols/public/p_message.pb.h" #include "core/utility/protobuf.h" #include "core/posix/user.h" using sf::core::bin::ApiFdSource; using sf::core::context::Static; using sf::core::event::NullDrain; using sf::core::event::TestFdDrain; using sf::core::exception::CorruptedData; using sf::core::exception::FactoryNotFound; using sf::core::model::EventDrainRef; using sf::core::model::EventRef; using sf::core::protocol::public_api::Message; using sf::core::utility::MessageIO; using sf::core::posix::User; class ApiSourceTest : public ::testing::Test { protected: int read_fd; int write_fd; ApiFdSource* api; EventDrainRef drain; public: ApiSourceTest() { Static::initialise(new User()); int pipe[2]; Static::posix()->pipe(pipe, O_NONBLOCK); this->read_fd = pipe[0]; this->write_fd = pipe[1]; this->api = new ApiFdSource( this->read_fd, "test", EventDrainRef(new NullDrain()) ); this->drain = EventDrainRef(new TestFdDrain(this->write_fd, "test")); } ~ApiSourceTest() { delete this->api; this->drain.reset(); Static::destroy(); } void write(const char* buffer) { Static::posix()->write(this->write_fd, buffer, strlen(buffer)); } void write(Message message) { MessageIO<Message>::send(this->drain, message); this->drain->flush(); } }; TEST_F(ApiSourceTest, FailCorruptData) { this->write(""); ASSERT_THROW(this->api->fetch(), CorruptedData); } TEST_F(ApiSourceTest, FailHandlerNotFound) { Message message; message.set_code(Message::Ack); this->write(message); ASSERT_THROW(this->api->fetch(), FactoryNotFound); } TEST_F(ApiSourceTest, HandlerIsCalled) { Message message; message.set_code(Message::Introduce); this->write(message); EventRef event = this->api->fetch(); ASSERT_NE(nullptr, event.get()); } TEST_F(ApiSourceTest, HasDrain) { Message message; message.set_code(Message::Introduce); this->write(message); EventRef event = this->api->fetch(); ASSERT_EQ("NULL", event->drain()->id()); }
23.346535
73
0.693384
ArcticNature
c2b1d5f5f3a81f517bb7e1b315059df936fa2bd6
305
hpp
C++
addons/bi/caliber/556/f2000.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/bi/caliber/556/f2000.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/bi/caliber/556/f2000.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
// F2000 Rifles - All rifles inherit // F2000 - Long Barrel class arifle_Mk20_F: mk20_base_F { recoil = QCLASS(556_Bullpup_Long); }; class arifle_Mk20C_F: mk20_base_F { recoil = QCLASS(556_Bullpup_Long); }; // GL class arifle_Mk20_GL_F: mk20_base_F { recoil = QCLASS(556_Bullpup_GL_Long); };
21.785714
41
0.727869
Theseus-Aegis
c2b212f7cb89bb1901849e08151a81d70b6ebf6f
11,421
cpp
C++
lab09_templatedBinarySearchTree_BST/executive.cpp
JackNGould/programming2
59c127b6a6c586a6fcd69526763aad27cd152d90
[ "MIT" ]
null
null
null
lab09_templatedBinarySearchTree_BST/executive.cpp
JackNGould/programming2
59c127b6a6c586a6fcd69526763aad27cd152d90
[ "MIT" ]
null
null
null
lab09_templatedBinarySearchTree_BST/executive.cpp
JackNGould/programming2
59c127b6a6c586a6fcd69526763aad27cd152d90
[ "MIT" ]
null
null
null
/* * @project: Binary Search Tree filled with custom objects. * @file: executive.cpp * @author: Jack Gould * @brief: Implementation File for executive class. Defines member methods. Class governs the program's 'executive' actions of filling a BST from the inputFile data, and generating a menu of options for the user. Controls program flow. * @date: 04-17-2020 */ #include "executive.h" #include "jackException.h" #include <sstream> #include <iostream> #include <limits> executive::executive(std::string fName) { std::ifstream inFile(fName); if (inFile.is_open()) { std::string line; while (getline(inFile, line)) { inputLineList.enqueue(line); } inFile.close(); } else { throw(jackException("\ninFile not found/opened.\n")); } } void executive::writeToFile(pokemon entry) { outFile.open(outFileName, std::fstream::app); //must be opened in append mode so that every new line doesn't override old line(s) if (outFile.is_open()) { outFile << entry.getAmerican() << '\t' << entry.getIndex() << '\t' << entry.getJapanese() << '\n'; outFile.close(); } else { throw(jackException("\noutFile not found/opened.\n")); } } executive::~executive() { } void executive::run() { fillTree(); bool runMenu = true; do { std::cout << "\n--------\n--Menu--\n--------\n"; std::cout << "1)Search the pokedex\n"; std::cout << "2)Add an entry to the pokedex\n"; std::cout << "3)Copy Pokedex(one-time only)\n"; std::cout << "4)Remove from Pokedex Copy\n"; std::cout << "5)Save a Pokedex\n"; std::cout << "6)Run a Test\n"; std::cout << "7)Exit the Program\n"; int userInput = 0; std::cout << "Please make a selection(1-7): "; try { std::cin >> userInput; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nBad Input Provided, please make sure input is an integer.\n")); } switch(userInput) { case 1: { int pokedexChoice = 0; if(copyCreated == true) { std::cout << "Search selected, please select a pokedex, 1 for the original, 2 for the copy.\n"; std::cin >> pokedexChoice; if(std::cin.fail() || pokedexChoice <=0 || pokedexChoice > 2) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, pokedex choice must be either 1 or 2.\n")); } } std::cout << "Please input the american name of a pokemon to search the pokedex for:\n"; std::string searchTerm; std::cin >> searchTerm; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, couldn't interpret cin input.\n")); } pokemon temp; if(pokedexChoice == 2) { temp = (copyBST.search(searchTerm)); } else { temp = (myBST.search(searchTerm)); } std::cout << "\nPokemon Found!\n\tAmerican Name: " << temp.getAmerican() << "\n\tPokedex Number: " << temp.getIndex() << "\n\tJapanese Name: " << temp.getJapanese() << '\n'; break; } case 2: { std::string americanName, japaneseName; int pokedex; InputLoop: std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Add Entry selected: Please first input an American name for the new pokemon:\n"; std::cin >> americanName; if(std::cin.fail()) { goto InputLoop; } std::cout << "\nNow input a Japanese name for the new pokemon:\n"; std::cin >> japaneseName; if(std::cin.fail()) { goto InputLoop; } std::cout << "\nNow input a pokedex number for the new pokemon:\n"; std::cin >> pokedex; if(std::cin.fail()) { goto InputLoop; } //end InputLoop pokemon newPokemon(americanName, pokedex, japaneseName); if(copyCreated == true) { copyBST.add(newPokemon); std::cout << '\n' << americanName << " was added to the pokedex COPY\n"; } else { myBST.add(newPokemon); std::cout << '\n' << americanName << " was added to the original pokedex\n"; } break; } case 3: { if(copyCreated == false) { std::cout << "\nCreating a deep copy of the Pokedex...\nREMINDER:Once a copy has been created, edits can only be made to the copy\n"; copyBST = myBST; copyCreated = true; std::cout << "\nCopy Created\n"; } else { throw(jackException("\nA Deep copy was already made, please work with the copy you have already created.\n")); } break; } case 4: { if(copyCreated == true) { std::cout << "\nRemove selected, please input the american name of a pokemon to remove from the copied Pokedex\n"; std::string keyTerm; std::cin >> keyTerm; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, couldn't interpret cin input.\n")); } copyBST.remove(keyTerm); std::cout << keyTerm << " was removed from the copied pokedex\n."; } else { std::cout << "\nNo copy has been been created, the original pokedex is protected from Node removal.\n"; } break; } case 5: { int pokedexChoice = 0; int traversalChoice = 0; savePokedexPrompts(pokedexChoice, traversalChoice, outFileName); switch(traversalChoice) { case 1: { if(pokedexChoice == 2) { copyBST.visitPreOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } else { myBST.visitPreOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } break; } case 2: { if(pokedexChoice == 2) { copyBST.visitInOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } else { myBST.visitInOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } break; } case 3: { if(pokedexChoice == 2) { copyBST.visitPostOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } else { myBST.visitPostOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } break; } default: { throw(jackException("\nSomething really had to break for this error to print\n")); } } break; } case 6: { int testChoice = 0; std::cout << "\nTests on constructors/destructor selected, please choose a test:\n1)Test ADD\n2)Test Remove\n3)Test Write\n"; std::cin >> testChoice; if(std::cin.fail() || testChoice <=0 || testChoice > 3) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, pokedex choice must be either 1 or 2.\n")); } switch(testChoice) { case 1: { tester.testAdds(myBST); break; } case 2: { tester.testRemoves(myBST); break; } case 3: { tester.testWriteToFile(myBST); break; } default: { throw(jackException("\nSomething broke here.\n")); } } break; } case 7: { std::cout << "\nExiting Program...\n"; runMenu = false; break; } default: { throw(jackException("\nError, invalid menu option entered, please input 1, 2, or 3\n")); break; } } } catch(jackException& rte) { std::cout << rte.what(); } }while(runMenu != false); } void executive::savePokedexPrompts(int& pokedex, int& traversal, std::string& outFile) { if(copyCreated == true) { std::cout << "Save selected, please select a pokedex, 1 for the original, 2 for the copy.\n"; std::cin >> pokedex; if(std::cin.fail() || pokedex <=0 || pokedex > 2) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, pokedex choice must be either 1 or 2.\n")); } } else { pokedex = 1; } std::cout << "Save selected, please enter a file name to write the output to\n"; std::cin >> outFile; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, cin input could not be read.\n")); } std::cout << "Please select an order to traverse the tree in:\n1)PreOrder\n2)InOrder\n3)PostOrder\n"; std::cin >> traversal; if(std::cin.fail() || traversal <= 0 || traversal > 3) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, traversal choice must be 1, 2, or 3.\n")); } } void executive::fillTree() { int objectCount = inputLineList.getLength(); std::string line = ""; std::string american, pokedex, japanese; int pokedexNum = 0; for(int i=0;i<objectCount;++i) { try { line = inputLineList.peekFront(); std::istringstream iss (line); iss >> american; iss >> pokedex; iss >> japanese; pokedexNum = stoi(pokedex); pokemon myPokemon(american, pokedexNum, japanese); myBST.add(myPokemon); inputLineList.dequeue(); } catch(jackException& rte) { std::cout << rte.what(); } } }
31.46281
235
0.492952
JackNGould
c2b219aa24d7be26c06877dbda3b2bbe8b33529f
14,941
cpp
C++
sdk/src/logging/Logger.cpp
andrie/rstudio-launcher-plugin-sdk
0b13a149fe263b578c90c98c8ab2d739b830ca60
[ "MIT" ]
4
2021-01-14T08:06:35.000Z
2021-09-24T12:39:31.000Z
sdk/src/logging/Logger.cpp
andrie/rstudio-launcher-plugin-sdk
0b13a149fe263b578c90c98c8ab2d739b830ca60
[ "MIT" ]
14
2021-01-19T21:21:16.000Z
2022-03-03T22:17:23.000Z
sdk/src/logging/Logger.cpp
andrie/rstudio-launcher-plugin-sdk
0b13a149fe263b578c90c98c8ab2d739b830ca60
[ "MIT" ]
3
2021-01-14T07:54:47.000Z
2021-11-23T18:20:19.000Z
/* * Logger.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement * with RStudio, then this program is licensed to you under the following terms: * * 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 <logging/Logger.hpp> #include <cassert> #include <sstream> #include <boost/algorithm/string.hpp> #include <Error.hpp> #include <Noncopyable.hpp> #include <Optional.hpp> #include <logging/ILogDestination.hpp> #include <system/DateTime.hpp> #include "../system/ReaderWriterMutex.hpp" namespace rstudio { namespace launcher_plugins { namespace logging { typedef std::map<unsigned int, std::shared_ptr<ILogDestination> > LogMap; typedef std::map<std::string, LogMap> SectionLogMap; namespace { constexpr const char* s_loggedFrom = "LOGGED FROM"; std::ostream& operator<<(std::ostream& io_ostream, LogLevel in_logLevel) { switch (in_logLevel) { case LogLevel::ERR: { io_ostream << "ERROR"; break; } case LogLevel::WARN: { io_ostream << "WARNING"; break; } case LogLevel::DEBUG: { io_ostream << "DEBUG"; break; } case LogLevel::INFO: { io_ostream << "INFO"; break; } case LogLevel::OFF: { io_ostream << "OFF"; break; } default: { assert(false); // This shouldn't be possible if (in_logLevel > LogLevel::INFO) io_ostream << "INFO"; else io_ostream << "OFF"; } } return io_ostream; } std::string formatLogMessage( LogLevel in_logLevel, const std::string& in_message, const std::string& in_programId, const ErrorLocation& in_loggedFrom = ErrorLocation(), bool in_formatForSyslog = false) { std::ostringstream oss; if (!in_formatForSyslog) { // Add the time. oss << system::DateTime().toString("%d %b %Y %H:%M:%S") << " [" << in_programId << "] "; } oss << in_logLevel << " " << in_message; if (in_loggedFrom.hasLocation()) oss << s_delim << " " << s_loggedFrom << ": " << cleanDelimiters(in_loggedFrom.asString()); oss << std::endl; if (in_formatForSyslog) { // Newlines delimit logs in syslog, so replace them with ||| return boost::replace_all_copy(oss.str(), "\n", "|||"); } return oss.str(); } } // anonymous namespace // Logger Object ======================================================================================================= /** * @brief Class which logs messages to destinations. * * Multiple destinations may be added to this logger in order to write the same message to each destination. * The default log level is ERROR. */ struct Logger : Noncopyable { public: /** * @brief Writes a pre-formatted message to all registered destinations. * * @param in_logLevel The log level of the message, which is passed to the destination for informational purposes. * @param in_message The pre-formatted message. * @param in_section The section to which to log this message. * @param in_loggedFrom The location from which the error message was logged. */ void writeMessageToDestinations( LogLevel in_logLevel, const std::string& in_message, const std::string& in_section = std::string(), const ErrorLocation& in_loggedFrom = ErrorLocation()); /** * @brief Constructor to prevent multiple instances of Logger. */ Logger() : MaxLogLevel(LogLevel::OFF), ProgramId("") { }; // The maximum level of message to write across all log sections. LogLevel MaxLogLevel; // The ID of the program fr which to write logs. std::string ProgramId; // The registered default log destinations. Any logs without a section or with an unregistered section will be logged // to these destinations. LogMap DefaultLogDestinations; // The registered sectioned log destinations. Any logs with a registered section will be logged to the destinations // assigned to that section. SectionLogMap SectionedLogDestinations; // The read-write mutex to protect the maps. system::ReaderWriterMutex Mutex; }; Logger& logger() { static Logger logger; return logger; } void Logger::writeMessageToDestinations( LogLevel in_logLevel, const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { READ_LOCK_BEGIN(Mutex) // Don't log this message, it's too detailed for any of the logs. if (in_logLevel > MaxLogLevel) return; LogMap* logMap = &DefaultLogDestinations; if (!in_section.empty()) { // Don't log anything if there is no logger for this section. if (SectionedLogDestinations.find(in_section) == SectionedLogDestinations.end()) return; auto logDestIter = SectionedLogDestinations.find(in_section); logMap = &logDestIter->second; } // Preformat the message for non-syslog loggers. std::string formattedMessage = formatLogMessage(in_logLevel, in_message, ProgramId, in_loggedFrom); const auto destEnd = logMap->end(); for (auto iter = logMap->begin(); iter != destEnd; ++iter) { iter->second->writeLog(in_logLevel, formattedMessage); } RW_LOCK_END(false) } // Logging functions void setProgramId(const std::string& in_programId) { WRITE_LOCK_BEGIN(logger().Mutex) { if (!logger().ProgramId.empty() && (logger().ProgramId != in_programId)) logWarningMessage("Changing the program id from " + logger().ProgramId + " to " + in_programId); logger().ProgramId = in_programId; } RW_LOCK_END(false) } void addLogDestination(const std::shared_ptr<ILogDestination>& in_destination) { WRITE_LOCK_BEGIN(logger().Mutex) { LogMap& logMap = logger().DefaultLogDestinations; if (logMap.find(in_destination->getId()) == logMap.end()) { logMap.insert(std::make_pair(in_destination->getId(), in_destination)); if (in_destination->getLogLevel() > logger().MaxLogLevel) logger().MaxLogLevel = in_destination->getLogLevel(); return; } } RW_LOCK_END(false) logDebugMessage( "Attempted to register a log destination that has already been registered with id " + std::to_string(in_destination->getId())); } void addLogDestination(const std::shared_ptr<ILogDestination>& in_destination, const std::string& in_section) { WRITE_LOCK_BEGIN(logger().Mutex) { Logger& log = logger(); SectionLogMap& secLogMap = log.SectionedLogDestinations; if (secLogMap.find(in_section) == secLogMap.end()) secLogMap.insert(std::make_pair(in_section, LogMap())); LogMap& logMap = secLogMap.find(in_section)->second; if (logMap.find(in_destination->getId()) == logMap.end()) { logMap.insert(std::make_pair(in_destination->getId(), in_destination)); if (log.MaxLogLevel < in_destination->getLogLevel()) log.MaxLogLevel = in_destination->getLogLevel(); return; } } RW_LOCK_END(false) logDebugMessage( "Attempted to register a log destination that has already been registered with id " + std::to_string(in_destination->getId()) + " to section " + in_section); } std::string cleanDelimiters(const std::string& in_str) { std::string toClean(in_str); std::replace(toClean.begin(), toClean.end(), s_delim, ' '); return toClean; } void logError(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::ERR, in_error.asString()); } void logError(const Error& in_error, const ErrorLocation& in_location) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::ERR, in_error.asString(), "", in_location); } void logErrorAsWarning(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::WARN, in_error.asString()); } void logErrorAsInfo(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::INFO, in_error.asString()); } void logErrorAsDebug(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::DEBUG, in_error.asString()); } void logErrorMessage(const std::string& in_message, const std::string& in_section) { logErrorMessage(in_message, in_section, ErrorLocation()); } void logErrorMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logErrorMessage(in_message, "", in_loggedFrom); } void logErrorMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { Logger& log = logger(); if (log.MaxLogLevel >= LogLevel::ERR) log.writeMessageToDestinations(LogLevel::ERR, in_message, in_section, in_loggedFrom); } void logWarningMessage(const std::string& in_message, const std::string& in_section) { logWarningMessage(in_message, in_section, ErrorLocation()); } void logWarningMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logWarningMessage(in_message, "", in_loggedFrom); } void logWarningMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { Logger& log = logger(); if (log.MaxLogLevel >= LogLevel::WARN) log.writeMessageToDestinations(LogLevel::WARN, in_message, in_section, in_loggedFrom); } void logDebugMessage(const std::string& in_message, const std::string& in_section) { logDebugMessage(in_message, in_section, ErrorLocation()); } void logDebugMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logDebugMessage(in_message, "", in_loggedFrom); } void logDebugMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { logger().writeMessageToDestinations(LogLevel::DEBUG, in_message, in_section, in_loggedFrom); } void logInfoMessage(const std::string& in_message, const std::string& in_section) { logInfoMessage(in_message, in_section, ErrorLocation()); } void logInfoMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logInfoMessage(in_message, "", in_loggedFrom); } void logInfoMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { logger().writeMessageToDestinations(LogLevel::INFO, in_message, in_section, in_loggedFrom); } void reloadAllLogDestinations() { Logger& log = logger(); WRITE_LOCK_BEGIN(log.Mutex) { for (auto& dest : log.DefaultLogDestinations) dest.second->reload(); for (auto& section : log.SectionedLogDestinations) { for (auto& dest : section.second) dest.second->reload(); } } RW_LOCK_END(false); } void removeLogDestination(unsigned int in_destinationId, const std::string& in_section) { Logger& log = logger(); if (in_section.empty()) { // Remove the log from default destinations if it's found. Keep track of whether we find it for logging purposes. bool found = false; WRITE_LOCK_BEGIN(log.Mutex) { auto iter = log.DefaultLogDestinations.find(in_destinationId); if (iter != log.DefaultLogDestinations.end()) { found = true; log.DefaultLogDestinations.erase(iter); } // Remove it from any sections it may have been registered to. std::vector<std::string> sectionsToRemove; for (auto secIter: log.SectionedLogDestinations) { iter = secIter.second.find(in_destinationId); if (iter != secIter.second.end()) { found = true; secIter.second.erase(iter); } if (secIter.second.empty()) sectionsToRemove.push_back(secIter.first); } // Clean up any empty sections. for (const std::string& toRemove: sectionsToRemove) log.SectionedLogDestinations.erase(log.SectionedLogDestinations.find(toRemove)); } RW_LOCK_END(false); // Log a debug message if this destination wasn't registered. if (!found) { logDebugMessage( "Attempted to unregister a log destination that has not been registered with id" + std::to_string(in_destinationId)); } } else if (log.SectionedLogDestinations.find(in_section) != log.SectionedLogDestinations.end()) { WRITE_LOCK_BEGIN(log.Mutex) { auto secIter = log.SectionedLogDestinations.find(in_section); auto iter = secIter->second.find(in_destinationId); if (iter != secIter->second.end()) { secIter->second.erase(iter); if (secIter->second.empty()) log.SectionedLogDestinations.erase(secIter); return; } } RW_LOCK_END(false); logDebugMessage( "Attempted to unregister a log destination that has not been registered to the specified section (" + in_section + ") with id " + std::to_string(in_destinationId)); } else { logDebugMessage( "Attempted to unregister a log destination that has not been registered to the specified section (" + in_section + ") with id " + std::to_string(in_destinationId)); } } std::ostream& writeError(const Error& in_error, std::ostream& io_os) { return io_os << writeError(in_error); } std::string writeError(const Error& in_error) { return formatLogMessage(LogLevel::ERR, in_error.asString(), logger().ProgramId); } } // namespace logging } // namespace launcher_plugins } // namespace rstudio
30.616803
124
0.673047
andrie
c2b2c0a5159fce1a4e7ad6e07431889f6d5c62b9
1,020
hpp
C++
source/drivers/audio_decoder.hpp
HuangDave/BlockBoombox
d1750149f533d83fc6b955a1a12e75f14d4230e8
[ "Apache-2.0" ]
null
null
null
source/drivers/audio_decoder.hpp
HuangDave/BlockBoombox
d1750149f533d83fc6b955a1a12e75f14d4230e8
[ "Apache-2.0" ]
6
2020-07-29T23:26:15.000Z
2020-07-29T23:45:21.000Z
source/drivers/audio_decoder.hpp
HuangDave/BlockBoombox
d1750149f533d83fc6b955a1a12e75f14d4230e8
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> /// An interface containing controls for an audio decoder. class AudioDecoder { public: /// Initialize the device for use. virtual void Initialize() const = 0; /// Reset the device. virtual void Reset() const = 0; /// Enable the device to be ready to decode audio data. virtual void Enable() const = 0; /// Pause audio decoding. virtual void Pause() const = 0; /// Attempts to resume audio decoding. virtual void Resume() const = 0; /// Reset decode time back to 00:00. virtual void ClearDecodeTime() const = 0; /// Buffer audio data for decoding. /// /// @param data Pointer to the array containing the data bytes to buffer. /// @param length The number of data bytes in the array. virtual void Buffer(const uint8_t * data, size_t length) const = 0; /// @param percentage Volume percentage ranging from 0.0 to 1.0, where 1.0 is /// 100 percent. virtual void SetVolume(float percentage) const = 0; };
26.842105
79
0.676471
HuangDave
c2b4f441ad85d02f75fc53c4fc32ee5d0be81ae1
3,972
cpp
C++
IGC/Compiler/CISACodeGen/TimeStatsCounter.cpp
lfelipe/intel-graphics-compiler
da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd
[ "MIT" ]
null
null
null
IGC/Compiler/CISACodeGen/TimeStatsCounter.cpp
lfelipe/intel-graphics-compiler
da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd
[ "MIT" ]
1
2021-02-24T08:39:15.000Z
2021-02-24T08:39:15.000Z
IGC/Compiler/CISACodeGen/TimeStatsCounter.cpp
lfelipe/intel-graphics-compiler
da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd
[ "MIT" ]
null
null
null
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======================= end_copyright_notice ==================================*/ #include "Compiler/CISACodeGen/TimeStatsCounter.h" #include "Compiler/IGCPassSupport.h" #include "common/LLVMWarningsPush.hpp" #include <llvm/Pass.h> #include "common/LLVMWarningsPop.hpp" using namespace llvm; using namespace IGC; namespace { class TimeStatsCounter : public ModulePass { CodeGenContext* ctx; COMPILE_TIME_INTERVALS interval; TimeStatsCounterStartEndMode mode; std::string igcPass; TimeStatsCounterType type; public: static char ID; TimeStatsCounter() : ModulePass(ID) { initializeTimeStatsCounterPass(*PassRegistry::getPassRegistry()); } TimeStatsCounter(CodeGenContext* _ctx, COMPILE_TIME_INTERVALS _interval, TimeStatsCounterStartEndMode _mode) : ModulePass(ID) { initializeTimeStatsCounterPass(*PassRegistry::getPassRegistry()); ctx = _ctx; interval = _interval; mode = _mode; type = STATS_COUNTER_ENUM_TYPE; } TimeStatsCounter(CodeGenContext* _ctx, std::string _igcPass, TimeStatsCounterStartEndMode _mode) : ModulePass(ID) { initializeTimeStatsCounterPass(*PassRegistry::getPassRegistry()); ctx = _ctx; mode = _mode; igcPass = _igcPass; type = STATS_COUNTER_LLVM_PASS; } bool runOnModule(Module&) override; private: }; } // End anonymous namespace ModulePass* IGC::createTimeStatsCounterPass(CodeGenContext* _ctx, COMPILE_TIME_INTERVALS _interval, TimeStatsCounterStartEndMode _mode) { return new TimeStatsCounter(_ctx, _interval, _mode); } ModulePass* IGC::createTimeStatsIGCPass(CodeGenContext* _ctx, std::string _igcPass, TimeStatsCounterStartEndMode _mode) { return new TimeStatsCounter(_ctx, _igcPass, _mode); } char TimeStatsCounter::ID = 0; #define PASS_FLAG "time-stats-counter" #define PASS_DESC "TimeStatsCounter Start/Stop" #define PASS_CFG_ONLY false #define PASS_ANALYSIS false namespace IGC { IGC_INITIALIZE_PASS_BEGIN(TimeStatsCounter, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS) IGC_INITIALIZE_PASS_END(TimeStatsCounter, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS) } bool TimeStatsCounter::runOnModule(Module& F) { if (type == STATS_COUNTER_ENUM_TYPE) { if (mode == STATS_COUNTER_START) { COMPILER_TIME_START(ctx, interval); } else { COMPILER_TIME_END(ctx, interval); } } else { if (mode == STATS_COUNTER_START) { COMPILER_TIME_PASS_START(ctx, igcPass); } else { COMPILER_TIME_PASS_END(ctx, igcPass); } } return false; }
32.826446
137
0.690584
lfelipe
c2b6fe6b9ed4683af1dcc6505dfcbb50f42ad445
26,923
cpp
C++
src/items/weapons/weapons.cpp
Waclaw-I/BagnoOTS
dbeb04322698ecdb795eba196872815b36ca134f
[ "MIT" ]
null
null
null
src/items/weapons/weapons.cpp
Waclaw-I/BagnoOTS
dbeb04322698ecdb795eba196872815b36ca134f
[ "MIT" ]
null
null
null
src/items/weapons/weapons.cpp
Waclaw-I/BagnoOTS
dbeb04322698ecdb795eba196872815b36ca134f
[ "MIT" ]
null
null
null
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2019 Mark Samman <mark.samman@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "creatures/combat/combat.h" #include "game/game.h" #include "utils/pugicast.h" #include "lua/creature/events.h" #include "items/weapons/weapons.h" Weapons::Weapons() { scriptInterface.initState(); } Weapons::~Weapons() { clear(false); } const Weapon* Weapons::getWeapon(const Item* item) const { if (!item) { return nullptr; } auto it = weapons.find(item->getID()); if (it == weapons.end()) { return nullptr; } return it->second; } void Weapons::clear(bool fromLua) { for (auto it = weapons.begin(); it != weapons.end(); ) { if (fromLua == it->second->fromLua) { it = weapons.erase(it); } else { ++it; } } reInitState(fromLua); } LuaScriptInterface& Weapons::getScriptInterface() { return scriptInterface; } std::string Weapons::getScriptBaseName() const { return "weapons"; } void Weapons::loadDefaults() { for (size_t i = 100, size = Item::items.size(); i < size; ++i) { const ItemType& it = Item::items.getItemType(i); if (it.id == 0 || weapons.find(i) != weapons.end()) { continue; } switch (it.weaponType) { case WEAPON_AXE: case WEAPON_SWORD: case WEAPON_CLUB: { WeaponMelee* weapon = new WeaponMelee(&scriptInterface); weapon->configureWeapon(it); weapons[i] = weapon; break; } case WEAPON_AMMO: case WEAPON_DISTANCE: { if (it.weaponType == WEAPON_DISTANCE && it.ammoType != AMMO_NONE) { continue; } WeaponDistance* weapon = new WeaponDistance(&scriptInterface); weapon->configureWeapon(it); weapons[i] = weapon; break; } default: break; } } } Event_ptr Weapons::getEvent(const std::string& nodeName) { if (strcasecmp(nodeName.c_str(), "melee") == 0) { return Event_ptr(new WeaponMelee(&scriptInterface)); } else if (strcasecmp(nodeName.c_str(), "distance") == 0) { return Event_ptr(new WeaponDistance(&scriptInterface)); } else if (strcasecmp(nodeName.c_str(), "wand") == 0) { return Event_ptr(new WeaponWand(&scriptInterface)); } return nullptr; } bool Weapons::registerEvent(Event_ptr event, const pugi::xml_node&) { Weapon* weapon = static_cast<Weapon*>(event.release()); //event is guaranteed to be a Weapon auto result = weapons.emplace(weapon->getID(), weapon); if (!result.second) { SPDLOG_WARN("[Weapons::registerEvent] - " "Duplicate registered item with id: {}", weapon->getID()); } return result.second; } bool Weapons::registerLuaEvent(Weapon* event) { weapons[event->getID()] = event; return true; } //monsters int32_t Weapons::getMaxMeleeDamage(int32_t attackSkill, int32_t attackValue) { return static_cast<int32_t>(std::ceil((attackSkill * (attackValue * 0.05)) + (attackValue * 0.5))); } //players int32_t Weapons::getMaxWeaponDamage(uint32_t level, int32_t attackSkill, int32_t attackValue, float attackFactor, bool isMelee) { if (isMelee) { return static_cast<int32_t>(std::round((0.085 * attackFactor * attackValue * attackSkill) + (level / 5))); } else { return static_cast<int32_t>(std::round((0.09 * attackFactor * attackValue * attackSkill) + (level / 5))); } } bool Weapon::configureEvent(const pugi::xml_node& node) { pugi::xml_attribute attr; if (!(attr = node.attribute("id"))) { SPDLOG_ERROR("[Weapon::configureEvent] - Weapon without id"); return false; } id = pugi::cast<uint16_t>(attr.value()); if ((attr = node.attribute("level"))) { level = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("maglv")) || (attr = node.attribute("maglevel"))) { magLevel = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("mana"))) { mana = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("manapercent"))) { manaPercent = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("soul"))) { soul = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("prem"))) { premium = attr.as_bool(); } if ((attr = node.attribute("breakchance")) && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES)) { breakChance = std::min<uint8_t>(100, pugi::cast<uint16_t>(attr.value())); } if ((attr = node.attribute("action"))) { action = getWeaponAction(asLowerCaseString(attr.as_string())); if (action == WEAPONACTION_NONE) { SPDLOG_WARN("[Weapon::configureEvent] - " "Unknown action {}", attr.as_string()); } } if ((attr = node.attribute("enabled"))) { enabled = attr.as_bool(); } if ((attr = node.attribute("unproperly"))) { wieldUnproperly = attr.as_bool(); } std::list<std::string> vocStringList; for (auto vocationNode : node.children()) { if (!(attr = vocationNode.attribute("name"))) { continue; } uint16_t vocationId = g_vocations().getVocationId(attr.as_string()); if (vocationId != -1) { vocWeaponMap[vocationId] = true; int32_t promotedVocation = g_vocations().getPromotedVocation(vocationId); if (promotedVocation != VOCATION_NONE) { vocWeaponMap[promotedVocation] = true; } if (vocationNode.attribute("showInDescription").as_bool(true)) { vocStringList.push_back(asLowerCaseString(attr.as_string())); } } } std::string vocationString; for (const std::string& str : vocStringList) { if (!vocationString.empty()) { if (str != vocStringList.back()) { vocationString.push_back(','); vocationString.push_back(' '); } else { vocationString += " and "; } } vocationString += str; vocationString.push_back('s'); } uint32_t wieldInfo = 0; if (getReqLevel() > 0) { wieldInfo |= WIELDINFO_LEVEL; } if (getReqMagLv() > 0) { wieldInfo |= WIELDINFO_MAGLV; } if (!vocationString.empty()) { wieldInfo |= WIELDINFO_VOCREQ; } if (isPremium()) { wieldInfo |= WIELDINFO_PREMIUM; } if (wieldInfo != 0) { ItemType& it = Item::items.getItemType(id); it.wieldInfo = wieldInfo; it.vocationString = vocationString; it.minReqLevel = getReqLevel(); it.minReqMagicLevel = getReqMagLv(); } configureWeapon(Item::items[id]); return true; } void Weapon::configureWeapon(const ItemType& it) { id = it.id; } std::string Weapon::getScriptEventName() const { return "onUseWeapon"; } int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shootRange) const { const Position& playerPos = player->getPosition(); const Position& targetPos = target->getPosition(); if (playerPos.z != targetPos.z) { return 0; } if (std::max<uint32_t>(Position::getDistanceX(playerPos, targetPos), Position::getDistanceY(playerPos, targetPos)) > shootRange) { return 0; } if (!player->hasFlag(PlayerFlag_IgnoreWeaponCheck)) { if (!enabled) { return 0; } if (player->getMana() < getManaCost(player)) { return 0; } if (player->getHealth() < getHealthCost(player)) { return 0; } if (player->getSoul() < soul) { return 0; } if (isPremium() && !player->isPremium()) { return 0; } if (!vocWeaponMap.empty()) { if (vocWeaponMap.find(player->getVocationId()) == vocWeaponMap.end()) { return 0; } } int32_t damageModifier = 100; if (player->getLevel() < getReqLevel()) { damageModifier = (isWieldedUnproperly() ? damageModifier / 2 : 0); } if (player->getMagicLevel() < getReqMagLv()) { damageModifier = (isWieldedUnproperly() ? damageModifier / 2 : 0); } return damageModifier; } return 100; } bool Weapon::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; } internalUseWeapon(player, item, target, damageModifier); return true; } CombatDamage Weapon::getCombatDamage(CombatDamage combat, Player * player, Item * item, int32_t damageModifier) const { //Local variables uint32_t level = player->getLevel(); int16_t elementalAttack = getElementDamageValue(); int32_t weaponAttack = std::max<int32_t>(0, item->getAttack()); int32_t playerSkill = player->getWeaponSkill(item); float attackFactor = player->getAttackFactor(); // full atk, balanced or full defense //Getting values factores int32_t totalAttack = elementalAttack + weaponAttack; double weaponAttackProportion = (double)weaponAttack / (double)totalAttack; //Calculating damage int32_t maxDamage = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, playerSkill, totalAttack, attackFactor, true) * player->getVocation()->meleeDamageMultiplier * damageModifier / 100); int32_t minDamage = level / 5; int32_t realDamage = normal_random(minDamage, maxDamage); //Setting damage to combat combat.primary.value = realDamage * weaponAttackProportion; combat.secondary.value = realDamage * (1 - weaponAttackProportion); return combat; } bool Weapon::useFist(Player* player, Creature* target) { if (!Position::areInRange<1, 1>(player->getPosition(), target->getPosition())) { return false; } float attackFactor = player->getAttackFactor(); int32_t attackSkill = player->getSkillLevel(SKILL_FIST); int32_t attackValue = 7; int32_t maxDamage = Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, attackValue, attackFactor, true); CombatParams params; params.combatType = COMBAT_PHYSICALDAMAGE; params.blockedByArmor = true; params.blockedByShield = true; CombatDamage damage; damage.origin = ORIGIN_MELEE; damage.primary.type = params.combatType; damage.primary.value = -normal_random(0, maxDamage); Combat::doCombatHealth(player, target, damage, params); if (!player->hasFlag(PlayerFlag_NotGainSkill) && player->getAddAttackSkill()) { player->addSkillAdvance(SKILL_FIST, 1); } return true; } void Weapon::internalUseWeapon(Player* player, Item* item, Creature* target, int32_t damageModifier) const { if (scripted) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = target->getID(); executeUseWeapon(player, var); } else { CombatDamage damage; WeaponType_t weaponType = item->getWeaponType(); if (weaponType == WEAPON_AMMO || weaponType == WEAPON_DISTANCE) { damage.origin = ORIGIN_RANGED; } else { damage.origin = ORIGIN_MELEE; } damage.primary.type = params.combatType; damage.secondary.type = getElementType(); if (damage.secondary.type == COMBAT_NONE) { damage.primary.value = (getWeaponDamage(player, target, item) * damageModifier) / 100; damage.secondary.value = 0; } else { damage.primary.value = (getWeaponDamage(player, target, item) * damageModifier) / 100; damage.secondary.value = (getElementDamage(player, target, item) * damageModifier) / 100; } Combat::doCombatHealth(player, target, damage, params); } onUsedWeapon(player, item, target->getTile()); } void Weapon::internalUseWeapon(Player* player, Item* item, Tile* tile) const { if (scripted) { LuaVariant var; var.type = VARIANT_TARGETPOSITION; var.pos = tile->getPosition(); executeUseWeapon(player, var); } else { Combat::postCombatEffects(player, tile->getPosition(), params); g_game().addMagicEffect(tile->getPosition(), CONST_ME_POFF); } onUsedWeapon(player, item, tile); } void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const { if (!player->hasFlag(PlayerFlag_NotGainSkill)) { skills_t skillType; uint32_t skillPoint; if (getSkillType(player, item, skillType, skillPoint)) { player->addSkillAdvance(skillType, skillPoint); } } uint32_t manaCost = getManaCost(player); if (manaCost != 0) { player->addManaSpent(manaCost); player->changeMana(-static_cast<int32_t>(manaCost)); } uint32_t healthCost = getHealthCost(player); if (healthCost != 0) { player->changeHealth(-static_cast<int32_t>(healthCost)); } if (!player->hasFlag(PlayerFlag_HasInfiniteSoul) && soul > 0) { player->changeSoul(-static_cast<int32_t>(soul)); } if (breakChance != 0 && uniform_random(1, 100) <= breakChance) { Weapon::decrementItemCount(item); player->updateSupplyTracker(item); return; } switch (action) { case WEAPONACTION_REMOVECOUNT: if(g_configManager().getBoolean(REMOVE_WEAPON_AMMO)) { Weapon::decrementItemCount(item); player->updateSupplyTracker(item); } break; case WEAPONACTION_REMOVECHARGE: { if (uint16_t charges = item->getCharges() != 0 && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES)) { g_game().transformItem(item, item->getID(), charges - 1); } break; } case WEAPONACTION_MOVE: g_game().internalMoveItem(item->getParent(), destTile, INDEX_WHEREEVER, item, 1, nullptr, FLAG_NOLIMIT); break; default: break; } } uint32_t Weapon::getManaCost(const Player* player) const { if (mana != 0) { return mana; } if (manaPercent == 0) { return 0; } return (player->getMaxMana() * manaPercent) / 100; } int32_t Weapon::getHealthCost(const Player* player) const { if (health != 0) { return health; } if (healthPercent == 0) { return 0; } return (player->getMaxHealth() * healthPercent) / 100; } bool Weapon::executeUseWeapon(Player* player, const LuaVariant& var) const { //onUseWeapon(player, var) if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[Weapon::executeUseWeapon - Player {} weaponId {}]" "Call stack overflow. Too many lua script calls being nested.", player->getName(), getID()); return false; } ScriptEnvironment* env = scriptInterface->getScriptEnv(); env->setScriptId(scriptId, scriptInterface); lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); scriptInterface->pushVariant(L, var); return scriptInterface->callFunction(2); } void Weapon::decrementItemCount(Item* item) { uint16_t count = item->getItemCount(); if (count > 1) { g_game().transformItem(item, item->getID(), count - 1); } else { g_game().internalRemoveItem(item); } } WeaponMelee::WeaponMelee(LuaScriptInterface* interface) : Weapon(interface) { params.blockedByArmor = true; params.blockedByShield = true; params.combatType = COMBAT_PHYSICALDAMAGE; } void WeaponMelee::configureWeapon(const ItemType& it) { if (it.abilities) { elementType = it.abilities->elementType; elementDamage = it.abilities->elementDamage; params.aggressive = true; params.useCharges = true; } else { elementType = COMBAT_NONE; elementDamage = 0; } Weapon::configureWeapon(it); } bool WeaponMelee::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; } internalUseWeapon(player, item, target, damageModifier); return true; } bool WeaponMelee::getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const { if (player->getAddAttackSkill() && player->getLastAttackBlockType() != BLOCK_IMMUNITY) { skillpoint = 1; } else { skillpoint = 0; } WeaponType_t weaponType = item->getWeaponType(); switch (weaponType) { case WEAPON_SWORD: { skill = SKILL_SWORD; return true; } case WEAPON_CLUB: { skill = SKILL_CLUB; return true; } case WEAPON_AXE: { skill = SKILL_AXE; return true; } default: break; } return false; } int32_t WeaponMelee::getElementDamage(const Player* player, const Creature*, const Item* item) const { if (elementType == COMBAT_NONE) { return 0; } int32_t attackSkill = player->getWeaponSkill(item); int32_t attackValue = elementDamage; float attackFactor = player->getAttackFactor(); uint32_t level = player->getLevel(); int32_t minValue = level / 5; int32_t maxValue = Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true); return -normal_random(minValue, static_cast<int32_t>(maxValue * player->getVocation()->meleeDamageMultiplier)); } int16_t WeaponMelee::getElementDamageValue() const { return elementDamage; } int32_t WeaponMelee::getWeaponDamage(const Player* player, const Creature*, const Item* item, bool maxDamage /*= false*/) const { using namespace std; int32_t attackSkill = player->getWeaponSkill(item); int32_t attackValue = std::max<int32_t>(0, item->getAttack()); float attackFactor = player->getAttackFactor(); uint32_t level = player->getLevel(); int32_t maxValue = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true) * player->getVocation()->meleeDamageMultiplier); int32_t minValue = level / 5; if (maxDamage) { return -maxValue; } return -normal_random(minValue, maxValue); } WeaponDistance::WeaponDistance(LuaScriptInterface* interface) : Weapon(interface) { params.blockedByArmor = true; params.combatType = COMBAT_PHYSICALDAMAGE; } void WeaponDistance::configureWeapon(const ItemType& it) { params.distanceEffect = it.shootType; if (it.abilities) { elementType = it.abilities->elementType; elementDamage = it.abilities->elementDamage; params.aggressive = true; params.useCharges = true; } else { elementType = COMBAT_NONE; elementDamage = 0; } Weapon::configureWeapon(it); } bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier; const ItemType& it = Item::items[id]; if (it.weaponType == WEAPON_AMMO) { Item* mainWeaponItem = player->getWeapon(true); const Weapon* mainWeapon = g_weapons().getWeapon(mainWeaponItem); if (mainWeapon) { damageModifier = mainWeapon->playerWeaponCheck(player, target, mainWeaponItem->getShootRange()); } else { damageModifier = playerWeaponCheck(player, target, mainWeaponItem->getShootRange()); } } else { damageModifier = playerWeaponCheck(player, target, item->getShootRange()); } if (damageModifier == 0) { return false; } int32_t chance; if (it.hitChance == 0) { //hit chance is based on distance to target and distance skill uint32_t skill = player->getSkillLevel(SKILL_DISTANCE); const Position& playerPos = player->getPosition(); const Position& targetPos = target->getPosition(); uint32_t distance = std::max<uint32_t>(Position::getDistanceX(playerPos, targetPos), Position::getDistanceY(playerPos, targetPos)); uint32_t maxHitChance; if (it.maxHitChance != -1) { maxHitChance = it.maxHitChance; } else if (it.ammoType != AMMO_NONE) { //hit chance on two-handed weapons is limited to 90% maxHitChance = 90; } else { //one-handed is set to 75% maxHitChance = 75; } if (maxHitChance == 75) { //chance for one-handed weapons switch (distance) { case 1: case 5: chance = std::min<uint32_t>(skill, 74) + 1; break; case 2: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 28) * 2.40f) + 8; break; case 3: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 45) * 1.55f) + 6; break; case 4: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 58) * 1.25f) + 3; break; case 6: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 90) * 0.80f) + 3; break; case 7: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 104) * 0.70f) + 2; break; default: chance = it.hitChance; break; } } else if (maxHitChance == 90) { //formula for two-handed weapons switch (distance) { case 1: case 5: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 74) * 1.20f) + 1; break; case 2: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 28) * 3.20f); break; case 3: chance = std::min<uint32_t>(skill, 45) * 2; break; case 4: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 58) * 1.55f); break; case 6: case 7: chance = std::min<uint32_t>(skill, 90); break; default: chance = it.hitChance; break; } } else if (maxHitChance == 100) { switch (distance) { case 1: case 5: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 73) * 1.35f) + 1; break; case 2: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 30) * 3.20f) + 4; break; case 3: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 48) * 2.05f) + 2; break; case 4: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 65) * 1.50f) + 2; break; case 6: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 87) * 1.20f) - 4; break; case 7: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 90) * 1.10f) + 1; break; default: chance = it.hitChance; break; } } else { chance = maxHitChance; } } else { chance = it.hitChance; } if (item->getWeaponType() == WEAPON_AMMO) { Item* bow = player->getWeapon(true); if (bow && bow->getHitChance() != 0) { chance += bow->getHitChance(); } } if (chance >= uniform_random(1, 100)) { Weapon::internalUseWeapon(player, item, target, damageModifier); } else { //miss target Tile* destTile = target->getTile(); if (!Position::areInRange<1, 1, 0>(player->getPosition(), target->getPosition())) { static std::vector<std::pair<int32_t, int32_t>> destList { {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1} }; std::shuffle(destList.begin(), destList.end(), getRandomGenerator()); Position destPos = target->getPosition(); for (const auto& dir : destList) { // Blocking tiles or tiles without ground ain't valid targets for spears Tile* tmpTile = g_game().map.getTile(static_cast<uint16_t>(destPos.x + dir.first), static_cast<uint16_t>(destPos.y + dir.second), destPos.z); if (tmpTile && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID) && tmpTile->getGround() != nullptr) { destTile = tmpTile; break; } } } Weapon::internalUseWeapon(player, item, destTile); } return true; } int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* target, const Item* item) const { if (elementType == COMBAT_NONE) { return 0; } int32_t attackValue = elementDamage; if (item->getWeaponType() == WEAPON_AMMO) { Item* weapon = player->getWeapon(true); if (weapon) { attackValue += item->getAttack(); attackValue += weapon->getAttack(); } } int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); float attackFactor = player->getAttackFactor(); int32_t minValue = std::round(player->getLevel() / 5); int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue) / 2; if (target) { if (target->getPlayer()) { minValue /= 4; } else { minValue /= 2; } } return -normal_random(minValue, static_cast<int32_t>(maxValue * player->getVocation()->distDamageMultiplier)); } int16_t WeaponDistance::getElementDamageValue() const { return elementDamage; } int32_t WeaponDistance::getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage /*= false*/) const { int32_t attackValue = item->getAttack(); bool hasElement = false; if (item->getWeaponType() == WEAPON_AMMO) { Item* weapon = player->getWeapon(true); if (weapon) { const ItemType& it = Item::items[item->getID()]; if (it.abilities && it.abilities->elementDamage != 0) { attackValue += it.abilities->elementDamage; hasElement = true; } attackValue += weapon->getAttack(); } } int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); float attackFactor = player->getAttackFactor(); int32_t minValue = player->getLevel() / 5; int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue); if (maxDamage) { return -maxValue; } if (target->getPlayer()) { if (hasElement) { minValue /= 4; } else { minValue /= 2; } } else { if (hasElement) { maxValue /= 2; minValue /= 2; } } return -normal_random(minValue, maxValue); } bool WeaponDistance::getSkillType(const Player* player, const Item*, skills_t& skill, uint32_t& skillpoint) const { skill = SKILL_DISTANCE; if (player->getAddAttackSkill()) { switch (player->getLastAttackBlockType()) { case BLOCK_NONE: { skillpoint = 2; break; } case BLOCK_DEFENSE: case BLOCK_ARMOR: { skillpoint = 1; break; } default: skillpoint = 0; break; } } else { skillpoint = 0; } return true; } bool WeaponWand::configureEvent(const pugi::xml_node& node) { if (!Weapon::configureEvent(node)) { return false; } pugi::xml_attribute attr; if ((attr = node.attribute("min"))) { minChange = pugi::cast<int32_t>(attr.value()); } if ((attr = node.attribute("max"))) { maxChange = pugi::cast<int32_t>(attr.value()); } attr = node.attribute("type"); if (!attr) { return true; } std::string tmpStrValue = asLowerCaseString(attr.as_string()); if (tmpStrValue == "earth") { params.combatType = COMBAT_EARTHDAMAGE; } else if (tmpStrValue == "ice") { params.combatType = COMBAT_ICEDAMAGE; } else if (tmpStrValue == "energy") { params.combatType = COMBAT_ENERGYDAMAGE; } else if (tmpStrValue == "fire") { params.combatType = COMBAT_FIREDAMAGE; } else if (tmpStrValue == "death") { params.combatType = COMBAT_DEATHDAMAGE; } else if (tmpStrValue == "holy") { params.combatType = COMBAT_HOLYDAMAGE; } else { SPDLOG_WARN("[WeaponWand::configureEvent] - " "Type {} does not exist", attr.as_string()); } return true; } void WeaponWand::configureWeapon(const ItemType& it) { params.distanceEffect = it.shootType; const_cast<ItemType&>(it).combatType = params.combatType; const_cast<ItemType&>(it).maxHitChance = (minChange + maxChange) / 2; Weapon::configureWeapon(it); } int32_t WeaponWand::getWeaponDamage(const Player*, const Creature*, const Item*, bool maxDamage /*= false*/) const { if (maxDamage) { return -maxChange; } return -normal_random(minChange, maxChange); } int16_t WeaponWand::getElementDamageValue() const { return 0; }
26.291992
194
0.682539
Waclaw-I
c2ba3bbe0fe0efa2f354c638489ddc65aae093c9
34,408
cpp
C++
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityLoadManager.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityLoadManager.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityLoadManager.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2010. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Handles management for loading of entities ------------------------------------------------------------------------- History: - 15:03:2010: Created by Kevin Kirst *************************************************************************/ #include "stdafx.h" #include "EntityLoadManager.h" #include "EntityPoolManager.h" #include "EntitySystem.h" #include "Entity.h" #include "EntityLayer.h" #include "INetwork.h" ////////////////////////////////////////////////////////////////////////// CEntityLoadManager::CEntityLoadManager(CEntitySystem *pEntitySystem) : m_pEntitySystem(pEntitySystem) , m_bSWLoading(false) { assert(m_pEntitySystem); } ////////////////////////////////////////////////////////////////////////// CEntityLoadManager::~CEntityLoadManager() { stl::free_container(m_queuedAttachments); stl::free_container(m_queuedFlowgraphs); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::Reset() { m_clonedLayerIds.clear(); } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::LoadEntities(XmlNodeRef &entitiesNode, bool bIsLoadingLevelFile, const Vec3 &segmentOffset, std::vector<IEntity *> *outGlobalEntityIds, std::vector<IEntity *> *outLocalEntityIds) { bool bResult = false; m_bSWLoading = gEnv->p3DEngine->IsSegmentOperationInProgress(); if (entitiesNode && ReserveEntityIds(entitiesNode)) { PrepareBatchCreation(entitiesNode->getChildCount()); bResult = ParseEntities(entitiesNode, bIsLoadingLevelFile, segmentOffset, outGlobalEntityIds, outLocalEntityIds); OnBatchCreationCompleted(); } return bResult; } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::SetupHeldLayer(const char* pLayerName) { // Look up the layer with this name. Note that normally only layers that can be // dynamically loaded will be in here, but we have a hack in ObjectLayerManager to make // one of these for every layer. CEntityLayer* pLayer = m_pEntitySystem->FindLayer(pLayerName); // Walk up the layer tree until we find the top level parent. That's what we group held // entities by. while (pLayer != NULL) { const string& parentName = pLayer->GetParentName(); if (parentName.empty()) break; pLayer = m_pEntitySystem->FindLayer(parentName.c_str()); } if (!gEnv->IsEditor()) CRY_ASSERT_MESSAGE(pLayer != NULL, "All layers should be in the entity system, level may need to be reexported"); if (pLayer != NULL) { int heldLayerIdx = -1; // Go through our held layers, looking for one with the parent name for (size_t i = 0; i < m_heldLayers.size(); ++i) { if (m_heldLayers[i].m_layerName == pLayer->GetName()) { heldLayerIdx = i; break; } } // Crc the original layer name and add it to the map. If the layer is held we // store the index, or -1 if it isn't held. uint32 layerCrc = gEnv->pSystem->GetCrc32Gen()->GetCRC32(pLayerName); m_layerNameMap[layerCrc] = heldLayerIdx; } } bool CEntityLoadManager::IsHeldLayer(XmlNodeRef& entityNode) { if (m_heldLayers.empty()) return false; const char* pLayerName = entityNode->getAttr("Layer"); uint32 layerCrc = gEnv->pSystem->GetCrc32Gen()->GetCRC32(pLayerName); std::map<uint32, int>::iterator it = m_layerNameMap.find(layerCrc); // First time we've seen this layer, cache off info for it if (it == m_layerNameMap.end()) { SetupHeldLayer(pLayerName); it = m_layerNameMap.find(layerCrc); if (it == m_layerNameMap.end()) return false; } int heldLayerIdx = it->second; // If this is a held layer, cache off the creation info and return true (don't add) if (heldLayerIdx != -1) { m_heldLayers[heldLayerIdx].m_entities.push_back(entityNode); return true; } else { return false; } } void CEntityLoadManager::HoldLayerEntities(const char* pLayerName) { m_heldLayers.resize(m_heldLayers.size() + 1); SHeldLayer& heldLayer = m_heldLayers[m_heldLayers.size() - 1]; heldLayer.m_layerName = pLayerName; } void CEntityLoadManager::CloneHeldLayerEntities(const char* pLayerName, const Vec3& localOffset, const Matrix34& l2w, const char** pIncludeLayers, int numIncludeLayers) { int heldLayerIdx = -1; // Get the index of the held layer for (size_t i = 0; i < m_heldLayers.size(); ++i) { if (m_heldLayers[i].m_layerName == pLayerName) { heldLayerIdx = i; break; } } if (heldLayerIdx == -1) { CRY_ASSERT_MESSAGE(0, "Trying to add a layer that wasn't held"); return; } // Allocate a map for storing the mapping from the original entity ids to the cloned ones int cloneIdx = (int)m_clonedLayerIds.size(); m_clonedLayerIds.resize(cloneIdx+1); TClonedIds& clonedIds = m_clonedLayerIds[cloneIdx]; // Get all the held entities for this layer std::vector<XmlNodeRef>& entities = m_heldLayers[heldLayerIdx].m_entities; CEntityPoolManager *pEntityPoolManager = m_pEntitySystem->GetEntityPoolManager(); assert(pEntityPoolManager); const bool bEnablePoolUse = pEntityPoolManager->IsUsingPools(); const int nSize=entities.size(); for (int i = 0; i < nSize; i++) { XmlNodeRef entityNode = entities[i]; const char* pLayerName = entityNode->getAttr("Layer"); bool isIncluded = (numIncludeLayers > 0) ? false : true; // Check if this layer is in our include list for (int j = 0; j < numIncludeLayers; ++j) { if (strcmp(pLayerName, pIncludeLayers[j]) == 0) { isIncluded = true; break; } } if (!isIncluded) continue; ////////////////////////////////////////////////////////////////////////// // // Copy/paste from CEntityLoadManager::ParseEntities // INDENT_LOG_DURING_SCOPE (true, "Parsing entity '%s'", entityNode->getAttr("Name")); bool bSuccess = false; SEntityLoadParams loadParams; if (ExtractEntityLoadParams(entityNode, loadParams, Vec3(0,0,0), true)) { // ONLY REAL CHANGES //////////////////////////////////////////////////// Matrix34 local(Matrix33(loadParams.spawnParams.qRotation)); local.SetTranslation(loadParams.spawnParams.vPosition - localOffset); Matrix34 world = l2w * local; // If this entity has a parent, keep the transform local EntityId parentId; if (entityNode->getAttr("ParentId", parentId)) { local.SetTranslation(loadParams.spawnParams.vPosition); world = local; } loadParams.spawnParams.vPosition = world.GetTranslation(); loadParams.spawnParams.qRotation = Quat(world); EntityId origId = loadParams.spawnParams.id; loadParams.spawnParams.id = m_pEntitySystem->GenerateEntityId(true); loadParams.clonedLayerId = cloneIdx; ////////////////////////////////////////////////////////////////////////// if (bEnablePoolUse && loadParams.spawnParams.bCreatedThroughPool) { CEntityPoolManager *pPoolManager = m_pEntitySystem->GetEntityPoolManager(); bSuccess = (pPoolManager && pPoolManager->AddPoolBookmark(loadParams)); } // Default to just creating the entity if (!bSuccess) { EntityId usingId = 0; // if we just want to reload this entity's properties if (entityNode->haveAttr("ReloadProperties")) { EntityId id; entityNode->getAttr("EntityId", id); loadParams.pReuseEntity = m_pEntitySystem->GetEntityFromID(id); } bSuccess = CreateEntity(loadParams, usingId, true); } if (!bSuccess) { string sName = entityNode->getAttr("Name"); EntityWarning("CEntityLoadManager::ParseEntities : Failed when parsing entity \'%s\'", sName.empty() ? "Unknown" : sName.c_str()); } else { // If we successfully cloned the entity, save the mapping from original id to cloned clonedIds[origId] = loadParams.spawnParams.id; m_clonedEntitiesTemp.push_back(loadParams.spawnParams.id); } } // // End copy/paste // ////////////////////////////////////////////////////////////////////////// } // All attachment parent ids will be for the source copy, so we need to remap that id // to the cloned one. TQueuedAttachments::iterator itQueuedAttachment = m_queuedAttachments.begin(); TQueuedAttachments::iterator itQueuedAttachmentEnd = m_queuedAttachments.end(); for (; itQueuedAttachment != itQueuedAttachmentEnd; ++itQueuedAttachment) { SEntityAttachment& entityAttachment = *itQueuedAttachment; entityAttachment.parent = m_pEntitySystem->GetClonedEntityId(entityAttachment.parent, entityAttachment.child); } // Now that all the cloned ids are ready, go though all the entities we just cloned // and update the ids for any entity links. for (std::vector<EntityId>::iterator it = m_clonedEntitiesTemp.begin(); it != m_clonedEntitiesTemp.end(); ++it) { IEntity* pEntity = m_pEntitySystem->GetEntity(*it); if (pEntity != NULL) { IEntityLink* pLink = pEntity->GetEntityLinks(); while (pLink != NULL) { pLink->entityId = m_pEntitySystem->GetClonedEntityId(pLink->entityId, *it); pLink = pLink->next; } } } m_clonedEntitiesTemp.clear(); OnBatchCreationCompleted(); } void CEntityLoadManager::ReleaseHeldEntities() { m_heldLayers.clear(); m_layerNameMap.clear(); } ////////////////////////////////////////////////////////////////////////// //bool CEntityLoadManager::CreateEntities(TEntityLoadParamsContainer &container) //{ // bool bResult = container.empty(); // // if (!bResult) // { // PrepareBatchCreation(container.size()); // // bResult = true; // TEntityLoadParamsContainer::iterator itLoadParams = container.begin(); // TEntityLoadParamsContainer::iterator itLoadParamsEnd = container.end(); // for (; itLoadParams != itLoadParamsEnd; ++itLoadParams) // { // bResult &= CreateEntity(*itLoadParams); // } // // OnBatchCreationCompleted(); // } // // return bResult; //} ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ReserveEntityIds(XmlNodeRef &entitiesNode) { assert( entitiesNode ); bool bResult = false; // Reserve the Ids to coop with dynamic entity spawning that may happen during this stage const int iChildCount = (entitiesNode ? entitiesNode->getChildCount() : 0); for (int i = 0; i < iChildCount; ++i) { XmlNodeRef entityNode = entitiesNode->getChild(i); if (entityNode && entityNode->isTag("Entity")) { EntityId entityId; EntityGUID guid; if (entityNode->getAttr("EntityId", entityId)) { m_pEntitySystem->ReserveEntityId(entityId); bResult = true; } else if(entityNode->getAttr("EntityGuid", guid)) { bResult = true; } else { // entity has no ID assigned bResult = true; } } } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::CanParseEntity(XmlNodeRef &entityNode, std::vector<IEntity *> *outGlobalEntityIds) { assert( entityNode ); bool bResult = true; if (!entityNode) return bResult; int nMinSpec = -1; if (entityNode->getAttr("MinSpec", nMinSpec) && nMinSpec > 0) { static ICVar *e_obj_quality(gEnv->pConsole->GetCVar("e_ObjQuality")); int obj_quality = (e_obj_quality ? e_obj_quality->GetIVal() : 0); // If the entity minimal spec is higher then the current server object quality this entity will not be loaded. bResult = (obj_quality >= nMinSpec || obj_quality == 0); } int globalInSW = 0; if(m_bSWLoading && outGlobalEntityIds && entityNode && entityNode->getAttr("GlobalInSW", globalInSW) && globalInSW) { EntityGUID guid; if(entityNode->getAttr("EntityGuid", guid)) { EntityId id = gEnv->pEntitySystem->FindEntityByGuid(guid); if(IEntity *pEntity = gEnv->pEntitySystem->GetEntity(id)) { #ifdef SEG_WORLD pEntity->SetLocalSeg(false); #endif outGlobalEntityIds->push_back(pEntity); } } // In segmented world, global entity will not be loaded while streaming each segment bResult &= false; } if (bResult) { const char* pLayerName = entityNode->getAttr("Layer"); CEntityLayer* pLayer = m_pEntitySystem->FindLayer( pLayerName ); if (pLayer) bResult = !pLayer->IsSkippedBySpec(); } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ParseEntities(XmlNodeRef &entitiesNode, bool bIsLoadingLevelFile, const Vec3 &segmentOffset, std::vector<IEntity *> *outGlobalEntityIds, std::vector<IEntity *> *outLocalEntityIds) { #if !defined(SYS_ENV_AS_STRUCT) assert(gEnv); PREFAST_ASSUME(gEnv); #endif assert(entitiesNode); bool bResult = true; CEntityPoolManager *pEntityPoolManager = m_pEntitySystem->GetEntityPoolManager(); assert(pEntityPoolManager); const bool bEnablePoolUse = pEntityPoolManager->IsUsingPools(); const int iChildCount = entitiesNode->getChildCount(); CryLog ("Parsing %u entities...", iChildCount); INDENT_LOG_DURING_SCOPE(); for (int i = 0; i < iChildCount; ++i) { //Update loading screen and important tick functions SYNCHRONOUS_LOADING_TICK(); XmlNodeRef entityNode = entitiesNode->getChild(i); if (entityNode && entityNode->isTag("Entity") && CanParseEntity(entityNode, outGlobalEntityIds)) { // Create entities only if they are not in an held layer and we are not in editor game mode. if (!IsHeldLayer(entityNode) && !gEnv->IsEditorGameMode()) { INDENT_LOG_DURING_SCOPE (true, "Parsing entity '%s'", entityNode->getAttr("Name")); bool bSuccess = false; SEntityLoadParams loadParams; if (ExtractEntityLoadParams(entityNode, loadParams, segmentOffset, true)) { if (bEnablePoolUse && loadParams.spawnParams.bCreatedThroughPool) { CEntityPoolManager *pPoolManager = m_pEntitySystem->GetEntityPoolManager(); bSuccess = (pPoolManager && pPoolManager->AddPoolBookmark(loadParams)); } // Default to just creating the entity if (!bSuccess) { EntityId usingId = 0; // if we just want to reload this entity's properties if (entityNode->haveAttr("ReloadProperties")) { EntityId id; entityNode->getAttr("EntityId", id); loadParams.pReuseEntity = m_pEntitySystem->GetEntityFromID(id); } bSuccess = CreateEntity(loadParams, usingId, bIsLoadingLevelFile); if(m_bSWLoading && outLocalEntityIds && usingId) { if (IEntity *pEntity = m_pEntitySystem->GetEntity(usingId)) { #ifdef SEG_WORLD pEntity->SetLocalSeg(true); #endif outLocalEntityIds->push_back(pEntity); } } } } if (!bSuccess) { string sName = entityNode->getAttr("Name"); EntityWarning("CEntityLoadManager::ParseEntities : Failed when parsing entity \'%s\'", sName.empty() ? "Unknown" : sName.c_str()); } bResult &= bSuccess; } } if (0 == (i&7)) { gEnv->pNetwork->SyncWithGame(eNGS_FrameStart); gEnv->pNetwork->SyncWithGame(eNGS_FrameEnd); gEnv->pNetwork->SyncWithGame(eNGS_WakeNetwork); } } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ExtractEntityLoadParams(XmlNodeRef &entityNode, SEntityLoadParams &outLoadParams, const Vec3 &segmentOffset,bool bWarningMsg) const { assert(entityNode); bool bResult = true; const char *sEntityClass = entityNode->getAttr("EntityClass"); const char *sEntityName = entityNode->getAttr("Name"); IEntityClass *pClass = m_pEntitySystem->GetClassRegistry()->FindClass(sEntityClass); if (pClass) { SEntitySpawnParams &spawnParams = outLoadParams.spawnParams; outLoadParams.spawnParams.entityNode = entityNode; // Load spawn parameters from xml node. spawnParams.pClass = pClass; spawnParams.sName = sEntityName; spawnParams.sLayerName = entityNode->getAttr("Layer"); // Entities loaded from the xml cannot be fully deleted in single player. if (!gEnv->bMultiplayer) spawnParams.nFlags |= ENTITY_FLAG_UNREMOVABLE; Vec3 pos(Vec3Constants<float>::fVec3_Zero); Quat rot(Quat::CreateIdentity()); Vec3 scale(Vec3Constants<float>::fVec3_One); entityNode->getAttr("Pos", pos); entityNode->getAttr("Rotate", rot); entityNode->getAttr("Scale", scale); /*Ang3 vAngles; if (entityNode->getAttr("Angles", vAngles)) { spawnParams.qRotation.SetRotationXYZ(vAngles); }*/ spawnParams.vPosition = pos; spawnParams.qRotation = rot; spawnParams.vScale = scale; spawnParams.id = 0; if(!gEnv->pEntitySystem->EntitiesUseGUIDs()) { entityNode->getAttr("EntityId", spawnParams.id); } entityNode->getAttr("EntityGuid", spawnParams.guid); ISegmentsManager *pSM = gEnv->p3DEngine->GetSegmentsManager(); if(pSM) { Vec2 coordInSW(Vec2Constants<float>::fVec2_Zero); if(entityNode->getAttr("CoordInSW", coordInSW)) pSM->GlobalSegVecToLocalSegVec(pos, coordInSW, spawnParams.vPosition); EntityGUID parentGuid; if(!entityNode->getAttr("ParentGuid", parentGuid)) spawnParams.vPosition += segmentOffset; } // Get flags. //bool bRecvShadow = true; // true by default (do not change, it must be coordinated with editor export) bool bGoodOccluder = false; // false by default (do not change, it must be coordinated with editor export) bool bOutdoorOnly = false; bool bNoDecals = false; int nCastShadowMinSpec = CONFIG_LOW_SPEC; entityNode->getAttr("CastShadowMinSpec", nCastShadowMinSpec); //entityNode->getAttr("RecvShadow", bRecvShadow); entityNode->getAttr("GoodOccluder", bGoodOccluder); entityNode->getAttr("OutdoorOnly", bOutdoorOnly); entityNode->getAttr("NoDecals", bNoDecals); static ICVar* pObjShadowCastSpec = gEnv->pConsole->GetCVar("e_ObjShadowCastSpec"); if(nCastShadowMinSpec <= pObjShadowCastSpec->GetIVal()) { spawnParams.nFlags |= ENTITY_FLAG_CASTSHADOW; } //if (bRecvShadow) //spawnParams.nFlags |= ENTITY_FLAG_RECVSHADOW; if (bGoodOccluder) spawnParams.nFlags |= ENTITY_FLAG_GOOD_OCCLUDER; if(bOutdoorOnly) spawnParams.nFlags |= ENTITY_FLAG_OUTDOORONLY; if(bNoDecals) spawnParams.nFlags |= ENTITY_FLAG_NO_DECALNODE_DECALS; const char *sArchetypeName = entityNode->getAttr("Archetype"); if (sArchetypeName && sArchetypeName[0]) { MEMSTAT_CONTEXT_FMT(EMemStatContextTypes::MSC_Other, 0, "%s", sArchetypeName); spawnParams.pArchetype = m_pEntitySystem->LoadEntityArchetype(sArchetypeName); if (!spawnParams.pArchetype) { EntityWarning("Archetype %s used by entity %s cannot be found! Entity cannot be loaded.", sArchetypeName, spawnParams.sName); bResult = false; } } entityNode->getAttr("CreatedThroughPool", spawnParams.bCreatedThroughPool); if (!spawnParams.bCreatedThroughPool) { // Check if forced via its class CEntityPoolManager *pPoolManager = m_pEntitySystem->GetEntityPoolManager(); spawnParams.bCreatedThroughPool = (pPoolManager && pPoolManager->IsClassForcedBookmarked(pClass)); } } else // No entity class found! { if (bWarningMsg) EntityWarning("Entity class %s used by entity %s cannot be found! Entity cannot be loaded.", sEntityClass, sEntityName); bResult = false; } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ExtractEntityLoadParams(XmlNodeRef &entityNode, SEntitySpawnParams &spawnParams) const { SEntityLoadParams loadParams; bool bRes=ExtractEntityLoadParams(entityNode,loadParams,Vec3(0,0,0),false); spawnParams=loadParams.spawnParams; return(bRes); } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::CreateEntity(XmlNodeRef &entityNode,SEntitySpawnParams &pParams,EntityId &outUsingId) { SEntityLoadParams loadParams; loadParams.spawnParams=pParams; loadParams.spawnParams.entityNode=entityNode; if ((loadParams.spawnParams.id==0) && ((loadParams.spawnParams.pClass->GetFlags() & ECLF_DO_NOT_SPAWN_AS_STATIC) == 0)) { // If ID is not set we generate a static ID. loadParams.spawnParams.id=m_pEntitySystem->GenerateEntityId(true); } return(CreateEntity(loadParams,outUsingId,true)); } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::CreateEntity(SEntityLoadParams &loadParams, EntityId &outUsingId, bool bIsLoadingLevellFile) { MEMSTAT_CONTEXT_FMT(EMemStatContextTypes::MSC_Entity, 0, "Entity %s", loadParams.spawnParams.pClass->GetName()); bool bResult = true; outUsingId = 0; XmlNodeRef &entityNode = loadParams.spawnParams.entityNode; SEntitySpawnParams &spawnParams = loadParams.spawnParams; uint32 entityGuid = 0; if(entityNode) { // Only runtime prefabs should have GUID id's const char* entityGuidStr = entityNode->getAttr("Id"); if (entityGuidStr[0] != '\0') { entityGuid = gEnv->pSystem->GetCrc32Gen()->GetCRC32Lowercase(entityGuidStr); } } IEntity *pSpawnedEntity = NULL; bool bWasSpawned = false; if (loadParams.pReuseEntity) { // Attempt to reload pSpawnedEntity = (loadParams.pReuseEntity->ReloadEntity(loadParams) ? loadParams.pReuseEntity : NULL); } else if (m_pEntitySystem->OnBeforeSpawn(spawnParams)) { // Create a new one pSpawnedEntity = m_pEntitySystem->SpawnEntity(spawnParams, false); bWasSpawned = true; } if (bResult && pSpawnedEntity) { m_pEntitySystem->AddEntityToLayer(spawnParams.sLayerName, pSpawnedEntity->GetId()); CEntity *pCSpawnedEntity = (CEntity*)pSpawnedEntity; pCSpawnedEntity->SetLoadedFromLevelFile(bIsLoadingLevellFile); pCSpawnedEntity->SetCloneLayerId(loadParams.clonedLayerId); const char *szMtlName(NULL); if (spawnParams.pArchetype) { IScriptTable* pArchetypeProperties=spawnParams.pArchetype->GetProperties(); if (pArchetypeProperties) { pArchetypeProperties->GetValue("PrototypeMaterial",szMtlName); } } if (entityNode) { // Create needed proxies if (entityNode->findChild("Area")) { pSpawnedEntity->CreateProxy(ENTITY_PROXY_AREA); } if (entityNode->findChild("Rope")) { pSpawnedEntity->CreateProxy(ENTITY_PROXY_ROPE); } if (entityNode->findChild("ClipVolume")) { pSpawnedEntity->CreateProxy(ENTITY_PROXY_CLIPVOLUME); } if (spawnParams.pClass) { const char* pClassName = spawnParams.pClass->GetName(); if (pClassName && !strcmp(pClassName, "Light")) { IEntityRenderProxyPtr pRP = crycomponent_cast<IEntityRenderProxyPtr> (pSpawnedEntity->CreateProxy(ENTITY_PROXY_RENDER)); if (pRP) { pRP->SerializeXML(entityNode, true); int nMinSpec = -1; if (entityNode->getAttr("MinSpec", nMinSpec) && nMinSpec >= 0) pRP->GetRenderNode()->SetMinSpec(nMinSpec); } } } // If we have an instance material, we use it... if (entityNode->haveAttr("Material")) { szMtlName = entityNode->getAttr("Material"); } // Prepare the entity from Xml if it was just spawned if (pCSpawnedEntity && bWasSpawned) { if (IEntityPropertyHandler* pPropertyHandler = pCSpawnedEntity->GetClass()->GetPropertyHandler()) pPropertyHandler->LoadEntityXMLProperties(pCSpawnedEntity, entityNode); if (IEntityEventHandler* pEventHandler = pCSpawnedEntity->GetClass()->GetEventHandler()) pEventHandler->LoadEntityXMLEvents(pCSpawnedEntity, entityNode); // Serialize script proxy. CScriptProxy *pScriptProxy = pCSpawnedEntity->GetScriptProxy(); if (pScriptProxy) pScriptProxy->SerializeXML(entityNode, true); } } // If any material has to be set... if (szMtlName && *szMtlName != 0) { // ... we load it... IMaterial *pMtl = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(szMtlName); if (pMtl) { // ... and set it... pSpawnedEntity->SetMaterial(pMtl); } } if (bWasSpawned) { const bool bInited = m_pEntitySystem->InitEntity(pSpawnedEntity, spawnParams); if (!bInited) { // Failed to initialise an entity, need to bail or we'll crash return true; } } else { m_pEntitySystem->OnEntityReused(pSpawnedEntity, spawnParams); if (pCSpawnedEntity && loadParams.bCallInit) { CScriptProxy *pScriptProxy = pCSpawnedEntity->GetScriptProxy(); if (pScriptProxy) pScriptProxy->CallInitEvent(true); } } if (entityNode) { ////////////////////////////////////////////////////////////////////////// // Load geom entity (Must be before serializing proxies. ////////////////////////////////////////////////////////////////////////// if (spawnParams.pClass->GetFlags() & ECLF_DEFAULT) { // Check if it have geometry. const char *sGeom = entityNode->getAttr("Geometry"); if (sGeom[0] != 0) { // check if character. const char *ext = PathUtil::GetExt(sGeom); if (stricmp(ext,CRY_SKEL_FILE_EXT) == 0 || stricmp(ext,CRY_CHARACTER_DEFINITION_FILE_EXT) == 0 || stricmp(ext,CRY_ANIM_GEOMETRY_FILE_EXT) == 0) { pSpawnedEntity->LoadCharacter( 0,sGeom,IEntity::EF_AUTO_PHYSICALIZE ); } else { pSpawnedEntity->LoadGeometry( 0,sGeom,0,IEntity::EF_AUTO_PHYSICALIZE ); } } } ////////////////////////////////////////////////////////////////////////// // Serialize all entity proxies except Script proxy after initialization. if (pCSpawnedEntity) { CScriptProxy *pScriptProxy = pCSpawnedEntity->GetScriptProxy(); pCSpawnedEntity->SerializeXML_ExceptScriptProxy( entityNode, true ); } const char *attachmentType = entityNode->getAttr("AttachmentType"); const char *attachmentTarget = entityNode->getAttr("AttachmentTarget"); int flags = 0; if (strcmp(attachmentType, "GeomCacheNode") == 0) { flags |= IEntity::ATTACHMENT_GEOMCACHENODE; } else if (strcmp(attachmentType, "CharacterBone") == 0) { flags |= IEntity::ATTACHMENT_CHARACTERBONE; } // Add attachment to parent. if(m_pEntitySystem->EntitiesUseGUIDs()) { EntityGUID nParentGuid = 0; if (entityNode->getAttr( "ParentGuid",nParentGuid )) { AddQueuedAttachment(0, nParentGuid, spawnParams.id, spawnParams.vPosition, spawnParams.qRotation, spawnParams.vScale, false, flags, attachmentTarget); } } else if (entityGuid == 0) { EntityId nParentId = 0; if (entityNode->getAttr("ParentId", nParentId)) { AddQueuedAttachment(nParentId, 0, spawnParams.id, spawnParams.vPosition, spawnParams.qRotation, spawnParams.vScale, false, flags, attachmentTarget); } } else { const char* pParentGuid = entityNode->getAttr("Parent"); if (pParentGuid[0] != '\0') { uint32 parentGuid = gEnv->pSystem->GetCrc32Gen()->GetCRC32Lowercase(pParentGuid); AddQueuedAttachment((EntityId)parentGuid, 0, spawnParams.id, spawnParams.vPosition, spawnParams.qRotation, spawnParams.vScale, true, flags, attachmentTarget); } } // check for a flow graph // only store them for later serialization as the FG proxy relies // on all EntityGUIDs already loaded if (entityNode->findChild("FlowGraph")) { AddQueuedFlowgraph(pSpawnedEntity, entityNode); } // Load entity links. XmlNodeRef linksNode = entityNode->findChild("EntityLinks"); if (linksNode) { const int iChildCount = linksNode->getChildCount(); for (int i = 0; i < iChildCount; ++i) { XmlNodeRef linkNode = linksNode->getChild(i); if (linkNode) { if (entityGuid == 0) { EntityId targetId = 0; EntityGUID targetGuid = 0; if (gEnv->pEntitySystem->EntitiesUseGUIDs()) linkNode->getAttr( "TargetGuid",targetGuid ); else linkNode->getAttr("TargetId", targetId); const char *sLinkName = linkNode->getAttr("Name"); Quat relRot(IDENTITY); Vec3 relPos(IDENTITY); pSpawnedEntity->AddEntityLink(sLinkName, targetId, targetGuid); } else { // If this is a runtime prefab we're spawning, queue the entity // link for later, since it has a guid target id we need to look up. AddQueuedEntityLink(pSpawnedEntity, linkNode); } } } } // Hide entity in game. Done after potential RenderProxy is created, so it catches the Hide if (bWasSpawned) { bool bHiddenInGame = false; entityNode->getAttr("HiddenInGame", bHiddenInGame); if (bHiddenInGame) pSpawnedEntity->Hide(true); } int nMinSpec = -1; if (entityNode->getAttr("MinSpec", nMinSpec) && nMinSpec >= 0) { if (IEntityRenderProxy *pRenderProxy = (IEntityRenderProxy*)pSpawnedEntity->GetProxy(ENTITY_PROXY_RENDER)) pRenderProxy->GetRenderNode()->SetMinSpec(nMinSpec); } } } if (!bResult) { EntityWarning("[CEntityLoadManager::CreateEntity] Entity Load Failed: %s (%s)", spawnParams.sName, spawnParams.pClass->GetName()); } outUsingId = (pSpawnedEntity ? pSpawnedEntity->GetId() : 0); if (outUsingId != 0 && entityGuid != 0) { m_guidToId[entityGuid] = outUsingId; } return bResult; } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::PrepareBatchCreation(int nSize) { m_queuedAttachments.clear(); m_queuedFlowgraphs.clear(); m_queuedAttachments.reserve(nSize); m_queuedFlowgraphs.reserve(nSize); m_guidToId.clear(); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::AddQueuedAttachment(EntityId nParent, EntityGUID nParentGuid, EntityId nChild, const Vec3& pos, const Quat& rot, const Vec3& scale, bool guid, const int flags, const char *target) { SEntityAttachment entityAttachment; entityAttachment.child = nChild; entityAttachment.parent = nParent; entityAttachment.parentGuid = nParentGuid; entityAttachment.pos = pos; entityAttachment.rot = rot; entityAttachment.scale = scale; entityAttachment.guid = guid; entityAttachment.flags = flags; entityAttachment.target = target; m_queuedAttachments.push_back(entityAttachment); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::AddQueuedFlowgraph(IEntity *pEntity, XmlNodeRef &pNode) { SQueuedFlowGraph f; f.pEntity = pEntity; f.pNode = pNode; m_queuedFlowgraphs.push_back(f); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::AddQueuedEntityLink(IEntity *pEntity, XmlNodeRef &pNode) { SQueuedFlowGraph f; f.pEntity = pEntity; f.pNode = pNode; m_queuedEntityLinks.push_back(f); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::OnBatchCreationCompleted() { CEntityPoolManager *pEntityPoolManager = m_pEntitySystem->GetEntityPoolManager(); assert(pEntityPoolManager); // Load attachments TQueuedAttachments::iterator itQueuedAttachment = m_queuedAttachments.begin(); TQueuedAttachments::iterator itQueuedAttachmentEnd = m_queuedAttachments.end(); for (; itQueuedAttachment != itQueuedAttachmentEnd; ++itQueuedAttachment) { const SEntityAttachment &entityAttachment = *itQueuedAttachment; IEntity *pChild = m_pEntitySystem->GetEntity(entityAttachment.child); if (pChild) { EntityId parentId = entityAttachment.parent; if (m_pEntitySystem->EntitiesUseGUIDs()) parentId = m_pEntitySystem->FindEntityByGuid(entityAttachment.parentGuid); else if (entityAttachment.guid) parentId = m_guidToId[(uint32)entityAttachment.parent]; IEntity *pParent = m_pEntitySystem->GetEntity(parentId); if (pParent) { SChildAttachParams attachParams(entityAttachment.flags, entityAttachment.target.c_str()); pParent->AttachChild(pChild, attachParams); pChild->SetLocalTM(Matrix34::Create(entityAttachment.scale, entityAttachment.rot, entityAttachment.pos)); } else if (pEntityPoolManager->IsEntityBookmarked(entityAttachment.parent)) { pEntityPoolManager->AddAttachmentToBookmark(entityAttachment.parent, entityAttachment); } } } m_queuedAttachments.clear(); // Load flowgraphs TQueuedFlowgraphs::iterator itQueuedFlowgraph = m_queuedFlowgraphs.begin(); TQueuedFlowgraphs::iterator itQueuedFlowgraphEnd = m_queuedFlowgraphs.end(); for (; itQueuedFlowgraph != itQueuedFlowgraphEnd; ++itQueuedFlowgraph) { SQueuedFlowGraph &f = *itQueuedFlowgraph; if (f.pEntity) { IEntityProxyPtr pProxy = f.pEntity->CreateProxy(ENTITY_PROXY_FLOWGRAPH); if (pProxy) pProxy->SerializeXML(f.pNode, true); } } m_queuedFlowgraphs.clear(); // Load entity links TQueuedFlowgraphs::iterator itQueuedEntityLink = m_queuedEntityLinks.begin(); TQueuedFlowgraphs::iterator itQueuedEntityLinkEnd = m_queuedEntityLinks.end(); for (; itQueuedEntityLink != itQueuedEntityLinkEnd; ++itQueuedEntityLink) { SQueuedFlowGraph &f = *itQueuedEntityLink; if (f.pEntity) { const char* targetGuidStr = f.pNode->getAttr("TargetId"); if (targetGuidStr[0] != '\0') { EntityId targetId = FindEntityByEditorGuid(targetGuidStr); const char *sLinkName = f.pNode->getAttr("Name"); Quat relRot(IDENTITY); Vec3 relPos(IDENTITY); f.pEntity->AddEntityLink(sLinkName, targetId, 0); } } } stl::free_container(m_queuedEntityLinks); stl::free_container(m_guidToId); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::ResolveLinks() { if(!m_pEntitySystem->EntitiesUseGUIDs()) return; IEntityItPtr pIt = m_pEntitySystem->GetEntityIterator(); pIt->MoveFirst(); while (IEntity* pEntity = pIt->Next()) { IEntityLink* pLink = pEntity->GetEntityLinks(); while (pLink) { if (pLink->entityId == 0) pLink->entityId = m_pEntitySystem->FindEntityByGuid(pLink->entityGuid); pLink = pLink->next; } } } ////////////////////////////////////////////////////////////////////////// EntityId CEntityLoadManager::GetClonedId(int clonedLayerId, EntityId originalId) { if (clonedLayerId >= 0 && clonedLayerId < (int)m_clonedLayerIds.size()) { TClonedIds& clonedIds = m_clonedLayerIds[clonedLayerId]; return clonedIds[originalId]; } return 0; } ////////////////////////////////////////////////////////////////////////// EntityId CEntityLoadManager::FindEntityByEditorGuid(const char* pGuid) const { uint32 guidCrc = gEnv->pSystem->GetCrc32Gen()->GetCRC32Lowercase(pGuid); TGuidToId::const_iterator it = m_guidToId.find(guidCrc); if (it != m_guidToId.end()) return it->second; return INVALID_ENTITYID; }
30.557726
204
0.668449
amrhead
c2ba81a29826d6addde581df2c9f48c2fb6cc0f4
283
hpp
C++
includes/AbstractClasses/AbstractVisitable.hpp
edubrunaldi/poker-bot
b851aa86c73a5b1b6c586439fbc01ccecac8c0f1
[ "MIT" ]
null
null
null
includes/AbstractClasses/AbstractVisitable.hpp
edubrunaldi/poker-bot
b851aa86c73a5b1b6c586439fbc01ccecac8c0f1
[ "MIT" ]
null
null
null
includes/AbstractClasses/AbstractVisitable.hpp
edubrunaldi/poker-bot
b851aa86c73a5b1b6c586439fbc01ccecac8c0f1
[ "MIT" ]
2
2019-09-08T10:40:21.000Z
2021-01-06T16:17:37.000Z
//Visitor // Created by xima on 02/08/19. // #ifndef POKER_BOT_ABSTRACTVISITABLE_HPP #define POKER_BOT_ABSTRACTVISITABLE_HPP class AbstractVisitor; class AbstractVisitable { public: virtual void accept(AbstractVisitor& visitor) = 0; }; #endif //POKER_BOT_ABSTRACTVISITABLE_HPP
17.6875
52
0.798587
edubrunaldi
c2bc4824d65d2d58cbaa73d68063130e5989eb6a
5,427
cpp
C++
examples/ndtest.cpp
Brillist/libutl
e55c2af091ba1101a1d0608db2830e279ec95d16
[ "MIT" ]
1
2021-09-14T06:12:58.000Z
2021-09-14T06:12:58.000Z
examples/ndtest.cpp
Brillist/libutl
e55c2af091ba1101a1d0608db2830e279ec95d16
[ "MIT" ]
null
null
null
examples/ndtest.cpp
Brillist/libutl
e55c2af091ba1101a1d0608db2830e279ec95d16
[ "MIT" ]
2
2019-05-13T23:04:31.000Z
2021-09-14T06:12:59.000Z
#include <libutl/libutl.h> #include <libutl/Application.h> #include <libutl/Array.h> #include <libutl/BufferedFDstream.h> #include <libutl/CmdLineArgs.h> #include <libutl/Thread.h> #undef new #include <algorithm> #include <libutl/gblnew_macros.h> //////////////////////////////////////////////////////////////////////////////////////////////////// class AllocatorThread : public utl::Thread { UTL_CLASS_DECL_ABC(AllocatorThread, utl::Thread); public: AllocatorThread(size_t* sizes, size_t numSizes, size_t numRuns) { _sizes = sizes; _numSizes = numSizes; _numRuns = numRuns; _ptrs = (void**)malloc(numSizes * sizeof(void*)); } void* run(void*); protected: virtual void oneRun() = 0; protected: size_t* _sizes; void** _ptrs; size_t _numSizes; size_t _numRuns; private: void init() { ABORT(); } void deInit() { free(_ptrs); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// void* AllocatorThread::run(void*) { for (size_t i = 0; i != _numRuns; ++i) oneRun(); return nullptr; } //////////////////////////////////////////////////////////////////////////////////////////////////// class MallocFreeThread : public AllocatorThread { UTL_CLASS_DECL(MallocFreeThread, AllocatorThread); UTL_CLASS_DEFID; public: MallocFreeThread(size_t* sizes, size_t numSizes, size_t numRuns) : AllocatorThread(sizes, numSizes, numRuns) { } protected: virtual void oneRun() { size_t* sizes = _sizes; size_t s = _numSizes; size_t* sizesLim = sizes + s; void** ptrs = _ptrs; void** ptrsLim = ptrs + s; // allocate size_t* sp = sizes; void** pp = ptrs; for (; sp != sizesLim; ++sp, ++pp) { *pp = malloc(*sp); } // free for (pp = ptrs; pp != ptrsLim; ++pp) { free(*pp); } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// class NewDeleteThread : public AllocatorThread { UTL_CLASS_DECL(NewDeleteThread, AllocatorThread); UTL_CLASS_DEFID; public: NewDeleteThread(size_t* sizes, size_t numSizes, size_t numRuns) : AllocatorThread(sizes, numSizes, numRuns) { } protected: virtual void oneRun() { size_t* sizes = _sizes; size_t s = _numSizes; size_t* sizesLim = sizes + s; void** ptrs = _ptrs; void** ptrsLim = ptrs + s; // allocate size_t* sp = sizes; void** pp = ptrs; for (; sp != sizesLim; ++sp, ++pp) { *pp = new byte_t[*sp]; } // free for (pp = ptrs; pp != ptrsLim; ++pp) { delete[](byte_t*) * pp; } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_CLASS_IMPL_ABC(AllocatorThread); UTL_CLASS_IMPL(MallocFreeThread); UTL_CLASS_IMPL(NewDeleteThread); //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_NS_USE; UTL_APP(Test); UTL_MAIN_RL(Test); //////////////////////////////////////////////////////////////////////////////////////////////////// int Test::run(int argc, char** argv) { CmdLineArgs args(argc, argv); // check if help was requested if (args.isSet("h") || args.isSet("help")) { cerr << "ndtest [-t threads] [-r runs/thread] [-c count] [-m]" << endl; return 1; } // set # of threads size_t numThreads = 1; String arg; if (args.isSet("t", arg)) { numThreads = Uint(arg); if (numThreads < 1) numThreads = 1; if (numThreads > 256) numThreads = 256; } // set # of runs per thread size_t numRuns = 1; if (args.isSet("r", arg)) { numRuns = Uint(arg); if (numRuns < 1) numRuns = 1; if (numRuns > KB(64)) numRuns = KB(64); } // set # of allocations of each size size_t numAllocs = 256; if (args.isSet("c", arg)) { numAllocs = Uint(arg); if (numAllocs < 1) numAllocs = 1; if (numAllocs > KB(16)) numAllocs = KB(16); } // use malloc/free ? bool useMalloc = args.isSet("m"); // create the array of block sizes size_t numSizes = numAllocs * (256 / 8); size_t* sizes = (size_t*)malloc(numSizes * sizeof(size_t)); size_t* sizePtr = sizes; for (size_t i = 0; i != numAllocs; ++i) { for (size_t j = 8; j <= 256; j += 8) { *sizePtr++ = j; } } // spawn threads Array threads(false); for (size_t i = 0; i != numThreads; ++i) { Thread* t; if (useMalloc) t = new MallocFreeThread(sizes, numSizes, numRuns); else t = new NewDeleteThread(sizes, numSizes, numRuns); threads += t; t->start(nullptr, true); } cout << "threads are started.." << endl; // join on threads for (size_t i = 0; i != numThreads; ++i) { Thread* t = (Thread*)threads[i]; t->join(); } cout << "threads are done!" << endl; // clean up (why not?) free(sizes); return 0; }
22.518672
100
0.466556
Brillist
c2bcd01ad7f86285605f55f77d8810315c11520b
5,399
cpp
C++
source/Model.cpp
xdanieldzd/libfrenda
ea10a413f6aac567c29d8dac43b0ab5cb207167a
[ "MIT" ]
1
2019-10-05T01:39:01.000Z
2019-10-05T01:39:01.000Z
source/Model.cpp
xdanieldzd/libfrenda
ea10a413f6aac567c29d8dac43b0ab5cb207167a
[ "MIT" ]
null
null
null
source/Model.cpp
xdanieldzd/libfrenda
ea10a413f6aac567c29d8dac43b0ab5cb207167a
[ "MIT" ]
2
2016-12-11T08:43:32.000Z
2022-01-02T07:55:33.000Z
/*------------------------------------------------------------ MODEL.CPP - "Frenda 3D" model loader -------------------------------------------------------------*/ #include "include/frenda.h" using namespace std; namespace frenda { const std::string Model::formatTag = "Fr3Dv04"; Model::Model(frenda::System *s, std::string filename) { sys = s; sys->debugLog("%s -> loading model '%s'...\n", __PRETTY_FUNCTION__, filename.c_str()); memset(&header, 0, sizeof(HeaderStruct)); memset(&textureList, 0, sizeof(TextureListStruct)); memset(&geometryList, 0, sizeof(GeometryListStruct)); load(filename); } Model::~Model() { for(uint32 i = 0; i < geometryList.geometryCount; i++) { //sys->debugLog(" -> unloading geometry %lu/%lu '%s'...\n", (i + 1), geometryList.geometryCount, geometryList.geometry[i].geometryName); for(uint32 j = 0; j < textureList.textureCount; j++) { //sys->debugLog(" -> unloading vertex list %lu/%lu\n", (j + 1), textureList.textureCount); delete[] geometryList.geometry[i].vertexLists[j].vertices; } delete[] geometryList.geometry[i].vertexLists; } delete[] geometryList.geometry; delete[] geometryList.geometryOffsets; for(uint32 i = 0; i < textureList.textureCount; i++) { if(textureList.textures[i].texture != NULL) plx_txr_destroy(textureList.textures[i].texture); } delete[] textureList.textures; delete[] textureList.textureOffsets; } void Model::load(std::string filename) { uint8 *data; file_t fd = fs_open(filename.c_str(), O_RDONLY); data = new uint8[fs_total(fd)]; fs_read(fd, data, fs_total(fd)); fs_close(fd); uint32 rofs; memcpy(&header, data, sizeof(HeaderStruct)); assert_msg(Model::formatTag.compare(header.formatTag) == 0, "Wrong model format OR version"); /* Read textures */ rofs = header.textureOffset; memcpy(&textureList.textureCount, &data[rofs], 4); rofs += 4; textureList.textureOffsets = new uint32[textureList.textureCount]; memcpy(textureList.textureOffsets, &data[rofs], (sizeof(uint32) * textureList.textureCount)); textureList.textures = new TextureDataStruct[textureList.textureCount]; for(uint32 i = 0; i < textureList.textureCount; i++) { //sys->debugLog(" -> loading texture %lu/%lu from 0x%08lx\n", (i + 1), textureList.textureCount, textureList.textureOffsets[i]); rofs = textureList.textureOffsets[i]; int w = 0, h = 0, fmt = 0, byte_count = 0; memcpy(&w, &data[rofs], 4); memcpy(&h, &data[rofs + 0x4], 4); memcpy(&fmt, &data[rofs + 0x8], 4); memcpy(&byte_count, &data[rofs + 0xC], 4); uint16 *tdata = new uint16[byte_count]; memcpy(tdata, &data[rofs + 0x10], byte_count); TextureDataStruct *t = &textureList.textures[i]; int pvrfmt = -1; if(fmt == KOS_IMG_FMT_ARGB1555) pvrfmt = PVR_TXRFMT_ARGB1555; else if(fmt == KOS_IMG_FMT_ARGB4444) pvrfmt = PVR_TXRFMT_ARGB4444; assert_msg(pvrfmt != -1, "Cannot determine PVR texture format"); t->texture = plx_txr_canvas(w, h, pvrfmt); pvr_txr_load_ex(tdata, t->texture->ptr, t->texture->w, t->texture->h, PVR_TXRLOAD_16BPP); delete[] tdata; } /* Read geometry */ rofs = header.geometryOffset; memcpy(&geometryList.geometryCount, &data[rofs], 4); rofs += 4; geometryList.geometryOffsets = new uint32[geometryList.geometryCount]; memcpy(geometryList.geometryOffsets, &data[rofs], (sizeof(uint32) * geometryList.geometryCount)); geometryList.geometry = new GeometryStruct[geometryList.geometryCount]; for(uint32 i = 0; i < geometryList.geometryCount; i++) { rofs = geometryList.geometryOffsets[i]; memcpy(&geometryList.geometry[i].geometryName, &data[rofs], 16); rofs += 16; //sys->debugLog(" -> loading geometry %lu/%lu '%s' from 0x%08lx...\n", (i + 1), geometryList.geometryCount, geometryList.geometry[i].geometryName, geometryList.geometryOffsets[i]); geometryList.geometry[i].vertexLists = new VertexListStruct[textureList.textureCount]; for(uint32 j = 0; j < textureList.textureCount; j++) { memcpy(&geometryList.geometry[i].vertexLists[j].vertexCount, &data[rofs], 4); rofs += 4; //sys->debugLog(" -> loading vertex list %lu/%lu, %lu vertices\n", (j + 1), textureList.textureCount, geometryList.geometry[i].vertexLists[j].vertexCount); geometryList.geometry[i].vertexLists[j].vertices = new pvr_vertex_t[geometryList.geometry[i].vertexLists[j].vertexCount]; if(geometryList.geometry[i].vertexLists[j].vertexCount > 0) { memcpy(geometryList.geometry[i].vertexLists[j].vertices, &data[rofs], (sizeof(pvr_vertex_t) * geometryList.geometry[i].vertexLists[j].vertexCount)); rofs += (sizeof(pvr_vertex_t) * geometryList.geometry[i].vertexLists[j].vertexCount); } } } delete[] data; } void Model::render(frenda::PVR *pvr) { for(uint32 i = 0; i < geometryList.geometryCount; i++) { render(pvr, i); } } void Model::render(frenda::PVR *pvr, uint32 geometryID) { for(uint32 i = 0; i < textureList.textureCount; i++) { if(geometryList.geometry[geometryID].vertexLists[i].vertexCount > 0) { pvr->setTexture(PVR_LIST_TR_POLY, textureList.textures[i].texture); pvr->sendVertexList(PVR_LIST_TR_POLY, geometryList.geometry[geometryID].vertexLists[i].vertices, (int)geometryList.geometry[geometryID].vertexLists[i].vertexCount); } } } }
34.608974
183
0.668828
xdanieldzd
c2bece07afb04a783cebe7bf3a55bf11cb7343ee
2,645
cpp
C++
VereEngine-Tools/GenerateTrees.cpp
VereWolf/VereEngine
6b5453554cef1ef5d5dbf58206806198a3beec35
[ "Zlib", "MIT" ]
4
2017-06-21T19:37:00.000Z
2017-07-14T06:21:40.000Z
VereEngine-Tools/GenerateTrees.cpp
VereWolf/VereEngine
6b5453554cef1ef5d5dbf58206806198a3beec35
[ "Zlib", "MIT" ]
null
null
null
VereEngine-Tools/GenerateTrees.cpp
VereWolf/VereEngine
6b5453554cef1ef5d5dbf58206806198a3beec35
[ "Zlib", "MIT" ]
1
2017-09-30T06:10:38.000Z
2017-09-30T06:10:38.000Z
#include "stdafx.h" #include "GenerateTrees.h" GenerateTrees::GenerateTrees() { SetFolderName(L"Calc_Trees"); } void GenerateTrees::Generate(int randomValue) { srand(randomValue); std::vector<int> TM; std::vector<Float4> TM2; TM.resize(512 * 512, 0); TM2.resize(512 * 512, Float4(0.0f, 0.0f, 0.0f, 0.0f)); bool B = true; int S = 0; std::vector<int> pos(4 * 8 * 8 + 1, -1); for (int i = 512; i > 0; i /= 2) { for (int by = 0; by < 512 / i; by++) { for (int bx = 0; bx < 512 / i; bx++) { int x = bx * i + rand() % i; int y = by * i + rand() % i; B = true; for (int sy = -2 * i; sy < 3 * i; sy++) { for (int sx = -2 * i; sx < 3 * i; sx++) { int px = VMath::Wrap(sx + x, 512); int py = VMath::Wrap(sy + y, 512); if (TM[py * 512 + px] > 0) { B = false; } } } if (B == true) { TM[y * 512 + x] = pow(VMath::Clamp(i, 0, 64), 0.5f); ++S; } } } } for (int i = 0; i < 512 * 512; i++) { if (TM[i] > 0) { switch (TM[i]) { case 1: TM2[i].x = 1; TM2[i].y = 0; TM2[i].z = 0; TM[i] = 1; break; case 2: TM2[i].x = 0; TM2[i].y = 1; TM2[i].z = 0; TM[i] = 2; break; case 3: TM2[i].x = 0; TM2[i].y = 1; TM2[i].z = 0; TM[i] = 2; break; case 4: TM2[i].x = 0; TM2[i].y = 0; TM2[i].z = 1; TM[i] = 3; break; case 5: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; case 6: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; case 7: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; case 8: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; } } } std::vector<float> trees(S * 2, -1); int j = 0; int k = 0; for (int by = 0; by < 8; ++by) { for (int bx = 0; bx < 8; ++bx) { for (int i = 1; i < 5; ++i) { pos[k] = j; ++k; for (int cy = 0; cy < 64; ++cy) { for (int cx = 0; cx < 64; ++cx) { int x = bx * 64 + cx; int y = by * 64 + cy; if (TM[y * 512 + x] == i) { trees[2 * j] = (float)x * 0.00195694716f; trees[2 * j + 1] = (float)y * 0.00195694716f; ++j; } } } } } } pos.back() = trees.size() / 2; DataStreaming::SaveImage(GetWholeFilePatch(L"Trees.jpg"), &TM2, 512, 512); DataStreaming::SaveFile(GetWholeFilePatch("Trees_index.raw"), &pos[0], 1, pos.size(), sizeof(int)); DataStreaming::SaveFile(GetWholeFilePatch("Trees_tiles.raw"), &trees[0], 1, trees.size(), sizeof(float)); }
17.287582
106
0.438563
VereWolf
c2c59e3de767f1acef373193b01c88b784d71a01
2,776
cpp
C++
Random.cpp
yuanyangwangTJ/RSA
384423bf33d555047755bb253a3531e35870ffd6
[ "MIT" ]
null
null
null
Random.cpp
yuanyangwangTJ/RSA
384423bf33d555047755bb253a3531e35870ffd6
[ "MIT" ]
null
null
null
Random.cpp
yuanyangwangTJ/RSA
384423bf33d555047755bb253a3531e35870ffd6
[ "MIT" ]
null
null
null
/************************************** * Class Name: PRNG, PrimeGen * Function: 伪随机数与伪随机素数比特生成器 * Introduction: PrimeGen 继承于 PRNG 类 * ***********************************/ #include "Random.h" #include "TDES.h" #include <iostream> #include <ctime> #include <cstring> #include <NTL/ZZ.h> using namespace std; using namespace NTL; typedef unsigned long long size_ul; /*--------------------------------- * Class: PRNG *-------------------------------*/ // 构造函数,进行初始化操作 PRNG::PRNG(int n) { m = n; x = new bitset<64>[m]; s = ""; } // 析构函数,释放内存空间 PRNG::~PRNG() { delete [] x; } // 通过外界修改 m 的数值 void PRNG::SetM(int n) { m = n; delete [] x; x = new bitset<64>[m]; } // 伪随机数比特生成函数 ZZ PRNG::GenerateRandom() { // 获取本地时间日期 time_t now = time(0); bitset<64> Date(now); // 产生 64 比特随机种子 s size_ul ss = size_ul(random()) << 32 + random(); bitset<64> s(ss); TDES td; td.plain = Date; bitset<64> Im = td.TDESEncrypt(); for (int i = 0; i < m; i++) { td.plain = Im ^ s; x[i] = td.TDESEncrypt(); td.plain = x[i] ^ Im; s = td.TDESEncrypt(); } // 生成字符串类型保存 bitsToString(); ZZ res = bitsToNumber(); return res; } // 将比特数转化为 ZZ 型数字 ZZ PRNG::bitsToNumber() { ZZ res(0); for (int i = 0; i < m; i++) { string str = x[i].to_string(); for (int j = 0; j < 64; j++) { res = res * 2; if (str[j] == '1') { res = res + 1; } } } return res; } // 比特位转为字符串类型(01字符串) void PRNG::bitsToString() { s = ""; for (int i = 0; i < m; i++) { s += x[i].to_string(); } } // 以十六进制打印比特数值 void PRNG::PrintInDER() { cout << "modulus:"; string pairstr = ""; for (size_t i = 0; i < s.length(); i += 4) { int index = 0; for (size_t j = i; j < i + 4; j++) { index = index << 1; if (s[j] == '1') { index += 1; } } pairstr += DERTable[index]; if (pairstr.length() == 2) { cout << pairstr; if (i + 4 < s.length()) { cout << ":"; } pairstr = ""; } if (i % 120 == 0) { cout << endl << '\t'; } } cout << endl; } /*--------------------------------- * Class: PrimeGen *-------------------------------*/ PrimeGen::PrimeGen(int n) : PRNG(n) { cout << "Create a pseudorandom number generator.\n"; } // 生成随机素数,使用 NTL 中库函数检验 // 素性检测算法为 Miller-Rabin 检测 ZZ PrimeGen::GeneratePrime() { ZZ res(0); // 此处进行 srandom,为产生 64 比特随机种子 srandom((unsigned)time(NULL)); do { res = GenerateRandom(); } while(!ProbPrime(res, m * 32)); return res; }
19.971223
56
0.439841
yuanyangwangTJ
c2cb7da54a485a4dcea154ca0c205b70fa691ba3
2,428
cpp
C++
problems/acmicpc_2188.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_2188.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_2188.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <queue> #include <utility> #include <vector> using namespace std; class graph { class edge; class vertex { public: vector<edge*> edges; void add_edge(vertex *v) { auto p = edge::make_edge(this, v); edges.push_back(p.first); v->edges.push_back(p.second); } }; class edge { vertex *u, *v; int capacity; edge *reverse; edge(vertex *u, vertex *v, int capacity) : u(u), v(v), capacity(capacity), reverse(nullptr) {} public: static pair<edge*, edge*> make_edge(vertex *u, vertex *v) { auto const forward = new edge(u, v, 1); auto const backward = new edge(v, u, 0); forward->reverse = backward; backward->reverse = forward; return { forward, backward }; } [[nodiscard]] vertex *next() const { return v; } [[nodiscard]] bool empty() const { return capacity == 0; } void fill(int f) { capacity -= f; reverse->capacity += f; } }; int from, to; vertex *vertices; static void add_edge(vertex *u, vertex *v) { u->add_edge(v); } [[nodiscard]] vertex* start(int x) const { return vertices + x + 1; } [[nodiscard]] vertex* end(int x) const { return vertices + x + from + 1; } public: graph(int from, int to) : from(from), to(to), vertices(new vertex[from + to + 2]) { for(int i = 1; i <= from; i++) { add_edge(vertices, start(i)); } for(int i = 1; i <= to; i++) { add_edge(end(i), vertices + 1); } } void add_edge(int u, int v) { add_edge(start(u), end(v)); } int flow() { auto visited = make_unique<bool[]>(from + to + 2); queue<pair<int, pair<vector<edge*>, int>>> q; q.push({ 0, { {}, 1 } }); while(!q.empty()) { auto const now = q.front(); q.pop(); if(visited[now.first]) continue; visited[now.first] = true; if(now.first == 1) { for(auto e : now.second.first) { e->fill(1); } return 1; } for(auto e : vertices[now.first].edges) { auto const next = e->next() - vertices; if(e->empty() || visited[next]) continue; auto v = now.second.first; v.push_back(e); q.push({ next, { v, 1 } }); } } return 0; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n, m; cin >> n >> m; graph g(n, m); for(int i = 1; i <= n; i++) { int t, x; cin >> t; for(int j = 0; j < t; j++) { cin >> x; g.add_edge(i, x); } } int flow, res = 0; while((flow = g.flow())) res += flow; cout << res; }
25.030928
96
0.580725
qawbecrdtey
c2cc509b0044c492fe6e19de41aa3973bae6ba24
2,073
cpp
C++
DS Prep/Trees/Unusual Traversals/verticalOrder.cpp
Kanna727/My-C-git
3fc81b24f07f8533e2b3881b8f1aeb442dca2bd3
[ "Apache-2.0" ]
1
2021-04-05T18:55:20.000Z
2021-04-05T18:55:20.000Z
DS Prep/Trees/Unusual Traversals/verticalOrder.cpp
Kanna727/My-C-git
3fc81b24f07f8533e2b3881b8f1aeb442dca2bd3
[ "Apache-2.0" ]
null
null
null
DS Prep/Trees/Unusual Traversals/verticalOrder.cpp
Kanna727/My-C-git
3fc81b24f07f8533e2b3881b8f1aeb442dca2bd3
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; } void printVerticalOrder(Node* root) { // Base case if (!root) return; // Create a map and store vertical oder in // map using function getVerticalOrder() map < int,vector<int> > m; int hd = 0; // Create queue to do level order traversal. // Every item of queue contains node and // horizontal distance. queue<pair<Node*, int> > que; que.push(make_pair(root, hd)); while (!que.empty()) { // pop from queue front pair<Node *,int> temp = que.front(); que.pop(); hd = temp.second; Node* node = temp.first; // insert this node's data in vector of hash m[hd].push_back(node->data); if (node->left != NULL) que.push(make_pair(node->left, hd-1)); if (node->right != NULL) que.push(make_pair(node->right, hd+1)); } // Traverse the map and print nodes at // every horigontal distance (hd) map< int,vector<int> > :: iterator it; for (it=m.begin(); it!=m.end(); it++) { for (int i=0; i<it->second.size(); ++i) cout << it->second[i] << " "; cout << endl; } } int main() { int n; std::cout << "Enter no of node sin tree (except root node): "; cin>>n; map<int, Node*> m; struct Node* root = NULL; struct Node *parent, *child; while(n--){ int p,c; char lr; cin>>p>>c>>lr; if(m.find(p) == m.end()){ parent = newNode(p); m[p] = parent; if(!root) root = parent; } else{ parent = m[p]; } child = newNode(c); lr == 'L' ? parent->left = child : parent->right = child; m[c] = child; } printVerticalOrder(root); cout<<endl; system("pause"); return 0; }
23.033333
66
0.514713
Kanna727
c2db002dc2057571014d5b16bd55699d793abd70
3,107
cxx
C++
registration/stats.cxx
valette/FROG
5d36729b7c4309303baa39d472d6beaf795d1173
[ "CECILL-B" ]
15
2019-10-13T05:25:50.000Z
2022-03-12T16:58:39.000Z
registration/stats.cxx
valette/FROG
5d36729b7c4309303baa39d472d6beaf795d1173
[ "CECILL-B" ]
7
2020-10-22T20:05:42.000Z
2020-11-18T19:41:03.000Z
registration/stats.cxx
valette/FROG
5d36729b7c4309303baa39d472d6beaf795d1173
[ "CECILL-B" ]
1
2020-01-21T09:16:01.000Z
2020-01-21T09:16:01.000Z
#include <algorithm> #include <fstream> #include <iostream> #include <numeric> #include "stats.h" #define print( v, size ) { for (int __i = 0; __i < size; __i++ ) { std::cout << v[ __i ]; if ( __i < ( size - 1 ) ) std::cout<< " " ;} std::cout << std::endl;} using namespace std; int Stats::maxSize = 10000; int Stats::maxIterations = 10000; float Stats::epsilon = 1e-6; void Stats::estimateDistribution() { const float esp = 1.59576912160573; int iteration = 0; const float epsilon = Stats::epsilon; while ( iteration++ < Stats::maxIterations ) { float sum1 = 0; float sum2 = 0; float sum3 = 0; float sum4 = 0; float sum5 = 0; for ( int i = 0; i < this->size; i++ ) { float f1 = ratio * chipdf( samples[ i ] / c1 ) / c1; float f2 = ( 1.0 - ratio ) * chipdf( samples[ i ] / c2 ) / c2; float t = f1/ ( f1 + f2 + 1e-16); float p = this->samples[ i ] * this->weights[ i ]; sum1 += t * p; sum2 += t * this->weights[ i ]; sum3 += ( 1.0 - t ) * p; sum4 += ( 1.0 - t ) * this->weights[ i ]; sum5 += this->weights[ i ]; } sum2 = max( sum2, epsilon); sum3 = max( sum3, epsilon); sum5 = max( sum5, epsilon); float nc1 = max( epsilon, sum1 / sum2 / esp ); float nc2 = max( epsilon, sum3 / sum4 / esp ); float nRatio = max( epsilon, sum2 / sum5 ); if ( abs( ( c1 - nc1 ) / nc1 ) < 0.001 && abs( ( c2 - nc2 ) / nc2 ) < 0.001 && abs( ( nRatio - ratio ) / nRatio ) < 0.001 ) { c1 = nc1; c2 = nc2; ratio = nRatio; break; } else { c1 = nc1; c2 = nc2; ratio = nRatio; } } return; } void Stats::displayParameters() { int s = this->size; cout << "c1=" << c1 << ","; cout << "c2=" << c2 << ","; cout << "r=" << ratio << ","; cout << "nSamples=" << s; double sum = accumulate( samples.begin(), samples.begin() + s , 0.0 ); double mean = sum / s; double sq_sum = std::inner_product( samples.begin(), samples.begin() + s, samples.begin(), 0.0 ); auto max = max_element( samples.begin(), samples.begin() + s ); double stdev = sqrt( sq_sum / s - mean * mean); cout <<",max=" << *max << ",mean="<< mean << ",stdev=" << stdev << endl; } void Stats::saveHistogram( const char *file ) { this->getHistogram(); std::fstream fs; fs.open ( file, std::fstream::out | std::fstream::trunc ); for ( int i = 0; i < this->histogram.size(); i++ ) fs << histogram[ i ] << endl; fs.close(); } void Stats::saveSamples( const char *file, int subsampling ) { std::fstream fs; fs.open ( file, std::fstream::out | std::fstream::trunc ); for ( int i = 0; i < this->size; i++ ) if ( !( i % subsampling ) ) fs << this->samples[ i ] << endl; fs.close(); } void Stats::getHistogram( float binSize ) { float max = 0; for ( int i = 0; i < this->size; i++ ) { if ( max < this->samples[ i ] ) max = this->samples[ i ]; } int size = round( max / binSize ) + 1; this->histogram.resize( size ); for ( int i = 0; i < size; i++ ) this->histogram[ i ] = 0; for ( int i = 0; i < this->size; i++ ) { int position = round( this->samples[ i ] / binSize ); this->histogram[ position ]++; } }
21.280822
159
0.551979
valette
c2db30ee45dc1115c3fbb8eb56f190faec8ca064
8,991
cpp
C++
src/vulkan/vulkan_swapchain.cpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/vulkan/vulkan_swapchain.cpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/vulkan/vulkan_swapchain.cpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
#include "vulkan_swapchain.hpp" #include <GLFW/glfw3.h> #include "instrumentor.hpp" #include "vulkan/vulkan_check.hpp" #include "vulkan/vulkan_render_pass.hpp" #include "vulkan/vulkan_swapchain_support_details.hpp" #include "vulkan/vulkan_queue_family_indices.hpp" #include "vulkan/vulkan_window_data.hpp" namespace cl::vulkan { #pragma warning(push) #pragma warning(disable: 26812) void VulkanSwapchain::CreateSwapchain() { CALCIUM_PROFILE_FUNCTION(); VulkanSwapchainSupportDetails swapchain_support(window_data->context_data->physical_device, window_data->surface); VkSurfaceFormatKHR surface_format = swapchain_support.ChooseBestSurfaceFormat(); VkPresentModeKHR present_mode = swapchain_support.ChooseBestPresentMode(window_data->enable_vsync); extent = swapchain_support.ChooseSwapExtent(window_data->glfw_window); image_format = surface_format.format; // It's recommended to request at least one more swapchain image than the minimum supported, as this avoids having // to wait for the driver to complete internal operations before we can acquire the next image to render to image_count = swapchain_support.surface_capabilities.minImageCount + 1; // Make sure we do not exceed the maximum number of swapchain images // 0 is a special value indicating that there is no maximum if (swapchain_support.surface_capabilities.maxImageCount > 0 && image_count > swapchain_support.surface_capabilities.maxImageCount) { image_count = swapchain_support.surface_capabilities.maxImageCount; } VkSwapchainCreateInfoKHR create_info { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR }; create_info.surface = window_data->surface; create_info.minImageCount = image_count; create_info.imageFormat = surface_format.format; create_info.imageColorSpace = surface_format.colorSpace; create_info.imageExtent = extent; // imageArrayLayers greater than 1 can be used for things like stereoscopic 3D create_info.imageArrayLayers = 1; // We are rendering directly to this swapchain - if we were rendering to a texture and performing postprocessing // maybe we would use VK_IMAGE_USAGE_TRANSFER_DST_BIT create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // Next we must specify how to handle swapchain images that will be used across multiple queue families. If so, we // would need to draw on the images in the graphics queue, then submit them on the present queue. VulkanQueueFamilyIndices indices(window_data->context_data->physical_device, window_data->surface); uint32_t queue_family_indices[] = { indices.graphics_family, indices.present_family }; if (indices.graphics_family == indices.present_family) { // VK_SHARING_MODE_EXCLUSIVE offers the best performance create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // No need to specify queueFamilyIndexCount or pQueueFamilyIndices as Vulkan assumes by default that you will be // using the same queue for both graphics and presentation } else { create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; create_info.queueFamilyIndexCount = 2; create_info.pQueueFamilyIndices = queue_family_indices; } // To specify that we don't want a transform (such as a 90 degree rotation or horizontal flip), we can set this to // the current transform supplied by default create_info.preTransform = swapchain_support.surface_capabilities.currentTransform; // compositeAlpha is used to specify whether the alpha channel should be used for blending with other windows in the // window system. We don't need this, so we can ignore the alpha channel. create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; create_info.presentMode = present_mode; // clipped means we don't care about the colour of pixels that are obscured, for example by another window create_info.clipped = VK_TRUE; create_info.oldSwapchain = VK_NULL_HANDLE; VK_CHECK(vkCreateSwapchainKHR(window_data->context_data->device, &create_info, window_data->context_data->allocator, &swapchain)); // We only ever specified a minimum number of swapchain images, so it's possible the swapchain we have created has // more. Therefore we need to query the swapchain to find out how many images it contains. // We don't need to destroy the images, since they are implicity destroyed when we destroy the swapchain - we are // only retrieving image handles vkGetSwapchainImagesKHR(window_data->context_data->device, swapchain, &image_count, nullptr); images.resize(image_count); vkGetSwapchainImagesKHR(window_data->context_data->device, swapchain, &image_count, images.data()); // Create image views image_views.resize(images.size()); for (size_t i = 0; i < images.size(); ++i) { VkImageViewCreateInfo create_info { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; create_info.image = images[i]; // We want to treat each image as a 2D texture create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; create_info.format = image_format; // Use default mapping for colour channels // Note: Swizzling other than VK_COMPONENT_SWIZZLE_IDENTITY is not available on some incomplete Vulkan implementations, for example MoltenVK create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; // subresourceRange describes image use, as well as which part of the image to access create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; create_info.subresourceRange.baseMipLevel = 0; create_info.subresourceRange.levelCount = 1; create_info.subresourceRange.baseArrayLayer = 0; create_info.subresourceRange.layerCount = 1; VK_CHECK(vkCreateImageView(window_data->context_data->device, &create_info, window_data->context_data->allocator, &image_views[i])); } if (window_data->enable_depth_test) { depth_buffer = new VulkanDepthBuffer(window_data->context_data, extent); } } void VulkanSwapchain::DestroySwapchain() { CALCIUM_PROFILE_FUNCTION(); vkDeviceWaitIdle(window_data->context_data->device); if (window_data->enable_depth_test) { delete depth_buffer; } for (auto image_view : image_views) { vkDestroyImageView(window_data->context_data->device, image_view, window_data->context_data->allocator); } vkDestroySwapchainKHR(window_data->context_data->device, swapchain, window_data->context_data->allocator); } void VulkanSwapchain::RecreateSwapchain() { CALCIUM_PROFILE_FUNCTION(); // If the window is minimized, wait until it is unminimized int width = 0, height = 0; glfwGetFramebufferSize(window_data->glfw_window, &width, &height); while (width == 0 || height == 0) { glfwGetFramebufferSize(window_data->glfw_window, &width, &height); glfwWaitEvents(); } vkDeviceWaitIdle(window_data->context_data->device); DestroySwapchainFramebuffers(); vkDestroyRenderPass(window_data->context_data->device, window_data->swapchain.render_pass, window_data->context_data->allocator); DestroySwapchain(); CreateSwapchain(); render_pass = CreateSwapchainRenderPass(*this); CreateSwapchainFramebuffers(); } void VulkanSwapchain::CreateSwapchainFramebuffers() { CALCIUM_PROFILE_FUNCTION(); framebuffers.resize(image_views.size()); // Each image view needs its own framebuffer for (size_t i = 0; i < image_views.size(); ++i) { std::vector<VkImageView> attachments = { image_views[i] }; if (enable_depth_test) { attachments.push_back(depth_buffer->depth_image_view); } VkFramebufferCreateInfo create_info { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; create_info.renderPass = render_pass; create_info.attachmentCount = (uint32_t)attachments.size(); create_info.pAttachments = attachments.data(); create_info.width = extent.width; create_info.height = extent.height; create_info.layers = 1; VK_CHECK(vkCreateFramebuffer(window_data->context_data->device, &create_info, window_data->context_data->allocator, &framebuffers[i])); } } void VulkanSwapchain::DestroySwapchainFramebuffers() { CALCIUM_PROFILE_FUNCTION(); for (auto framebuffer : framebuffers) { vkDestroyFramebuffer(window_data->context_data->device, framebuffer, window_data->context_data->allocator); } } void VulkanSwapchain::SetClearValue(const Colour& colour) { CALCIUM_PROFILE_FUNCTION(); clear_values.clear(); VkClearValue colour_clear_value { }; colour_clear_value.color.float32[0] = colour.r; colour_clear_value.color.float32[1] = colour.g; colour_clear_value.color.float32[2] = colour.b; colour_clear_value.color.float32[3] = colour.a; clear_values.push_back(colour_clear_value); if (enable_depth_test) { VkClearValue depth_clear_value { }; depth_clear_value.depthStencil = { 1.0f, 0 }; clear_values.push_back(depth_clear_value); } } #pragma warning(pop) }
41.43318
144
0.779446
zfccxt
c2dbb966bf88dfb1beb05d2ff8ef147bdfeecd27
16,516
hpp
C++
TinySTL/utility.hpp
syn1w/TinySTL
04961c8fcec560d23cb99d049d44ff1b88113118
[ "MIT" ]
7
2020-11-07T04:52:29.000Z
2022-01-14T06:35:42.000Z
TinySTL/utility.hpp
vczn/TinySTL
ad9951cf38ada8f6903146f306f58778cb132b6a
[ "MIT" ]
1
2021-04-14T10:13:43.000Z
2021-04-14T10:13:43.000Z
TinySTL/utility.hpp
vczn/TinySTL
ad9951cf38ada8f6903146f306f58778cb132b6a
[ "MIT" ]
2
2020-12-06T03:24:11.000Z
2021-04-14T10:11:04.000Z
// Copyright (C) 2021 syn1w // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "type_traits.hpp" #include <type_traits> #if _MSVC_LANG >= 201402L || __cplusplus >= 201402L #define TINY_STL_CXX14 #endif // _MSVC_LANG >= 201402L #if _MSVC_LANG >= 201703L || __cplusplus >= 201703L #define TINY_STL_CXX17 #endif // _MSVC_LANG >= 201703L #ifdef TINY_STL_CXX14 #define XCONSTEXPR14 constexpr #else #define XCONSTEXPR14 inline #endif // TINY_STL_CXX14 #ifdef TINY_STL_CXX17 #define IFCONSTEXPR constexpr #else #define IFCONSTEXPR #endif // TINY_STL_CXX17 namespace tiny_stl { template <typename T> constexpr remove_reference_t<T>&& move(T&& param) noexcept { return static_cast<remove_reference_t<T>&&>(param); } template <typename T> constexpr T&& forward(remove_reference_t<T>& param) noexcept { return static_cast<T&&>(param); } template <typename T> constexpr T&& forward(remove_reference_t<T>&& param) noexcept { return static_cast<T&&>(param); } template <typename T> inline void swap(T& lhs, T& rhs) noexcept( is_nothrow_move_constructible_v<T>&& is_nothrow_move_assignable_v<T>) { T tmp = tiny_stl::move(lhs); lhs = tiny_stl::move(rhs); rhs = tiny_stl::move(tmp); } template <typename FwdIter1, typename FwdIter2> inline void iter_swap(FwdIter1 lhs, FwdIter2 rhs) { swap(*lhs, *rhs); } // swap array lhs and rhs template <typename T, std::size_t N> inline void swap(T (&lhs)[N], T (&rhs)[N]) noexcept(is_nothrow_swappable<T>::value) { if (&lhs != &rhs) { T* first1 = lhs; T* last1 = lhs + N; T* first2 = rhs; for (; first1 != last1; ++first1, ++first2) { tiny_stl::iter_swap(first1, first2); } } } template <typename T> inline void swapADL(T& lhs, T& rhs) noexcept(is_nothrow_swappable<T>::value) { // ADL: argument-dependent lookup swap(lhs, rhs); // std::swap(a, b); // maybe => // using std::swap; // swap(a, b); } struct piecewise_construct_t { explicit piecewise_construct_t() = default; }; constexpr piecewise_construct_t piecewise_construct{}; template <typename...> class tuple; template <typename T1, typename T2> struct pair { using first_type = T1; using second_type = T2; first_type first; second_type second; // (1) template <typename U1 = T1, typename U2 = T2, typename = enable_if_t<is_default_constructible<U1>::value && is_default_constructible<U2>::value>> /*explicit*/ constexpr pair() : first(), second() { } // (2) template <typename U1 = T1, typename U2 = T2, typename = enable_if_t<is_copy_constructible<U1>::value && is_copy_constructible<U2>::value>, enable_if_t<!is_convertible<const U1&, U1>::value || !is_convertible<const U2&, U2>::value, int> = 0> constexpr explicit pair(const T1& f, const T2& s) : first(f), second(s) { } // (2) template <typename U1 = T1, typename U2 = T2, typename = enable_if_t<is_copy_constructible<U1>::value && is_copy_constructible<U2>::value>, enable_if_t<is_convertible<const U1&, U1>::value && is_convertible<const U2&, U2>::value, int> = 0> constexpr pair(const T1& f, const T2& s) : first(f), second(s) { } // (3) template <typename U1, typename U2, typename = enable_if_t<is_constructible<T1, U1&&>::value && is_constructible<T2, U2&&>::value>, enable_if_t<!is_convertible<U1&&, T1>::value || !is_convertible<U2&&, T2>::value, int> = 0> constexpr explicit pair(U1&& f, U2&& s) : first(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)) { } // (3) template <typename U1, typename U2, typename = enable_if_t<is_constructible<T1, U1&&>::value && is_constructible<T2, U2&&>::value>, enable_if_t<is_convertible<U1&&, T1>::value && is_convertible<U2&&, T2>::value, int> = 0> constexpr pair(U1&& f, U2&& s) : first(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)) { } // (4) template <typename U1, typename U2, typename = enable_if_t<is_constructible<T1, const U1&>::value && is_constructible<T2, const U2&>::value>, enable_if_t<!is_convertible<const U1&, T1>::value || !is_convertible<const U2&, T2>::value, int> = 0> constexpr explicit pair(const pair<U1, U2>& rhs) : first(rhs.first), second(rhs.second) { } // (4) template <typename U1, typename U2, typename = enable_if_t<is_constructible<T1, const U1&>::value && is_constructible<T2, const T2&>::value>, enable_if_t<is_convertible<const U1&, T1>::value && is_convertible<const U2&, T2>::value, int> = 0> constexpr pair(const pair<U1, U2>& rhs) : first(rhs.first), second(rhs.second) { } // (5) template <typename U1, typename U2, typename = enable_if_t<is_constructible<T1, U1&&>::value && is_constructible<T2, U2&&>::value>, enable_if_t<!is_convertible<U1&&, T1>::value || !is_convertible<U1&&, T1>::value, int> = 0> constexpr explicit pair(pair<U1, U2>&& rhs) : first(tiny_stl::forward<U1>(rhs.first)), second(tiny_stl::forward<U2>(rhs.second)) { } // (5) template <typename U1, typename U2, typename = enable_if_t<is_constructible<T1, U1&&>::value && is_constructible<T2, U2&&>::value>, enable_if_t<is_convertible<U1&&, T1>::value && is_convertible<U1&&, T1>::value, int> = 0> constexpr pair(pair<U1, U2>&& rhs) : first(tiny_stl::forward<U1>(rhs.first)), second(tiny_stl::forward<U2>(rhs.second)) { } // (6) template <typename... Args1, typename... Args2> pair(piecewise_construct_t, tuple<Args1...> t1, tuple<Args2...> t2); // (7) pair(const pair& p) = default; // (8) pair(pair&&) = default; // operator=() pair& operator=(const pair& rhs) { first = rhs.first; second = rhs.second; return *this; } template <typename U1, typename U2> pair& operator=(const pair<U1, U2>& rhs) { first = rhs.first; second = rhs.second; return *this; } pair& operator=(pair&& rhs) noexcept(is_nothrow_move_assignable<T1>::value&& is_nothrow_move_assignable<T2>::value) { first = tiny_stl::forward<T1>(rhs.first); second = tiny_stl::forward<T2>(rhs.second); return *this; } template <typename U1, typename U2> pair& operator=(pair<U1, U2>&& rhs) { first = tiny_stl::forward<T1>(rhs.first); second = tiny_stl::forward<T2>(rhs.second); return *this; } void swap(pair& rhs) noexcept(is_nothrow_swappable<first_type>::value&& is_nothrow_swappable<second_type>::value) { if (this != tiny_stl::addressof(rhs)) { swapADL(first, rhs.first); swapADL(second, rhs.second); } } }; // class pair<T1, T2> // if reference_wrap<T> -> T& // else -> decay_t<T> template <typename T1, typename T2> constexpr pair<typename UnRefWrap<T1>::type, typename UnRefWrap<T2>::type> make_pair(T1&& t1, T2&& t2) { using Type_pair = pair<typename UnRefWrap<T1>::type, typename UnRefWrap<T2>::type>; return Type_pair(tiny_stl::forward<T1>(t1), tiny_stl::forward<T2>(t2)); } template <typename T1, typename T2> constexpr bool operator==(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) { return (lhs.first == rhs.first && lhs.second == lhs.second); } template <typename T1, typename T2> constexpr bool operator!=(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) { return (!(lhs == rhs)); } template <typename T1, typename T2> constexpr bool operator<(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) { return (lhs.first < rhs.first) || (lhs.first == rhs.first && lhs.second < rhs.second); } template <typename T1, typename T2> constexpr bool operator<=(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) { return (!(rhs < lhs)); } template <typename T1, typename T2> constexpr bool operator>(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) { return (rhs < lhs); } template <typename T1, typename T2> constexpr bool operator>=(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) { return (!(lhs < rhs)); } template <typename T1, typename T2> inline void swap(pair<T1, T2>& lhs, pair<T1, T2>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } template <typename T> struct tuple_size; // tuple_size to pair template <typename T1, typename T2> struct tuple_size<pair<T1, T2>> : integral_constant<std::size_t, 2> {}; // tuple_size to tuple template <typename... Ts> struct tuple_size<tuple<Ts...>> : integral_constant<std::size_t, sizeof...(Ts)> {}; template <typename T> struct tuple_size<const T> : integral_constant<std::size_t, tuple_size<T>::value> {}; template <typename T> struct tuple_size<volatile T> : integral_constant<std::size_t, tuple_size<T>::value> {}; template <typename T> struct tuple_size<const volatile T> : integral_constant<std::size_t, tuple_size<T>::value> {}; // tuple element template <typename T> struct AlwaysFalse : false_type {}; template <std::size_t Idx, typename Tuple> struct tuple_element; // tuple_element to tuple template <std::size_t Idx> struct tuple_element<Idx, tuple<>> { static_assert(AlwaysFalse<integral_constant<std::size_t, Idx>>::value, "tuple index out of range"); }; template <typename Head, typename... Tail> struct tuple_element<0, tuple<Head, Tail...>> { using type = Head; using TupleType = tuple<Head, Tail...>; }; template <std::size_t Idx, typename Head, typename... Tail> struct tuple_element<Idx, tuple<Head, Tail...>> : tuple_element<Idx - 1, tuple<Tail...>> {}; template <std::size_t Idx, typename Tuple> struct tuple_element<Idx, const Tuple> : tuple_element<Idx, Tuple> { using BaseType = tuple_element<Idx, Tuple>; using type = add_const_t<typename BaseType::type>; }; template <std::size_t Idx, typename Tuple> struct tuple_element<Idx, volatile Tuple> : tuple_element<Idx, Tuple> { using BaseType = tuple_element<Idx, Tuple>; using type = add_volatile_t<typename BaseType::type>; }; template <std::size_t Idx, typename Tuple> struct tuple_element<Idx, const volatile Tuple> : tuple_element<Idx, Tuple> { using BaseType = tuple_element<Idx, Tuple>; using type = add_cv_t<typename BaseType::type>; }; // tuple_element to pair template <typename T1, typename T2> struct tuple_element<0, pair<T1, T2>> { using type = T1; }; template <typename T1, typename T2> struct tuple_element<1, pair<T1, T2>> { using type = T2; }; template <std::size_t Idx, typename T> using tuple_element_t = typename tuple_element<Idx, T>::type; template <typename Ret, typename Pair> constexpr Ret pairGetHelper(Pair& p, integral_constant<std::size_t, 0>) noexcept { return (p.first); } template <typename Ret, typename Pair> constexpr Ret pairGetHelper(Pair& p, integral_constant<std::size_t, 1>) noexcept { return (p.second); } // get<Idx>(pair<T1, T2>) // (1) C++ 14 template <std::size_t Idx, typename T1, typename T2> constexpr tuple_element_t<Idx, pair<T1, T2>>& get(pair<T1, T2>& p) noexcept { using Ret = tuple_element_t<Idx, pair<T1, T2>>&; return pairGetHelper<Ret>(p, integral_constant<std::size_t, Idx>{}); } // (2) C++ 14 template <std::size_t Idx, typename T1, typename T2> constexpr const tuple_element_t<Idx, pair<T1, T2>>& get(const pair<T1, T2>& p) noexcept { using Ret = const tuple_element_t<Idx, pair<T1, T2>>&; return pairGetHelper<Ret>(p, integral_constant<std::size_t, Idx>{}); } // (3) C++ 14 template <std::size_t Idx, typename T1, typename T2> constexpr tuple_element_t<Idx, pair<T1, T2>>&& get(pair<T1, T2>&& p) noexcept { using Ret = tuple_element_t<Idx, pair<T1, T2>>&&; return tiny_stl::forward<Ret>(get<Idx>(p)); } // (4) C++ 17 template <std::size_t Idx, typename T1, typename T2> constexpr const tuple_element_t<Idx, pair<T1, T2>>&& get(const pair<T1, T2>&& p) noexcept { using Ret = const tuple_element_t<Idx, pair<T1, T2>>&&; return tiny_stl::forward<Ret>(get<Idx>(p)); } // (5) C++ 14 template <typename T1, typename T2> constexpr T1& get(pair<T1, T2>& p) noexcept { return get<0>(p); } // (6) C++ 14 template <typename T1, typename T2> constexpr const T1& get(const pair<T1, T2>& p) noexcept { return get<0>(p); } // (7) C++ 14 template <typename T1, typename T2> constexpr T1&& get(pair<T1, T2>&& p) noexcept { return get<0>(tiny_stl::move(p)); } // (8) C++ 17 template <typename T1, typename T2> constexpr const T1&& get(const pair<T1, T2>&& p) noexcept { return get<0>(tiny_stl::move(p)); } // (9) C++ 14 template <typename T1, typename T2> constexpr T1& get(pair<T2, T1>& p) noexcept { return get<1>(p); } // (10) C++ 14 template <typename T1, typename T2> constexpr const T1& get(const pair<T2, T1>& p) noexcept { return get<1>(p); } // (11) C++ 14 template <typename T1, typename T2> constexpr T1&& get(pair<T2, T1>&& p) noexcept { return get<1>(tiny_stl::move(p)); } // (12) C++ 17 template <typename T1, typename T2> constexpr const T1&& get(const pair<T2, T1>&& p) noexcept { return get<1>(tiny_stl::move(p)); } namespace extra { // compress pair template <typename T1, typename T2, bool = is_empty<T1>::value && !is_final<T1>::value> class compress_pair final : private T1 { public: using first_type = T1; using second_type = T2; private: T2 second; using Base = T1; public: constexpr explicit compress_pair() : T1(), second() { } template <typename U1, typename... U2> compress_pair(U1&& f, U2&&... s) : T1(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)...) { } T1& get_first() noexcept { return *this; } const T1& get_first() const noexcept { return *this; } T2& get_second() noexcept { return second; } const T2& get_second() const noexcept { return second; } }; template <typename T1, typename T2> class compress_pair<T1, T2, false> { public: using first_type = T1; using second_type = T2; private: T1 first; T2 second; public: constexpr explicit compress_pair() : first(), second() { } template <typename U1, typename... U2> compress_pair(U1&& f, U2&&... s) : first(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)...) { } T1& get_first() noexcept { return first; } const T1& get_first() const noexcept { return first; } T2& get_second() noexcept { return second; } const T2& get_second() const noexcept { return second; } }; // class extra::compress_pair<T1, T2> } // namespace extra template <typename T> struct TidyRAII { // strong exception guarantee T* obj; ~TidyRAII() { if (obj) { obj->tidy(); } } }; struct in_place_t { explicit in_place_t() = default; }; constexpr in_place_t in_place{}; template <typename T> struct in_place_type_t { explicit in_place_type_t() = default; }; template <typename T> constexpr in_place_type_t<T> in_place_type{}; template <std::size_t I> struct in_place_index_t { explicit in_place_index_t() = default; }; template <std::size_t I> constexpr in_place_index_t<I> in_place_index{}; } // namespace tiny_stl
28.723478
80
0.607653
syn1w
c2dc2d42b2427109966c9edcf921908444869951
278
hpp
C++
include/miniberry/Port.hpp
krzysztof-magosa/MiniBerry
b4e4aac914d1813238fd3f43753c1e71488b8f90
[ "MIT" ]
1
2015-06-27T16:24:34.000Z
2015-06-27T16:24:34.000Z
include/miniberry/Port.hpp
krzysztof-magosa/MiniBerry
b4e4aac914d1813238fd3f43753c1e71488b8f90
[ "MIT" ]
null
null
null
include/miniberry/Port.hpp
krzysztof-magosa/MiniBerry
b4e4aac914d1813238fd3f43753c1e71488b8f90
[ "MIT" ]
null
null
null
#ifndef MINIBERRY_PORT_HPP #define MINIBERRY_PORT_HPP #include <stdint.h> namespace miniberry { class Port { public: volatile uint8_t* port; volatile uint8_t* pin; volatile uint8_t* ddr; protected: Port() {} }; } #endif
12.636364
31
0.604317
krzysztof-magosa
c2df85fa013e02ad895a93a54a9010a49c3d98c9
1,495
cpp
C++
src/certificate/AccessDescription.cpp
LabSEC/libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-26T16:40:59.000Z
2022-02-22T19:52:55.000Z
src/certificate/AccessDescription.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
14
2015-09-01T00:39:22.000Z
2018-12-17T16:24:28.000Z
src/certificate/AccessDescription.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-31T19:17:37.000Z
2021-01-04T13:38:35.000Z
#include <libcryptosec/certificate/AccessDescription.h> AccessDescription::AccessDescription() { } AccessDescription::AccessDescription(ACCESS_DESCRIPTION *accessDescription) { if(accessDescription->method) { accessMethod = ObjectIdentifier(OBJ_dup(accessDescription->method)); } if(accessDescription->location) { accessLocation = GeneralName(accessDescription->location); } } ACCESS_DESCRIPTION* AccessDescription::getAccessDescription() { ACCESS_DESCRIPTION* accessDescription = ACCESS_DESCRIPTION_new(); accessDescription->method = accessMethod.getObjectIdentifier(); accessDescription->location = accessLocation.getGeneralName(); return accessDescription; } GeneralName AccessDescription::getAccessLocation() { return accessLocation; } ObjectIdentifier AccessDescription::getAccessMethod() { return accessMethod; } void AccessDescription::setAccessLocation(GeneralName accessLocation) { this->accessLocation = accessLocation; } void AccessDescription::setAccessMethod(ObjectIdentifier accessMethod) { this->accessMethod = accessMethod; } std::string AccessDescription::getXmlEncoded() { return this->getXmlEncoded(""); } std::string AccessDescription::getXmlEncoded(std::string tab) { std::string ret; ret = tab + "<accessDescription>\n"; ret += this->accessMethod.getXmlEncoded(tab + "\t"); ret += this->accessLocation.getXmlEncoded(tab + "\t"); ret += tab + "</accessDescription>\n"; return ret; } AccessDescription::~AccessDescription() { }
24.508197
77
0.776589
LabSEC
123fb4a420334ec65d9a6526c2eff759062554d3
40,867
cpp
C++
src/object.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
1
2018-09-16T03:17:50.000Z
2018-09-16T03:17:50.000Z
src/object.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
src/object.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
#include "system.h" void read_string( FILE*, char**, char, int ); /* * LOCAL_CONSTANTS */ const char* item_type_name [] = { "other", "light", "scroll", "wand", "staff", "weapon", "gem", "spellbook", "treasure", "armor", "potion", "reagent", "furniture", "trash", "cross", "container", "lock.pick", "drink.container", "key", "food", "money", "key.ring", "boat", "corpse", "bait", "fountain", "whistle", "trap", "light.perm", "bandage", "bounty", "gate", "arrow", "skin", "body.part", "chair", "table", "book", "pipe", "tobacco", "deck.cards", "fire", "garrote", "shield", "herb", "flower", "jewelry", "ore", "tree", "plant", "charm", "charm.bracelet", "toy", "apparel", "dragon.scale", "shot", "bolt", "s.corpse", "musical", "poison", "ancient.oak.tree", "statue" }; const char* item_values [] = { "unused", //other "unused | unused | life time | unused", //light "spell | level | duration | unused", //scroll "spell | level | duration | charges", //wand "spell | level | duration | charges", //staff "enchantment | damdice | damside | weapon class", //weapon "hardness | condition", //gem "unused", //spell book "unused", //treasure "enchantment | armor value | bracer ac | unused", //armor "spell | level | duration | unused", //potion "charges", //reagent "unused", //furniture "unused", //trash "unused", //cross "capacity | container flags | key vnum | unused", //container "pick modifier | unused", //pick modifier? "capacity | contains | liquid | poisoned == -1", //drink container "unused", //key "food value | cooked? | unused | poisoned == -1", //food "unused", //money "unused", //key ring "unused", //boat object?!? "half-life| species | level of PC corpse | identity of PC", //corpse "unused", //bait "required to be -1 | unused | liquid | poisoned == -1", //fountain "range | unused", //whistle "trap flags | damdice | damside | unused", //trap, values unused? "unused | unused | lifetime | unused", //permanent light, duration? "unused", //bandage "unused", //bounty? "lifetime | unused", //gate "unused | damdice | damside | shots", //arrow "unused", //skin "unused", //body part "seats | unused", //chair "unused", //table "unused", //book "unused", //pipe "unused", //tobacco "unused", //deck of cards "timer | next item | unused", //fire "unused", //garrote "enchantment | armor value | bracer ac | unused", //shield "unused", //herb "unused", //flower "unused", //jewelry "unused", //ore "unused", //tree "unused", //plant "unused", //charm "unused", //charm bracelet "unused", //toy "unused", //apparel "unused", //dragon.scale "unused | damdice | damside | shots", //shot "unused | damdice | damside | shots", //bolt "half-life| species", //s.corpse "unused", //musical "unused", //poison "unused", //ancient tree "unused", //statues }; const char *cont_flag_name [] = { "closeable", "pickproof", "closed", "locked", "holding" }; /* * OBJ_CLSS_DATA CLASS */ Synergy :: Synergy( ) { record_new( sizeof( synergy ), MEM_OBJ_CLSS ); skill = empty_string; clss = 0; amount = 0; } Synergy :: ~Synergy( ) { record_delete( sizeof( synergy ), MEM_OBJ_CLSS ); } Obj_Clss_Data :: Obj_Clss_Data( ) { record_new( sizeof( obj_clss_data ), MEM_OBJ_CLSS ); oprog = NULL; date = -1; count = 0; } Obj_Clss_Data :: ~Obj_Clss_Data( ) { record_delete( sizeof( obj_clss_data ), MEM_OBJ_CLSS ); if( item_type == ITEM_MONEY ) update_coinage(); // memory leaks galore } Obj_Clss_Data :: Obj_Clss_Data( obj_clss_data* obj_copy, const char* name, int vnumber, const char* acreator ) { char buf [ MAX_INPUT_LENGTH ]; record_new( sizeof( obj_clss_data ), MEM_OBJ_CLSS ); vnum = vnumber; fakes = vnumber; // obj_copy->vnum ?? sprintf( buf, "%ss", name ); singular = alloc_string( name, MEM_OBJ_CLSS ); plural = alloc_string( buf, MEM_OBJ_CLSS ); before = alloc_string( obj_copy->before, MEM_OBJ_CLSS ); after = alloc_string( obj_copy->after, MEM_OBJ_CLSS ); long_s = alloc_string( obj_copy->long_s, MEM_OBJ_CLSS ); long_p = alloc_string( obj_copy->long_p, MEM_OBJ_CLSS ); prefix_singular = alloc_string( obj_copy->prefix_singular, MEM_OBJ_CLSS ); prefix_plural = alloc_string( obj_copy->prefix_plural, MEM_OBJ_CLSS ); creator = alloc_string( acreator, MEM_OBJ_CLSS ); last_mod = alloc_string( acreator, MEM_OBJ_CLSS ); item_type = obj_copy->item_type; memcpy( extra_flags, obj_copy->extra_flags, sizeof( extra_flags ) ); wear_flags = obj_copy->wear_flags; anti_flags = obj_copy->anti_flags; restrictions = obj_copy->restrictions; size_flags = obj_copy->size_flags; materials = obj_copy->materials; memcpy( affect_flags, obj_copy->affect_flags, sizeof( affect_flags ) ); layer_flags = obj_copy->layer_flags; memcpy( value, obj_copy->value, sizeof( value ) ); weight = obj_copy->weight; cost = obj_copy->cost; level = obj_copy->level; limit = obj_copy->limit; repair = obj_copy->repair; durability = obj_copy->durability; blocks = obj_copy->blocks; light = obj_copy->light; memcpy( clss_synergy, obj_copy->clss_synergy, sizeof( clss_synergy ) ); religion_flags = obj_copy->religion_flags; color = obj_copy->color; count = 0; date = time(0); copy_extras( extra_descr, obj_copy->extra_descr ); oprog = NULL; // one day dupe oprogs } Obj_Clss_Data :: Obj_Clss_Data( const char* name, int vnumber, const char* acreator ) { char buf [ MAX_INPUT_LENGTH ]; record_new( sizeof( obj_clss_data ), MEM_OBJ_CLSS ); vnum = vnumber; fakes = vnumber; sprintf( buf, "%ss", name ); singular = alloc_string( name, MEM_OBJ_CLSS ); plural = alloc_string( buf, MEM_OBJ_CLSS ); before = empty_string; after = empty_string; long_s = empty_string; long_p = empty_string; prefix_singular = empty_string; prefix_plural = empty_string; creator = alloc_string( acreator, MEM_OBJ_CLSS ); last_mod = alloc_string( acreator, MEM_OBJ_CLSS ); item_type = ITEM_TRASH; vzero( extra_flags, 2 ); wear_flags = 0; set_bit( &wear_flags, ITEM_TAKE ); anti_flags = 0; restrictions = 0; size_flags = 0; materials = 0; vzero( affect_flags, AFFECT_INTS ); layer_flags = 0; vzero( value, 4 ); weight = 0; cost = 0; level = 1; limit = -1; repair = 10; durability = 1000; blocks = 0; light = 0; vzero( clss_synergy, MAX_NEW_CLSS ); religion_flags = 0; color = ANSI_NORMAL; count = 0; date = time(0); oprog = NULL; } /* * Obj_Clss_Data Synergy Stuff */ void Obj_Clss_Data :: HandleSynergyEdit( wizard_data* ch, char* argument ) { if( *argument == '\0' ) { // display the synergies if( is_empty( synergy_array ) ) { page( ch, "There are no synergies on %s.\r\n", this->Name( ) ); return; } DisplaySynergyList( ch ); return; } else if( exact_match( argument, "delete" ) ) { if( *argument == '\0' ) { page( ch, "Which synergy do you wish to delte?\r\n" ); page( ch, "Syntax: <unsure yet>\r\n" ); return; } if( is_empty( synergy_array ) ) { page( ch, "There are no synergies to delete.\r\n" ); return; } int i = atoi( argument ); if( i < 1 || i > synergy_array ) { page( ch, "Selected synergy '%s' out of range [1-%d].\r\n", argument, synergy_array.size ); return; } Synergy* syn = synergy_array[i-1]; if( syn != NULL ) { synergy_array -= syn; page( ch, "Synergy #%i deleted.\r\n", i ); delete syn; } else { send( ch, "[BUG] Synergy #%i not found.\r\n", i ); } return; } else if( exact_match( argument, "new" ) ) { Synergy* syn = new Synergy; // add the synergy to the array for that object class // then make the immortal edit it ch->SynergyEdit = syn; synergy_array += syn; page( ch, "Synergy created and you are editting it.\r\n" ); return; } else if( isdigit( *argument ) ) { int i = atoi( argument ); if( i < 1 || i > synergy_array ) { page( ch, "Selected synergy '%s' is out of range [1-%d].\r\n", argument, synergy_array.size ); return; } synergy* syn = synergy_array[i-1]; if( syn != NULL ) { ch->SynergyEdit = syn; page( ch, "You are now editting synergy #%i.\r\n", i ); } else { send( ch, "[BUG] Synergy #%i not found.\r\n", i ); } return; } else { send( ch, "Syntax: <unknown>\r\n" ); } } void Obj_Clss_Data :: DisplaySynergyList( wizard_data* ch ) { bool found = false; if( is_empty( synergy_array ) ) { page( ch, "%s has no synergies.\r\n", Name( ) ); return; } for( int i = 0; i < synergy_array; i++ ) { synergy* syn = synergy_array[i]; if( !found ) { page( ch, "Skill specific synergies on %s.\r\n", Name( ) ); page_underlined( ch, " # Skill Amount Class\r\n" ); found = true; } page( ch, "[%3i] %-26s%6i %s\r\n", i+1, syn->skill, syn->amount, clss_table[ syn->clss ].name ); } return; } void Obj_Clss_Data :: HandleSynergySet( wizard_data* ch, char* argument ) { synergy* syn = ch->SynergyEdit; if( *argument == '\0' ) { HandleSynergyStat( ch ); return; } if( syn == NULL ) { send( ch, "You are not currently editting a synergy.\r\n" ); return; } class int_field int_list [] = { { "amount", -20000, 100, &syn->amount }, { "", 0, 0, NULL }, }; if( process( int_list, ch, "synergy", argument ) ) return; if( exact_match( argument, "skill" ) ) { int skill; if( ( skill = skill_index( argument ) ) != -1 ) { syn->skill = skill_table[skill].name; send( ch, "%s now synergizes %s.\r\n", Name( ), skill_table[skill].name ); return; } else { send( ch, "%s is an invalid skill.\r\n", argument ); return; } } if( exact_match( argument, "class" ) ) { for( int i = 0; i < MAX_CLSS; i++ ) { if( fmatches( argument, clss_table[i].name ) ) { syn->clss = i; send( ch, "%s now synergizes with %s class skill set.\r\n", Name( ), clss_table[i].name ); return; } } } send( ch, "Unknown parameters\r\n" ); return; } void Obj_Clss_Data :: HandleSynergyStat( wizard_data* ch ) { synergy* syn = ch->SynergyEdit; if( syn == NULL ) { send( ch, "You are not editting any synergy right now.\r\n" ); return; } page_title( ch, "Object %s - Synergy Being Editted", Name( ) ); page( ch, "\r\n" ); page( ch, " Skill: %s\r\n", syn->skill ); page( ch, " Amount: %i\r\n", syn->amount ); page( ch, " Class: %s\r\n", clss_table[ syn->clss ].name ); return; } bool Synergy :: Save( FILE* fp ) { fprintf( fp, "%d\n", 1 ); // version fprintf( fp, "%s~\n", skill ); fprintf( fp, "%d\n", amount ); fprintf( fp, "%d\n", clss ); return true; } bool Synergy :: Load( FILE* fp ) { int version = fread_number( fp ); skill = fread_string( fp, MEM_OBJ_CLSS ); amount = fread_number( fp ); clss = fread_number( fp ); return true; } void do_synedit( char_data* ch, char* argument ) { wizard_data* imm = wizard( ch ); if( imm == NULL ) return; obj_clss_data* obj = imm->obj_edit; if( obj == NULL ) { send( ch, "You need to be editting an object to work on synergies.\r\n" ); return; } obj->HandleSynergyEdit( imm, argument ); } void do_synset( char_data* ch, char* argument ) { wizard_data* imm = wizard( ch ); if( imm == NULL ) return; obj_clss_data* obj = imm->obj_edit; if( obj == NULL ) { send( ch, "You need to be editting an object to work on synergies.\r\n" ); return; } if( imm->SynergyEdit == NULL ) { send( ch, "You are not editting a synergy.\r\n" ); return; } obj->HandleSynergySet( imm, argument ); } /* * OBJ_DATA */ int compare_vnum( obj_data* obj1, obj_data* obj2 ) { int a = obj1->pIndexData->vnum; int b = obj2->pIndexData->vnum; return( a < b ? -1 : ( a > b ? 1 : 0 ) ); } Obj_Data :: Obj_Data( obj_clss_data* obj_clss ) { record_new( sizeof( obj_data ), MEM_OBJECT ); valid = OBJ_DATA; extra_descr = NULL; array = NULL; save = NULL; owner = NULL; source = empty_string; label = empty_string; reset_mob_vnum = 0; reset_room_vnum = 0; position = WEAR_NONE; layer = 0; unjunked = 0; pIndexData = obj_clss; insert( obj_list, this, binary_search( obj_list, this, compare_vnum ) ); } Obj_Data :: ~Obj_Data( ) { record_delete( sizeof( obj_data ), MEM_OBJECT ); obj_list -= this; } /* * SUPPORT FUNCTIONS */ bool can_extract( obj_clss_data* obj_clss, char_data* ch ) { /* if( obj_clss->vnum == 1 ) { send( ch, "You may not delete the template object.\r\n" ); return FALSE; } */ for( int i = 0; i < obj_list; i++ ) { if( obj_list[i]->Is_Valid() && obj_list[i]->pIndexData == obj_clss ) { send( ch, "You must destroy all examples of %s first.\r\n", obj_clss ); return FALSE; } } if( generic_search( ch, obj_clss, obj_clss->vnum, OBJECT, true ) ) { send( ch, "You must remove all references of that object first.\r\n" ); return FALSE; } return TRUE; } /* * LOW LEVEL OBJECT ROUTINES */ int coin_value_in_condition( obj_data* obj ) { int cost = 0; if( obj == NULL ) return 0; cost = obj->Cost( ); if( obj->pIndexData->item_type == ITEM_ARMOR || obj->pIndexData->item_type == ITEM_SHIELD || obj->pIndexData->item_type == ITEM_WEAPON ) cost /= 12; else cost /= 4; cost = cost*obj->condition/obj->pIndexData->durability*sqr(4-obj->rust)/16; switch( obj->pIndexData->item_type ) { case ITEM_STAFF : case ITEM_WAND : if( obj->value[0] != 0 ) cost = cost*(1+obj->value[3]/obj->value[0])/2; break; case ITEM_DRINK_CON : cost += obj->value[1]*liquid_table[ obj->value[2] ].cost/100; break; } cost += cost*12/(3+obj->number); return cost; } bool is_same( obj_data* obj1, obj_data* obj2 ) { obj_array* array; if( obj1->pIndexData != obj2->pIndexData ) return FALSE; if( obj1->pIndexData->item_type == ITEM_MONEY ) return TRUE; // perhaps money-specific checks later if you want 'dented gold coin' etc if( !is_empty( obj1->contents ) || !is_empty( obj2->contents ) || !is_empty( obj1->affected ) || !is_empty( obj2->affected ) || !is_empty( obj1->events ) || !is_empty( obj2->events ) || obj1->extra_flags[0] != obj2->extra_flags[0] || obj1->extra_flags[1] != obj2->extra_flags[1] || obj1->timer != obj2->timer || obj1->condition != obj2->condition || obj1->materials != obj2->materials || obj1->rust != obj2->rust || obj1->owner != obj2->owner || obj1->weight != obj2->weight || obj1->unjunked != obj2->unjunked || obj1->position != obj2->position ) return FALSE; for( int i = 0; i < 4; i++ ) if( obj1->value[i] != obj2->value[i] ) return FALSE; if( obj2->save != NULL ) { if( obj1->save == NULL ) { obj1->save = obj2->save; obj2->save = NULL; array = &obj1->save->save_list; for( int i = 0; ; i++ ) { if( i >= array->size ) panic( "Is_Same: Object not in save array." ); if( obj2 == array->list[i] ) { array->list[i] = obj1; break; } } } else if( obj1->save != obj2->save ) return FALSE; } if( obj1->pIndexData->vnum == OBJ_BALL_OF_LIGHT && range( 0, obj1->value[2] / 5, 10 ) != range( 0, obj2->value[2] / 5, 10 ) ) return FALSE; if( obj1->pIndexData->vnum == OBJ_CORPSE_LIGHT && ( obj1->value[3] > 0 ? range( 0, 6 * obj1->value[2] / obj1->value[3], 6 ) : 6 ) != ( obj2->value[3] > 0 ? range( 0, 6 * obj2->value[2] / obj2->value[3], 6 ) : 6 ) ) return FALSE; if( obj1->pIndexData->item_type == ITEM_CORPSE ) return FALSE; if( obj1->source != obj2->source && strcmp( obj1->source, obj2->source ) != 0 ) return FALSE; return( !strcmp( obj1->label, obj2->label ) ); } /* * OWNERSHIP */ bool Obj_Data :: Belongs( char_data* ch ) { return( owner == NULL || ( ch != NULL && ch->pcdata != NULL && ch->pcdata->pfile == owner ) ); } void set_owner( pfile_data* pfile, thing_array& array, bool force_transfer ) { obj_data* obj; for( int i = 0; i < array; i++ ) { if( ( obj = object( array[i] ) ) != NULL ) { if ( obj->pIndexData->item_type != ITEM_MONEY ) { if( obj->owner == NULL || force_transfer ) obj->owner = pfile; } set_owner( pfile, obj->contents, force_transfer ); } } } void set_owner( obj_data* obj, pfile_data* buyer ) { obj_data* content; if( obj->pIndexData->item_type != ITEM_MONEY ) obj->owner = buyer; for( int i = 0; i < obj->contents; i++ ) if( ( content = object( obj->contents[i] ) ) != NULL ) set_owner( content, buyer ); } void set_owner( obj_data* obj, char_data* buyer, char_data* seller ) { obj_data* content; if( obj->Belongs( seller ) && obj->pIndexData->item_type != ITEM_MONEY ) obj->owner = ( ( buyer != NULL && buyer->pcdata != NULL ) ? buyer->pcdata->pfile : NULL ); for( int i = 0; i < obj->contents; i++ ) if( ( content = object( obj->contents[i] ) ) != NULL ) set_owner( content, buyer, seller ); } /* * MISC ROUTINES */ void condition_abbrev( char* tmp, obj_data* obj, char_data* ch ) { const char* abbrev [] = { "wls", "dmg", "vwn", "wrn", "vsc", "scr", "rea", "goo", "vgo", "exc" }; int i; i = 1000*obj->condition/obj->pIndexData->durability; i = range( 0, i/100, 9 ); sprintf( tmp, "%s%s%s", i > 4 ? ( i > 7 ? blue( ch ) : green( ch ) ) : ( i > 2 ? yellow( ch ) : red( ch ) ), abbrev[i], normal( ch ) ); return; } void age_abbrev( char* tmp, obj_data*, char_data* ) { sprintf( tmp, " " ); return; } const char* obj_data :: repair_condition_name( char_data* ch, bool ansi ) { static char tmp [ ONE_LINE ]; int i; const char* txt; i = 1000 * repair_condition(this) / pIndexData->durability; i = range( 0, i/100, 9 ); if( i == 0 ) txt = "worthless"; else if( i == 1 ) txt = "damaged"; else if( i == 2 ) txt = "very worn"; else if( i == 3 ) txt = "worn"; else if( i == 4 ) txt = "very scratched"; else if( i == 5 ) txt = "scratched"; else if( i == 6 ) txt = "reasonable"; else if( i == 7 ) txt = "good"; else if( i == 8 ) txt = "very good"; else txt = "excellent"; if( !ansi || ch->pcdata == NULL || ch->pcdata->terminal != TERM_ANSI ) return txt; sprintf( tmp, "%s%s%s", i > 4 ? ( i > 7 ? blue( ch ) : green( ch ) ) : ( i > 2 ? yellow( ch ) : red( ch ) ), txt, normal( ch ) ); return tmp; } const char* obj_data :: condition_name( char_data* ch, bool ansi ) { static char tmp [ ONE_LINE ]; int i; const char* txt; i = 1000*condition/pIndexData->durability; i = range( 0, i/100, 9 ); if( i == 0 ) txt = "worthless"; else if( i == 1 ) txt = "damaged"; else if( i == 2 ) txt = "very worn"; else if( i == 3 ) txt = "worn"; else if( i == 4 ) txt = "very scratched"; else if( i == 5 ) txt = "scratched"; else if( i == 6 ) txt = "reasonable"; else if( i == 7 ) txt = "good"; else if( i == 8 ) txt = "very good"; else txt = "excellent"; if( !ansi || ch->pcdata == NULL || ( ch->pcdata->terminal != TERM_ANSI && ch->pcdata->terminal != TERM_MXP ) ) return txt; sprintf( tmp, "%s%s%s", i > 4 ? ( i > 7 ? blue( ch ) : green( ch ) ) : ( i > 2 ? yellow( ch ) : red( ch ) ), txt, normal( ch ) ); return tmp; } /* * WEIGHT/NUMBER ROUTINES */ int Obj_Data :: Cost( ) { int cost = pIndexData->cost; int i; if( ( pIndexData->item_type == ITEM_WEAPON || pIndexData->item_type == ITEM_ARMOR || pIndexData->item_type == ITEM_SHIELD ) && is_set( extra_flags, OFLAG_IDENTIFIED ) ) cost += cost*sqr( URANGE( 0, value[0], 5 ) )/2; if( ( pIndexData->item_type != ITEM_WEAPON && pIndexData->item_type != ITEM_ARMOR && pIndexData->item_type != ITEM_SHIELD ) || !is_set( pIndexData->extra_flags, OFLAG_RANDOM_METAL ) ) return cost; for( i = MAT_BRONZE; i <= MAT_LIRIDIUM; i++ ) if( is_set( &pIndexData->materials, i ) ) return cost*material_table[i].cost; return cost; } /* * OBJECT UTILITY ROUTINES */ void enchant_object( obj_data* obj ) { int i; if( obj->pIndexData->item_type == ITEM_WAND || obj->pIndexData->item_type == ITEM_STAFF ) obj->value[3] = number_range( 0, obj->pIndexData->value[3] ); if( ( obj->pIndexData->item_type == ITEM_WEAPON || obj->pIndexData->item_type == ITEM_SHIELD || obj->pIndexData->item_type == ITEM_ARMOR ) && !is_set( obj->extra_flags, OFLAG_NO_ENCHANT ) ) { if( ( i = number_range( 0, 1000 ) ) >= 900 ) { obj->value[0] = ( i > 950 ? ( i > 990 ? ( i == 1000 ? 3 : 2 ) : 1 ) : ( i < 910 ? ( i == 900 ? -3 : -2 ) : -1 ) ); set_bit( obj->extra_flags, OFLAG_MAGIC ); if( obj->value[0] < 0 ) set_bit( obj->extra_flags, OFLAG_NOREMOVE ); } } } void rust_object( obj_data* obj, int chance ) { int i; if( obj->metal( ) && !is_set( obj->extra_flags, OFLAG_RUST_PROOF ) && number_range( 0, 100 ) < chance ) { i = number_range( 0, 1000 ); obj->rust = ( i > 700 ? 1 : ( i > 400 ? 2 : 3 ) ); } if( obj->pIndexData->item_type == ITEM_WEAPON || obj->pIndexData->item_type == ITEM_SHIELD || obj->pIndexData->item_type == ITEM_ARMOR ) { obj->age = number_range( 0, obj->pIndexData->durability/25-1 ); obj->condition = number_range( 1, repair_condition( obj ) ); } } void set_alloy( obj_data* obj, int level ) { int metal; if( !is_set( obj->pIndexData->extra_flags, OFLAG_RANDOM_METAL ) ) return; for( metal = MAT_BRONZE; metal <= MAT_LIRIDIUM; metal++ ) if( is_set( &obj->materials, metal ) ) break; if( metal > MAT_LIRIDIUM ) { metal = MAT_BRONZE; for( ; ; ) { if( metal == MAT_LIRIDIUM || number_range( 0, level+75 ) > level-10*(metal-MAT_BRONZE) ) break; metal++; } set_bit( &obj->materials, metal ); } if( obj->pIndexData->item_type == ITEM_ARMOR || obj->pIndexData->item_type == ITEM_SHIELD ) obj->value[1] = obj->pIndexData->value[1]-MAT_BRONZE+metal; } obj_data* create( obj_clss_data* obj_clss, int number ) { obj_data* obj; if( obj_clss == NULL ) { roach( "Create_object: NULL obj_clss." ); return NULL; } obj = new obj_data( obj_clss ); obj->singular = obj_clss->singular; obj->plural = obj_clss->plural; obj->after = obj_clss->after; obj->before = obj_clss->before; obj->extra_flags[0] = obj_clss->extra_flags[0]; obj->extra_flags[1] = obj_clss->extra_flags[1]; if( is_set( &obj_clss->size_flags, SFLAG_CUSTOM ) ) obj->size_flags = -1; else obj->size_flags = obj_clss->size_flags; obj->value[0] = obj_clss->value[0]; obj->value[1] = obj_clss->value[1]; obj->value[2] = obj_clss->value[2]; obj->value[3] = obj_clss->value[3]; obj->condition = obj_clss->durability; obj->materials = obj_clss->materials; obj->weight = obj_clss->weight; obj->age = 0; obj->rust = 0; obj->timer = 0; if( number > 0 ) obj_clss->count += number; else number = -number; obj->number = number; obj->selected = number; obj->shown = number; switch( obj_clss->item_type ) { case ITEM_MONEY: obj->value[0] = obj->pIndexData->cost; break; case ITEM_FIRE: case ITEM_GATE: obj->timer = obj->value[0]; break; } if( obj_clss->item_type != ITEM_ARMOR && obj_clss->item_type != ITEM_WEAPON && obj_clss->item_type != ITEM_SHIELD && !strcmp( obj_clss->before, obj_clss->after ) && obj_clss->plural[0] != '{' && obj_clss->singular[0] != '{' ) set_bit( obj->extra_flags, OFLAG_IDENTIFIED ); return obj; } obj_data* duplicate( obj_data* copy, int num ) { obj_data* obj; obj_clss_data* obj_clss = copy->pIndexData; obj = new obj_data( obj_clss ); char* string_copy [] = { copy->singular, copy->plural, copy->before, copy->after }; char** string_obj [] = { &obj->singular, &obj->plural, &obj->before, &obj->after }; char* string_index [] = { obj_clss->singular, obj_clss->plural, obj_clss->before, obj_clss->after }; for( int i = 0; i < 4; i++ ) *string_obj[i] = ( string_copy[i] != string_index[i] ? alloc_string( string_copy[i], MEM_OBJECT ) : string_index[i] ); obj->age = copy->age; obj->extra_flags[0] = copy->extra_flags[0]; obj->extra_flags[1] = copy->extra_flags[1]; obj->size_flags = copy->size_flags; obj->value[0] = copy->value[0]; obj->value[1] = copy->value[1]; obj->value[2] = copy->value[2]; obj->value[3] = copy->value[3]; obj->weight = copy->weight; obj->condition = copy->condition; obj->rust = copy->rust; obj->timer = copy->timer; obj->materials = copy->materials; obj->owner = copy->owner; obj->temp = copy->temp; obj->number = num; obj->selected = num; obj->shown = num; obj_clss->count += num; if( copy->save != NULL ) { copy->save->save_list += obj; obj->save = copy->save; } return obj; } /* * OBJECT TRANSFER FUNCTIONS */ int drop_contents( obj_data* obj ) { room_data* room; if( obj == NULL || obj->array == NULL || (room = Room(obj->array->where)) == NULL ) return 0; int num = 0; for( int i = obj->contents.size - 1; i >= 0; i-- ) { obj_data *content = object(obj->contents[i]); if (!content || !content->Is_Valid()) continue; content->From(content->number); content->To(room); num++; } return num; } /* * OBJECT EXTRACTION ROUTINES */ void Obj_Data :: Extract( int i ) { if( i < number ) { remove_weight( this, i ); number -= i; if( boot_stage == BOOT_COMPLETE ) pIndexData->count -= i; return; } if( i > number ) { roach( "Extract( Obj ): number > amount." ); roach( "-- Obj = %s", this ); roach( "-- Number = %d", i ); roach( "-- Amount = %d", number ); } Extract( ); } void Obj_Data :: Extract( ) { obj_array* array; int i; if( !Is_Valid( ) ) { roach( "Extracting invalid object." ); roach( "-- Valid = %d", valid ); roach( "-- Obj = %s", this ); return; } if( pIndexData->vnum == OBJ_CORPSE_PC ) corpse_list -= this; if( this->array != NULL ) From( number ); extract( contents ); if( boot_stage == BOOT_COMPLETE ) pIndexData->count -= number; clear_queue( this ); stop_events( this ); if( save != NULL ) { array = &save->save_list; for( i = 0; ; i++ ) { if( i >= array->size ) panic( "Extract: Object not found in save array." ); if( this == array->list[i] ) { array->list[i] = NULL; save = NULL; break; } } } delete_list( affected ); free_string( source, MEM_OBJECT ); if( singular != pIndexData->singular ) free_string( singular, MEM_OBJECT ); if( plural != pIndexData->plural ) free_string( plural, MEM_OBJECT ); if( after != pIndexData->after ) free_string( after, MEM_OBJECT ); if( before != pIndexData->before ) free_string( before, MEM_OBJECT ); timer = -2; valid = -1; extracted += this; } /* * DISK ROUTINES */ void fix( obj_clss_data* obj_clss ) { if( obj_clss->item_type == ITEM_SCROLL ) set_bit( &obj_clss->materials, MAT_PAPER ); for( int i = 0; i < MAX_ANTI; i++ ) { if( !strncasecmp( anti_flags[i], "unused", 6 ) ) remove_bit( &obj_clss->anti_flags, i ); } if( obj_clss->color < COLOR_DEFAULT || obj_clss->color > MAX_COLOR ) obj_clss->color = COLOR_DEFAULT; return; } void load_objects( void ) { FILE* fp; obj_clss_data* obj_clss; oprog_data* oprog; char letter; int i; int vnum; int count = 0; bool boot_old = false, boot_tfh = false; int version = 0; echo( "Loading Objects ...\r\n" ); vzero( obj_index_list, MAX_OBJ_INDEX ); fp = open_file( AREA_DIR, OBJECT_FILE, "rb", TRUE ); char *word = fread_word( fp ); if( !strcmp( word, "#M2_OBJECTS" ) ) { version = fread_number( fp ); } else if( !strcmp( word, "#OLD_OBJECTS" ) ) { log("... old style object file"); boot_old = true; } else if( !str_cmp( word, "#TFH_OBJECTS" ) ) { log("... tfh style object file"); boot_tfh = true; } else if( !strcmp( word, "#OBJECTS" ) ) { // version 0 object file } else { panic( "Load_objects: header not found" ); } log( " * %-20s : v%d :", OBJECT_FILE, version ); for( ; ; ) { letter = fread_letter( fp ); if( letter != '#' ) panic( "Load_objects: # not found." ); if( ( vnum = fread_number( fp ) ) == 0 ) break; if( vnum < 0 || vnum >= MAX_OBJ_INDEX ) panic( "Load_objects: vnum out of range." ); if( obj_index_list[vnum] != NULL ) panic( "Load_objects: vnum %d duplicated.", vnum ); obj_clss = new obj_clss_data; obj_index_list[vnum] = obj_clss; obj_clss->vnum = vnum; obj_clss->fakes = vnum; obj_clss->singular = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->plural = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->before = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->after = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->long_s = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->long_p = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->prefix_singular = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->prefix_plural = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->creator = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->last_mod = fread_string( fp, MEM_OBJ_CLSS ); obj_clss->item_type = fread_number( fp ); obj_clss->fakes = fread_number( fp ); obj_clss->extra_flags[0] = fread_number( fp ); obj_clss->extra_flags[1] = fread_number( fp ); obj_clss->wear_flags = fread_number( fp ); if( boot_old ) { // perform object translation int old_flags = obj_clss->wear_flags; obj_clss->wear_flags = 0; for (int i = 0; i < MAX_WEAR; i++) if (is_set(&old_flags, i)) set_bit(&obj_clss->wear_flags, old_wear_locs[i]); } obj_clss->anti_flags = fread_number( fp ); obj_clss->restrictions = fread_number( fp ); obj_clss->size_flags = fread_number( fp ); obj_clss->materials = fread_number( fp ); obj_clss->affect_flags[0] = fread_number( fp ); obj_clss->affect_flags[1] = fread_number( fp ); obj_clss->affect_flags[2] = fread_number( fp ); if( version < 3 ) { obj_clss->affect_flags[3] = 0; obj_clss->affect_flags[4] = 0; } else { obj_clss->affect_flags[3] = fread_number( fp ); obj_clss->affect_flags[4] = fread_number( fp ); } if( version < 10 ) { obj_clss->affect_flags[5] = 0; obj_clss->affect_flags[6] = 0; obj_clss->affect_flags[7] = 0; obj_clss->affect_flags[8] = 0; obj_clss->affect_flags[9] = 0; } else { obj_clss->affect_flags[5] = fread_number( fp ); obj_clss->affect_flags[6] = fread_number( fp ); obj_clss->affect_flags[7] = fread_number( fp ); obj_clss->affect_flags[8] = fread_number( fp ); obj_clss->affect_flags[9] = fread_number( fp ); } obj_clss->layer_flags = fread_number( fp ); obj_clss->value[0] = fread_number( fp ); obj_clss->value[1] = fread_number( fp ); obj_clss->value[2] = fread_number( fp ); obj_clss->value[3] = fread_number( fp ); obj_clss->weight = fread_number( fp ); obj_clss->cost = fread_number( fp ); obj_clss->level = fread_number( fp ); obj_clss->limit = fread_number( fp ); obj_clss->repair = fread_number( fp ); obj_clss->durability = fread_number( fp ); obj_clss->blocks = fread_number( fp ); obj_clss->light = fread_number( fp ); if( version < 6 ) obj_clss->color = 0; else obj_clss->color = fread_number( fp ); if( version < 7 ) obj_clss->religion_flags = 0; else obj_clss->religion_flags = fread_number( fp ); if( version < 5 ) { obj_clss->clss_synergy[ CLSS_THIEF+1 ] = 0; obj_clss->clss_synergy[ CLSS_MAGE+1 ] = 0; obj_clss->clss_synergy[ CLSS_SORCERER+1 ] = 0; obj_clss->clss_synergy[ CLSS_CLERIC+1 ] = 0; obj_clss->clss_synergy[ CLSS_DANCER+1 ] = 0; } else { obj_clss->clss_synergy[ CLSS_THIEF+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_MAGE+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_SORCERER+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_CLERIC+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_DANCER+1 ] = fread_number( fp ); } if( version < 10 ) obj_clss->clss_synergy[ CLSS_DRUID+1 ] = 0; else obj_clss->clss_synergy[ CLSS_DRUID+1 ] = fread_number( fp ); if( version < 11 ) { obj_clss->clss_synergy[ CLSS_WARRIOR+1 ] = 0; obj_clss->clss_synergy[ CLSS_CAVALIER+1 ] = 0; obj_clss->clss_synergy[ CLSS_BARBARIAN+1 ] = 0; obj_clss->clss_synergy[ CLSS_PALADIN+1 ] = 0; obj_clss->clss_synergy[ CLSS_RANGER+1 ] = 0; obj_clss->clss_synergy[ CLSS_DEFENSIVE+1 ] = 0; obj_clss->clss_synergy[ CLSS_MONK+1 ] = 0; obj_clss->clss_synergy[ CLSS_ROGUE+1 ] = 0; obj_clss->clss_synergy[ CLSS_ASSASSIN+1 ] = 0; } else { obj_clss->clss_synergy[ CLSS_WARRIOR+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_CAVALIER+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_BARBARIAN+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_PALADIN+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_RANGER+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_DEFENSIVE+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_MONK+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_ROGUE+1 ] = fread_number( fp ); obj_clss->clss_synergy[ CLSS_ASSASSIN+1 ] = fread_number( fp ); } if( version > 8 ) count = fread_number( fp ); // Reading skills (not likely, but i am hoping ) /* for( int i = 0; i < MAX_SKILL; i++ ) obj_clss->skill_modifier[i] = 0; if( version < 4 ) { for( int i = 0; i < MAX_SKILL; i++ ) obj_clss->skill_modifier[i] = 0; } else if( version < 8 ) { for( int i = 0; i < 600; i++ ) { obj_clss->skill_modifier[i] = fread_number( fp ); } } else if( version < 9 ) { for( int i = 0; i < MAX_SKILL; i++ ) obj_clss->skill_modifier[i] = fread_number( fp ); } else */if( version < 12 ) { if( count > 0 ) { for( int i = 0; i < count; i++ ) { const char* skill = fread_string( fp, MEM_OBJ_CLSS ); for( int j = 0; j < MAX_SKILL; j++ ) { if( !strcmp( skill, skill_table[j].name ) ) { // obj_clss->skill_modifier[j] = fread_number( fp ); synergy* syn = new Synergy; syn->skill = skill_table[j].name; syn->amount = fread_number( fp ); obj_clss->synergy_array += syn; break; } if( j == MAX_SKILL ) { fread_number( fp ); } } } } } else if( version < 13 ) { int size = fread_number( fp ); for( int i = 0; i < size; i++ ) { synergy* syn = new Synergy; syn->Load( fp ); obj_clss->synergy_array += syn; } } if( boot_tfh ) { fread_number( fp ); fread_number( fp ); } obj_clss->date = fread_number( fp ); read_affects( fp, obj_clss, version >= 2 ? false : true ); // version 2 object file introduced new affects format read_extra( fp, obj_clss->extra_descr ); fread_letter( fp ); for( ; ; ) { int number = fread_number( fp ); if( number == -1 ) break; oprog = new oprog_data( obj_clss ); append( obj_clss->oprog, oprog ); oprog->trigger = number; if( oprog->trigger == OPROG_TRIGGER_WEAR ) oprog->trigger = OPROG_TRIGGER_AFTER_USE; oprog->obj_vnum = fread_number( fp ); if( boot_old ) { oprog->value = 0; } else { oprog->value = fread_number( fp ); } oprog->command = fread_string( fp, MEM_OPROG ); oprog->target = fread_string( fp, MEM_OPROG ); // oprog->value = fread_number( fp ); oprog->code = fread_string( fp, MEM_OPROG ); read_extra( fp, oprog->data ); } fix( obj_clss ); } fclose( fp ); for( i = 0; i < MAX_OBJ_INDEX; i++ ) if( obj_index_list[i] != NULL ) for( oprog = obj_index_list[i]->oprog; oprog != NULL; oprog = oprog->next ) if( oprog->obj_vnum > 0 ) oprog->obj_act = get_obj_index( oprog->obj_vnum ); return; }
29.21158
216
0.532802
Celissa
123fc1ac7a5431b39d285aac6ed78ee4b7a57040
1,492
cpp
C++
WeirdEngine/src/TestProject/Source Files/PlaySceneInputComponent.cpp
jeramauni/Proyecto-3
2dbdba99ef2899e498dea3eb9a085417773686d7
[ "Apache-2.0" ]
null
null
null
WeirdEngine/src/TestProject/Source Files/PlaySceneInputComponent.cpp
jeramauni/Proyecto-3
2dbdba99ef2899e498dea3eb9a085417773686d7
[ "Apache-2.0" ]
null
null
null
WeirdEngine/src/TestProject/Source Files/PlaySceneInputComponent.cpp
jeramauni/Proyecto-3
2dbdba99ef2899e498dea3eb9a085417773686d7
[ "Apache-2.0" ]
null
null
null
#include "PlaySceneInputComponent.h" #include <iostream> #include <Container.h> #include <Messages_defs.h> #include <ComponentFactory.h> CREATE_REGISTER(PlaySceneInput); PlaySceneInputComponent::PlaySceneInputComponent(Container* e) : InputComponent(e){ _listener = new WEInputListener(e); _name = "PlayScene" + _name; _parent->getWEManager()->addKeyListener(_listener, _name); } void PlaySceneInputComponent::Init(std::unordered_map<std::string, std::string>& param) { PauseMenu = OIS::KC_ESCAPE; } // Cuando reacciona al teclado WEInputListener* PlaySceneInputComponent::getKeyListener() { return _listener; } // Cuando reacciona al raton InputMouseListener* PlaySceneInputComponent::getMouseListener() { return nullptr; } ////-----------------------LISTENER------------------------- WEInputListener::WEInputListener(Container* ow) { _owner = ow; } WEInputListener::~WEInputListener() {} bool WEInputListener::keyPressed(const OIS::KeyEvent& ke) { switch (ke.key) { case OIS::KC_ESCAPE: _owner->globalSend(this, msg::Close_Win(msg::WEManager, msg::Broadcast)); break; case OIS::KC_SPACE: std::cout << "Funciona\n"; //_owner->localSend(this, msg::Prueba(msg::Player, msg::Broadcast)); //_owner->send(this, msg::Prueba(msg::WEManager, msg::Broadcast)); break; default: break; } return true; } bool WEInputListener::keyReleased(const OIS::KeyEvent& ke) { return true; }
26.175439
89
0.676944
jeramauni
12400188b528059e5e9c0ccf1ac9b43545084cb3
5,991
cpp
C++
Code/IO/GenerateMesh.cpp
guanjilai/FastCAE
7afd59a3c0a82c1edf8f5d09482e906e878eb807
[ "BSD-3-Clause" ]
1
2021-08-14T04:49:56.000Z
2021-08-14T04:49:56.000Z
Code/IO/GenerateMesh.cpp
guanjilai/FastCAE
7afd59a3c0a82c1edf8f5d09482e906e878eb807
[ "BSD-3-Clause" ]
null
null
null
Code/IO/GenerateMesh.cpp
guanjilai/FastCAE
7afd59a3c0a82c1edf8f5d09482e906e878eb807
[ "BSD-3-Clause" ]
null
null
null
#include "GenerateMesh.h" #include "Gmsh/GmshThread.h" #include "Gmsh/GmshModule.h" #include "Gmsh/GmshThreadManager.h" #include "moduleBase/processBar.h" #include "geometry/geometryData.h" #include "geometry/GeoComponent.h" #include "geometry/geometrySet.h" #include "meshData/ElementType.h" #include <qdom.h> #include <vtkDataSet.h> #include <vtkCell.h> #include <qfile.h> namespace IO { void GenerateMesh::iniGenerateMesh(GUI::MainWindow* mw, QString path) { _mw = mw; _filePath = path; iniParameter(); connect(_thread, SIGNAL(writeToSolveFileSig(vtkDataSet*)), this, SLOT(writeToSolveFileSlot(vtkDataSet*))); } void GenerateMesh::iniParameter() { Geometry::GeometryData* geoData = Geometry::GeometryData::getInstance(); QList<Geometry::GeoComponent*> gcs = geoData->getGeoComponentList(); QMultiHash<int, int> Surface, Body; for (Geometry::GeoComponent* gc : gcs) { if (!gc) continue; QMultiHash<Geometry::GeometrySet*, int> items = gc->getSelectedItems(); QHashIterator<Geometry::GeometrySet*, int> it(items); while (it.hasNext()) { it.next(); int ID = it.key()->getID(); int index = it.value(); if (gc->getGCType() == Geometry::GeoComponentType::Surface) Surface.insert(ID, index); else if (gc->getGCType() == Geometry::GeoComponentType::Body) Body.insert(ID, index); } } Gmsh::GMshPara* para = new Gmsh::GMshPara; para->_solidHash = Body; para->_surfaceHash = Surface; para->_elementType = "Tet"; para->_method = 1; para->_dim = 3; para->_elementOrder = 1; para->_sizeFactor = 1.00; para->_maxSize = 100.00; para->_minSize = 0.00; para->_isGridCoplanar = true; para->_geoclean = true; Gmsh::GmshModule* gModule = Gmsh::GmshModule::getInstance(_mw); _thread = gModule->iniGmshThread(para); } void GenerateMesh::startGenerateMesh() { _thread->isSaveDataToKernal(false); Gmsh::GmshModule* gModule = Gmsh::GmshModule::getInstance(_mw); Gmsh::GmshThreadManager* manager = gModule->getGmshThreadManager(); auto processBar = new ModuleBase::ProcessBar(_mw, QObject::tr("Gmsh Working...")); manager->insertThread(processBar, _thread); } void GenerateMesh::writeToSolveFileSlot(vtkDataSet* data) { QDomDocument doc; QDomProcessingInstruction instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); doc.appendChild(instruction); QDomElement root = doc.createElement("DISO_FILE_1.0"); doc.appendChild(root); QDomElement mesh = doc.createElement("Mesh"); root.appendChild(mesh); writeMeshToSolveFile(&doc, &mesh, data); writeComponentToSolveFile(&doc, &mesh, data); QFile file(_filePath + "/meshdata.xml"); if (file.open(QFile::WriteOnly | QFile::Text)) { QTextStream out(&file); doc.save(out, QDomNode::EncodingFromDocument); file.close(); } } void GenerateMesh::writeMeshToSolveFile(QDomDocument* doc, QDomElement* parent, vtkDataSet* data) { int pointsCount = data->GetNumberOfPoints(); int cellsCount = data->GetNumberOfCells(); QDomElement generatedMesh = doc->createElement("GeneratedMesh"); parent->appendChild(generatedMesh); QDomElement nodelist = doc->createElement("NodeList"); generatedMesh.appendChild(nodelist); for (int i = 0; i < pointsCount; i++) { double* array = data->GetPoint(i); QStringList list; list << QString::number(i) << QString::number(array[0]) << QString::number(array[1]) << QString::number(array[2]); QString str = list.join(','); QDomText text = doc->createTextNode(str); QDomElement node = doc->createElement("Node"); nodelist.appendChild(node); node.appendChild(text); } QDomElement elementlist = doc->createElement("ElementList"); generatedMesh.appendChild(elementlist); for (int i = 0; i < cellsCount; i++) { vtkCell* cell = data->GetCell(i); QString stype = MeshData::vtkCellTYpeToString((VTKCellType)cell->GetCellType()); QString text = QString("%1,%2").arg(i).arg(stype); vtkIdList* ids = cell->GetPointIds(); int count = ids->GetNumberOfIds(); QDomElement element = doc->createElement("Element"); for (int j = 0; j < count; j++) { int id = ids->GetId(j); text.append(","); text.append(QString("%1").arg(id)); } QDomText eletext = doc->createTextNode(text); elementlist.appendChild(element); element.appendChild(eletext); } } void GenerateMesh::writeComponentToSolveFile(QDomDocument* doc, QDomElement* parent, vtkDataSet* data) { QDomElement set = doc->createElement("Set"); parent->appendChild(set); Geometry::GeometryData* geoData = Geometry::GeometryData::getInstance(); QList<Geometry::GeoComponent*> gcs = geoData->getGeoComponentList(); QList<Gmsh::itemInfo> infos = _thread->generateGeoIds(data); for (Geometry::GeoComponent* gc : gcs) { if (!gc) continue; QDomElement geoComponent = doc->createElement("GeoComponent"); geoComponent.setAttribute("ID", gc->getID()); geoComponent.setAttribute("Name", gc->getName()); geoComponent.setAttribute("Type", "Element"); set.appendChild(geoComponent); QDomElement member = doc->createElement("Member"); geoComponent.appendChild(member); QString cellIndexs = getCellIndexs(infos, gc); QDomText text = doc->createTextNode(cellIndexs); member.appendChild(text); } } QString GenerateMesh::getCellIndexs(QList<Gmsh::itemInfo>& infos, Geometry::GeoComponent*gc/*int geoSetID, int itemIndex*/) { QString cellIndexs; QMultiHash<Geometry::GeometrySet*, int> items = gc->getSelectedItems(); QHashIterator<Geometry::GeometrySet*, int> it(items); while (it.hasNext()) { it.next(); int geoSetID = it.key()->getID(); int itemIndex = it.value(); for (Gmsh::itemInfo info : infos) { if (info.geoSetID == geoSetID && info.itemIndex == itemIndex) { for (int index : info.cellIndexs) cellIndexs.append(QString::number(index)).append(','); break; } } } return cellIndexs.left(cellIndexs.size() - 1); } }
32.209677
124
0.697212
guanjilai
1240720287dbe4fe8e41388f8fb50f390dc268a3
2,153
cpp
C++
ocs2_robotic_examples/ocs2_nadia/src/gait/Gait.cpp
james-p-foster/ocs2
8f1da414ba9ebb94ad1e8dd9bd513dbb9cc462fa
[ "BSD-3-Clause" ]
null
null
null
ocs2_robotic_examples/ocs2_nadia/src/gait/Gait.cpp
james-p-foster/ocs2
8f1da414ba9ebb94ad1e8dd9bd513dbb9cc462fa
[ "BSD-3-Clause" ]
null
null
null
ocs2_robotic_examples/ocs2_nadia/src/gait/Gait.cpp
james-p-foster/ocs2
8f1da414ba9ebb94ad1e8dd9bd513dbb9cc462fa
[ "BSD-3-Clause" ]
null
null
null
#include "ocs2_nadia/gait/Gait.h" #include <ocs2_core/misc/Display.h> #include <algorithm> #include <cassert> #include <cmath> namespace ocs2 { namespace legged_robot { bool isValidGait(const Gait& gait) { bool validGait = true; validGait &= gait.duration > 0.0; validGait &= std::all_of(gait.eventPhases.begin(), gait.eventPhases.end(), [](scalar_t phase) { return 0.0 < phase && phase < 1.0; }); validGait &= std::is_sorted(gait.eventPhases.begin(), gait.eventPhases.end()); validGait &= gait.eventPhases.size() + 1 == gait.modeSequence.size(); return validGait; } bool isValidPhase(scalar_t phase) { return phase >= 0.0 && phase < 1.0; } scalar_t wrapPhase(scalar_t phase) { phase = std::fmod(phase, 1.0); if (phase < 0.0) { phase += 1.0; } return phase; } int getModeIndexFromPhase(scalar_t phase, const Gait& gait) { assert(isValidPhase(phase)); assert(isValidGait(gait)); auto firstLargerValueIterator = std::upper_bound(gait.eventPhases.begin(), gait.eventPhases.end(), phase); return static_cast<int>(firstLargerValueIterator - gait.eventPhases.begin()); } size_t getModeFromPhase(scalar_t phase, const Gait& gait) { assert(isValidPhase(phase)); assert(isValidGait(gait)); return gait.modeSequence[getModeIndexFromPhase(phase, gait)]; } scalar_t timeLeftInGait(scalar_t phase, const Gait& gait) { assert(isValidPhase(phase)); assert(isValidGait(gait)); return (1.0 - phase) * gait.duration; } scalar_t timeLeftInMode(scalar_t phase, const Gait& gait) { assert(isValidPhase(phase)); assert(isValidGait(gait)); int modeIndex = getModeIndexFromPhase(phase, gait); if (modeIndex < gait.eventPhases.size()) { return (gait.eventPhases[modeIndex] - phase) * gait.duration; } else { return timeLeftInGait(phase, gait); } } std::ostream& operator<<(std::ostream& stream, const Gait& gait) { stream << "Duration: " << gait.duration << "\n"; stream << "Event phases: {" << toDelimitedString(gait.eventPhases) << "}\n"; stream << "Mode sequence: {" << toDelimitedString(gait.modeSequence) << "}\n"; return stream; } } // namespace legged_robot } // namespace ocs2
29.902778
136
0.699025
james-p-foster
1243fa74c62b5e80b178f84fc7fb8eadc1079278
1,683
cpp
C++
Project/Main/Onket/goodgenralinfowidget.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
1
2021-01-03T21:33:26.000Z
2021-01-03T21:33:26.000Z
Project/Main/Onket/goodgenralinfowidget.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
null
null
null
Project/Main/Onket/goodgenralinfowidget.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
1
2020-07-22T14:48:58.000Z
2020-07-22T14:48:58.000Z
#include "goodgenralinfowidget.h" #include "ui_goodgenralinfowidget.h" void GoodGenralInfoWidget::update() { if(this->info_valid==true) { Good& g=Good::getGood(good_id); if(g.getDiscountpercent()==0) { this->ui->lab_price->setStyleSheet(this->font_regular); } else { this->ui->lab_price->setStyleSheet(this->font_skriteout); } ui->lab_name->setText(g.getName()); ui->lab_seller->setText(g.getMakerId()); ui->lab_price->setText(price::number(g.getPrice())); ui->lab_discount_percent->setText(QString::number(g.getDiscountpercent()*100)); ui->lab_final_price->setText(price::number(g.getFinalPrice())); ui->gridLayout->addWidget(ui->lab_1,0,0); ui->gridLayout->addWidget(ui->lab_2,1,0); ui->gridLayout->addWidget(ui->lab_3,2,0); ui->gridLayout->addWidget(ui->lab_4,3,0); ui->gridLayout->addWidget(ui->lab_5,4,0); ui->gridLayout->addWidget(ui->lab_name,0,1); ui->gridLayout->addWidget(ui->lab_seller,1,1); ui->gridLayout->addWidget(ui->lab_price,2,1); ui->gridLayout->addWidget(ui->lab_discount_percent,3,1); ui->gridLayout->addWidget(ui->lab_final_price,4,1); } } GoodGenralInfoWidget::GoodGenralInfoWidget(const QString& good_id,QWidget *parent) : QWidget(parent), ui(new Ui::GoodGenralInfoWidget) { ui->setupUi(this); this->good_id=good_id; if(Good::existGoodId(good_id)==false) { return; } else { this->info_valid=true; update(); } } GoodGenralInfoWidget::~GoodGenralInfoWidget() { delete ui; }
25.119403
87
0.620915
IsfahanUniversityOfTechnology-CE2019-23
12478c4c20dff2eb0a6695abb649947dff78812b
444
hpp
C++
Notes_Week7/friendDemo/budget.hpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
1
2019-01-06T22:36:01.000Z
2019-01-06T22:36:01.000Z
Notes_Week7/friendDemo/budget.hpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
Notes_Week7/friendDemo/budget.hpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
#ifndef BUDGET_HPP #define BUDGET_HPP #include "aux.hpp" class Budget { private: static double corpBudget; double divBudget; public: Budget() { divBudget = 0;} void addBudget(double b) { this->divBudget += b; this->corpBudget += divBudget; } double getDivBudget() const {return this->divBudget;} static double getCorpBudget() {return corpBudget;} friend void Aux::addBudget(double); }; #endif
21.142857
57
0.664414
WeiChienHsu
1247a50cfa2148ab27780aa67c44238c57f1c5f1
544
cpp
C++
12_cmake_with_unittest/wolfram/alpha.cpp
TeachYourselfCS/cmakeDemo
752ab76cd43aa80aaa647eed4f5389f4f1ff39e7
[ "MIT" ]
null
null
null
12_cmake_with_unittest/wolfram/alpha.cpp
TeachYourselfCS/cmakeDemo
752ab76cd43aa80aaa647eed4f5389f4f1ff39e7
[ "MIT" ]
null
null
null
12_cmake_with_unittest/wolfram/alpha.cpp
TeachYourselfCS/cmakeDemo
752ab76cd43aa80aaa647eed4f5389f4f1ff39e7
[ "MIT" ]
null
null
null
#include "wolfram/alpha.hpp" #include <curl_wrapper/curl_wrapper.hpp> namespace wolfram { const std::string API_BASE = "https://api.wolframalpha.com/v1/result"; std::string simple_query(const std::string &appid, const std::string &query) { // 使用 curl_wrapper 库提供的对 CURL 的 C++ 封装 using curl_wrapper::url_encode; using curl_wrapper::http_get_string; const auto url = API_BASE + "?appid=" + url_encode(appid) + "&i=" + url_encode(query); return http_get_string(url); } } // namespace wolfram
34
94
0.672794
TeachYourselfCS
1248872175050391e57b1e55632ee79d9f6705c2
3,414
hpp
C++
stm32/stm32f1/include/stm32f1/dma/Channel.hpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
1
2022-01-31T01:59:52.000Z
2022-01-31T01:59:52.000Z
stm32/stm32f1/include/stm32f1/dma/Channel.hpp
PhischDotOrg/stm32-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
5
2020-04-13T21:55:12.000Z
2020-06-27T17:44:44.000Z
stm32/stm32f1/include/stm32f1/dma/Channel.hpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
null
null
null
/*- * $Copyright$ -*/ #ifndef _DMA_CHANNEL_STM32_HPP_B6BD9823_B66D_4724_9A96_965E03319555 #define _DMA_CHANNEL_STM32_HPP_B6BD9823_B66D_4724_9A96_965E03319555 #include <stdint.h> #include <stddef.h> #include <stm32/dma/Types.hpp> #include <stm32f1/dma/Stream.hpp> /*****************************************************************************/ namespace stm32 { namespace f1 { /*****************************************************************************/ /*****************************************************************************/ class DmaChannel { DMA_Channel_TypeDef & m_channel; protected: DmaChannel(DMA_Channel_TypeDef *p_channel) : m_channel(*p_channel) { } public: static constexpr intptr_t getDmaChannelAddress(intptr_t p_dmaEngine, unsigned p_channel) { return (p_dmaEngine + 0x1c + p_channel * 20); } void handleIrq(void) const { (void) m_channel; } }; /*****************************************************************************/ /*****************************************************************************/ template< typename NvicT, typename DmaEngineT, unsigned nChannelNo > class DmaChannelT : public EngineT< DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo) >, public DmaChannel { static_assert(nChannelNo >= 0); static_assert((DmaEngineT::m_engineType == DMA1_BASE) && (nChannelNo <= 7)); const NvicT & m_nvic; public: DmaChannelT(const NvicT &p_nvic, const DmaEngineT & /* p_dmaEngine */) : DmaChannel(reinterpret_cast<DMA_Channel_TypeDef *>(DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo))), m_nvic(p_nvic) { m_nvic.enableIrq(* static_cast< EngineT< DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo) > *>(this)); } ~DmaChannelT() { m_nvic.disableIrq(* static_cast< EngineT< DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo) > *>(this)); } void setup(const dma::DmaDirection_t /* p_direction */, const size_t /* p_length */) const { // this->m_stream.disable(); // this->m_stream.setup(this->m_channel, p_direction, p_length); } void setupFifo(const dma::DmaBurstSize_t /* p_burst */, const dma::DmaFifoThreshold_t /* p_threshold */) const { } void setupSource(const void * const /* p_addr */, const unsigned /* p_width */, const bool /* p_incr */) const { // this->m_stream.setupSource(p_addr, p_width, p_incr); } void setupTarget(void * const /* p_addr */, const unsigned /* p_width */, const bool /* p_incr */) const { // this->m_stream.setupTarget(p_addr, p_width, p_incr); } void start(/* const DmaChannelCallback * const p_callback */ void) const { // assert(this->m_callback == NULL); // this->m_callback = p_callback; // this->m_stream.enable(&this->m_streamCallback); } void stop(void) const { // this->m_stream.disable(); // this->m_callback = NULL; } }; /*****************************************************************************/ /*****************************************************************************/ } /* namespace f1 */ } /* namespace dma */ /*****************************************************************************/ #endif /* _DMA_CHANNEL_STM32_HPP_B6BD9823_B66D_4724_9A96_965E03319555 */
34.836735
149
0.550088
PhischDotOrg
1249a9e10b06ff417f104350e87b75ba712d9446
2,470
hpp
C++
src/client/ofi_connector.hpp
ashahba/aeon
eafbc6b7040bf594854bd92f1606d37ddd862943
[ "Apache-2.0" ]
null
null
null
src/client/ofi_connector.hpp
ashahba/aeon
eafbc6b7040bf594854bd92f1606d37ddd862943
[ "Apache-2.0" ]
3
2021-09-08T02:26:12.000Z
2022-03-12T00:45:28.000Z
src/client/ofi_connector.hpp
ashahba/aeon
eafbc6b7040bf594854bd92f1606d37ddd862943
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 Intel(R) Nervana(TM) 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. */ #pragma once #include <memory> #include "http_connector.hpp" #include "../rdma/ofi.hpp" namespace nervana { class ofi_connector final : public http_connector { public: explicit ofi_connector(const std::string& address, unsigned int port, std::shared_ptr<http_connector> base_connector); ofi_connector() = delete; ~ofi_connector(); http_response get(const std::string& endpoint, const http_query_t& query = http_query_t()) override; http_response post(const std::string& endpoint, const std::string& body = "") override { return m_base_connector->post(endpoint, body); } http_response post(const std::string& endpoint, const http_query_t& query) override { return m_base_connector->post(endpoint, query); } http_response del(const std::string& endpoint, const http_query_t& query = http_query_t()) override; private: void connect(const std::string& address, unsigned int port); void disconnect(); void register_rdma_memory(size_t size); void unregister_rdma_memory(); bool is_rdma_registered() { return m_rdma_memory.is_registered(); } http_response receive_data(const std::string& endpoint, const http_query_t& query); http_response receive_message_data(const std::string& endpoint, const http_query_t& query); http_response receive_rdma_data(const std::string& endpoint, const http_query_t& query); std::shared_ptr<http_connector> m_base_connector; std::string m_connection_id; ofi::ofi m_ofi; ofi::rdma_memory m_rdma_memory; }; }
38
99
0.640081
ashahba
124fd45622dd2f9fb7cb43fc834bca9ecfbc2925
3,128
cpp
C++
jbmc/unit/java_bytecode/expr2java.cpp
DamonLiuTHU/cbmc
67f8c916672347ab05418db45eebbd93885efdec
[ "BSD-4-Clause" ]
null
null
null
jbmc/unit/java_bytecode/expr2java.cpp
DamonLiuTHU/cbmc
67f8c916672347ab05418db45eebbd93885efdec
[ "BSD-4-Clause" ]
null
null
null
jbmc/unit/java_bytecode/expr2java.cpp
DamonLiuTHU/cbmc
67f8c916672347ab05418db45eebbd93885efdec
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Unit tests for expr-to-java string conversion Author: Diffblue Ltd. \*******************************************************************/ #include <testing-utils/catch.hpp> #include <java_bytecode/expr2java.h> TEST_CASE( "expr2java tests", "[core][java_bytecode][expr2java][floating_point_to_java_string]") { SECTION("0.0 double to string") { REQUIRE(floating_point_to_java_string(0.0) == "0.0"); } SECTION("0.0 float to string") { REQUIRE(floating_point_to_java_string(0.0f) == "0.0f"); } SECTION("-0.0 double to string") { REQUIRE(floating_point_to_java_string(-0.0) == "-0.0"); } SECTION("-0.0 float to string") { REQUIRE(floating_point_to_java_string(-0.0f) == "-0.0f"); } SECTION("1.0 double to string") { REQUIRE(floating_point_to_java_string(1.0) == "1.0"); } SECTION("1.0 float to string") { REQUIRE(floating_point_to_java_string(1.0f) == "1.0f"); } SECTION("-1.0 double to string") { REQUIRE(floating_point_to_java_string(-1.0) == "-1.0"); } SECTION("-1.0 float to string") { REQUIRE(floating_point_to_java_string(-1.0f) == "-1.0f"); } SECTION("Infinity double to string") { REQUIRE( floating_point_to_java_string(static_cast<double>(INFINITY)) == "Double.POSITIVE_INFINITY"); } SECTION("Infinity float to string") { REQUIRE( floating_point_to_java_string(static_cast<float>(INFINITY)) == "Float.POSITIVE_INFINITY"); } SECTION("Negative infinity double to string") { REQUIRE( floating_point_to_java_string(static_cast<double>(-INFINITY)) == "Double.NEGATIVE_INFINITY"); } SECTION("Negative infinity float to string") { REQUIRE( floating_point_to_java_string(static_cast<float>(-INFINITY)) == "Float.NEGATIVE_INFINITY"); } SECTION("Float NaN to string") { REQUIRE( floating_point_to_java_string(static_cast<float>(NAN)) == "Float.NaN"); } SECTION("Double NaN to string") { REQUIRE( floating_point_to_java_string(static_cast<double>(NAN)) == "Double.NaN"); } SECTION("Hex float to string (print a comment)") { const float value = std::strtod("0x1p+37f", nullptr); #ifndef _MSC_VER REQUIRE( floating_point_to_java_string(value) == "0x1p+37f /* 1.37439e+11 */"); #else REQUIRE( floating_point_to_java_string(value) == "0x1.000000p+37f /* 1.37439e+11 */"); #endif } SECTION("Hex double to string (print a comment)") { const double value = std::strtod("0x1p+37f", nullptr); #ifndef _MSC_VER REQUIRE( floating_point_to_java_string(value) == "0x1p+37 /* 1.37439e+11 */"); #else REQUIRE( floating_point_to_java_string(value) == "0x1.000000p+37 /* 1.37439e+11 */"); #endif } SECTION("Beyond numeric limits") { #ifndef _MSC_VER REQUIRE( floating_point_to_java_string(-5.56268e-309) .find("/* -5.56268e-309 */") != std::string::npos); #else REQUIRE(floating_point_to_java_string(-5.56268e-309) == "-5.56268e-309"); #endif } }
23.518797
79
0.624361
DamonLiuTHU
125941b9721baa7147c01a5b8adf1f094d456f39
4,167
cpp
C++
demo/Demo.cpp
logicomacorp/pulsejet
ec73d19ccb71ff05b2122e258fe4b7b16e55fb53
[ "MIT" ]
30
2021-06-07T20:25:48.000Z
2022-03-30T00:52:38.000Z
demo/Demo.cpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
null
null
null
demo/Demo.cpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
1
2021-09-21T11:17:45.000Z
2021-09-21T11:17:45.000Z
#include "FastSinusoids.hpp" // Required by `Pulsejet::Encode` and `Pulsejet::Decode` namespace Pulsejet::Shims { inline float CosF(float x) { return FastSinusoids::CosF(x); } inline float Exp2f(float x) { return exp2f(x); } inline float SinF(float x) { return FastSinusoids::SinF(x); } inline float SqrtF(float x) { return sqrtf(x); } } #include <Pulsejet/Pulsejet.hpp> #include <cstdint> #include <cstring> #include <fstream> #include <iomanip> #include <iostream> #include <vector> using namespace std; static void PrintUsage(const char **argv) { cout << "Usage:\n"; cout << " encode: " << argv[0] << " -e <target bit rate in kbps> <input.raw> <output.pulsejet>\n"; cout << " decode: " << argv[0] << " -d <input.pulsejet> <output.raw>\n"; } static void ErrorInvalidArgs(const char **argv) { cout << "ERROR: Invalid args\n\n"; PrintUsage(argv); } static vector<uint8_t> ReadFile(const char *fileName) { ifstream inputFile(fileName, ios::binary | ios::ate); const auto inputFileSize = inputFile.tellg(); inputFile.seekg(0, ios::beg); vector<uint8_t> ret(inputFileSize); inputFile.read(reinterpret_cast<char *>(ret.data()), inputFileSize); return ret; } int main(int argc, const char **argv) { if (argc < 4) { ErrorInvalidArgs(argv); return 1; } cout << "library version: " << Pulsejet::LibraryVersionString() << "\n"; cout << "codec version: " << Pulsejet::CodecVersionString() << "\n"; FastSinusoids::Init(); if (!strcmp(argv[1], "-e")) { if (argc != 5) { ErrorInvalidArgs(argv); return 1; } const double targetBitRate = stod(argv[2]); const auto inputFileName = argv[3]; const auto outputFileName = argv[4]; cout << "reading ... " << flush; const auto input = ReadFile(inputFileName); cout << "ok\n"; cout << "size check ... " << flush; if (input.size() % sizeof(float)) { cout << "ERROR: Input size is not aligned to float size\n\n"; return 1; } cout << "ok\n"; cout << "encoding ... " << flush; const uint32_t numSamples = static_cast<uint32_t>(input.size()) / sizeof(float); const double sampleRate = 44100.0; double totalBitsEstimate; const auto encodedSample = Pulsejet::Encode(reinterpret_cast<const float *>(input.data()), numSamples, sampleRate, targetBitRate, totalBitsEstimate); const auto bitRateEstimate = totalBitsEstimate / 1000.0 / (static_cast<double>(numSamples) / sampleRate); cout << "ok, compressed size estimate: " << static_cast<uint32_t>(ceil(totalBitsEstimate / 8.0)) << " byte(s) (~" << setprecision(4) << bitRateEstimate << "kbps)\n"; cout << "writing ... " << flush; ofstream outputFile(outputFileName, ios::binary); outputFile.write(reinterpret_cast<const char *>(encodedSample.data()), encodedSample.size()); cout << "ok\n"; cout << "encoding successful!\n"; } else if (!strcmp(argv[1], "-d")) { if (argc != 4) { ErrorInvalidArgs(argv); return 1; } const auto inputFileName = argv[2]; const auto outputFileName = argv[3]; cout << "reading ... " << flush; const auto input = ReadFile(inputFileName); cout << "ok\n"; cout << "sample check ... " << flush; if (!Pulsejet::CheckSample(input.data())) { cout << "ERROR: Input is not a pulsejet sample\n\n"; return 1; } cout << "ok\n"; cout << "sample version: " << Pulsejet::SampleVersionString(input.data()) << "\n"; cout << "sample version check ... " << flush; if (!Pulsejet::CheckSampleVersion(input.data())) { cout << "ERROR: Incompatible codec and sample versions\n\n"; return 1; } cout << "ok\n"; cout << "decoding ... " << flush; uint32_t numDecodedSamples; const auto decodedSample = Pulsejet::Decode(input.data(), &numDecodedSamples); cout << "ok, " << numDecodedSamples << " samples\n"; cout << "writing ... " << flush; ofstream outputFile(outputFileName, ios::binary); outputFile.write(reinterpret_cast<const char *>(decodedSample), numDecodedSamples * sizeof(float)); cout << "ok\n"; cout << "cleanup ... " << flush; delete [] decodedSample; cout << "ok\n"; cout << "decoding successful!\n"; } else { ErrorInvalidArgs(argv); return 1; } return 0; }
24.656805
167
0.648908
logicomacorp
125dcfd5073caa4a21da9cf969edd3a46e6c89d8
30,060
cpp
C++
framework/NetKinectArray.cpp
steppobeck/rgbd-recon
171a8336c8e3ba52a1b187b73544338fdd3c9285
[ "MIT" ]
18
2016-09-03T05:12:25.000Z
2022-02-23T15:52:33.000Z
framework/NetKinectArray.cpp
3d-scan/rgbd-recon
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
[ "MIT" ]
1
2016-05-04T09:06:29.000Z
2016-05-04T09:06:29.000Z
framework/NetKinectArray.cpp
3d-scan/rgbd-recon
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
[ "MIT" ]
7
2016-04-20T13:58:50.000Z
2018-07-09T15:47:26.000Z
#include "NetKinectArray.h" #include "calibration_files.hpp" #include "texture_blitter.hpp" #include "screen_quad.hpp" #include <FileBuffer.h> #include <TextureArray.h> #include <KinectCalibrationFile.h> #include "CalibVolumes.hpp" #include <DXTCompressor.h> #include "timer_database.hpp" #include <glbinding/gl/gl.h> #include <glbinding/gl/functions-patches.h> using namespace gl; #include <globjects/Program.h> #include <globjects/Texture.h> #include <globjects/Framebuffer.h> #include <globjects/Buffer.h> #include <globjects/Shader.h> #include <globjects/logging.h> #include <globjects/NamedString.h> #include <globjects/base/File.h> #include <globjects/Query.h> #include <globjects/NamedString.h> #include <globjects/base/File.h> #include "squish/squish.h" #include <zmq.hpp> #include <iostream> #include <vector> #include <string> #include <fstream> #include <thread> namespace kinect{ static const std::size_t s_num_bg_frames = 20; NetKinectArray::NetKinectArray(std::string const& serverport, std::string const& slaveport, CalibrationFiles const* calibs, CalibVolumes const* vols, bool readfromfile) : m_numLayers(0), m_colorArray(), m_depthArray_raw(), m_textures_depth{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_textures_depth_b{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_textures_depth2{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY), globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_textures_quality{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_textures_normal{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_textures_color{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_textures_bg{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY), globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_textures_silhouette{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)}, m_fbo{new globjects::Framebuffer()}, m_colorArray_back(), m_colorsize(0), m_depthsize(0), m_pbo_colors(), m_pbo_depths(), m_mutex_pbo(), m_readThread(), m_running(true), m_filter_textures(true), m_refine_bound(true), m_serverport(serverport), m_slaveport(slaveport), m_num_frame{0}, m_curr_frametime{0.0}, m_use_processed_depth{true}, m_start_texture_unit(0), m_calib_files{calibs}, m_calib_vols{vols}, m_streamslot(0) { m_programs.emplace("filter", new globjects::Program()); m_programs.emplace("normal", new globjects::Program()); m_programs.emplace("quality", new globjects::Program()); m_programs.emplace("boundary", new globjects::Program()); m_programs.emplace("morph", new globjects::Program()); // must happen before thread launching init(); if(readfromfile){ readFromFiles(); } else{ m_readThread = std::unique_ptr<std::thread>{new std::thread(std::bind(&NetKinectArray::readLoop, this))}; } globjects::NamedString::create("/bricks.glsl", new globjects::File("glsl/inc_bricks.glsl")); m_programs.at("filter")->attach( globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs") ,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_depth.fs") ); m_programs.at("normal")->attach( globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs") ,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_normal.fs") ); m_programs.at("quality")->attach( globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs") ,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_quality.fs") ); m_programs.at("boundary")->attach( globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs") ,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_boundary.fs") ); m_programs.at("morph")->attach( globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs") ,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_morph.fs") ); } bool NetKinectArray::init(){ m_numLayers = m_calib_files->num(); m_resolution_depth = glm::uvec2{m_calib_files->getWidth(), m_calib_files->getHeight()}; m_resolution_color = glm::uvec2{m_calib_files->getWidthC(), m_calib_files->getHeightC()}; if(m_calib_files->isCompressedRGB() == 1){ mvt::DXTCompressor dxt; dxt.init(m_calib_files->getWidthC(), m_calib_files->getHeightC(), FORMAT_DXT1); m_colorsize = dxt.getStorageSize(); } else if(m_calib_files->isCompressedRGB() == 5){ std::cerr << "NetKinectArray: using DXT5" << std::endl; m_colorsize = 307200; } else{ m_colorsize = m_resolution_color.x * m_resolution_color.y * 3 * sizeof(byte); } m_pbo_colors = double_pbo{m_colorsize * m_numLayers}; if(m_calib_files->isCompressedDepth()){ m_pbo_depths.size = m_resolution_depth.x * m_resolution_depth.y * m_numLayers * sizeof(byte); m_depthsize = m_resolution_depth.x * m_resolution_depth.y * sizeof(byte); } else{ m_pbo_depths.size = m_resolution_depth.x * m_resolution_depth.y * m_numLayers * sizeof(float); m_depthsize = m_resolution_depth.x * m_resolution_depth.y * sizeof(float); } m_pbo_depths = double_pbo{m_depthsize * m_numLayers}; /* kinect color: GL_RGB32F, GL_RGB, GL_FLOAT*/ /* kinect depth: GL_LUMINANCE32F_ARB, GL_RED, GL_FLOAT*/ //m_colorArray = new TextureArray(m_resolution_depth.x, m_resolution_depth.y, m_numLayers, GL_RGB32F, GL_RGB, GL_FLOAT); if(m_calib_files->isCompressedRGB() == 1){ std::cout << "Color DXT 1 compressed" << std::endl; m_colorArray = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, m_colorsize)}; } else if(m_calib_files->isCompressedRGB() == 5){ std::cout << "Color DXT 5 compressed" << std::endl; m_colorArray = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_UNSIGNED_BYTE, m_colorsize)}; } else{ m_colorArray = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE)}; } m_colorArray_back = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE)}; m_textures_color->image3D(0, GL_RGB32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RGB, GL_FLOAT, (void*)nullptr); m_textures_quality->image3D(0, GL_LUMINANCE32F_ARB, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr); m_textures_normal->image3D(0, GL_RGB32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RGB, GL_FLOAT, (void*)nullptr); std::vector<glm::fvec2> empty_bg_tex(m_resolution_depth.x * m_resolution_depth.y * m_numLayers, glm::fvec2{0.0f}); m_textures_bg.front->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, empty_bg_tex.data()); m_textures_bg.back->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, empty_bg_tex.data()); m_textures_silhouette->image3D(0, GL_R32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr); if(m_calib_files->isCompressedDepth()){ m_depthArray_raw = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_depth.x, m_resolution_depth.y, m_numLayers, GL_LUMINANCE, GL_RED, GL_UNSIGNED_BYTE)}; } else{ m_depthArray_raw = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_depth.x, m_resolution_depth.y, m_numLayers, GL_LUMINANCE32F_ARB, GL_RED, GL_FLOAT)}; } m_textures_depth->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, (void*)nullptr); m_textures_depth_b->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, (void*)nullptr); m_textures_depth2.front->image3D(0, GL_LUMINANCE32F_ARB, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr); m_textures_depth2.back->image3D(0, GL_LUMINANCE32F_ARB, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr); m_depthArray_raw->setMAGMINFilter(GL_NEAREST); m_textures_depth_b->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_textures_depth_b->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_textures_depth->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_textures_depth->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_textures_depth2.front->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_textures_depth2.front->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_textures_depth2.back->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_textures_depth2.back->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_texture_unit_offsets.emplace("morph_input", 42); m_texture_unit_offsets.emplace("raw_depth", 40); // m_texture_unit_offsets.emplace("bg_depth", 41); m_programs.at("filter")->setUniform("kinect_depths", getTextureUnit("raw_depth")); glm::fvec2 tex_size_inv{1.0f/m_resolution_depth.x, 1.0f/m_resolution_depth.y}; m_programs.at("filter")->setUniform("texSizeInv", tex_size_inv); m_programs.at("normal")->setUniform("texSizeInv", tex_size_inv); m_programs.at("quality")->setUniform("texSizeInv", tex_size_inv); m_programs.at("quality")->setUniform("camera_positions", m_calib_vols->getCameraPositions()); m_programs.at("morph")->setUniform("texSizeInv", tex_size_inv); m_programs.at("morph")->setUniform("kinect_depths", getTextureUnit("morph_input")); m_programs.at("boundary")->setUniform("texSizeInv", tex_size_inv); // m_programs.at("bg")->setUniform("bg_depths", getTextureUnit("bg_depth")); globjects::NamedString::create("/inc_bbox_test.glsl", new globjects::File("glsl/inc_bbox_test.glsl")); globjects::NamedString::create("/inc_color.glsl", new globjects::File("glsl/inc_color.glsl")); TimerDatabase::instance().addTimer("morph"); TimerDatabase::instance().addTimer("bilateral"); TimerDatabase::instance().addTimer("boundary"); TimerDatabase::instance().addTimer("normal"); TimerDatabase::instance().addTimer("quality"); TimerDatabase::instance().addTimer("1preprocess"); return true; } NetKinectArray::~NetKinectArray(){ m_running = false; m_readThread->join(); } bool NetKinectArray::update() { // lock pbos before checking status std::unique_lock<std::mutex> lock(m_mutex_pbo); // skip if no new frame was received if(!m_pbo_colors.dirty || !m_pbo_depths.dirty) return false; m_colorArray->fillLayersFromPBO(m_pbo_colors.get()->id()); m_depthArray_raw->fillLayersFromPBO(m_pbo_depths.get()->id()); // processTextures(); return true; } glm::uvec2 NetKinectArray::getDepthResolution() const { return m_resolution_depth; } glm::uvec2 NetKinectArray::getColorResolution() const { return m_resolution_color; } int NetKinectArray::getTextureUnit(std::string const& name) const { return m_texture_unit_offsets.at(name); } void NetKinectArray::processDepth() { m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0}); glActiveTexture(GL_TEXTURE0 + getTextureUnit("morph_input")); m_depthArray_raw->bind(); m_programs.at("morph")->use(); m_programs.at("morph")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits()); // erode m_programs.at("morph")->setUniform("mode", 0u); for(unsigned i = 0; i < m_calib_files->num(); ++i){ m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth2.back, 0, i); m_programs.at("morph")->setUniform("layer", i); ScreenQuad::draw(); } // dilate m_programs.at("morph")->setUniform("mode", 1u); m_textures_depth2.swapBuffers(); m_textures_depth2.front->bindActive(getTextureUnit("morph_input")); for(unsigned i = 0; i < m_calib_files->num(); ++i){ m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth2.back, 0, i); m_programs.at("morph")->setUniform("layer", i); ScreenQuad::draw(); } m_textures_depth2.front->unbindActive(getTextureUnit("morph_input")); m_programs.at("morph")->release(); m_textures_depth2.swapBuffers(); m_textures_depth2.front->bindActive(getTextureUnit("morph_depth")); if(m_use_processed_depth) { m_textures_depth2.front->bindActive(getTextureUnit("raw_depth")); } } void NetKinectArray::processBackground() { m_textures_bg.front->bindActive(getTextureUnit("bg_depth")); m_programs.at("bg")->use(); for(unsigned i = 0; i < m_calib_files->num(); ++i){ m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_bg.back, 0, i); m_programs.at("bg")->setUniform("layer", i); ScreenQuad::draw(); } m_programs.at("bg")->release(); m_textures_bg.swapBuffers(); m_textures_bg.front->bindActive(getTextureUnit("bg")); ++m_num_frame; } void NetKinectArray::processTextures(){ TimerDatabase::instance().begin("1preprocess"); GLint current_fbo; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &current_fbo); GLsizei old_vp_params[4]; glGetIntegerv(GL_VIEWPORT, old_vp_params); glViewport(0, 0, m_resolution_depth.x, m_resolution_depth.y); glActiveTexture(GL_TEXTURE0 + getTextureUnit("raw_depth")); m_depthArray_raw->bind(); m_fbo->bind(); TimerDatabase::instance().begin("morph"); processDepth(); TimerDatabase::instance().end("morph"); TimerDatabase::instance().begin("bilateral"); m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1}); m_programs.at("filter")->use(); m_programs.at("filter")->setUniform("filter_textures", m_filter_textures); m_programs.at("filter")->setUniform("processed_depth", m_use_processed_depth); m_programs.at("filter")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits()); m_programs.at("filter")->setUniform("cv_uv", m_calib_vols->getUVVolumeUnits()); // depth and old quality for(unsigned i = 0; i < m_calib_files->num(); ++i){ m_programs.at("filter")->setUniform("cv_min_ds", m_calib_vols->getDepthLimits(i).x); m_programs.at("filter")->setUniform("cv_max_ds", m_calib_vols->getDepthLimits(i).y); m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth, 0, i); m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT1, m_textures_color, 0, i); m_programs.at("filter")->setUniform("layer", i); m_programs.at("filter")->setUniform("compress", m_calib_files->getCalibs()[i].isCompressedDepth()); const float near = m_calib_files->getCalibs()[i].getNear(); const float far = m_calib_files->getCalibs()[i].getFar(); const float scale = (far - near); m_programs.at("filter")->setUniform("scale", scale); m_programs.at("filter")->setUniform("near", near); m_programs.at("filter")->setUniform("scaled_near", scale/255.0f); ScreenQuad::draw(); } m_programs.at("filter")->release(); TimerDatabase::instance().end("bilateral"); // boundary TimerDatabase::instance().begin("boundary"); m_programs.at("boundary")->use(); m_programs.at("boundary")->setUniform("cv_uv", m_calib_vols->getUVVolumeUnits()); m_programs.at("boundary")->setUniform("refine", m_refine_bound); m_textures_depth->bindActive(getTextureUnit("depth")); for(unsigned i = 0; i < m_calib_files->num(); ++i){ m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth_b, 0, i); m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT1, m_textures_silhouette, 0, i); m_programs.at("boundary")->setUniform("layer", i); ScreenQuad::draw(); } m_programs.at("boundary")->release(); TimerDatabase::instance().end("boundary"); m_textures_depth_b->bindActive(getTextureUnit("depth")); // normals TimerDatabase::instance().begin("normal"); m_programs.at("normal")->use(); m_programs.at("normal")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits()); m_programs.at("normal")->setUniform("cv_uv", m_calib_vols->getUVVolumeUnits()); m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0}); for(unsigned i = 0; i < m_calib_files->num(); ++i){ m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_normal, 0, i); m_programs.at("normal")->setUniform("layer", i); ScreenQuad::draw(); } m_programs.at("normal")->release(); TimerDatabase::instance().end("normal"); // quality TimerDatabase::instance().begin("quality"); m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0}); m_programs.at("quality")->use(); m_programs.at("quality")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits()); m_programs.at("quality")->setUniform("processed_depth", m_use_processed_depth); for(unsigned i = 0; i < m_calib_files->num(); ++i){ m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_quality, 0, i); m_programs.at("quality")->setUniform("layer", i); ScreenQuad::draw(); } m_programs.at("quality")->release(); TimerDatabase::instance().end("quality"); if(m_num_frame < s_num_bg_frames && m_curr_frametime < 0.5) { // processBackground(); } m_fbo->unbind(); glViewport ((GLsizei)old_vp_params[0], (GLsizei)old_vp_params[1], (GLsizei)old_vp_params[2], (GLsizei)old_vp_params[3]); TimerDatabase::instance().end("1preprocess"); } void NetKinectArray::setStartTextureUnit(unsigned start_texture_unit) { m_start_texture_unit = start_texture_unit; m_texture_unit_offsets["color"] = m_start_texture_unit; m_texture_unit_offsets["depth"] = m_start_texture_unit + 1; m_texture_unit_offsets["quality"] = m_start_texture_unit + 2; m_texture_unit_offsets["normal"] = m_start_texture_unit + 3; m_texture_unit_offsets["silhouette"] = m_start_texture_unit + 4; // m_texture_unit_offsets["bg"] = m_start_texture_unit + 5; m_texture_unit_offsets["morph_depth"] = m_start_texture_unit + 5; m_texture_unit_offsets["color_lab"] = m_start_texture_unit + 6; bindToTextureUnits(); m_programs.at("filter")->setUniform("kinect_colors", getTextureUnit("color")); m_programs.at("normal")->setUniform("kinect_depths", getTextureUnit("depth")); m_programs.at("quality")->setUniform("kinect_depths", getTextureUnit("depth")); m_programs.at("quality")->setUniform("kinect_normals", getTextureUnit("normal")); m_programs.at("quality")->setUniform("kinect_colors_lab", getTextureUnit("color_lab")); m_programs.at("boundary")->setUniform("kinect_colors_lab", getTextureUnit("color_lab")); m_programs.at("boundary")->setUniform("kinect_depths", getTextureUnit("depth")); m_programs.at("boundary")->setUniform("kinect_colors", getTextureUnit("color")); } void NetKinectArray::bindToTextureUnits() const { glActiveTexture(GL_TEXTURE0 + getTextureUnit("color")); m_colorArray->bind(); m_textures_quality->bindActive(getTextureUnit("quality")); m_textures_normal->bindActive(getTextureUnit("normal")); m_textures_silhouette->bindActive(getTextureUnit("silhouette")); // m_textures_bg.front->bindActive(getTextureUnit("bg")); m_textures_depth2.front->bindActive(getTextureUnit("morph_depth")); m_textures_color->bindActive(getTextureUnit("color_lab")); glActiveTexture(GL_TEXTURE0 + getTextureUnit("raw_depth")); m_depthArray_raw->bind(); } unsigned NetKinectArray::getStartTextureUnit() const { return m_start_texture_unit; } void NetKinectArray::filterTextures(bool filter) { m_filter_textures = filter; // process with new settings processTextures(); } void NetKinectArray::useProcessedDepths(bool filter) { m_use_processed_depth = filter; processTextures(); } void NetKinectArray::refineBoundary(bool filter) { m_refine_bound = filter; processTextures(); } void NetKinectArray::readLoop(){ // open multicast listening connection to server and port zmq::context_t ctx(1); // means single threaded zmq::socket_t socket(ctx, ZMQ_SUB); // means a subscriber socket.setsockopt(ZMQ_SUBSCRIBE, "", 0); uint32_t hwm = 1; socket.setsockopt(ZMQ_RCVHWM, &hwm, sizeof(hwm)); std::string endpoint("tcp://" + m_serverport); socket.connect(endpoint.c_str()); zmq::socket_t slave_socket(ctx, ZMQ_SUB); // means a subscriber slave_socket.setsockopt(ZMQ_SUBSCRIBE, "", 0); uint32_t slave_hwm = 1; slave_socket.setsockopt(ZMQ_RCVHWM, &slave_hwm, sizeof(slave_hwm)); std::string slave_endpoint("tcp://" + m_slaveport); slave_socket.connect(slave_endpoint.c_str()); //const unsigned pixelcountc = m_calib_files->getWidthC() * m_calib_files->getHeightC(); const unsigned colorsize = m_colorsize; const unsigned depthsize = m_depthsize;//pixelcount * sizeof(float); double current_time = 0.0; while(m_running){ zmq::message_t zmqm((colorsize + depthsize) * m_calib_files->num()); if(1 == m_streamslot){ slave_socket.recv(&zmqm); // blocking } else{ socket.recv(&zmqm); // blocking } { // lock pbos std::unique_lock<std::mutex> lock(m_mutex_pbo); memcpy(&current_time, (byte*)zmqm.data(), sizeof(double)); // std::cout << "time " << current_time << std::endl; m_curr_frametime = current_time; unsigned offset = 0; // receive data const unsigned number_of_kinects = m_calib_files->num(); // is 5 in the current example // this loop goes over each kinect like K1_frame_1 K2_frame_1 K3_frame_1 for(unsigned i = 0; i < number_of_kinects; ++i){ memcpy((byte*) m_pbo_colors.pointer() + i*colorsize , (byte*) zmqm.data() + offset, colorsize); offset += colorsize; memcpy((byte*) m_pbo_depths.pointer() + i*depthsize , (byte*) zmqm.data() + offset, depthsize); offset += depthsize; } // swap m_pbo_colors.dirty = true; m_pbo_depths.dirty = true; } } } void NetKinectArray::writeCurrentTexture(std::string prefix){ //depths if (m_calib_files->isCompressedDepth()) { glPixelStorei(GL_PACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D_ARRAY,m_depthArray_raw->getGLHandle()); int width, height, depth; glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_WIDTH, &width); glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_HEIGHT, &height); glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_DEPTH, &depth); std::vector<std::uint8_t> depths; depths.resize(width*height*depth); glGetTexImage(GL_TEXTURE_2D_ARRAY, 0, GL_RED, GL_UNSIGNED_BYTE, (void*)&depths[0]); int offset = 0; for (int k = 0; k < depth; ++k) { std::stringstream sstr; sstr << "output/" << prefix << "_d_" << k << ".bmp"; std::string filename (sstr.str()); std::cout << "writing depth texture for kinect " << k << " to file " << filename << std::endl; offset += width*height; writeBMP(filename, depths, offset, 1); offset += width*height; } } else { glPixelStorei(GL_PACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D_ARRAY,m_depthArray_raw->getGLHandle()); int width, height, depth; glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_WIDTH, &width); glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_HEIGHT, &height); glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_DEPTH, &depth); std::vector<float> depthsTmp; depthsTmp.resize(width*height*depth); glGetTexImage(GL_TEXTURE_2D_ARRAY, 0, GL_RED, GL_FLOAT, (void*)&depthsTmp[0]); std::vector<std::uint8_t> depths; depths.resize(depthsTmp.size()); for (int i = 0; i < width*height*depth; ++i) { depths[i] = (std::uint8_t)depthsTmp[i] * 255.0f; } int offset = 0; for (int k = 0; k < depth; ++k) { std::stringstream sstr; sstr << "output/" << prefix << "_d_" << k << ".bmp"; std::string filename (sstr.str()); std::cout << "writing depth texture for kinect " << k << " to file " << filename << " (values are compressed to 8bit)" << std::endl; writeBMP(filename, depths, offset, 1); offset += width*height; } } //color if (m_calib_files->isCompressedRGB() == 1) { glPixelStorei(GL_PACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D_ARRAY,m_colorArray->getGLHandle()); int size; glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &size); std::vector<std::uint8_t> data; data.resize(size); glGetCompressedTexImage(GL_TEXTURE_2D_ARRAY, 0, (void*)&data[0]); std::vector<std::uint8_t> colors; colors.resize(4*m_resolution_color.x*m_resolution_color.y); for (unsigned k = 0; k < m_numLayers; ++k) { squish::DecompressImage (&colors[0], m_resolution_color.x, m_resolution_color.y, &data[k*m_colorsize], squish::kDxt1); std::stringstream sstr; sstr << "output/" << prefix << "_col_" << k << ".bmp"; std::string filename (sstr.str()); std::cout << "writing color texture for kinect " << k << " to file " << filename << std::endl; writeBMP(filename, colors, 0, 4); } } else { glPixelStorei(GL_PACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D_ARRAY,m_colorArray->getGLHandle()); int width, height, depth; glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_WIDTH, &width); glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_HEIGHT, &height); glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_DEPTH, &depth); std::vector<std::uint8_t> colors; colors.resize(3*width*height*depth); glGetTexImage(GL_TEXTURE_2D_ARRAY, 0, GL_RGB, GL_UNSIGNED_BYTE, (void*)&colors[0]); int offset = 0; for (int k = 0; k < depth; ++k) { std::stringstream sstr; sstr << "output/" << prefix << "_col_" << k << ".bmp"; std::string filename (sstr.str()); std::cout << "writing color texture for kinect " << k << " to file " << filename << std::endl; writeBMP(filename, colors, offset, 3); offset += 3 * width*height; } } } // no universal use! very unflexible, resolution depth = resolution color, no row padding void NetKinectArray::writeBMP(std::string filename, std::vector<std::uint8_t> const& data, unsigned int offset, unsigned int bytesPerPixel) { std::ofstream file (filename, std::ofstream::binary); char c; short s; int i; c = 'B'; file.write(&c, 1); c = 'M'; file.write(&c, 1); i = m_resolution_color.x * m_resolution_color.y * 3 + 54; file.write((char const*) &i, 4); i = 0; file.write((char const*) &i,4); i = 54; file.write((char const*) &i, 4); i = 40; file.write((char const*) &i, 4); i = m_resolution_color.x; file.write((char const*) &i, 4); i = m_resolution_color.y; file.write((char const*) &i, 4); s = 1; file.write((char const*) &s, 2); s = 24; file.write((char const*) &s, 2); i = 0; file.write((char const*) &i, 4); i = m_resolution_color.x * m_resolution_color.y * 3; file.write((char const*) &i, 4); i = 0; file.write((char const*) &i, 4); i = 0; file.write((char const*) &i, 4); i = 0; file.write((char const*) &i, 4); i = 0; file.write((char const*) &i, 4); for (unsigned int h = m_resolution_color.y; h > 0; --h) { for (unsigned int w = 0; w < m_resolution_color.x * bytesPerPixel; w += bytesPerPixel) { if (bytesPerPixel == 1) { file.write((char const*) &data[offset + w + (h-1) * m_resolution_color.x * bytesPerPixel], 1); file.write((char const*) &data[offset + w + (h-1) * m_resolution_color.x * bytesPerPixel], 1); file.write((char const*) &data[offset + w + (h-1) * m_resolution_color.x * bytesPerPixel], 1); } else if (bytesPerPixel == 3 || bytesPerPixel == 4) { file.write((char const*) &data[offset + w+2 + (h-1) * m_resolution_color.x * bytesPerPixel], 1); file.write((char const*) &data[offset + w+1 + (h-1) * m_resolution_color.x * bytesPerPixel], 1); file.write((char const*) &data[offset + w+0 + (h-1) * m_resolution_color.x * bytesPerPixel], 1); } } } file.close(); } void NetKinectArray::readFromFiles(){ std::vector<sys::FileBuffer*> fbs; for(unsigned i = 0 ; i < m_calib_files->num(); ++i){ std::string yml(m_calib_files->getCalibs()[i]._filePath); std::string base((const char*) basename((char *) yml.c_str())); base.replace( base.end() - 4, base.end(), ""); std::string filename = std::string("recordings/" + base + ".stream"); fbs.push_back(new sys::FileBuffer(filename.c_str())); if(!fbs.back()->open("r")){ std::cerr << "error opening " << filename << " exiting..." << std::endl; exit(1); } fbs.back()->setLooping(/*true*/false); } const unsigned colorsize = m_colorsize; const unsigned depthsize = m_depthsize; { // lock pbos std::unique_lock<std::mutex> lock(m_mutex_pbo); unsigned offset = 0; // receive data for(unsigned i = 0; i < m_calib_files->num(); ++i){ //memcpy((byte*) m_pbo_colors.pointer() + i*colorsize , (byte*) zmqm.data() + offset, colorsize); fbs[i]->read((byte*) m_pbo_colors.pointer() + i*colorsize, colorsize); offset += colorsize; //memcpy((byte*) m_pbo_depths.pointer() + i*depthsize , (byte*) zmqm.data() + offset, depthsize); fbs[i]->read((byte*) m_pbo_depths.pointer() + i*depthsize, depthsize); offset += depthsize; } m_pbo_colors.dirty = true; m_pbo_depths.dirty = true; } } void NetKinectArray::updateInputSocket(unsigned stream_slot){ if(stream_slot != m_streamslot){ m_streamslot = stream_slot; } } }
38.837209
225
0.699235
steppobeck
125dfa4fbc0f4c504f0bcc1b2116a3f49b7abe53
12,181
hpp
C++
memory/shared-pointer.hpp
daleksla/STL
c9b107cb7434e123dc25f3e0d9e8423f6be0030a
[ "BSL-1.0" ]
1
2021-03-01T05:03:52.000Z
2021-03-01T05:03:52.000Z
memory/shared-pointer.hpp
daleksla/STL
c9b107cb7434e123dc25f3e0d9e8423f6be0030a
[ "BSL-1.0" ]
3
2021-03-01T04:21:26.000Z
2021-06-28T18:30:52.000Z
memory/shared-pointer.hpp
daleksla/STL
c9b107cb7434e123dc25f3e0d9e8423f6be0030a
[ "BSL-1.0" ]
null
null
null
#ifndef SHARED_POINTER_HPP #define SHARED_POINTER_HPP #include "base-pointer.hpp" /** @brief Shared pointer class, which persists a dynamic resource until the last Shared pointer object is destroyed or reset @author Salih Mahmoud Sayed Ahmed @email ahmed233@uni.coventry.ac.uk @date May 2021 **/ namespace salih { namespace memory { template<class T> class SharedPointer : public Pointer<T> { /** This class is the derived-class shared smart pointer implementation, which allows for the sharing and existence of a piece of memory till no shared pointer at all is making use of the pointed-to resource **/ private: unsigned long* count ; public: /** Empty constructor, intialises shared smart pointer container @return <initialised-object> **/ SharedPointer() ; /** Regular constructor, intialises shared smart pointer container @param nullptr_t (special type indicating NULL) @return <initialised-object> **/ SharedPointer(const decltype(nullptr)) ; /** Regular constructor, intialises shared smart pointer container to point at T-type pointer @param T* (raw pointer to object of type T) @return <initialised-object> **/ SharedPointer(T*) ; /** Regular constructor, intialises shared smart pointer container to void pointer @param void* (raw void pointer) @return <initialised-object> **/ explicit SharedPointer(void*) ; /** Regular assignment operator, assigns null pointer to shared smart pointer @param nullptr_t (special type indicating NULL) @return reference to modified smart pointer **/ SharedPointer& operator=(const decltype(nullptr)) ; /** Regular assignment operator, assigns null pointer to shared smart pointer @param T* (raw pointer to object of type T) @return reference to modified smart pointer **/ SharedPointer& operator=(T*) ; /** Copy constructor, creates copy of a given shared smart pointer @param a (l-value) base class reference @return <initialised-object> **/ SharedPointer(const SharedPointer&) ; /** Pseudo-copy constructor, creates copy of a given specialised void smart pointer @param a (l-value) base class reference @return <initialised-object> **/ explicit SharedPointer(const SharedPointer<void>&) ; /** Copy assignment operator, creates copy of a given shared smart pointer @param a (l-value) base class reference @return reference to modified smart pointer **/ SharedPointer& operator=(const SharedPointer&) ; /** Move constructor, takes ownership of a given shared smart pointer @param an r-value object reference @return <initialised-object> **/ SharedPointer(SharedPointer&&) ; /** Pseudo-move constructor, takes ownership of a given specialised void shared smart pointer @param an r-value object reference @return <initialised-object> **/ explicit SharedPointer(SharedPointer<void>&&) ; /** Move assignment operator, takes ownership of a given shared smart pointer @param an r-value object reference @return reference to modified smart pointer **/ SharedPointer& operator=(SharedPointer&&) ; /** reset method, to appropriately disengage from pointing at data **/ void reset() ; /** Destructor, frees memory if appropriate and deletes objects **/ ~SharedPointer() ; friend class SharedPointer<void> ; } ; template<class T> class SharedPointer<T[]> : public Pointer<T[]> { /** This class is the derived-class shared smart pointer implementation, specialised for dynamically allocated arrays, which allows for the sharing and existence of a piece of memory till no shared pointer at all is making use of the pointed-to resource **/ private: unsigned long* count ; public: /** Empty constructor, intialises shared smart pointer container @return <initialised-object> **/ SharedPointer() ; /** Regular constructor, intialises shared smart pointer container @param nullptr_t (special type indicating NULL) @return <initialised-object> **/ SharedPointer(const decltype(nullptr)) ; /** Regular constructor, intialises shared smart pointer container to point at T-type pointer @param T* (raw pointer to object of type T) @return <initialised-object> **/ SharedPointer(T*) ; /** Regular constructor, intialises shared smart pointer container to void pointer @param void* (raw void pointer) @return <initialised-object> **/ explicit SharedPointer(void*) ; /** Regular assignment operator, assigns null pointer to shared smart pointer @param nullptr_t (special type indicating NULL) @return reference to modified smart pointer **/ SharedPointer& operator=(const decltype(nullptr)) ; /** Regular assignment operator, assigns null pointer to shared smart pointer @param T* (raw pointer to object of type T) @return reference to modified smart pointer **/ SharedPointer& operator=(T*) ; /** Copy constructor, creates copy of a given shared smart pointer @param a (l-value) base class reference @return <initialised-object> **/ SharedPointer(const SharedPointer&) ; /** Pseudo-copy constructor, creates copy of a given specialised void smart pointer @param a (l-value) base class reference @return <initialised-object> **/ explicit SharedPointer(const SharedPointer<void>&) ; /** Copy assignment operator, creates copy of a given shared smart pointer @param a (l-value) base class reference @return reference to modified smart pointer **/ SharedPointer& operator=(const SharedPointer&) ; /** Move constructor, takes ownership of a given shared smart pointer @param an r-value object reference @return <initialised-object> **/ SharedPointer(SharedPointer&&) ; /** Pseudo-move constructor, takes ownership of a given specialised void shared smart pointer @param an r-value object reference @return <initialised-object> **/ explicit SharedPointer(SharedPointer<void>&&) ; /** Move assignment operator, takes ownership of a given shared smart pointer @param an r-value object reference @return reference to modified smart pointer **/ SharedPointer& operator=(SharedPointer&&) ; /** reset method, to appropriately disengage from pointing at data **/ void reset() ; /** Destructor, frees memory if appropriate and deletes objects **/ ~SharedPointer() ; friend class SharedPointer<void> ; } ; template<> class SharedPointer<void> : public Pointer<void> { /** This class is the derived-class shared smart pointer implementation, specialised for void pointer usage, which allows for the sharing and existence of a piece of memory till no shared pointer at all is making use of the pointed-to resource **/ private: unsigned long* count ; public: /** Empty constructor, intialises shared smart pointer container @return <initialised-object> **/ SharedPointer() ; /** Regular constructor, intialises shared smart pointer container @param nullptr_t (special type indicating NULL) @return <initialised-object> **/ SharedPointer(const decltype(nullptr)) ; /** Regular constructor, intialises shared smart pointer container to point at T-type pointer @param T* (raw pointer to object of type T) @return <initialised-object> **/ template<typename T> SharedPointer(T*) ; SharedPointer(void*) = delete ; /** Regular assignment operator, assigns null pointer to shared smart pointer @param nullptr_t (special type indicating NULL) @return reference to modified smart pointer **/ SharedPointer& operator=(const decltype(nullptr)) ; /** Regular assignment operator, intialises shared smart pointer container to point at T-type pointer @param T* (raw pointer to object of type T) @return reference to modified smart pointer **/ template<typename T> SharedPointer& operator=(T*) ; SharedPointer& operator=(void*) = delete ; /** Copy constructor, creates copy of a given shared smart pointer @param a (l-value) object reference @return <initialised-object> **/ SharedPointer(const SharedPointer&) ; /** Pseudo-copy constructor, creates copy of a templated shared smart pointer @param a (l-value) templated-object reference @return <initialised-object> **/ template<typename T> SharedPointer(const SharedPointer<T>&) ; /** Pseudo-copy constructor, creates copy of a templated shared smart pointer @param a (l-value) templated-object reference @return <initialised-object> **/ template<typename T> SharedPointer(const SharedPointer<T[]>&) ; /** Copy constructor, creates copy (of base-properties) of a given shared smart pointer @param a (l-value) object reference @return reference to modified smart pointer **/ SharedPointer& operator=(const SharedPointer&) ; /** Pseudo-copy constructor, creates copy of a given templated shared smart pointer @param a (l-value) templated object reference @return reference to modified smart pointer **/ template<typename T> SharedPointer& operator=(const SharedPointer<T>&) ; /** Pseudo-copy constructor, creates copy of a given templated shared smart pointer @param a (l-value) templated object reference @return reference to modified smart pointer **/ template<typename T> SharedPointer& operator=(const SharedPointer<T[]>&) ; /** Pseudo-move constructor, takes ownership of a given templated shared smart pointer @param an r-value templated base class reference @return <initialised-object> **/ SharedPointer(SharedPointer&&) ; /** Pseudo-move constructor, takes ownership of a given templated shared smart pointer @param an r-value templated-object reference @return <initialised-object> **/ template<typename T> SharedPointer(SharedPointer<T>&&) ; /** Pseudo-move constructor, takes ownership of a given templated shared smart pointer @param an r-value templated-object reference @return <initialised-object> **/ template<typename T> SharedPointer(SharedPointer<T[]>&&) ; /** Move assignment operator, takes ownership of a given shared smart pointer @param an r-value object reference @return reference to modified smart pointer **/ SharedPointer& operator=(SharedPointer&&) ; /** Pseudo-move assignment operator, takes ownership of a given templated shared smart pointer @param an r-value templated-object reference @return <initialised-object> **/ template<typename T> SharedPointer& operator=(SharedPointer<T>&&) ; /** Pseudo-move assignment operator, takes ownership of a given templated shared smart pointer @param an r-value templated-object reference @return <initialised-object> **/ template<typename T> SharedPointer& operator=(SharedPointer<T[]>&&) ; /** reset method, to appropriately disengage from pointing at data **/ void reset() ; /** Destructor, frees memory if appropriate and deletes objects **/ ~SharedPointer() ; template<typename T> friend class SharedPointer ; } ; /** This is the makeShared function, which creates a SharedPointer object of type T on the heap (using said object's empty / default initialisation) * @return SharedPointer of type T **/ template<class T> SharedPointer<T> makeShared() ; /** This is the makeShared function, which creates a SharedPointer object of type T on the heap, initialising the object using constructor determined by the parameters given * @param Variadic template (arguments to pass in order to initialise object of type T) * @return SharedPointer of type T **/ template<class T, class... Args> SharedPointer<T> makeShared(Args&&...) ; /** This is the makeShared function, which creates a SharedPointer object of an array of T's (T[]) on the heap, * @param number of T's to allocate in contiguous block * @return SharedPointer of type T[] **/ template<class T> SharedPointer<T[]> makeShared(const unsigned long) ; } } #include "shared-pointer.tpp" #endif
40.069079
259
0.714638
daleksla
126d72b5adedb55434b1eef86f6e9fe3817b4338
2,148
cpp
C++
oneEngine/oneGame/source/core/math/noise/WorleyCellNoise.cpp
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
8
2017-12-08T02:59:31.000Z
2022-02-02T04:30:03.000Z
oneEngine/oneGame/source/core/math/noise/WorleyCellNoise.cpp
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
2
2021-04-16T03:44:42.000Z
2021-08-30T06:48:44.000Z
oneEngine/oneGame/source/core/math/noise/WorleyCellNoise.cpp
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
1
2021-04-16T02:09:54.000Z
2021-04-16T02:09:54.000Z
#include "WorleyCellNoise.h" #include "core/math/Math.h" #include <algorithm> #include <random> static Vector3f RandomCellPoint( int32 celX, int32 celY, int32 celZ, float offsets [1024] ) { return Vector3f( celX + offsets[(celX + celY^celZ) & (1024 - 1)], celY + offsets[(celY * 912 + celX^celZ) & (1024 - 1)], celZ + offsets[(celZ * 1024 * 871 + celX^celY) & (1024 - 1)] ); } // Noise ( vec3, randombuf ) : Performs 3x3 sample for worley static float WorleyCell(float vec[3], float offsets [1024]) { // Select proper unit cube with the point const int32 X = ((int32)std::floor(vec[0])) & 0xFF; const int32 Y = ((int32)std::floor(vec[1])) & 0xFF; const int32 Z = ((int32)std::floor(vec[2])) & 0xFF; float distance = 1.0e10F; // Sample the 3x3 cells to get the minimum distance to a cell for (int32 xo = -1; xo <= 1; xo++) { for (int32 yo = -1; yo <= 1; yo++) { for (int32 zo = -1; zo <= 1; zo++) { const int32 Xi = X + xo; const int32 Yi = Y + yo; const int32 Zi = Z + zo; const Vector3f celPosition = RandomCellPoint(Xi, Yi, Zi, offsets); distance = std::min<float>(distance, (celPosition - Vector3f(vec[0], vec[1], vec[2])).magnitude()); } } } distance = math::saturate(distance); return distance; } float WorleyCellNoise::Get (const float position) { float vec[3] = {position * m_cellcount, 0.0F, 0.0F}; float result = WorleyCell(vec, m_offset); return (result - 0.5F) * 2.0F * m_amp; } float WorleyCellNoise::Get (const Vector2f& position) { float vec[3] = {position.x * m_cellcount, position.y * m_cellcount, 0.0F}; float result = WorleyCell(vec, m_offset); return (result - 0.5F) * 2.0F * m_amp; } float WorleyCellNoise::Get (const Vector3f& position) { float vec[3] = {position.x * m_cellcount, position.y * m_cellcount, position.z * m_cellcount}; float result = WorleyCell(vec, m_offset); return (result - 0.5F) * 2.0F * m_amp; } void WorleyCellNoise::init ( void ) { std::mt19937 random_engine (m_seed); std::uniform_real_distribution distro (0.0F, +1.0F); for (int i = 0; i < 1024; ++i) { m_offset[i] = distro(random_engine); } }
26.85
103
0.641061
skarik
127bf5ca58020439263bc71b18088083af902bec
4,806
hpp
C++
include/sharpen/IoEvent.hpp
Kylepoops/Sharpen
5ef19d89ddab0b63ffc4d2489a1cd50e2d5bb132
[ "MIT" ]
13
2020-10-25T04:02:07.000Z
2022-03-29T13:21:30.000Z
include/sharpen/IoEvent.hpp
Kylepoops/Sharpen
5ef19d89ddab0b63ffc4d2489a1cd50e2d5bb132
[ "MIT" ]
18
2020-10-09T04:51:03.000Z
2022-03-01T06:24:23.000Z
include/sharpen/IoEvent.hpp
Kylepoops/Sharpen
5ef19d89ddab0b63ffc4d2489a1cd50e2d5bb132
[ "MIT" ]
7
2020-10-23T04:25:28.000Z
2022-03-23T06:52:39.000Z
#pragma once #ifndef _SHARPEN_IOEVENT_HPP #define _SHARPEN_IOEVENT_HPP #include "TypeDef.hpp" #include "Noncopyable.hpp" #include "Nonmovable.hpp" #include "SystemError.hpp" #include "IChannel.hpp" namespace sharpen { class IoEvent { public: //event type struct EventTypeEnum { enum { //empty event None = 0, //read event Read = 1, //write event Write = 2, //close by peer Close = 4, //error Error = 8, //iocp only //io completed Completed = 16, //io request Request = 32, //accept handle Accept = 64, //connect Connect = 128, //send file Sendfile = 256, //poll Poll = 512 }; }; using EventType = sharpen::Uint32; private: using Self = sharpen::IoEvent; using WeakChannel = std::weak_ptr<sharpen::IChannel>; EventType type_; WeakChannel channel_; void *data_; sharpen::ErrorCode errorCode_; public: IoEvent() :type_(EventTypeEnum::None) ,channel_() ,data_(nullptr) ,errorCode_(0) {} IoEvent(EventType type,sharpen::ChannelPtr channel,void *data,sharpen::ErrorCode error) :type_(type) ,channel_(channel) ,data_(data) ,errorCode_(error) {} IoEvent(const Self &other) :type_(other.type_) ,channel_(other.channel_) ,data_(other.data_) ,errorCode_(other.errorCode_) {} IoEvent(Self &&other) noexcept :type_(other.type_) ,channel_(other.channel_) ,data_(other.data_) ,errorCode_(other.errorCode_) { other.type_ = EventTypeEnum::None; other.channel_.reset(); other.data_ = nullptr; other.errorCode_ = 0; } Self &operator=(const Self &other) { this->type_ = other.type_; this->channel_ = other.channel_; this->data_ = other.data_; this->errorCode_ = other.errorCode_; return *this; } Self &operator=(Self &&other) noexcept { this->type_ = other.type_; this->channel_ = other.channel_; this->data_ = other.data_; this->errorCode_ = other.errorCode_; other.type_ = EventTypeEnum::None; other.channel_.reset(); other.data_ = nullptr; other.errorCode_ = 0; return *this; } ~IoEvent() noexcept = default; bool IsReadEvent() const noexcept { return this->type_ & EventTypeEnum::Read; } bool IsWriteEvent() const noexcept { return this->type_ & EventTypeEnum::Write; } bool IsCloseEvent() const noexcept { return this->type_ & EventTypeEnum::Close; } bool IsErrorEvent() const noexcept { return this->type_ & EventTypeEnum::Error; } bool IsCompletedEvent() const noexcept { return this->type_ & EventTypeEnum::Completed; } bool IsRequestEvent() const noexcept { return this->type_ & EventTypeEnum::Request; } sharpen::ChannelPtr GetChannel() const noexcept { return this->channel_.lock(); } void *GetData() const noexcept { return this->data_; } void SetData(void *data) { this->data_ = data; } sharpen::ErrorCode GetErrorCode() const noexcept { return this->errorCode_; } void SetErrorCode(sharpen::ErrorCode error) { this->errorCode_ = error; } void SetChannel(const sharpen::ChannelPtr &channel) { this->channel_ = channel; } void SetEvent(EventType ev) { this->type_ = ev; } EventType GetEventType() const noexcept { return this->type_; } void AddEvent(EventType ev) { this->type_ |= ev; } void RemoveEvent(EventType ev) { this->type_ ^= ev; } }; } #endif
24.150754
95
0.468997
Kylepoops
1283e20a085c260f030a1be7cfdcfc3d69945ee3
1,996
cpp
C++
TextOverviewTextEdit.cpp
B1anky/CppEditor
bb68ca521c35a8d7e658f9ddf789201d7b269a08
[ "MIT" ]
1
2020-09-11T12:42:15.000Z
2020-09-11T12:42:15.000Z
TextOverviewTextEdit.cpp
B1anky/CppEditor
bb68ca521c35a8d7e658f9ddf789201d7b269a08
[ "MIT" ]
null
null
null
TextOverviewTextEdit.cpp
B1anky/CppEditor
bb68ca521c35a8d7e658f9ddf789201d7b269a08
[ "MIT" ]
null
null
null
#include "TextOverviewTextEdit.h" #include <QVBoxLayout> #include "TextEditor.h" TextOverviewTextEdit::TextOverviewTextEdit(QWidget* parent) : QPlainTextEdit(parent){ setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //setReadOnly(true); setFrameStyle(QFrame::NoFrame); setLineWrapMode(QPlainTextEdit::NoWrap); if(qobject_cast<TextEditor*>(parentWidget())){ setFocusProxy(parentWidget()); } } //This widget will not scroll on its own, its companion text editor will do that void TextOverviewTextEdit::wheelEvent(QWheelEvent* event){ if(qobject_cast<TextEditor*>(parentWidget())){ qobject_cast<TextEditor*>(parentWidget())->wheelEvent(event); }else{ event->accept(); } } void TextOverviewTextEdit::keyPressEvent(QKeyEvent* event){ setReadOnly(false); QPlainTextEdit::keyPressEvent(event); setReadOnly(true); } void TextOverviewTextEdit::keyReleaseEvent(QKeyEvent* event){ /* if(qobject_cast<TextEditor*>(parentWidget())){ qobject_cast<TextEditor*>(parentWidget())->keyReleaseEvent(event); }else{ event->accept(); } */ setReadOnly(false); QPlainTextEdit::keyPressEvent(event); setReadOnly(true); } void TextOverviewTextEdit::mousePressEvent(QMouseEvent* event){ if(qobject_cast<TextEditor*>(parentWidget())){ qobject_cast<TextEditor*>(parentWidget())->mousePressEvent(event); }else{ event->accept(); } } void TextOverviewTextEdit::mouseReleaseEvent(QMouseEvent* event){ if(qobject_cast<TextEditor*>(parentWidget())){ qobject_cast<TextEditor*>(parentWidget())->mouseReleaseEvent(event); }else{ event->accept(); } } void TextOverviewTextEdit::mouseMoveEvent(QMouseEvent* event){ if(qobject_cast<TextEditor*>(parentWidget())){ qobject_cast<TextEditor*>(parentWidget())->mouseMoveEvent(event); }else{ event->accept(); } }
26.263158
85
0.700401
B1anky
12846557f534c7c4c4b801379967939dcbf2bbc2
140
cpp
C++
cf/contest/741/d/temp.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
cf/contest/741/d/temp.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
cf/contest/741/d/temp.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
#include <cstdio> int main() { int n = 500000; printf( "%d\n", n ); for( int i = 1; i < n; i ++ ) { printf( "%d %c\n", i, 'a' ); } }
14
32
0.435714
woshiluo
129327ac92ab53807fd23e9ec0dfb564ab1f1f43
64
cpp
C++
src/gitcpp/implementation/config/ConfigLevel.cpp
ekuch/gitcpp
8f29d4fd3f63a6a52885505983c756e5b5ee27dc
[ "MIT" ]
1
2017-02-07T14:20:59.000Z
2017-02-07T14:20:59.000Z
src/gitcpp/implementation/config/ConfigLevel.cpp
ekuch/gitcpp
8f29d4fd3f63a6a52885505983c756e5b5ee27dc
[ "MIT" ]
null
null
null
src/gitcpp/implementation/config/ConfigLevel.cpp
ekuch/gitcpp
8f29d4fd3f63a6a52885505983c756e5b5ee27dc
[ "MIT" ]
null
null
null
// // Created by ekuch on 10/5/15. // #include "ConfigLevel.h"
10.666667
31
0.625
ekuch
12a15ab2534c96d692424ec4d7ef0e76165f9c6e
651
cpp
C++
Problems/0123. Best Time to Buy and Sell Stock III.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0123. Best Time to Buy and Sell Stock III.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0123. Best Time to Buy and Sell Stock III.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
class Solution { public: int maxProfit(vector<int>& prices) { int buy1{INT_MIN},sell1{0},buy2{INT_MIN},sell2{0}; for(auto p: prices){ buy1 = max(buy1, -p); sell1 = max(sell1, buy1 + p); buy2 = max(buy2, sell1 - p); sell2 = max(sell2, buy2 + p); } return sell2; } }; /* Note that buying stock means we are spending money equivalent to the price of the stock, * thus subtract the price. On selling the stock we add the price because the associated * price is getting added to our profit. * Final Profit = (Initial Profit — Buying Price) + Selling Price */
32.55
92
0.602151
KrKush23
12a9eb8a4a390166a79cd5287179c03fe7b75d60
14,479
cpp
C++
src/Core/Input/InputManager.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
442
2017-03-03T11:42:11.000Z
2021-05-20T13:40:02.000Z
src/Core/Input/InputManager.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
308
2017-02-21T10:39:31.000Z
2021-05-14T21:30:56.000Z
src/Core/Input/InputManager.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
45
2017-03-11T15:24:28.000Z
2021-05-09T15:21:42.000Z
#include <set> #include <Input/Exceptions.hpp> #include <Input/InputManager.hpp> #include <Utils/VectorUtils.hpp> namespace obe::Input { bool updateOrCleanMonitor( Event::EventGroupPtr events, const std::weak_ptr<InputButtonMonitor>& element) { if (auto monitor = element.lock()) { monitor->update(events); return false; } else { return true; } } bool InputManager::isActionCurrentlyInUse(const std::string& actionId) { for (const auto& action : m_currentActions) { if (action->getId() == actionId) { return true; } } return false; } InputManager::InputManager(Event::EventNamespace& eventNamespace) : e_actions(eventNamespace.createGroup("Actions")) , e_inputs(eventNamespace.createGroup("Keys")) , Togglable(true) { this->createInputMap(); this->createEvents(); } InputAction& InputManager::getAction(const std::string& actionId) { for (auto& action : m_allActions) { if (action->getId() == actionId) { return *action.get(); } } std::vector<std::string> actionIds; actionIds.reserve(m_allActions.size()); for (auto& action : m_allActions) { actionIds.push_back(action->getId()); } throw Exceptions::UnknownInputAction(actionId, actionIds, EXC_INFO); } void InputManager::update() { if (m_enabled) { auto actionBuffer = m_currentActions; for (auto action : actionBuffer) { action->update(); } if (m_refresh) { bool shouldRefresh = false; for (auto& [_, input] : m_inputs) { if (input->isPressed()) { shouldRefresh = true; break; } } m_monitors.erase(std::remove_if(m_monitors.begin(), m_monitors.end(), [this](const std::weak_ptr<InputButtonMonitor>& element) { return updateOrCleanMonitor(e_inputs, element); }), m_monitors.end()); for (const auto& monitorPtr : m_monitors) { if (const auto& monitor = monitorPtr.lock()) { if (monitor->checkForRefresh()) { shouldRefresh = true; break; } } } m_refresh = shouldRefresh; } } } bool InputManager::actionExists(const std::string& actionId) { for (auto& action : m_allActions) { if (action->getId() == actionId) { return true; } } return false; } void InputManager::clear() { m_currentActions.clear(); for (auto& action : m_allActions) e_actions->remove(action->getId()); m_allActions.clear(); } void InputManager::configure(vili::node& config) { std::vector<std::string> alreadyInFile; for (auto& [contextName, context] : config.items()) { for (auto& [actionName, condition] : context.items()) { if (!this->actionExists(actionName)) { m_allActions.push_back( std::make_unique<InputAction>(e_actions.get(), actionName)); } else if (!Utils::Vector::contains(actionName, alreadyInFile)) { this->getAction(actionName).clearConditions(); } auto inputCondition = [this](InputManager* inputManager, const std::string& action, vili::node& condition) { InputCondition actionCondition; InputCombination combination; try { combination = this->makeCombination(condition); } catch (const BaseException& e) { throw Exceptions::InvalidInputCombinationCode(action, condition, EXC_INFO) .nest(e); } actionCondition.setCombination(combination); Debug::Log->debug( "<InputManager> Associated Key '{0}' for Action '{1}'", condition, action); inputManager->getAction(action).addCondition(actionCondition); }; if (condition.is_primitive()) { inputCondition(this, actionName, condition); } else if (condition.is<vili::array>()) { for (vili::node& singleCondition : condition) { inputCondition(this, actionName, singleCondition); } } this->getAction(actionName).addContext(contextName); alreadyInFile.push_back(actionName); } } // Add Context keys in real time <REVISION> } void InputManager::clearContexts() { for (InputAction* action : m_currentActions) { action->disable(); } m_currentActions.clear(); // m_monitors.clear(); } InputManager& InputManager::addContext(const std::string& context) { Debug::Log->debug("<InputManager> Adding Context '{0}'", context); for (auto& action : m_allActions) { if (Utils::Vector::contains(context, action->getContexts()) && !isActionCurrentlyInUse(action->getId())) { Debug::Log->debug( "<InputManager> Add Action '{0}' in Context '{1}'", action->getId(), context); m_currentActions.push_back(action.get()); std::vector<InputButtonMonitorPtr> monitors; for (InputButton* button : action->getInvolvedButtons()) { monitors.push_back(this->monitor(*button)); } action->enable(monitors); } } return *this; } InputManager& InputManager::removeContext(const std::string& context) { //<REVISION> Multiple context, keep which one, remove keys of wrong // context m_currentActions.erase(std::remove_if(m_currentActions.begin(), m_currentActions.end(), [&context](auto& action) -> bool { const auto& contexts = action->getContexts(); auto isActionInContext = std::find(contexts.begin(), contexts.end(), context) != contexts.end(); if (isActionInContext) { Debug::Log->debug("<InputManager> Remove Action '{0}' " "from Context '{1}'", action->getId(), context); action->disable(); return true; } else { return false; } }), m_currentActions.end()); return *this; } void InputManager::setContext(const std::string& context) { this->clearContexts(); this->addContext(context); } std::vector<std::string> InputManager::getContexts() { std::set<std::string> allContexts; for (const auto& action : m_currentActions) { for (const auto& context : action->getContexts()) { allContexts.emplace(context); } } return std::vector<std::string>(allContexts.begin(), allContexts.end()); } InputButton& InputManager::getInput(const std::string& keyId) { if (m_inputs.find(keyId) != m_inputs.end()) return *m_inputs[keyId].get(); throw Exceptions::UnknownInputButton(keyId, this->getAllInputButtonNames(), EXC_INFO); } std::vector<InputButton*> InputManager::getInputs() { std::vector<InputButton*> inputs; inputs.reserve(m_inputs.size()); for (auto& [_, input] : m_inputs) { inputs.push_back(input.get()); } return inputs; } std::vector<InputButton*> InputManager::getInputs(InputType filter) { std::vector<InputButton*> inputs; for (auto& keyIterator : m_inputs) { if (keyIterator.second->is(filter)) { inputs.push_back(keyIterator.second.get()); } } return inputs; } std::vector<InputButton*> InputManager::getPressedInputs() { std::vector<InputButton*> allPressedButtons; for (auto& keyIterator : m_inputs) { if (keyIterator.second->isPressed()) { allPressedButtons.push_back(keyIterator.second.get()); } } return allPressedButtons; } InputButtonMonitorPtr InputManager::monitor(const std::string& name) { return this->monitor(this->getInput(name)); } InputButtonMonitorPtr InputManager::monitor(InputButton& input) { for (auto& monitor : m_monitors) { if (const auto sharedMonitor = monitor.lock()) { if (&sharedMonitor->getButton() == &input) return InputButtonMonitorPtr(sharedMonitor); } } InputButtonMonitorPtr monitor = std::make_shared<InputButtonMonitor>(input); m_monitors.push_back(monitor); return std::move(monitor); } void InputManager::requireRefresh() { m_refresh = true; } bool isKeyAlreadyInCombination(InputCombination& combination, InputButton* button) { for (auto& [monitoredButton, _] : combination) { if (monitoredButton == button) { return true; } } return false; } InputCombination InputManager::makeCombination(const std::string& code) { InputCombination combination; std::vector<std::string> elements = Utils::String::split(code, "+"); if (code != "NotAssociated") { for (std::string element : elements) { Utils::String::replaceInPlace(element, " ", ""); std::vector<std::string> stateAndButton = Utils::String::split(element, ":"); if (stateAndButton.size() == 1 || stateAndButton.size() == 2) { if (stateAndButton.size() == 1) { stateAndButton.push_back(stateAndButton[0]); stateAndButton[0] = "Pressed"; } std::vector<std::string> stateList = Utils::String::split(stateAndButton[0], ","); Types::FlagSet<InputButtonState> buttonStates; for (std::string& buttonState : stateList) { if (Utils::Vector::contains( buttonState, { "Idle", "Hold", "Pressed", "Released" })) { buttonStates |= stringToInputButtonState(buttonState); } else { throw Exceptions::InvalidInputButtonState(buttonState, EXC_INFO); } } const std::string keyId = stateAndButton[1]; // Detect gamepad button / axis and initialize whole gamepad if (keyId.substr(0, 3) == "GP_") { auto gamepadParts = Utils::String::split(keyId, "_"); unsigned int gamepadIndex; try { gamepadIndex = std::stoi(gamepadParts[1]); } catch (const std::invalid_argument& exc) { throw Exceptions::InvalidGamepadButton(keyId, EXC_INFO); } catch (const std::out_of_range& exc) { throw Exceptions::InvalidGamepadButton(keyId, EXC_INFO); } this->initializeGamepad(gamepadIndex); } if (m_inputs.find(keyId) != m_inputs.end()) { InputButton& button = this->getInput(keyId); if (!isKeyAlreadyInCombination(combination, &button)) { combination.emplace_back(&button, buttonStates); } else { throw Exceptions::InputButtonAlreadyInCombination( button.getName(), EXC_INFO); } } else { throw Exceptions::UnknownInputButton( keyId, this->getAllInputButtonNames(), EXC_INFO); } } } } return combination; } } // namespace obe::Input
34.638756
99
0.457421
lukefelsberg
12aa7fa7dcac95d6dcc6274d18bd45dcc4753ecd
3,342
cxx
C++
vital/types/camera_rpc.cxx
judajake/kwiver
303a11ebb43c020ab8e48b6ef70407b460dba46b
[ "BSD-3-Clause" ]
null
null
null
vital/types/camera_rpc.cxx
judajake/kwiver
303a11ebb43c020ab8e48b6ef70407b460dba46b
[ "BSD-3-Clause" ]
null
null
null
vital/types/camera_rpc.cxx
judajake/kwiver
303a11ebb43c020ab8e48b6ef70407b460dba46b
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2013-2018 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file * \brief Implementation of \link kwiver::vital::camera_rpc * camera_rpc \endlink class */ #include <vital/types/camera_rpc.h> #include <vital/io/eigen_io.h> #include <vital/types/matrix.h> #include <Eigen/Geometry> #include <iomanip> namespace kwiver { namespace vital { camera_rpc ::camera_rpc() : m_logger( kwiver::vital::get_logger( "vital.camera_rpc" ) ) { } /// Project a 3D point into a 2D image point vector_2d camera_rpc ::project( const vector_3d& pt ) const { // Normalize points vector_3d norm_pt = ( pt - world_offset() ).cwiseQuotient( world_scale() ); // Calculate polynomials // TODO: why doesn't this work ? // auto polys = this->rpc_coeffs()*this->power_vector(norm_pt); auto rpc = this->rpc_coeffs(); auto pv = this->power_vector(norm_pt); auto polys = rpc*pv; vector_2d image_pt( polys[0] / polys[1], polys[2] / polys[3]); // Un-normalize return image_pt.cwiseProduct( image_scale() ) + image_offset(); } Eigen::Matrix<double, 20, 1> simple_camera_rpc ::power_vector( const vector_3d& pt ) const { // Form the monomials in homogeneous form double w = 1.0; double x = pt.x(); double y = pt.y(); double z = pt.z(); double xx = x * x; double xy = x * y; double xz = x * z; double yy = y * y; double yz = y * z; double zz = z * z; double xxx = xx * x; double xxy = xx * y; double xxz = xx * z; double xyy = xy * y; double xyz = xy * z; double xzz = xz * z; double yyy = yy * y; double yyz = yy * z; double yzz = yz * z; double zzz = zz * z; // Fill in vector Eigen::Matrix<double, 20, 1> retVec; retVec << w, x, y, z, xy, xz, yz, xx, yy, zz, xyz, xxx, xyy, xzz, xxy, yyy, yzz, xxz, yyz, zzz; return retVec; } } } // end namespace
29.839286
81
0.691203
judajake