blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
140f4cd1b379105cb2a11478ec76bbbc40b9c75f
e156eecc9bddfd5812336956acb415123f5e9dc0
/nn/include/output_layer.h
8869729cad582b8965cdb84cb034539d86ad5928
[ "MIT" ]
permissive
echentw/neural-network
3152d382d16312b6fd57ea262644ba7166a651ae
63bb2adbd31a6b37e94dfd868a402d47e168d862
refs/heads/master
2021-01-18T21:12:25.783507
2016-05-17T03:17:32
2016-05-17T03:17:32
38,932,531
0
0
null
null
null
null
UTF-8
C++
false
false
799
h
#ifndef __OUTPUT_LAYER__H #define __OUTPUT_LAYER__H #include "layer.h" #include "output_node.h" #include "boost/multi_array.hpp" class OutputLayer : public Layer { private: std::vector<OutputNode> node_list; // gradients[i] = partial derivative of cost w.r.t. input i boost::multi_array<double, 1> gradients; public: OutputLayer(int size); void adjust(int new_size); double getInput(int i) const; double getOutput(int i) const; std::vector<double> getInput() const; std::vector<double> getOutput() const; void receiveInput(const std::vector<double>& input); void computeGradient(const std::vector<double>& output); // returns the partial derivative of cost // w.r.t. the input #input_id of this layer double getPartialDerivative(int input_id) const; }; #endif
[ "chen1994tw@gmail.com" ]
chen1994tw@gmail.com
3793aa9fdb714074fa3462ec4582ed2655264ae9
f162089eaa4722bc98b320e6954b5c88c228ed34
/src/Console.cpp
5e6c5aa8bf8cfbb27b913fce2d23874239825f76
[ "MIT" ]
permissive
roslinman/engine
97828470caacb50f07f046f62c887e8f71737574
061a1fa1b6e4cbe6a90698b08d6a88d2ef705542
refs/heads/develop
2021-05-27T21:12:22.202409
2014-06-03T19:37:10
2014-06-03T19:37:10
110,465,392
1
0
null
2017-11-12T20:13:20
2017-11-12T20:13:20
null
UTF-8
C++
false
false
1,512
cpp
#include "Console.h" #include "jni\defines.h" namespace star_w { static const WORD MAX_CONSOLE_LINES = 500; void RedirectIOToConsole() { int32 hConHandle; long lStdHandle; CONSOLE_SCREEN_BUFFER_INFO conInfo; FILE * fp; // allocate a console for this app AllocConsole(); // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &conInfo); conInfo.dwSize.Y = MAX_CONSOLE_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), conInfo.dwSize); // redirect unbuffered STDOUT to the console lStdHandle = long(GetStdHandle(STD_OUTPUT_HANDLE)); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen(hConHandle, "w"); *stdout = *fp; setvbuf(stdout, NULL, _IONBF, 0); // redirect unbuffered STDIN to the console lStdHandle = long(GetStdHandle(STD_INPUT_HANDLE)); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen(hConHandle, "r"); *stdin = *fp; setvbuf(stdin, NULL, _IONBF, 0); // redirect unbuffered STDERR to the console lStdHandle = long(GetStdHandle(STD_ERROR_HANDLE)); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen(hConHandle, "w"); *stderr = *fp; setvbuf(stderr, NULL, _IONBF, 0); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well std::ios::sync_with_stdio(); } void CleanUpConsole() { FreeConsole(); } }
[ "decauwsemaecker.glen@gmail.com" ]
decauwsemaecker.glen@gmail.com
78c914ba811b661ea2714d984f9dad62e335d17b
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/MPLSTunnelHop/UNIX_MPLSTunnelHop_ZOS.hxx
63c635ce6bb45e7e47328df68997ae85e8d0ab16
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,809
hxx
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifdef PEGASUS_OS_ZOS #ifndef __UNIX_MPLSTUNNELHOP_PRIVATE_H #define __UNIX_MPLSTUNNELHOP_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
69b6df41b54dd5fba4c3bfdebec156e59bf32cac
98d9e1a599b5f782291d442e02d5e5b76c513b78
/StRefMultCorr/CentralityMaker.h
675775b47ca6175bae9c8733de3ca989bb3ee8cd
[]
no_license
joelmazer/Centrality
efb7f069e6b0000fa4e8e19e43467c5ef319dd0d
c36c4c6adac8ed690216412e5ee568baa193be48
refs/heads/master
2023-04-15T00:03:58.925348
2021-04-12T23:04:21
2021-04-12T23:04:21
113,375,261
0
1
null
null
null
null
UTF-8
C++
false
false
4,347
h
//---------------------------------------------------------------------------------------------------- // $Id: CentralityMaker.h,v 1.5 2015/05/22 06:51:58 hmasui Exp $ // $Log: CentralityMaker.h,v $ // Revision 1.5 2015/05/22 06:51:58 hmasui // Add grefmult for Run14 Au+Au 200 GeV // // Revision 1.4 2013/05/10 18:33:33 hmasui // Add TOF tray mult, preliminary update for Run12 U+U // // Revision 1.3 2012/05/19 00:49:14 hmasui // Update refmult3 // // Revision 1.2 2012/05/08 03:19:39 hmasui // Move parameters to Centrality_def_refmult.txt // // Revision 1.1 2012/04/23 21:32:16 hmasui // Interface for future extention of centrality correction maker to other centrality measures, like refmult2 // //---------------------------------------------------------------------------------------------------- // * Interface of StRefMultCorr for possible extention of StRefMultCorr class to the other // centrality measure, such as refmult2. // * This interface is also useful when StRefMultCorr needs to be called from two or more different // makers in order to have exactly the same corrected refmult and centrality bins among different makers. // // There is only one change you have to make // Replace // StRefMultCorr* refmultCorr = new StRefMultCorr(); // to // StRefMultCorr* refmultCorr = CentralityMaker::instance()->getRefMultCorr(); // // authors: Hiroshi Masui //---------------------------------------------------------------------------------------------------- #ifndef __CentralityMaker_h__ #define __CentralityMaker_h__ class StRefMultCorr ; #include "Rtypes.h" //____________________________________________________________________________________________________ class CentralityMaker { public: static CentralityMaker* instance(); // Use this function to access StRefMultCorr virtual ~CentralityMaker(); /// Default destructor // Interface StRefMultCorr* getRefMultCorr() ; // For refmult StRefMultCorr* getRefMult2Corr() ; // For refmult2 StRefMultCorr* getRefMult3Corr() ; // For refmult3 StRefMultCorr* getTofTrayMultCorr() ; // For TOF tray multiplicity StRefMultCorr* getgRefMultCorr() ; // For grefmult //Run14 AuAu200GeV StRefMultCorr* getgRefMultCorr_P16id() ; // For grefmult //Run14 AuAu200GeV, P16id StRefMultCorr* getgRefMultCorr_P17id_VpdMB30() ; // for P17id, VPDMB-30; |vz| < 30 StRefMultCorr* getgRefMultCorr_P18ih_VpdMB30() ; // for P18ih, VPDMB-30; |vz| < 30, added June10, 2019 (New Run14 production) StRefMultCorr* getgRefMultCorr_P18ih_VpdMB30_AllLumi() ; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities StRefMultCorr* getgRefMultCorr_P18ih_VpdMB30_AllLumi_MB5sc() ; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities StRefMultCorr* getgRefMultCorr_VpdMB30() ; // for VPDMB-30; |vz| < 30 StRefMultCorr* getgRefMultCorr_VpdMBnoVtx() ; // for VPDMB-noVtx; |vz| < 100 // Print help messages void help() const ; private: CentralityMaker() ; // Constructor is private static CentralityMaker* fInstance ; // Static pointer of CentralityMaker // Centrality correction classes StRefMultCorr* fRefMultCorr ; // refmult based centrality StRefMultCorr* fRefMult2Corr ; // refmult2 based centrality StRefMultCorr* fRefMult3Corr ; // refmult3 based centrality StRefMultCorr* fTofTrayMultCorr ; // tofTrayMult based centrality StRefMultCorr* fgRefMultCorr ; // grefmult based centrality StRefMultCorr* fgRefMultCorr_P16id ; // grefmult based centrality, P16id StRefMultCorr* fgRefMultCorr_P17id_VpdMB30; // for P17id, VPDMB-30; |vz| < 30 StRefMultCorr* fgRefMultCorr_P18ih_VpdMB30; // for P18ih, VPDMB-30; |vz| < 30, added June10, 2019 (New Run14 production) StRefMultCorr* fgRefMultCorr_P18ih_VpdMB30_AllLumi; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities StRefMultCorr* fgRefMultCorr_P18ih_VpdMB30_AllLumi_MB5sc; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities StRefMultCorr* fgRefMultCorr_VpdMB30; // for VPDMB-30; |vz| < 30 StRefMultCorr* fgRefMultCorr_VpdMBnoVtx; // for VPDMB-noVtx; |vz| < 100 ClassDef(CentralityMaker, 0) }; #endif
[ "joel.mazer@cern.ch" ]
joel.mazer@cern.ch
d3d0190bcc2d778d74a32f7e45d704548fac9e88
e8c837604c46d5e672ba9e0d1458cc5bae9dd1a2
/PantsuSDK/esp.h
9c569c66bdd7c1a5c60254ce8515425a023d76d3
[]
no_license
pSilent-Github/Pantsu-SDK
17de5ff479457598b82ae8d2b2bd4a4169869829
c5202078524aeb89e861da137a86f3e5f32b3527
refs/heads/master
2021-07-12T05:31:04.421812
2017-10-13T17:47:46
2017-10-13T17:47:46
106,767,630
0
1
null
null
null
null
UTF-8
C++
false
false
2,277
h
#pragma once #include "client-entity-list.h" #include "engine-client.h" #include "entity.h" #include "render.h" class CESP { public: void Think( ) { CBaseEntity* Local = ( CBaseEntity* )ClientEntityList->GetClientEntity( EngineClient->GetLocalPlayer( ) ); PlayerInfo_t Info; Matrix3x4_t Matrix = EngineClient->GetMatrix( ); CVector Screen, Head; for ( int i = 0; i < 64; ++i ) { CBaseEntity* Entity = ( CBaseEntity* ) ClientEntityList->GetClientEntity( i ); if ( !Entity ) continue; if ( Entity == Local ) continue; if ( Entity->GetDormant( ) ) continue; if ( Entity->GetHealth( ) ) { EngineClient->GetPlayerInfo( i, &Info ); if ( WorldToScreen( Entity->GetOrigin( ), Screen ) && WorldToScreen( ( Entity->GetEyePosition( ) + CVector( 0, 0, 8.f ) ), Head ) ) { CColor Color( 255, 255, 255, 255 ); if ( Entity->GetTeam( ) != Local->GetTeam( ) ) Color = CColor( 255, 0, 0, 255 ); else Color = CColor( 0, 255, 255, 255 ); Render->DrawF(Head.x, Head.y - 12, CColor(255, 255, 255, 255), 5, 1, "%s", Info.Name ); Render->DrawF(Screen.x, Screen.y + 2, CColor(255, 255, 255, 255), 5, 1, "HP: %d", Entity->GetHealth( ) ); int Height = Screen.y - Head.y, Width = Height / 2.5; Render->DrawInlineRect( Head.x - Width / 2, Head.y, Width, Height, Color ); } } } } __forceinline bool WorldToScreen( CVector In, CVector& Out ) { Matrix3x4_t ViewMatrix = EngineClient->GetMatrix( ); Out.x = ViewMatrix.Matrix[ 0 ] * In.x + ViewMatrix.Matrix[ 1 ] * In.y + ViewMatrix.Matrix[ 2 ] * In.z + ViewMatrix.Matrix[ 3 ]; Out.y = ViewMatrix.Matrix[ 4 ] * In.x + ViewMatrix.Matrix[ 5 ] * In.y + ViewMatrix.Matrix[ 6 ] * In.z + ViewMatrix.Matrix[ 7 ]; Out.z = ViewMatrix.Matrix[ 12 ] * In.x + ViewMatrix.Matrix[ 13 ] * In.y + ViewMatrix.Matrix[ 14 ] * In.z + ViewMatrix.Matrix[ 15 ]; if ( Out.z < 0.01f ) return false; float Inverse = 1.f / Out.z; Out.x *= Inverse; Out.y *= Inverse; int Width, Height; EngineClient->GetScreenSize( Width, Height ); auto X = Width / 2; auto Y = Height / 2; X += 0.5 * Out.x * Width + 0.5; Y -= 0.5 * Out.y * Height + 0.5; Out.x = X; Out.y = Y; return true; } };
[ "pSilent@github.com" ]
pSilent@github.com
55d561c48bdfae93adb41eb26e126760895380f1
aadf31061666fc9fd95583710a34d01fa571b09f
/tests/TestFieldPointerVariable.cpp
a670e5a4cca1f2c561b0e8e12ae9906212fd45b6
[]
no_license
vladfridman/wisey
6198cf88387ea82175ea6e1734edb7f9f7cf20c6
9d0efcee32e05c7b8dc3dfd22293737324294fea
refs/heads/master
2022-04-14T08:00:42.743194
2020-03-12T14:22:45
2020-03-12T14:22:45
74,822,543
0
0
null
null
null
null
UTF-8
C++
false
false
7,286
cpp
// // TestFieldPointerVariable.cpp // Wisey // // Created by Vladimir Fridman on 4/3/18. // Copyright © 2018 Vladimir Fridman. All rights reserved. // // Tests {@link FieldPointerVariable} // #include <gtest/gtest.h> #include <gmock/gmock.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Constants.h> #include <llvm/Support/raw_ostream.h> #include "MockExpression.hpp" #include "TestFileRunner.hpp" #include "TestPrefix.hpp" #include "FieldPointerVariable.hpp" #include "IExpression.hpp" #include "IInterfaceTypeSpecifier.hpp" #include "IRGenerationContext.hpp" #include "IRWriter.hpp" #include "LLVMPrimitiveTypes.hpp" #include "ParameterReferenceVariable.hpp" #include "PrimitiveTypes.hpp" #include "StateField.hpp" using namespace llvm; using namespace std; using namespace wisey; using ::testing::_; using ::testing::Mock; using ::testing::NiceMock; using ::testing::Return; using ::testing::Test; struct FieldPointerVariableTest : Test { IRGenerationContext mContext; LLVMContext& mLLVMContext; Controller* mObject; Interface* mInterface; BasicBlock* mBasicBlock; FieldPointerVariable* mFieldPointerVariable; const LLVMPointerType* mPointerType; Node* mNode; string mStringBuffer; raw_string_ostream* mStringStream; FieldPointerVariableTest() : mLLVMContext(mContext.getLLVMContext()) { TestPrefix::generateIR(mContext); string interfaceFullName = "systems.vos.wisey.compiler.tests.IInterface"; StructType* interfaceStructType = StructType::create(mLLVMContext, interfaceFullName); vector<IInterfaceTypeSpecifier*> parentInterfaces; vector<IObjectElementDefinition*> interfaceElements; mInterface = Interface::newInterface(AccessLevel::PUBLIC_ACCESS, interfaceFullName, interfaceStructType, parentInterfaces, interfaceElements, mContext.getImportProfile(), 0); vector<Interface*> interfaces; interfaces.push_back(mInterface); string nodeFullName = "systems.vos.wisey.compiler.tests.NNode"; StructType* nodeStructType = StructType::create(mLLVMContext, nodeFullName); mNode = Node::newNode(AccessLevel::PUBLIC_ACCESS, nodeFullName, nodeStructType, mContext.getImportProfile(), 0); mNode->setInterfaces(interfaces); mPointerType = LLVMPrimitiveTypes::I64->getPointerType(mContext, 0); vector<Type*> types; types.push_back(FunctionType::get(Type::getInt32Ty(mLLVMContext), true) ->getPointerTo()->getPointerTo()); types.push_back(mPointerType->getLLVMType(mContext)); types.push_back(mInterface->getLLVMType(mContext)); string objectFullName = "systems.vos.wisey.compiler.tests.CController"; StructType* objectStructType = StructType::create(mLLVMContext, objectFullName); objectStructType->setBody(types); vector<IField*> fields; fields.push_back(new StateField(mPointerType, "foo", 0)); fields.push_back(new StateField(mInterface, "bar", 0)); mObject = Controller::newController(AccessLevel::PUBLIC_ACCESS, objectFullName, objectStructType, mContext.getImportProfile(), 0); mObject->setFields(mContext, fields, 1u); FunctionType* functionType = FunctionType::get(Type::getInt32Ty(mContext.getLLVMContext()), false); Function* function = Function::Create(functionType, GlobalValue::InternalLinkage, "main", mContext.getModule()); BasicBlock* declareBlock = BasicBlock::Create(mLLVMContext, "declare", function); mBasicBlock = BasicBlock::Create(mLLVMContext, "entry", function); mContext.setDeclarationsBlock(declareBlock); mContext.setBasicBlock(mBasicBlock); mContext.getScopes().pushScope(); Value* thisPointer = ConstantPointerNull::get(mObject->getLLVMType(mContext)); IVariable* thisVariable = new ParameterReferenceVariable(IObjectType::THIS, mObject, thisPointer, 0); mContext.getScopes().setVariable(mContext, thisVariable); mFieldPointerVariable = new FieldPointerVariable("foo", mObject, 0); mStringStream = new raw_string_ostream(mStringBuffer); } ~FieldPointerVariableTest() { delete mStringStream; delete mObject; } }; TEST_F(FieldPointerVariableTest, basicFieldsTest) { EXPECT_STREQ("foo", mFieldPointerVariable->getName().c_str()); EXPECT_EQ(mPointerType, mFieldPointerVariable->getType()); EXPECT_TRUE(mFieldPointerVariable->isField()); EXPECT_FALSE(mFieldPointerVariable->isStatic()); } TEST_F(FieldPointerVariableTest, generateIdentifierIRTest) { mFieldPointerVariable->generateIdentifierIR(mContext, 0); *mStringStream << *mBasicBlock; string expected = string() + "\nentry: ; No predecessors!" + "\n %0 = getelementptr %systems.vos.wisey.compiler.tests.CController, %systems.vos.wisey.compiler.tests.CController* null, i32 0, i32 1" "\n %foo = load i64*, i64** %0\n"; EXPECT_STREQ(expected.c_str(), mStringStream->str().c_str()); } TEST_F(FieldPointerVariableTest, generateIdentifierreferenceIRTest) { mFieldPointerVariable->generateIdentifierReferenceIR(mContext, 0); *mStringStream << *mBasicBlock; string expected = string() + "\nentry: ; No predecessors!" + "\n %0 = getelementptr %systems.vos.wisey.compiler.tests.CController, %systems.vos.wisey.compiler.tests.CController* null, i32 0, i32 1\n"; EXPECT_STREQ(expected.c_str(), mStringStream->str().c_str()); } TEST_F(FieldPointerVariableTest, generateAssignmentIRTest) { NiceMock<MockExpression> assignToExpression; Value* assignToValue = ConstantPointerNull::get(mNode->getLLVMType(mContext)); ON_CALL(assignToExpression, getType(_)).WillByDefault(Return(mNode)); ON_CALL(assignToExpression, generateIR(_, _)).WillByDefault(Return(assignToValue)); vector<const IExpression*> arrayIndices; mFieldPointerVariable->generateAssignmentIR(mContext, &assignToExpression, arrayIndices, 0); *mStringStream << *mBasicBlock; string expected = string() + "\nentry: ; No predecessors!" + "\n %0 = bitcast %systems.vos.wisey.compiler.tests.NNode* null to i64*" "\n %1 = getelementptr %systems.vos.wisey.compiler.tests.CController, %systems.vos.wisey.compiler.tests.CController* null, i32 0, i32 1" "\n store i64* %0, i64** %1\n"; EXPECT_STREQ(expected.c_str(), mStringStream->str().c_str()); } TEST_F(TestFileRunner, fieldPointerVariableRunTest) { runFile("tests/samples/test_field_pointer_variable.yz", 1); }
[ "vlad.fridman@gmail.com" ]
vlad.fridman@gmail.com
2ba9d3a63af5db8dcd147e59d50c81ff4e866358
f71b74eb0386711937c656f7813dadf70358a35b
/SearchingAndSorting/1_first_and_last_occ/first_and_last_occ.cpp
2d365cd0e2970c49f75dd96da51ddfabc47f3d81
[]
no_license
tanishq1306/DSA-Solved-Questions
74e3d39ddd1014e11d7f649ac1cb9d25ee9ac56f
c9419717c7c62a32a317cecd747bc151fcf62f78
refs/heads/main
2023-05-31T13:17:33.632186
2021-06-07T12:32:57
2021-06-07T12:32:57
304,842,758
19
6
null
null
null
null
UTF-8
C++
false
false
665
cpp
/** * author: tanishq * created: 17.12.2020 **/ #include <bits/stdc++.h> #define int long long using namespace std; signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int test_case; cin >> test_case; while (test_case--) { int n, k; cin >> n >> k; int first = -1, last = -1, x; for (int i = 0; i < n; i++) { cin >> x; if (x == k) { if (first == -1) { first = i + 1; last = i + 1; } else { last = i + 1; } } } if (first == -1) { cout << first << endl; } else { cout << first << " " << last << endl; } } return 0; }
[ "52647176+tanishq1306@users.noreply.github.com" ]
52647176+tanishq1306@users.noreply.github.com
f5d14893b4e42fc33d23780012aa1882f5deb60c
ad822f849322c5dcad78d609f28259031a96c98e
/SDK/Sun_functions.cpp
aace6051de2bbe74766b5ae4694710525db661dc
[]
no_license
zH4x-SDK/zAstroneer-SDK
1cdc9c51b60be619202c0258a0dd66bf96898ac4
35047f506eaef251a161792fcd2ddd24fe446050
refs/heads/main
2023-07-24T08:20:55.346698
2021-08-27T13:33:33
2021-08-27T13:33:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,517
cpp
#include "../SDK.h" // Name: Astroneer-SDK, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function Sun.Sun_C.Set Intensity // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ASun_C::Set_Intensity() { static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.Set Intensity"); ASun_C_Set_Intensity_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Sun.Sun_C.UserConstructionScript // (Event, Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ASun_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.UserConstructionScript"); ASun_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Sun.Sun_C.ReceiveBeginPlay // (Event, Protected, BlueprintEvent) void ASun_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.ReceiveBeginPlay"); ASun_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Sun.Sun_C.ReceiveTick // (Event, Public, BlueprintEvent) // Parameters: // float DeltaSeconds (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void ASun_C::ReceiveTick(float DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.ReceiveTick"); ASun_C_ReceiveTick_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Sun.Sun_C.ExecuteUbergraph_Sun // () // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void ASun_C::ExecuteUbergraph_Sun(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.ExecuteUbergraph_Sun"); ASun_C_ExecuteUbergraph_Sun_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
14400e790aa515ea6733196f79df5b3f677e65c0
27f68827fd788bc53b7669296c07fa39962a2b68
/Devices/Window/CommonWindow/SubComponents/BaseRenderer/src/BaseRenderer.cpp
42acb9a350ef8f9d39c2201b57ce2fe9adb97ae7
[]
no_license
Dholguin-Programmer/Assignment_1
9a79dc7d6fabde95c8eb63ec8797ab595ad4071d
f4e18f27dc23ab62a5c74a724b36718541709df5
refs/heads/master
2022-07-05T17:30:07.330389
2020-05-20T19:58:06
2020-05-20T19:58:06
262,688,117
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include "BaseRenderer.h" using namespace Renderer::SubComponent; /////////////////////////////////////////////////////////////////////[/////////// Base::Base(Window::Device::Manager& manager) : m_windowManager(manager) { // no nothing }
[ "Dholguin.Programmer@gmail.com" ]
Dholguin.Programmer@gmail.com
4eeb21d670dc47474696da66e1175278697fa512
ee44c5351afcbf8d44f2893151661f1739ea62bc
/include/level.hh
7a2141a2094c62a0fdb61a9b84dc0070491b467e
[]
no_license
jgardella/CS585
892f9721c77818948cffc5f7e89f15a6c74fe74c
42049d5fc20509bc0469da917427f74276451757
refs/heads/master
2021-01-01T16:39:59.957828
2014-12-02T04:35:16
2014-12-02T04:35:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,329
hh
#ifndef _LEVEL_HH_ #define _LEVEL_HH_ #include "levelinfo.hh" #include "fixedgrid.hh" #include "scenemanager.hh" #include "tilefactory.hh" #include "statemachine.hh" #include "building.hh" #include "charactercontroller.hh" #include "ilistenercallback.hh" #include "ievent.hh" #include "deathevent.hh" #include "menumanager.hh" class Level : public ITickable { public: // Constructs a level with a world of the given width and height. // Parameters: // int width - the width of the world // int height - the height of the world Level(tLevelInfo level); void tick(float dt); int getWorldWidth(); int getWorldHeight(); Building* getHome(unsigned int teamNum); Building* getBlacksmith(unsigned int teamNum); Building* getApothecary(unsigned int teamNum); std::string getDefaultTile(); CharacterController* getControllerForCharacter(unsigned int id); void removeControllerForCharacter(unsigned int id); void addControllerForCharacter(CharacterController* controller); void addHome(Building* building); void addBlacksmith(Building* building); void addApothecary(Building* building); IListenerCallback* getListener(); unsigned int getPlayerGold(); void changePlayerGold(int amount); bool isApothecaryBuilt(); bool isBlacksmithBuilt(); void setApothecaryBuilt(bool val); void setBlacksmithBuilt(bool val); private: int width; int height; bool apothecaryBuilt, blacksmithBuilt; unsigned int playerGold; std::string defaultTile; DynamicArray<Building*>* teamHomes; DynamicArray<Building*>* teamBlacksmiths; DynamicArray<Building*>* teamApothecaries; DynamicArray<CharacterController*>* characterControllers; void processDeathEvent(DeathEvent* event); // Listener callback for deaths class OnDeathEvent : public IListenerCallback { public: OnDeathEvent() { } void setInstance(Level* level) { this->level = level; } // Transfers gold and removes the controller for the dead actor. virtual void execute(IEvent* event) { DEBUG_LOG("LEVEL", "Death event callback executed."); if(event->getType().compare("death") == 0) { DeathEvent* deathEvent = (DeathEvent*) event; level->processDeathEvent(deathEvent); } } private: Level* level; } onDeathEvent; }; #endif
[ "jgardell@stevens.edu" ]
jgardell@stevens.edu
2e3c9a07c28d102791a5c7ad0b844a32c3adb203
7d6d0eb3b34773edf7a7f98c8a1a9fd6358f6c5e
/timer.cpp
1edc4b726e1d1467c1eb6fb603787d4274d4ad66
[]
no_license
illuvatar88/UNIX_IPC_benchmark_SHM
356e0c2b9d3d868ca10077378d7eb252a5378105
10023aa181c54d54cd1d3119a5434791c825b154
refs/heads/master
2021-01-01T18:17:02.701840
2014-10-16T07:48:58
2014-10-16T07:48:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
/*This file contains the declaration of the function timerval() that is used in the benchmarks to *register time */ #include <sys/time.h> double timerval () { struct timeval st; gettimeofday (&st, NULL); return st.tv_sec + st.tv_usec * 1e-6; }
[ "illuvatar@ufl.edu" ]
illuvatar@ufl.edu
bbc227cb1db148cf367d3ccc60988bfd3f993354
361390c6fb4bef1dd04dfd57bc74c7f64149922f
/RunGun/Skills/Weapons/C_FiringComp.h
d389e5b8dd18c9ea004c75048f31e4efdccf6593
[]
no_license
maunglinkyaw/RunGun
d602b491d1d74bf6b3f7d033a3bf6ef9edc5dc40
b18b97254e1f04d95855d04b7690dce141f834eb
refs/heads/main
2023-04-22T00:31:30.251457
2021-05-07T19:00:46
2021-05-07T19:00:46
360,533,685
0
0
null
null
null
null
UTF-8
C++
false
false
930
h
// Lin & Yin 2020 #pragma once #include "CoreMinimal.h" #include "C_WeaponComp.h" #include "C_FiringComp.generated.h" class AC_Skill; class AC_Projectile; class UC_SkillManager; UCLASS() class RUNGUN_API UC_FiringComp : public UC_WeaponComp { GENERATED_BODY() public: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Weapon") UC_SkillManager* m_SkillManager = nullptr; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "WeaponStats|Pooling") TSubclassOf<AC_Skill> m_SkillClass = nullptr; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "WeaponStats|Pooling") int32 m_PoolCount = 0; void InitWeaponComp(AC_Weapon* weapon) override; virtual void RequestFireWeapon(float chargeRate); virtual void RemoveWeaponComp() override; protected: virtual void FireWeapon(float chargeRate); AC_Projectile* m_TempProjectile; void BeginPoolAmmo(); AC_Projectile* GetProjectileFromPool(); };
[ "83018188+maunglinkyaw@users.noreply.github.com" ]
83018188+maunglinkyaw@users.noreply.github.com
08ec1d7ac1b6358c529a76c8a501c86af9946748
93becb0e207e95d75dbb05c92c08c07402bcc492
/yuki/no804.cpp
5bf79b2b6419d06fc0daeda776fd4c216feae9f1
[]
no_license
veqcc/atcoder
2c5f12e12704ca8eace9e2e1ec46a354f1ec71ed
cc3b30a818ba2f90c4d29c74b4d2231e8bca1903
refs/heads/master
2023-04-14T21:39:29.705256
2023-04-10T02:31:49
2023-04-10T02:31:49
136,691,016
2
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
#include <algorithm> #include <iostream> #include <iomanip> #include <cstring> #include <string> #include <vector> #include <random> #include <bitset> #include <queue> #include <cmath> #include <stack> #include <set> #include <map> typedef long long ll; using namespace std; const ll MOD = 1000000007LL; int main() { int a, b, c, d; cin >> a >> b >> c >> d; int ans = 0; while (true) { if (a == 0) break; if (b < c) break; if (d < 1 + c) break; a--; b -= c; d -= 1 + c; ans++; } cout << ans << "\n"; return 0; }
[ "kambe3141@gmail.com" ]
kambe3141@gmail.com
5541fe1844c972951f15a8a1bef8186e2353815e
f2c3efa6db82fd8e59fa39c43c7768ede38d02f0
/include/polimidl/internal/runner.hpp
686991306439ac5cdcc84d4ca928ecb634a59bc2
[ "MIT" ]
permissive
darianfrajberg/polimidl
ce6e260e86149064142cfc87096884f42eb45481
ab338269c25a0fcccf06bbfccbfe7fe16ee7cf04
refs/heads/master
2021-07-05T03:49:41.119174
2020-09-20T21:04:22
2020-09-20T21:04:22
176,907,084
3
2
MIT
2020-09-20T21:04:23
2019-03-21T08:58:51
C++
UTF-8
C++
false
false
8,005
hpp
#ifndef POLIMIDL_INTERNAL_RUNNER_HPP #define POLIMIDL_INTERNAL_RUNNER_HPP #include <chrono> #include <sstream> #include <type_traits> #include "./memory_layout.hpp" namespace polimidl { namespace internal { template <typename layer_t> std::size_t input_size_of(std::size_t input_rows, std::size_t input_columns) { return layer_t::input_components * input_rows * input_columns; } template <typename layer_t> std::size_t output_size_of(std::size_t ouput_rows, std::size_t output_columns) { return layer_t::output_components * ouput_rows * output_columns; } template <std::size_t alignment, typename type_t, bool is_inverted, typename... Layers> class runner {}; template <std::size_t alignment, typename type_t, bool is_inverted, typename layer_t> class runner<alignment, type_t, is_inverted, layer_t> { public: runner(span<type_t> buffer, std::size_t input_rows, std::size_t input_columns, unsigned int number_of_workers, layer_t&& layer) : layer_(std::forward<layer_t>(layer)), input_rows_(input_rows), input_columns_(input_columns), output_rows_(layer_t::output_rows(input_rows_)), output_columns_(layer_t::output_columns(input_columns_)), input_( input_of<alignment, layer_t, is_inverted>(buffer, this->input_size())), temporary_(temporary_of<alignment, layer_t, is_inverted>( buffer, this->input_size(), this->output_size(), number_of_workers)), output_( output_of<alignment, layer_t, is_inverted>(buffer, this->output_size())), accumulated_execution_duration_(0) {} std::size_t input_rows() const { return input_rows_; } std::size_t input_columns() const { return input_columns_; } std::size_t input_components() const { return layer_t::input_components; } std::size_t input_size() const { return input_size_of<layer_t>(input_rows(), input_columns()); } std::size_t output_rows() const { return output_rows_; } std::size_t output_columns() const { return output_columns_; } std::size_t output_components() const { return layer_t::output_components; } std::size_t output_size() const { return output_size_of<layer_t>(output_rows(), output_columns()); } span<type_t> input() const { return input_; } span<type_t> output() const { return output_; } template <typename scheduler_t> void run(const scheduler_t& scheduler) const { layer_(input(), temporary_, output(), input_rows(), input_columns(), scheduler); } template <typename scheduler_t> void run_with_statistics(const scheduler_t& scheduler) { using std::chrono::high_resolution_clock; const auto start = high_resolution_clock::now(); layer_(input(), temporary_, output(), input_rows(), input_columns(), scheduler); accumulated_execution_duration_ += high_resolution_clock::now() - start; } template <typename scheduler_t> void optimize_for(const scheduler_t& scheduler) { layer_.optimize_for(input(), temporary_, output(), input_rows(), input_columns(), scheduler); } void print_statistics(std::stringstream& stream, std::size_t position, std::size_t accumulated_executions) { stream << "Layer " << position << " Avg Time = " << std::chrono::duration_cast<std::chrono::microseconds>( accumulated_execution_duration_ / accumulated_executions).count() << " microseconds" << std::endl; } private: static_assert(std::is_same<type_t, typename layer_t::type_t>::value, "The layer is not of the same data type of the network"); layer_t layer_; std::size_t input_rows_; std::size_t input_columns_; std::size_t output_rows_; std::size_t output_columns_; span<type_t> input_; span<type_t> temporary_; span<type_t> output_; std::chrono::high_resolution_clock::duration accumulated_execution_duration_; }; template <std::size_t alignment, typename type_t, bool is_inverted, typename layer_t, typename next_layer_t, typename... Layers> class runner<alignment, type_t, is_inverted, layer_t, next_layer_t, Layers...> { public: runner(span<type_t> buffer, std::size_t input_rows, std::size_t input_columns, unsigned int number_of_workers, layer_t&& layer, next_layer_t&& next_layer, Layers&&... layers) : layer_(std::forward<layer_t>(layer)), input_rows_(input_rows), input_columns_(input_columns), next_runner_(buffer, layer_t::output_rows(input_rows_), layer_t::output_columns(input_columns_), number_of_workers, std::forward<next_layer_t>(next_layer), std::forward<Layers>(layers)...), input_( input_of<alignment, layer_t, is_inverted>(buffer, this->input_size())), temporary_(temporary_of<alignment, layer_t, is_inverted>( buffer, this->input_size(), next_runner_.input_size(), number_of_workers)), accumulated_execution_duration_(0) {} std::size_t input_rows() const { return input_rows_; } std::size_t input_columns() const { return input_columns_; } std::size_t input_components() const { return layer_t::input_components; } std::size_t input_size() const { return input_size_of<layer_t>(input_rows(), input_columns()); } std::size_t output_rows() const { return next_runner_.output_rows(); } std::size_t output_columns() const { return next_runner_.output_columns(); } std::size_t output_components() const { return next_runner_.output_components(); } std::size_t output_size() const { return next_runner_.output_size(); } span<type_t> input() const { return input_; } span<type_t> output() const { return next_runner_.output(); } template <typename scheduler_t> void run(const scheduler_t& scheduler) const { layer_(input(), temporary_, next_runner_.input(), input_rows(), input_columns(), scheduler); next_runner_.run(scheduler); } template <typename scheduler_t> void run_with_statistics(const scheduler_t& scheduler) { using std::chrono::high_resolution_clock; const auto start = high_resolution_clock::now(); layer_(input(), temporary_, next_runner_.input(), input_rows(), input_columns(), scheduler); accumulated_execution_duration_ += high_resolution_clock::now() - start; next_runner_.run_with_statistics(scheduler); } template <typename scheduler_t> void optimize_for(const scheduler_t& scheduler) { layer_.optimize_for(input(), temporary_, next_runner_.input(), input_rows(), input_columns(), scheduler); next_runner_.optimize_for(scheduler); } void print_statistics(std::stringstream& stream, std::size_t position, std::size_t accumulated_executions) { stream << "Layer " << ++position << " Avg Time = " << std::chrono::duration_cast<std::chrono::microseconds>( accumulated_execution_duration_ / accumulated_executions).count() << " microseconds" << std::endl; next_runner_.print_statistics(stream, position, accumulated_executions); } private: static_assert(std::is_same<type_t, typename layer_t::type_t>::value, "The layer is not of the same data type of the network"); static_assert(layer_t::output_components == next_layer_t::input_components, "The number of output components of this layer is different " "from the number of input components in the next one"); layer_t layer_; std::size_t input_rows_; std::size_t input_columns_; static constexpr bool is_next_layer_inverted = (is_inverted && layer_t::is_in_place) || (!is_inverted && !layer_t::is_in_place); runner<alignment, type_t, is_next_layer_inverted, next_layer_t, Layers...> next_runner_; span<type_t> input_; span<type_t> temporary_; std::chrono::high_resolution_clock::duration accumulated_execution_duration_; }; } } #endif // POLIMIDL_INTERNAL_RUNNER_HPP
[ "darian.frajberg@polimi.it" ]
darian.frajberg@polimi.it
8b3d486c02feefc5bc213d7443d9335c3e766d2d
4cb5b2389b536d364471514d2efc20c86e8ae6f5
/src/user/init/main.cc
480dbca602c3e88c1393b699f0b163407d454bdc
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
cjsmeele/RikaiOS
d48c11b21c91d1827f264a101a1c420a8581d959
4da9da8a4492adefb1733fdad152f0e098ddc7fd
refs/heads/master
2021-06-18T21:38:37.410485
2021-02-10T18:35:25
2021-02-10T18:35:25
177,954,455
9
1
null
null
null
null
UTF-8
C++
false
false
2,058
cc
/* Copyright 2019 Chris Smeele * * 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 * * https://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 <io.hh> #include <proc.hh> #include <os-std/ostd.hh> using namespace ostd; int main(int, const char**) { // (arguments are ignored) // Open stdin/out/err. These will be inherited by processes we spawn. // If a serial port is available, use it for all I/O. errno_t err = open(stdin , "/dev/uart0", "r"); if (err >= 0) { // OK. err = open(stdout, "/dev/uart0", "w"); if (err < 0) return 1; } else if (err == ERR_not_exists) { // TODO: Provide a tty driver. Open a pipe to it here. // Serial port not available, use keyboard+monitor instead. err = open(stdin , "/dev/keyboard", "r"); if (err < 0) return 1; err = open(stdout, "/dev/video-text", "w"); if (err < 0) return 1; // This pretends to be succesful, but we actually can't use video-text // as a console for userland currently. We depend on a working UART. } else { return 1; } // stderr should appear in the same place as stdout. err = duplicate_fd(stderr, stdout); if (err < 0) return 1; // Note: The current working directory should be the root of the first // mounted partition. We look for a shell in its "/bin" directory. Array<StringView, 1> args { "shell" }; err = spawn("bin/shell.elf", args, true); if (err < 0) { print(stderr, "init: could not load the shell: {}\n", error_name(err)); return 1; } return 0; }
[ "cj.smeele@xs4all.nl" ]
cj.smeele@xs4all.nl
846c3bd24692dc112d655c014a0af865d755d94d
d502103fc5f72e66b382d01b6d502d95ffa3cb43
/mainwindow.cpp
4e02423fcce600c00e2c76dd6bd27535a9ce794f
[ "MIT" ]
permissive
abrarShariar/ToDo-Qt
0d109382bb8326f40bf6db6d5997d81901ad27d2
b1c6c5f714b2830aed8719f3cddb4aa8f3fb344c
refs/heads/master
2020-12-25T21:01:41.649848
2016-02-13T12:46:23
2016-02-13T12:46:23
49,495,994
0
0
null
null
null
null
UTF-8
C++
false
false
3,272
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "dialog.h" #include "tasklist.h" #include<QTime> #include<QDebug> #include<QtSql> qint8 getDaysLeft(QDateTime); qint16 getHoursLeft(QDateTime); qint32 getMinsLeft(QDateTime); MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { //connect to database QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("E:\\QtProject\\database\\taskDB.db"); bool db_ok=db.open(); if(db_ok){ qDebug()<<"Database Connected"; } QTime currentTime=QTime::currentTime(); ui->setupUi(this); //everything must be after setupUi QDate currentDate=ui->calendarWidget->selectedDate(); ui->dateTimeEdit->setTime(currentTime); ui->dateTimeEdit->setDate(currentDate); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_released() { //prepare deadline in string QTime selectedTime=ui->dateTimeEdit->time(); QDate selectedDate=ui->calendarWidget->selectedDate(); //qDebug()<<time; //time left(hours) ui->dateTimeEdit->setTime(selectedTime); ui->dateTimeEdit->setDate(selectedDate); QDateTime selectedDateTime=ui->dateTimeEdit->dateTime(); //getting selected deadline ui->lcdNumber->display(getDaysLeft(selectedDateTime)); ui->lcdNumber_2->display(getHoursLeft(selectedDateTime)); ui->lcdNumber_3->display(getMinsLeft(selectedDateTime)); } void MainWindow::on_pushButton_2_clicked() { QString taskText=ui->plainTextEdit->toPlainText(); QString deadline=ui->dateTimeEdit->dateTime().toString("yyyy-MM-dd hh:mm:ss"); //insert into database if(taskText!="" && taskText!=" "){ QSqlQuery addTaskQuery; addTaskQuery.prepare("INSERT INTO allTask(task,deadline) values(:task,:deadline)"); addTaskQuery.bindValue(":task",taskText); addTaskQuery.bindValue(":deadline",deadline); if(addTaskQuery.exec()){ Dialog addSuccess; addSuccess.showTaskText(taskText); addSuccess.showDeadline(deadline); addSuccess.exec(); } } } //time left (days) qint8 getDaysLeft(QDateTime selected){ qint8 daysLeft; QDateTime current=QDateTime::currentDateTime(); daysLeft=current.daysTo(selected); return daysLeft; } qint16 getHoursLeft(QDateTime selected){ qint16 hoursLeft; QDateTime current=QDateTime::currentDateTime(); hoursLeft=current.secsTo(selected)/(60*60); return hoursLeft; } qint32 getMinsLeft(QDateTime selected){ qint32 minsLeft; QDateTime current=QDateTime::currentDateTime(); minsLeft=current.secsTo(selected)/(60); return minsLeft; } //show task per type void MainWindow::on_actionUpcoming_triggered() { taskList list; list.setTitle("Upcoming Tasks"); list.showUpcomingTask(); list.exec(); } void MainWindow::on_actionPending_triggered() { taskList list; list.setTitle("Pending Tasks"); list.exec(); } void MainWindow::on_actionCompleted_triggered() { taskList list; list.setTitle("Completed Tasks"); list.exec(); } void MainWindow::on_actionExpired_triggered() { taskList list; list.setTitle("Expired Tasks"); list.showExpiredTask(); list.exec(); }
[ "shariarabrar@gmail.com" ]
shariarabrar@gmail.com
bc964aa465b039a826dfc67367370cd4125c4b01
4040d743d3cc4af68773b659947a92a5acbb07de
/LIB/far3/src/~message/box.cpp
66756a0816abacd2f27492173b64bf59ddf3020b
[]
no_license
msxxxp/main
67072e745a550b6bc58c2b3cb9f3d6d55a6bdf3a
904da0db6239b4d1baf7644037bf1326592e64c1
refs/heads/master
2020-12-24T19:18:02.182013
2014-12-02T17:15:07
2014-12-02T17:15:07
30,285,895
1
0
null
2015-02-04T06:55:42
2015-02-04T06:55:41
null
UTF-8
C++
false
false
2,343
cpp
 /** © 2014 Andrew Grechkin Source code: <http://code.google.com/p/andrew-grechkin> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <far3/message.hpp> namespace far3 { namespace message { void ibox(PCWSTR text, PCWSTR tit) { PCWSTR Msg[] = {tit, text}; psi().Message(get_plugin_guid(), nullptr, FMSG_MB_OK, nullptr, Msg, lengthof(Msg), 1); } void mbox(PCWSTR text, PCWSTR tit) { PCWSTR Msg[] = {tit, text}; psi().Message(get_plugin_guid(), nullptr, FMSG_MB_OK, nullptr, Msg, lengthof(Msg), 1); } void ebox(PCWSTR text, PCWSTR tit) { PCWSTR Msg[] = {tit, text}; psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OK, nullptr, Msg, lengthof(Msg), 1); } void ebox(PCWSTR msgs[], size_t size, PCWSTR help) { psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OK, help, msgs, size, 1); } // void ebox(const cstr::mstring& msg, PCWSTR title) // { // size_t len = msg.size() + 1; // PCWSTR tmp[len]; // tmp[0] = title; // for (size_t i = 0; i < msg.size(); ++i) { // tmp[i + 1] = msg[i]; // } // psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OK, nullptr, tmp, len, 1); // } // void ebox(DWORD err) { // ustring title(L"Error: "); // title += Base::as_str(err); ::SetLastError(err); // PCWSTR Msg[] = {title.c_str(), L"OK", }; psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_ERRORTYPE | FMSG_MB_OK, nullptr, nullptr, 0, 0); } bool question(PCWSTR text, PCWSTR tit) { PCWSTR Msg[] = {tit, text}; return psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OKCANCEL, nullptr, Msg, lengthof(Msg), 2) == 0; } } }
[ "andrew.grechkin@gmail.com" ]
andrew.grechkin@gmail.com
dd0ab93c2a5c808c0602b8b7eac9f02b8ecae736
bacf9e0bbaf00b399ae05cadd4e6c8c3fc886fdb
/caldifspeedinsphere.cpp
6ffd80fac117b0047b52ac244b62bd8121ac3475
[]
no_license
zfzlinux/CrawlerWithHIK
3283c0d82ade118e8deada13a7784b6b869bb008
cd12ed8b3b2e78baef81a057ba5c0d943c7901bd
refs/heads/master
2020-04-01T17:24:26.278865
2019-03-18T07:49:39
2019-03-18T07:49:39
153,427,703
0
1
null
null
null
null
UTF-8
C++
false
false
9,824
cpp
#include "caldifspeedinsphere.h" #include "ui_caldifspeedinsphere.h" #include "crawlerserial.h" #include "crawlerstatusparam.h" CalDifSpeedInSphere::CalDifSpeedInSphere(QWidget *parent) : QWidget(parent), ui(new Ui::CalDifSpeedInSphere), m_radiusOfSphere(1500.00), m_crawlerWidth(300), m_radian_CrawlerCenter(1) { ui->setupUi(this); initUI(); } CalDifSpeedInSphere::~CalDifSpeedInSphere() { delete ui; } double CalDifSpeedInSphere::getCrawlerBothSidesRatio_Sin(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian) { this->setAllParam(radius,width,radian); double minRadian = this->CalMinRadiusOfCrawlerWidth(); double maxRadian = this->CalMaxRadiusOfCrawlerWidth(); double ratio = sin(minRadian)/sin(maxRadian); return ratio; } void CalDifSpeedInSphere::setAllParam(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian) { this->setRadiusOfSphere(radius); this->setCrawlerWidth(width); this->setRadianOfCrawlerCenter(radian); } void CalDifSpeedInSphere::setRadiusOfSphere(const RadiusSp &radius) { if(radius.m_radius>MINRADIUSOFSPHERE) this->m_radiusOfSphere = radius.m_radius; } double CalDifSpeedInSphere::getRadiusOfSphere() { return this->m_radiusOfSphere; } void CalDifSpeedInSphere::setCrawlerWidth(const CrawlerWidth &width) { if(width.m_width > 0) this->m_crawlerWidth = width.m_width; } CrawlerWidth CalDifSpeedInSphere::getCrawlerWidth() { return CrawlerWidth(this->m_crawlerWidth); } void CalDifSpeedInSphere::setRadianOfCrawlerCenter(const RadianCenter &radian) { if(radian.m_radianCenter>MINRADIAN) this->m_radian_CrawlerCenter = radian.m_radianCenter; } RadianCenter CalDifSpeedInSphere::getRadianOfCrawlerCenter() { return RadianCenter(this->m_radian_CrawlerCenter); } //将中心角度转换为环向周长。 double CalDifSpeedInSphere::radianCenterToPerimeter(double radian) { //球的半径 double radius =this->getRadiusOfSphere(); //根据中心角度,求出环向周长的半径。 double radiusOfPerimeter = radius * sin(radian); double perimeter = 2 * D_PI * radiusOfPerimeter; return perimeter; } //将环向周长转换为角度 double CalDifSpeedInSphere::perimeterToRadianCenter(double perimeter) { //球的半径 double radius = this->getRadiusOfSphere(); if(radius <=0) return 0.00; //根据环向周长的半径,求出中心角度。 double radiusOfPerimeter = perimeter / (2*D_PI); double radian = asin(radiusOfPerimeter/radius); return radian; } double CalDifSpeedInSphere::CalMinRadiusOfCrawlerWidth() { return this->CalMinRadiusOfCrawlerWidth(RadiusSp(m_radiusOfSphere),CrawlerWidth(m_crawlerWidth),RadianCenter(m_radian_CrawlerCenter)); } double CalDifSpeedInSphere::CalMinRadiusOfCrawlerWidth(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian) { double minRadian = 0.0; this->setAllParam(radius,width,radian); double radianOfWidth = this->getRadianOfCrawlerWidth(radius,width); minRadian = radian.m_radianCenter - radianOfWidth/2; // 车体中心在球体上的夹角弧度值 - 车体宽度弧度值的一半,//得到车体最小的弧度值。 if(minRadian < MINRADIAN) return MINRADIAN; else return minRadian; } double CalDifSpeedInSphere::CalMaxRadiusOfCrawlerWidth() { return this->CalMaxRadiusOfCrawlerWidth(RadiusSp(m_radiusOfSphere),CrawlerWidth(m_crawlerWidth),RadianCenter(m_radian_CrawlerCenter)); } double CalDifSpeedInSphere::CalMaxRadiusOfCrawlerWidth(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian) { double maxRadian = 0.0; this->setAllParam(radius,width,radian); double radianOfWidth = this->getRadianOfCrawlerWidth(radius,width); maxRadian = radian.m_radianCenter + radianOfWidth/2; // 车体中心在球体上的夹角弧度值 + 车体宽度弧度值的一半,//得到车体最大的弧度值。 if(maxRadian > MAXRADIAN) return MAXRADIAN; else return maxRadian; } //double CalDifSpeedInSphere::getRatioOfRing(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian) //{ // double radianOfObjArc = this->getRadianOfArcLength(radius,width); // double topPointRadian = radian - radianOfObjArc/2; // double tailPointRadian = radian + radianOfObjArc/2; // //the topPoint radius // double topRadius = radius * sin(topPointRadian); // double tailRadius = radius * sin(tailPointRadian); // double ratioOfRing = topRadius/tailRadius; // return ratioOfRing; //} double CalDifSpeedInSphere::getRadianOfCrawlerWidth(const RadiusSp &radius, const CrawlerWidth &width) { if(radius.m_radius>0) return width.m_width/radius.m_radius; else return 0.00; } //转换 //角度与弧度转换 //#define D_PI 3.141592654 //#define ANGTORAD(a) ((a) * D_PI / 180.0) //#define RADTOANG(a) ((a) * 180.0 / D_PI) double CalDifSpeedInSphere::AngleToRadian(const double angle) { if((angle >= MINANGLE) && (angle <= MAXANGLE)) return (angle * D_PI/180.0); else return 0.0; } double CalDifSpeedInSphere::RadianToAngle(const double radian) { if((radian >=MINRADIAN) && (radian <=MAXRADIAN)) return (radian *180.0/D_PI); else return 0.0; } void CalDifSpeedInSphere::updatePWMValueByRatio(double Ratio) { // quint16 m_leftValue,m_rightValue; m_leftValue = m_PWMLeftByConfig; m_rightValue = m_leftValue / Ratio; // MinPWMValue = 300, //MaxPWMValue = 2100, if(m_rightValue >= MaxPWMValue) { m_rightValue = MaxPWMValue; m_leftValue = m_rightValue * Ratio; } if(m_rightValue <= MinPWMValue) { m_rightValue = MinPWMValue; m_leftValue = m_rightValue *Ratio; } // ui->showChangedLeftPWM->setText(QString::number(m_leftValue)); ui->showChangedRightPWM->setText(QString::number(m_rightValue)); m_changedPWMLeft = m_leftValue; m_changedPWMRight = m_rightValue; } void CalDifSpeedInSphere::slUpdatePWMValueByConfig(EnumPWMType PWMType, quint16 value) { switch (PWMType) { case PWMLeftByConfig: ui->showCurLeftPWM->setText(QString::number(value)); m_PWMLeftByConfig = value; break; case PWMRightByConfig: ui->showCurRightPWM->setText(QString::number(value)); m_PWMRightByConfig =value; break; default: break; } } void CalDifSpeedInSphere::on_CenterAngle_editingFinished() { double radian = this->AngleToRadian(ui->CenterAngle->value()); this->setRadianOfCrawlerCenter(radian); //求出环向周长 double perimeter = radianCenterToPerimeter(radian); ui->perimeterSpinBox->setValue(perimeter); } void CalDifSpeedInSphere::on_crawlerWidth_editingFinished() { this->setCrawlerWidth(ui->crawlerWidth->value()); } void CalDifSpeedInSphere::on_radiusOfSphere_editingFinished() { this->setRadiusOfSphere(RadiusSp(ui->radiusOfSphere->value())); } void CalDifSpeedInSphere::on_pushButton_clicked() { // double radius = ui->radiusOfSphere->value(); double width = ui->crawlerWidth->value(); double radian = this->AngleToRadian(ui->CenterAngle->value()); double ratioValue = this->getCrawlerBothSidesRatio_Sin(RadiusSp(radius),CrawlerWidth(width),RadianCenter(radian)); ui->showRatioLabel->setText(QString::number(ratioValue,'f',2)); this->updatePWMValueByRatio(ratioValue); } void CalDifSpeedInSphere::on_pushButton_2_clicked() { double radius = ui->radiusOfSphere->value(); double width = ui->crawlerWidth->value(); double radian = this->AngleToRadian(ui->CenterAngle->value()); double ratioValue = this->getCrawlerBothSidesRatio_Sin(RadiusSp(radius),CrawlerWidth(width),RadianCenter(radian)); ui->showRatioLabel->setText(QString::number(1/ratioValue,'f',2)); this->updatePWMValueByRatio(1/ratioValue); } void CalDifSpeedInSphere::initUI() { CrawlerStatusParam *crawlerStatus = CrawlerStatusParam::getInstance(); connect(crawlerStatus,SIGNAL(sgUpdatePWMValueByConfig(EnumPWMType,quint16)),this,SLOT(slUpdatePWMValueByConfig(EnumPWMType,quint16))); m_PWMLeftByConfig =crawlerStatus->getCurPWMValueByConfig(PWMLeftByConfig); m_PWMRightByConfig = crawlerStatus->getCurPWMValueByConfig(PWMRightByConfig); m_changedPWMLeft = m_PWMLeftByConfig; m_changedPWMRight = m_PWMRightByConfig; ui->showCurLeftPWM->setText(QString::number(m_PWMLeftByConfig)); ui->showCurRightPWM->setText(QString::number(m_PWMRightByConfig)); ui->showChangedLeftPWM->setText(QString::number(m_PWMLeftByConfig)); ui->showChangedRightPWM->setText(QString::number(m_PWMLeftByConfig)); } void CalDifSpeedInSphere::on_changedPWMValueBtn_clicked() { CrawlerSerial *crawlerSerial = CrawlerSerial::getInstance(); crawlerSerial->setPWMValue(PWMLeftByConfig,m_changedPWMLeft); crawlerSerial->setPWMValue(PWMRightByConfig,m_changedPWMRight); } void CalDifSpeedInSphere::on_clearChangedBtn_clicked() { CrawlerSerial *crawlerSerial = CrawlerSerial::getInstance(); crawlerSerial->setPWMValue(PWMLeftByConfig,m_PWMLeftByConfig); crawlerSerial->setPWMValue(PWMRightByConfig,m_PWMLeftByConfig); ui->showChangedLeftPWM->setText(QString::number(m_PWMLeftByConfig)); ui->showChangedRightPWM->setText(QString::number(m_PWMLeftByConfig)); m_changedPWMLeft = m_PWMLeftByConfig; m_changedPWMRight = m_PWMLeftByConfig; } void CalDifSpeedInSphere::on_perimeterSpinBox_editingFinished() { double perimeter = ui->perimeterSpinBox->value(); double radian = this->perimeterToRadianCenter(perimeter); double angle = this->RadianToAngle(radian); ui->CenterAngle->setValue(angle); }
[ "836430025@qq.com" ]
836430025@qq.com
b67fe585199d40232b35a680a712de1f6c3666e7
895b3f891d4aab73f13f93091183477e7ba5c89f
/src/ewc_base/wnd/impl_wx/iwnd_checkbox.cpp
f9dbc7d9af33dde8f2af27d8a988af3345e8f954
[ "Apache-2.0" ]
permissive
luoxz-ai/ew_base
6e63877d0dcd992171e43729c804cc72018d0f19
8186f63d3e9ddbc16e63c807fec9140f28bc27b6
refs/heads/master
2021-06-20T02:24:11.759172
2017-08-09T09:22:54
2017-08-09T09:22:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
cpp
#include "ewc_base/wnd/impl_wx/iwnd_checkbox.h" EW_ENTER IWnd_checkbox::IWnd_checkbox(wxWindow* p,const WndPropertyEx& h) :wxCheckBox(p,h.id(),h.label(),h,h) { this->Connect(wxEVT_CHECKBOX,wxCommandEventHandler(IWnd_controlT<IWnd_checkbox>::OnCommandIntChanged)); } template<> class ValidatorW<IWnd_checkbox> : public Validator { public: LitePtrT<IWnd_checkbox> pWindow; wxWindow* GetWindow(){return pWindow;} ValidatorW(IWnd_checkbox* w):pWindow(w) { pWindow->m_pVald.reset(this); } virtual bool DoSetValue(int32_t v) { pWindow->SetValue(v!=0); return true; } virtual bool DoGetValue(int32_t& v) { v=pWindow->GetValue()?1:0; return true; } }; template<> class WndInfoT<IWnd_checkbox> : public WndInfoBaseT<IWnd_checkbox> { public: WndInfoT(const String& s):WndInfoBaseT<IWnd_checkbox>(s) { } virtual Validator* CreateValidator(wxWindow* w,EvtProxyT<int32_t>* p) { return CreateValidatorBaseT(w,p); } Validator* CreateValidator(wxWindow* w) { return new ValidatorW<IWnd_checkbox>((IWnd_checkbox*)w); } }; template<> void WndInfoManger_Register<IWnd_checkbox>(WndInfoManger& imgr,const String& name) { static WndInfoT<IWnd_checkbox> info(name); imgr.Register(&info); } EW_LEAVE
[ "hanwd@eastfdtd.com" ]
hanwd@eastfdtd.com
7e89e54ca5656841a62f0bf5a3c25906397c560e
99857bc88436220187db7a948c67b6c8a18f9946
/stl/iterator_tag_with_traits.cpp
a36a16bdbb0be5ef609e64cd3b120d1b578ae736
[ "MIT" ]
permissive
frankbearzou/c-cpp-demo
162fb8bef0399a67da6b03f566e4191dd65328c7
523b49b1b279d99d495414cf8e620c907beb2788
refs/heads/master
2021-05-30T04:47:57.743807
2015-12-13T01:29:14
2015-12-13T01:29:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
835
cpp
#include <iostream> #include <iterator> using namespace std; struct rand_tag { }; struct bi_tag { }; struct bi_iter : public iterator<bi_tag, float> { }; struct rand_iter : public iterator<rand_tag, int> { }; template<class _Ty, class Dis> void adv(_Ty iter, Dis n, rand_tag) { cout << "rand adv" << endl; } template<class _Ty, class Dis> void adv(_Ty iter, Dis n, bi_tag) { cout << "bi adv" << endl; } template<class _Ty> typename iterator_traits<_Ty>::iterator_category iter_cast(const _Ty&) { typename iterator_traits<_Ty>::iterator_category cat; return (cat); } template<class _Ty, class Dis> void adv(_Ty& iter, Dis n) { // adv(iter, n, typename iterator_traits<_Ty>::iterator_category()); adv(iter, n, iter_cast(iter)); } void main() { rand_iter i; adv(i, 3); bi_iter f; adv(f, 4); system("pause"); }
[ "frankbearzou@gmail.com" ]
frankbearzou@gmail.com
a2591ff92757e1f0d0c4b1755eb400cca86b9a04
4f951e96accafe3ae8f687d18e142a8c9c657d05
/foundation_questions/q28.cpp
cd70de54433558f58ef7dad9295004189a5a2b18
[]
no_license
amey16/Important-codes
ef9ef780d81f57198959ad784b242b284d89c4af
6ddee5e4c52bdefbbf0bbcf13b6c7b852ce67746
refs/heads/master
2022-06-20T12:10:49.642747
2020-05-12T09:15:51
2020-05-12T09:15:51
260,652,677
0
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
#include<iostream> using namespace std; int main(int argc,char** argv){ int n; cin>>n; int s[n],cnt=0; for(int i=0;i<n;i++) cin>>s[i]; for(int i=0;i<n-1;i++){ if(cnt==2) break; else if(s[i+1]<s[i] && cnt==0) continue; else if(s[i+1]>s[i] && cnt==0){ cnt++; continue; } else if(s[i+1]<s[i] && cnt==1){ cnt++; continue; } else { continue; } } if(cnt==2) cout<<"False"<<endl; else cout<<"True"<<endl; }
[ "ameyagupta19@gmail.com" ]
ameyagupta19@gmail.com
4520f343c082ebec51fdb866b60efd9ad6106dbb
4f72aa73fd32b64f68ac837fa15f77d95b313550
/src/qt/sendcoinsentry.cpp
79dc4fb39df26b34606c70c67fe962143e6cead9
[ "MIT" ]
permissive
wecarecoin/wecarecoin
1ca2925b9d5f9304c675c4d6fa5d69afa0055f73
60f9eaa6c9bc7e996ef99a03e615403bff59ac70
refs/heads/master
2021-04-28T04:40:10.130141
2018-02-20T07:51:21
2018-02-20T07:51:21
122,165,953
0
0
null
null
null
null
UTF-8
C++
false
false
4,294
cpp
#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a wecare address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
[ "34125545+wecarecoin@users.noreply.github.com" ]
34125545+wecarecoin@users.noreply.github.com
2805a4352681e4161f0c683b344636a7cb207712
397e445e7c333731d1692d63bcb54f20f34104d0
/Allenamenti_OII/barbablu.cpp
b01a0c07509354c5a2af8799378097c144831eb4
[]
no_license
xYinXiao/School
e66399e80dcdb9d60e3740df8812e5d1be38379a
e3a2999168050100a03ccf095ae9bbcac916814d
refs/heads/master
2021-01-10T01:17:58.024574
2017-04-07T09:34:39
2017-04-07T09:34:39
47,881,543
0
0
null
null
null
null
UTF-8
C++
false
false
2,206
cpp
#include <stdio.h> #include <assert.h> #include <vector> #include <algorithm> #include <set> #include <limits.h> using namespace std; vector<int> isAria(31, 0); int nCabine, nCorridoi, tesoro, nAria; struct edge { int to, length; }; struct Cmp { bool operator()(const pair<int, pair<int, int> >& a, const pair<int, pair<int, int> >&b) { return a.first < b.first; } }; int dijkstra(const vector< vector<edge> >& graph, int sorgente, int destinazione) { vector<int> distanze_minime(graph.size() + 1, INT_MAX); set< pair<int, pair<int, int> >, Cmp> nodi_attivi; int ossigeno = 20; distanze_minime[sorgente] = 0; nodi_attivi.insert( {0, {sorgente, ossigeno}} ); set< pair<int, pair<int, int> >, Cmp>::iterator it; while(!nodi_attivi.empty()) { int u = nodi_attivi.begin()->second.first; if (u == destinazione) return distanze_minime[u]; it = nodi_attivi.find({distanze_minime[u], {u, ossigeno} }); ossigeno = (*it).second.second; nodi_attivi.erase(nodi_attivi.begin()); for(edge dge : graph[u]) { if ((distanze_minime[dge.to] > distanze_minime[u] + dge.length) && (ossigeno - dge.length > 0)) { nodi_attivi.erase({distanze_minime[dge.to], {dge.to, ossigeno} }); distanze_minime[dge.to] = distanze_minime[u] + dge.length; nodi_attivi.insert({distanze_minime[dge.to], {dge.to, ((isAria[dge.to]) ? 20 : ossigeno - dge.length)} }); } } } return INT_MAX; } int main() { FILE *in, *out; int i; vector< vector <edge> > graph(31); in = fopen("input.txt", "r"); out = fopen("output.txt", "w"); fscanf(in, "%d%d%d%d", &nCabine, &nCorridoi, &tesoro, &nAria); int a, b, peso; for(i = 0;i < nAria;i++) { fscanf(in, "%d", &a); isAria[a] = 1; } for(i = 0;i < nCorridoi;i++) { fscanf(in, "%d%d%d", &a, &b, &peso); graph[a].push_back({b, peso}); graph[b].push_back({a, peso}); } int dist = dijkstra(graph, 1, tesoro); fprintf(out, "%d", ((dist != INT_MAX) ? dist : -1)); fclose(in); fclose(out); return 0; }
[ "xyinxiao@gmail.com" ]
xyinxiao@gmail.com
1e877ae6351c9ca2863ad0851a89372d1d10d79d
a720e508022ea15fcfd7aa311b596aaf68cc56b8
/HW2/Homework2.3.cpp
64a342cd6fc984da8760b57d6bdbb02559250bc8
[]
no_license
yterry/MF703_CPP_Projects
29b52c4a9fd7710071191da22273cd0e61f8d6e2
8358dc604b562af461b46a7ae44387c471a4a5c8
refs/heads/master
2021-01-09T21:48:19.549624
2016-02-05T02:08:29
2016-02-05T02:08:29
51,119,954
2
0
null
null
null
null
UTF-8
C++
false
false
1,344
cpp
// Homework2.3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "iostream" #include "vector" using namespace std; //function reverseDigits //takes an integer value and returns the number with its digits reversed int reverseDigits(long int num) { long int n = 1;//counts number of digits long int deno = 10;//denominator long int quotient; long int i; long int reverse=0; vector<int> v;//stores every digit bool t = true;//boolean value while (t) { quotient = num / deno; deno = deno * 10; if (quotient == 0) { t = false; } else { n += 1; } } //store each digit to vector v for (i = 0; i < n;i++) { quotient = num / pow(10, n - i - 1); v.push_back(quotient); num = num - quotient*pow(10, n - i - 1); } //rearrange the digits for (i = 0; i < n; i++) { reverse += v[i] * pow(10, i); } return reverse; } int driver() { //ask the user to input number to be reversed bool t = true; while (t) { long int num; long int b; cout << "Please enter a number to be reversed: "; cin >> num; cout << "\n"; cout << "This is the reversed number :" << reverseDigits(num) << "\n"; cout << "Do you want to compute another number ? (-1 to exit): "; cin >> b; cout << "\n"; if (b == -1)t = false; } return 0; } int main() { driver(); return 0; }
[ "yterry@bu.edu" ]
yterry@bu.edu
be4e5dac92c8380bfbfb6e0e2ea4eb003314f52e
b67a780af96a1b70569f81def205f2adbe328292
/Demo/String/SubString/BFSubString.cpp
39c6ac1a77fc44feaed94c7d20723d1933d5e83f
[]
no_license
doquanghuy/Algorithm
8c27933c5c42b4324b39e061c43542adf4a6372b
4dd63edd823bd0a158034e281c37ef1f6704ec9c
refs/heads/master
2020-04-13T18:52:44.872226
2019-01-16T15:04:48
2019-01-16T15:04:48
163,387,254
0
0
null
2019-01-16T14:21:06
2018-12-28T08:36:31
null
UTF-8
C++
false
false
611
cpp
// // BFSubString.cpp // Demo // // Created by Quang Huy on 1/11/19. // Copyright © 2019 Techmaster. All rights reserved. // #include "BFSubString.hpp" BFSubString:: BFSubString(std:: string pat) { this -> pat = pat; } unsigned long BFSubString:: search(std:: string txt) { unsigned long M = pat.length(); unsigned long N = txt.length(); for (int i = 0; i < N - M; i++) { for (int j = 0; j < M; j++) { if (pat[j] != txt[i + j]) { break; } else if (j == M - 1) { return i; } } } return N; }
[ "sin.do@mobiclixgroup.com" ]
sin.do@mobiclixgroup.com
0e7a8c8d7ccca816988a6b70ba1488421272e6f9
2a5cb1983b0760e15806e66d54b4310aa7e0c47e
/init_mix/d3dUtility.cpp
e5f6d2a89f2454b8d3d09432590b51cbb9245c81
[]
no_license
joker-hyt/directx_test
5914db56303cfc145bede9c4a014efd1440a38c1
e8c8ab76dffa8209f3d03497ccff8337905d88ab
refs/heads/master
2020-12-19T12:56:36.771328
2020-06-23T12:01:53
2020-06-23T12:01:53
235,739,799
0
0
null
null
null
null
GB18030
C++
false
false
4,316
cpp
#include "stdafx.h" #include "d3dUtility.h" #include "Resource.h" HINSTANCE hInst; // 当前实例 TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 D3DMATERIAL9 d3d::InitMtrl(D3DXCOLOR a, D3DXCOLOR d, D3DXCOLOR s, D3DXCOLOR e, float p) { D3DMATERIAL9 mtrl; mtrl.Ambient = a; mtrl.Diffuse = d; mtrl.Specular = s; mtrl.Emissive = e; mtrl.Power = p; return mtrl; } BOOL d3d::InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // 将实例句柄存储在全局变量中 hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION); D3DCAPS9 caps; d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps); int vp = 0; if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) { vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; } else { vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; } D3DPRESENT_PARAMETERS d3dpp; d3dpp.BackBufferWidth = 800; d3dpp.BackBufferHeight = 600; d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.MultiSampleQuality = 0; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = hWnd; d3dpp.Windowed = true; d3dpp.EnableAutoDepthStencil = true; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.Flags = 0; d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; HRESULT hr = d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, vp, &d3dpp, &device); if(FAILED(hr)) { MessageBox(hWnd, _T("Create Device Failed"), 0, 0); } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } ATOM d3d::MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = d3d::WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_INIT)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_INIT); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } LRESULT CALLBACK d3d::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (msg) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // 分析菜单选择: switch (wmId) { case IDM_ABOUT: //DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: 在此添加任意绘图代码... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } bool d3d::InitD3D(HINSTANCE hInstance, int width, int height, bool windowed, int nCmdShow, D3DDEVTYPE deviceType, IDirect3DDevice9** device) { // 初始化全局字符串 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_INIT, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // 执行应用程序初始化: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } return TRUE; } int d3d::EnterMsgLoop(bool (*ptr_display)(float timeDelta)) { MSG msg; ZeroMemory(&msg, sizeof(msg)); static float lastTime = (float)timeGetTime(); while(msg.message != WM_QUIT) { if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { float currTime = (float)timeGetTime(); float timeDelta = (currTime - lastTime) * 0.001f; ptr_display(timeDelta); lastTime = currTime; } } return 0; }
[ "joker.hyt@gmail.com" ]
joker.hyt@gmail.com
258e69e6f40282252ab6022252d0ac2a4e8e35e3
b98f824600c00343851917c646ed3430755e2eea
/inet/src/inet/physicallayer/base/packetlevel/FlatReceptionBase_m.cc
aa2ba5460814dff350e0250b18a9dee0be1fbefa
[]
no_license
ZitaoLi/tsn_omnetpp_nesting_rev
7be3e15957a16b9d3071d6526e2a4d19e236e6e6
23ab3a2e9cffa5d01a5297547e7e8a71a66b60c8
refs/heads/master
2020-05-07T22:23:45.523901
2019-04-12T10:49:40
2019-04-12T10:49:40
180,943,408
1
0
null
null
null
null
UTF-8
C++
false
false
14,144
cc
// // Generated file, do not edit! Created by nedtool 5.4 from inet/physicallayer/base/packetlevel/FlatReceptionBase.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include <memory> #include "FlatReceptionBase_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i = 0; i < n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i = 0; i < n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i = 0; i < n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace { template <class T> inline typename std::enable_if<std::is_polymorphic<T>::value && std::is_base_of<omnetpp::cObject,T>::value, void *>::type toVoidPtr(T* t) { return (void *)(static_cast<const omnetpp::cObject *>(t)); } template <class T> inline typename std::enable_if<std::is_polymorphic<T>::value && !std::is_base_of<omnetpp::cObject,T>::value, void *>::type toVoidPtr(T* t) { return (void *)dynamic_cast<const void *>(t); } template <class T> inline typename std::enable_if<!std::is_polymorphic<T>::value, void *>::type toVoidPtr(T* t) { return (void *)static_cast<const void *>(t); } } namespace inet { namespace physicallayer { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule to generate operator<< for shared_ptr<T> template<typename T> inline std::ostream& operator<<(std::ostream& out,const std::shared_ptr<T>& t) { return out << t.get(); } // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } class FlatReceptionBaseDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; enum FieldConstants { }; public: FlatReceptionBaseDescriptor(); virtual ~FlatReceptionBaseDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(FlatReceptionBaseDescriptor) FlatReceptionBaseDescriptor::FlatReceptionBaseDescriptor() : omnetpp::cClassDescriptor(omnetpp::opp_typename(typeid(inet::physicallayer::FlatReceptionBase)), "inet::physicallayer::NarrowbandReceptionBase") { propertynames = nullptr; } FlatReceptionBaseDescriptor::~FlatReceptionBaseDescriptor() { delete[] propertynames; } bool FlatReceptionBaseDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<FlatReceptionBase *>(obj)!=nullptr; } const char **FlatReceptionBaseDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { "existingClass", "descriptor", nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *FlatReceptionBaseDescriptor::getProperty(const char *propertyname) const { if (!strcmp(propertyname, "existingClass")) return ""; if (!strcmp(propertyname, "descriptor")) return "readonly"; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int FlatReceptionBaseDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 0+basedesc->getFieldCount() : 0; } unsigned int FlatReceptionBaseDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } return 0; } const char *FlatReceptionBaseDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } return nullptr; } int FlatReceptionBaseDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->findField(fieldName) : -1; } const char *FlatReceptionBaseDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } return nullptr; } const char **FlatReceptionBaseDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *FlatReceptionBaseDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int FlatReceptionBaseDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp; switch (field) { default: return 0; } } const char *FlatReceptionBaseDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp; switch (field) { default: return nullptr; } } std::string FlatReceptionBaseDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp; switch (field) { default: return ""; } } bool FlatReceptionBaseDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp; switch (field) { default: return false; } } const char *FlatReceptionBaseDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } return nullptr; } void *FlatReceptionBaseDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace physicallayer } // namespace inet
[ "494240799@qq.com" ]
494240799@qq.com
e4a82641755c4cd9e5bcfb953811fc9c51efa231
be662d258a2ba20b7b94943c1cfd2ebc1fda0bd4
/VulkanSupport/Vendor/tinyobjloader/tiny_obj_loader.h
fdbdfb9d3dcb35137f644dd5c2b9924983742028
[ "Apache-2.0" ]
permissive
xRiveria/Crescent
c4d6e5f3143e4ca4c97831a207c696d8ae8c7183
b6512b6a8dab2d27cf542c562ccc28f21bf2345d
refs/heads/master
2023-08-17T20:30:28.444093
2021-09-26T11:42:01
2021-09-26T11:42:01
320,224,982
5
0
null
null
null
null
UTF-8
C++
false
false
119,464
h
#pragma once /* The MIT License (MIT) Copyright (c) 2012-Present, Syoyo Fujita and many contributors. 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. */ // // version 2.0.0 : Add new object oriented API. 1.x API is still provided. // * Support line primitive. // * Support points primitive. // * Support multiple search path for .mtl(v1 API). // * Support vertex weight `vw`(as an tinyobj extension) // * Support escaped whitespece in mtllib // version 1.4.0 : Modifed ParseTextureNameAndOption API // version 1.3.1 : Make ParseTextureNameAndOption API public // version 1.3.0 : Separate warning and error message(breaking API of LoadObj) // version 1.2.3 : Added color space extension('-colorspace') to tex opts. // version 1.2.2 : Parse multiple group names. // version 1.2.1 : Added initial support for line('l') primitive(PR #178) // version 1.2.0 : Hardened implementation(#175) // version 1.1.1 : Support smoothing groups(#162) // version 1.1.0 : Support parsing vertex color(#144) // version 1.0.8 : Fix parsing `g` tag just after `usemtl`(#138) // version 1.0.7 : Support multiple tex options(#126) // version 1.0.6 : Add TINYOBJLOADER_USE_DOUBLE option(#124) // version 1.0.5 : Ignore `Tr` when `d` exists in MTL(#43) // version 1.0.4 : Support multiple filenames for 'mtllib'(#112) // version 1.0.3 : Support parsing texture options(#85) // version 1.0.2 : Improve parsing speed by about a factor of 2 for large // files(#105) // version 1.0.1 : Fixes a shape is lost if obj ends with a 'usemtl'(#104) // version 1.0.0 : Change data structure. Change license from BSD to MIT. // // // Use this in *one* .cc // #define TINYOBJLOADER_IMPLEMENTATION // #include "tiny_obj_loader.h" // #ifndef TINY_OBJ_LOADER_H_ #define TINY_OBJ_LOADER_H_ #include <map> #include <string> #include <vector> namespace tinyobj { // TODO(syoyo): Better C++11 detection for older compiler #if __cplusplus > 199711L #define TINYOBJ_OVERRIDE override #else #define TINYOBJ_OVERRIDE #endif #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #pragma clang diagnostic ignored "-Wpadded" #endif // https://en.wikipedia.org/wiki/Wavefront_.obj_file says ... // // -blendu on | off # set horizontal texture blending // (default on) // -blendv on | off # set vertical texture blending // (default on) // -boost real_value # boost mip-map sharpness // -mm base_value gain_value # modify texture map values (default // 0 1) // # base_value = brightness, // gain_value = contrast // -o u [v [w]] # Origin offset (default // 0 0 0) // -s u [v [w]] # Scale (default // 1 1 1) // -t u [v [w]] # Turbulence (default // 0 0 0) // -texres resolution # texture resolution to create // -clamp on | off # only render texels in the clamped // 0-1 range (default off) // # When unclamped, textures are // repeated across a surface, // # when clamped, only texels which // fall within the 0-1 // # range are rendered. // -bm mult_value # bump multiplier (for bump maps // only) // // -imfchan r | g | b | m | l | z # specifies which channel of the file // is used to // # create a scalar or bump texture. // r:red, g:green, // # b:blue, m:matte, l:luminance, // z:z-depth.. // # (the default for bump is 'l' and // for decal is 'm') // bump -imfchan r bumpmap.tga # says to use the red channel of // bumpmap.tga as the bumpmap // // For reflection maps... // // -type sphere # specifies a sphere for a "refl" // reflection map // -type cube_top | cube_bottom | # when using a cube map, the texture // file for each // cube_front | cube_back | # side of the cube is specified // separately // cube_left | cube_right // // TinyObjLoader extension. // // -colorspace SPACE # Color space of the texture. e.g. // 'sRGB` or 'linear' // #ifdef TINYOBJLOADER_USE_DOUBLE //#pragma message "using double" typedef double real_t; #else //#pragma message "using float" typedef float real_t; #endif typedef enum { TEXTURE_TYPE_NONE, // default TEXTURE_TYPE_SPHERE, TEXTURE_TYPE_CUBE_TOP, TEXTURE_TYPE_CUBE_BOTTOM, TEXTURE_TYPE_CUBE_FRONT, TEXTURE_TYPE_CUBE_BACK, TEXTURE_TYPE_CUBE_LEFT, TEXTURE_TYPE_CUBE_RIGHT } texture_type_t; struct texture_option_t { texture_type_t type; // -type (default TEXTURE_TYPE_NONE) real_t sharpness; // -boost (default 1.0?) real_t brightness; // base_value in -mm option (default 0) real_t contrast; // gain_value in -mm option (default 1) real_t origin_offset[3]; // -o u [v [w]] (default 0 0 0) real_t scale[3]; // -s u [v [w]] (default 1 1 1) real_t turbulence[3]; // -t u [v [w]] (default 0 0 0) int texture_resolution; // -texres resolution (No default value in the spec. // We'll use -1) bool clamp; // -clamp (default false) char imfchan; // -imfchan (the default for bump is 'l' and for decal is 'm') bool blendu; // -blendu (default on) bool blendv; // -blendv (default on) real_t bump_multiplier; // -bm (for bump maps only, default 1.0) // extension std::string colorspace; // Explicitly specify color space of stored texel // value. Usually `sRGB` or `linear` (default empty). }; struct material_t { std::string name; real_t ambient[3]; real_t diffuse[3]; real_t specular[3]; real_t transmittance[3]; real_t emission[3]; real_t shininess; real_t ior; // index of refraction real_t dissolve; // 1 == opaque; 0 == fully transparent // illumination model (see http://www.fileformat.info/format/material/) int illum; int dummy; // Suppress padding warning. std::string ambient_texname; // map_Ka std::string diffuse_texname; // map_Kd std::string specular_texname; // map_Ks std::string specular_highlight_texname; // map_Ns std::string bump_texname; // map_bump, map_Bump, bump std::string displacement_texname; // disp std::string alpha_texname; // map_d std::string reflection_texname; // refl texture_option_t ambient_texopt; texture_option_t diffuse_texopt; texture_option_t specular_texopt; texture_option_t specular_highlight_texopt; texture_option_t bump_texopt; texture_option_t displacement_texopt; texture_option_t alpha_texopt; texture_option_t reflection_texopt; // PBR extension // http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr real_t roughness; // [0, 1] default 0 real_t metallic; // [0, 1] default 0 real_t sheen; // [0, 1] default 0 real_t clearcoat_thickness; // [0, 1] default 0 real_t clearcoat_roughness; // [0, 1] default 0 real_t anisotropy; // aniso. [0, 1] default 0 real_t anisotropy_rotation; // anisor. [0, 1] default 0 real_t pad0; std::string roughness_texname; // map_Pr std::string metallic_texname; // map_Pm std::string sheen_texname; // map_Ps std::string emissive_texname; // map_Ke std::string normal_texname; // norm. For normal mapping. texture_option_t roughness_texopt; texture_option_t metallic_texopt; texture_option_t sheen_texopt; texture_option_t emissive_texopt; texture_option_t normal_texopt; int pad2; std::map<std::string, std::string> unknown_parameter; #ifdef TINY_OBJ_LOADER_PYTHON_BINDING // For pybind11 std::array<double, 3> GetDiffuse() { std::array<double, 3> values; values[0] = double(diffuse[0]); values[1] = double(diffuse[1]); values[2] = double(diffuse[2]); return values; } std::array<double, 3> GetSpecular() { std::array<double, 3> values; values[0] = double(specular[0]); values[1] = double(specular[1]); values[2] = double(specular[2]); return values; } std::array<double, 3> GetTransmittance() { std::array<double, 3> values; values[0] = double(transmittance[0]); values[1] = double(transmittance[1]); values[2] = double(transmittance[2]); return values; } std::array<double, 3> GetEmission() { std::array<double, 3> values; values[0] = double(emission[0]); values[1] = double(emission[1]); values[2] = double(emission[2]); return values; } std::array<double, 3> GetAmbient() { std::array<double, 3> values; values[0] = double(ambient[0]); values[1] = double(ambient[1]); values[2] = double(ambient[2]); return values; } void SetDiffuse(std::array<double, 3>& a) { diffuse[0] = real_t(a[0]); diffuse[1] = real_t(a[1]); diffuse[2] = real_t(a[2]); } void SetAmbient(std::array<double, 3>& a) { ambient[0] = real_t(a[0]); ambient[1] = real_t(a[1]); ambient[2] = real_t(a[2]); } void SetSpecular(std::array<double, 3>& a) { specular[0] = real_t(a[0]); specular[1] = real_t(a[1]); specular[2] = real_t(a[2]); } void SetTransmittance(std::array<double, 3>& a) { transmittance[0] = real_t(a[0]); transmittance[1] = real_t(a[1]); transmittance[2] = real_t(a[2]); } std::string GetCustomParameter(const std::string& key) { std::map<std::string, std::string>::const_iterator it = unknown_parameter.find(key); if (it != unknown_parameter.end()) { return it->second; } return std::string(); } #endif }; struct tag_t { std::string name; std::vector<int> intValues; std::vector<real_t> floatValues; std::vector<std::string> stringValues; }; struct joint_and_weight_t { int joint_id; real_t weight; }; struct skin_weight_t { int vertex_id; // Corresponding vertex index in `attrib_t::vertices`. // Compared to `index_t`, this index must be positive and // start with 0(does not allow relative indexing) std::vector<joint_and_weight_t> weightValues; }; // Index struct to support different indices for vtx/normal/texcoord. // -1 means not used. struct index_t { int vertex_index; int normal_index; int texcoord_index; }; struct mesh_t { std::vector<index_t> indices; std::vector<unsigned char> num_face_vertices; // The number of vertices per // face. 3 = triangle, 4 = quad, // ... Up to 255 vertices per face. std::vector<int> material_ids; // per-face material ID std::vector<unsigned int> smoothing_group_ids; // per-face smoothing group // ID(0 = off. positive value // = group id) std::vector<tag_t> tags; // SubD tag }; // struct path_t { // std::vector<int> indices; // pairs of indices for lines //}; struct lines_t { // Linear flattened indices. std::vector<index_t> indices; // indices for vertices(poly lines) std::vector<int> num_line_vertices; // The number of vertices per line. }; struct points_t { std::vector<index_t> indices; // indices for points }; struct shape_t { std::string name; mesh_t mesh; lines_t lines; points_t points; }; // Vertex attributes struct attrib_t { std::vector<real_t> vertices; // 'v'(xyz) // For backward compatibility, we store vertex weight in separate array. std::vector<real_t> vertex_weights; // 'v'(w) std::vector<real_t> normals; // 'vn' std::vector<real_t> texcoords; // 'vt'(uv) // For backward compatibility, we store texture coordinate 'w' in separate // array. std::vector<real_t> texcoord_ws; // 'vt'(w) std::vector<real_t> colors; // extension: vertex colors // // TinyObj extension. // // NOTE(syoyo): array index is based on the appearance order. // To get a corresponding skin weight for a specific vertex id `vid`, // Need to reconstruct a look up table: `skin_weight_t::vertex_id` == `vid` // (e.g. using std::map, std::unordered_map) std::vector<skin_weight_t> skin_weights; attrib_t() {} // // For pybind11 // const std::vector<real_t>& GetVertices() const { return vertices; } const std::vector<real_t>& GetVertexWeights() const { return vertex_weights; } }; struct callback_t { // W is optional and set to 1 if there is no `w` item in `v` line void (*vertex_cb)(void* user_data, real_t x, real_t y, real_t z, real_t w); void (*normal_cb)(void* user_data, real_t x, real_t y, real_t z); // y and z are optional and set to 0 if there is no `y` and/or `z` item(s) in // `vt` line. void (*texcoord_cb)(void* user_data, real_t x, real_t y, real_t z); // called per 'f' line. num_indices is the number of face indices(e.g. 3 for // triangle, 4 for quad) // 0 will be passed for undefined index in index_t members. void (*index_cb)(void* user_data, index_t* indices, int num_indices); // `name` material name, `material_id` = the array index of material_t[]. -1 // if // a material not found in .mtl void (*usemtl_cb)(void* user_data, const char* name, int material_id); // `materials` = parsed material data. void (*mtllib_cb)(void* user_data, const material_t* materials, int num_materials); // There may be multiple group names void (*group_cb)(void* user_data, const char** names, int num_names); void (*object_cb)(void* user_data, const char* name); callback_t() : vertex_cb(NULL), normal_cb(NULL), texcoord_cb(NULL), index_cb(NULL), usemtl_cb(NULL), mtllib_cb(NULL), group_cb(NULL), object_cb(NULL) {} }; class MaterialReader { public: MaterialReader() {} virtual ~MaterialReader(); virtual bool operator()(const std::string& matId, std::vector<material_t>* materials, std::map<std::string, int>* matMap, std::string* warn, std::string* err) = 0; }; /// /// Read .mtl from a file. /// class MaterialFileReader : public MaterialReader { public: // Path could contain separator(';' in Windows, ':' in Posix) explicit MaterialFileReader(const std::string& mtl_basedir) : m_mtlBaseDir(mtl_basedir) {} virtual ~MaterialFileReader() TINYOBJ_OVERRIDE {} virtual bool operator()(const std::string& matId, std::vector<material_t>* materials, std::map<std::string, int>* matMap, std::string* warn, std::string* err) TINYOBJ_OVERRIDE; private: std::string m_mtlBaseDir; }; /// /// Read .mtl from a stream. /// class MaterialStreamReader : public MaterialReader { public: explicit MaterialStreamReader(std::istream& inStream) : m_inStream(inStream) {} virtual ~MaterialStreamReader() TINYOBJ_OVERRIDE {} virtual bool operator()(const std::string& matId, std::vector<material_t>* materials, std::map<std::string, int>* matMap, std::string* warn, std::string* err) TINYOBJ_OVERRIDE; private: std::istream& m_inStream; }; // v2 API struct ObjReaderConfig { bool triangulate; // triangulate polygon? /// Parse vertex color. /// If vertex color is not present, its filled with default value. /// false = no vertex color /// This will increase memory of parsed .obj bool vertex_color; /// /// Search path to .mtl file. /// Default = "" = search from the same directory of .obj file. /// Valid only when loading .obj from a file. /// std::string mtl_search_path; ObjReaderConfig() : triangulate(true), vertex_color(true) {} }; /// /// Wavefront .obj reader class(v2 API) /// class ObjReader { public: ObjReader() : valid_(false) {} ~ObjReader() {} /// /// Load .obj and .mtl from a file. /// /// @param[in] filename wavefront .obj filename /// @param[in] config Reader configuration /// bool ParseFromFile(const std::string& filename, const ObjReaderConfig& config = ObjReaderConfig()); /// /// Parse .obj from a text string. /// Need to supply .mtl text string by `mtl_text`. /// This function ignores `mtllib` line in .obj text. /// /// @param[in] obj_text wavefront .obj filename /// @param[in] mtl_text wavefront .mtl filename /// @param[in] config Reader configuration /// bool ParseFromString(const std::string& obj_text, const std::string& mtl_text, const ObjReaderConfig& config = ObjReaderConfig()); /// /// .obj was loaded or parsed correctly. /// bool Valid() const { return valid_; } const attrib_t& GetAttrib() const { return attrib_; } const std::vector<shape_t>& GetShapes() const { return shapes_; } const std::vector<material_t>& GetMaterials() const { return materials_; } /// /// Warning message(may be filled after `Load` or `Parse`) /// const std::string& Warning() const { return warning_; } /// /// Error message(filled when `Load` or `Parse` failed) /// const std::string& Error() const { return error_; } private: bool valid_; attrib_t attrib_; std::vector<shape_t> shapes_; std::vector<material_t> materials_; std::string warning_; std::string error_; }; /// ==>>========= Legacy v1 API ============================================= /// Loads .obj from a file. /// 'attrib', 'shapes' and 'materials' will be filled with parsed shape data /// 'shapes' will be filled with parsed shape data /// Returns true when loading .obj become success. /// Returns warning message into `warn`, and error message into `err` /// 'mtl_basedir' is optional, and used for base directory for .mtl file. /// In default(`NULL'), .mtl file is searched from an application's working /// directory. /// 'triangulate' is optional, and used whether triangulate polygon face in .obj /// or not. /// Option 'default_vcols_fallback' specifies whether vertex colors should /// always be defined, even if no colors are given (fallback to white). bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes, std::vector<material_t>* materials, std::string* warn, std::string* err, const char* filename, const char* mtl_basedir = NULL, bool triangulate = true, bool default_vcols_fallback = true); /// Loads .obj from a file with custom user callback. /// .mtl is loaded as usual and parsed material_t data will be passed to /// `callback.mtllib_cb`. /// Returns true when loading .obj/.mtl become success. /// Returns warning message into `warn`, and error message into `err` /// See `examples/callback_api/` for how to use this function. bool LoadObjWithCallback(std::istream& inStream, const callback_t& callback, void* user_data = NULL, MaterialReader* readMatFn = NULL, std::string* warn = NULL, std::string* err = NULL); /// Loads object from a std::istream, uses `readMatFn` to retrieve /// std::istream for materials. /// Returns true when loading .obj become success. /// Returns warning and error message into `err` bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes, std::vector<material_t>* materials, std::string* warn, std::string* err, std::istream* inStream, MaterialReader* readMatFn = NULL, bool triangulate = true, bool default_vcols_fallback = true); /// Loads materials into std::map void LoadMtl(std::map<std::string, int>* material_map, std::vector<material_t>* materials, std::istream* inStream, std::string* warning, std::string* err); /// /// Parse texture name and texture option for custom texture parameter through /// material::unknown_parameter /// /// @param[out] texname Parsed texture name /// @param[out] texopt Parsed texopt /// @param[in] linebuf Input string /// bool ParseTextureNameAndOption(std::string* texname, texture_option_t* texopt, const char* linebuf); /// =<<========== Legacy v1 API ============================================= } // namespace tinyobj #endif // TINY_OBJ_LOADER_H_ #ifdef TINYOBJLOADER_IMPLEMENTATION #include <cassert> #include <cctype> #include <cmath> #include <cstddef> #include <cstdlib> #include <cstring> #include <fstream> #include <limits> #include <sstream> #include <utility> namespace tinyobj { MaterialReader::~MaterialReader() {} struct vertex_index_t { int v_idx, vt_idx, vn_idx; vertex_index_t() : v_idx(-1), vt_idx(-1), vn_idx(-1) {} explicit vertex_index_t(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {} vertex_index_t(int vidx, int vtidx, int vnidx) : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {} }; // Internal data structure for face representation // index + smoothing group. struct face_t { unsigned int smoothing_group_id; // smoothing group id. 0 = smoothing groupd is off. int pad_; std::vector<vertex_index_t> vertex_indices; // face vertex indices. face_t() : smoothing_group_id(0), pad_(0) {} }; // Internal data structure for line representation struct __line_t { // l v1/vt1 v2/vt2 ... // In the specification, line primitrive does not have normal index, but // TinyObjLoader allow it std::vector<vertex_index_t> vertex_indices; }; // Internal data structure for points representation struct __points_t { // p v1 v2 ... // In the specification, point primitrive does not have normal index and // texture coord index, but TinyObjLoader allow it. std::vector<vertex_index_t> vertex_indices; }; struct tag_sizes { tag_sizes() : num_ints(0), num_reals(0), num_strings(0) {} int num_ints; int num_reals; int num_strings; }; struct obj_shape { std::vector<real_t> v; std::vector<real_t> vn; std::vector<real_t> vt; }; // // Manages group of primitives(face, line, points, ...) struct PrimGroup { std::vector<face_t> faceGroup; std::vector<__line_t> lineGroup; std::vector<__points_t> pointsGroup; void clear() { faceGroup.clear(); lineGroup.clear(); pointsGroup.clear(); } bool IsEmpty() const { return faceGroup.empty() && lineGroup.empty() && pointsGroup.empty(); } // TODO(syoyo): bspline, surface, ... }; // See // http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf static std::istream& safeGetline(std::istream& is, std::string& t) { t.clear(); // The characters in the stream are read one-by-one using a std::streambuf. // That is faster than reading them one-by-one using the std::istream. // Code that uses streambuf this way must be guarded by a sentry object. // The sentry object performs various tasks, // such as thread synchronization and updating the stream state. std::istream::sentry se(is, true); std::streambuf* sb = is.rdbuf(); if (se) { for (;;) { int c = sb->sbumpc(); switch (c) { case '\n': return is; case '\r': if (sb->sgetc() == '\n') sb->sbumpc(); return is; case EOF: // Also handle the case when the last line has no line ending if (t.empty()) is.setstate(std::ios::eofbit); return is; default: t += static_cast<char>(c); } } } return is; } #define IS_SPACE(x) (((x) == ' ') || ((x) == '\t')) #define IS_DIGIT(x) \ (static_cast<unsigned int>((x) - '0') < static_cast<unsigned int>(10)) #define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0')) // Make index zero-base, and also support relative index. static inline bool fixIndex(int idx, int n, int* ret) { if (!ret) { return false; } if (idx > 0) { (*ret) = idx - 1; return true; } if (idx == 0) { // zero is not allowed according to the spec. return false; } if (idx < 0) { (*ret) = n + idx; // negative value = relative return true; } return false; // never reach here. } static inline std::string parseString(const char** token) { std::string s; (*token) += strspn((*token), " \t"); size_t e = strcspn((*token), " \t\r"); s = std::string((*token), &(*token)[e]); (*token) += e; return s; } static inline int parseInt(const char** token) { (*token) += strspn((*token), " \t"); int i = atoi((*token)); (*token) += strcspn((*token), " \t\r"); return i; } // Tries to parse a floating point number located at s. // // s_end should be a location in the string where reading should absolutely // stop. For example at the end of the string, to prevent buffer overflows. // // Parses the following EBNF grammar: // sign = "+" | "-" ; // END = ? anything not in digit ? // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; // integer = [sign] , digit , {digit} ; // decimal = integer , ["." , integer] ; // float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ; // // Valid strings are for example: // -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 // // If the parsing is a success, result is set to the parsed value and true // is returned. // // The function is greedy and will parse until any of the following happens: // - a non-conforming character is encountered. // - s_end is reached. // // The following situations triggers a failure: // - s >= s_end. // - parse failure. // static bool tryParseDouble(const char* s, const char* s_end, double* result) { if (s >= s_end) { return false; } double mantissa = 0.0; // This exponent is base 2 rather than 10. // However the exponent we parse is supposed to be one of ten, // thus we must take care to convert the exponent/and or the // mantissa to a * 2^E, where a is the mantissa and E is the // exponent. // To get the final double we will use ldexp, it requires the // exponent to be in base 2. int exponent = 0; // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED // TO JUMP OVER DEFINITIONS. char sign = '+'; char exp_sign = '+'; char const* curr = s; // How many characters were read in a loop. int read = 0; // Tells whether a loop terminated due to reaching s_end. bool end_not_reached = false; bool leading_decimal_dots = false; /* BEGIN PARSING. */ // Find out what sign we've got. if (*curr == '+' || *curr == '-') { sign = *curr; curr++; if ((curr != s_end) && (*curr == '.')) { // accept. Somethig like `.7e+2`, `-.5234` leading_decimal_dots = true; } } else if (IS_DIGIT(*curr)) { /* Pass through. */ } else if (*curr == '.') { // accept. Somethig like `.7e+2`, `-.5234` leading_decimal_dots = true; } else { goto fail; } // Read the integer part. end_not_reached = (curr != s_end); if (!leading_decimal_dots) { while (end_not_reached && IS_DIGIT(*curr)) { mantissa *= 10; mantissa += static_cast<int>(*curr - 0x30); curr++; read++; end_not_reached = (curr != s_end); } // We must make sure we actually got something. if (read == 0) goto fail; } // We allow numbers of form "#", "###" etc. if (!end_not_reached) goto assemble; // Read the decimal part. if (*curr == '.') { curr++; read = 1; end_not_reached = (curr != s_end); while (end_not_reached && IS_DIGIT(*curr)) { static const double pow_lut[] = { 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, }; const int lut_entries = sizeof pow_lut / sizeof pow_lut[0]; // NOTE: Don't use powf here, it will absolutely murder precision. mantissa += static_cast<int>(*curr - 0x30) * (read < lut_entries ? pow_lut[read] : std::pow(10.0, -read)); read++; curr++; end_not_reached = (curr != s_end); } } else if (*curr == 'e' || *curr == 'E') { } else { goto assemble; } if (!end_not_reached) goto assemble; // Read the exponent part. if (*curr == 'e' || *curr == 'E') { curr++; // Figure out if a sign is present and if it is. end_not_reached = (curr != s_end); if (end_not_reached && (*curr == '+' || *curr == '-')) { exp_sign = *curr; curr++; } else if (IS_DIGIT(*curr)) { /* Pass through. */ } else { // Empty E is not allowed. goto fail; } read = 0; end_not_reached = (curr != s_end); while (end_not_reached && IS_DIGIT(*curr)) { exponent *= 10; exponent += static_cast<int>(*curr - 0x30); curr++; read++; end_not_reached = (curr != s_end); } exponent *= (exp_sign == '+' ? 1 : -1); if (read == 0) goto fail; } assemble: *result = (sign == '+' ? 1 : -1) * (exponent ? std::ldexp(mantissa * std::pow(5.0, exponent), exponent) : mantissa); return true; fail: return false; } static inline real_t parseReal(const char** token, double default_value = 0.0) { (*token) += strspn((*token), " \t"); const char* end = (*token) + strcspn((*token), " \t\r"); double val = default_value; tryParseDouble((*token), end, &val); real_t f = static_cast<real_t>(val); (*token) = end; return f; } static inline bool parseReal(const char** token, real_t* out) { (*token) += strspn((*token), " \t"); const char* end = (*token) + strcspn((*token), " \t\r"); double val; bool ret = tryParseDouble((*token), end, &val); if (ret) { real_t f = static_cast<real_t>(val); (*out) = f; } (*token) = end; return ret; } static inline void parseReal2(real_t* x, real_t* y, const char** token, const double default_x = 0.0, const double default_y = 0.0) { (*x) = parseReal(token, default_x); (*y) = parseReal(token, default_y); } static inline void parseReal3(real_t* x, real_t* y, real_t* z, const char** token, const double default_x = 0.0, const double default_y = 0.0, const double default_z = 0.0) { (*x) = parseReal(token, default_x); (*y) = parseReal(token, default_y); (*z) = parseReal(token, default_z); } static inline void parseV(real_t* x, real_t* y, real_t* z, real_t* w, const char** token, const double default_x = 0.0, const double default_y = 0.0, const double default_z = 0.0, const double default_w = 1.0) { (*x) = parseReal(token, default_x); (*y) = parseReal(token, default_y); (*z) = parseReal(token, default_z); (*w) = parseReal(token, default_w); } // Extension: parse vertex with colors(6 items) static inline bool parseVertexWithColor(real_t* x, real_t* y, real_t* z, real_t* r, real_t* g, real_t* b, const char** token, const double default_x = 0.0, const double default_y = 0.0, const double default_z = 0.0) { (*x) = parseReal(token, default_x); (*y) = parseReal(token, default_y); (*z) = parseReal(token, default_z); const bool found_color = parseReal(token, r) && parseReal(token, g) && parseReal(token, b); if (!found_color) { (*r) = (*g) = (*b) = 1.0; } return found_color; } static inline bool parseOnOff(const char** token, bool default_value = true) { (*token) += strspn((*token), " \t"); const char* end = (*token) + strcspn((*token), " \t\r"); bool ret = default_value; if ((0 == strncmp((*token), "on", 2))) { ret = true; } else if ((0 == strncmp((*token), "off", 3))) { ret = false; } (*token) = end; return ret; } static inline texture_type_t parseTextureType( const char** token, texture_type_t default_value = TEXTURE_TYPE_NONE) { (*token) += strspn((*token), " \t"); const char* end = (*token) + strcspn((*token), " \t\r"); texture_type_t ty = default_value; if ((0 == strncmp((*token), "cube_top", strlen("cube_top")))) { ty = TEXTURE_TYPE_CUBE_TOP; } else if ((0 == strncmp((*token), "cube_bottom", strlen("cube_bottom")))) { ty = TEXTURE_TYPE_CUBE_BOTTOM; } else if ((0 == strncmp((*token), "cube_left", strlen("cube_left")))) { ty = TEXTURE_TYPE_CUBE_LEFT; } else if ((0 == strncmp((*token), "cube_right", strlen("cube_right")))) { ty = TEXTURE_TYPE_CUBE_RIGHT; } else if ((0 == strncmp((*token), "cube_front", strlen("cube_front")))) { ty = TEXTURE_TYPE_CUBE_FRONT; } else if ((0 == strncmp((*token), "cube_back", strlen("cube_back")))) { ty = TEXTURE_TYPE_CUBE_BACK; } else if ((0 == strncmp((*token), "sphere", strlen("sphere")))) { ty = TEXTURE_TYPE_SPHERE; } (*token) = end; return ty; } static tag_sizes parseTagTriple(const char** token) { tag_sizes ts; (*token) += strspn((*token), " \t"); ts.num_ints = atoi((*token)); (*token) += strcspn((*token), "/ \t\r"); if ((*token)[0] != '/') { return ts; } (*token)++; // Skip '/' (*token) += strspn((*token), " \t"); ts.num_reals = atoi((*token)); (*token) += strcspn((*token), "/ \t\r"); if ((*token)[0] != '/') { return ts; } (*token)++; // Skip '/' ts.num_strings = parseInt(token); return ts; } // Parse triples with index offsets: i, i/j/k, i//k, i/j static bool parseTriple(const char** token, int vsize, int vnsize, int vtsize, vertex_index_t* ret) { if (!ret) { return false; } vertex_index_t vi(-1); if (!fixIndex(atoi((*token)), vsize, &(vi.v_idx))) { return false; } (*token) += strcspn((*token), "/ \t\r"); if ((*token)[0] != '/') { (*ret) = vi; return true; } (*token)++; // i//k if ((*token)[0] == '/') { (*token)++; if (!fixIndex(atoi((*token)), vnsize, &(vi.vn_idx))) { return false; } (*token) += strcspn((*token), "/ \t\r"); (*ret) = vi; return true; } // i/j/k or i/j if (!fixIndex(atoi((*token)), vtsize, &(vi.vt_idx))) { return false; } (*token) += strcspn((*token), "/ \t\r"); if ((*token)[0] != '/') { (*ret) = vi; return true; } // i/j/k (*token)++; // skip '/' if (!fixIndex(atoi((*token)), vnsize, &(vi.vn_idx))) { return false; } (*token) += strcspn((*token), "/ \t\r"); (*ret) = vi; return true; } // Parse raw triples: i, i/j/k, i//k, i/j static vertex_index_t parseRawTriple(const char** token) { vertex_index_t vi(static_cast<int>(0)); // 0 is an invalid index in OBJ vi.v_idx = atoi((*token)); (*token) += strcspn((*token), "/ \t\r"); if ((*token)[0] != '/') { return vi; } (*token)++; // i//k if ((*token)[0] == '/') { (*token)++; vi.vn_idx = atoi((*token)); (*token) += strcspn((*token), "/ \t\r"); return vi; } // i/j/k or i/j vi.vt_idx = atoi((*token)); (*token) += strcspn((*token), "/ \t\r"); if ((*token)[0] != '/') { return vi; } // i/j/k (*token)++; // skip '/' vi.vn_idx = atoi((*token)); (*token) += strcspn((*token), "/ \t\r"); return vi; } bool ParseTextureNameAndOption(std::string* texname, texture_option_t* texopt, const char* linebuf) { // @todo { write more robust lexer and parser. } bool found_texname = false; std::string texture_name; const char* token = linebuf; // Assume line ends with NULL while (!IS_NEW_LINE((*token))) { token += strspn(token, " \t"); // skip space if ((0 == strncmp(token, "-blendu", 7)) && IS_SPACE((token[7]))) { token += 8; texopt->blendu = parseOnOff(&token, /* default */ true); } else if ((0 == strncmp(token, "-blendv", 7)) && IS_SPACE((token[7]))) { token += 8; texopt->blendv = parseOnOff(&token, /* default */ true); } else if ((0 == strncmp(token, "-clamp", 6)) && IS_SPACE((token[6]))) { token += 7; texopt->clamp = parseOnOff(&token, /* default */ true); } else if ((0 == strncmp(token, "-boost", 6)) && IS_SPACE((token[6]))) { token += 7; texopt->sharpness = parseReal(&token, 1.0); } else if ((0 == strncmp(token, "-bm", 3)) && IS_SPACE((token[3]))) { token += 4; texopt->bump_multiplier = parseReal(&token, 1.0); } else if ((0 == strncmp(token, "-o", 2)) && IS_SPACE((token[2]))) { token += 3; parseReal3(&(texopt->origin_offset[0]), &(texopt->origin_offset[1]), &(texopt->origin_offset[2]), &token); } else if ((0 == strncmp(token, "-s", 2)) && IS_SPACE((token[2]))) { token += 3; parseReal3(&(texopt->scale[0]), &(texopt->scale[1]), &(texopt->scale[2]), &token, 1.0, 1.0, 1.0); } else if ((0 == strncmp(token, "-t", 2)) && IS_SPACE((token[2]))) { token += 3; parseReal3(&(texopt->turbulence[0]), &(texopt->turbulence[1]), &(texopt->turbulence[2]), &token); } else if ((0 == strncmp(token, "-type", 5)) && IS_SPACE((token[5]))) { token += 5; texopt->type = parseTextureType((&token), TEXTURE_TYPE_NONE); } else if ((0 == strncmp(token, "-texres", 7)) && IS_SPACE((token[7]))) { token += 7; // TODO(syoyo): Check if arg is int type. texopt->texture_resolution = parseInt(&token); } else if ((0 == strncmp(token, "-imfchan", 8)) && IS_SPACE((token[8]))) { token += 9; token += strspn(token, " \t"); const char* end = token + strcspn(token, " \t\r"); if ((end - token) == 1) { // Assume one char for -imfchan texopt->imfchan = (*token); } token = end; } else if ((0 == strncmp(token, "-mm", 3)) && IS_SPACE((token[3]))) { token += 4; parseReal2(&(texopt->brightness), &(texopt->contrast), &token, 0.0, 1.0); } else if ((0 == strncmp(token, "-colorspace", 11)) && IS_SPACE((token[11]))) { token += 12; texopt->colorspace = parseString(&token); } else { // Assume texture filename #if 0 size_t len = strcspn(token, " \t\r"); // untile next space texture_name = std::string(token, token + len); token += len; token += strspn(token, " \t"); // skip space #else // Read filename until line end to parse filename containing whitespace // TODO(syoyo): Support parsing texture option flag after the filename. texture_name = std::string(token); token += texture_name.length(); #endif found_texname = true; } } if (found_texname) { (*texname) = texture_name; return true; } else { return false; } } static void InitTexOpt(texture_option_t* texopt, const bool is_bump) { if (is_bump) { texopt->imfchan = 'l'; } else { texopt->imfchan = 'm'; } texopt->bump_multiplier = static_cast<real_t>(1.0); texopt->clamp = false; texopt->blendu = true; texopt->blendv = true; texopt->sharpness = static_cast<real_t>(1.0); texopt->brightness = static_cast<real_t>(0.0); texopt->contrast = static_cast<real_t>(1.0); texopt->origin_offset[0] = static_cast<real_t>(0.0); texopt->origin_offset[1] = static_cast<real_t>(0.0); texopt->origin_offset[2] = static_cast<real_t>(0.0); texopt->scale[0] = static_cast<real_t>(1.0); texopt->scale[1] = static_cast<real_t>(1.0); texopt->scale[2] = static_cast<real_t>(1.0); texopt->turbulence[0] = static_cast<real_t>(0.0); texopt->turbulence[1] = static_cast<real_t>(0.0); texopt->turbulence[2] = static_cast<real_t>(0.0); texopt->texture_resolution = -1; texopt->type = TEXTURE_TYPE_NONE; } static void InitMaterial(material_t* material) { InitTexOpt(&material->ambient_texopt, /* is_bump */ false); InitTexOpt(&material->diffuse_texopt, /* is_bump */ false); InitTexOpt(&material->specular_texopt, /* is_bump */ false); InitTexOpt(&material->specular_highlight_texopt, /* is_bump */ false); InitTexOpt(&material->bump_texopt, /* is_bump */ true); InitTexOpt(&material->displacement_texopt, /* is_bump */ false); InitTexOpt(&material->alpha_texopt, /* is_bump */ false); InitTexOpt(&material->reflection_texopt, /* is_bump */ false); InitTexOpt(&material->roughness_texopt, /* is_bump */ false); InitTexOpt(&material->metallic_texopt, /* is_bump */ false); InitTexOpt(&material->sheen_texopt, /* is_bump */ false); InitTexOpt(&material->emissive_texopt, /* is_bump */ false); InitTexOpt(&material->normal_texopt, /* is_bump */ false); // @fixme { is_bump will be true? } material->name = ""; material->ambient_texname = ""; material->diffuse_texname = ""; material->specular_texname = ""; material->specular_highlight_texname = ""; material->bump_texname = ""; material->displacement_texname = ""; material->reflection_texname = ""; material->alpha_texname = ""; for (int i = 0; i < 3; i++) { material->ambient[i] = static_cast<real_t>(0.0); material->diffuse[i] = static_cast<real_t>(0.0); material->specular[i] = static_cast<real_t>(0.0); material->transmittance[i] = static_cast<real_t>(0.0); material->emission[i] = static_cast<real_t>(0.0); } material->illum = 0; material->dissolve = static_cast<real_t>(1.0); material->shininess = static_cast<real_t>(1.0); material->ior = static_cast<real_t>(1.0); material->roughness = static_cast<real_t>(0.0); material->metallic = static_cast<real_t>(0.0); material->sheen = static_cast<real_t>(0.0); material->clearcoat_thickness = static_cast<real_t>(0.0); material->clearcoat_roughness = static_cast<real_t>(0.0); material->anisotropy_rotation = static_cast<real_t>(0.0); material->anisotropy = static_cast<real_t>(0.0); material->roughness_texname = ""; material->metallic_texname = ""; material->sheen_texname = ""; material->emissive_texname = ""; material->normal_texname = ""; material->unknown_parameter.clear(); } // code from https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html template <typename T> static int pnpoly(int nvert, T* vertx, T* verty, T testx, T testy) { int i, j, c = 0; for (i = 0, j = nvert - 1; i < nvert; j = i++) { if (((verty[i] > testy) != (verty[j] > testy)) && (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i])) c = !c; } return c; } // TODO(syoyo): refactor function. static bool exportGroupsToShape(shape_t* shape, const PrimGroup& prim_group, const std::vector<tag_t>& tags, const int material_id, const std::string& name, bool triangulate, const std::vector<real_t>& v, std::string* warn) { if (prim_group.IsEmpty()) { return false; } shape->name = name; // polygon if (!prim_group.faceGroup.empty()) { // Flatten vertices and indices for (size_t i = 0; i < prim_group.faceGroup.size(); i++) { const face_t& face = prim_group.faceGroup[i]; size_t npolys = face.vertex_indices.size(); if (npolys < 3) { // Face must have 3+ vertices. if (warn) { (*warn) += "Degenerated face found\n."; } continue; } if (triangulate) { if (npolys == 4) { vertex_index_t i0 = face.vertex_indices[0]; vertex_index_t i1 = face.vertex_indices[1]; vertex_index_t i2 = face.vertex_indices[2]; vertex_index_t i3 = face.vertex_indices[3]; size_t vi0 = size_t(i0.v_idx); size_t vi1 = size_t(i1.v_idx); size_t vi2 = size_t(i2.v_idx); size_t vi3 = size_t(i3.v_idx); if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) || ((3 * vi2 + 2) >= v.size()) || ((3 * vi3 + 2) >= v.size())) { // Invalid triangle. // FIXME(syoyo): Is it ok to simply skip this invalid triangle? if (warn) { (*warn) += "Face with invalid vertex index found.\n"; } continue; } real_t v0x = v[vi0 * 3 + 0]; real_t v0y = v[vi0 * 3 + 1]; real_t v0z = v[vi0 * 3 + 2]; real_t v1x = v[vi1 * 3 + 0]; real_t v1y = v[vi1 * 3 + 1]; real_t v1z = v[vi1 * 3 + 2]; real_t v2x = v[vi2 * 3 + 0]; real_t v2y = v[vi2 * 3 + 1]; real_t v2z = v[vi2 * 3 + 2]; real_t v3x = v[vi3 * 3 + 0]; real_t v3y = v[vi3 * 3 + 1]; real_t v3z = v[vi3 * 3 + 2]; // There are two candidates to split the quad into two triangles. // // Choose the shortest edge. // TODO: Is it better to determine the edge to split by calculating // the area of each triangle? // // +---+ // |\ | // | \ | // | \| // +---+ // // +---+ // | /| // | / | // |/ | // +---+ real_t e02x = v2x - v0x; real_t e02y = v2y - v0y; real_t e02z = v2z - v0z; real_t e13x = v3x - v1x; real_t e13y = v3y - v1y; real_t e13z = v3z - v1z; real_t sqr02 = e02x * e02x + e02y * e02y + e02z * e02z; real_t sqr13 = e13x * e13x + e13y * e13y + e13z * e13z; index_t idx0, idx1, idx2, idx3; idx0.vertex_index = i0.v_idx; idx0.normal_index = i0.vn_idx; idx0.texcoord_index = i0.vt_idx; idx1.vertex_index = i1.v_idx; idx1.normal_index = i1.vn_idx; idx1.texcoord_index = i1.vt_idx; idx2.vertex_index = i2.v_idx; idx2.normal_index = i2.vn_idx; idx2.texcoord_index = i2.vt_idx; idx3.vertex_index = i3.v_idx; idx3.normal_index = i3.vn_idx; idx3.texcoord_index = i3.vt_idx; if (sqr02 < sqr13) { // [0, 1, 2], [0, 2, 3] shape->mesh.indices.push_back(idx0); shape->mesh.indices.push_back(idx1); shape->mesh.indices.push_back(idx2); shape->mesh.indices.push_back(idx0); shape->mesh.indices.push_back(idx2); shape->mesh.indices.push_back(idx3); } else { // [0, 1, 3], [1, 2, 3] shape->mesh.indices.push_back(idx0); shape->mesh.indices.push_back(idx1); shape->mesh.indices.push_back(idx3); shape->mesh.indices.push_back(idx1); shape->mesh.indices.push_back(idx2); shape->mesh.indices.push_back(idx3); } // Two triangle faces shape->mesh.num_face_vertices.push_back(3); shape->mesh.num_face_vertices.push_back(3); shape->mesh.material_ids.push_back(material_id); shape->mesh.material_ids.push_back(material_id); shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id); shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id); } else { vertex_index_t i0 = face.vertex_indices[0]; vertex_index_t i1(-1); vertex_index_t i2 = face.vertex_indices[1]; // find the two axes to work in size_t axes[2] = { 1, 2 }; for (size_t k = 0; k < npolys; ++k) { i0 = face.vertex_indices[(k + 0) % npolys]; i1 = face.vertex_indices[(k + 1) % npolys]; i2 = face.vertex_indices[(k + 2) % npolys]; size_t vi0 = size_t(i0.v_idx); size_t vi1 = size_t(i1.v_idx); size_t vi2 = size_t(i2.v_idx); if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) || ((3 * vi2 + 2) >= v.size())) { // Invalid triangle. // FIXME(syoyo): Is it ok to simply skip this invalid triangle? continue; } real_t v0x = v[vi0 * 3 + 0]; real_t v0y = v[vi0 * 3 + 1]; real_t v0z = v[vi0 * 3 + 2]; real_t v1x = v[vi1 * 3 + 0]; real_t v1y = v[vi1 * 3 + 1]; real_t v1z = v[vi1 * 3 + 2]; real_t v2x = v[vi2 * 3 + 0]; real_t v2y = v[vi2 * 3 + 1]; real_t v2z = v[vi2 * 3 + 2]; real_t e0x = v1x - v0x; real_t e0y = v1y - v0y; real_t e0z = v1z - v0z; real_t e1x = v2x - v1x; real_t e1y = v2y - v1y; real_t e1z = v2z - v1z; real_t cx = std::fabs(e0y * e1z - e0z * e1y); real_t cy = std::fabs(e0z * e1x - e0x * e1z); real_t cz = std::fabs(e0x * e1y - e0y * e1x); const real_t epsilon = std::numeric_limits<real_t>::epsilon(); if (cx > epsilon || cy > epsilon || cz > epsilon) { // found a corner if (cx > cy && cx > cz) { } else { axes[0] = 0; if (cz > cx && cz > cy) axes[1] = 1; } break; } } real_t area = 0; for (size_t k = 0; k < npolys; ++k) { i0 = face.vertex_indices[(k + 0) % npolys]; i1 = face.vertex_indices[(k + 1) % npolys]; size_t vi0 = size_t(i0.v_idx); size_t vi1 = size_t(i1.v_idx); if (((vi0 * 3 + axes[0]) >= v.size()) || ((vi0 * 3 + axes[1]) >= v.size()) || ((vi1 * 3 + axes[0]) >= v.size()) || ((vi1 * 3 + axes[1]) >= v.size())) { // Invalid index. continue; } real_t v0x = v[vi0 * 3 + axes[0]]; real_t v0y = v[vi0 * 3 + axes[1]]; real_t v1x = v[vi1 * 3 + axes[0]]; real_t v1y = v[vi1 * 3 + axes[1]]; area += (v0x * v1y - v0y * v1x) * static_cast<real_t>(0.5); } face_t remainingFace = face; // copy size_t guess_vert = 0; vertex_index_t ind[3]; real_t vx[3]; real_t vy[3]; // How many iterations can we do without decreasing the remaining // vertices. size_t remainingIterations = face.vertex_indices.size(); size_t previousRemainingVertices = remainingFace.vertex_indices.size(); while (remainingFace.vertex_indices.size() > 3 && remainingIterations > 0) { npolys = remainingFace.vertex_indices.size(); if (guess_vert >= npolys) { guess_vert -= npolys; } if (previousRemainingVertices != npolys) { // The number of remaining vertices decreased. Reset counters. previousRemainingVertices = npolys; remainingIterations = npolys; } else { // We didn't consume a vertex on previous iteration, reduce the // available iterations. remainingIterations--; } for (size_t k = 0; k < 3; k++) { ind[k] = remainingFace.vertex_indices[(guess_vert + k) % npolys]; size_t vi = size_t(ind[k].v_idx); if (((vi * 3 + axes[0]) >= v.size()) || ((vi * 3 + axes[1]) >= v.size())) { // ??? vx[k] = static_cast<real_t>(0.0); vy[k] = static_cast<real_t>(0.0); } else { vx[k] = v[vi * 3 + axes[0]]; vy[k] = v[vi * 3 + axes[1]]; } } real_t e0x = vx[1] - vx[0]; real_t e0y = vy[1] - vy[0]; real_t e1x = vx[2] - vx[1]; real_t e1y = vy[2] - vy[1]; real_t cross = e0x * e1y - e0y * e1x; // if an internal angle if (cross * area < static_cast<real_t>(0.0)) { guess_vert += 1; continue; } // check all other verts in case they are inside this triangle bool overlap = false; for (size_t otherVert = 3; otherVert < npolys; ++otherVert) { size_t idx = (guess_vert + otherVert) % npolys; if (idx >= remainingFace.vertex_indices.size()) { // ??? continue; } size_t ovi = size_t(remainingFace.vertex_indices[idx].v_idx); if (((ovi * 3 + axes[0]) >= v.size()) || ((ovi * 3 + axes[1]) >= v.size())) { // ??? continue; } real_t tx = v[ovi * 3 + axes[0]]; real_t ty = v[ovi * 3 + axes[1]]; if (pnpoly(3, vx, vy, tx, ty)) { overlap = true; break; } } if (overlap) { guess_vert += 1; continue; } // this triangle is an ear { index_t idx0, idx1, idx2; idx0.vertex_index = ind[0].v_idx; idx0.normal_index = ind[0].vn_idx; idx0.texcoord_index = ind[0].vt_idx; idx1.vertex_index = ind[1].v_idx; idx1.normal_index = ind[1].vn_idx; idx1.texcoord_index = ind[1].vt_idx; idx2.vertex_index = ind[2].v_idx; idx2.normal_index = ind[2].vn_idx; idx2.texcoord_index = ind[2].vt_idx; shape->mesh.indices.push_back(idx0); shape->mesh.indices.push_back(idx1); shape->mesh.indices.push_back(idx2); shape->mesh.num_face_vertices.push_back(3); shape->mesh.material_ids.push_back(material_id); shape->mesh.smoothing_group_ids.push_back( face.smoothing_group_id); } // remove v1 from the list size_t removed_vert_index = (guess_vert + 1) % npolys; while (removed_vert_index + 1 < npolys) { remainingFace.vertex_indices[removed_vert_index] = remainingFace.vertex_indices[removed_vert_index + 1]; removed_vert_index += 1; } remainingFace.vertex_indices.pop_back(); } if (remainingFace.vertex_indices.size() == 3) { i0 = remainingFace.vertex_indices[0]; i1 = remainingFace.vertex_indices[1]; i2 = remainingFace.vertex_indices[2]; { index_t idx0, idx1, idx2; idx0.vertex_index = i0.v_idx; idx0.normal_index = i0.vn_idx; idx0.texcoord_index = i0.vt_idx; idx1.vertex_index = i1.v_idx; idx1.normal_index = i1.vn_idx; idx1.texcoord_index = i1.vt_idx; idx2.vertex_index = i2.v_idx; idx2.normal_index = i2.vn_idx; idx2.texcoord_index = i2.vt_idx; shape->mesh.indices.push_back(idx0); shape->mesh.indices.push_back(idx1); shape->mesh.indices.push_back(idx2); shape->mesh.num_face_vertices.push_back(3); shape->mesh.material_ids.push_back(material_id); shape->mesh.smoothing_group_ids.push_back( face.smoothing_group_id); } } } // npolys } else { for (size_t k = 0; k < npolys; k++) { index_t idx; idx.vertex_index = face.vertex_indices[k].v_idx; idx.normal_index = face.vertex_indices[k].vn_idx; idx.texcoord_index = face.vertex_indices[k].vt_idx; shape->mesh.indices.push_back(idx); } shape->mesh.num_face_vertices.push_back( static_cast<unsigned char>(npolys)); shape->mesh.material_ids.push_back(material_id); // per face shape->mesh.smoothing_group_ids.push_back( face.smoothing_group_id); // per face } } shape->mesh.tags = tags; } // line if (!prim_group.lineGroup.empty()) { // Flatten indices for (size_t i = 0; i < prim_group.lineGroup.size(); i++) { for (size_t j = 0; j < prim_group.lineGroup[i].vertex_indices.size(); j++) { const vertex_index_t& vi = prim_group.lineGroup[i].vertex_indices[j]; index_t idx; idx.vertex_index = vi.v_idx; idx.normal_index = vi.vn_idx; idx.texcoord_index = vi.vt_idx; shape->lines.indices.push_back(idx); } shape->lines.num_line_vertices.push_back( int(prim_group.lineGroup[i].vertex_indices.size())); } } // points if (!prim_group.pointsGroup.empty()) { // Flatten & convert indices for (size_t i = 0; i < prim_group.pointsGroup.size(); i++) { for (size_t j = 0; j < prim_group.pointsGroup[i].vertex_indices.size(); j++) { const vertex_index_t& vi = prim_group.pointsGroup[i].vertex_indices[j]; index_t idx; idx.vertex_index = vi.v_idx; idx.normal_index = vi.vn_idx; idx.texcoord_index = vi.vt_idx; shape->points.indices.push_back(idx); } } } return true; } // Split a string with specified delimiter character and escape character. // https://rosettacode.org/wiki/Tokenize_a_string_with_escaping#C.2B.2B static void SplitString(const std::string& s, char delim, char escape, std::vector<std::string>& elems) { std::string token; bool escaping = false; for (size_t i = 0; i < s.size(); ++i) { char ch = s[i]; if (escaping) { escaping = false; } else if (ch == escape) { escaping = true; continue; } else if (ch == delim) { if (!token.empty()) { elems.push_back(token); } token.clear(); continue; } token += ch; } elems.push_back(token); } static std::string JoinPath(const std::string& dir, const std::string& filename) { if (dir.empty()) { return filename; } else { // check '/' char lastChar = *dir.rbegin(); if (lastChar != '/') { return dir + std::string("/") + filename; } else { return dir + filename; } } } void LoadMtl(std::map<std::string, int>* material_map, std::vector<material_t>* materials, std::istream* inStream, std::string* warning, std::string* err) { (void)err; // Create a default material anyway. material_t material; InitMaterial(&material); // Issue 43. `d` wins against `Tr` since `Tr` is not in the MTL specification. bool has_d = false; bool has_tr = false; // has_kd is used to set a default diffuse value when map_Kd is present // and Kd is not. bool has_kd = false; std::stringstream warn_ss; size_t line_no = 0; std::string linebuf; while (inStream->peek() != -1) { safeGetline(*inStream, linebuf); line_no++; // Trim trailing whitespace. if (linebuf.size() > 0) { linebuf = linebuf.substr(0, linebuf.find_last_not_of(" \t") + 1); } // Trim newline '\r\n' or '\n' if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1); } if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\r') linebuf.erase(linebuf.size() - 1); } // Skip if empty line. if (linebuf.empty()) { continue; } // Skip leading space. const char* token = linebuf.c_str(); token += strspn(token, " \t"); assert(token); if (token[0] == '\0') continue; // empty line if (token[0] == '#') continue; // comment line // new mtl if ((0 == strncmp(token, "newmtl", 6)) && IS_SPACE((token[6]))) { // flush previous material. if (!material.name.empty()) { material_map->insert(std::pair<std::string, int>( material.name, static_cast<int>(materials->size()))); materials->push_back(material); } // initial temporary material InitMaterial(&material); has_d = false; has_tr = false; // set new mtl name token += 7; { std::stringstream sstr; sstr << token; material.name = sstr.str(); } continue; } // ambient if (token[0] == 'K' && token[1] == 'a' && IS_SPACE((token[2]))) { token += 2; real_t r, g, b; parseReal3(&r, &g, &b, &token); material.ambient[0] = r; material.ambient[1] = g; material.ambient[2] = b; continue; } // diffuse if (token[0] == 'K' && token[1] == 'd' && IS_SPACE((token[2]))) { token += 2; real_t r, g, b; parseReal3(&r, &g, &b, &token); material.diffuse[0] = r; material.diffuse[1] = g; material.diffuse[2] = b; has_kd = true; continue; } // specular if (token[0] == 'K' && token[1] == 's' && IS_SPACE((token[2]))) { token += 2; real_t r, g, b; parseReal3(&r, &g, &b, &token); material.specular[0] = r; material.specular[1] = g; material.specular[2] = b; continue; } // transmittance if ((token[0] == 'K' && token[1] == 't' && IS_SPACE((token[2]))) || (token[0] == 'T' && token[1] == 'f' && IS_SPACE((token[2])))) { token += 2; real_t r, g, b; parseReal3(&r, &g, &b, &token); material.transmittance[0] = r; material.transmittance[1] = g; material.transmittance[2] = b; continue; } // ior(index of refraction) if (token[0] == 'N' && token[1] == 'i' && IS_SPACE((token[2]))) { token += 2; material.ior = parseReal(&token); continue; } // emission if (token[0] == 'K' && token[1] == 'e' && IS_SPACE(token[2])) { token += 2; real_t r, g, b; parseReal3(&r, &g, &b, &token); material.emission[0] = r; material.emission[1] = g; material.emission[2] = b; continue; } // shininess if (token[0] == 'N' && token[1] == 's' && IS_SPACE(token[2])) { token += 2; material.shininess = parseReal(&token); continue; } // illum model if (0 == strncmp(token, "illum", 5) && IS_SPACE(token[5])) { token += 6; material.illum = parseInt(&token); continue; } // dissolve if ((token[0] == 'd' && IS_SPACE(token[1]))) { token += 1; material.dissolve = parseReal(&token); if (has_tr) { warn_ss << "Both `d` and `Tr` parameters defined for \"" << material.name << "\". Use the value of `d` for dissolve (line " << line_no << " in .mtl.)" << std::endl; } has_d = true; continue; } if (token[0] == 'T' && token[1] == 'r' && IS_SPACE(token[2])) { token += 2; if (has_d) { // `d` wins. Ignore `Tr` value. warn_ss << "Both `d` and `Tr` parameters defined for \"" << material.name << "\". Use the value of `d` for dissolve (line " << line_no << " in .mtl.)" << std::endl; } else { // We invert value of Tr(assume Tr is in range [0, 1]) // NOTE: Interpretation of Tr is application(exporter) dependent. For // some application(e.g. 3ds max obj exporter), Tr = d(Issue 43) material.dissolve = static_cast<real_t>(1.0) - parseReal(&token); } has_tr = true; continue; } // PBR: roughness if (token[0] == 'P' && token[1] == 'r' && IS_SPACE(token[2])) { token += 2; material.roughness = parseReal(&token); continue; } // PBR: metallic if (token[0] == 'P' && token[1] == 'm' && IS_SPACE(token[2])) { token += 2; material.metallic = parseReal(&token); continue; } // PBR: sheen if (token[0] == 'P' && token[1] == 's' && IS_SPACE(token[2])) { token += 2; material.sheen = parseReal(&token); continue; } // PBR: clearcoat thickness if (token[0] == 'P' && token[1] == 'c' && IS_SPACE(token[2])) { token += 2; material.clearcoat_thickness = parseReal(&token); continue; } // PBR: clearcoat roughness if ((0 == strncmp(token, "Pcr", 3)) && IS_SPACE(token[3])) { token += 4; material.clearcoat_roughness = parseReal(&token); continue; } // PBR: anisotropy if ((0 == strncmp(token, "aniso", 5)) && IS_SPACE(token[5])) { token += 6; material.anisotropy = parseReal(&token); continue; } // PBR: anisotropy rotation if ((0 == strncmp(token, "anisor", 6)) && IS_SPACE(token[6])) { token += 7; material.anisotropy_rotation = parseReal(&token); continue; } // ambient texture if ((0 == strncmp(token, "map_Ka", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.ambient_texname), &(material.ambient_texopt), token); continue; } // diffuse texture if ((0 == strncmp(token, "map_Kd", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.diffuse_texname), &(material.diffuse_texopt), token); // Set a decent diffuse default value if a diffuse texture is specified // without a matching Kd value. if (!has_kd) { material.diffuse[0] = static_cast<real_t>(0.6); material.diffuse[1] = static_cast<real_t>(0.6); material.diffuse[2] = static_cast<real_t>(0.6); } continue; } // specular texture if ((0 == strncmp(token, "map_Ks", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.specular_texname), &(material.specular_texopt), token); continue; } // specular highlight texture if ((0 == strncmp(token, "map_Ns", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.specular_highlight_texname), &(material.specular_highlight_texopt), token); continue; } // bump texture if ((0 == strncmp(token, "map_bump", 8)) && IS_SPACE(token[8])) { token += 9; ParseTextureNameAndOption(&(material.bump_texname), &(material.bump_texopt), token); continue; } // bump texture if ((0 == strncmp(token, "map_Bump", 8)) && IS_SPACE(token[8])) { token += 9; ParseTextureNameAndOption(&(material.bump_texname), &(material.bump_texopt), token); continue; } // bump texture if ((0 == strncmp(token, "bump", 4)) && IS_SPACE(token[4])) { token += 5; ParseTextureNameAndOption(&(material.bump_texname), &(material.bump_texopt), token); continue; } // alpha texture if ((0 == strncmp(token, "map_d", 5)) && IS_SPACE(token[5])) { token += 6; material.alpha_texname = token; ParseTextureNameAndOption(&(material.alpha_texname), &(material.alpha_texopt), token); continue; } // displacement texture if ((0 == strncmp(token, "disp", 4)) && IS_SPACE(token[4])) { token += 5; ParseTextureNameAndOption(&(material.displacement_texname), &(material.displacement_texopt), token); continue; } // reflection map if ((0 == strncmp(token, "refl", 4)) && IS_SPACE(token[4])) { token += 5; ParseTextureNameAndOption(&(material.reflection_texname), &(material.reflection_texopt), token); continue; } // PBR: roughness texture if ((0 == strncmp(token, "map_Pr", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.roughness_texname), &(material.roughness_texopt), token); continue; } // PBR: metallic texture if ((0 == strncmp(token, "map_Pm", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.metallic_texname), &(material.metallic_texopt), token); continue; } // PBR: sheen texture if ((0 == strncmp(token, "map_Ps", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.sheen_texname), &(material.sheen_texopt), token); continue; } // PBR: emissive texture if ((0 == strncmp(token, "map_Ke", 6)) && IS_SPACE(token[6])) { token += 7; ParseTextureNameAndOption(&(material.emissive_texname), &(material.emissive_texopt), token); continue; } // PBR: normal map texture if ((0 == strncmp(token, "norm", 4)) && IS_SPACE(token[4])) { token += 5; ParseTextureNameAndOption(&(material.normal_texname), &(material.normal_texopt), token); continue; } // unknown parameter const char* _space = strchr(token, ' '); if (!_space) { _space = strchr(token, '\t'); } if (_space) { std::ptrdiff_t len = _space - token; std::string key(token, static_cast<size_t>(len)); std::string value = _space + 1; material.unknown_parameter.insert( std::pair<std::string, std::string>(key, value)); } } // flush last material. material_map->insert(std::pair<std::string, int>( material.name, static_cast<int>(materials->size()))); materials->push_back(material); if (warning) { (*warning) = warn_ss.str(); } } bool MaterialFileReader::operator()(const std::string& matId, std::vector<material_t>* materials, std::map<std::string, int>* matMap, std::string* warn, std::string* err) { if (!m_mtlBaseDir.empty()) { #ifdef _WIN32 char sep = ';'; #else char sep = ':'; #endif // https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g std::vector<std::string> paths; std::istringstream f(m_mtlBaseDir); std::string s; while (getline(f, s, sep)) { paths.push_back(s); } for (size_t i = 0; i < paths.size(); i++) { std::string filepath = JoinPath(paths[i], matId); std::ifstream matIStream(filepath.c_str()); if (matIStream) { LoadMtl(matMap, materials, &matIStream, warn, err); return true; } } std::stringstream ss; ss << "Material file [ " << matId << " ] not found in a path : " << m_mtlBaseDir << std::endl; if (warn) { (*warn) += ss.str(); } return false; } else { std::string filepath = matId; std::ifstream matIStream(filepath.c_str()); if (matIStream) { LoadMtl(matMap, materials, &matIStream, warn, err); return true; } std::stringstream ss; ss << "Material file [ " << filepath << " ] not found in a path : " << m_mtlBaseDir << std::endl; if (warn) { (*warn) += ss.str(); } return false; } } bool MaterialStreamReader::operator()(const std::string& matId, std::vector<material_t>* materials, std::map<std::string, int>* matMap, std::string* warn, std::string* err) { (void)err; (void)matId; if (!m_inStream) { std::stringstream ss; ss << "Material stream in error state. " << std::endl; if (warn) { (*warn) += ss.str(); } return false; } LoadMtl(matMap, materials, &m_inStream, warn, err); return true; } bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes, std::vector<material_t>* materials, std::string* warn, std::string* err, const char* filename, const char* mtl_basedir, bool triangulate, bool default_vcols_fallback) { attrib->vertices.clear(); attrib->normals.clear(); attrib->texcoords.clear(); attrib->colors.clear(); shapes->clear(); std::stringstream errss; std::ifstream ifs(filename); if (!ifs) { errss << "Cannot open file [" << filename << "]" << std::endl; if (err) { (*err) = errss.str(); } return false; } std::string baseDir = mtl_basedir ? mtl_basedir : ""; if (!baseDir.empty()) { #ifndef _WIN32 const char dirsep = '/'; #else const char dirsep = '\\'; #endif if (baseDir[baseDir.length() - 1] != dirsep) baseDir += dirsep; } MaterialFileReader matFileReader(baseDir); return LoadObj(attrib, shapes, materials, warn, err, &ifs, &matFileReader, triangulate, default_vcols_fallback); } bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes, std::vector<material_t>* materials, std::string* warn, std::string* err, std::istream* inStream, MaterialReader* readMatFn /*= NULL*/, bool triangulate, bool default_vcols_fallback) { std::stringstream errss; std::vector<real_t> v; std::vector<real_t> vn; std::vector<real_t> vt; std::vector<real_t> vc; std::vector<skin_weight_t> vw; std::vector<tag_t> tags; PrimGroup prim_group; std::string name; // material std::map<std::string, int> material_map; int material = -1; // smoothing group id unsigned int current_smoothing_id = 0; // Initial value. 0 means no smoothing. int greatest_v_idx = -1; int greatest_vn_idx = -1; int greatest_vt_idx = -1; shape_t shape; bool found_all_colors = true; size_t line_num = 0; std::string linebuf; while (inStream->peek() != -1) { safeGetline(*inStream, linebuf); line_num++; // Trim newline '\r\n' or '\n' if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1); } if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\r') linebuf.erase(linebuf.size() - 1); } // Skip if empty line. if (linebuf.empty()) { continue; } // Skip leading space. const char* token = linebuf.c_str(); token += strspn(token, " \t"); assert(token); if (token[0] == '\0') continue; // empty line if (token[0] == '#') continue; // comment line // vertex if (token[0] == 'v' && IS_SPACE((token[1]))) { token += 2; real_t x, y, z; real_t r, g, b; found_all_colors &= parseVertexWithColor(&x, &y, &z, &r, &g, &b, &token); v.push_back(x); v.push_back(y); v.push_back(z); if (found_all_colors || default_vcols_fallback) { vc.push_back(r); vc.push_back(g); vc.push_back(b); } continue; } // normal if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { token += 3; real_t x, y, z; parseReal3(&x, &y, &z, &token); vn.push_back(x); vn.push_back(y); vn.push_back(z); continue; } // texcoord if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { token += 3; real_t x, y; parseReal2(&x, &y, &token); vt.push_back(x); vt.push_back(y); continue; } // skin weight. tinyobj extension if (token[0] == 'v' && token[1] == 'w' && IS_SPACE((token[2]))) { token += 3; // vw <vid> <joint_0> <weight_0> <joint_1> <weight_1> ... // example: // vw 0 0 0.25 1 0.25 2 0.5 // TODO(syoyo): Add syntax check int vid = 0; vid = parseInt(&token); skin_weight_t sw; sw.vertex_id = vid; while (!IS_NEW_LINE(token[0])) { real_t j, w; // joint_id should not be negative, weight may be negative // TODO(syoyo): # of elements check parseReal2(&j, &w, &token, -1.0); if (j < 0.0) { if (err) { std::stringstream ss; ss << "Failed parse `vw' line. joint_id is negative. " "line " << line_num << ".)\n"; (*err) += ss.str(); } return false; } joint_and_weight_t jw; jw.joint_id = int(j); jw.weight = w; sw.weightValues.push_back(jw); size_t n = strspn(token, " \t\r"); token += n; } vw.push_back(sw); } // line if (token[0] == 'l' && IS_SPACE((token[1]))) { token += 2; __line_t line; while (!IS_NEW_LINE(token[0])) { vertex_index_t vi; if (!parseTriple(&token, static_cast<int>(v.size() / 3), static_cast<int>(vn.size() / 3), static_cast<int>(vt.size() / 2), &vi)) { if (err) { std::stringstream ss; ss << "Failed parse `l' line(e.g. zero value for vertex index. " "line " << line_num << ".)\n"; (*err) += ss.str(); } return false; } line.vertex_indices.push_back(vi); size_t n = strspn(token, " \t\r"); token += n; } prim_group.lineGroup.push_back(line); continue; } // points if (token[0] == 'p' && IS_SPACE((token[1]))) { token += 2; __points_t pts; while (!IS_NEW_LINE(token[0])) { vertex_index_t vi; if (!parseTriple(&token, static_cast<int>(v.size() / 3), static_cast<int>(vn.size() / 3), static_cast<int>(vt.size() / 2), &vi)) { if (err) { std::stringstream ss; ss << "Failed parse `p' line(e.g. zero value for vertex index. " "line " << line_num << ".)\n"; (*err) += ss.str(); } return false; } pts.vertex_indices.push_back(vi); size_t n = strspn(token, " \t\r"); token += n; } prim_group.pointsGroup.push_back(pts); continue; } // face if (token[0] == 'f' && IS_SPACE((token[1]))) { token += 2; token += strspn(token, " \t"); face_t face; face.smoothing_group_id = current_smoothing_id; face.vertex_indices.reserve(3); while (!IS_NEW_LINE(token[0])) { vertex_index_t vi; if (!parseTriple(&token, static_cast<int>(v.size() / 3), static_cast<int>(vn.size() / 3), static_cast<int>(vt.size() / 2), &vi)) { if (err) { std::stringstream ss; ss << "Failed parse `f' line(e.g. zero value for face index. line " << line_num << ".)\n"; (*err) += ss.str(); } return false; } greatest_v_idx = greatest_v_idx > vi.v_idx ? greatest_v_idx : vi.v_idx; greatest_vn_idx = greatest_vn_idx > vi.vn_idx ? greatest_vn_idx : vi.vn_idx; greatest_vt_idx = greatest_vt_idx > vi.vt_idx ? greatest_vt_idx : vi.vt_idx; face.vertex_indices.push_back(vi); size_t n = strspn(token, " \t\r"); token += n; } // replace with emplace_back + std::move on C++11 prim_group.faceGroup.push_back(face); continue; } // use mtl if ((0 == strncmp(token, "usemtl", 6))) { token += 6; std::string namebuf = parseString(&token); int newMaterialId = -1; std::map<std::string, int>::const_iterator it = material_map.find(namebuf); if (it != material_map.end()) { newMaterialId = it->second; } else { // { error!! material not found } if (warn) { (*warn) += "material [ '" + namebuf + "' ] not found in .mtl\n"; } } if (newMaterialId != material) { // Create per-face material. Thus we don't add `shape` to `shapes` at // this time. // just clear `faceGroup` after `exportGroupsToShape()` call. exportGroupsToShape(&shape, prim_group, tags, material, name, triangulate, v, warn); prim_group.faceGroup.clear(); material = newMaterialId; } continue; } // load mtl if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { if (readMatFn) { token += 7; std::vector<std::string> filenames; SplitString(std::string(token), ' ', '\\', filenames); if (filenames.empty()) { if (warn) { std::stringstream ss; ss << "Looks like empty filename for mtllib. Use default " "material (line " << line_num << ".)\n"; (*warn) += ss.str(); } } else { bool found = false; for (size_t s = 0; s < filenames.size(); s++) { std::string warn_mtl; std::string err_mtl; bool ok = (*readMatFn)(filenames[s].c_str(), materials, &material_map, &warn_mtl, &err_mtl); if (warn && (!warn_mtl.empty())) { (*warn) += warn_mtl; } if (err && (!err_mtl.empty())) { (*err) += err_mtl; } if (ok) { found = true; break; } } if (!found) { if (warn) { (*warn) += "Failed to load material file(s). Use default " "material.\n"; } } } } continue; } // group name if (token[0] == 'g' && IS_SPACE((token[1]))) { // flush previous face group. bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, triangulate, v, warn); (void)ret; // return value not used. if (shape.mesh.indices.size() > 0) { shapes->push_back(shape); } shape = shape_t(); // material = -1; prim_group.clear(); std::vector<std::string> names; while (!IS_NEW_LINE(token[0])) { std::string str = parseString(&token); names.push_back(str); token += strspn(token, " \t\r"); // skip tag } // names[0] must be 'g' if (names.size() < 2) { // 'g' with empty names if (warn) { std::stringstream ss; ss << "Empty group name. line: " << line_num << "\n"; (*warn) += ss.str(); name = ""; } } else { std::stringstream ss; ss << names[1]; // tinyobjloader does not support multiple groups for a primitive. // Currently we concatinate multiple group names with a space to get // single group name. for (size_t i = 2; i < names.size(); i++) { ss << " " << names[i]; } name = ss.str(); } continue; } // object name if (token[0] == 'o' && IS_SPACE((token[1]))) { // flush previous face group. bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, triangulate, v, warn); (void)ret; // return value not used. if (shape.mesh.indices.size() > 0 || shape.lines.indices.size() > 0 || shape.points.indices.size() > 0) { shapes->push_back(shape); } // material = -1; prim_group.clear(); shape = shape_t(); // @todo { multiple object name? } token += 2; std::stringstream ss; ss << token; name = ss.str(); continue; } if (token[0] == 't' && IS_SPACE(token[1])) { const int max_tag_nums = 8192; // FIXME(syoyo): Parameterize. tag_t tag; token += 2; tag.name = parseString(&token); tag_sizes ts = parseTagTriple(&token); if (ts.num_ints < 0) { ts.num_ints = 0; } if (ts.num_ints > max_tag_nums) { ts.num_ints = max_tag_nums; } if (ts.num_reals < 0) { ts.num_reals = 0; } if (ts.num_reals > max_tag_nums) { ts.num_reals = max_tag_nums; } if (ts.num_strings < 0) { ts.num_strings = 0; } if (ts.num_strings > max_tag_nums) { ts.num_strings = max_tag_nums; } tag.intValues.resize(static_cast<size_t>(ts.num_ints)); for (size_t i = 0; i < static_cast<size_t>(ts.num_ints); ++i) { tag.intValues[i] = parseInt(&token); } tag.floatValues.resize(static_cast<size_t>(ts.num_reals)); for (size_t i = 0; i < static_cast<size_t>(ts.num_reals); ++i) { tag.floatValues[i] = parseReal(&token); } tag.stringValues.resize(static_cast<size_t>(ts.num_strings)); for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) { tag.stringValues[i] = parseString(&token); } tags.push_back(tag); continue; } if (token[0] == 's' && IS_SPACE(token[1])) { // smoothing group id token += 2; // skip space. token += strspn(token, " \t"); // skip space if (token[0] == '\0') { continue; } if (token[0] == '\r' || token[1] == '\n') { continue; } if (strlen(token) >= 3 && token[0] == 'o' && token[1] == 'f' && token[2] == 'f') { current_smoothing_id = 0; } else { // assume number int smGroupId = parseInt(&token); if (smGroupId < 0) { // parse error. force set to 0. // FIXME(syoyo): Report warning. current_smoothing_id = 0; } else { current_smoothing_id = static_cast<unsigned int>(smGroupId); } } continue; } // smoothing group id // Ignore unknown command. } // not all vertices have colors, no default colors desired? -> clear colors if (!found_all_colors && !default_vcols_fallback) { vc.clear(); } if (greatest_v_idx >= static_cast<int>(v.size() / 3)) { if (warn) { std::stringstream ss; ss << "Vertex indices out of bounds (line " << line_num << ".)\n" << std::endl; (*warn) += ss.str(); } } if (greatest_vn_idx >= static_cast<int>(vn.size() / 3)) { if (warn) { std::stringstream ss; ss << "Vertex normal indices out of bounds (line " << line_num << ".)\n" << std::endl; (*warn) += ss.str(); } } if (greatest_vt_idx >= static_cast<int>(vt.size() / 2)) { if (warn) { std::stringstream ss; ss << "Vertex texcoord indices out of bounds (line " << line_num << ".)\n" << std::endl; (*warn) += ss.str(); } } bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, triangulate, v, warn); // exportGroupsToShape return false when `usemtl` is called in the last // line. // we also add `shape` to `shapes` when `shape.mesh` has already some // faces(indices) if (ret || shape.mesh.indices .size()) { // FIXME(syoyo): Support other prims(e.g. lines) shapes->push_back(shape); } prim_group.clear(); // for safety if (err) { (*err) += errss.str(); } attrib->vertices.swap(v); attrib->vertex_weights.swap(v); attrib->normals.swap(vn); attrib->texcoords.swap(vt); attrib->texcoord_ws.swap(vt); attrib->colors.swap(vc); attrib->skin_weights.swap(vw); return true; } bool LoadObjWithCallback(std::istream& inStream, const callback_t& callback, void* user_data /*= NULL*/, MaterialReader* readMatFn /*= NULL*/, std::string* warn, /* = NULL*/ std::string* err /*= NULL*/) { std::stringstream errss; // material std::map<std::string, int> material_map; int material_id = -1; // -1 = invalid std::vector<index_t> indices; std::vector<material_t> materials; std::vector<std::string> names; names.reserve(2); std::vector<const char*> names_out; std::string linebuf; while (inStream.peek() != -1) { safeGetline(inStream, linebuf); // Trim newline '\r\n' or '\n' if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1); } if (linebuf.size() > 0) { if (linebuf[linebuf.size() - 1] == '\r') linebuf.erase(linebuf.size() - 1); } // Skip if empty line. if (linebuf.empty()) { continue; } // Skip leading space. const char* token = linebuf.c_str(); token += strspn(token, " \t"); assert(token); if (token[0] == '\0') continue; // empty line if (token[0] == '#') continue; // comment line // vertex if (token[0] == 'v' && IS_SPACE((token[1]))) { token += 2; // TODO(syoyo): Support parsing vertex color extension. real_t x, y, z, w; // w is optional. default = 1.0 parseV(&x, &y, &z, &w, &token); if (callback.vertex_cb) { callback.vertex_cb(user_data, x, y, z, w); } continue; } // normal if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { token += 3; real_t x, y, z; parseReal3(&x, &y, &z, &token); if (callback.normal_cb) { callback.normal_cb(user_data, x, y, z); } continue; } // texcoord if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { token += 3; real_t x, y, z; // y and z are optional. default = 0.0 parseReal3(&x, &y, &z, &token); if (callback.texcoord_cb) { callback.texcoord_cb(user_data, x, y, z); } continue; } // face if (token[0] == 'f' && IS_SPACE((token[1]))) { token += 2; token += strspn(token, " \t"); indices.clear(); while (!IS_NEW_LINE(token[0])) { vertex_index_t vi = parseRawTriple(&token); index_t idx; idx.vertex_index = vi.v_idx; idx.normal_index = vi.vn_idx; idx.texcoord_index = vi.vt_idx; indices.push_back(idx); size_t n = strspn(token, " \t\r"); token += n; } if (callback.index_cb && indices.size() > 0) { callback.index_cb(user_data, &indices.at(0), static_cast<int>(indices.size())); } continue; } // use mtl if ((0 == strncmp(token, "usemtl", 6)) && IS_SPACE((token[6]))) { token += 7; std::stringstream ss; ss << token; std::string namebuf = ss.str(); int newMaterialId = -1; std::map<std::string, int>::const_iterator it = material_map.find(namebuf); if (it != material_map.end()) { newMaterialId = it->second; } else { // { warn!! material not found } if (warn && (!callback.usemtl_cb)) { (*warn) += "material [ " + namebuf + " ] not found in .mtl\n"; } } if (newMaterialId != material_id) { material_id = newMaterialId; } if (callback.usemtl_cb) { callback.usemtl_cb(user_data, namebuf.c_str(), material_id); } continue; } // load mtl if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { if (readMatFn) { token += 7; std::vector<std::string> filenames; SplitString(std::string(token), ' ', '\\', filenames); if (filenames.empty()) { if (warn) { (*warn) += "Looks like empty filename for mtllib. Use default " "material. \n"; } } else { bool found = false; for (size_t s = 0; s < filenames.size(); s++) { std::string warn_mtl; std::string err_mtl; bool ok = (*readMatFn)(filenames[s].c_str(), &materials, &material_map, &warn_mtl, &err_mtl); if (warn && (!warn_mtl.empty())) { (*warn) += warn_mtl; // This should be warn message. } if (err && (!err_mtl.empty())) { (*err) += err_mtl; } if (ok) { found = true; break; } } if (!found) { if (warn) { (*warn) += "Failed to load material file(s). Use default " "material.\n"; } } else { if (callback.mtllib_cb) { callback.mtllib_cb(user_data, &materials.at(0), static_cast<int>(materials.size())); } } } } continue; } // group name if (token[0] == 'g' && IS_SPACE((token[1]))) { names.clear(); while (!IS_NEW_LINE(token[0])) { std::string str = parseString(&token); names.push_back(str); token += strspn(token, " \t\r"); // skip tag } assert(names.size() > 0); if (callback.group_cb) { if (names.size() > 1) { // create const char* array. names_out.resize(names.size() - 1); for (size_t j = 0; j < names_out.size(); j++) { names_out[j] = names[j + 1].c_str(); } callback.group_cb(user_data, &names_out.at(0), static_cast<int>(names_out.size())); } else { callback.group_cb(user_data, NULL, 0); } } continue; } // object name if (token[0] == 'o' && IS_SPACE((token[1]))) { // @todo { multiple object name? } token += 2; std::stringstream ss; ss << token; std::string object_name = ss.str(); if (callback.object_cb) { callback.object_cb(user_data, object_name.c_str()); } continue; } #if 0 // @todo if (token[0] == 't' && IS_SPACE(token[1])) { tag_t tag; token += 2; std::stringstream ss; ss << token; tag.name = ss.str(); token += tag.name.size() + 1; tag_sizes ts = parseTagTriple(&token); tag.intValues.resize(static_cast<size_t>(ts.num_ints)); for (size_t i = 0; i < static_cast<size_t>(ts.num_ints); ++i) { tag.intValues[i] = atoi(token); token += strcspn(token, "/ \t\r") + 1; } tag.floatValues.resize(static_cast<size_t>(ts.num_reals)); for (size_t i = 0; i < static_cast<size_t>(ts.num_reals); ++i) { tag.floatValues[i] = parseReal(&token); token += strcspn(token, "/ \t\r") + 1; } tag.stringValues.resize(static_cast<size_t>(ts.num_strings)); for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) { std::stringstream ss; ss << token; tag.stringValues[i] = ss.str(); token += tag.stringValues[i].size() + 1; } tags.push_back(tag); } #endif // Ignore unknown command. } if (err) { (*err) += errss.str(); } return true; } bool ObjReader::ParseFromFile(const std::string& filename, const ObjReaderConfig& config) { std::string mtl_search_path; if (config.mtl_search_path.empty()) { // // split at last '/'(for unixish system) or '\\'(for windows) to get // the base directory of .obj file // size_t pos = filename.find_last_of("/\\"); if (pos != std::string::npos) { mtl_search_path = filename.substr(0, pos); } } else { mtl_search_path = config.mtl_search_path; } valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_, filename.c_str(), mtl_search_path.c_str(), config.triangulate, config.vertex_color); return valid_; } bool ObjReader::ParseFromString(const std::string& obj_text, const std::string& mtl_text, const ObjReaderConfig& config) { std::stringbuf obj_buf(obj_text); std::stringbuf mtl_buf(mtl_text); std::istream obj_ifs(&obj_buf); std::istream mtl_ifs(&mtl_buf); MaterialStreamReader mtl_ss(mtl_ifs); valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_, &obj_ifs, &mtl_ss, config.triangulate, config.vertex_color); return valid_; } #ifdef __clang__ #pragma clang diagnostic pop #endif } // namespace tinyobj #endif
[ "ryan-wende@outlook.com" ]
ryan-wende@outlook.com
c3e0f39efe1b575568970a1f26d4c26f203f6206
9b1c54260c0b317c6ed6ce3eb22f4ced37c758c7
/packcompute/main.cpp
0939366e577134ddcffe40d65bc504bd1e256896
[]
no_license
vkirangoud/ALAFF
8174387a89bd453c8da3e9171033284778113e9f
04007b6633f1e2a88de69431df8201819ebbe800
refs/heads/master
2022-12-29T07:59:11.466875
2020-10-11T16:21:16
2020-10-11T16:21:16
278,116,604
1
0
null
2020-07-08T14:48:21
2020-07-08T14:48:20
null
UTF-8
C++
false
false
4,116
cpp
#include <stdio.h> #include <stdlib.h> #include "Params.h" size_t dgemm_pack_get_size(char identifier, const int m, const int n, const int k); size_t sgemm_pack_get_size(char identifier, const int m, const int n, const int k); void dgemm_pack_A(const dim_t m, const dim_t n, const dim_t k, const double alpha1, const double* src, const dim_t ld, double* dest); void sgemm_pack_A(const dim_t m, const dim_t n, const dim_t k, const float alpha1, const float* src, const dim_t ld, float* dest); void dgemmCompute(int m, int n, int k, double* A, int lda, double* B, int ldb, double* C, int ldc); void dumpPackBuffer(char* str, double* ap, dim_t numbytes); extern dim_t MC; extern dim_t KC; extern dim_t NC; int main(int argc, char** argv) { FILE* fp = NULL; int m, k, n; int lda, ldb, ldc; double* ap = NULL; double* bp = NULL; double* cp = NULL; double alpha1 = 1.0f; double* packbuf = NULL; if (argc < 2) { printf("Usage: ./PackMatrix.x input.txt \n"); exit(1); } fp = fopen(argv[1], "r"); if (fp == NULL) { printf("Error opening the input file %s \n", argv[1]); exit(1); } char filename[100]; printf("MC = %ld KC = %ld NC = %ld MR = %ld NR = %ld\n", MC, KC, NC, MR, NR); while (fscanf(fp, "%d %d %d %d %d %d\n", &m, &k, &n, &lda, &ldb, &ldc) == 6) { // Row major int nelems_A = (m - 1) * lda + (k - 1) * 1 + 1; // rs_a = lda, cs = 1 int nelems_B = (k - 1) * ldb + (n - 1) * 1 + 1; // rs_b = ldb, cs = 1 int nelems_C = (m - 1) * ldc + (n - 1) * 1 + 1; // rs_c = ldb, cs = 1 // column-major // int nelems_A = (m - 1) * 1 + (k - 1) * lda + 1; // rs_a = 1, cs = lda // int nelems_B = (k - 1) * 1 + (n - 1) * ldb + 1; // rs_b = 1, cs = ldb ap = (double*)malloc(sizeof(double) * nelems_A); if (ap == NULL) { printf("Error allocation memory A \n"); exit(1); } bp = (double*)malloc(sizeof(double) * nelems_B); if (bp == NULL) { printf("Error allocation memory B \n"); exit(1); } cp = (double*)malloc(sizeof(double) * nelems_C); if (cp == NULL) { printf("Error allocation memory C \n"); exit(1); } for (int i = 0; i < nelems_C; i++) cp[i] = 0.0; double* cp_ref = (double*)malloc(sizeof(double) * nelems_C); if (cp_ref == NULL) { printf("Error allocation memory C \n"); exit(1); } for (int i = 0; i < nelems_C; i++) cp_ref[i] = 0; // create a matrix row-major gen_random_matrix(ap, m, k, lda, 1); gen_random_matrix(bp, k, n, ldb, 1); // gen_random_matrix(cp_ref, m, n, ldc, 1); MyGemm_ref(m, n, k, ap, lda, bp, ldb, cp_ref, ldc); // Column-major matrices //gen_random_matrix(ap, m, k, 1, lda); //gen_random_matrix(bp, k, n, 1, ldb); // Compute the size of packed buffer dim_t totlBytes = dgemm_pack_get_size('A', m, n, k); // allocate memory to packed buffer packbuf = (double*)malloc(totlBytes); if (packbuf == NULL) { printf("Error allocating memory \n"); exit(1); } dim_t elements = totlBytes / sizeof(double); for (dim_t i = 0; i < elements; i++) packbuf[i] = 0.0; // Perform packing of A dgemm_pack_A(m, n, k, alpha1, ap, lda, packbuf); // sprintf(filename, "packA%d_%d_%d.txt", m, n, k); // Dump to a file // dumpPackBuffer(filename, packbuf, totlBytes); // Perform matrix multiplication //void dgemmCompute(int m, int n, int k, double* A, int lda, double* B, int ldb, double* C, int ldc) dgemmCompute(m, n, k, packbuf, lda, bp, ldb, cp, ldc); if (isMatrixMatch(cp_ref, cp, m, n, ldc) == 1) { printf(" %d %d %d %d %d %d ---> Passed\n", m, n, k, lda, ldb, ldc); } else { printf(" %d %d %d %d %d %d ---> Failed\n", m, n, k, lda, ldb, ldc); } free(ap); free(bp); free(cp); free(packbuf); } return 0; }
[ "kirangoud.v@gmail.com" ]
kirangoud.v@gmail.com
e3f91300ffb6a8296824d81f7e2d039b4dbb8d4b
9824d607fab0a0a827abff255865f320e2a7a692
/界面资源/[XTreme.Toolkit.9.6.MFC].Xtreme.Toolkit.Pro.v9.60/Samples/Common/MultiLanguage/MultiLanguageDoc.cpp
ead1ac329f5c39f5fe2b34ba516c7a6b16d84ba3
[]
no_license
tuian/pcshare
013b24af954b671aaf98604d6ab330def675a561
5d6455226d9720d65cfce841f8d00ef9eb09a5b8
refs/heads/master
2021-01-23T19:16:44.227266
2014-09-18T02:31:05
2014-09-18T02:31:05
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,514
cpp
// MultiLanguageDoc.cpp : implementation of the CMultiLanguageDoc class // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // ©1998-2005 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MultiLanguage.h" #include "MultiLanguageDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMultiLanguageDoc IMPLEMENT_DYNCREATE(CMultiLanguageDoc, CDocument) BEGIN_MESSAGE_MAP(CMultiLanguageDoc, CDocument) //{{AFX_MSG_MAP(CMultiLanguageDoc) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMultiLanguageDoc construction/destruction CMultiLanguageDoc::CMultiLanguageDoc() { // TODO: add one-time construction code here } CMultiLanguageDoc::~CMultiLanguageDoc() { } BOOL CMultiLanguageDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CMultiLanguageDoc serialization void CMultiLanguageDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } ///////////////////////////////////////////////////////////////////////////// // CMultiLanguageDoc diagnostics #ifdef _DEBUG void CMultiLanguageDoc::AssertValid() const { CDocument::AssertValid(); } void CMultiLanguageDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMultiLanguageDoc commands
[ "sincoder@vip.qq.com" ]
sincoder@vip.qq.com
0d3a9680bfb8459b4975b6be95f177bc7afd429c
b26cde55d82cda91243f945dc9d31f7ab3e8fb78
/src/qt/bitcoingui.cpp
af676d185a223d330aad9a5d59ca228126e2e141
[ "MIT" ]
permissive
GridBit/GridBit
e6482e999e785db051a813b5036b0aef1686fd52
4de0669d6c7a9b053ae24c570f211335390da396
refs/heads/master
2016-09-09T21:31:31.635190
2014-08-18T08:39:10
2014-08-18T08:39:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,119
cpp
/* * Qt4 bitcoin GUI. * * W.J. van der Laan 2011-2012 * The Bitcoin Developers 2011-2012 */ #include "bitcoingui.h" #include "transactiontablemodel.h" #include "addressbookpage.h" #include "sendcoinsdialog.h" #include "signverifymessagedialog.h" #include "optionsdialog.h" #include "aboutdialog.h" #include "clientmodel.h" #include "walletmodel.h" #include "editaddressdialog.h" #include "optionsmodel.h" #include "transactiondescdialog.h" #include "addresstablemodel.h" #include "transactionview.h" #include "overviewpage.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "askpassphrasedialog.h" #include "notificator.h" #include "guiutil.h" #include "rpcconsole.h" #include "wallet.h" #include "bitcoinrpc.h" #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include <QApplication> #include <QMainWindow> #include <QMenuBar> #include <QMenu> #include <QIcon> #include <QTabWidget> #include <QVBoxLayout> #include <QToolBar> #include <QStatusBar> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QLocale> #include <QMessageBox> #include <QProgressBar> #include <QStackedWidget> #include <QDateTime> #include <QMovie> #include <QFileDialog> #include <QDesktopServices> #include <QTimer> #include <QDragEnterEvent> #include <QUrl> #include <QStyle> #include <QMimeData> #include <iostream> extern CWallet *pwalletMain; extern int64 nLastCoinStakeSearchInterval; BitcoinGUI::BitcoinGUI(QWidget *parent): QMainWindow(parent), clientModel(0), walletModel(0), encryptWalletAction(0), changePassphraseAction(0), lockWalletToggleAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0) { resize(850, 550); setWindowTitle(tr("GridBit") + " - " + tr("Wallet")); #ifndef Q_OS_MAC qApp->setWindowIcon(QIcon(":icons/bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); #else setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Accept D&D of URIs setAcceptDrops(true); setObjectName("TheWallet"); setStyleSheet("#TheWallet { background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 #eeeeee, stop:1.0 #fefefe); } QToolTip { color: #cecece; background-color: #333333; border:0px;} "); // Create actions for the toolbar, menu bar and tray/dock icon createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create the tray icon (or setup the dock icon) createTrayIcon(); // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); transactionsPage->setLayout(vbox); addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab); receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab); sendCoinsPage = new SendCoinsDialog(this); signVerifyMessageDialog = new SignVerifyMessageDialog(this); centralWidget = new QStackedWidget(this); centralWidget->addWidget(overviewPage); centralWidget->addWidget(transactionsPage); centralWidget->addWidget(addressBookPage); centralWidget->addWidget(receiveCoinsPage); centralWidget->addWidget(sendCoinsPage); setCentralWidget(centralWidget); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); labelEncryptionIcon = new QLabel(); labelMintingIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelMintingIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); labelEncryptionIcon->setObjectName("labelEncryptionIcon"); labelConnectionsIcon->setObjectName("labelConnectionsIcon"); labelBlocksIcon->setObjectName("labelBlocksIcon"); labelMintingIcon->setObjectName("labelMintingIcon"); labelEncryptionIcon->setStyleSheet("#labelEncryptionIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); labelConnectionsIcon->setStyleSheet("#labelConnectionsIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); labelBlocksIcon->setStyleSheet("#labelBlocksIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); labelMintingIcon->setStyleSheet("#labelMintingIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); // Set minting pixmap labelMintingIcon->setPixmap(QIcon(":/icons/minting").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelMintingIcon->setEnabled(false); // Add timer to update minting icon QTimer *timerMintingIcon = new QTimer(labelMintingIcon); timerMintingIcon->start(MODEL_UPDATE_DELAY); connect(timerMintingIcon, SIGNAL(timeout()), this, SLOT(updateMintingIcon())); // Add timer to update minting weights QTimer *timerMintingWeights = new QTimer(labelMintingIcon); timerMintingWeights->start(30 * 1000); connect(timerMintingWeights, SIGNAL(timeout()), this, SLOT(updateMintingWeights())); // Set initial values for user and network weights nWeight, nNetworkWeight = 0; // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = qApp->style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); statusBar()->setObjectName("TheStatusBar"); statusBar()->setStyleSheet("#TheStatusBar { border-top-color: #102056; border-top-width: 2px; border-top-style: inset; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #102056, stop:1.0 #0a1536); background-image: url(:images/shadowbar); background-repeat: repeat-x; background-position: bottom center; color: #ffffff; }"); syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this); // this->setStyleSheet("background-color: #effbef;"); // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage())); connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // Clicking on "Verify Message" in the address book sends you to the verify message tab connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString))); // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString))); gotoOverviewPage(); } BitcoinGUI::~BitcoinGUI() { if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; #endif } void BitcoinGUI::createActions() { QActionGroup *tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setToolTip(tr("Show general overview of wallet")); overviewAction->setCheckable(true); overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this); sendCoinsAction->setToolTip(tr("Send coins to a GridBit address")); sendCoinsAction->setCheckable(true); sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this); receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments")); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setToolTip(tr("Browse transaction history")); historyAction->setCheckable(true); historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this); addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels")); addressBookAction->setCheckable(true); addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); tabGroup->addAction(addressBookAction); connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage())); quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setToolTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About GridBit"), this); aboutAction->setToolTip(tr("Show information about GridBit")); aboutAction->setMenuRole(QAction::AboutRole); aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); aboutQtAction->setToolTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setToolTip(tr("Modify configuration options for GridBit")); optionsAction->setMenuRole(QAction::PreferencesRole); toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setToolTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption")); lockWalletToggleAction = new QAction(this); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this); exportAction->setToolTip(tr("Export the data in the current tab to a file")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this); openRPCConsoleAction->setToolTip(tr("Open debugging and diagnostic console")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase())); connect(lockWalletToggleAction, SIGNAL(triggered()), this, SLOT(lockWalletToggle())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); file->addAction(backupWalletAction); file->addAction(exportAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(quitAction); QMenu *settings = appMenuBar->addMenu(tr("&Settings")); settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addAction(lockWalletToggleAction); settings->addSeparator(); settings->addAction(optionsAction); QMenu *help = appMenuBar->addMenu(tr("&Help")); help->addAction(openRPCConsoleAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); // QString ss("QMenuBar::item { background-color: #effbef; color: black }"); // appMenuBar->setStyleSheet(ss); } void BitcoinGUI::createToolBars() { QToolBar *toolbar = addToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); toolbar->addAction(addressBookAction); QToolBar *toolbar2 = addToolBar(tr("Actions toolbar")); toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar2->addAction(lockWalletToggleAction); toolbar2->addAction(exportAction); toolbar->setObjectName("tabsToolbar"); toolbar2->setObjectName("actionsToolbar"); const char ss[] = "QToolButton { min-height:48px;color:#ffffff;border:none;margin:0px;padding:0px;} QToolButton:hover { color: #ffffff; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #00bff3, stop:1.0 #0083a9); margin:0px; padding:0px; border:none; } QToolButton:checked, QToolButton:pressed, QToolButton:selected { color: #ffffff; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #0a1536, stop:1.0 #08102a); margin:0px; padding:0px; border:none;} #tabsToolbar, #actionsToolbar, QToolBar::handle { min-height:48px; color: #ffffff; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #102056, stop:1.0 #0c183d); margin:0px; padding:0px; border:none;}"; toolbar->setStyleSheet(ss); toolbar2->setStyleSheet(ss); } void BitcoinGUI::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; if(clientModel) { // Replace some strings and icons, when using the testnet if(clientModel->isTestNet()) { setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]")); #ifndef Q_OS_MAC qApp->setWindowIcon(QIcon(":icons/bitcoin_testnet")); setWindowIcon(QIcon(":icons/bitcoin_testnet")); #else MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); #endif if(trayIcon) { trayIcon->setToolTip(tr("GridBit client") + QString(" ") + tr("[testnet]")); trayIcon->setIcon(QIcon(":/icons/toolbar_testnet")); toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet")); } aboutAction->setIcon(QIcon(":/icons/toolbar_testnet")); } // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers()); connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Report errors from network/worker thread connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool))); rpcConsole->setClientModel(clientModel); addressBookPage->setOptionsModel(clientModel->getOptionsModel()); receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel()); } } void BitcoinGUI::setWalletModel(WalletModel *walletModel) { this->walletModel = walletModel; if(walletModel) { // Report errors from wallet thread connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool))); // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setModel(walletModel); addressBookPage->setModel(walletModel->getAddressTableModel()); receiveCoinsPage->setModel(walletModel->getAddressTableModel()); sendCoinsPage->setModel(walletModel); signVerifyMessageDialog->setModel(walletModel); setEncryptionStatus(walletModel->getEncryptionStatus()); connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int))); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(incomingTransaction(QModelIndex,int,int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); } } void BitcoinGUI::createTrayIcon() { QMenu *trayIconMenu; #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); trayIcon->setToolTip(tr("GridBit client")); trayIcon->setIcon(QIcon(":/icons/toolbar")); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); trayIcon->show(); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance(); trayIconMenu = dockIconHandler->dockMenu(); dockIconHandler->setMainWindow((QMainWindow*)this); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addAction(openRPCConsoleAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif notificator = new Notificator(qApp->applicationName(), trayIcon); } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHideAction->trigger(); } } #endif void BitcoinGUI::optionsClicked() { if(!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg; dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { AboutDialog dlg; dlg.setModel(clientModel); dlg.exec(); } void BitcoinGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to GridBit network.", "", count)); } void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks) { // don't show / hide progress bar and its label if we have no connection to the network if (!clientModel || clientModel->getNumConnections() == 0) { progressBarLabel->setVisible(false); progressBar->setVisible(false); return; } QString strStatusBarWarnings = clientModel->getStatusBarWarnings(); QString tooltip; if(count < nTotalBlocks) { int nRemainingBlocks = nTotalBlocks - count; float nPercentageDone = count / (nTotalBlocks * 0.01f); if (strStatusBarWarnings.isEmpty()) { progressBarLabel->setText(tr("Synchronizing with network...")); progressBarLabel->setVisible(true); progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks)); progressBar->setMaximum(nTotalBlocks); progressBar->setValue(count); progressBar->setVisible(true); } tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2); } else { if (strStatusBarWarnings.isEmpty()) progressBarLabel->setVisible(false); progressBar->setVisible(false); tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count); } // Override progressBarLabel text and hide progress bar, when we have warnings to display if (!strStatusBarWarnings.isEmpty()) { progressBarLabel->setText(strStatusBarWarnings); progressBarLabel->setVisible(true); progressBar->setVisible(false); } tooltip = tr("Current difficulty is %1.").arg(clientModel->GetDifficulty()) + QString("<br>") + tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); int secs = lastBlockDate.secsTo(QDateTime::currentDateTime()); QString text; // Represent time from last generated block in human readable text if(secs <= 0) { // Fully up to date. Leave text empty. } else if(secs < 60) { text = tr("%n second(s) ago","",secs); } else if(secs < 60*60) { text = tr("%n minute(s) ago","",secs/60); } else if(secs < 24*60*60) { text = tr("%n hour(s) ago","",secs/(60*60)); } else { text = tr("%n day(s) ago","",secs/(60*60*24)); } // Set icon state: spinning if catching up, tick otherwise if(secs < 90*60 && count >= nTotalBlocks) { tooltip = tr("Up to date") + QString(".<br>") + tooltip; labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); overviewPage->showOutOfSyncWarning(false); } else { tooltip = tr("Catching up...") + QString("<br>") + tooltip; labelBlocksIcon->setMovie(syncIconMovie); syncIconMovie->start(); overviewPage->showOutOfSyncWarning(true); } if(!text.isEmpty()) { tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1.").arg(text); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::error(const QString &title, const QString &message, bool modal) { // Report errors from network/worker thread if(modal) { QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok); } else { notificator->notify(Notificator::Critical, title, message); } } void BitcoinGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if(e->type() == QEvent::WindowStateChange) { if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e); if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent *event) { if(clientModel) { #ifndef Q_OS_MAC // Ignored on Mac if(!clientModel->getOptionsModel()->getMinimizeToTray() && !clientModel->getOptionsModel()->getMinimizeOnClose()) { qApp->quit(); } #endif } QMainWindow::closeEvent(event); } void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee) { QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, " "which goes to the nodes that process your transaction and helps to support the network. " "Do you want to pay the fee?").arg( BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired)); QMessageBox::StandardButton retval = QMessageBox::question( this, tr("Confirm transaction fee"), strMessage, QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes); *payFee = (retval == QMessageBox::Yes); } void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end) { if(!walletModel || !clientModel) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent) .data(Qt::EditRole).toULongLong(); if(!clientModel->inInitialBlockDownload()) { // On new transaction, make an info balloon // Unless the initial block download is in progress, to prevent balloon-spam QString date = ttm->index(start, TransactionTableModel::Date, parent) .data().toString(); QString type = ttm->index(start, TransactionTableModel::Type, parent) .data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent) .data().toString(); QIcon icon = qvariant_cast<QIcon>(ttm->index(start, TransactionTableModel::ToAddress, parent) .data(Qt::DecorationRole)); notificator->notify(Notificator::Information, (amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true)) .arg(type) .arg(address), icon); } } void BitcoinGUI::gotoOverviewPage() { overviewAction->setChecked(true); centralWidget->setCurrentWidget(overviewPage); exportAction->setEnabled(false); disconnect(exportAction, SIGNAL(triggered()), 0, 0); } void BitcoinGUI::gotoHistoryPage() { historyAction->setChecked(true); centralWidget->setCurrentWidget(transactionsPage); exportAction->setEnabled(true); disconnect(exportAction, SIGNAL(triggered()), 0, 0); connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked())); } void BitcoinGUI::gotoAddressBookPage() { addressBookAction->setChecked(true); centralWidget->setCurrentWidget(addressBookPage); exportAction->setEnabled(true); disconnect(exportAction, SIGNAL(triggered()), 0, 0); connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked())); } void BitcoinGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); centralWidget->setCurrentWidget(receiveCoinsPage); exportAction->setEnabled(true); disconnect(exportAction, SIGNAL(triggered()), 0, 0); connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked())); } void BitcoinGUI::gotoSendCoinsPage() { sendCoinsAction->setChecked(true); centralWidget->setCurrentWidget(sendCoinsPage); exportAction->setEnabled(false); disconnect(exportAction, SIGNAL(triggered()), 0, 0); } void BitcoinGUI::gotoSignMessageTab(QString addr) { // call show() in showTab_SM() signVerifyMessageDialog->showTab_SM(true); if(!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { // call show() in showTab_VM() signVerifyMessageDialog->showTab_VM(true); if(!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs if(event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls()) { int nValidUrisFound = 0; QList<QUrl> uris = event->mimeData()->urls(); foreach(const QUrl &uri, uris) { if (sendCoinsPage->handleURI(uri.toString())) nValidUrisFound++; } // if valid URIs were found if (nValidUrisFound) gotoSendCoinsPage(); else notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid GridBit address or malformed URI parameters.")); } event->acceptProposedAction(); } void BitcoinGUI::handleURI(QString strURI) { // URI has to be valid if (sendCoinsPage->handleURI(strURI)) { showNormalIfMinimized(); gotoSendCoinsPage(); } else notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid GridBit address or malformed URI parameters.")); } void BitcoinGUI::setEncryptionStatus(int status) { switch(status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); encryptWalletAction->setEnabled(true); changePassphraseAction->setEnabled(false); lockWalletToggleAction->setVisible(false); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>.")); encryptWalletAction->setChecked(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported changePassphraseAction->setEnabled(true); lockWalletToggleAction->setVisible(true); lockWalletToggleAction->setIcon(QIcon(":/icons/lock_closed")); lockWalletToggleAction->setText(tr("&Lock Wallet")); lockWalletToggleAction->setToolTip(tr("Lock wallet")); break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>.")); encryptWalletAction->setChecked(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported changePassphraseAction->setEnabled(true); lockWalletToggleAction->setVisible(true); lockWalletToggleAction->setIcon(QIcon(":/icons/lock_open")); lockWalletToggleAction->setText(tr("&Unlock Wallet...")); lockWalletToggleAction->setToolTip(tr("Unlock wallet")); break; } } void BitcoinGUI::encryptWallet(bool status) { if(!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt: AskPassphraseDialog::Decrypt, this); dlg.setModel(walletModel); dlg.exec(); setEncryptionStatus(walletModel->getEncryptionStatus()); } void BitcoinGUI::backupWallet() { QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)")); if(!filename.isEmpty()) { if(!walletModel->backupWallet(filename)) { QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location.")); } } } void BitcoinGUI::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this); dlg.setModel(walletModel); dlg.exec(); } void BitcoinGUI::lockWalletToggle() { if(!walletModel) return; // Unlock wallet when requested by wallet model if(walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog::Mode mode = AskPassphraseDialog::UnlockMinting; AskPassphraseDialog dlg(mode, this); dlg.setModel(walletModel); dlg.exec(); } else walletModel->setWalletLocked(true); } void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if(fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::updateMintingIcon() { if (pwalletMain && pwalletMain->IsLocked()) { labelMintingIcon->setToolTip(tr("Not minting because wallet is locked.")); labelMintingIcon->setEnabled(false); } else if (vNodes.empty()) { labelMintingIcon->setToolTip(tr("Not minting because wallet is offline.")); labelMintingIcon->setEnabled(false); } else if (IsInitialBlockDownload()) { labelMintingIcon->setToolTip(tr("Not minting because wallet is syncing.")); labelMintingIcon->setEnabled(false); } else if (!nWeight) { labelMintingIcon->setToolTip(tr("Not minting because you don't have mature coins.")); labelMintingIcon->setEnabled(false); } else if (nLastCoinStakeSearchInterval) { uint64 nEstimateTime = nTargetSpacing * nNetworkWeight / nWeight; QString text; if (nEstimateTime < 60) { text = tr("%n second(s)", "", nEstimateTime); } else if (nEstimateTime < 60*60) { text = tr("%n minute(s)", "", nEstimateTime/60); } else if (nEstimateTime < 24*60*60) { text = tr("%n hour(s)", "", nEstimateTime/(60*60)); } else { text = tr("%n day(s)", "", nEstimateTime/(60*60*24)); } labelMintingIcon->setEnabled(true); labelMintingIcon->setToolTip(tr("Minting.<br>Your weight is %1.<br>Network weight is %2.<br>Expected time to earn reward is %3.").arg(nWeight).arg(nNetworkWeight).arg(text)); } else { labelMintingIcon->setToolTip(tr("Not minting.")); labelMintingIcon->setEnabled(false); } } void BitcoinGUI::updateMintingWeights() { // Only update if we have the network's current number of blocks, or weight(s) are zero (fixes lagging GUI) if ((clientModel && clientModel->getNumBlocks() == clientModel->getNumBlocksOfPeers()) || !nWeight || !nNetworkWeight) { nWeight = 0; if (pwalletMain) pwalletMain->GetStakeWeight(*pwalletMain, nMinMax, nMinMax, nWeight); nNetworkWeight = GetPoSKernelPS(); } }
[ "team@gridbit.co" ]
team@gridbit.co
eb47c11b5270f7dd13f629b5b9580151d45549a2
9cdb592be8149d1d6f832be40947c270363bfb2f
/c2c/Algo/DepVisitor.cpp
8210e6d42256af3d34aa1318975d9c24be2bd700
[]
no_license
luciusmagn/c2compiler
56a66d3afd527b34964b25228cdc79248db74856
b30b4be152f803b6ad3e3f8b466964efe361ddbf
refs/heads/master
2021-01-17T07:30:29.567539
2018-05-03T11:08:30
2018-05-03T11:08:30
90,610,186
1
0
null
2018-05-03T11:08:31
2017-05-08T09:27:47
C++
UTF-8
C++
false
false
9,392
cpp
/* Copyright 2013-2018 Bas van den Berg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include "Algo/DepVisitor.h" #include "AST/Type.h" #include "AST/Decl.h" #include "AST/Stmt.h" #include "AST/Expr.h" using namespace C2; void DepVisitor::run() { //fprintf(stderr, "CHECKING %s\n", decl->getName()); checkDecl(decl); } void DepVisitor::checkDecl(const Decl* D) { switch (D->getKind()) { case DECL_FUNC: checkFunctionDecl(cast<FunctionDecl>(D)); break; case DECL_VAR: checkVarDecl(cast<VarDecl>(D)); break; case DECL_ENUMVALUE: assert(0); break; case DECL_ALIASTYPE: checkType(cast<AliasTypeDecl>(D)->getRefType()); break; case DECL_STRUCTTYPE: { const StructTypeDecl* S = cast<StructTypeDecl>(D); for (unsigned i=0; i<S->numMembers(); i++) { checkDecl(S->getMember(i)); } break; } case DECL_ENUMTYPE: { const EnumTypeDecl* E = cast<EnumTypeDecl>(D); for (unsigned i=0; i<E->numConstants(); i++) { const EnumConstantDecl* ECD = E->getConstant(i); if (ECD->getInitValue()) checkExpr(ECD->getInitValue()); } break; } case DECL_FUNCTIONTYPE: { const FunctionTypeDecl* F = cast<FunctionTypeDecl>(D); checkFunctionDecl(F->getDecl()); break; } case DECL_ARRAYVALUE: assert(0 && "TODO"); break; case DECL_IMPORT: case DECL_LABEL: break; } } void DepVisitor::checkFunctionDecl(const FunctionDecl* F) { // return Type checkType(F->getReturnType()); // args for (unsigned i=0; i<F->numArgs(); i++) { checkVarDecl(F->getArg(i)); } // check body if (F->getBody()) checkCompoundStmt(F->getBody()); } void DepVisitor::checkVarDecl(const VarDecl* V) { checkType(V->getType()); if (V->getInitValue()) checkExpr(V->getInitValue()); } void DepVisitor::checkType(QualType Q, bool isFullDep) { const Type* T = Q.getTypePtr(); switch (T->getTypeClass()) { case TC_BUILTIN: return; case TC_POINTER: checkType(cast<PointerType>(T)->getPointeeType(), false); break; case TC_ARRAY: { const ArrayType* A = cast<ArrayType>(T); checkType(A->getElementType(), isFullDep); if (A->getSizeExpr()) checkExpr(A->getSizeExpr()); break; } case TC_UNRESOLVED: addDep(cast<UnresolvedType>(T)->getDecl(), isFullDep); break; case TC_ALIAS: addDep(cast<AliasType>(T)->getDecl(), isFullDep); break; case TC_STRUCT: addDep(cast<StructType>(T)->getDecl(), isFullDep); break; case TC_ENUM: addDep(cast<EnumType>(T)->getDecl(), isFullDep); break; case TC_FUNCTION: addDep(cast<FunctionType>(T)->getDecl(), isFullDep); break; case TC_MODULE: assert(0); break; } } void DepVisitor::checkStmt(const Stmt* S) { assert(S); switch (S->getKind()) { case STMT_RETURN: { const ReturnStmt* R = cast<ReturnStmt>(S); if (R->getExpr()) checkExpr(R->getExpr()); break; } case STMT_EXPR: checkExpr(cast<Expr>(S)); break; case STMT_IF: { const IfStmt* I = cast<IfStmt>(S); checkStmt(I->getCond()); checkStmt(I->getThen()); if (I->getElse()) checkStmt(I->getElse()); break; } case STMT_WHILE: { const WhileStmt* W = cast<WhileStmt>(S); checkStmt(W->getCond()); checkStmt(W->getBody()); break; } case STMT_DO: { const DoStmt* D = cast<DoStmt>(S); checkStmt(D->getCond()); checkStmt(D->getBody()); break; } case STMT_FOR: { const ForStmt* F = cast<ForStmt>(S); if (F->getInit()) checkStmt(F->getInit()); if (F->getCond()) checkExpr(F->getCond()); if (F->getIncr()) checkExpr(F->getIncr()); checkStmt(F->getBody()); break; } case STMT_SWITCH: { const SwitchStmt* SW = cast<SwitchStmt>(S); checkStmt(SW->getCond()); Stmt** cases = SW->getCases(); for (unsigned i=0; i<SW->numCases(); i++) { checkStmt(cases[i]); } break; } case STMT_CASE: { const CaseStmt* C = cast<CaseStmt>(S); checkExpr(C->getCond()); Stmt** stmts = C->getStmts(); for (unsigned i=0; i<C->numStmts(); i++) { checkStmt(stmts[i]); } break; } case STMT_DEFAULT: { const DefaultStmt* D = cast<DefaultStmt>(S); Stmt** stmts = D->getStmts(); for (unsigned i=0; i<D->numStmts(); i++) { checkStmt(stmts[i]); } break; } case STMT_BREAK: case STMT_CONTINUE: case STMT_LABEL: case STMT_GOTO: break; case STMT_COMPOUND: checkCompoundStmt(cast<CompoundStmt>(S)); break; case STMT_DECL: checkVarDecl(cast<DeclStmt>(S)->getDecl()); break; } } void DepVisitor::checkCompoundStmt(const CompoundStmt* C) { Stmt** stmts = C->getStmts(); for (unsigned i=0; i<C->numStmts(); i++) { checkStmt(stmts[i]); } } void DepVisitor::checkExpr(const Expr* E) { assert(E); switch (E->getKind()) { case EXPR_INTEGER_LITERAL: case EXPR_FLOAT_LITERAL: case EXPR_BOOL_LITERAL: case EXPR_CHAR_LITERAL: case EXPR_STRING_LITERAL: case EXPR_NIL: break; case EXPR_IDENTIFIER: addDep(cast<IdentifierExpr>(E)->getDecl()); break; case EXPR_TYPE: // only in sizeof(int), so no need to check here break; case EXPR_CALL: { const CallExpr* C = cast<CallExpr>(E); checkExpr(C->getFn()); for (unsigned i=0; i<C->numArgs(); i++) { checkExpr(C->getArg(i)); } break; } case EXPR_INITLIST: { const InitListExpr* I = cast<InitListExpr>(E); Expr** values = I->getValues(); for (unsigned i=0; i<I->numValues(); i++) { checkExpr(values[i]); } break; } case EXPR_DESIGNATOR_INIT: break; case EXPR_BINOP: { const BinaryOperator* B = cast<BinaryOperator>(E); checkExpr(B->getLHS()); checkExpr(B->getRHS()); break; } case EXPR_CONDOP: { const ConditionalOperator* C = cast<ConditionalOperator>(E); checkExpr(C->getCond()); checkExpr(C->getLHS()); checkExpr(C->getRHS()); break; } case EXPR_UNARYOP: checkExpr(cast<UnaryOperator>(E)->getExpr()); break; case EXPR_BUILTIN: checkExpr(cast<BuiltinExpr>(E)->getExpr()); break; case EXPR_ARRAYSUBSCRIPT: { const ArraySubscriptExpr* A = cast<ArraySubscriptExpr>(E); checkExpr(A->getBase()); checkExpr(A->getIndex()); break; } case EXPR_MEMBER: { const MemberExpr* M = cast<MemberExpr>(E); if (M->isModulePrefix()) { addDep(M->getDecl()); } else { checkExpr(M->getBase()); if (M->isStructFunction()) addDep(M->getDecl()); } break; } case EXPR_PAREN: checkExpr(cast<ParenExpr>(E)->getExpr()); break; case EXPR_BITOFFSET: { const BitOffsetExpr* B = cast<BitOffsetExpr>(E); checkExpr(B->getLHS()); checkExpr(B->getRHS()); break; } break; case EXPR_CAST: { const ExplicitCastExpr* ECE = cast<ExplicitCastExpr>(E); checkExpr(ECE->getInner()); checkType(ECE->getDestType()); } break; } } void DepVisitor::addDep(const Decl* D, bool isFullDep) { assert(D); // Skip local VarDecls if (const VarDecl* V = dyncast<VarDecl>(D)) { switch (V->getVarKind()) { case VARDECL_GLOBAL: break; case VARDECL_LOCAL: case VARDECL_PARAM: return; case VARDECL_MEMBER: break; } } if (!checkExternals && D->getModule() != decl->getModule()) return; // Convert EnumConstants -> EnumTypeDecl (via EnumType) if (const EnumConstantDecl* ECD = dyncast<EnumConstantDecl>(D)) { QualType Q = ECD->getType(); const EnumType* T = cast<EnumType>(Q.getTypePtr()); D = T->getDecl(); } for (unsigned i=0; i<deps.size(); i++) { if (getDep(i) == D) { // update pointer to full if needed if (isFullDep) deps[i] |= 0x1; return; } } deps.push_back((uintptr_t)D | isFullDep); //fprintf(stderr, " %s -> %s %p (%s)\n", decl->getName(), D->getName(), D, isFullDep ? "full" : "pointer"); }
[ "b.van.den.berg.nl@gmail.com" ]
b.van.den.berg.nl@gmail.com
0c34bebafb67054c2cabd621507755b8e086cc58
16c2b8eae3103348a7a8a8addb08071d5a4e70e2
/main.cpp
a20894cb32a17e98c6316c6eea5a988a1e687a38
[ "MIT" ]
permissive
lcala99/MakeIThome
f1bae8497c03f34e142a677a4591fc4012de0619
dc8767391bb64c96e5374670d7ceb494050b081b
refs/heads/main
2023-07-31T13:41:38.559305
2021-09-21T14:22:54
2021-09-21T14:22:54
408,850,298
0
0
null
null
null
null
UTF-8
C++
false
false
331
cpp
#include <QApplication> #include <iostream> #include "view.h" #include "model.h" #include "controller.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Catalogo cat; Model model(cat); Controller controller(&model); View* view = new View(&controller); view->show(); return a.exec(); }
[ "40360727+lcala99@users.noreply.github.com" ]
40360727+lcala99@users.noreply.github.com
d372ddefe8f11abd5c3ca0332453c81a962f6458
a13e7993275058dceae188f2101ad0750501b704
/2022/2133. Check if Every Row and Column Contains All Numbers.cpp
8bbc268b380af48d29bb0f4dfa0b3b5406021855
[]
no_license
yangjufo/LeetCode
f8cf8d76e5f1e78cbc053707af8bf4df7a5d1940
15a4ab7ce0b92b0a774ddae0841a57974450eb79
refs/heads/master
2023-09-01T01:52:49.036101
2023-08-31T00:23:19
2023-08-31T00:23:19
126,698,393
0
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
class Solution { public: bool checkValid(vector<vector<int>>& matrix) { int n = matrix.size(); for (int i = 0; i < n; i++) { vector<int> found(n + 1, false); int count = 0; for (int j = 0; j < n; j++) { if (found[matrix[i][j]] == false) { found[matrix[i][j]] = true; count++; } } if (count < n) { return false; } } for (int j = 0; j < n; j++) { vector<int> found(n + 1, false); int count = 0; for (int i = 0; i < n; i++) { if (found[matrix[i][j]] == false) { found[matrix[i][j]] = true; count++; } } if (count < n) { return false; } } return true; } };
[ "yangjufo@gmail.com" ]
yangjufo@gmail.com
833fcda85fe69da76ef2424e0bc0a0f2dd1a84c9
8200cae3d64bc7e05f5033c70f31717d7592302b
/libraries/touchgfx_lib/TouchGFX/generated/fonts/src/Font_simkai_30_4bpp_9.cpp
e8a5c0f594a792fcbd7a0e12744e10b9566f24dd
[]
no_license
yixiangwenhai/Wisdom-agriculture_RTT
05598a44fd18e1358279034cb5c74d4d97ad7c15
42f9395786e814e9d5348fcaefa57c0ad1f176a4
refs/heads/master
2023-09-01T04:31:34.083477
2021-09-28T10:28:38
2021-09-28T10:28:38
411,233,186
0
0
null
null
null
null
UTF-8
C++
false
false
1,677
cpp
#include <touchgfx/hal/Types.hpp> FONT_GLYPH_LOCATION_FLASH_PRAGMA KEEP extern const uint8_t unicodes_simkai_30_4bpp_9[] FONT_GLYPH_LOCATION_FLASH_ATTRIBUTE = { // Unicode: [0x4E8C] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0xA7, 0x7B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x44, 0x65, 0x98, 0xEC, 0xFF, 0xFF, 0xEF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xFC, 0xFF, 0xEF, 0x9B, 0x57, 0x34, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x74, 0xB9, 0xCD, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x75, 0xA8, 0xEC, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0x01, 0xA6, 0xBA, 0xDC, 0xFE, 0xFF, 0xFF, 0xDF, 0xBC, 0x89, 0x77, 0x66, 0x87, 0xA9, 0x04, 0x81, 0xFE, 0xDF, 0x9B, 0x57, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
[ "921036028@qq.com" ]
921036028@qq.com
03fd3b8c0ccfe7473fd4d3448b4c64d31898cb8a
d9a6b301d938e76dc94a8f4a0159abf627da1f1f
/game/Source/attacker.cpp
6b15c78d53097ac1a7ce278274ec39f9a69344c0
[]
no_license
benjcleveland/UW-Game
ea3c1111d86c35075f6c6305ca78c3e14037b13b
83722919c9ed464639dee5b0f890bed90b163bfb
refs/heads/master
2021-01-02T09:14:47.578658
2012-05-02T02:01:47
2012-05-02T02:01:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,115
cpp
/* Copyright Steve Rabin, 2008. * All rights reserved worldwide. * * This software is provided "as is" without express or implied * warranties. You may freely copy and compile this source into * applications you distribute provided that the copyright text * below is included in the resulting source code, for example: * "Portions Copyright Steve Rabin, 2008" */ #include "DXUT.h" #include "attacker.h" #include "database.h" #include "collision.h" #include "Tiny.h" #include "deathsm.h" // another hack extern VecCollQuad vecCollQuad; extern CTiny *g_pPlayer; //Add new states here enum StateName { STATE_Initialize, //Note: the first enum is the starting state STATE_Idle, STATE_AttackPlayer, STATE_Runaway, STATE_ArrivedAtLocation }; //Add new substates here enum SubstateName { SUBSTATE_RenameThisSubstate1, SUBSTATE_RenameThisSubstate2, SUBSTATE_RenameThisSubstate3 }; bool Attacker::States( State_Machine_Event event, MSG_Object * msg, int state, int substate ) { BeginStateMachine //Global message responses go here /* Not currently used */ OnMsg( MSG_CollisionPlayer ) // stop moving m_owner->getMovement()->setTarget(m_owner->getMovement()->getPosition()); //ChangeStateDelayed(10, STATE_Runaway ); OnMsg(MSG_ASTAR_DEBUG) // toggle a star debugging m_owner->setAStarDebug(msg->GetBoolData()); OnMsg(MSG_NPCHitByProjectile) // npc has been hit - replace this sm with death state machine ReplaceStateMachine( *new Death(*m_owner)); OnMsg(MSG_Reset) m_owner->getMovement()->reset(); //PopStateMachine(); /////////////////////////////////////////////////////////////// DeclareState( STATE_Initialize ) OnEnter ChangeState( STATE_Idle ); /////////////////////////////////////////////////////////////// DeclareState( STATE_Idle ) OnEnter // make sure we can see the player and we are within the appropriate distance bool see_player = runNPCSeePlayer(&m_owner->getMovement()->getPosition(), &g_pPlayer->GetPosition()); float dist = D3DXVec3Length( &(m_owner->getMovement()->getPosition() - g_pPlayer->GetPosition())); if( see_player == true && dist < 5) { // change the state to seeking the player ChangeState( STATE_AttackPlayer ); } else { // we can't see the player so go back to wandering // do this by removing the attacker statemachine PopStateMachine(); } /////////////////////////////////////////////////////////////// DeclareState( STATE_AttackPlayer ) OnEnter // change the color of the debug line m_owner->getDebugLine()->setColor(D3DCOLOR_COLORVALUE(1,0,0,1)); // make sure we are facing the player m_owner->getMovement()->setDestLocation( g_pPlayer->GetPosition()); // attack the player!, after some delay... SendMsgDelayedToState(RandDelay(1,2),MSG_Attack,MSG_Data()); OnMsg( MSG_Attack ) // create the name of the projectile char name[10] = "PROJ"; sprintf(name, "%s%s", name, &m_owner->GetName()[3]); // we have attacked the player so now run away SendMsg( MSG_ProjectileLaunch, g_database.GetIDByName( name), MSG_Data( m_owner->getMovement()->getPosition())); // runaway from the player ChangeState( STATE_Runaway ); /////////////////////////////////////////////////////////////// DeclareState( STATE_Runaway ) OnEnter // determine a location behind the NPC to run to D3DXVECTOR3 diff = m_owner->getNPC()->getFacing(); D3DXVECTOR3 move_pos = D3DXVECTOR3(5,0,5); move_pos.x *= diff.x; move_pos.z *= diff.z; move_pos = m_owner->getMovement()->getPosition() - move_pos; if( move_pos.x <= 2.f ) move_pos.x = 2.5f; if( move_pos.z <= 2.f ) move_pos.z = 2.5f; // verify the location D3DXVECTOR3 coll_pos; // Verify the location, ie, no collision bool collision = runNPCSeePlayer(&m_owner->getMovement()->getPosition(), &move_pos, coll_pos); // update the target if necessary, this kindof works.... if( collision == false ) // false means there was a collision { //if( (int)move_pos.x != (int)coll_pos.x ) { coll_pos.x += .5f*((coll_pos.x > move_pos.x) ? 1 : -1); } //if( (int) move_pos.z != (int)coll_pos.z ) coll_pos.z += .5f*((coll_pos.z > move_pos.z) ? 1 : -1); // hack if( coll_pos.z <= 2 ) coll_pos.z = 2.f; if( coll_pos.x <= 2 ) coll_pos.x = 2.f; // update the seek location m_owner->getMovement()->setDestLocation( coll_pos ); } else // change the location m_owner->getMovement()->setDestLocation( move_pos); // change the color of the debug line m_owner->getDebugLine()->setColor(D3DCOLOR_COLORVALUE(0,1,0,1)); OnMsg( MSG_Arrived ) // arrived at the destination, change state to arrived ChangeState( STATE_ArrivedAtLocation ); /////////////////////////////////////////////////////////////// DeclareState( STATE_ArrivedAtLocation ) OnEnter SendMsgDelayedToState( RandDelay(1,2), MSG_DoneSleeping, MSG_Data()); OnMsg( MSG_DoneSleeping ) // pop the state machine PopStateMachine(); EndStateMachine }
[ "ben.j.cleveland@gmail.com" ]
ben.j.cleveland@gmail.com
8aff237ad928fc7f4f073a19ae40c83def6cbe8e
9b87c038a5ce9b3c0caabb35cd1b8bf44a19c1da
/ColdEyes/Pattern/IDataHandler.h
4928ffecf2840890c50ec76a82c7318ed1f28147
[]
no_license
EmbededMind/ColdEyes
98d519bf80d7f090ce65338d6aae473d07b4731e
3cb007a76345f0f5751024b66e62a775c32de7f2
refs/heads/master
2021-01-11T08:47:14.230784
2017-01-05T02:05:56
2017-01-05T02:05:56
76,835,389
1
1
null
null
null
null
UTF-8
C++
false
false
105
h
#pragma once class IDataHandler { public: virtual void HandleData(UINT8* pData, size_t length) = 0; };
[ "815407069@qq.com" ]
815407069@qq.com
e2129ad55265c73467eb7bf73a7b9942cc21c24c
3f3a42f429f8bcd769644148b24c3b0e6e2589ed
/GameProject/GameEngine/EngineCore/Math/Matrix.h
8265f6abdf7c338a22c320735afd62996914f750
[]
no_license
DanielNeander/my-3d-engine
d10ad3e57a205f6148357f47467b550c7e0e0f33
7f0babbfdf0b719ea4b114a89997d3e52bcb2b6c
refs/heads/master
2021-01-10T17:58:25.691360
2013-04-24T07:37:31
2013-04-24T07:37:31
53,236,587
3
0
null
null
null
null
UTF-8
C++
false
false
96,382
h
#ifndef MATH_MATRIX_H #define MATH_MATRIX_H #include "Vector.h" #define MATRIX_INVERSE_EPSILON 1e-14 #define MATRIX_EPSILON 1e-6 class noAngles; class noRotation; class noQuat; class idCQuat; class noMat4; //=============================================================== // // noMat2 - 2x2 matrix // //=============================================================== class noMat2 { public: noMat2( void ); explicit noMat2( const noVec2 &x, const noVec2 &y ); explicit noMat2( const float xx, const float xy, const float yx, const float yy ); explicit noMat2( const float src[ 2 ][ 2 ] ); const noVec2 & operator[]( int index ) const; noVec2 & operator[]( int index ); noMat2 operator-() const; noMat2 operator*( const float a ) const; noVec2 operator*( const noVec2 &vec ) const; noMat2 operator*( const noMat2 &a ) const; noMat2 operator+( const noMat2 &a ) const; noMat2 operator-( const noMat2 &a ) const; noMat2 & operator*=( const float a ); noMat2 & operator*=( const noMat2 &a ); noMat2 & operator+=( const noMat2 &a ); noMat2 & operator-=( const noMat2 &a ); friend noMat2 operator*( const float a, const noMat2 &mat ); friend noVec2 operator*( const noVec2 &vec, const noMat2 &mat ); friend noVec2 & operator*=( noVec2 &vec, const noMat2 &mat ); bool Compare( const noMat2 &a ) const; // exact compare, no epsilon bool Compare( const noMat2 &a, const float epsilon ) const; // compare with epsilon bool operator==( const noMat2 &a ) const; // exact compare, no epsilon bool operator!=( const noMat2 &a ) const; // exact compare, no epsilon void Zero( void ); void Identity( void ); bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const; bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const; float Trace( void ) const; float Determinant( void ) const; noMat2 Transpose( void ) const; // returns transpose noMat2 & TransposeSelf( void ); noMat2 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseSelf( void ); // returns false if determinant is zero noMat2 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseFastSelf( void ); // returns false if determinant is zero int GetDimension( void ) const; const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; private: noVec2 mat[ 2 ]; }; extern noMat2 mat2_zero; extern noMat2 mat2_identity; #define mat2_default mat2_identity NO_INLINE noMat2::noMat2( void ) { } NO_INLINE noMat2::noMat2( const noVec2 &x, const noVec2 &y ) { mat[ 0 ].x = x.x; mat[ 0 ].y = x.y; mat[ 1 ].x = y.x; mat[ 1 ].y = y.y; } NO_INLINE noMat2::noMat2( const float xx, const float xy, const float yx, const float yy ) { mat[ 0 ].x = xx; mat[ 0 ].y = xy; mat[ 1 ].x = yx; mat[ 1 ].y = yy; } NO_INLINE noMat2::noMat2( const float src[ 2 ][ 2 ] ) { memcpy( mat, src, 2 * 2 * sizeof( float ) ); } NO_INLINE const noVec2 &noMat2::operator[]( int index ) const { //assert( ( index >= 0 ) && ( index < 2 ) ); return mat[ index ]; } NO_INLINE noVec2 &noMat2::operator[]( int index ) { //assert( ( index >= 0 ) && ( index < 2 ) ); return mat[ index ]; } NO_INLINE noMat2 noMat2::operator-() const { return noMat2( -mat[0][0], -mat[0][1], -mat[1][0], -mat[1][1] ); } NO_INLINE noVec2 noMat2::operator*( const noVec2 &vec ) const { return noVec2( mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y, mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y ); } NO_INLINE noMat2 noMat2::operator*( const noMat2 &a ) const { return noMat2( mat[0].x * a[0].x + mat[0].y * a[1].x, mat[0].x * a[0].y + mat[0].y * a[1].y, mat[1].x * a[0].x + mat[1].y * a[1].x, mat[1].x * a[0].y + mat[1].y * a[1].y ); } NO_INLINE noMat2 noMat2::operator*( const float a ) const { return noMat2( mat[0].x * a, mat[0].y * a, mat[1].x * a, mat[1].y * a ); } NO_INLINE noMat2 noMat2::operator+( const noMat2 &a ) const { return noMat2( mat[0].x + a[0].x, mat[0].y + a[0].y, mat[1].x + a[1].x, mat[1].y + a[1].y ); } NO_INLINE noMat2 noMat2::operator-( const noMat2 &a ) const { return noMat2( mat[0].x - a[0].x, mat[0].y - a[0].y, mat[1].x - a[1].x, mat[1].y - a[1].y ); } NO_INLINE noMat2 &noMat2::operator*=( const float a ) { mat[0].x *= a; mat[0].y *= a; mat[1].x *= a; mat[1].y *= a; return *this; } NO_INLINE noMat2 &noMat2::operator*=( const noMat2 &a ) { float x, y; x = mat[0].x; y = mat[0].y; mat[0].x = x * a[0].x + y * a[1].x; mat[0].y = x * a[0].y + y * a[1].y; x = mat[1].x; y = mat[1].y; mat[1].x = x * a[0].x + y * a[1].x; mat[1].y = x * a[0].y + y * a[1].y; return *this; } NO_INLINE noMat2 &noMat2::operator+=( const noMat2 &a ) { mat[0].x += a[0].x; mat[0].y += a[0].y; mat[1].x += a[1].x; mat[1].y += a[1].y; return *this; } NO_INLINE noMat2 &noMat2::operator-=( const noMat2 &a ) { mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[1].x -= a[1].x; mat[1].y -= a[1].y; return *this; } NO_INLINE noVec2 operator*( const noVec2 &vec, const noMat2 &mat ) { return mat * vec; } NO_INLINE noMat2 operator*( const float a, noMat2 const &mat ) { return mat * a; } NO_INLINE noVec2 &operator*=( noVec2 &vec, const noMat2 &mat ) { vec = mat * vec; return vec; } NO_INLINE bool noMat2::Compare( const noMat2 &a ) const { if ( mat[0].Compare( a[0] ) && mat[1].Compare( a[1] ) ) { return true; } return false; } NO_INLINE bool noMat2::Compare( const noMat2 &a, const float epsilon ) const { if ( mat[0].Compare( a[0], epsilon ) && mat[1].Compare( a[1], epsilon ) ) { return true; } return false; } NO_INLINE bool noMat2::operator==( const noMat2 &a ) const { return Compare( a ); } NO_INLINE bool noMat2::operator!=( const noMat2 &a ) const { return !Compare( a ); } NO_INLINE void noMat2::Zero( void ) { mat[0].Zero(); mat[1].Zero(); } NO_INLINE void noMat2::Identity( void ) { *this = mat2_identity; } NO_INLINE bool noMat2::IsIdentity( const float epsilon ) const { return Compare( mat2_identity, epsilon ); } NO_INLINE bool noMat2::IsSymmetric( const float epsilon ) const { return ( noMath::Fabs( mat[0][1] - mat[1][0] ) < epsilon ); } NO_INLINE bool noMat2::IsDiagonal( const float epsilon ) const { if ( noMath::Fabs( mat[0][1] ) > epsilon || noMath::Fabs( mat[1][0] ) > epsilon ) { return false; } return true; } NO_INLINE float noMat2::Trace( void ) const { return ( mat[0][0] + mat[1][1] ); } NO_INLINE float noMat2::Determinant( void ) const { return mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]; } NO_INLINE noMat2 noMat2::Transpose( void ) const { return noMat2( mat[0][0], mat[1][0], mat[0][1], mat[1][1] ); } NO_INLINE noMat2 &noMat2::TransposeSelf( void ) { float tmp; tmp = mat[0][1]; mat[0][1] = mat[1][0]; mat[1][0] = tmp; return *this; } NO_INLINE noMat2 noMat2::Inverse( void ) const { noMat2 invMat; invMat = *this; int r = invMat.InverseSelf(); assert( r ); return invMat; } NO_INLINE noMat2 noMat2::InverseFast( void ) const { noMat2 invMat; invMat = *this; int r = invMat.InverseFastSelf(); assert( r ); return invMat; } NO_INLINE int noMat2::GetDimension( void ) const { return 4; } NO_INLINE const float *noMat2::ToFloatPtr( void ) const { return mat[0].ToFloatPtr(); } NO_INLINE float *noMat2::ToFloatPtr( void ) { return mat[0].ToFloatPtr(); } //=============================================================== // // noMat3 - 3x3 matrix // // NOTE: matrix is column-major // //=============================================================== class noMat3 { public: noMat3( void ); explicit noMat3( const noVec3 &x, const noVec3 &y, const noVec3 &z ); explicit noMat3( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ); explicit noMat3( const float src[ 3 ][ 3 ] ); const noVec3 & operator[]( int index ) const; noVec3 & operator[]( int index ); noMat3 operator-() const; noMat3 operator*( const float a ) const; noVec3 operator*( const noVec3 &vec ) const; noMat3 operator*( const noMat3 &a ) const; noMat3 operator+( const noMat3 &a ) const; noMat3 operator-( const noMat3 &a ) const; noMat3 & operator*=( const float a ); noMat3 & operator*=( const noMat3 &a ); noMat3 & operator+=( const noMat3 &a ); noMat3 & operator-=( const noMat3 &a ); friend noMat3 operator*( const float a, const noMat3 &mat ); friend noVec3 operator*( const noVec3 &vec, const noMat3 &mat ); friend noVec3 & operator*=( noVec3 &vec, const noMat3 &mat ); bool Compare( const noMat3 &a ) const; // exact compare, no epsilon bool Compare( const noMat3 &a, const float epsilon ) const; // compare with epsilon bool operator==( const noMat3 &a ) const; // exact compare, no epsilon bool operator!=( const noMat3 &a ) const; // exact compare, no epsilon void Zero( void ); void Identity( void ); bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const; bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const; bool IsRotated( void ) const; void ProjectVector( const noVec3 &src, noVec3 &dst ) const; void UnprojectVector( const noVec3 &src, noVec3 &dst ) const; bool FixDegeneracies( void ); // fix degenerate axial cases bool FixDenormals( void ); // change tiny numbers to zero float Trace( void ) const; float Determinant( void ) const; noMat3 OrthoNormalize( void ) const; noMat3 & OrthoNormalizeSelf( void ); noMat3 Transpose( void ) const; // returns transpose noMat3 & TransposeSelf( void ); noMat3 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseSelf( void ); // returns false if determinant is zero noMat3 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseFastSelf( void ); // returns false if determinant is zero noMat3 TransposeMultiply( const noMat3 &b ) const; noMat3 InertiaTranslate( const float mass, const noVec3 &centerOfMass, const noVec3 &translation ) const; noMat3 & InertiaTranslateSelf( const float mass, const noVec3 &centerOfMass, const noVec3 &translation ); noMat3 InertiaRotate( const noMat3 &rotation ) const; noMat3 & InertiaRotateSelf( const noMat3 &rotation ); int GetDimension( void ) const; noAngles ToAngles( void ) const; noQuat ToQuat( void ) const; idCQuat ToCQuat( void ) const; noRotation ToRotation( void ) const; noMat4 ToMat4( void ) const; noVec3 ToAngularVelocity( void ) const; const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; friend void TransposeMultiply( const noMat3 &inv, const noMat3 &b, noMat3 &dst ); friend noMat3 SkewSymmetric( noVec3 const &src ); noVec3 mat[ 3 ]; private: }; extern noMat3 mat3_zero; extern noMat3 mat3_identity; #define mat3_default mat3_identity __forceinline noMat3::noMat3( void ) { } __forceinline noMat3::noMat3( const noVec3 &x, const noVec3 &y, const noVec3 &z ) { mat[ 0 ].x = x.x; mat[ 0 ].y = x.y; mat[ 0 ].z = x.z; mat[ 1 ].x = y.x; mat[ 1 ].y = y.y; mat[ 1 ].z = y.z; mat[ 2 ].x = z.x; mat[ 2 ].y = z.y; mat[ 2 ].z = z.z; } __forceinline noMat3::noMat3( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ) { mat[ 0 ].x = xx; mat[ 0 ].y = xy; mat[ 0 ].z = xz; mat[ 1 ].x = yx; mat[ 1 ].y = yy; mat[ 1 ].z = yz; mat[ 2 ].x = zx; mat[ 2 ].y = zy; mat[ 2 ].z = zz; } __forceinline noMat3::noMat3( const float src[ 3 ][ 3 ] ) { memcpy( mat, src, 3 * 3 * sizeof( float ) ); } __forceinline const noVec3 &noMat3::operator[]( int index ) const { //assert( ( index >= 0 ) && ( index < 3 ) ); return mat[ index ]; } __forceinline noVec3 &noMat3::operator[]( int index ) { //assert( ( index >= 0 ) && ( index < 3 ) ); return mat[ index ]; } __forceinline noMat3 noMat3::operator-() const { return noMat3( -mat[0][0], -mat[0][1], -mat[0][2], -mat[1][0], -mat[1][1], -mat[1][2], -mat[2][0], -mat[2][1], -mat[2][2] ); } __forceinline noVec3 noMat3::operator*( const noVec3 &vec ) const { return noVec3( mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z, mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z, mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z ); } __forceinline noMat3 noMat3::operator*( const noMat3 &a ) const { int i, j; const float *m1Ptr, *m2Ptr; float *dstPtr; noMat3 dst; m1Ptr = reinterpret_cast<const float *>(this); m2Ptr = reinterpret_cast<const float *>(&a); dstPtr = reinterpret_cast<float *>(&dst); for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 3; j++ ) { *dstPtr = m1Ptr[0] * m2Ptr[ 0 * 3 + j ] + m1Ptr[1] * m2Ptr[ 1 * 3 + j ] + m1Ptr[2] * m2Ptr[ 2 * 3 + j ]; dstPtr++; } m1Ptr += 3; } return dst; } __forceinline noMat3 noMat3::operator*( const float a ) const { return noMat3( mat[0].x * a, mat[0].y * a, mat[0].z * a, mat[1].x * a, mat[1].y * a, mat[1].z * a, mat[2].x * a, mat[2].y * a, mat[2].z * a ); } __forceinline noMat3 noMat3::operator+( const noMat3 &a ) const { return noMat3( mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z, mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z, mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z ); } __forceinline noMat3 noMat3::operator-( const noMat3 &a ) const { return noMat3( mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z, mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z, mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z ); } __forceinline noMat3 &noMat3::operator*=( const float a ) { mat[0].x *= a; mat[0].y *= a; mat[0].z *= a; mat[1].x *= a; mat[1].y *= a; mat[1].z *= a; mat[2].x *= a; mat[2].y *= a; mat[2].z *= a; return *this; } __forceinline noMat3 &noMat3::operator*=( const noMat3 &a ) { int i, j; const float *m2Ptr; float *m1Ptr, dst[3]; m1Ptr = reinterpret_cast<float *>(this); m2Ptr = reinterpret_cast<const float *>(&a); for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 3; j++ ) { dst[j] = m1Ptr[0] * m2Ptr[ 0 * 3 + j ] + m1Ptr[1] * m2Ptr[ 1 * 3 + j ] + m1Ptr[2] * m2Ptr[ 2 * 3 + j ]; } m1Ptr[0] = dst[0]; m1Ptr[1] = dst[1]; m1Ptr[2] = dst[2]; m1Ptr += 3; } return *this; } __forceinline noMat3 &noMat3::operator+=( const noMat3 &a ) { mat[0].x += a[0].x; mat[0].y += a[0].y; mat[0].z += a[0].z; mat[1].x += a[1].x; mat[1].y += a[1].y; mat[1].z += a[1].z; mat[2].x += a[2].x; mat[2].y += a[2].y; mat[2].z += a[2].z; return *this; } __forceinline noMat3 &noMat3::operator-=( const noMat3 &a ) { mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[0].z -= a[0].z; mat[1].x -= a[1].x; mat[1].y -= a[1].y; mat[1].z -= a[1].z; mat[2].x -= a[2].x; mat[2].y -= a[2].y; mat[2].z -= a[2].z; return *this; } __forceinline noVec3 operator*( const noVec3 &vec, const noMat3 &mat ) { return mat * vec; } __forceinline noMat3 operator*( const float a, const noMat3 &mat ) { return mat * a; } __forceinline noVec3 &operator*=( noVec3 &vec, const noMat3 &mat ) { float x = mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z; float y = mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z; vec.z = mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z; vec.x = x; vec.y = y; return vec; } __forceinline bool noMat3::Compare( const noMat3 &a ) const { if ( mat[0].Compare( a[0] ) && mat[1].Compare( a[1] ) && mat[2].Compare( a[2] ) ) { return true; } return false; } __forceinline bool noMat3::Compare( const noMat3 &a, const float epsilon ) const { if ( mat[0].Compare( a[0], epsilon ) && mat[1].Compare( a[1], epsilon ) && mat[2].Compare( a[2], epsilon ) ) { return true; } return false; } __forceinline bool noMat3::operator==( const noMat3 &a ) const { return Compare( a ); } __forceinline bool noMat3::operator!=( const noMat3 &a ) const { return !Compare( a ); } __forceinline void noMat3::Zero( void ) { memset( mat, 0, sizeof( noMat3 ) ); } __forceinline void noMat3::Identity( void ) { *this = mat3_identity; } __forceinline bool noMat3::IsIdentity( const float epsilon ) const { return Compare( mat3_identity, epsilon ); } __forceinline bool noMat3::IsSymmetric( const float epsilon ) const { if ( noMath::Fabs( mat[0][1] - mat[1][0] ) > epsilon ) { return false; } if ( noMath::Fabs( mat[0][2] - mat[2][0] ) > epsilon ) { return false; } if ( noMath::Fabs( mat[1][2] - mat[2][1] ) > epsilon ) { return false; } return true; } __forceinline bool noMat3::IsDiagonal( const float epsilon ) const { if ( noMath::Fabs( mat[0][1] ) > epsilon || noMath::Fabs( mat[0][2] ) > epsilon || noMath::Fabs( mat[1][0] ) > epsilon || noMath::Fabs( mat[1][2] ) > epsilon || noMath::Fabs( mat[2][0] ) > epsilon || noMath::Fabs( mat[2][1] ) > epsilon ) { return false; } return true; } __forceinline bool noMat3::IsRotated( void ) const { return !Compare( mat3_identity ); } __forceinline void noMat3::ProjectVector( const noVec3 &src, noVec3 &dst ) const { dst.x = src * mat[ 0 ]; dst.y = src * mat[ 1 ]; dst.z = src * mat[ 2 ]; } __forceinline void noMat3::UnprojectVector( const noVec3 &src, noVec3 &dst ) const { dst = mat[ 0 ] * src.x + mat[ 1 ] * src.y + mat[ 2 ] * src.z; } __forceinline bool noMat3::FixDegeneracies( void ) { bool r = mat[0].FixDegenerateNormal(); r |= mat[1].FixDegenerateNormal(); r |= mat[2].FixDegenerateNormal(); return r; } __forceinline bool noMat3::FixDenormals( void ) { bool r = mat[0].FixDenormals(); r |= mat[1].FixDenormals(); r |= mat[2].FixDenormals(); return r; } __forceinline float noMat3::Trace( void ) const { return ( mat[0][0] + mat[1][1] + mat[2][2] ); } __forceinline noMat3 noMat3::OrthoNormalize( void ) const { noMat3 ortho; ortho = *this; ortho[ 0 ].Normalize(); ortho[ 2 ].Cross( mat[ 0 ], mat[ 1 ] ); ortho[ 2 ].Normalize(); ortho[ 1 ].Cross( mat[ 2 ], mat[ 0 ] ); ortho[ 1 ].Normalize(); return ortho; } __forceinline noMat3 &noMat3::OrthoNormalizeSelf( void ) { mat[ 0 ].Normalize(); mat[ 2 ].Cross( mat[ 0 ], mat[ 1 ] ); mat[ 2 ].Normalize(); mat[ 1 ].Cross( mat[ 2 ], mat[ 0 ] ); mat[ 1 ].Normalize(); return *this; } __forceinline noMat3 noMat3::Transpose( void ) const { return noMat3( mat[0][0], mat[1][0], mat[2][0], mat[0][1], mat[1][1], mat[2][1], mat[0][2], mat[1][2], mat[2][2] ); } __forceinline noMat3 &noMat3::TransposeSelf( void ) { float tmp0, tmp1, tmp2; tmp0 = mat[0][1]; mat[0][1] = mat[1][0]; mat[1][0] = tmp0; tmp1 = mat[0][2]; mat[0][2] = mat[2][0]; mat[2][0] = tmp1; tmp2 = mat[1][2]; mat[1][2] = mat[2][1]; mat[2][1] = tmp2; return *this; } __forceinline noMat3 noMat3::Inverse( void ) const { noMat3 invMat; invMat = *this; int r = invMat.InverseSelf(); assert( r ); return invMat; } __forceinline noMat3 noMat3::InverseFast( void ) const { noMat3 invMat; invMat = *this; int r = invMat.InverseFastSelf(); assert( r ); return invMat; } __forceinline noMat3 noMat3::TransposeMultiply( const noMat3 &b ) const { return noMat3( mat[0].x * b[0].x + mat[1].x * b[1].x + mat[2].x * b[2].x, mat[0].x * b[0].y + mat[1].x * b[1].y + mat[2].x * b[2].y, mat[0].x * b[0].z + mat[1].x * b[1].z + mat[2].x * b[2].z, mat[0].y * b[0].x + mat[1].y * b[1].x + mat[2].y * b[2].x, mat[0].y * b[0].y + mat[1].y * b[1].y + mat[2].y * b[2].y, mat[0].y * b[0].z + mat[1].y * b[1].z + mat[2].y * b[2].z, mat[0].z * b[0].x + mat[1].z * b[1].x + mat[2].z * b[2].x, mat[0].z * b[0].y + mat[1].z * b[1].y + mat[2].z * b[2].y, mat[0].z * b[0].z + mat[1].z * b[1].z + mat[2].z * b[2].z ); } __forceinline void TransposeMultiply( const noMat3 &transpose, const noMat3 &b, noMat3 &dst ) { dst[0].x = transpose[0].x * b[0].x + transpose[1].x * b[1].x + transpose[2].x * b[2].x; dst[0].y = transpose[0].x * b[0].y + transpose[1].x * b[1].y + transpose[2].x * b[2].y; dst[0].z = transpose[0].x * b[0].z + transpose[1].x * b[1].z + transpose[2].x * b[2].z; dst[1].x = transpose[0].y * b[0].x + transpose[1].y * b[1].x + transpose[2].y * b[2].x; dst[1].y = transpose[0].y * b[0].y + transpose[1].y * b[1].y + transpose[2].y * b[2].y; dst[1].z = transpose[0].y * b[0].z + transpose[1].y * b[1].z + transpose[2].y * b[2].z; dst[2].x = transpose[0].z * b[0].x + transpose[1].z * b[1].x + transpose[2].z * b[2].x; dst[2].y = transpose[0].z * b[0].y + transpose[1].z * b[1].y + transpose[2].z * b[2].y; dst[2].z = transpose[0].z * b[0].z + transpose[1].z * b[1].z + transpose[2].z * b[2].z; } __forceinline noMat3 SkewSymmetric( noVec3 const &src ) { return noMat3( 0.0f, -src.z, src.y, src.z, 0.0f, -src.x, -src.y, src.x, 0.0f ); } __forceinline int noMat3::GetDimension( void ) const { return 9; } __forceinline const float *noMat3::ToFloatPtr( void ) const { return mat[0].ToFloatPtr(); } __forceinline float *noMat3::ToFloatPtr( void ) { return mat[0].ToFloatPtr(); } //=============================================================== // // noMat4 - 4x4 matrix // //=============================================================== class noMat4 { public: noMat4( void ); explicit noMat4( const noVec4 &x, const noVec4 &y, const noVec4 &z, const noVec4 &w ); explicit noMat4(const float xx, const float xy, const float xz, const float xw, const float yx, const float yy, const float yz, const float yw, const float zx, const float zy, const float zz, const float zw, const float wx, const float wy, const float wz, const float ww ); explicit noMat4( const noMat3 &rotation, const noVec3 &translation ); explicit noMat4( const float src[ 4 ][ 4 ] ); explicit noMat4( const float src[ 16 ] ); const noVec4 & operator[]( int index ) const; noVec4 & operator[]( int index ); noMat4 operator*( const float a ) const; noVec4 operator*( const noVec4 &vec ) const; noVec3 operator*( const noVec3 &vec ) const; noMat4 operator*( const noMat4 &a ) const; noMat4 operator+( const noMat4 &a ) const; noMat4 operator-( const noMat4 &a ) const; noMat4 & operator*=( const float a ); noMat4 & operator*=( const noMat4 &a ); noMat4 & operator+=( const noMat4 &a ); noMat4 & operator-=( const noMat4 &a ); void Translation(const noVec3& t); friend noMat4 operator*( const float a, const noMat4 &mat ); friend noVec4 operator*( const noVec4 &vec, const noMat4 &mat ); friend noVec3 operator*( const noVec3 &vec, const noMat4 &mat ); friend noVec4 & operator*=( noVec4 &vec, const noMat4 &mat ); friend noVec3 & operator*=( noVec3 &vec, const noMat4 &mat ); bool Compare( const noMat4 &a ) const; // exact compare, no epsilon bool Compare( const noMat4 &a, const float epsilon ) const; // compare with epsilon bool operator==( const noMat4 &a ) const; // exact compare, no epsilon bool operator!=( const noMat4 &a ) const; // exact compare, no epsilon void Zero( void ); void Identity( void ); bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const; bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const; bool IsRotated( void ) const; void ProjectVector( const noVec4 &src, noVec4 &dst ) const; void UnprojectVector( const noVec4 &src, noVec4 &dst ) const; float Trace( void ) const; float Determinant( void ) const; noMat4 Transpose( void ) const; // returns transpose noMat4 & TransposeSelf( void ); noMat4 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseSelf( void ); // returns false if determinant is zero noMat4 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseFastSelf( void ); // returns false if determinant is zero noMat4 TransposeMultiply( const noMat4 &b ) const; int GetDimension( void ) const; const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; void Scale( const noVec3& t ); void SetOrigin(const noVec3& v); noVec3 GetOrigin() const; void RemoveScaling(FLOAT Tolerance =SMALL_NUMBER); noVec4 mat[ 4 ]; private: }; extern noMat4 mat4_zero; extern noMat4 mat4_identity; #define mat4_default mat4_identity __forceinline noMat4::noMat4( void ) { } __forceinline noMat4::noMat4( const noVec4 &x, const noVec4 &y, const noVec4 &z, const noVec4 &w ) { mat[ 0 ] = x; mat[ 1 ] = y; mat[ 2 ] = z; mat[ 3 ] = w; } __forceinline noMat4::noMat4( const float xx, const float xy, const float xz, const float xw, const float yx, const float yy, const float yz, const float yw, const float zx, const float zy, const float zz, const float zw, const float wx, const float wy, const float wz, const float ww ) { mat[0][0] = xx; mat[0][1] = xy; mat[0][2] = xz; mat[0][3] = xw; mat[1][0] = yx; mat[1][1] = yy; mat[1][2] = yz; mat[1][3] = yw; mat[2][0] = zx; mat[2][1] = zy; mat[2][2] = zz; mat[2][3] = zw; mat[3][0] = wx; mat[3][1] = wy; mat[3][2] = wz; mat[3][3] = ww; } __forceinline noMat4::noMat4( const noMat3 &rotation, const noVec3 &translation ) { // NOTE: noMat3 is transposed because it is column-major mat[ 0 ][ 0 ] = rotation[0][0]; mat[ 0 ][ 1 ] = rotation[1][0]; mat[ 0 ][ 2 ] = rotation[2][0]; mat[ 0 ][ 3 ] = translation[0]; mat[ 1 ][ 0 ] = rotation[0][1]; mat[ 1 ][ 1 ] = rotation[1][1]; mat[ 1 ][ 2 ] = rotation[2][1]; mat[ 1 ][ 3 ] = translation[1]; mat[ 2 ][ 0 ] = rotation[0][2]; mat[ 2 ][ 1 ] = rotation[1][2]; mat[ 2 ][ 2 ] = rotation[2][2]; mat[ 2 ][ 3 ] = translation[2]; mat[ 3 ][ 0 ] = 0.0f; mat[ 3 ][ 1 ] = 0.0f; mat[ 3 ][ 2 ] = 0.0f; mat[ 3 ][ 3 ] = 1.0f; } __forceinline noMat4::noMat4( const float src[ 4 ][ 4 ] ) { memcpy( mat, src, 4 * 4 * sizeof( float ) ); } __forceinline noMat4::noMat4( const float src[ 16 ] ) { memcpy( mat, src, 4 * 4 * sizeof( float ) ); } __forceinline const noVec4 &noMat4::operator[]( int index ) const { //assert( ( index >= 0 ) && ( index < 4 ) ); return mat[ index ]; } __forceinline noVec4 &noMat4::operator[]( int index ) { //assert( ( index >= 0 ) && ( index < 4 ) ); return mat[ index ]; } __forceinline noMat4 noMat4::operator*( const float a ) const { return noMat4( mat[0].x * a, mat[0].y * a, mat[0].z * a, mat[0].w * a, mat[1].x * a, mat[1].y * a, mat[1].z * a, mat[1].w * a, mat[2].x * a, mat[2].y * a, mat[2].z * a, mat[2].w * a, mat[3].x * a, mat[3].y * a, mat[3].z * a, mat[3].w * a ); } __forceinline noVec4 noMat4::operator*( const noVec4 &vec ) const { return noVec4( mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y + mat[ 0 ].z * vec.z + mat[ 0 ].w * vec.w, mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y + mat[ 1 ].z * vec.z + mat[ 1 ].w * vec.w, mat[ 2 ].x * vec.x + mat[ 2 ].y * vec.y + mat[ 2 ].z * vec.z + mat[ 2 ].w * vec.w, mat[ 3 ].x * vec.x + mat[ 3 ].y * vec.y + mat[ 3 ].z * vec.z + mat[ 3 ].w * vec.w ); } __forceinline noVec3 noMat4::operator*( const noVec3 &vec ) const { float s = mat[ 3 ].x * vec.x + mat[ 3 ].y * vec.y + mat[ 3 ].z * vec.z + mat[ 3 ].w; if ( s == 0.0f ) { return noVec3( 0.0f, 0.0f, 0.0f ); } if ( s == 1.0f ) { return noVec3( mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y + mat[ 0 ].z * vec.z + mat[ 0 ].w, mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y + mat[ 1 ].z * vec.z + mat[ 1 ].w, mat[ 2 ].x * vec.x + mat[ 2 ].y * vec.y + mat[ 2 ].z * vec.z + mat[ 2 ].w ); } else { float invS = 1.0f / s; return noVec3( (mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y + mat[ 0 ].z * vec.z + mat[ 0 ].w) * invS, (mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y + mat[ 1 ].z * vec.z + mat[ 1 ].w) * invS, (mat[ 2 ].x * vec.x + mat[ 2 ].y * vec.y + mat[ 2 ].z * vec.z + mat[ 2 ].w) * invS ); } } __forceinline noMat4 noMat4::operator*( const noMat4 &a ) const { int i, j; const float *m1Ptr, *m2Ptr; float *dstPtr; noMat4 dst; m1Ptr = reinterpret_cast<const float *>(this); m2Ptr = reinterpret_cast<const float *>(&a); dstPtr = reinterpret_cast<float *>(&dst); for ( i = 0; i < 4; i++ ) { for ( j = 0; j < 4; j++ ) { *dstPtr = m1Ptr[0] * m2Ptr[ 0 * 4 + j ] + m1Ptr[1] * m2Ptr[ 1 * 4 + j ] + m1Ptr[2] * m2Ptr[ 2 * 4 + j ] + m1Ptr[3] * m2Ptr[ 3 * 4 + j ]; dstPtr++; } m1Ptr += 4; } return dst; } __forceinline noMat4 noMat4::operator+( const noMat4 &a ) const { return noMat4( mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z, mat[0].w + a[0].w, mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z, mat[1].w + a[1].w, mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z, mat[2].w + a[2].w, mat[3].x + a[3].x, mat[3].y + a[3].y, mat[3].z + a[3].z, mat[3].w + a[3].w ); } __forceinline noMat4 noMat4::operator-( const noMat4 &a ) const { return noMat4( mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z, mat[0].w - a[0].w, mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z, mat[1].w - a[1].w, mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z, mat[2].w - a[2].w, mat[3].x - a[3].x, mat[3].y - a[3].y, mat[3].z - a[3].z, mat[3].w - a[3].w ); } __forceinline noMat4 &noMat4::operator*=( const float a ) { mat[0].x *= a; mat[0].y *= a; mat[0].z *= a; mat[0].w *= a; mat[1].x *= a; mat[1].y *= a; mat[1].z *= a; mat[1].w *= a; mat[2].x *= a; mat[2].y *= a; mat[2].z *= a; mat[2].w *= a; mat[3].x *= a; mat[3].y *= a; mat[3].z *= a; mat[3].w *= a; return *this; } __forceinline noMat4 &noMat4::operator*=( const noMat4 &a ) { *this = (*this) * a; return *this; } __forceinline noMat4 &noMat4::operator+=( const noMat4 &a ) { mat[0].x += a[0].x; mat[0].y += a[0].y; mat[0].z += a[0].z; mat[0].w += a[0].w; mat[1].x += a[1].x; mat[1].y += a[1].y; mat[1].z += a[1].z; mat[1].w += a[1].w; mat[2].x += a[2].x; mat[2].y += a[2].y; mat[2].z += a[2].z; mat[2].w += a[2].w; mat[3].x += a[3].x; mat[3].y += a[3].y; mat[3].z += a[3].z; mat[3].w += a[3].w; return *this; } __forceinline noMat4 &noMat4::operator-=( const noMat4 &a ) { mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[0].z -= a[0].z; mat[0].w -= a[0].w; mat[1].x -= a[1].x; mat[1].y -= a[1].y; mat[1].z -= a[1].z; mat[1].w -= a[1].w; mat[2].x -= a[2].x; mat[2].y -= a[2].y; mat[2].z -= a[2].z; mat[2].w -= a[2].w; mat[3].x -= a[3].x; mat[3].y -= a[3].y; mat[3].z -= a[3].z; mat[3].w -= a[3].w; return *this; } __forceinline noMat4 operator*( const float a, const noMat4 &mat ) { return mat * a; } __forceinline noVec4 operator*( const noVec4 &vec, const noMat4 &mat ) { return mat * vec; } __forceinline noVec3 operator*( const noVec3 &vec, const noMat4 &mat ) { return mat * vec; } __forceinline noVec4 &operator*=( noVec4 &vec, const noMat4 &mat ) { vec = mat * vec; return vec; } __forceinline noVec3 &operator*=( noVec3 &vec, const noMat4 &mat ) { vec = mat * vec; return vec; } __forceinline bool noMat4::Compare( const noMat4 &a ) const { dword i; const float *ptr1, *ptr2; ptr1 = reinterpret_cast<const float *>(mat); ptr2 = reinterpret_cast<const float *>(a.mat); for ( i = 0; i < 4*4; i++ ) { if ( ptr1[i] != ptr2[i] ) { return false; } } return true; } __forceinline bool noMat4::Compare( const noMat4 &a, const float epsilon ) const { dword i; const float *ptr1, *ptr2; ptr1 = reinterpret_cast<const float *>(mat); ptr2 = reinterpret_cast<const float *>(a.mat); for ( i = 0; i < 4*4; i++ ) { if ( noMath::Fabs( ptr1[i] - ptr2[i] ) > epsilon ) { return false; } } return true; } __forceinline bool noMat4::operator==( const noMat4 &a ) const { return Compare( a ); } __forceinline bool noMat4::operator!=( const noMat4 &a ) const { return !Compare( a ); } __forceinline void noMat4::Zero( void ) { memset( mat, 0, sizeof( noMat4 ) ); } __forceinline void noMat4::Identity( void ) { *this = mat4_identity; } __forceinline bool noMat4::IsIdentity( const float epsilon ) const { return Compare( mat4_identity, epsilon ); } __forceinline bool noMat4::IsSymmetric( const float epsilon ) const { for ( int i = 1; i < 4; i++ ) { for ( int j = 0; j < i; j++ ) { if ( noMath::Fabs( mat[i][j] - mat[j][i] ) > epsilon ) { return false; } } } return true; } __forceinline bool noMat4::IsDiagonal( const float epsilon ) const { for ( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 4; j++ ) { if ( i != j && noMath::Fabs( mat[i][j] ) > epsilon ) { return false; } } } return true; } __forceinline bool noMat4::IsRotated( void ) const { if ( !mat[ 0 ][ 1 ] && !mat[ 0 ][ 2 ] && !mat[ 1 ][ 0 ] && !mat[ 1 ][ 2 ] && !mat[ 2 ][ 0 ] && !mat[ 2 ][ 1 ] ) { return false; } return true; } __forceinline void noMat4::ProjectVector( const noVec4 &src, noVec4 &dst ) const { dst.x = src * mat[ 0 ]; dst.y = src * mat[ 1 ]; dst.z = src * mat[ 2 ]; dst.w = src * mat[ 3 ]; } __forceinline void noMat4::UnprojectVector( const noVec4 &src, noVec4 &dst ) const { dst = mat[ 0 ] * src.x + mat[ 1 ] * src.y + mat[ 2 ] * src.z + mat[ 3 ] * src.w; } __forceinline float noMat4::Trace( void ) const { return ( mat[0][0] + mat[1][1] + mat[2][2] + mat[3][3] ); } __forceinline noMat4 noMat4::Inverse( void ) const { noMat4 invMat; invMat = *this; int r = invMat.InverseSelf(); assert( r ); return invMat; } __forceinline noMat4 noMat4::InverseFast( void ) const { noMat4 invMat; invMat = *this; int r = invMat.InverseFastSelf(); assert( r ); return invMat; } __forceinline noMat4 noMat3::ToMat4( void ) const { // NOTE: noMat3 is transposed because it is column-major return noMat4( mat[0][0], mat[1][0], mat[2][0], 0.0f, mat[0][1], mat[1][1], mat[2][1], 0.0f, mat[0][2], mat[1][2], mat[2][2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); } __forceinline int noMat4::GetDimension( void ) const { return 16; } __forceinline const float *noMat4::ToFloatPtr( void ) const { return mat[0].ToFloatPtr(); } __forceinline void noMat4::Translation( const noVec3& t ) { Identity(); mat[0][3] = t.x; mat[1][3] = t.y; mat[2][3] = t.z; } __forceinline void noMat4::Scale( const noVec3& t ) { Zero(); mat[0][0] = t.x; mat[1][1] = t.y; mat[2][2] = t.z; mat[3][3] = 1.0f; } __forceinline float *noMat4::ToFloatPtr( void ) { return mat[0].ToFloatPtr(); } NO_INLINE void noMat4::SetOrigin(const noVec3& v) { mat[0][3] = v.x; mat[1][3] = v.y; mat[2][3] = v.z; } __forceinline noVec3 noMat4::GetOrigin() const { return noVec3(mat[0][3], mat[1][3], mat[2][3]); } // Remove any scaling from this matrix (ie magnitude of each row is 1) __forceinline void noMat4::RemoveScaling(FLOAT Tolerance/*=SMALL_NUMBER*/) { // For each row, find magnitude, and if its non-zero re-scale so its unit length. for(INT i=0; i<3; i++) { const FLOAT SquareSum = (mat[i][0] * mat[i][0]) + (mat[i][1] * mat[i][1]) + (mat[i][2] * mat[i][2]); if(SquareSum > Tolerance) { const FLOAT Scale = noMath::InvSqrt(SquareSum); mat[i][0] *= Scale; mat[i][1] *= Scale; mat[i][2] *= Scale; } } } // Symmetric matrices can be optimized template< class SCALAR, class V3, class T_MATRIX3 > class T_SYMMETRIC_MATRIX3 { public: SCALAR xx, yy, zz; //diagonal elements SCALAR xy, xz, yz; //off-diagonal elements public: T_SYMMETRIC_MATRIX3() { //identity xx = yy = zz = 1; xy = xz = yz = 0; } T_SYMMETRIC_MATRIX3( const SCALAR xx, const SCALAR yy, const SCALAR zz, const SCALAR xy, const SCALAR xz, const SCALAR yz ) { this->xx = xx; this->yy = yy; this->zz = zz; this->xy = xy; this->xz = xz; this->yz = yz; } //set equal to another matrix const T_SYMMETRIC_MATRIX3& operator = ( const T_SYMMETRIC_MATRIX3& m ) { this->xx = m.xx; this->yy = m.yy; this->zz = m.zz; this->xy = m.xy; this->xz = m.xz; this->yz = m.yz; return *this; } //increment by another matrix const T_SYMMETRIC_MATRIX3& operator += ( const T_SYMMETRIC_MATRIX3& m ) { this->xx += m.xx; this->yy += m.yy; this->zz += m.zz; this->xy += m.xy; this->xz += m.xz; this->yz += m.yz; return *this; } //decrement by another matrix const T_SYMMETRIC_MATRIX3& operator -=( const T_SYMMETRIC_MATRIX3& m ) { this->xx -= m.xx; this->yy -= m.yy; this->zz -= m.zz; this->xy -= m.xy; this->xz -= m.xz; this->yz -= m.yz; return *this; } //add two matrices T_SYMMETRIC_MATRIX3 operator + ( const T_SYMMETRIC_MATRIX3& m ) const { return T_SYMMETRIC_MATRIX3( xx + m.xx, yy + m.yy, zz + m.zz, xy + m.xy, xz + m.xz, yz + m.yz ); } //subtract two matrices T_SYMMETRIC_MATRIX3 operator - ( const T_SYMMETRIC_MATRIX3& m ) const { return T_SYMMETRIC_MATRIX3( xx - m.xx, yy - m.yy, zz - m.zz, xy - m.xy, xz - m.xz, yz - m.yz ); } //post-multiply by a vector V3 operator * ( const V3& v ) const { return V3( v.x*xx + v.y*xy + v.z*xz, v.x*xy + v.y*yy + v.z*yz, v.z*xz + v.y*yz + v.z*zz ); } //pre-multiply by a vector friend inline V3 operator * ( const V3& v, const T_SYMMETRIC_MATRIX3& m ) { return m * v; } //NOTE: Can't do a self-multiply because the product of two symmetric matrices //is not necessarily a symmetric matrix //multiply two symmetric matrices // T_SYMMETRIC_MATRIX3 operator * ( const T_SYMMETRIC_MATRIX3& m ) const // { // return T_MATRIX3(); // } // - matrix specific - // //a symmetric matrix is equal to its transpose //Is there a simplified formula for the inverse of a symmetric matrix? }; typedef T_SYMMETRIC_MATRIX3< float, noVec3, noMat3 > noSymmetricMat3; //=============================================================== // // idMat5 - 5x5 matrix // //=============================================================== class idMat5 { public: idMat5( void ); explicit idMat5( const idVec5 &v0, const idVec5 &v1, const idVec5 &v2, const idVec5 &v3, const idVec5 &v4 ); explicit idMat5( const float src[ 5 ][ 5 ] ); const idVec5 & operator[]( int index ) const; idVec5 & operator[]( int index ); idMat5 operator*( const float a ) const; idVec5 operator*( const idVec5 &vec ) const; idMat5 operator*( const idMat5 &a ) const; idMat5 operator+( const idMat5 &a ) const; idMat5 operator-( const idMat5 &a ) const; idMat5 & operator*=( const float a ); idMat5 & operator*=( const idMat5 &a ); idMat5 & operator+=( const idMat5 &a ); idMat5 & operator-=( const idMat5 &a ); friend idMat5 operator*( const float a, const idMat5 &mat ); friend idVec5 operator*( const idVec5 &vec, const idMat5 &mat ); friend idVec5 & operator*=( idVec5 &vec, const idMat5 &mat ); bool Compare( const idMat5 &a ) const; // exact compare, no epsilon bool Compare( const idMat5 &a, const float epsilon ) const; // compare with epsilon bool operator==( const idMat5 &a ) const; // exact compare, no epsilon bool operator!=( const idMat5 &a ) const; // exact compare, no epsilon void Zero( void ); void Identity( void ); bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const; bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const; float Trace( void ) const; float Determinant( void ) const; idMat5 Transpose( void ) const; // returns transpose idMat5 & TransposeSelf( void ); idMat5 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseSelf( void ); // returns false if determinant is zero idMat5 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseFastSelf( void ); // returns false if determinant is zero int GetDimension( void ) const; const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; private: idVec5 mat[ 5 ]; }; extern idMat5 mat5_zero; extern idMat5 mat5_identity; #define mat5_default mat5_identity ID_INLINE idMat5::idMat5( void ) { } ID_INLINE idMat5::idMat5( const float src[ 5 ][ 5 ] ) { memcpy( mat, src, 5 * 5 * sizeof( float ) ); } ID_INLINE idMat5::idMat5( const idVec5 &v0, const idVec5 &v1, const idVec5 &v2, const idVec5 &v3, const idVec5 &v4 ) { mat[0] = v0; mat[1] = v1; mat[2] = v2; mat[3] = v3; mat[4] = v4; } ID_INLINE const idVec5 &idMat5::operator[]( int index ) const { //assert( ( index >= 0 ) && ( index < 5 ) ); return mat[ index ]; } ID_INLINE idVec5 &idMat5::operator[]( int index ) { //assert( ( index >= 0 ) && ( index < 5 ) ); return mat[ index ]; } ID_INLINE idMat5 idMat5::operator*( const idMat5 &a ) const { int i, j; const float *m1Ptr, *m2Ptr; float *dstPtr; idMat5 dst; m1Ptr = reinterpret_cast<const float *>(this); m2Ptr = reinterpret_cast<const float *>(&a); dstPtr = reinterpret_cast<float *>(&dst); for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 5; j++ ) { *dstPtr = m1Ptr[0] * m2Ptr[ 0 * 5 + j ] + m1Ptr[1] * m2Ptr[ 1 * 5 + j ] + m1Ptr[2] * m2Ptr[ 2 * 5 + j ] + m1Ptr[3] * m2Ptr[ 3 * 5 + j ] + m1Ptr[4] * m2Ptr[ 4 * 5 + j ]; dstPtr++; } m1Ptr += 5; } return dst; } ID_INLINE idMat5 idMat5::operator*( const float a ) const { return idMat5( idVec5( mat[0][0] * a, mat[0][1] * a, mat[0][2] * a, mat[0][3] * a, mat[0][4] * a ), idVec5( mat[1][0] * a, mat[1][1] * a, mat[1][2] * a, mat[1][3] * a, mat[1][4] * a ), idVec5( mat[2][0] * a, mat[2][1] * a, mat[2][2] * a, mat[2][3] * a, mat[2][4] * a ), idVec5( mat[3][0] * a, mat[3][1] * a, mat[3][2] * a, mat[3][3] * a, mat[3][4] * a ), idVec5( mat[4][0] * a, mat[4][1] * a, mat[4][2] * a, mat[4][3] * a, mat[4][4] * a ) ); } ID_INLINE idVec5 idMat5::operator*( const idVec5 &vec ) const { return idVec5( mat[0][0] * vec[0] + mat[0][1] * vec[1] + mat[0][2] * vec[2] + mat[0][3] * vec[3] + mat[0][4] * vec[4], mat[1][0] * vec[0] + mat[1][1] * vec[1] + mat[1][2] * vec[2] + mat[1][3] * vec[3] + mat[1][4] * vec[4], mat[2][0] * vec[0] + mat[2][1] * vec[1] + mat[2][2] * vec[2] + mat[2][3] * vec[3] + mat[2][4] * vec[4], mat[3][0] * vec[0] + mat[3][1] * vec[1] + mat[3][2] * vec[2] + mat[3][3] * vec[3] + mat[3][4] * vec[4], mat[4][0] * vec[0] + mat[4][1] * vec[1] + mat[4][2] * vec[2] + mat[4][3] * vec[3] + mat[4][4] * vec[4] ); } ID_INLINE idMat5 idMat5::operator+( const idMat5 &a ) const { return idMat5( idVec5( mat[0][0] + a[0][0], mat[0][1] + a[0][1], mat[0][2] + a[0][2], mat[0][3] + a[0][3], mat[0][4] + a[0][4] ), idVec5( mat[1][0] + a[1][0], mat[1][1] + a[1][1], mat[1][2] + a[1][2], mat[1][3] + a[1][3], mat[1][4] + a[1][4] ), idVec5( mat[2][0] + a[2][0], mat[2][1] + a[2][1], mat[2][2] + a[2][2], mat[2][3] + a[2][3], mat[2][4] + a[2][4] ), idVec5( mat[3][0] + a[3][0], mat[3][1] + a[3][1], mat[3][2] + a[3][2], mat[3][3] + a[3][3], mat[3][4] + a[3][4] ), idVec5( mat[4][0] + a[4][0], mat[4][1] + a[4][1], mat[4][2] + a[4][2], mat[4][3] + a[4][3], mat[4][4] + a[4][4] ) ); } ID_INLINE idMat5 idMat5::operator-( const idMat5 &a ) const { return idMat5( idVec5( mat[0][0] - a[0][0], mat[0][1] - a[0][1], mat[0][2] - a[0][2], mat[0][3] - a[0][3], mat[0][4] - a[0][4] ), idVec5( mat[1][0] - a[1][0], mat[1][1] - a[1][1], mat[1][2] - a[1][2], mat[1][3] - a[1][3], mat[1][4] - a[1][4] ), idVec5( mat[2][0] - a[2][0], mat[2][1] - a[2][1], mat[2][2] - a[2][2], mat[2][3] - a[2][3], mat[2][4] - a[2][4] ), idVec5( mat[3][0] - a[3][0], mat[3][1] - a[3][1], mat[3][2] - a[3][2], mat[3][3] - a[3][3], mat[3][4] - a[3][4] ), idVec5( mat[4][0] - a[4][0], mat[4][1] - a[4][1], mat[4][2] - a[4][2], mat[4][3] - a[4][3], mat[4][4] - a[4][4] ) ); } ID_INLINE idMat5 &idMat5::operator*=( const float a ) { mat[0][0] *= a; mat[0][1] *= a; mat[0][2] *= a; mat[0][3] *= a; mat[0][4] *= a; mat[1][0] *= a; mat[1][1] *= a; mat[1][2] *= a; mat[1][3] *= a; mat[1][4] *= a; mat[2][0] *= a; mat[2][1] *= a; mat[2][2] *= a; mat[2][3] *= a; mat[2][4] *= a; mat[3][0] *= a; mat[3][1] *= a; mat[3][2] *= a; mat[3][3] *= a; mat[3][4] *= a; mat[4][0] *= a; mat[4][1] *= a; mat[4][2] *= a; mat[4][3] *= a; mat[4][4] *= a; return *this; } ID_INLINE idMat5 &idMat5::operator*=( const idMat5 &a ) { *this = *this * a; return *this; } ID_INLINE idMat5 &idMat5::operator+=( const idMat5 &a ) { mat[0][0] += a[0][0]; mat[0][1] += a[0][1]; mat[0][2] += a[0][2]; mat[0][3] += a[0][3]; mat[0][4] += a[0][4]; mat[1][0] += a[1][0]; mat[1][1] += a[1][1]; mat[1][2] += a[1][2]; mat[1][3] += a[1][3]; mat[1][4] += a[1][4]; mat[2][0] += a[2][0]; mat[2][1] += a[2][1]; mat[2][2] += a[2][2]; mat[2][3] += a[2][3]; mat[2][4] += a[2][4]; mat[3][0] += a[3][0]; mat[3][1] += a[3][1]; mat[3][2] += a[3][2]; mat[3][3] += a[3][3]; mat[3][4] += a[3][4]; mat[4][0] += a[4][0]; mat[4][1] += a[4][1]; mat[4][2] += a[4][2]; mat[4][3] += a[4][3]; mat[4][4] += a[4][4]; return *this; } ID_INLINE idMat5 &idMat5::operator-=( const idMat5 &a ) { mat[0][0] -= a[0][0]; mat[0][1] -= a[0][1]; mat[0][2] -= a[0][2]; mat[0][3] -= a[0][3]; mat[0][4] -= a[0][4]; mat[1][0] -= a[1][0]; mat[1][1] -= a[1][1]; mat[1][2] -= a[1][2]; mat[1][3] -= a[1][3]; mat[1][4] -= a[1][4]; mat[2][0] -= a[2][0]; mat[2][1] -= a[2][1]; mat[2][2] -= a[2][2]; mat[2][3] -= a[2][3]; mat[2][4] -= a[2][4]; mat[3][0] -= a[3][0]; mat[3][1] -= a[3][1]; mat[3][2] -= a[3][2]; mat[3][3] -= a[3][3]; mat[3][4] -= a[3][4]; mat[4][0] -= a[4][0]; mat[4][1] -= a[4][1]; mat[4][2] -= a[4][2]; mat[4][3] -= a[4][3]; mat[4][4] -= a[4][4]; return *this; } ID_INLINE idVec5 operator*( const idVec5 &vec, const idMat5 &mat ) { return mat * vec; } ID_INLINE idMat5 operator*( const float a, idMat5 const &mat ) { return mat * a; } ID_INLINE idVec5 &operator*=( idVec5 &vec, const idMat5 &mat ) { vec = mat * vec; return vec; } ID_INLINE bool idMat5::Compare( const idMat5 &a ) const { dword i; const float *ptr1, *ptr2; ptr1 = reinterpret_cast<const float *>(mat); ptr2 = reinterpret_cast<const float *>(a.mat); for ( i = 0; i < 5*5; i++ ) { if ( ptr1[i] != ptr2[i] ) { return false; } } return true; } ID_INLINE bool idMat5::Compare( const idMat5 &a, const float epsilon ) const { dword i; const float *ptr1, *ptr2; ptr1 = reinterpret_cast<const float *>(mat); ptr2 = reinterpret_cast<const float *>(a.mat); for ( i = 0; i < 5*5; i++ ) { if ( noMath::Fabs( ptr1[i] - ptr2[i] ) > epsilon ) { return false; } } return true; } ID_INLINE bool idMat5::operator==( const idMat5 &a ) const { return Compare( a ); } ID_INLINE bool idMat5::operator!=( const idMat5 &a ) const { return !Compare( a ); } ID_INLINE void idMat5::Zero( void ) { memset( mat, 0, sizeof( idMat5 ) ); } ID_INLINE void idMat5::Identity( void ) { *this = mat5_identity; } ID_INLINE bool idMat5::IsIdentity( const float epsilon ) const { return Compare( mat5_identity, epsilon ); } ID_INLINE bool idMat5::IsSymmetric( const float epsilon ) const { for ( int i = 1; i < 5; i++ ) { for ( int j = 0; j < i; j++ ) { if ( noMath::Fabs( mat[i][j] - mat[j][i] ) > epsilon ) { return false; } } } return true; } ID_INLINE bool idMat5::IsDiagonal( const float epsilon ) const { for ( int i = 0; i < 5; i++ ) { for ( int j = 0; j < 5; j++ ) { if ( i != j && noMath::Fabs( mat[i][j] ) > epsilon ) { return false; } } } return true; } ID_INLINE float idMat5::Trace( void ) const { return ( mat[0][0] + mat[1][1] + mat[2][2] + mat[3][3] + mat[4][4] ); } ID_INLINE idMat5 idMat5::Inverse( void ) const { idMat5 invMat; invMat = *this; int r = invMat.InverseSelf(); assert( r ); return invMat; } ID_INLINE idMat5 idMat5::InverseFast( void ) const { idMat5 invMat; invMat = *this; int r = invMat.InverseFastSelf(); assert( r ); return invMat; } ID_INLINE int idMat5::GetDimension( void ) const { return 25; } ID_INLINE const float *idMat5::ToFloatPtr( void ) const { return mat[0].ToFloatPtr(); } ID_INLINE float *idMat5::ToFloatPtr( void ) { return mat[0].ToFloatPtr(); } //=============================================================== // // idMat6 - 6x6 matrix // //=============================================================== class idMat6 { public: idMat6( void ); explicit idMat6( const idVec6 &v0, const idVec6 &v1, const idVec6 &v2, const idVec6 &v3, const idVec6 &v4, const idVec6 &v5 ); explicit idMat6( const noMat3 &m0, const noMat3 &m1, const noMat3 &m2, const noMat3 &m3 ); explicit idMat6( const float src[ 6 ][ 6 ] ); const idVec6 & operator[]( int index ) const; idVec6 & operator[]( int index ); idMat6 operator*( const float a ) const; idVec6 operator*( const idVec6 &vec ) const; idMat6 operator*( const idMat6 &a ) const; idMat6 operator+( const idMat6 &a ) const; idMat6 operator-( const idMat6 &a ) const; idMat6 & operator*=( const float a ); idMat6 & operator*=( const idMat6 &a ); idMat6 & operator+=( const idMat6 &a ); idMat6 & operator-=( const idMat6 &a ); friend idMat6 operator*( const float a, const idMat6 &mat ); friend idVec6 operator*( const idVec6 &vec, const idMat6 &mat ); friend idVec6 & operator*=( idVec6 &vec, const idMat6 &mat ); bool Compare( const idMat6 &a ) const; // exact compare, no epsilon bool Compare( const idMat6 &a, const float epsilon ) const; // compare with epsilon bool operator==( const idMat6 &a ) const; // exact compare, no epsilon bool operator!=( const idMat6 &a ) const; // exact compare, no epsilon void Zero( void ); void Identity( void ); bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const; bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const; noMat3 SubMat3( int n ) const; float Trace( void ) const; float Determinant( void ) const; idMat6 Transpose( void ) const; // returns transpose idMat6 & TransposeSelf( void ); idMat6 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseSelf( void ); // returns false if determinant is zero idMat6 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseFastSelf( void ); // returns false if determinant is zero int GetDimension( void ) const; const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; private: idVec6 mat[ 6 ]; }; extern idMat6 mat6_zero; extern idMat6 mat6_identity; #define mat6_default mat6_identity ID_INLINE idMat6::idMat6( void ) { } ID_INLINE idMat6::idMat6( const noMat3 &m0, const noMat3 &m1, const noMat3 &m2, const noMat3 &m3 ) { mat[0] = idVec6( m0[0][0], m0[0][1], m0[0][2], m1[0][0], m1[0][1], m1[0][2] ); mat[1] = idVec6( m0[1][0], m0[1][1], m0[1][2], m1[1][0], m1[1][1], m1[1][2] ); mat[2] = idVec6( m0[2][0], m0[2][1], m0[2][2], m1[2][0], m1[2][1], m1[2][2] ); mat[3] = idVec6( m2[0][0], m2[0][1], m2[0][2], m3[0][0], m3[0][1], m3[0][2] ); mat[4] = idVec6( m2[1][0], m2[1][1], m2[1][2], m3[1][0], m3[1][1], m3[1][2] ); mat[5] = idVec6( m2[2][0], m2[2][1], m2[2][2], m3[2][0], m3[2][1], m3[2][2] ); } ID_INLINE idMat6::idMat6( const idVec6 &v0, const idVec6 &v1, const idVec6 &v2, const idVec6 &v3, const idVec6 &v4, const idVec6 &v5 ) { mat[0] = v0; mat[1] = v1; mat[2] = v2; mat[3] = v3; mat[4] = v4; mat[5] = v5; } ID_INLINE idMat6::idMat6( const float src[ 6 ][ 6 ] ) { memcpy( mat, src, 6 * 6 * sizeof( float ) ); } ID_INLINE const idVec6 &idMat6::operator[]( int index ) const { //assert( ( index >= 0 ) && ( index < 6 ) ); return mat[ index ]; } ID_INLINE idVec6 &idMat6::operator[]( int index ) { //assert( ( index >= 0 ) && ( index < 6 ) ); return mat[ index ]; } ID_INLINE idMat6 idMat6::operator*( const idMat6 &a ) const { int i, j; const float *m1Ptr, *m2Ptr; float *dstPtr; idMat6 dst; m1Ptr = reinterpret_cast<const float *>(this); m2Ptr = reinterpret_cast<const float *>(&a); dstPtr = reinterpret_cast<float *>(&dst); for ( i = 0; i < 6; i++ ) { for ( j = 0; j < 6; j++ ) { *dstPtr = m1Ptr[0] * m2Ptr[ 0 * 6 + j ] + m1Ptr[1] * m2Ptr[ 1 * 6 + j ] + m1Ptr[2] * m2Ptr[ 2 * 6 + j ] + m1Ptr[3] * m2Ptr[ 3 * 6 + j ] + m1Ptr[4] * m2Ptr[ 4 * 6 + j ] + m1Ptr[5] * m2Ptr[ 5 * 6 + j ]; dstPtr++; } m1Ptr += 6; } return dst; } ID_INLINE idMat6 idMat6::operator*( const float a ) const { return idMat6( idVec6( mat[0][0] * a, mat[0][1] * a, mat[0][2] * a, mat[0][3] * a, mat[0][4] * a, mat[0][5] * a ), idVec6( mat[1][0] * a, mat[1][1] * a, mat[1][2] * a, mat[1][3] * a, mat[1][4] * a, mat[1][5] * a ), idVec6( mat[2][0] * a, mat[2][1] * a, mat[2][2] * a, mat[2][3] * a, mat[2][4] * a, mat[2][5] * a ), idVec6( mat[3][0] * a, mat[3][1] * a, mat[3][2] * a, mat[3][3] * a, mat[3][4] * a, mat[3][5] * a ), idVec6( mat[4][0] * a, mat[4][1] * a, mat[4][2] * a, mat[4][3] * a, mat[4][4] * a, mat[4][5] * a ), idVec6( mat[5][0] * a, mat[5][1] * a, mat[5][2] * a, mat[5][3] * a, mat[5][4] * a, mat[5][5] * a ) ); } ID_INLINE idVec6 idMat6::operator*( const idVec6 &vec ) const { return idVec6( mat[0][0] * vec[0] + mat[0][1] * vec[1] + mat[0][2] * vec[2] + mat[0][3] * vec[3] + mat[0][4] * vec[4] + mat[0][5] * vec[5], mat[1][0] * vec[0] + mat[1][1] * vec[1] + mat[1][2] * vec[2] + mat[1][3] * vec[3] + mat[1][4] * vec[4] + mat[1][5] * vec[5], mat[2][0] * vec[0] + mat[2][1] * vec[1] + mat[2][2] * vec[2] + mat[2][3] * vec[3] + mat[2][4] * vec[4] + mat[2][5] * vec[5], mat[3][0] * vec[0] + mat[3][1] * vec[1] + mat[3][2] * vec[2] + mat[3][3] * vec[3] + mat[3][4] * vec[4] + mat[3][5] * vec[5], mat[4][0] * vec[0] + mat[4][1] * vec[1] + mat[4][2] * vec[2] + mat[4][3] * vec[3] + mat[4][4] * vec[4] + mat[4][5] * vec[5], mat[5][0] * vec[0] + mat[5][1] * vec[1] + mat[5][2] * vec[2] + mat[5][3] * vec[3] + mat[5][4] * vec[4] + mat[5][5] * vec[5] ); } ID_INLINE idMat6 idMat6::operator+( const idMat6 &a ) const { return idMat6( idVec6( mat[0][0] + a[0][0], mat[0][1] + a[0][1], mat[0][2] + a[0][2], mat[0][3] + a[0][3], mat[0][4] + a[0][4], mat[0][5] + a[0][5] ), idVec6( mat[1][0] + a[1][0], mat[1][1] + a[1][1], mat[1][2] + a[1][2], mat[1][3] + a[1][3], mat[1][4] + a[1][4], mat[1][5] + a[1][5] ), idVec6( mat[2][0] + a[2][0], mat[2][1] + a[2][1], mat[2][2] + a[2][2], mat[2][3] + a[2][3], mat[2][4] + a[2][4], mat[2][5] + a[2][5] ), idVec6( mat[3][0] + a[3][0], mat[3][1] + a[3][1], mat[3][2] + a[3][2], mat[3][3] + a[3][3], mat[3][4] + a[3][4], mat[3][5] + a[3][5] ), idVec6( mat[4][0] + a[4][0], mat[4][1] + a[4][1], mat[4][2] + a[4][2], mat[4][3] + a[4][3], mat[4][4] + a[4][4], mat[4][5] + a[4][5] ), idVec6( mat[5][0] + a[5][0], mat[5][1] + a[5][1], mat[5][2] + a[5][2], mat[5][3] + a[5][3], mat[5][4] + a[5][4], mat[5][5] + a[5][5] ) ); } ID_INLINE idMat6 idMat6::operator-( const idMat6 &a ) const { return idMat6( idVec6( mat[0][0] - a[0][0], mat[0][1] - a[0][1], mat[0][2] - a[0][2], mat[0][3] - a[0][3], mat[0][4] - a[0][4], mat[0][5] - a[0][5] ), idVec6( mat[1][0] - a[1][0], mat[1][1] - a[1][1], mat[1][2] - a[1][2], mat[1][3] - a[1][3], mat[1][4] - a[1][4], mat[1][5] - a[1][5] ), idVec6( mat[2][0] - a[2][0], mat[2][1] - a[2][1], mat[2][2] - a[2][2], mat[2][3] - a[2][3], mat[2][4] - a[2][4], mat[2][5] - a[2][5] ), idVec6( mat[3][0] - a[3][0], mat[3][1] - a[3][1], mat[3][2] - a[3][2], mat[3][3] - a[3][3], mat[3][4] - a[3][4], mat[3][5] - a[3][5] ), idVec6( mat[4][0] - a[4][0], mat[4][1] - a[4][1], mat[4][2] - a[4][2], mat[4][3] - a[4][3], mat[4][4] - a[4][4], mat[4][5] - a[4][5] ), idVec6( mat[5][0] - a[5][0], mat[5][1] - a[5][1], mat[5][2] - a[5][2], mat[5][3] - a[5][3], mat[5][4] - a[5][4], mat[5][5] - a[5][5] ) ); } ID_INLINE idMat6 &idMat6::operator*=( const float a ) { mat[0][0] *= a; mat[0][1] *= a; mat[0][2] *= a; mat[0][3] *= a; mat[0][4] *= a; mat[0][5] *= a; mat[1][0] *= a; mat[1][1] *= a; mat[1][2] *= a; mat[1][3] *= a; mat[1][4] *= a; mat[1][5] *= a; mat[2][0] *= a; mat[2][1] *= a; mat[2][2] *= a; mat[2][3] *= a; mat[2][4] *= a; mat[2][5] *= a; mat[3][0] *= a; mat[3][1] *= a; mat[3][2] *= a; mat[3][3] *= a; mat[3][4] *= a; mat[3][5] *= a; mat[4][0] *= a; mat[4][1] *= a; mat[4][2] *= a; mat[4][3] *= a; mat[4][4] *= a; mat[4][5] *= a; mat[5][0] *= a; mat[5][1] *= a; mat[5][2] *= a; mat[5][3] *= a; mat[5][4] *= a; mat[5][5] *= a; return *this; } ID_INLINE idMat6 &idMat6::operator*=( const idMat6 &a ) { *this = *this * a; return *this; } ID_INLINE idMat6 &idMat6::operator+=( const idMat6 &a ) { mat[0][0] += a[0][0]; mat[0][1] += a[0][1]; mat[0][2] += a[0][2]; mat[0][3] += a[0][3]; mat[0][4] += a[0][4]; mat[0][5] += a[0][5]; mat[1][0] += a[1][0]; mat[1][1] += a[1][1]; mat[1][2] += a[1][2]; mat[1][3] += a[1][3]; mat[1][4] += a[1][4]; mat[1][5] += a[1][5]; mat[2][0] += a[2][0]; mat[2][1] += a[2][1]; mat[2][2] += a[2][2]; mat[2][3] += a[2][3]; mat[2][4] += a[2][4]; mat[2][5] += a[2][5]; mat[3][0] += a[3][0]; mat[3][1] += a[3][1]; mat[3][2] += a[3][2]; mat[3][3] += a[3][3]; mat[3][4] += a[3][4]; mat[3][5] += a[3][5]; mat[4][0] += a[4][0]; mat[4][1] += a[4][1]; mat[4][2] += a[4][2]; mat[4][3] += a[4][3]; mat[4][4] += a[4][4]; mat[4][5] += a[4][5]; mat[5][0] += a[5][0]; mat[5][1] += a[5][1]; mat[5][2] += a[5][2]; mat[5][3] += a[5][3]; mat[5][4] += a[5][4]; mat[5][5] += a[5][5]; return *this; } ID_INLINE idMat6 &idMat6::operator-=( const idMat6 &a ) { mat[0][0] -= a[0][0]; mat[0][1] -= a[0][1]; mat[0][2] -= a[0][2]; mat[0][3] -= a[0][3]; mat[0][4] -= a[0][4]; mat[0][5] -= a[0][5]; mat[1][0] -= a[1][0]; mat[1][1] -= a[1][1]; mat[1][2] -= a[1][2]; mat[1][3] -= a[1][3]; mat[1][4] -= a[1][4]; mat[1][5] -= a[1][5]; mat[2][0] -= a[2][0]; mat[2][1] -= a[2][1]; mat[2][2] -= a[2][2]; mat[2][3] -= a[2][3]; mat[2][4] -= a[2][4]; mat[2][5] -= a[2][5]; mat[3][0] -= a[3][0]; mat[3][1] -= a[3][1]; mat[3][2] -= a[3][2]; mat[3][3] -= a[3][3]; mat[3][4] -= a[3][4]; mat[3][5] -= a[3][5]; mat[4][0] -= a[4][0]; mat[4][1] -= a[4][1]; mat[4][2] -= a[4][2]; mat[4][3] -= a[4][3]; mat[4][4] -= a[4][4]; mat[4][5] -= a[4][5]; mat[5][0] -= a[5][0]; mat[5][1] -= a[5][1]; mat[5][2] -= a[5][2]; mat[5][3] -= a[5][3]; mat[5][4] -= a[5][4]; mat[5][5] -= a[5][5]; return *this; } ID_INLINE idVec6 operator*( const idVec6 &vec, const idMat6 &mat ) { return mat * vec; } ID_INLINE idMat6 operator*( const float a, idMat6 const &mat ) { return mat * a; } ID_INLINE idVec6 &operator*=( idVec6 &vec, const idMat6 &mat ) { vec = mat * vec; return vec; } ID_INLINE bool idMat6::Compare( const idMat6 &a ) const { dword i; const float *ptr1, *ptr2; ptr1 = reinterpret_cast<const float *>(mat); ptr2 = reinterpret_cast<const float *>(a.mat); for ( i = 0; i < 6*6; i++ ) { if ( ptr1[i] != ptr2[i] ) { return false; } } return true; } ID_INLINE bool idMat6::Compare( const idMat6 &a, const float epsilon ) const { dword i; const float *ptr1, *ptr2; ptr1 = reinterpret_cast<const float *>(mat); ptr2 = reinterpret_cast<const float *>(a.mat); for ( i = 0; i < 6*6; i++ ) { if ( noMath::Fabs( ptr1[i] - ptr2[i] ) > epsilon ) { return false; } } return true; } ID_INLINE bool idMat6::operator==( const idMat6 &a ) const { return Compare( a ); } ID_INLINE bool idMat6::operator!=( const idMat6 &a ) const { return !Compare( a ); } ID_INLINE void idMat6::Zero( void ) { memset( mat, 0, sizeof( idMat6 ) ); } ID_INLINE void idMat6::Identity( void ) { *this = mat6_identity; } ID_INLINE bool idMat6::IsIdentity( const float epsilon ) const { return Compare( mat6_identity, epsilon ); } ID_INLINE bool idMat6::IsSymmetric( const float epsilon ) const { for ( int i = 1; i < 6; i++ ) { for ( int j = 0; j < i; j++ ) { if ( noMath::Fabs( mat[i][j] - mat[j][i] ) > epsilon ) { return false; } } } return true; } ID_INLINE bool idMat6::IsDiagonal( const float epsilon ) const { for ( int i = 0; i < 6; i++ ) { for ( int j = 0; j < 6; j++ ) { if ( i != j && noMath::Fabs( mat[i][j] ) > epsilon ) { return false; } } } return true; } ID_INLINE noMat3 idMat6::SubMat3( int n ) const { assert( n >= 0 && n < 4 ); int b0 = ((n & 2) >> 1) * 3; int b1 = (n & 1) * 3; return noMat3( mat[b0 + 0][b1 + 0], mat[b0 + 0][b1 + 1], mat[b0 + 0][b1 + 2], mat[b0 + 1][b1 + 0], mat[b0 + 1][b1 + 1], mat[b0 + 1][b1 + 2], mat[b0 + 2][b1 + 0], mat[b0 + 2][b1 + 1], mat[b0 + 2][b1 + 2] ); } ID_INLINE float idMat6::Trace( void ) const { return ( mat[0][0] + mat[1][1] + mat[2][2] + mat[3][3] + mat[4][4] + mat[5][5] ); } ID_INLINE idMat6 idMat6::Inverse( void ) const { idMat6 invMat; invMat = *this; int r = invMat.InverseSelf(); assert( r ); return invMat; } ID_INLINE idMat6 idMat6::InverseFast( void ) const { idMat6 invMat; invMat = *this; int r = invMat.InverseFastSelf(); assert( r ); return invMat; } ID_INLINE int idMat6::GetDimension( void ) const { return 36; } ID_INLINE const float *idMat6::ToFloatPtr( void ) const { return mat[0].ToFloatPtr(); } ID_INLINE float *idMat6::ToFloatPtr( void ) { return mat[0].ToFloatPtr(); } //=============================================================== // // idMatX - arbitrary sized dense real matrix // // The matrix lives on 16 byte aligned and 16 byte padded memory. // // NOTE: due to the temporary memory pool idMatX cannot be used by multiple threads. // //=============================================================== #define MATX_MAX_TEMP 1024 #define MATX_QUAD( x ) ( ( ( ( x ) + 3 ) & ~3 ) * sizeof( float ) ) #define MATX_CLEAREND() int s = numRows * numColumns; while( s < ( ( s + 3 ) & ~3 ) ) { mat[s++] = 0.0f; } #define MATX_ALLOCA( n ) ( (float *) _alloca16( MATX_QUAD( n ) ) ) #define MATX_SIMD class idMatX { public: idMatX( void ); explicit idMatX( int rows, int columns ); explicit idMatX( int rows, int columns, float *src ); ~idMatX( void ); void Set( int rows, int columns, const float *src ); void Set( const noMat3 &m1, const noMat3 &m2 ); void Set( const noMat3 &m1, const noMat3 &m2, const noMat3 &m3, const noMat3 &m4 ); const float * operator[]( int index ) const; float * operator[]( int index ); idMatX & operator=( const idMatX &a ); idMatX operator*( const float a ) const; idVecX operator*( const idVecX &vec ) const; idMatX operator*( const idMatX &a ) const; idMatX operator+( const idMatX &a ) const; idMatX operator-( const idMatX &a ) const; idMatX & operator*=( const float a ); idMatX & operator*=( const idMatX &a ); idMatX & operator+=( const idMatX &a ); idMatX & operator-=( const idMatX &a ); friend idMatX operator*( const float a, const idMatX &m ); friend idVecX operator*( const idVecX &vec, const idMatX &m ); friend idVecX & operator*=( idVecX &vec, const idMatX &m ); bool Compare( const idMatX &a ) const; // exact compare, no epsilon bool Compare( const idMatX &a, const float epsilon ) const; // compare with epsilon bool operator==( const idMatX &a ) const; // exact compare, no epsilon bool operator!=( const idMatX &a ) const; // exact compare, no epsilon void SetSize( int rows, int columns ); // set the number of rows/columns void ChangeSize( int rows, int columns, bool makeZero = false ); // change the size keeping data intact where possible int GetNumRows( void ) const { return numRows; } // get the number of rows int GetNumColumns( void ) const { return numColumns; } // get the number of columns void SetData( int rows, int columns, float *data ); // set float array pointer void Zero( void ); // clear matrix void Zero( int rows, int columns ); // set size and clear matrix void Identity( void ); // clear to identity matrix void Identity( int rows, int columns ); // set size and clear to identity matrix void Diag( const idVecX &v ); // create diagonal matrix from vector void Random( int seed, float l = 0.0f, float u = 1.0f ); // fill matrix with random values void Random( int rows, int columns, int seed, float l = 0.0f, float u = 1.0f ); void Negate( void ); // (*this) = - (*this) void Clamp( float min, float max ); // clamp all values idMatX & SwapRows( int r1, int r2 ); // swap rows idMatX & SwapColumns( int r1, int r2 ); // swap columns idMatX & SwapRowsColumns( int r1, int r2 ); // swap rows and columns idMatX & RemoveRow( int r ); // remove a row idMatX & RemoveColumn( int r ); // remove a column idMatX & RemoveRowColumn( int r ); // remove a row and column void ClearUpperTriangle( void ); // clear the upper triangle void ClearLowerTriangle( void ); // clear the lower triangle void SquareSubMatrix( const idMatX &m, int size ); // get square sub-matrix from 0,0 to size,size float MaxDifference( const idMatX &m ) const; // return maximum element difference between this and m bool IsSquare( void ) const { return ( numRows == numColumns ); } bool IsZero( const float epsilon = MATRIX_EPSILON ) const; bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const; bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const; bool IsTriDiagonal( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const; bool IsOrthogonal( const float epsilon = MATRIX_EPSILON ) const; bool IsOrthonormal( const float epsilon = MATRIX_EPSILON ) const; bool IsPMatrix( const float epsilon = MATRIX_EPSILON ) const; bool IsZMatrix( const float epsilon = MATRIX_EPSILON ) const; bool IsPositiveDefinite( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetricPositiveDefinite( const float epsilon = MATRIX_EPSILON ) const; bool IsPositiveSemiDefinite( const float epsilon = MATRIX_EPSILON ) const; bool IsSymmetricPositiveSemiDefinite( const float epsilon = MATRIX_EPSILON ) const; float Trace( void ) const; // returns product of diagonal elements float Determinant( void ) const; // returns determinant of matrix idMatX Transpose( void ) const; // returns transpose idMatX & TransposeSelf( void ); // transposes the matrix itself idMatX Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseSelf( void ); // returns false if determinant is zero idMatX InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity ) bool InverseFastSelf( void ); // returns false if determinant is zero bool LowerTriangularInverse( void ); // in-place inversion, returns false if determinant is zero bool UpperTriangularInverse( void ); // in-place inversion, returns false if determinant is zero idVecX Multiply( const idVecX &vec ) const; // (*this) * vec idVecX TransposeMultiply( const idVecX &vec ) const; // this->Transpose() * vec idMatX Multiply( const idMatX &a ) const; // (*this) * a idMatX TransposeMultiply( const idMatX &a ) const; // this->Transpose() * a void Multiply( idVecX &dst, const idVecX &vec ) const; // dst = (*this) * vec void MultiplyAdd( idVecX &dst, const idVecX &vec ) const; // dst += (*this) * vec void MultiplySub( idVecX &dst, const idVecX &vec ) const; // dst -= (*this) * vec void TransposeMultiply( idVecX &dst, const idVecX &vec ) const; // dst = this->Transpose() * vec void TransposeMultiplyAdd( idVecX &dst, const idVecX &vec ) const; // dst += this->Transpose() * vec void TransposeMultiplySub( idVecX &dst, const idVecX &vec ) const; // dst -= this->Transpose() * vec void Multiply( idMatX &dst, const idMatX &a ) const; // dst = (*this) * a void TransposeMultiply( idMatX &dst, const idMatX &a ) const; // dst = this->Transpose() * a int GetDimension( void ) const; // returns total number of values in matrix const idVec6 & SubVec6( int row ) const; // interpret beginning of row as a const idVec6 idVec6 & SubVec6( int row ); // interpret beginning of row as an idVec6 const idVecX SubVecX( int row ) const; // interpret complete row as a const idVecX idVecX SubVecX( int row ); // interpret complete row as an idVecX const float * ToFloatPtr( void ) const; // pointer to const matrix float array float * ToFloatPtr( void ); // pointer to matrix float array const char * ToString( int precision = 2 ) const; void Update_RankOne( const idVecX &v, const idVecX &w, float alpha ); void Update_RankOneSymmetric( const idVecX &v, float alpha ); void Update_RowColumn( const idVecX &v, const idVecX &w, int r ); void Update_RowColumnSymmetric( const idVecX &v, int r ); void Update_Increment( const idVecX &v, const idVecX &w ); void Update_IncrementSymmetric( const idVecX &v ); void Update_Decrement( int r ); bool Inverse_GaussJordan( void ); // invert in-place with Gauss-Jordan elimination bool Inverse_UpdateRankOne( const idVecX &v, const idVecX &w, float alpha ); bool Inverse_UpdateRowColumn( const idVecX &v, const idVecX &w, int r ); bool Inverse_UpdateIncrement( const idVecX &v, const idVecX &w ); bool Inverse_UpdateDecrement( const idVecX &v, const idVecX &w, int r ); void Inverse_Solve( idVecX &x, const idVecX &b ) const; bool LU_Factor( int *index, float *det = NULL ); // factor in-place: L * U bool LU_UpdateRankOne( const idVecX &v, const idVecX &w, float alpha, int *index ); bool LU_UpdateRowColumn( const idVecX &v, const idVecX &w, int r, int *index ); bool LU_UpdateIncrement( const idVecX &v, const idVecX &w, int *index ); bool LU_UpdateDecrement( const idVecX &v, const idVecX &w, const idVecX &u, int r, int *index ); void LU_Solve( idVecX &x, const idVecX &b, const int *index ) const; void LU_Inverse( idMatX &inv, const int *index ) const; void LU_UnpackFactors( idMatX &L, idMatX &U ) const; void LU_MultiplyFactors( idMatX &m, const int *index ) const; bool QR_Factor( idVecX &c, idVecX &d ); // factor in-place: Q * R bool QR_UpdateRankOne( idMatX &R, const idVecX &v, const idVecX &w, float alpha ); bool QR_UpdateRowColumn( idMatX &R, const idVecX &v, const idVecX &w, int r ); bool QR_UpdateIncrement( idMatX &R, const idVecX &v, const idVecX &w ); bool QR_UpdateDecrement( idMatX &R, const idVecX &v, const idVecX &w, int r ); void QR_Solve( idVecX &x, const idVecX &b, const idVecX &c, const idVecX &d ) const; void QR_Solve( idVecX &x, const idVecX &b, const idMatX &R ) const; void QR_Inverse( idMatX &inv, const idVecX &c, const idVecX &d ) const; void QR_UnpackFactors( idMatX &Q, idMatX &R, const idVecX &c, const idVecX &d ) const; void QR_MultiplyFactors( idMatX &m, const idVecX &c, const idVecX &d ) const; bool SVD_Factor( idVecX &w, idMatX &V ); // factor in-place: U * Diag(w) * V.Transpose() void SVD_Solve( idVecX &x, const idVecX &b, const idVecX &w, const idMatX &V ) const; void SVD_Inverse( idMatX &inv, const idVecX &w, const idMatX &V ) const; void SVD_MultiplyFactors( idMatX &m, const idVecX &w, const idMatX &V ) const; bool Cholesky_Factor( void ); // factor in-place: L * L.Transpose() bool Cholesky_UpdateRankOne( const idVecX &v, float alpha, int offset = 0 ); bool Cholesky_UpdateRowColumn( const idVecX &v, int r ); bool Cholesky_UpdateIncrement( const idVecX &v ); bool Cholesky_UpdateDecrement( const idVecX &v, int r ); void Cholesky_Solve( idVecX &x, const idVecX &b ) const; void Cholesky_Inverse( idMatX &inv ) const; void Cholesky_MultiplyFactors( idMatX &m ) const; bool LDLT_Factor( void ); // factor in-place: L * D * L.Transpose() bool LDLT_UpdateRankOne( const idVecX &v, float alpha, int offset = 0 ); bool LDLT_UpdateRowColumn( const idVecX &v, int r ); bool LDLT_UpdateIncrement( const idVecX &v ); bool LDLT_UpdateDecrement( const idVecX &v, int r ); void LDLT_Solve( idVecX &x, const idVecX &b ) const; void LDLT_Inverse( idMatX &inv ) const; void LDLT_UnpackFactors( idMatX &L, idMatX &D ) const; void LDLT_MultiplyFactors( idMatX &m ) const; void TriDiagonal_ClearTriangles( void ); bool TriDiagonal_Solve( idVecX &x, const idVecX &b ) const; void TriDiagonal_Inverse( idMatX &inv ) const; bool Eigen_SolveSymmetricTriDiagonal( idVecX &eigenValues ); bool Eigen_SolveSymmetric( idVecX &eigenValues ); bool Eigen_Solve( idVecX &realEigenValues, idVecX &imaginaryEigenValues ); void Eigen_SortIncreasing( idVecX &eigenValues ); void Eigen_SortDecreasing( idVecX &eigenValues ); static void Test( void ); private: int numRows; // number of rows int numColumns; // number of columns int alloced; // floats allocated, if -1 then mat points to data set with SetData float * mat; // memory the matrix is stored static float temp[MATX_MAX_TEMP+4]; // used to store intermediate results static float * tempPtr; // pointer to 16 byte aligned temporary memory static int tempIndex; // index into memory pool, wraps around private: void SetTempSize( int rows, int columns ); float DeterminantGeneric( void ) const; bool InverseSelfGeneric( void ); void QR_Rotate( idMatX &R, int i, float a, float b ); float Pythag( float a, float b ) const; void SVD_BiDiag( idVecX &w, idVecX &rv1, float &anorm ); void SVD_InitialWV( idVecX &w, idMatX &V, idVecX &rv1 ); void HouseholderReduction( idVecX &diag, idVecX &subd ); bool QL( idVecX &diag, idVecX &subd ); void HessenbergReduction( idMatX &H ); void ComplexDivision( float xr, float xi, float yr, float yi, float &cdivr, float &cdivi ); bool HessenbergToRealSchur( idMatX &H, idVecX &realEigenValues, idVecX &imaginaryEigenValues ); }; ID_INLINE idMatX::idMatX( void ) { numRows = numColumns = alloced = 0; mat = NULL; } ID_INLINE idMatX::~idMatX( void ) { // if not temp memory if ( mat != NULL && ( mat < idMatX::tempPtr || mat > idMatX::tempPtr + MATX_MAX_TEMP ) && alloced != -1 ) { Mem_Free16( mat ); } } ID_INLINE idMatX::idMatX( int rows, int columns ) { numRows = numColumns = alloced = 0; mat = NULL; SetSize( rows, columns ); } ID_INLINE idMatX::idMatX( int rows, int columns, float *src ) { numRows = numColumns = alloced = 0; mat = NULL; SetData( rows, columns, src ); } ID_INLINE void idMatX::Set( int rows, int columns, const float *src ) { SetSize( rows, columns ); memcpy( this->mat, src, rows * columns * sizeof( float ) ); } ID_INLINE void idMatX::Set( const noMat3 &m1, const noMat3 &m2 ) { int i, j; SetSize( 3, 6 ); for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 3; j++ ) { mat[(i+0) * numColumns + (j+0)] = m1[i][j]; mat[(i+0) * numColumns + (j+3)] = m2[i][j]; } } } ID_INLINE void idMatX::Set( const noMat3 &m1, const noMat3 &m2, const noMat3 &m3, const noMat3 &m4 ) { int i, j; SetSize( 6, 6 ); for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 3; j++ ) { mat[(i+0) * numColumns + (j+0)] = m1[i][j]; mat[(i+0) * numColumns + (j+3)] = m2[i][j]; mat[(i+3) * numColumns + (j+0)] = m3[i][j]; mat[(i+3) * numColumns + (j+3)] = m4[i][j]; } } } ID_INLINE const float *idMatX::operator[]( int index ) const { assert( ( index >= 0 ) && ( index < numRows ) ); return mat + index * numColumns; } ID_INLINE float *idMatX::operator[]( int index ) { assert( ( index >= 0 ) && ( index < numRows ) ); return mat + index * numColumns; } ID_INLINE idMatX &idMatX::operator=( const idMatX &a ) { SetSize( a.numRows, a.numColumns ); #ifdef MATX_SIMD SIMDProcessor->Copy16( mat, a.mat, a.numRows * a.numColumns ); #else memcpy( mat, a.mat, a.numRows * a.numColumns * sizeof( float ) ); #endif idMatX::tempIndex = 0; return *this; } ID_INLINE idMatX idMatX::operator*( const float a ) const { idMatX m; m.SetTempSize( numRows, numColumns ); #ifdef MATX_SIMD SIMDProcessor->Mul16( m.mat, mat, a, numRows * numColumns ); #else int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { m.mat[i] = mat[i] * a; } #endif return m; } ID_INLINE idVecX idMatX::operator*( const idVecX &vec ) const { idVecX dst; assert( numColumns == vec.GetSize() ); dst.SetTempSize( numRows ); #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplyVecX( dst, *this, vec ); #else Multiply( dst, vec ); #endif return dst; } ID_INLINE idMatX idMatX::operator*( const idMatX &a ) const { idMatX dst; assert( numColumns == a.numRows ); dst.SetTempSize( numRows, a.numColumns ); #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplyMatX( dst, *this, a ); #else Multiply( dst, a ); #endif return dst; } ID_INLINE idMatX idMatX::operator+( const idMatX &a ) const { idMatX m; assert( numRows == a.numRows && numColumns == a.numColumns ); m.SetTempSize( numRows, numColumns ); #ifdef MATX_SIMD SIMDProcessor->Add16( m.mat, mat, a.mat, numRows * numColumns ); #else int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { m.mat[i] = mat[i] + a.mat[i]; } #endif return m; } ID_INLINE idMatX idMatX::operator-( const idMatX &a ) const { idMatX m; assert( numRows == a.numRows && numColumns == a.numColumns ); m.SetTempSize( numRows, numColumns ); #ifdef MATX_SIMD SIMDProcessor->Sub16( m.mat, mat, a.mat, numRows * numColumns ); #else int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { m.mat[i] = mat[i] - a.mat[i]; } #endif return m; } ID_INLINE idMatX &idMatX::operator*=( const float a ) { #ifdef MATX_SIMD SIMDProcessor->MulAssign16( mat, a, numRows * numColumns ); #else int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { mat[i] *= a; } #endif idMatX::tempIndex = 0; return *this; } ID_INLINE idMatX &idMatX::operator*=( const idMatX &a ) { *this = *this * a; idMatX::tempIndex = 0; return *this; } ID_INLINE idMatX &idMatX::operator+=( const idMatX &a ) { assert( numRows == a.numRows && numColumns == a.numColumns ); #ifdef MATX_SIMD SIMDProcessor->AddAssign16( mat, a.mat, numRows * numColumns ); #else int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { mat[i] += a.mat[i]; } #endif idMatX::tempIndex = 0; return *this; } ID_INLINE idMatX &idMatX::operator-=( const idMatX &a ) { assert( numRows == a.numRows && numColumns == a.numColumns ); #ifdef MATX_SIMD SIMDProcessor->SubAssign16( mat, a.mat, numRows * numColumns ); #else int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { mat[i] -= a.mat[i]; } #endif idMatX::tempIndex = 0; return *this; } ID_INLINE idMatX operator*( const float a, idMatX const &m ) { return m * a; } ID_INLINE idVecX operator*( const idVecX &vec, const idMatX &m ) { return m * vec; } ID_INLINE idVecX &operator*=( idVecX &vec, const idMatX &m ) { vec = m * vec; return vec; } ID_INLINE bool idMatX::Compare( const idMatX &a ) const { int i, s; assert( numRows == a.numRows && numColumns == a.numColumns ); s = numRows * numColumns; for ( i = 0; i < s; i++ ) { if ( mat[i] != a.mat[i] ) { return false; } } return true; } ID_INLINE bool idMatX::Compare( const idMatX &a, const float epsilon ) const { int i, s; assert( numRows == a.numRows && numColumns == a.numColumns ); s = numRows * numColumns; for ( i = 0; i < s; i++ ) { if ( noMath::Fabs( mat[i] - a.mat[i] ) > epsilon ) { return false; } } return true; } ID_INLINE bool idMatX::operator==( const idMatX &a ) const { return Compare( a ); } ID_INLINE bool idMatX::operator!=( const idMatX &a ) const { return !Compare( a ); } ID_INLINE void idMatX::SetSize( int rows, int columns ) { assert( mat < idMatX::tempPtr || mat > idMatX::tempPtr + MATX_MAX_TEMP ); int alloc = ( rows * columns + 3 ) & ~3; if ( alloc > alloced && alloced != -1 ) { if ( mat != NULL ) { Mem_Free16( mat ); } mat = (float *) Mem_Alloc16( alloc * sizeof( float ) ); alloced = alloc; } numRows = rows; numColumns = columns; MATX_CLEAREND(); } ID_INLINE void idMatX::SetTempSize( int rows, int columns ) { int newSize; newSize = ( rows * columns + 3 ) & ~3; assert( newSize < MATX_MAX_TEMP ); if ( idMatX::tempIndex + newSize > MATX_MAX_TEMP ) { idMatX::tempIndex = 0; } mat = idMatX::tempPtr + idMatX::tempIndex; idMatX::tempIndex += newSize; alloced = newSize; numRows = rows; numColumns = columns; MATX_CLEAREND(); } ID_INLINE void idMatX::SetData( int rows, int columns, float *data ) { assert( mat < idMatX::tempPtr || mat > idMatX::tempPtr + MATX_MAX_TEMP ); if ( mat != NULL && alloced != -1 ) { Mem_Free16( mat ); } assert( ( ( (int) data ) & 15 ) == 0 ); // data must be 16 byte aligned mat = data; alloced = -1; numRows = rows; numColumns = columns; MATX_CLEAREND(); } ID_INLINE void idMatX::Zero( void ) { #ifdef MATX_SIMD SIMDProcessor->Zero16( mat, numRows * numColumns ); #else memset( mat, 0, numRows * numColumns * sizeof( float ) ); #endif } ID_INLINE void idMatX::Zero( int rows, int columns ) { SetSize( rows, columns ); #ifdef MATX_SIMD SIMDProcessor->Zero16( mat, numRows * numColumns ); #else memset( mat, 0, rows * columns * sizeof( float ) ); #endif } ID_INLINE void idMatX::Identity( void ) { assert( numRows == numColumns ); #ifdef MATX_SIMD SIMDProcessor->Zero16( mat, numRows * numColumns ); #else memset( mat, 0, numRows * numColumns * sizeof( float ) ); #endif for ( int i = 0; i < numRows; i++ ) { mat[i * numColumns + i] = 1.0f; } } ID_INLINE void idMatX::Identity( int rows, int columns ) { assert( rows == columns ); SetSize( rows, columns ); idMatX::Identity(); } ID_INLINE void idMatX::Diag( const idVecX &v ) { Zero( v.GetSize(), v.GetSize() ); for ( int i = 0; i < v.GetSize(); i++ ) { mat[i * numColumns + i] = v[i]; } } ID_INLINE void idMatX::Random( int seed, float l, float u ) { int i, s; float c; idRandom rnd(seed); c = u - l; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { mat[i] = l + rnd.RandomFloat() * c; } } ID_INLINE void idMatX::Random( int rows, int columns, int seed, float l, float u ) { int i, s; float c; idRandom rnd(seed); SetSize( rows, columns ); c = u - l; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { mat[i] = l + rnd.RandomFloat() * c; } } ID_INLINE void idMatX::Negate( void ) { #ifdef MATX_SIMD SIMDProcessor->Negate16( mat, numRows * numColumns ); #else int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { mat[i] = -mat[i]; } #endif } ID_INLINE void idMatX::Clamp( float min, float max ) { int i, s; s = numRows * numColumns; for ( i = 0; i < s; i++ ) { if ( mat[i] < min ) { mat[i] = min; } else if ( mat[i] > max ) { mat[i] = max; } } } ID_INLINE idMatX &idMatX::SwapRows( int r1, int r2 ) { float *ptr; ptr = (float *) _alloca16( numColumns * sizeof( float ) ); memcpy( ptr, mat + r1 * numColumns, numColumns * sizeof( float ) ); memcpy( mat + r1 * numColumns, mat + r2 * numColumns, numColumns * sizeof( float ) ); memcpy( mat + r2 * numColumns, ptr, numColumns * sizeof( float ) ); return *this; } ID_INLINE idMatX &idMatX::SwapColumns( int r1, int r2 ) { int i; float tmp, *ptr; for ( i = 0; i < numRows; i++ ) { ptr = mat + i * numColumns; tmp = ptr[r1]; ptr[r1] = ptr[r2]; ptr[r2] = tmp; } return *this; } ID_INLINE idMatX &idMatX::SwapRowsColumns( int r1, int r2 ) { SwapRows( r1, r2 ); SwapColumns( r1, r2 ); return *this; } ID_INLINE void idMatX::ClearUpperTriangle( void ) { assert( numRows == numColumns ); for ( int i = numRows-2; i >= 0; i-- ) { memset( mat + i * numColumns + i + 1, 0, (numColumns - 1 - i) * sizeof(float) ); } } ID_INLINE void idMatX::ClearLowerTriangle( void ) { assert( numRows == numColumns ); for ( int i = 1; i < numRows; i++ ) { memset( mat + i * numColumns, 0, i * sizeof(float) ); } } ID_INLINE void idMatX::SquareSubMatrix( const idMatX &m, int size ) { int i; assert( size <= m.numRows && size <= m.numColumns ); SetSize( size, size ); for ( i = 0; i < size; i++ ) { memcpy( mat + i * numColumns, m.mat + i * m.numColumns, size * sizeof( float ) ); } } ID_INLINE float idMatX::MaxDifference( const idMatX &m ) const { int i, j; float diff, maxDiff; assert( numRows == m.numRows && numColumns == m.numColumns ); maxDiff = -1.0f; for ( i = 0; i < numRows; i++ ) { for ( j = 0; j < numColumns; j++ ) { diff = noMath::Fabs( mat[ i * numColumns + j ] - m[i][j] ); if ( maxDiff < 0.0f || diff > maxDiff ) { maxDiff = diff; } } } return maxDiff; } ID_INLINE bool idMatX::IsZero( const float epsilon ) const { // returns true if (*this) == Zero for ( int i = 0; i < numRows; i++ ) { for ( int j = 0; j < numColumns; j++ ) { if ( noMath::Fabs( mat[i * numColumns + j] ) > epsilon ) { return false; } } } return true; } ID_INLINE bool idMatX::IsIdentity( const float epsilon ) const { // returns true if (*this) == Identity assert( numRows == numColumns ); for ( int i = 0; i < numRows; i++ ) { for ( int j = 0; j < numColumns; j++ ) { if ( noMath::Fabs( mat[i * numColumns + j] - (float)( i == j ) ) > epsilon ) { return false; } } } return true; } ID_INLINE bool idMatX::IsDiagonal( const float epsilon ) const { // returns true if all elements are zero except for the elements on the diagonal assert( numRows == numColumns ); for ( int i = 0; i < numRows; i++ ) { for ( int j = 0; j < numColumns; j++ ) { if ( i != j && noMath::Fabs( mat[i * numColumns + j] ) > epsilon ) { return false; } } } return true; } ID_INLINE bool idMatX::IsTriDiagonal( const float epsilon ) const { // returns true if all elements are zero except for the elements on the diagonal plus or minus one column if ( numRows != numColumns ) { return false; } for ( int i = 0; i < numRows-2; i++ ) { for ( int j = i+2; j < numColumns; j++ ) { if ( noMath::Fabs( (*this)[i][j] ) > epsilon ) { return false; } if ( noMath::Fabs( (*this)[j][i] ) > epsilon ) { return false; } } } return true; } ID_INLINE bool idMatX::IsSymmetric( const float epsilon ) const { // (*this)[i][j] == (*this)[j][i] if ( numRows != numColumns ) { return false; } for ( int i = 0; i < numRows; i++ ) { for ( int j = 0; j < numColumns; j++ ) { if ( noMath::Fabs( mat[ i * numColumns + j ] - mat[ j * numColumns + i ] ) > epsilon ) { return false; } } } return true; } ID_INLINE float idMatX::Trace( void ) const { float trace = 0.0f; assert( numRows == numColumns ); // sum of elements on the diagonal for ( int i = 0; i < numRows; i++ ) { trace += mat[i * numRows + i]; } return trace; } ID_INLINE float idMatX::Determinant( void ) const { assert( numRows == numColumns ); switch( numRows ) { case 1: return mat[0]; case 2: return reinterpret_cast<const noMat2 *>(mat)->Determinant(); case 3: return reinterpret_cast<const noMat3 *>(mat)->Determinant(); case 4: return reinterpret_cast<const noMat4 *>(mat)->Determinant(); case 5: return reinterpret_cast<const idMat5 *>(mat)->Determinant(); case 6: return reinterpret_cast<const idMat6 *>(mat)->Determinant(); default: return DeterminantGeneric(); } return 0.0f; } ID_INLINE idMatX idMatX::Transpose( void ) const { idMatX transpose; int i, j; transpose.SetTempSize( numColumns, numRows ); for ( i = 0; i < numRows; i++ ) { for ( j = 0; j < numColumns; j++ ) { transpose.mat[j * transpose.numColumns + i] = mat[i * numColumns + j]; } } return transpose; } ID_INLINE idMatX &idMatX::TransposeSelf( void ) { *this = Transpose(); return *this; } ID_INLINE idMatX idMatX::Inverse( void ) const { idMatX invMat; invMat.SetTempSize( numRows, numColumns ); memcpy( invMat.mat, mat, numRows * numColumns * sizeof( float ) ); int r = invMat.InverseSelf(); assert( r ); return invMat; } ID_INLINE bool idMatX::InverseSelf( void ) { assert( numRows == numColumns ); switch( numRows ) { case 1: if ( noMath::Fabs( mat[0] ) < MATRIX_INVERSE_EPSILON ) { return false; } mat[0] = 1.0f / mat[0]; return true; case 2: return reinterpret_cast<noMat2 *>(mat)->InverseSelf(); case 3: return reinterpret_cast<noMat3 *>(mat)->InverseSelf(); case 4: return reinterpret_cast<noMat4 *>(mat)->InverseSelf(); case 5: return reinterpret_cast<idMat5 *>(mat)->InverseSelf(); case 6: return reinterpret_cast<idMat6 *>(mat)->InverseSelf(); default: return InverseSelfGeneric(); } } ID_INLINE idMatX idMatX::InverseFast( void ) const { idMatX invMat; invMat.SetTempSize( numRows, numColumns ); memcpy( invMat.mat, mat, numRows * numColumns * sizeof( float ) ); int r = invMat.InverseFastSelf(); assert( r ); return invMat; } ID_INLINE bool idMatX::InverseFastSelf( void ) { assert( numRows == numColumns ); switch( numRows ) { case 1: if ( noMath::Fabs( mat[0] ) < MATRIX_INVERSE_EPSILON ) { return false; } mat[0] = 1.0f / mat[0]; return true; case 2: return reinterpret_cast<noMat2 *>(mat)->InverseFastSelf(); case 3: return reinterpret_cast<noMat3 *>(mat)->InverseFastSelf(); case 4: return reinterpret_cast<noMat4 *>(mat)->InverseFastSelf(); case 5: return reinterpret_cast<idMat5 *>(mat)->InverseFastSelf(); case 6: return reinterpret_cast<idMat6 *>(mat)->InverseFastSelf(); default: return InverseSelfGeneric(); } return false; } ID_INLINE idVecX idMatX::Multiply( const idVecX &vec ) const { idVecX dst; assert( numColumns == vec.GetSize() ); dst.SetTempSize( numRows ); #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplyVecX( dst, *this, vec ); #else Multiply( dst, vec ); #endif return dst; } ID_INLINE idMatX idMatX::Multiply( const idMatX &a ) const { idMatX dst; assert( numColumns == a.numRows ); dst.SetTempSize( numRows, a.numColumns ); #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplyMatX( dst, *this, a ); #else Multiply( dst, a ); #endif return dst; } ID_INLINE idVecX idMatX::TransposeMultiply( const idVecX &vec ) const { idVecX dst; assert( numRows == vec.GetSize() ); dst.SetTempSize( numColumns ); #ifdef MATX_SIMD SIMDProcessor->MatX_TransposeMultiplyVecX( dst, *this, vec ); #else TransposeMultiply( dst, vec ); #endif return dst; } ID_INLINE idMatX idMatX::TransposeMultiply( const idMatX &a ) const { idMatX dst; assert( numRows == a.numRows ); dst.SetTempSize( numColumns, a.numColumns ); #ifdef MATX_SIMD SIMDProcessor->MatX_TransposeMultiplyMatX( dst, *this, a ); #else TransposeMultiply( dst, a ); #endif return dst; } ID_INLINE void idMatX::Multiply( idVecX &dst, const idVecX &vec ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplyVecX( dst, *this, vec ); #else int i, j; const float *mPtr, *vPtr; float *dstPtr; mPtr = mat; vPtr = vec.ToFloatPtr(); dstPtr = dst.ToFloatPtr(); for ( i = 0; i < numRows; i++ ) { float sum = mPtr[0] * vPtr[0]; for ( j = 1; j < numColumns; j++ ) { sum += mPtr[j] * vPtr[j]; } dstPtr[i] = sum; mPtr += numColumns; } #endif } ID_INLINE void idMatX::MultiplyAdd( idVecX &dst, const idVecX &vec ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplyAddVecX( dst, *this, vec ); #else int i, j; const float *mPtr, *vPtr; float *dstPtr; mPtr = mat; vPtr = vec.ToFloatPtr(); dstPtr = dst.ToFloatPtr(); for ( i = 0; i < numRows; i++ ) { float sum = mPtr[0] * vPtr[0]; for ( j = 1; j < numColumns; j++ ) { sum += mPtr[j] * vPtr[j]; } dstPtr[i] += sum; mPtr += numColumns; } #endif } ID_INLINE void idMatX::MultiplySub( idVecX &dst, const idVecX &vec ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplySubVecX( dst, *this, vec ); #else int i, j; const float *mPtr, *vPtr; float *dstPtr; mPtr = mat; vPtr = vec.ToFloatPtr(); dstPtr = dst.ToFloatPtr(); for ( i = 0; i < numRows; i++ ) { float sum = mPtr[0] * vPtr[0]; for ( j = 1; j < numColumns; j++ ) { sum += mPtr[j] * vPtr[j]; } dstPtr[i] -= sum; mPtr += numColumns; } #endif } ID_INLINE void idMatX::TransposeMultiply( idVecX &dst, const idVecX &vec ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_TransposeMultiplyVecX( dst, *this, vec ); #else int i, j; const float *mPtr, *vPtr; float *dstPtr; vPtr = vec.ToFloatPtr(); dstPtr = dst.ToFloatPtr(); for ( i = 0; i < numColumns; i++ ) { mPtr = mat + i; float sum = mPtr[0] * vPtr[0]; for ( j = 1; j < numRows; j++ ) { mPtr += numColumns; sum += mPtr[0] * vPtr[j]; } dstPtr[i] = sum; } #endif } ID_INLINE void idMatX::TransposeMultiplyAdd( idVecX &dst, const idVecX &vec ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_TransposeMultiplyAddVecX( dst, *this, vec ); #else int i, j; const float *mPtr, *vPtr; float *dstPtr; vPtr = vec.ToFloatPtr(); dstPtr = dst.ToFloatPtr(); for ( i = 0; i < numColumns; i++ ) { mPtr = mat + i; float sum = mPtr[0] * vPtr[0]; for ( j = 1; j < numRows; j++ ) { mPtr += numColumns; sum += mPtr[0] * vPtr[j]; } dstPtr[i] += sum; } #endif } ID_INLINE void idMatX::TransposeMultiplySub( idVecX &dst, const idVecX &vec ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_TransposeMultiplySubVecX( dst, *this, vec ); #else int i, j; const float *mPtr, *vPtr; float *dstPtr; vPtr = vec.ToFloatPtr(); dstPtr = dst.ToFloatPtr(); for ( i = 0; i < numColumns; i++ ) { mPtr = mat + i; float sum = mPtr[0] * vPtr[0]; for ( j = 1; j < numRows; j++ ) { mPtr += numColumns; sum += mPtr[0] * vPtr[j]; } dstPtr[i] -= sum; } #endif } ID_INLINE void idMatX::Multiply( idMatX &dst, const idMatX &a ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_MultiplyMatX( dst, *this, a ); #else int i, j, k, l, n; float *dstPtr; const float *m1Ptr, *m2Ptr; double sum; assert( numColumns == a.numRows ); dstPtr = dst.ToFloatPtr(); m1Ptr = ToFloatPtr(); m2Ptr = a.ToFloatPtr(); k = numRows; l = a.GetNumColumns(); for ( i = 0; i < k; i++ ) { for ( j = 0; j < l; j++ ) { m2Ptr = a.ToFloatPtr() + j; sum = m1Ptr[0] * m2Ptr[0]; for ( n = 1; n < numColumns; n++ ) { m2Ptr += l; sum += m1Ptr[n] * m2Ptr[0]; } *dstPtr++ = sum; } m1Ptr += numColumns; } #endif } ID_INLINE void idMatX::TransposeMultiply( idMatX &dst, const idMatX &a ) const { #ifdef MATX_SIMD SIMDProcessor->MatX_TransposeMultiplyMatX( dst, *this, a ); #else int i, j, k, l, n; float *dstPtr; const float *m1Ptr, *m2Ptr; double sum; assert( numRows == a.numRows ); dstPtr = dst.ToFloatPtr(); m1Ptr = ToFloatPtr(); k = numColumns; l = a.numColumns; for ( i = 0; i < k; i++ ) { for ( j = 0; j < l; j++ ) { m1Ptr = ToFloatPtr() + i; m2Ptr = a.ToFloatPtr() + j; sum = m1Ptr[0] * m2Ptr[0]; for ( n = 1; n < numRows; n++ ) { m1Ptr += numColumns; m2Ptr += a.numColumns; sum += m1Ptr[0] * m2Ptr[0]; } *dstPtr++ = sum; } } #endif } ID_INLINE int idMatX::GetDimension( void ) const { return numRows * numColumns; } ID_INLINE const idVec6 &idMatX::SubVec6( int row ) const { assert( numColumns >= 6 && row >= 0 && row < numRows ); return *reinterpret_cast<const idVec6 *>(mat + row * numColumns); } ID_INLINE idVec6 &idMatX::SubVec6( int row ) { assert( numColumns >= 6 && row >= 0 && row < numRows ); return *reinterpret_cast<idVec6 *>(mat + row * numColumns); } ID_INLINE const idVecX idMatX::SubVecX( int row ) const { idVecX v; assert( row >= 0 && row < numRows ); v.SetData( numColumns, mat + row * numColumns ); return v; } ID_INLINE idVecX idMatX::SubVecX( int row ) { idVecX v; assert( row >= 0 && row < numRows ); v.SetData( numColumns, mat + row * numColumns ); return v; } ID_INLINE const float *idMatX::ToFloatPtr( void ) const { return mat; } ID_INLINE float *idMatX::ToFloatPtr( void ) { return mat; } #endif
[ "Sangyong79@gmail.com" ]
Sangyong79@gmail.com
6298c3a24f7bc7053f6e863cbbdd563c0809f641
2800d84b1b3e190e1cee4aa2ab509e66d6cf0b3c
/driect_project/window_start/15_cpp_1/SpreadsheetCell.h
f19c2ed2bb52e8f082351de6ac5938f4dcaf2271
[]
no_license
kakaxi1100/DirectxHeaven
835db2c9e6e7b25ee2f82483fea9c8c71802f446
197a8c603cd59f76c1f3f53fa03154b61db05c94
refs/heads/master
2020-04-15T14:29:11.136594
2016-08-28T10:18:35
2016-08-28T10:18:35
50,349,706
0
0
null
null
null
null
UTF-8
C++
false
false
408
h
#pragma once #include <string> class SpreadsheetCell { public: SpreadsheetCell(const SpreadsheetCell& rsh); void setValue(double inValue); double getValue() const; void setString(const std::string inString); const std::string getString() const; private: std::string doubleToString(double inValue) const; double stringToDouble(const std::string inString) const; double mValue; std::string mString; };
[ "aresleecool@163.com" ]
aresleecool@163.com
b64de015023e8b6dd0090edfc6639449128d3fe7
d40d73a0973a2071285e52884cd3f6b6fdb28f56
/Stopwatch-Timer/sketch_Stopwatch.ino
d6c598bd2ef2a5ec53fc5f84f725df1c4335a8c1
[]
no_license
mrinalraj2809/Arduino
bd10c20eba38cb340470ff35e4d775ad6b7c3d74
dab65b4423660235d3634fd1eb26a1ddb1695c63
refs/heads/master
2020-08-04T19:30:41.548433
2019-10-02T05:45:14
2019-10-02T05:45:14
212,255,066
1
0
null
null
null
null
UTF-8
C++
false
false
989
ino
#include <LiquidCrystal.h> LiquidCrystal lcd(7,6,5,4,3,2); void setup() { pinMode(8,INPUT); pinMode(9,INPUT); Serial.begin(9600); digitalWrite(8,HIGH); digitalWrite(9,HIGH); lcd.begin(16,2); lcd.clear(); } double i,a,c; void loop() { lcd.clear(); lcd.print("Press Start"); delay(100); if(digitalRead(8)==LOW) { lcd.clear(); a=millis(); while(digitalRead(9)==HIGH) { c=millis(); lcd.clear(); i=(c-a)/1000; lcd.setCursor(0,0); lcd.print(i); lcd.setCursor(11,0); lcd.print("Sec's"); lcd.clear(); Serial.println(c); Serial.println(a); Serial.println(i); Serial.println("----------"); delay(100); } if(digitalRead(9)==LOW) { while(digitalRead(8)==LOW) { lcd.clear(); lcd.setCursor(0,0); lcd.print(i); lcd.setCursor(11,0); lcd.print("Sec's"); delay(100); lcd.clear(); } } } }
[ "mrinalraj2809@gmail.com" ]
mrinalraj2809@gmail.com
ae0ee55c88f9f7bb114f747551efb2eb165ab61d
9bdca347c1d0cb80edf4bdbd2e9a80ead6092af7
/downsampler.cpp
86c55271f3d67bb9578c626fb077ea99ec5971bf
[]
no_license
batusai8889/libKeyFinder
4882fd1728b9076c8f84ca737db869b4483b6830
aa69a99bff0baae8cc75101b99b9042539230ffe
refs/heads/master
2020-12-24T20:43:34.788076
2013-01-21T14:59:13
2013-01-21T14:59:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,956
cpp
/************************************************************************* Copyright 2011-2013 Ibrahim Sha'ath This file is part of LibKeyFinder. LibKeyFinder is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LibKeyFinder 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 LibKeyFinder. If not, see <http://www.gnu.org/licenses/>. *************************************************************************/ #include "downsampler.h" namespace KeyFinder{ void Downsampler::downsample(AudioData*& audioIn, const float& lastFreq, LowPassFilterFactory* lpfFactory) const{ // TODO: there is presumably some good maths to determine filter frequencies float midCutoff = lastFreq * 1.05; float endCutoff = lastFreq * 1.10; unsigned int downsampleFactor = (int)floor( audioIn->getFrameRate() / 2 / endCutoff ); if (downsampleFactor == 1) return; // prep output buffer AudioData* audioOut = new AudioData(); audioOut->setFrameRate(audioIn->getFrameRate() / downsampleFactor); audioOut->setChannels(audioIn->getChannels()); unsigned int c = audioIn->getChannels(); unsigned int ns = audioIn->getSampleCount() / downsampleFactor; while(ns % c != 0) ns++; if (audioIn->getSampleCount() % downsampleFactor > 0) ns += c; try{ audioOut->addToSampleCount(ns); }catch(const Exception& e){ throw e; } // prep filter unsigned int filterOrder = 160; unsigned int filterDelay = filterOrder/2; // create circular buffer for filter delay Binode<float>* p = new Binode<float>(); // first node Binode<float>* q = p; for (unsigned int i=0; i<filterOrder; i++){ q->r = new Binode<float>(); // subsequent nodes q->r->l = q; q = q->r; } // join first and last nodes p->l = q; q->r = p; // get filter LowPassFilter* lpf = lpfFactory->getLowPassFilter(filterOrder + 1, audioIn->getFrameRate(), midCutoff, 2048); // for each channel (should be mono by this point but just in case) for (unsigned int i = 0; i < c; i++){ q = p; // clear delay buffer for (unsigned int k = 0; k <= filterOrder; k++){ q->data = 0.0; q = q->r; } // for each frame (running off the end of the sample stream by filterDelay) for (int j = i; j < (signed)(audioIn->getSampleCount() + filterDelay); j += c){ // shuffle old samples along delay buffer p = p->r; // load new sample into delay buffer if (j < (signed)audioIn->getSampleCount()) p->l->data = audioIn->getSample(j) / lpf->gain; else p->l->data = 0.0; // zero pad once we're into the delay at the end of the file if ((j % (downsampleFactor * c)) < c){ // only do the maths for the useful samples float sum = 0.0; q = p; for (unsigned int k = 0; k <= filterOrder; k++){ sum += lpf->coefficients[k] * q->data; q = q->r; } // don't try and set samples during the warm-up, only once we've passed filterDelay samples if (j - (signed)filterDelay >= 0){ audioOut->setSample(((j-filterDelay) / downsampleFactor) + i, sum); } } } } // delete delay buffer for (unsigned int k = 0; k <= filterOrder; k++){ q = p; p = p->r; delete q; } // note we don't delete the LPF; it's stored in the factory for reuse delete audioIn; audioIn = audioOut; } }
[ "ibrahimshaath@gmail.com" ]
ibrahimshaath@gmail.com
034ce4d2596bbd07768eaf9a6fd351e7d087454f
b0c8df4b9c606a58c2f9779273120f2f0acc6024
/Unisinos/Estruturas de dados C++/Lista de exercícios 2/Exercício 2/Guerreiro.h
9e4ef0e5fec8b056094ecf01ba09dea27755efb8
[]
no_license
MarshallAlvarez/Codigos_em_CPP
2c1b8bf164bba8cfe77573142b4a7a58ed91d1bb
80efc62b9bd5efb8420cdd61b2637760df7e3166
refs/heads/master
2021-01-07T15:38:56.011234
2020-04-19T22:33:56
2020-04-19T22:33:56
226,173,468
0
0
null
null
null
null
UTF-8
C++
false
false
934
h
#ifndef GUERREIRO_H #define GUERREIRO_H #include "Humano.h" class Guerreiro : public Humano { public : // Guerreiro void lutar ( Guerreiro *l ) ; void beber ( Guerreiro *l ) ; void morrer ( Guerreiro *l ) ; void treinar ( Guerreiro *l ) ; void afiarArma( Guerreiro *l ) ; // Paladino void rezar ( Guerreiro *s ) ; void heroismo ( Guerreiro *s ) ; void vitalidade ( Guerreiro *s ) ; void auraDaVida ( Guerreiro *s ) ; void favorDivino( Guerreiro *s ) ; // Barbaro void furia ( Guerreiro *b ) ; void matar ( Guerreiro *b ) ; void reviver ( Guerreiro *b ) ; void retaliar ( Guerreiro *b ) ; void instintoPrimal( Guerreiro *b ) ; } ; #endif
[ "noreply@github.com" ]
MarshallAlvarez.noreply@github.com
c08c365aed66ee1744b63aebd0aef8516a4e898c
ca4b4c9ae9497f0e20a33ba883c66e7f3d5bab53
/JetStudies/16663_CompressedMoneyPlot/MakeMoneyPlotTry4.cpp
3d7ce1d4538aa21eb5d5fb781a9726a41cbcb231
[]
no_license
FHead/PhysicsHIJetMass
79c0dd7a0019b0198803af64dfc7a4753b7a9174
7cb8c27aa1c89593986a90a2b68ddcc991806c00
refs/heads/master
2023-05-31T07:52:24.263711
2021-06-16T09:00:35
2021-06-16T09:00:35
377,433,346
0
0
null
null
null
null
UTF-8
C++
false
false
32,277
cpp
#include <iostream> #include <vector> using namespace std; #include "TCanvas.h" #include "TH1D.h" #include "TGraphAsymmErrors.h" #include "TPad.h" #include "TGaxis.h" #include "TLine.h" #include "TLatex.h" #include "TLegend.h" #include "PlotHelper3.h" #define SD0_PT 0 #define SD0_CENTRALITY 1 #define SD7_PT 2 #define SD7_CENTRALITY 3 int main(); void MakePlot(vector<TGraphAsymmErrors *> G, vector<TGraphAsymmErrors *> T, string OutputBase, int Preset = SD0_PT); bool DivideAndShift(vector<TGraphAsymmErrors *> &G, vector<TGraphAsymmErrors *> &R, double YShift, double RShift); bool DivideAndShiftTheory(vector<TGraphAsymmErrors *> &T, vector<TGraphAsymmErrors *> &R, double YShift, double RShift); void Division(TGraphAsymmErrors *G1, TGraphAsymmErrors *G2, TGraphAsymmErrors *GRatio); void ShiftUp(TGraphAsymmErrors *G, double Amount); TGraphAsymmErrors *HistogramToGraph(TH1D *H); int main() { TFile F0("Graphs_SD0_DataCentered.root"); TFile F7("Graphs_SD7_DataCentered.root"); TFile FT0("PickedPlots_SD0.root"); TFile FT7("PickedPlots_SD7.root"); vector<TGraphAsymmErrors *> G(16); vector<TGraphAsymmErrors *> T(24); G[0] = (TGraphAsymmErrors *)F0.Get("MassData0_0_1")->Clone(); G[1] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_1")->Clone(); G[2] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_1")->Clone(); G[3] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_1")->Clone(); G[4] = (TGraphAsymmErrors *)F0.Get("MassData0_0_2")->Clone(); G[5] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_2")->Clone(); G[6] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_2")->Clone(); G[7] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_2")->Clone(); G[8] = (TGraphAsymmErrors *)F0.Get("MassData0_0_3")->Clone(); G[9] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_3")->Clone(); G[10] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_3")->Clone(); G[11] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_3")->Clone(); G[12] = (TGraphAsymmErrors *)F0.Get("MassData0_0_4")->Clone(); G[13] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_4")->Clone(); G[14] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_4")->Clone(); G[15] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_4")->Clone(); T[0] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT1")); T[1] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT1")); T[2] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT1")); T[3] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT1")); T[4] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT1")); T[5] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT1")); T[6] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT2")); T[7] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT2")); T[8] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT2")); T[9] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT2")); T[10] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT2")); T[11] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT2")); T[12] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT3")); T[13] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT3")); T[14] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT3")); T[15] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT3")); T[16] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT3")); T[17] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT3")); T[18] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT4")); T[19] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT4")); T[20] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT4")); T[21] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT4")); T[22] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT4")); T[23] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT4")); MakePlot(G, T, "Plots/SD0_CBin0", SD0_PT); G[0] = (TGraphAsymmErrors *)F7.Get("MassData_0_1")->Clone(); G[1] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_1")->Clone(); G[2] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_1")->Clone(); G[3] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_1")->Clone(); G[4] = (TGraphAsymmErrors *)F7.Get("MassData_0_2")->Clone(); G[5] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_2")->Clone(); G[6] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_2")->Clone(); G[7] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_2")->Clone(); G[8] = (TGraphAsymmErrors *)F7.Get("MassData_0_3")->Clone(); G[9] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_3")->Clone(); G[10] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_3")->Clone(); G[11] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_3")->Clone(); G[12] = (TGraphAsymmErrors *)F7.Get("MassData_0_4")->Clone(); G[13] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_4")->Clone(); G[14] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_4")->Clone(); G[15] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_4")->Clone(); T[0] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT1")); T[1] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT1")); T[2] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT1")); T[3] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT1")); T[4] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT1")); T[5] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT1")); T[6] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT2")); T[7] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT2")); T[8] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT2")); T[9] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT2")); T[10] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT2")); T[11] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT2")); T[12] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT3")); T[13] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT3")); T[14] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT3")); T[15] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT3")); T[16] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT3")); T[17] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT3")); T[18] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT4")); T[19] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT4")); T[20] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT4")); T[21] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT4")); T[22] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT4")); T[23] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT4")); MakePlot(G, T, "Plots/SD7_CBin0", SD7_PT); G[0] = (TGraphAsymmErrors *)F0.Get("MassData0_0_2")->Clone(); G[1] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_2")->Clone(); G[2] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_2")->Clone(); G[3] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_2")->Clone(); G[4] = (TGraphAsymmErrors *)F0.Get("MassData0_1_2")->Clone(); G[5] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_1_2")->Clone(); G[6] = (TGraphAsymmErrors *)F0.Get("MassSmear0_1_2")->Clone(); G[7] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_1_2")->Clone(); G[8] = (TGraphAsymmErrors *)F0.Get("MassData0_2_2")->Clone(); G[9] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_2_2")->Clone(); G[10] = (TGraphAsymmErrors *)F0.Get("MassSmear0_2_2")->Clone(); G[11] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_2_2")->Clone(); G[12] = (TGraphAsymmErrors *)F0.Get("MassData0_3_2")->Clone(); G[13] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_3_2")->Clone(); G[14] = (TGraphAsymmErrors *)F0.Get("MassSmear0_3_2")->Clone(); G[15] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_3_2")->Clone(); for(int i = 0; i < 24; i++) T[i] = NULL; MakePlot(G, T, "Plots/SD0_PTBin2", SD0_CENTRALITY); G[0] = (TGraphAsymmErrors *)F7.Get("MassData_0_2")->Clone(); G[1] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_2")->Clone(); G[2] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_2")->Clone(); G[3] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_2")->Clone(); G[4] = (TGraphAsymmErrors *)F7.Get("MassData_1_2")->Clone(); G[5] = (TGraphAsymmErrors *)F7.Get("MassDataSys_1_2")->Clone(); G[6] = (TGraphAsymmErrors *)F7.Get("MassSmear_1_2")->Clone(); G[7] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_1_2")->Clone(); G[8] = (TGraphAsymmErrors *)F7.Get("MassData_2_2")->Clone(); G[9] = (TGraphAsymmErrors *)F7.Get("MassDataSys_2_2")->Clone(); G[10] = (TGraphAsymmErrors *)F7.Get("MassSmear_2_2")->Clone(); G[11] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_2_2")->Clone(); G[12] = (TGraphAsymmErrors *)F7.Get("MassData_3_2")->Clone(); G[13] = (TGraphAsymmErrors *)F7.Get("MassDataSys_3_2")->Clone(); G[14] = (TGraphAsymmErrors *)F7.Get("MassSmear_3_2")->Clone(); G[15] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_3_2")->Clone(); for(int i = 0; i < 24; i++) T[i] = NULL; MakePlot(G, T, "Plots/SD7_PTBin2", SD7_CENTRALITY); FT7.Close(); FT0.Close(); F7.Close(); F0.Close(); return 0; } void MakePlot(vector<TGraphAsymmErrors *> G, vector<TGraphAsymmErrors *> T, string OutputBase, int Preset) { // Inputs: edit to your liking double LeftMargin, RightMargin, TopMargin, BottomMargin, Height, Width; double XMin, XMax, YMin, YMax, RMin, RMax; double HeaderSize, BreakPointOffset, BreakPointSizeX, BreakPointSizeY, BreakPointSpacing; double TextSpacing; double TextYX, TextYY, TextRX, TextRY; int TextRAlign, TextYAlign; int AxisStyle, TopAxisStyle; LeftMargin = 100; RightMargin = 50; TopMargin = 50; BottomMargin = 75; Height = 700; Width = 500; TextSpacing = 0.035; if(Preset == SD0_PT) { XMin = 0.00; XMax = 0.27; YMin = 0.00; YMax = 7.99; RMin = 0.00; RMax = 11.99; HeaderSize = 1.5; BreakPointOffset = -0.07; BreakPointSizeX = 0.020; BreakPointSizeY = 0.004; BreakPointSpacing = 0.003; TextYAlign = 22; TextYX = 0.50; TextYY = 9.00; TextRAlign = 22; TextRX = 0.50; TextRY = 4.00; AxisStyle = 502; TopAxisStyle = 505; } if(Preset == SD7_PT) { XMin = 0.00; XMax = 0.26; YMin = 0.00; YMax = 19.99; RMin = 0.00; RMax = 6.99; HeaderSize = 1.5; BreakPointOffset = -0.07; BreakPointSizeX = 0.020; BreakPointSizeY = 0.004; BreakPointSpacing = 0.003; TextYAlign = 22; TextYX = 0.70; TextYY = 5.50; TextRAlign = 22; TextRX = 0.50; TextRY = 2.50; AxisStyle = 502; TopAxisStyle = 505; } if(Preset == SD0_CENTRALITY) { XMin = 0.00; XMax = 0.27; YMin = 0.00; YMax = 11.99; RMin = 0.00; RMax = 2.99; HeaderSize = 1.5; BreakPointOffset = -0.07; BreakPointSizeX = 0.020; BreakPointSizeY = 0.004; BreakPointSpacing = 0.003; TextYAlign = 22; TextYX = 0.50; TextYY = 9.50; TextRAlign = 22; TextRX = 0.50; TextRY = 1.70; AxisStyle = 502; TopAxisStyle = 505; } if(Preset == SD7_CENTRALITY) { XMin = 0.00; XMax = 0.26; YMin = 0.00; YMax = 19.99; RMin = 0.00; RMax = 2.99; HeaderSize = 1.5; BreakPointOffset = -0.07; BreakPointSizeX = 0.020; BreakPointSizeY = 0.004; BreakPointSpacing = 0.003; TextYAlign = 22; TextYX = 0.70; TextYY = 5.50; TextRAlign = 22; TextRX = 0.50; TextRY = 1.70; AxisStyle = 502; TopAxisStyle = 505; } // Derived inputs. Don't edit. double TotalHeight = Height + TopMargin + BottomMargin; double TotalWidth = Width + LeftMargin + RightMargin; double WorldYMin = YMin; double WorldYMax = YMin + (YMax - YMin) * (4 + HeaderSize); double YShift = YMax - YMin; double WorldRMin = RMin; double WorldRMax = RMin + (RMax - RMin) * (4 + HeaderSize); double RShift = RMax - RMin; double PanelHeight = Height / (4 + HeaderSize); // Canvas and pad settings TCanvas Canvas("Canvas", "", TotalWidth, TotalHeight); TPad *Pad = new TPad("Pad", "", LeftMargin / TotalWidth, BottomMargin / TotalHeight, (LeftMargin + Width) / TotalWidth, (BottomMargin + Height) / TotalHeight); Pad->SetTopMargin(0); Pad->SetRightMargin(0); Pad->SetBottomMargin(0); Pad->SetLeftMargin(0); Pad->Draw(); // Make sure the inputs are done correctly vector<TGraphAsymmErrors *> R(8, NULL); bool Success = DivideAndShift(G, R, YShift, RShift); if(Success == false) { for(int i = 0; i < 16; i++) { if(G[i] != NULL) delete G[i]; G[i] = NULL; } for(int i = 0; i < 24; i++) { if(T[i] != NULL) delete T[i]; T[i] = NULL; } return; } bool HasTheory = true; for(int i = 0; i < 24; i++) if(T[i] == NULL) HasTheory = false; vector<TGraphAsymmErrors *> RT(12, NULL); if(HasTheory == true) { Success = DivideAndShiftTheory(T, RT, YShift, RShift); if(Success == false) { for(int i = 0; i < 16; i++) { if(G[i] != NULL) delete G[i]; G[i] = NULL; } for(int i = 0; i < 24; i++) { if(T[i] != NULL) delete T[i]; T[i] = NULL; } return; } } // Set the stage TH2D HWorld("HWorld", ";;", 100, XMin, XMax, 100, WorldYMin, WorldYMax); HWorld.SetStats(0); HWorld.GetXaxis()->SetLabelSize(0); HWorld.GetYaxis()->SetLabelSize(0); HWorld.GetXaxis()->SetTickLength(0); HWorld.GetYaxis()->SetTickLength(0); TH2D HWorldRatio("HWorldRatio", ";;", 100, XMin, XMax, 100, WorldRMin, WorldRMax); HWorldRatio.SetStats(0); HWorldRatio.GetXaxis()->SetLabelSize(0); HWorldRatio.GetYaxis()->SetLabelSize(0); HWorldRatio.GetXaxis()->SetTickLength(0); HWorldRatio.GetYaxis()->SetTickLength(0); // Prepare axis TGaxis BottomAxis(LeftMargin / TotalWidth, BottomMargin / TotalHeight, (LeftMargin + Width) / TotalWidth, BottomMargin / TotalHeight, XMin, XMax, 1005, "S"); BottomAxis.SetName("BottomAxis"); BottomAxis.SetTitle("M_{g} / p_{T,jet}"); BottomAxis.SetTickLength(0.025); BottomAxis.SetTextFont(42); BottomAxis.SetLabelFont(42); BottomAxis.CenterTitle(true); BottomAxis.SetLabelOffset(-0.005); BottomAxis.SetTitleOffset(0.80); BottomAxis.Draw(); TGaxis LeftAxis1(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 0) / TotalHeight, LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight, YMin, YMax, AxisStyle, "S"); LeftAxis1.SetName("LeftAxis1"); LeftAxis1.SetTitle(""); LeftAxis1.SetTickLength(0.2); LeftAxis1.SetLabelFont(42); LeftAxis1.Draw(); TGaxis LeftAxis2(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight, LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight, YMin, YMax, AxisStyle, "S"); LeftAxis2.SetName("LeftAxis2"); LeftAxis2.SetTitle(""); LeftAxis2.SetTickLength(0.2); LeftAxis2.SetLabelFont(42); LeftAxis2.Draw(); TGaxis LeftAxis3(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight, LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight, YMin, YMax, AxisStyle, "S"); LeftAxis3.SetName("LeftAxis3"); LeftAxis3.SetTitle(""); LeftAxis3.SetTickLength(0.2); LeftAxis3.SetLabelFont(42); LeftAxis3.Draw(); TGaxis LeftAxis4(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight, LeftMargin / TotalWidth, (BottomMargin + Height) / TotalHeight, YMin, YMax + (YMax - YMin) * HeaderSize, TopAxisStyle, "S"); LeftAxis4.SetName("LeftAxis4"); LeftAxis4.SetTitle(""); LeftAxis4.SetTickLength(0.2 / (1 + HeaderSize)); LeftAxis4.SetLabelFont(42); LeftAxis4.Draw(); TGaxis LeftAxis(LeftMargin / TotalWidth, BottomMargin / TotalHeight, LeftMargin / TotalWidth, (BottomMargin + Height) / TotalHeight, YMin, YMax, 510, "S"); LeftAxis.SetName("LeftAxis"); LeftAxis.SetTitle("#frac{1}{N} #frac{d N}{d M_{g} / p_{T,jet}}"); LeftAxis.SetTickLength(0); LeftAxis.SetTextFont(42); LeftAxis.SetLabelSize(0); LeftAxis.CenterTitle(true); LeftAxis.SetTitleOffset(1.40); LeftAxis.Draw(); TGaxis RightAxis1((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 0) / TotalHeight, (LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight, YMin, YMax, AxisStyle, "S+L"); RightAxis1.SetName("RightAxis1"); RightAxis1.SetTitle(""); RightAxis1.SetTickLength(0.2); RightAxis1.SetLabelFont(42); RightAxis1.SetLabelSize(0); RightAxis1.Draw(); TGaxis RightAxis2((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight, (LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight, YMin, YMax, AxisStyle, "S+L"); RightAxis2.SetName("RightAxis2"); RightAxis2.SetTitle(""); RightAxis2.SetTickLength(0.2); RightAxis2.SetLabelFont(42); RightAxis2.SetLabelSize(0); RightAxis2.Draw(); TGaxis RightAxis3((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight, (LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight, YMin, YMax, AxisStyle, "S+L"); RightAxis3.SetName("RightAxis3"); RightAxis3.SetTitle(""); RightAxis3.SetTickLength(0.2); RightAxis3.SetLabelFont(42); RightAxis3.SetLabelSize(0); RightAxis3.Draw(); TGaxis RightAxis4((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight, (LeftMargin + Width) / TotalWidth, (BottomMargin + Height) / TotalHeight, YMin, YMax + (YMax - YMin) * HeaderSize, TopAxisStyle, "S+L"); RightAxis4.SetName("RightAxis4"); RightAxis4.SetTitle(""); RightAxis4.SetTickLength(0.2 / (1 + HeaderSize)); RightAxis4.SetLabelFont(42); RightAxis4.SetLabelSize(0); RightAxis4.Draw(); TLine Line; Line.SetLineWidth(2); Line.SetNDC(); for(int i = 0; i < 3; i++) { double X = LeftMargin / TotalWidth; double Y = (BottomMargin + PanelHeight * (i + 1) + PanelHeight * BreakPointOffset) / TotalHeight; Line.SetLineColor(kBlack); Line.DrawLine(X - BreakPointSizeX / 2, Y + BreakPointSpacing / 2 - BreakPointSizeY / 2, X + BreakPointSizeX / 2, Y + BreakPointSpacing / 2 + BreakPointSizeY / 2); Line.DrawLine(X - BreakPointSizeX / 2, Y - BreakPointSpacing / 2 - BreakPointSizeY / 2, X + BreakPointSizeX / 2, Y - BreakPointSpacing / 2 + BreakPointSizeY / 2); Line.SetLineColor(kWhite); Line.DrawLine(X - BreakPointSizeX, Y - BreakPointSizeY, X + BreakPointSizeX, Y + BreakPointSizeY); X = (LeftMargin + Width) / TotalWidth; Line.SetLineColor(kBlack); Line.DrawLine(X - BreakPointSizeX / 2, Y + BreakPointSpacing / 2 - BreakPointSizeY / 2, X + BreakPointSizeX / 2, Y + BreakPointSpacing / 2 + BreakPointSizeY / 2); Line.DrawLine(X - BreakPointSizeX / 2, Y - BreakPointSpacing / 2 - BreakPointSizeY / 2, X + BreakPointSizeX / 2, Y - BreakPointSpacing / 2 + BreakPointSizeY / 2); Line.SetLineColor(kWhite); Line.DrawLine(X - BreakPointSizeX, Y - BreakPointSizeY, X + BreakPointSizeX, Y + BreakPointSizeY); } // Prepare TGraphs and TLines TLine UnityLine; UnityLine.SetLineStyle(kDotted); // Prepare TLatex TLatex Latex; Latex.SetTextFont(42); Latex.SetNDC(); Latex.SetTextSize(0.035); Latex.SetTextAlign(31); Latex.DrawLatex((LeftMargin + Width) / TotalWidth, (BottomMargin + Height) / TotalHeight + 0.005, "PbPb 404 #mub^{-1} (5.02 TeV), pp 27.4 #mub^{-1} (5.02 TeV)"); Latex.SetTextSize(0.065); Latex.SetTextAlign(13); Latex.DrawLatex((LeftMargin) / TotalWidth + 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight, "#font[62]{CMS}"); Latex.SetTextSize(0.035); Latex.SetTextAlign(31); Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 0.5, "anti-k_{T} R = 0.4, |#eta_{jet}| < 1.3"); if(Preset == SD0_PT || Preset == SD0_CENTRALITY) Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 1.5, "Soft drop z_{cut} = 0.1, #beta = 0.0"); else Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 1.5, "Soft drop z_{cut} = 0.5, #beta = 1.5"); Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 2.5, "#DeltaR_{12} > 0.1"); if(Preset == SD0_PT || Preset == SD7_PT) Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 3.5, "Centrality: 0-10%"); else Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 3.5, "160 < p_{T,jet} < 180 GeV"); // Set graph styles for(int i = 0; i < 4; i++) { G[i*4+0]->SetMarkerSize(2.0); G[i*4+2]->SetMarkerSize(2.0); if(i % 2 == 0) { G[i*4+0]->SetMarkerStyle(25); G[i*4+2]->SetMarkerStyle(26); } else { G[i*4+0]->SetMarkerStyle(25); G[i*4+2]->SetMarkerStyle(22); } G[i*4+2]->SetFillStyle(3145); G[i*4+3]->SetFillStyle(3145); G[i*4+0]->SetFillColor(kRed - 9); G[i*4+1]->SetFillColor(kRed - 9); G[i*4+2]->SetFillColor(kGray + 2); G[i*4+3]->SetFillColor(kGray + 2); R[i*2+0]->SetMarkerSize(2.0); R[i*2+0]->SetMarkerStyle(25); R[i*2+0]->SetMarkerColor(kBlack); R[i*2+0]->SetLineColor(kBlack); R[i*2+0]->SetFillColor(kRed - 9); R[i*2+1]->SetFillColor(kRed - 9); } // Prepare Legend TLegend Legend1(0.10, 0.70, 0.60, 0.85); Legend1.SetTextFont(42); Legend1.SetTextSize(0.045); Legend1.SetBorderSize(0); Legend1.SetFillStyle(0); Legend1.AddEntry(G[0], "PbPb", "lpf"); Legend1.AddEntry(G[2], "Smeared pp", "lpf"); Legend1.AddEntry("", " ", ""); Legend1.AddEntry("", " ", ""); TLegend Legend2(0.10, 0.70, 0.60, 0.85); Legend2.SetTextFont(42); Legend2.SetTextSize(0.045); Legend2.SetBorderSize(0); Legend2.SetFillStyle(0); Legend2.AddEntry(R[0], "Data", "lpf"); if(HasTheory == true) { Legend2.AddEntry(RT[0], "Jewel (Recoil off)", "lp"); Legend2.AddEntry(RT[1], "Jewel (Recoil on)", "lp"); Legend2.AddEntry(RT[2], "QPythia", "lp"); } else { Legend2.AddEntry("", " ", ""); Legend2.AddEntry("", " ", ""); Legend2.AddEntry("", " ", ""); } // Draw it! Pad->cd(); HWorld.Draw("axis"); for(int i = 1; i < 16; i = i + 2) G[i]->Draw("2"); for(int i = 0; i < 16; i = i + 2) G[i]->Draw("p"); Latex.SetTextSize(0.045); Latex.SetTextAlign(TextYAlign); if(Preset == SD0_PT || Preset == SD7_PT) { Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 0) / (WorldYMax - YMin), "200 < p_{T,jet} < 300 GeV"); Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 1) / (WorldYMax - YMin), "180 < p_{T,jet} < 200 GeV"); Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 2) / (WorldYMax - YMin), "160 < p_{T,jet} < 180 GeV"); Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 3) / (WorldYMax - YMin), "140 < p_{T,jet} < 160 GeV"); } else { Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 0) / (WorldYMax - YMin), "50-80%"); Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 1) / (WorldYMax - YMin), "30-50%"); Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 2) / (WorldYMax - YMin), "10-30%"); Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 3) / (WorldYMax - YMin), "0-10%"); } HWorld.Draw("axis same"); Legend1.Draw(); Canvas.cd(); Canvas.SaveAs((OutputBase + "_Spectrum.pdf").c_str()); // Draw ratio! LeftAxis1.SetWmin(RMin); LeftAxis1.SetWmax(RMax); LeftAxis2.SetWmin(RMin); LeftAxis2.SetWmax(RMax); LeftAxis3.SetWmin(RMin); LeftAxis3.SetWmax(RMax); LeftAxis4.SetWmin(RMin); LeftAxis4.SetWmax(RMax + (RMax - RMin) * HeaderSize); RightAxis1.SetWmin(RMin); RightAxis1.SetWmax(RMax); RightAxis2.SetWmin(RMin); RightAxis2.SetWmax(RMax); RightAxis3.SetWmin(RMin); RightAxis3.SetWmax(RMax); RightAxis4.SetWmin(RMin); RightAxis4.SetWmax(RMax + (RMax - RMin) * HeaderSize); LeftAxis.SetTitle("#frac{PbPb}{Smeared pp}"); Pad->cd(); HWorldRatio.Draw("axis"); for(int i = 1; i < 8; i = i + 2) R[i]->Draw("2"); UnityLine.DrawLine(XMin, 1 + RShift * 0, XMax, 1 + RShift * 0); UnityLine.DrawLine(XMin, 1 + RShift * 1, XMax, 1 + RShift * 1); UnityLine.DrawLine(XMin, 1 + RShift * 2, XMax, 1 + RShift * 2); UnityLine.DrawLine(XMin, 1 + RShift * 3, XMax, 1 + RShift * 3); for(int i = 0; i < 8; i = i + 2) R[i]->Draw("p"); if(HasTheory == true) { for(int i = 0; i < 4; i++) { RT[i*3+0]->SetLineWidth(2); RT[i*3+1]->SetLineWidth(2); RT[i*3+2]->SetLineWidth(2); RT[i*3+0]->SetLineColor(kGreen - 2); RT[i*3+1]->SetLineColor(kBlue); RT[i*3+2]->SetLineColor(kRed); RT[i*3+0]->SetLineStyle(kSolid); RT[i*3+1]->SetLineStyle(kDashed); RT[i*3+2]->SetLineStyle(kDotted); RT[i*3+0]->SetMarkerStyle(20); RT[i*3+1]->SetMarkerStyle(20); RT[i*3+2]->SetMarkerStyle(20); RT[i*3+0]->SetMarkerSize(0); RT[i*3+1]->SetMarkerSize(0); RT[i*3+2]->SetMarkerSize(0); RT[i*3+0]->SetMarkerColor(kGreen - 2); RT[i*3+1]->SetMarkerColor(kBlue); RT[i*3+2]->SetMarkerColor(kRed); } for(int i = 0; i < 12; i++) RT[i]->Draw("l"); } Latex.SetTextSize(0.045); Latex.SetTextAlign(TextRAlign); if(Preset == SD0_PT || Preset == SD7_PT) { Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 0) / (WorldRMax - RMin), "200 < p_{T,jet} < 300 GeV"); Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 1) / (WorldRMax - RMin), "180 < p_{T,jet} < 200 GeV"); Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 2) / (WorldRMax - RMin), "160 < p_{T,jet} < 180 GeV"); Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 3) / (WorldRMax - RMin), "140 < p_{T,jet} < 160 GeV"); } else { Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 0) / (WorldRMax - RMin), "50-80%"); Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 1) / (WorldRMax - RMin), "30-50%"); Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 2) / (WorldRMax - RMin), "10-30%"); Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 3) / (WorldRMax - RMin), "0-10%"); } HWorldRatio.Draw("axis same"); Legend2.Draw(); Canvas.cd(); Canvas.SaveAs((OutputBase + "_Ratio.pdf").c_str()); // Clean up for(int i = 0; i < 16; i++) { if(G[i] != NULL) delete G[i]; G[i] = NULL; } for(int i = 0; i < 8; i++) if(R[i] != NULL) delete R[i]; for(int i = 0; i < 24; i++) { if(T[i] != NULL) delete T[i]; T[i] = NULL; } for(int i = 0; i < 12; i++) if(RT[i] != NULL) delete RT[i]; } bool DivideAndShift(vector<TGraphAsymmErrors *> &G, vector<TGraphAsymmErrors *> &R, double YShift, double RShift) { if(G.size() != 16) return false; for(int i = 0; i < 16; i++) if(G[i] == NULL) return false; for(int i = 0; i < 8; i++) { if(R[i] != NULL) delete R[i]; R[i] = new TGraphAsymmErrors; } // First do the division Division(G[0], G[2], R[0]); Division(G[1], G[3], R[1]); Division(G[4], G[6], R[2]); Division(G[5], G[7], R[3]); Division(G[8], G[10], R[4]); Division(G[9], G[11], R[5]); Division(G[12], G[14], R[6]); Division(G[13], G[15], R[7]); // Then do the shifting ShiftUp(G[0], YShift * 3); ShiftUp(G[1], YShift * 3); ShiftUp(G[2], YShift * 3); ShiftUp(G[3], YShift * 3); ShiftUp(G[4], YShift * 2); ShiftUp(G[5], YShift * 2); ShiftUp(G[6], YShift * 2); ShiftUp(G[7], YShift * 2); ShiftUp(G[8], YShift * 1); ShiftUp(G[9], YShift * 1); ShiftUp(G[10], YShift * 1); ShiftUp(G[11], YShift * 1); ShiftUp(G[12], YShift * 0); ShiftUp(G[13], YShift * 0); ShiftUp(G[14], YShift * 0); ShiftUp(G[15], YShift * 0); ShiftUp(R[0], RShift * 3); ShiftUp(R[1], RShift * 3); ShiftUp(R[2], RShift * 2); ShiftUp(R[3], RShift * 2); ShiftUp(R[4], RShift * 1); ShiftUp(R[5], RShift * 1); ShiftUp(R[6], RShift * 0); ShiftUp(R[7], RShift * 0); return true; } bool DivideAndShiftTheory(vector<TGraphAsymmErrors *> &T, vector<TGraphAsymmErrors *> &R, double YShift, double RShift) { if(T.size() != 24) return false; for(int i = 0; i < 24; i++) if(T[i] == NULL) return false; for(int i = 0; i < 12; i++) { if(R[i] != NULL) delete R[i]; R[i] = new TGraphAsymmErrors; } // First do the division Division(T[0], T[1], R[0]); Division(T[2], T[3], R[1]); Division(T[4], T[5], R[2]); Division(T[6], T[7], R[3]); Division(T[8], T[9], R[4]); Division(T[10], T[11], R[5]); Division(T[12], T[13], R[6]); Division(T[14], T[15], R[7]); Division(T[16], T[17], R[8]); Division(T[18], T[19], R[9]); Division(T[20], T[21], R[10]); Division(T[22], T[23], R[11]); // Then do the shifting ShiftUp(R[0], RShift * 3); ShiftUp(R[1], RShift * 3); ShiftUp(R[2], RShift * 3); ShiftUp(R[3], RShift * 2); ShiftUp(R[4], RShift * 2); ShiftUp(R[5], RShift * 2); ShiftUp(R[6], RShift * 1); ShiftUp(R[7], RShift * 1); ShiftUp(R[8], RShift * 1); ShiftUp(R[9], RShift * 0); ShiftUp(R[10], RShift * 0); ShiftUp(R[11], RShift * 0); return true; } void Division(TGraphAsymmErrors *G1, TGraphAsymmErrors *G2, TGraphAsymmErrors *GRatio) { if(G1 == NULL || G2 == NULL || GRatio == NULL) return; int BinCount = min(G1->GetN(), G2->GetN()); for(int i = 0; i < BinCount; i++) { double x1, x2, y1, y2; G1->GetPoint(i, x1, y1); G2->GetPoint(i, x2, y2); double xl1, xh1, xl2, xh2; xl1 = G1->GetErrorXlow(i); xh1 = G1->GetErrorXhigh(i); xl2 = G2->GetErrorXlow(i); xh2 = G2->GetErrorXhigh(i); double yl1, yh1, yl2, yh2; yl1 = G1->GetErrorYlow(i); yh1 = G1->GetErrorYhigh(i); yl2 = G2->GetErrorYlow(i); yh2 = G2->GetErrorYhigh(i); double ratio = (y1 / y2); double yl = ratio * sqrt((yl1 / y1) * (yl1 / y1) + (yl2 / y2) * (yl2 / y2)); double yh = ratio * sqrt((yh1 / y1) * (yh1 / y1) + (yh2 / y2) * (yh2 / y2)); if(x1 == x1 && x2 == x2 && ratio == ratio) { int N = GRatio->GetN(); GRatio->SetPoint(N, x1, ratio); GRatio->SetPointError(N, xl1, xh1, yl, yh); } } } void ShiftUp(TGraphAsymmErrors *G, double Amount) { if(G == NULL) return; int BinCount = G->GetN(); for(int i = 0; i < BinCount; i++) { double x, y; G->GetPoint(i, x, y); G->SetPoint(i, x, y + Amount); } } TGraphAsymmErrors *HistogramToGraph(TH1D *H) { if(H == NULL) return NULL; TGraphAsymmErrors *G = new TGraphAsymmErrors; for(int i = 1; i <= H->GetNbinsX(); i++) { double x = H->GetBinCenter(i); double y = H->GetBinContent(i); double l = H->GetXaxis()->GetBinLowEdge(i); double r = H->GetXaxis()->GetBinUpEdge(i); double e = H->GetBinError(i); if(y != y) continue; if(x > 0.27) continue; int I = G->GetN(); G->SetPoint(I, x, y); // G->SetPointError(I, x - l, r - x, e, e); } return G; }
[ "chen.yi.first@gmail.com" ]
chen.yi.first@gmail.com
12905e1f5232ee29d47e845f0ed5b4f3412f9fbd
0b63fa8325233e25478b76d0b4a9a6ee3070056d
/src/appleseed/foundation/utility/benchmark/helpers.h
7f4d4a7edeaa073b7a736466786653bf592111d7
[ "MIT" ]
permissive
hipopotamo-hipotalamo/appleseed
e8c61ccec64baf01b6aeb3cde4dd3031d37ece17
eaf07e3e602218a35711e7495ac633ce210c6078
refs/heads/master
2020-12-07T02:39:27.454003
2013-10-29T13:10:59
2013-10-29T13:10:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,695
h
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifndef APPLESEED_FOUNDATION_UTILITY_BENCHMARK_HELPERS_H #define APPLESEED_FOUNDATION_UTILITY_BENCHMARK_HELPERS_H // appleseed.foundation headers. #include "foundation/utility/benchmark/benchmarksuite.h" #include "foundation/utility/benchmark/benchmarksuiterepository.h" #include "foundation/utility/benchmark/ibenchmarkcase.h" #include "foundation/utility/benchmark/ibenchmarkcasefactory.h" namespace foundation { // // Define a benchmark suite. // #define BENCHMARK_SUITE(Name) \ namespace BenchmarkSuite##Name \ { \ struct BenchmarkSuite##Name \ : public foundation::BenchmarkSuite \ { \ BenchmarkSuite##Name() \ : foundation::BenchmarkSuite(#Name) \ { \ } \ }; \ \ foundation::BenchmarkSuite& current_benchmark_suite__() \ { \ static BenchmarkSuite##Name bs; \ return bs; \ } \ \ struct RegisterBenchmarkSuite##Name \ { \ RegisterBenchmarkSuite##Name() \ { \ using namespace foundation; \ BenchmarkSuite& suite = current_benchmark_suite__(); \ BenchmarkSuiteRepository::instance().register_suite(&suite); \ } \ }; \ \ static RegisterBenchmarkSuite##Name RegisterBenchmarkSuite##Name##_instance__; \ } \ \ namespace BenchmarkSuite##Name // // Define a benchmark case without fixture. // #define BENCHMARK_CASE(Name) \ struct BenchmarkCase##Name \ : public foundation::IBenchmarkCase \ { \ virtual const char* get_name() const \ { \ return #Name; \ } \ \ virtual void run(); \ }; \ \ struct BenchmarkCase##Name##Factory \ : public foundation::IBenchmarkCaseFactory \ { \ virtual const char* get_name() const \ { \ return #Name; \ } \ \ virtual foundation::IBenchmarkCase* create() \ { \ return new BenchmarkCase##Name(); \ } \ }; \ \ struct RegisterBenchmarkCase##Name \ { \ RegisterBenchmarkCase##Name() \ { \ using namespace foundation; \ static BenchmarkCase##Name##Factory factory; \ current_benchmark_suite__().register_case(&factory); \ } \ }; \ \ static RegisterBenchmarkCase##Name RegisterBenchmarkCase##Name##_instance__; \ \ void BenchmarkCase##Name::run() // // Define a benchmark case with fixture. // #define BENCHMARK_CASE_F(Name, FixtureName) \ struct BenchmarkCase##Name \ : public foundation::IBenchmarkCase \ , public FixtureName \ { \ virtual const char* get_name() const \ { \ return #Name; \ } \ \ virtual void run(); \ }; \ \ struct BenchmarkCase##Name##Factory \ : public foundation::IBenchmarkCaseFactory \ { \ virtual const char* get_name() const \ { \ return #Name; \ } \ \ virtual foundation::IBenchmarkCase* create() \ { \ return new BenchmarkCase##Name(); \ } \ }; \ \ struct RegisterBenchmarkCase##Name \ { \ RegisterBenchmarkCase##Name() \ { \ using namespace foundation; \ static BenchmarkCase##Name##Factory factory; \ current_benchmark_suite__().register_case(&factory); \ } \ }; \ \ static RegisterBenchmarkCase##Name RegisterBenchmarkCase##Name##_instance__; \ \ void BenchmarkCase##Name::run() // // Forward-declare a benchmark case. // #define DECLARE_BENCHMARK_CASE(SuiteName, CaseName) \ namespace BenchmarkSuite##SuiteName { struct BenchmarkCase##CaseName; } // // Declare that a benchmark case has access to the internals of a class. // #define GRANT_ACCESS_TO_BENCHMARK_CASE(SuiteName, CaseName) \ friend struct BenchmarkSuite##SuiteName::BenchmarkCase##CaseName } // namespace foundation #endif // !APPLESEED_FOUNDATION_UTILITY_BENCHMARK_HELPERS_H
[ "beaune@aist.enst.fr" ]
beaune@aist.enst.fr
e73573998ebec275a11fafb268d3903a4aa5f07e
0243726f2168b61895ec23d1b1314aa4d968c925
/windows/CrashHandler.h
1453fe11b429851417ba84e8778441a3a1b6cdb3
[]
no_license
3F/FlightSDC.RPC-WebSockets
6eae6b2349c0d39efb7e65018af3746080fcd97c
fa73c59aa5de8e6bba0f1fc9e9062c40d339ae18
refs/heads/master
2021-01-21T08:12:18.221113
2013-07-07T16:03:11
2013-08-05T14:47:09
68,389,120
1
2
null
null
null
null
UTF-8
C++
false
false
15,611
h
// Copyright 2012 Idol Software, Inc. // // This file is part of CrashHandler library. // // CrashHandler library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef __CRASH_HANDLER_H__ #define __CRASH_HANDLER_H__ #include <windows.h> //! Contains data that identifies your application. struct ApplicationInfo { DWORD ApplicationInfoSize; //!< Size of this structure. Should be set to sizeof(ApplicationInfo). LPCSTR ApplicationGUID; //!< GUID assigned to this application. LPCSTR Prefix; //!< Prefix that will be used with the dump name: YourPrefix_v1.v2.v3.v4_YYYYMMDD_HHMMSS.mini.dmp. LPCWSTR AppName; //!< Application name that will be used in message box. LPCWSTR Company; //!< Company name that will be used in message box. USHORT V[4]; //!< Version of this application. USHORT Hotfix; //!< Version of hotfix for this application (reserved for future use, should be 0). LPCWSTR PrivacyPolicyUrl; //!< URL to privacy policy. If NULL default privacy policy is used. }; //! \brief Contains crash handling behavior customization parameters. //! //! Default values for all parameters is 0/FALSE. struct HandlerSettings { DWORD HandlerSettingsSize; //!< Size of this structure. Should be set to sizeof(HandlerSettings). BOOL LeaveDumpFilesInTempFolder; //!< To leave error reports in temp folder you should set this member to TRUE. Your support or test lab teams can use that reports later. BOOL OpenProblemInBrowser; //!< To open Web-page belonging to the uploaded report after it was uploaded set this member to TRUE. It is useful for test lab to track the bug or write some comments. BOOL UseWER; //!< To continue use Microsoft Windows Error Reporting (WER) set this member to TRUE. In that case after Crash Server send report dialog Microsoft send report dialog also will be shown. This can be necessary in case of Windows Logo program. DWORD SubmitterID; //!< Crash Server user ID. Uploaded report will be marked as uploaded by this user. This is useful for Crash Server and bug tracking system integration. Set to \b 0 if user using this application is anonymous. }; //! \brief To enable crash processing you should create an instance of this class. //! //! It should be created as global static object and correctly initialized. //! Also you may instantiate it in your main() or WinMain() function as soon as possible. class CrashHandler { public: //! \example Sample.cpp //! This is an example of how to use the CrashHandler class. //! CrashHandler constructor. Loads crshhndl.dll and initializes crash handling. //! \note The crshhndl.dll may missing. In that case there will be no crash handling. CrashHandler( LPCSTR applicationGUID, //!< [in] GUID assigned to this application. LPCSTR prefix, //!< [in] Prefix that will be used with the dump name: YourPrefix_v1.v2.v3.v4_YYYYMMDD_HHMMSS.mini.dmp. LPCWSTR appName, //!< [in] Application name that will be used in message box. LPCWSTR company, //!< [in] Company name that will be used in message box. BOOL ownProcess = TRUE //!< [in] If you own the process your code running in set this option to \b TRUE. If don't (for example you write //!< a plugin to some external application) set this option to \b FALSE. In that case you need to explicitly //!< catch exceptions. See \ref SendReport for more information. ) throw() { if (!LoadDll()) return; ApplicationInfo appInfo; memset(&appInfo, 0, sizeof(appInfo)); appInfo.ApplicationInfoSize = sizeof(appInfo); appInfo.ApplicationGUID = applicationGUID; appInfo.Prefix = prefix; appInfo.AppName = appName; appInfo.Company = company; if (!m_GetVersionFromApp(&appInfo)) appInfo.V[0] = 1; HandlerSettings handlerSettings; memset(&handlerSettings, 0, sizeof(handlerSettings)); handlerSettings.HandlerSettingsSize = sizeof(handlerSettings); m_InitCrashHandler(&appInfo, &handlerSettings, ownProcess); } //! CrashHandler constructor. Loads crshhndl.dll and initializes crash handling. //! \note The crshhndl.dll may missing. In that case there will be no crash handling. CrashHandler( ApplicationInfo* applicationInfo, //!< [in] Pointer to the ApplicationInfo structure that identifies your application. HandlerSettings* handlerSettings, //!< [in] Pointer to the HandlerSettings structure that customizes crash handling behavior. This paramenter can be \b NULL. BOOL ownProcess = TRUE //!< [in] If you own the process your code running in set this option to \b TRUE. If don't (for example you write //!< a plugin to some external application) set this option to \b FALSE. In that case you need to explicitly //!< catch exceptions. See \ref SendReport for more information. ) throw() { if (!LoadDll()) return; m_InitCrashHandler(applicationInfo, handlerSettings, ownProcess); } //! CrashHandler constructor. Loads crshhndl.dll. You should call \ref InitCrashHandler to turn on crash handling. //! \note The crshhndl.dll may missing. In that case there will be no crash handling. CrashHandler() throw() { LoadDll(); } //! CrashHandler destructor. //! \note It doesn't unload crshhndl.dll and doesn't disable crash handling since crash may appear on very late phase of application exit. //! For example destructor of some static variable that is called after return from main() may crash. ~CrashHandler() { if (!m_IsReadyToExit) return; // If crash has happen not in main thread we should wait here until report will be sent // or else program will be terminated after return from main() and report send will be halted. while (!m_IsReadyToExit()) ::Sleep(100); } //! Initializes crash handler. //! \note You may call this function multiple times if some data has changed. //! \return Return \b true if crash handling was enabled. bool InitCrashHandler( ApplicationInfo* applicationInfo, //!< [in] Pointer to the ApplicationInfo structure that identifies your application. HandlerSettings* handlerSettings, //!< [in] Pointer to the HandlerSettings structure that customizes crash handling behavior. This paramenter can be \b NULL. BOOL ownProcess = TRUE //!< [in] If you own the process your code running in set this option to \b TRUE. If don't (for example you write //!< a plugin to some external application) set this option to \b FALSE. In that case you need to explicitly //!< catch exceptions. See \ref SendReport for more information. ) throw() { if (!m_InitCrashHandler) return false; return m_InitCrashHandler(applicationInfo, handlerSettings, ownProcess) != FALSE; } //! You may add any key/value pair to crash report. //! \return If the function succeeds, the return value is \b true. bool AddUserInfoToReport( LPCWSTR key, //!< [in] key string that will be added to the report. LPCWSTR value //!< [in] value for the key. ) throw() { if (!m_AddUserInfoToReport) return false; m_AddUserInfoToReport(key, value); return true; } //! You may add any file to crash report. This file will be read when crash appears and will be sent within the report. //! Multiple files may be added. Filename of the file in the report may be changed to any name. //! \return If the function succeeds, the return value is \b true. bool AddFileToReport( LPCWSTR path, //!< [in] Path to the file, that will be added to the report. LPCWSTR reportFileName /* = NULL */ //!< [in] Filename that will be used in report for this file. If parameter is \b NULL, original name from path will be used. ) throw() { if (!m_AddFileToReport) return false; m_AddFileToReport(path, reportFileName); return true; } //! Remove from report the file that was registered earlier to be sent within report. //! \return If the function succeeds, the return value is \b true. bool RemoveFileFromReport( LPCWSTR path //!< [in] Path to the file, that will be removed from the report. ) throw() { if (!m_RemoveFileFromReport) return false; m_RemoveFileFromReport(path); return true; } //! Fills version field (V) of ApplicationInfo with product version //! found in the executable file of the current process. //! \return If the function succeeds, the return value is \b true. bool GetVersionFromApp( ApplicationInfo* appInfo //!< [out] Pointer to ApplicationInfo structure. Its version field (V) will be set to product version. ) throw() { if (!m_GetVersionFromApp) return false; return m_GetVersionFromApp(appInfo) != FALSE; } //! Fill version field (V) of ApplicationInfo with product version found in the file specified. //! \return If the function succeeds, the return value is \b true. bool GetVersionFromFile( LPCWSTR path, //!< [in] Path to the file product version will be extracted from. ApplicationInfo* appInfo //!< [out] Pointer to ApplicationInfo structure. Its version field (V) will be set to product version. ) throw() { if (!m_GetVersionFromFile) return false; return m_GetVersionFromFile(path, appInfo) != FALSE; } //! If you do not own the process your code running in (for example you write a plugin to some //! external application) you need to properly initialize CrashHandler using \b ownProcess option. //! Also you need to explicitly catch all exceptions in all entry points to your code and in all //! threads you create. To do so use this construction: //! \code //! bool SomeEntryPoint(PARAM p) //! { //! __try //! { //! return YouCode(p); //! } //! __except (CrashHandler::SendReport(GetExceptionInformation())) //! { //! ::ExitProcess(0); // It is better to stop the process here or else corrupted data may incomprehensibly crash it later. //! return false; //! } //! } //! \endcode LONG SendReport( EXCEPTION_POINTERS* exceptionPointers //!< [in] Pointer to EXCEPTION_POINTERS structure. You should get it using GetExceptionInformation() //!< function inside __except keyword. ) { if (!m_SendReport) return EXCEPTION_CONTINUE_SEARCH; // There is no crash handler but asserts should continue anyway if (exceptionPointers->ExceptionRecord->ExceptionCode == ExceptionAssertionViolated) return EXCEPTION_CONTINUE_EXECUTION; return m_SendReport(exceptionPointers); } //! To send a report about violated assertion you can throw exception with this exception code //! using: \code RaiseException(CrashHandler::ExceptionAssertionViolated, 0, 0, NULL); \endcode //! Execution will continue after report will be sent (EXCEPTION_CONTINUE_EXECUTION would be used). //! \note If you called CrashHandler constructor and crshhdnl.dll was missing you still may using this exception. //! It will be catched, ignored and execution will continue. \ref SendReport function also works safely //! when crshhdnl.dll was missing. static const DWORD ExceptionAssertionViolated = ((DWORD)0xCCE17000); //! Sends assertion violation report from this point and continue execution. //! \sa ExceptionAssertionViolated //! \note Functions prefixed with "CrashServer_" will be ignored in stack parsing. void CrashServer_SendAssertionViolated() { if (!m_InitCrashHandler) return; ::RaiseException(CrashHandler::ExceptionAssertionViolated, 0, 0, NULL); } private: bool LoadDll() throw() { bool result = false; // hCrshhndlDll should not be unloaded, crash may appear even after return from main(). // So hCrshhndlDll is not saved after construction. #ifdef _WIN64 HMODULE hCrshhndlDll = ::LoadLibraryW(L"crshhndl-x64.dll"); #else HMODULE hCrshhndlDll = ::LoadLibraryW(L"crshhndl-x86.dll"); #endif if (hCrshhndlDll != NULL) { m_InitCrashHandler = (pfnInitCrashHandler) GetProcAddress(hCrshhndlDll, "InitCrashHandler"); m_SendReport = (pfnSendReport) GetProcAddress(hCrshhndlDll, "SendReport"); m_IsReadyToExit = (pfnIsReadyToExit) GetProcAddress(hCrshhndlDll, "IsReadyToExit"); m_AddUserInfoToReport = (pfnAddUserInfoToReport) GetProcAddress(hCrshhndlDll, "AddUserInfoToReport"); m_AddFileToReport = (pfnAddFileToReport) GetProcAddress(hCrshhndlDll, "AddFileToReport"); m_RemoveFileFromReport = (pfnRemoveFileFromReport) GetProcAddress(hCrshhndlDll, "RemoveFileFromReport"); m_GetVersionFromApp = (pfnGetVersionFromApp) GetProcAddress(hCrshhndlDll, "GetVersionFromApp"); m_GetVersionFromFile = (pfnGetVersionFromFile) GetProcAddress(hCrshhndlDll, "GetVersionFromFile"); result = m_InitCrashHandler && m_SendReport && m_IsReadyToExit && m_AddUserInfoToReport && m_AddFileToReport && m_RemoveFileFromReport && m_GetVersionFromApp && m_GetVersionFromFile; } #if _WIN32_WINNT >= 0x0501 /*_WIN32_WINNT_WINXP*/ // if no crash processing was started, we need to ignore ExceptionAssertionViolated exceptions. if (!result) ::AddVectoredExceptionHandler(TRUE, SkipAsserts); #endif return result; } static LONG CALLBACK SkipAsserts(EXCEPTION_POINTERS* pExceptionInfo) { if (pExceptionInfo->ExceptionRecord->ExceptionCode == ExceptionAssertionViolated) return EXCEPTION_CONTINUE_EXECUTION; return EXCEPTION_CONTINUE_SEARCH; } typedef BOOL (*pfnInitCrashHandler)(ApplicationInfo* applicationInfo, HandlerSettings* handlerSettings, BOOL ownProcess); typedef LONG(*pfnSendReport)(EXCEPTION_POINTERS* exceptionPointers); typedef BOOL (*pfnIsReadyToExit)(); typedef void (*pfnAddUserInfoToReport)(LPCWSTR key, LPCWSTR value); typedef void (*pfnAddFileToReport)(LPCWSTR path, LPCWSTR reportFileName /* = NULL */); typedef void (*pfnRemoveFileFromReport)(LPCWSTR path); typedef BOOL (*pfnGetVersionFromApp)(ApplicationInfo* appInfo); typedef BOOL (*pfnGetVersionFromFile)(LPCWSTR path, ApplicationInfo* appInfo); pfnInitCrashHandler m_InitCrashHandler; pfnSendReport m_SendReport; pfnIsReadyToExit m_IsReadyToExit; pfnAddUserInfoToReport m_AddUserInfoToReport; pfnAddFileToReport m_AddFileToReport; pfnRemoveFileFromReport m_RemoveFileFromReport; pfnGetVersionFromApp m_GetVersionFromApp; pfnGetVersionFromFile m_GetVersionFromFile; }; #endif // __CRASH_HANDLER_H__
[ "entry.reg@gmail.com" ]
entry.reg@gmail.com
61c05eec42492fe666a2c07e94c2f8d66609d535
d2bd315e9f5ad3c4bf5894c1bfe3c8357042ad7f
/게임자료구조/5주차과제/CircularQueue.cpp
59c205166f2374ede43b552c685679afeaf2e71a
[]
no_license
bluebluerabbit/School_3.1
6007939717aa67ad58eadff88cf9532dc6867cb8
a36f9b6d21eff95a226f58344c11884e3863ca23
refs/heads/main
2023-08-04T05:16:30.811280
2021-09-23T06:37:58
2021-09-23T06:37:58
null
0
0
null
null
null
null
UHC
C++
false
false
1,484
cpp
///* // File Name: SimpleQueue.h // Author: Geun-Hyung Kim // // Description: // 정수형 배열로 구성된 Queue 클래스 기능 구형 프로그램 // // Date: 2021. 3. 24 // Version: 0.1.0 //*/ // //#include <iostream> //#include "CircularQueue.h" // //bool CircularQueue::full() { // return ((rear + 1) % length) == front; //} // //bool CircularQueue::empty() { // return rear == front; //} // //void CircularQueue::enQueue(int data) { // if (!full()) { // rear = (rear + 1) % length; // dataArray[rear] = data; // size++; // } // else { // throw "CircularQueue is full!!"; // } //} // //int CircularQueue::deQueue() { // if (!empty()) { // size--; // return dataArray[front = (front + 1) % length]; // } // else { // throw "CircularQueue is empty!!"; // } //} // //int CircularQueue::Front() { // return front; //} // //int CircularQueue::Back() { // return rear; //} // //ostream& operator<<(ostream& os, const CircularQueue& q) { // // os << "======================" << endl // << "data : [ "; // // if (q.front > q.rear ) { // for (int i = q.front + 1; i < q.length; i++) { // os << q.dataArray[i] << ", "; // } // for (int i = 0; i <= q.rear; i++) { // os << q.dataArray[i]; // if (i != q.rear) os << ", "; // } // } // else { // for (int i = q.front + 1; i <= q.rear; i++) { // os << q.dataArray[i]; // if (i != q.rear) os << ", "; // } // } // // // os << " ]" << endl // << "======================" << "\n\n"; // // return os; //}
[ "jinjoo021@naver.com" ]
jinjoo021@naver.com
6e49bcbc3b9a2a47610cd564e4d4cdd5241fae11
e44efcd7ff9278592b374fb49b65561a26fc125f
/RLSimion/Lib/neural-network.h
5492baffbbdfafdb46a2b15f04f085447422f62a
[ "Zlib", "Apache-2.0", "LicenseRef-scancode-public-domain", "X11", "MIT" ]
permissive
utercero/SimionZoo
341da0950a0642679414a6e07ed7ba0d9ff85ba3
1fa570ae88f5d7e88e13a67ec27cda2de820ffee
refs/heads/master
2021-07-16T00:27:33.589997
2020-03-24T09:34:47
2020-03-24T09:34:47
251,345,276
0
0
NOASSERTION
2020-03-30T15:21:06
2020-03-30T15:21:06
null
UTF-8
C++
false
false
1,803
h
#pragma once #include <string> using namespace std; //In progress:: NOT USABLE YET /* class NeuralNetwork : public StateActionFunction { vector<string> m_inputStateVariables; vector<string> m_inputActionVariables; size_t m_inputSize = 0; protected: INetwork * m_pNetwork = nullptr; NeuralNetwork() = default; NeuralNetwork(INetwork* pNetwork, vector<string>& inputStateVariables, vector<string>& inputActionVariables, int outputSize); size_t m_outputSize = 0; vector<double> m_inputStateBuffer; vector<double> m_inputActionBuffer; vector<double> m_outputBuffer; public: virtual ~NeuralNetwork(); size_t getInputSize(); size_t getOutputSize(); unsigned int getNumOutputs(); vector<double>& evaluate(const State* s, const Action* a); const vector<string>& getInputStateVariables() { return m_inputStateVariables; } const vector<string>& getInputActionVariables() { return m_inputActionVariables; } }; class NNQFunctionDiscreteActions : public NeuralNetwork { vector<double> m_outputActionValues; NNQFunctionDiscreteActions() = default; public: NNQFunctionDiscreteActions(INetwork* pNetwork, vector<string> &inputStateVariables, string outputAction, size_t numSteps, double min, double max); double getActionIndexOutput(size_t actionIndex); size_t getClosestOutputIndex(double value); NNQFunctionDiscreteActions* clone(); }; class NNQFunction : public NeuralNetwork { NNQFunction() = default; public: NNQFunction(INetwork* pNetwork, vector<string> &inputStateVariables, vector<string> &inputActionVariables); NNQFunction* clone(); }; class NNStateFunction : public NeuralNetwork { NNStateFunction() = default; public: NNStateFunction(INetwork* pNetwork, vector<string> &inputStateVariables, vector<string>& outputActionVariables); NNStateFunction* clone(); }; */
[ "borja.fernandez@ehu.eus" ]
borja.fernandez@ehu.eus
2d085fe2729133dc5f98bae93e027461544ac8e6
2351872312e3b5e38e4f625715ee5dfee4392302
/$P@/SPA/SPA/PKBController.cpp
eeb863ec7e9778c022b1a23e02d046157c30fb29
[]
no_license
allanckw/32Ol_32oII_intelli-spa
737c4dae974cd08cf98ad414b4da847bdc19af62
e6929f146275ae2127a58584c65de7a1d83ce8a5
refs/heads/master
2020-05-07T13:18:03.290332
2013-04-25T14:20:07
2013-04-25T14:20:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
#pragma once #include "PKBController.h" /** * Method to initalize the PKB, builds the AST from a SIMPLE source file, builds the CFG and initialization for queries * @param filename the file name of the SIMPLE source file */ void PKBController::initializePKB(string filename) { //Parse Source Parser* p = new Parser(filename); p->buildAST(); //build AST delete p; DesignExtractor::extractDesign(); //Extract Design CFGBuilder::buildCFG(); //Build CFG RulesOfEngagement::initialise(); //Initialize ROE for Queries }
[ "kw_chong@nus.edu.sg" ]
kw_chong@nus.edu.sg
c88f519e80c3474455980866828cf3827462f5da
2a6c97e4bc7e329ae5fcea951c996d20c461fd74
/ExamplesAndPractice/BankApplicationExamplewithTests/BankApplicationExamplewithTests/BankApplicationExamplewithTests/main.cpp
451967b5a2f6ce384c340ac5f9425bf9088ae647
[]
no_license
EdgarVi/CptS-122
690d5760ffcd25fa37c7fbd13980d063d6f13d35
daddf23bfc473191df3d754ff3f74f283b0a052a
refs/heads/main
2023-01-23T18:47:50.792774
2020-12-10T23:56:57
2020-12-10T23:56:57
320,418,852
0
0
null
null
null
null
UTF-8
C++
false
false
2,841
cpp
/////////////////////////////////////////////////////////////////////////////// /// \file Main Program App (main.cpp) /// \author Andrew S. O'Fallon /// \date /// \brief This application performs basic banking operations. /// Limited error checking is provided. /// /// /// REVISION HISTORY: /// \date /// /////////////////////////////////////////////////////////////////////////////// //Problem Statement: //Note: This project is similar to the Account Class //problem provided in your Deitel and Deitel C How To //Program book. You are to write a //basic bank application, in C++, that allows the user //of the application to manually create, //modify, and delete bank accounts. Before you write the //application you will need to create a class called Account. //The class Account is used to represent customers' bank //accounts. Your class should include four data members to //represent the account balance (a double), account number //(an integer), customer name (a string), and date the //account was opened (a string). //Your class should provide two constructors: one default //constructor with no parameters and one constructor with //the initial balance, account //number, customer name, and date created as parameters. //The second constructor should check the initial balance. //If the balance is not >= 0, the balance should be set to 0 //and an error message should be displayed. // //The class should provide several member functions. Some //of which are described below. Remember that you will have //to think about other appropriate member functions (think //about setter and getter functions!). Member function credit //should //add an amount to the current balance and store it back into //the balance. Member function debit should withdraw money //from the Account, modify //the balance, and ensure the debit amount does not exceed //the Account's balance. If it does, the balance should be //left unmodified and the function //should print an appropriate message. Member function //printAccountInfo should print the current balance, account //number, customer name, and date of the account. // //Once you have designed your Account class. You will need to //create the main bank program. Note that you can create the //main bank program //in the main function or you can try to create another class //for the main bank program. The main program needs to display //a menu for adding, //deleting, modifying, and displaying accounts. You decide //appropriate menu features! Have fun with this assignment! #include "BankManager.h" #include "TestApp.h" int main(void) { runTestSuite(); // run the series of tests available BankManager bankApp; bankApp.runBankApplication(); // run the actual application for the bank system return 0; }
[ "edgar.villasenor@wsu.edu" ]
edgar.villasenor@wsu.edu
f2973761175052c541d80721c8d7f328383f331e
c3b9668c9595a58b7751761780f5fa92ef11fa9c
/D01/ex05/Human.hpp
2328eea4a2e36bb9c015019c2dab42c3a6d954f2
[]
no_license
dgalide/piscinecpp
4a91e614c73474dfb90d20265603224edc5bd3f0
484f395f0dd24c53815c0645d1e792c7816af667
refs/heads/master
2020-03-30T06:27:52.182053
2018-10-13T07:20:58
2018-10-13T07:20:58
150,863,269
0
0
null
null
null
null
UTF-8
C++
false
false
207
hpp
#ifndef HUMAN_HPP #define HUMAN_HPP #include "Brain.hpp" class Human { public: Human(void); ~Human(void); Brain getBrain(void); std::string identify(void); private: Brain _brain; }; #endif
[ "dgalide@student.42.fr" ]
dgalide@student.42.fr
405c462abae9d8bf8b83ea9ac71eb52d891c9f10
54b9ee00bcd582d56853ddb90be5cfeb0c29ba29
/src/utils/bdcom_cache_test.cc
0eaa0479d9ec5fd23bdbfab5e32d2cd46381c09b
[ "BSD-3-Clause" ]
permissive
pengdu/bubblefs
8f4deb8668831496bb0cd8b7d9895900b1442ff1
9b27e191a287b3a1d012adfd3bab6a30629a5f33
refs/heads/master
2020-04-04T19:32:11.311925
2018-05-02T11:20:18
2018-05-02T11:20:18
156,210,664
2
0
null
2018-11-05T11:57:22
2018-11-05T11:57:21
null
UTF-8
C++
false
false
5,931
cc
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // leveldb/util/cache_test.cc #include "utils/bdcom_cache.h" #include <vector> #include "platform/test.h" #include "utils/coding.h" namespace bubblefs { namespace mybdcom { // Conversions between numeric keys/values and the types expected by Cache. static std::string EncodeKey(int k) { std::string result; core::PutFixed32(&result, k); return result; } static int DecodeKey(const Slice& k) { assert(k.size() == 4); return core::DecodeFixed32(k.data()); } static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); } static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); } class CacheTest : public ::testing::Test { public: static CacheTest* current_; static void Deleter(const Slice& key, void* v) { current_->deleted_keys_.push_back(DecodeKey(key)); current_->deleted_values_.push_back(DecodeValue(v)); } static const int kCacheSize = 1000; std::vector<int> deleted_keys_; std::vector<int> deleted_values_; Cache* cache_; CacheTest() : cache_(NewLRUCache(kCacheSize)) { current_ = this; } ~CacheTest() { delete cache_; } int Lookup(int key) { Cache::Handle* handle = cache_->Lookup(EncodeKey(key)); const int r = (handle == NULL) ? -1 : DecodeValue(cache_->Value(handle)); if (handle != NULL) { cache_->Release(handle); } return r; } void Insert(int key, int value, int charge = 1) { cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter)); } Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) { return cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter); } void Erase(int key) { cache_->Erase(EncodeKey(key)); } }; CacheTest* CacheTest::current_; TEST_F(CacheTest, HitAndMiss) { ASSERT_EQ(-1, Lookup(100)); Insert(100, 101); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(200, 201); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(100, 102); ASSERT_EQ(102, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); } TEST_F(CacheTest, Erase) { Erase(200); ASSERT_EQ(0, deleted_keys_.size()); Insert(100, 101); Insert(200, 201); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); } TEST_F(CacheTest, EntriesArePinned) { Insert(100, 101); Cache::Handle* h1 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(101, DecodeValue(cache_->Value(h1))); Insert(100, 102); Cache::Handle* h2 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(102, DecodeValue(cache_->Value(h2))); ASSERT_EQ(0, deleted_keys_.size()); cache_->Release(h1); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(1, deleted_keys_.size()); cache_->Release(h2); ASSERT_EQ(2, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[1]); ASSERT_EQ(102, deleted_values_[1]); } TEST_F(CacheTest, EvictionPolicy) { Insert(100, 101); Insert(200, 201); Insert(300, 301); Cache::Handle* h = cache_->Lookup(EncodeKey(300)); // Frequently used entry must be kept around, // as must things that are still in use. for (int i = 0; i < kCacheSize + 100; i++) { Insert(1000+i, 2000+i); ASSERT_EQ(2000+i, Lookup(1000+i)); ASSERT_EQ(101, Lookup(100)); } ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(301, Lookup(300)); cache_->Release(h); } TEST_F(CacheTest, UseExceedsCacheSize) { // Overfill the cache, keeping handles on all inserted entries. std::vector<Cache::Handle*> h; for (int i = 0; i < kCacheSize + 100; i++) { h.push_back(InsertAndReturnHandle(1000+i, 2000+i)); } // Check that all the entries can be found in the cache. for (size_t i = 0; i < h.size(); i++) { ASSERT_EQ(2000+i, Lookup(1000+i)); } for (size_t i = 0; i < h.size(); i++) { cache_->Release(h[i]); } } TEST_F(CacheTest, HeavyEntries) { // Add a bunch of light and heavy entries and then count the combined // size of items still in the cache, which must be approximately the // same as the total capacity. const int kLight = 1; const int kHeavy = 10; int added = 0; int index = 0; while (added < 2*kCacheSize) { const int weight = (index & 1) ? kLight : kHeavy; Insert(index, 1000+index, weight); added += weight; index++; } int cached_weight = 0; for (int i = 0; i < index; i++) { const int weight = (i & 1 ? kLight : kHeavy); int r = Lookup(i); if (r >= 0) { cached_weight += weight; ASSERT_EQ(1000+i, r); } } ASSERT_LE(cached_weight, kCacheSize + kCacheSize/10); } TEST_F(CacheTest, NewId) { uint64_t a = cache_->NewId(); uint64_t b = cache_->NewId(); ASSERT_NE(a, b); } TEST_F(CacheTest, Prune) { Insert(1, 100); Insert(2, 200); Cache::Handle* handle = cache_->Lookup(EncodeKey(1)); ASSERT_TRUE(handle); cache_->Prune(); cache_->Release(handle); ASSERT_EQ(100, Lookup(1)); ASSERT_EQ(-1, Lookup(2)); } } // namespace bubblefs } // namespace mybdcom int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "691225916@qq.com" ]
691225916@qq.com
52acd41cc9ae1686b75c8b0a66724b29aa7b6a4b
dc402d0a2c1c0fc5ae015b2249a36e7ce886f1d0
/deps/memkind/test/alloc_performance_tests.cpp
f8db5d0f983633497c0898ed7bf2855456d9311b
[ "BSD-3-Clause", "GPL-3.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "LicenseRef-scancode-autoconf-simple-exception", "NTP", "MIT", "BSD-2-Clause", "FSFULLR" ]
permissive
michalbiesek/redis
6ec74c1cf0c8e041dc4db6cd79f46f33a091f337
d0d0867e730998f3589b7933e968840a8e1e8db4
refs/heads/4.0-volatile
2023-07-23T02:03:14.386206
2018-10-24T07:58:36
2018-10-24T07:58:36
136,281,355
0
1
BSD-3-Clause
2021-03-30T19:02:31
2018-06-06T06:17:28
C
UTF-8
C++
false
false
54,898
cpp
/* * Copyright (C) 2016 - 2017 Intel Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice(s), * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice(s), * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "common.h" #include "allocator_perf_tool/TaskFactory.hpp" #include "allocator_perf_tool/Stats.hpp" #include "allocator_perf_tool/Thread.hpp" #include "allocator_perf_tool/GTestAdapter.hpp" class AllocPerformanceTest: public :: testing::Test { private: AllocatorFactory allocator_factory; protected: void SetUp() { allocator_factory.initialize_allocator(AllocatorTypes::STANDARD_ALLOCATOR); } void TearDown() {} float run(unsigned kind, unsigned call, size_t threads_number, size_t alloc_size, unsigned mem_operations_num) { TaskFactory task_factory; std::vector<Thread*> threads; std::vector<Task*> tasks; TypesConf func_calls; TypesConf allocator_types; func_calls.enable_type(FunctionCalls::FREE); func_calls.enable_type(call); allocator_types.enable_type(kind); TaskConf conf = { mem_operations_num, //number of memory operations { mem_operations_num, //number of memory operations alloc_size, //min. size of single allocation alloc_size //max. size of single allocatioion }, func_calls, //enable function calls allocator_types, //enable allocators 11, //random seed false, //does not log memory operations and statistics to csv file }; for (int i=0; i<threads_number; i++) { Task* task = task_factory.create(TaskFactory::FUNCTION_CALLS_PERFORMANCE_TASK, conf); tasks.push_back(task); threads.push_back(new Thread(task)); conf.seed += 1; } ThreadsManager threads_manager(threads); threads_manager.start(); threads_manager.barrier(); TimeStats time_stats; for (int i=0; i<tasks.size(); i++) { time_stats += tasks[i]->get_results(); } return time_stats.stats[kind][call].total_time; } void run_test(unsigned kind, unsigned call, size_t threads_number, size_t alloc_size, unsigned mem_operations_num) { allocator_factory.initialize_allocator(kind); float ref_time = run(AllocatorTypes::STANDARD_ALLOCATOR, call, threads_number, alloc_size, mem_operations_num); float perf_time = run(kind, call, threads_number, alloc_size, mem_operations_num); float ref_delta_time_percent = allocator_factory.calc_ref_delta(ref_time, perf_time); GTestAdapter::RecordProperty("total_time_spend_on_alloc", perf_time); GTestAdapter::RecordProperty("alloc_operations_per_thread", mem_operations_num); GTestAdapter::RecordProperty("ref_delta_time_percent", ref_delta_time_percent); } }; TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_ext_MEMKIND_HBW_calloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 1572864, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_100_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 100, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_4096_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 4096, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_1000_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 1000, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_1001_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 1001, 10000); } TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 1572864, 10000); }
[ "krzysztof.filipek@intel.com" ]
krzysztof.filipek@intel.com
f1b1aba887bd9cb76922546fb171939381a2626e
2367a63e0e079a520ed998df0ba3de125b6b3460
/Translator_file/deal.II/matrix_free/matrix_free.h
7aa096fd8372640685b40473b3eb4a75964e9f40
[ "MIT" ]
permissive
jiaqiwang969/deal.ii-course-practice
e005804c506bc764b9e8a25a32b35d28b3fec203
0da5ad1537d8152549d8a0e4de5872efe7619c8a
refs/heads/master
2023-06-03T16:35:07.191106
2021-06-19T04:13:02
2021-06-19T04:13:02
369,974,242
0
0
MIT
2021-06-15T09:04:32
2021-05-23T06:05:42
C++
UTF-8
C++
false
false
191,413
h
//include/deal.II-translator/matrix_free/matrix_free_0.txt // --------------------------------------------------------------------- // // Copyright (C) 2011 - 2021 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.md at // the top level directory of deal.II. // // --------------------------------------------------------------------- #ifndef dealii_matrix_free_h #define dealii_matrix_free_h #include <deal.II/base/config.h> #include <deal.II/base/aligned_vector.h> #include <deal.II/base/exceptions.h> #include <deal.II/base/quadrature.h> #include <deal.II/base/template_constraints.h> #include <deal.II/base/thread_local_storage.h> #include <deal.II/base/vectorization.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/fe/fe.h> #include <deal.II/fe/mapping.h> #include <deal.II/fe/mapping_q1.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/hp/dof_handler.h> #include <deal.II/hp/mapping_collection.h> #include <deal.II/hp/q_collection.h> #include <deal.II/lac/affine_constraints.h> #include <deal.II/lac/block_vector_base.h> #include <deal.II/lac/la_parallel_vector.h> #include <deal.II/lac/vector_operation.h> #include <deal.II/matrix_free/dof_info.h> #include <deal.II/matrix_free/mapping_info.h> #include <deal.II/matrix_free/shape_info.h> #include <deal.II/matrix_free/task_info.h> #include <deal.II/matrix_free/type_traits.h> #include <cstdlib> #include <limits> #include <list> #include <memory> DEAL_II_NAMESPACE_OPEN /** * 这个类收集了所有为矩阵自由实现而存储的数据。这个存储方案是针对用相同数据进行的几个循环而定制的,也就是说,通常在同一个网格上做许多矩阵-向量乘积或残差计算。该类在 * step-37 和 step-48 中使用。 * 该类不实现任何涉及有限元基函数的操作,即关于对单元的操作。对于这些操作,FEEvaluation类被设计为使用该类中收集的数据。 * 存储的数据可以细分为三个主要部分。 * * * * - DoFInfo:它存储了局部自由度与全局自由度的关系。它包括对约束条件的描述,这些约束条件被评估为穿过一个单元上的所有局部自由度。 * * * * - MappingInfo:它存储了从实数到单位单元的转换,这些转换对于建立有限元函数的导数和找到物理空间中正交权重的位置是必要的。 * * * - ShapeInfo:它包含有限元的形状函数,在单元格上进行评估。 * 除了初始化程序,这个类只实现了一个单一的操作,即所有单元的循环(cell_loop())。这个循环的安排方式是,共享自由度的单元不会同时工作,这意味着可以并行地写入向量(或矩阵),而不必明确地同步访问这些向量和矩阵。这个类没有实现任何形状值,它所做的只是缓存相应的数据。要实现有限元操作,请使用FEEvaluation类(或一些相关的类)。 * 这个类以不同的顺序遍历单元,与deal.II中通常的Triangulation类不同,以便在共享内存和矢量化的并行化方面具有灵活性。 * 矢量化是通过将几个拓扑单元合并成一个所谓的宏观单元来实现的。这使得几个单元的所有相关操作都可以用一条CPU指令来实现,这也是这个框架的主要特点之一。 * 关于这个类的使用细节,见FEEvaluation的描述或 @ref matrixfree "无矩阵模块" * 。 * * * @ingroup matrixfree * */ template <int dim, typename Number = double, typename VectorizedArrayType = VectorizedArray<Number>> class MatrixFree : public Subscriptor { static_assert( std::is_same<Number, typename VectorizedArrayType::value_type>::value, "Type of Number and of VectorizedArrayType do not match."); public: /** * 由模板参数指定的底层数字类型的别名。 * */ using value_type = Number; using vectorized_value_type = VectorizedArrayType; /** * 由模板参数`dim`设定的尺寸。 * */ static const unsigned int dimension = dim; /** * 收集用于MatrixFree类初始化的选项。第一个参数指定要使用的MPI通信器,第二个参数是共享内存中的并行化选项(基于任务的并行化,可以选择无并行化和避免访问相同向量项的单元同时被访问的三种方案),第三个参数是任务并行调度的块大小,第四个参数是这个类应该存储的更新标志。 * 第五个参数指定了三角形中的级别,索引将从该级别开始使用。如果级别设置为 * numbers::invalid_unsigned_int, * ,将遍历活动单元,否则将遍历指定级别的单元。这个选项在给出DoFHandler的情况下没有影响。 * 参数 @p initialize_plain_indices * 表示DoFInfo类是否也应该允许访问向量而不解决约束。 * 两个参数`initialize_indices`和`initialize_mapping`允许用户停用一些初始化过程。例如,如果只需要找到避免同时触及相同向量/矩阵指数的调度,就不需要初始化映射。同样,如果映射从一个迭代到下一个迭代发生了变化,但拓扑结构没有变化(比如使用MappingQEulerian的变形网格时),只需要初始化映射就足够了。 * 两个参数`cell_vectorization_categories`和`cell_vectorization_categories_strict`控制在几个单元上形成向量化的批次。它在使用hp-adaptivity时被隐含使用,但在其他情况下也很有用,比如在本地时间步进中,人们想控制哪些元素一起形成一批单元。数组`cell_vectorization_categories`在`mg_level`设置为 * `numbers::invalid_unsigned_int` * 的情况下,通过cell->active_cell_index()访问活动单元,对于水平单元则通过cell->index()访问。默认情况下,`cell_vectorization_category`中的不同类别可以混合使用,如果算法内部需要,允许算法将较低的类别数字与下一个较高的类别合并,以尽可能避免部分填充的SIMD通道。这样可以更好地利用矢量,但可能需要特殊处理,特别是对面积分。如果设置为 * @p true, * ,算法反而会将不同的类别分开,而不是将它们混合在一个矢量化数组中。 * */ struct AdditionalData { /** * 收集任务并行的选项。参见成员变量 * MatrixFree::AdditionalData::tasks_parallel_scheme * 的文档以获得详尽的描述。 * */ enum TasksParallelScheme { /** * 以串行方式执行应用。 * */ none = internal::MatrixFreeFunctions::TaskInfo::none, /** * 将单元格分成两层,之后形成块状。 * */ partition_partition = internal::MatrixFreeFunctions::TaskInfo::partition_partition, /** * 在全局层面进行分区,并对分区内的单元格进行着色。 * */ partition_color = internal::MatrixFreeFunctions::TaskInfo::partition_color, /** * 使用传统的着色算法:这就像 * TasksParallelScheme::partition_color, ,但只使用一个分区。 * */ color = internal::MatrixFreeFunctions::TaskInfo::color }; /** * 附加数据的构造函数。 * */ AdditionalData( const TasksParallelScheme tasks_parallel_scheme = partition_partition, const unsigned int tasks_block_size = 0, const UpdateFlags mapping_update_flags = update_gradients | update_JxW_values, const UpdateFlags mapping_update_flags_boundary_faces = update_default, const UpdateFlags mapping_update_flags_inner_faces = update_default, const UpdateFlags mapping_update_flags_faces_by_cells = update_default, const unsigned int mg_level = numbers::invalid_unsigned_int, const bool store_plain_indices = true, const bool initialize_indices = true, const bool initialize_mapping = true, const bool overlap_communication_computation = true, const bool hold_all_faces_to_owned_cells = false, const bool cell_vectorization_categories_strict = false) : tasks_parallel_scheme(tasks_parallel_scheme) , tasks_block_size(tasks_block_size) , mapping_update_flags(mapping_update_flags) , mapping_update_flags_boundary_faces(mapping_update_flags_boundary_faces) , mapping_update_flags_inner_faces(mapping_update_flags_inner_faces) , mapping_update_flags_faces_by_cells(mapping_update_flags_faces_by_cells) , mg_level(mg_level) , store_plain_indices(store_plain_indices) , initialize_indices(initialize_indices) , initialize_mapping(initialize_mapping) , overlap_communication_computation(overlap_communication_computation) , hold_all_faces_to_owned_cells(hold_all_faces_to_owned_cells) , cell_vectorization_categories_strict( cell_vectorization_categories_strict) , communicator_sm(MPI_COMM_SELF) {} /** * 复制构造器。 * */ AdditionalData(const AdditionalData &other) : tasks_parallel_scheme(other.tasks_parallel_scheme) , tasks_block_size(other.tasks_block_size) , mapping_update_flags(other.mapping_update_flags) , mapping_update_flags_boundary_faces( other.mapping_update_flags_boundary_faces) , mapping_update_flags_inner_faces(other.mapping_update_flags_inner_faces) , mapping_update_flags_faces_by_cells( other.mapping_update_flags_faces_by_cells) , mg_level(other.mg_level) , store_plain_indices(other.store_plain_indices) , initialize_indices(other.initialize_indices) , initialize_mapping(other.initialize_mapping) , overlap_communication_computation( other.overlap_communication_computation) , hold_all_faces_to_owned_cells(other.hold_all_faces_to_owned_cells) , cell_vectorization_category(other.cell_vectorization_category) , cell_vectorization_categories_strict( other.cell_vectorization_categories_strict) , communicator_sm(other.communicator_sm) {} /** * 拷贝赋值。 * */ AdditionalData & operator=(const AdditionalData &other) { tasks_parallel_scheme = other.tasks_parallel_scheme; tasks_block_size = other.tasks_block_size; mapping_update_flags = other.mapping_update_flags; mapping_update_flags_boundary_faces = other.mapping_update_flags_boundary_faces; mapping_update_flags_inner_faces = other.mapping_update_flags_inner_faces; mapping_update_flags_faces_by_cells = other.mapping_update_flags_faces_by_cells; mg_level = other.mg_level; store_plain_indices = other.store_plain_indices; initialize_indices = other.initialize_indices; initialize_mapping = other.initialize_mapping; overlap_communication_computation = other.overlap_communication_computation; hold_all_faces_to_owned_cells = other.hold_all_faces_to_owned_cells; cell_vectorization_category = other.cell_vectorization_category; cell_vectorization_categories_strict = other.cell_vectorization_categories_strict; communicator_sm = other.communicator_sm; return *this; } /** * 设置任务并行的方案。有四个选项可用。 * 如果设置为 @p none, * ,运算器的应用是以串行方式进行的,没有共享内存并行。如果这个类和MPI一起使用,并且MPI也用于节点内的并行,那么这个标志应该设置为 * @p none. 默认值是 @p partition_partition, * ,即我们实际上用下面描述的第一个选项使用多线程。 * 第一个选项 @p partition_partition * 是在洋葱皮一样的分区中对单元格进行两级分割,并在分割后形成tasks_block_size的块。分区找到独立的单元组,使其能够在不同时访问相同的向量项的情况下并行工作。 * 第二种选择 @p partition_color * 是在全局层面上使用分区,并在分区内为单元格着色(在一个颜色内的所有块是独立的)。在这里,将单元格细分为若干块是在分区之前完成的,如果自由度没有被重新编号,可能会得到更差的分区,但缓存性能更好。 * 第三种方案 @p color * 是在全局层面使用传统的着色算法。这种方案是第二种方案的一个特例,即只存在一个分区。请注意,对于有悬空节点的问题,有相当多的颜色(3D中为50种或更多),这可能会降低并行性能(不良的缓存行为,许多同步点)。 * @note * 对于进行内面积分的情况,线程支持目前是实验性的,如果可能的话,建议使用MPI并行。虽然该方案已经验证了在通常的DG元素的情况下可以使用`partition_partition`选项,但对于更一般的元素系统,如连续和不连续元素的组合,对所有项添加面积分的情况,没有进行全面的测试。 * */ TasksParallelScheme tasks_parallel_scheme; /** * 设置应该形成一个分区的所谓宏单元的数量。如果给定的尺寸为零,该类会尝试根据 * MultithreadInfo::n_threads() * 和存在的单元数为块找到一个好的尺寸。否则,将使用给定的数字。如果给定的数字大于总单元格数的三分之一,这意味着没有并行性。请注意,在使用矢量化的情况下,一个宏单元由一个以上的物理单元组成。 * */ unsigned int tasks_block_size; /** * 这个标志决定了单元格上的映射数据被缓存起来。该类可以缓存梯度计算(反雅各布)、雅各布行列式(JxW)、正交点以及Hessians(雅各布导数)的数据。默认情况下,只有梯度和雅各布行列式乘以正交权重JxW的数据被缓存。如果需要正交点或二次导数,它们必须由这个字段指定(即使这里没有设置这个选项,二次导数仍然可以在笛卡尔单元上评估,因为那里的雅各布系数完全描述了映射)。 * */ UpdateFlags mapping_update_flags; /** * 这个标志决定了边界面上的映射数据要被缓存。注意MatrixFree对面的积分使用单独的循环布局,以便在悬空节点(需要在两边有不同的子面设置)或者在一个VectorizedArray的批次中的一些单元与边界相邻而其他单元不相邻的情况下也能有效地进行矢量。 * 如果设置为不同于update_general的值(默认),面的信息将被显式建立。目前,MatrixFree支持缓存以下面的数据:逆雅各布,雅各布行列式(JxW),正交点,Hessians数据(雅各布的导数),以及法向量。 * @note 为了能够在 MatrixFree::loop()`, 中执行 "face_operation * "或 "boundary_operation",这个字段或 @p * mapping_update_flags_inner_faces 必须被设置为与 * UpdateFlags::update_default. 不同的值。 * */ UpdateFlags mapping_update_flags_boundary_faces; /** * 这个标志决定了要缓存的内部面的映射数据。请注意,MatrixFree对面的积分使用单独的循环布局,以便在悬空节点(需要在两边有不同的子面设置)或者在一个VectorizedArray的批中的一些单元与边界相邻而其他单元不相邻的情况下也能有效地进行矢量化。 * 如果设置为不同于update_general的值(默认),面的信息将被显式建立。目前,MatrixFree支持缓存以下面的数据:逆雅各布,雅各布行列式(JxW),正交点,Hessians数据(雅各布的导数),以及法向量。 * @note 为了能够在 MatrixFree::loop()`, 中执行 "face_operation * "或 "boundary_operation",这个字段或 @p * mapping_update_flags_boundary_faces 必须被设置为与 * UpdateFlags::update_default. 不同的值。 * */ UpdateFlags mapping_update_flags_inner_faces; /** * 这个标志决定了不同布局的面的映射数据与矢量化的关系。当`mapping_update_flags_inner_faces`和`mapping_update_flags_boundary_faces`触发以面为中心的方式建立数据并进行适当的矢量化时,当前的数据域将面的信息附加到单元格及其矢量化的方式。这只在特殊情况下需要,例如在块状Jacobi方法中,单元格的全部算子包括其面都被评估。该数据由 * <code>FEFaceEvaluation::reinit(cell_batch_index, * face_number)</code>访问。然而,目前用这种方法不能计算到邻居的耦合项,因为邻居不是由VectorizedArray数据布局的数组-结构-数组类型的数据结构来布置的。 * 注意,你应该只在真正需要的情况下计算这个数据域,因为它使面的映射数据所需的内存增加了一倍以上。 * 如果设置为不同于update_general的值(默认值),就会显式地建立面的信息。目前,MatrixFree支持缓存以下面的数据:反Jacobian,Jacobian行列式(JxW),正交点,Hessians(Jacobian的导数)数据,以及法向量。 * */ UpdateFlags mapping_update_flags_faces_by_cells; /** * 这个选项可以用来定义我们是否在网格的某一层工作,而不是活动单元。如果设置为invalid_unsigned_int * (这是默认值),就会对活动单元进行处理,否则就按这个参数给定的级别处理。请注意,如果你指定在一个层次上工作,其道夫必须通过使用 * <code>dof_handler.distribute_mg_dofs(fe);</code> 来分配。 * */ unsigned int mg_level; /** * 控制是否启用从向量读取而不解决约束,即只读取向量的局部值。默认情况下,这个选项是启用的。如果你想使用 * FEEvaluationBase::read_dof_values_plain, * ,这个标志需要被设置。 * */ bool store_plain_indices; /** * 选项用于控制是否应该读取存储在DoFHandler中的索引,以及是否应该在MatrixFree的初始化方法中设置任务并行的模式。默认值是true。如果映射需要重新计算(例如,当使用通过MappingEulerian描述的变形网格时),但单元格的拓扑结构保持不变,可以禁用。 * */ bool initialize_indices; /** * 控制是否应该在MatrixFree的初始化方法中计算映射信息的选项。默认值为true。当只需要设置一些索引时可以禁用(例如,当只需要计算一组独立的单元格时)。 * */ bool initialize_mapping; /** * 如果传递给循环的向量支持非阻塞数据交换,可以选择控制循环是否应该尽可能地重叠通信和计算。在大多数情况下,如果要发送的数据量超过几千字节,重叠会更快。如果发送的数据较少,在大多数集群上,通信是有延迟的(按照2016年的标准,在好的集群上,点到点的延迟大约是1微秒)。根据MPI实现和结构的不同,不重叠并等待数据的到来可能会更快。默认情况下是true,即通信和计算是重叠的。 * */ bool overlap_communication_computation; /** * 默认情况下,面的部分将只保存那些要被本地处理的面(和面后面的鬼元素)。如果MatrixFree需要访问本地拥有的单元上的所有邻域,这个选项可以在面域的末端添加相应的面。 * */ bool hold_all_faces_to_owned_cells; /** * 这个数据结构允许在建立矢量化信息时将一部分单元分配给不同的类别。在使用hp-adaptivity时,它被隐含地使用,但在其他情况下也是有用的,比如在本地时间步进中,人们想控制哪些元素共同构成一批单元。 * 在 @p mg_level 设置为 numbers::invalid_unsigned_int * 的活动单元上工作时,通过cell->active_cell_index()给出的数字访问这个数组,对于水平单元则通过cell->index()访问。 * @note * 这个字段在构建AdditionalData时是空的。用户有责任在填充数据时将此字段调整为`triangulation.n_active_cells()`或`triangulation.n_cells(level)`。 * */ std::vector<unsigned int> cell_vectorization_category; /** * 默认情况下, @p cell_vectorization_category * 中的不同类别可以混合,如果在算法内部有必要,允许算法将较低的类别与次高的类别合并。这样可以更好地利用矢量,但可能需要特殊处理,特别是对于面积分。如果设置为 * @p true, * ,算法会将不同的类别分开,而不是将它们混合在一个矢量化的数组中。 * */ bool cell_vectorization_categories_strict; /** * 共享内存的MPI通信器。默认值。MPI_COMM_SELF。 * */ MPI_Comm communicator_sm; }; /** * @name 1:构造和初始化 * */ //@{ /** * 默认的空构造函数。什么都不做。 * */ MatrixFree(); /** * 复制构造函数,调用copy_from * */ MatrixFree(const MatrixFree<dim, Number, VectorizedArrayType> &other); /** * 解构器。 * */ ~MatrixFree() override = default; /** * 提取在单元格上进行循环所需的信息。DoFHandler和AffineConstraints对象描述了自由度的布局,DoFHandler和映射描述了从单元到实数单元的转换,而DoFHandler底层的有限元与正交公式一起描述了局部操作。请注意,DoFHandler底层的有限元必须是标量的,或者包含同一元素的几个副本。不允许将几个不同的元素混入一个FES系统。在这种情况下,使用带有几个DoFHandler参数的初始化函数。 * */ template <typename QuadratureType, typename number2, typename MappingType> void reinit(const MappingType & mapping, const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraint, const QuadratureType & quad, const AdditionalData & additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用 $Q_1$ 的映射。 * @deprecated 使用重载来代替Mapping对象。 * */ template <typename QuadratureType, typename number2> DEAL_II_DEPRECATED void reinit(const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraint, const QuadratureType & quad, const AdditionalData & additional_data = AdditionalData()); /** * 提取在单元格上进行循环所需的信息。DoFHandler和AffineConstraints对象描述了自由度的布局,DoFHandler和映射描述了从单元到实数单元的转换,DoFHandler的基础有限元与正交公式一起描述了局部操作。与其他初始化函数处理的标量情况不同,这个函数允许有两个或多个不同的有限元的问题。每个元素的DoFHandlers必须作为指针传递给初始化函数。另外,一个由多个构件组成的系统也可以由一个带有FESystem元素的单一DoFHandler来表示。这种情况的前提条件是FESystem的每个基本元素必须与本类兼容,如FE_Q或FE_DGQ类。 * 这个函数也允许使用多个正交公式,例如当描述中包含不同程度的元素的独立积分时。然而,不同正交公式的数量可以独立于DoFHandlers的数量进行设置,当几个元素总是用同一个正交公式进行积分时。 * */ template <typename QuadratureType, typename number2, typename MappingType> void reinit(const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。与上述相同,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> DEAL_II_DEPRECATED void reinit(const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用 $Q_1$ 的映射。 * @deprecated 使用获取Mapping对象的重载来代替。 * */ template <typename QuadratureType, typename number2> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和以前一样,但现在本地拥有的自由度范围的索引集描述取自DoFHandler。此外,只使用一个正交公式,当一个矢量值问题中的几个分量基于同一个正交公式被整合在一起时,这可能是必要的。 * */ template <typename QuadratureType, typename number2, typename MappingType> void reinit(const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。与上述相同,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> DEAL_II_DEPRECATED void reinit(const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用 $Q_1$ 的映射。 * @deprecated 使用获取映射对象的重载来代替。 * */ template <typename QuadratureType, typename number2> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 复制函数。创建一个所有数据结构的深度拷贝。通常情况下,为不同的操作保留一次数据就足够了,所以不应该经常需要这个函数。 * */ void copy_from( const MatrixFree<dim, Number, VectorizedArrayType> &matrix_free_base); /** * 当底层几何体发生变化(例如,通过像MappingFEField这样可以通过空间配置的变化而变形的映射)而网格和未知数的拓扑结构保持不变时,重新刷新存储在MappingInfo字段中的几何体数据。与reinit()相比,这个操作只需要重新生成几何体阵列,因此可以大大降低成本(取决于评估几何体的成本)。 * */ void update_mapping(const Mapping<dim> &mapping); /** * 与上述相同,但有 hp::MappingCollection. 。 * */ void update_mapping(const std::shared_ptr<hp::MappingCollection<dim>> &mapping); /** * 清除所有的数据字段,使类进入类似于调用了默认构造函数后的状态。 * */ void clear(); //@} /** * 这个类定义了循环()中的面积分的数据访问类型,它被传递给并行向量的`update_ghost_values`和`compress`函数,目的是能够减少必须交换的数据量。数据交换是一个真正的瓶颈,特别是对于高等级的DG方法,因此更严格的交换方式显然是有益的。请注意,这种选择只适用于分配给访问 * `FaceToCellTopology::exterior_cells` * 的单元格外部的FEFaceEvaluation对象;所有<i>interior</i>对象在任何情况下都是可用的。 * */ enum class DataAccessOnFaces { /** * 循环不涉及任何FEFaceEvaluation对邻居的访问,就像只有边界积分(但没有内部面积分)或在类似 * MatrixFree::cell_loop() 的设置中做质量矩阵时的情况。 * */ none, /** * 循环只涉及到FEFaceEvaluation通过函数值访问邻居,如 * FEFaceEvaluation::gather_evaluate() 的参数 EvaluationFlags::values, * ,但没有访问形状函数导数(通常需要访问更多数据)。对于只有部分形状函数在面上有支持的FiniteElement类型,如FE_DGQ元素,其节点在元素表面的拉格朗日多项式,数据交换从`(k+1)^dim`减少到`(k+1)^(dim-1)`。 * */ values, /** * 与上述相同。如果FEFaceEvaluation通过提供单元批号和一个面的编号而被重新初始化,则必须从外部面访问数据时使用。这种配置在以单元为中心的循环中很有用。 * @pre AdditionalData::hold_all_faces_to_owned_cells 必须启用。 * */ values_all_faces, /** * 循环确实涉及到FEFaceEvaluation通过函数值和梯度访问到邻居,但没有二阶导数,比如 * FEFaceEvaluation::gather_evaluate() 设置了 EvaluationFlags::values * 和 EvaluationFlags::gradients * 。对于只有部分形状函数在一个面上有非零值和一阶导数的FiniteElement类型,例如FE_DGQHermite元素,数据交换会减少,例如从`(k+1)^dim`到`2(k+1)^(dim-1)`。请注意,对于不具备这种特殊属性的基数,无论如何都要发送完整的邻接数据。 * */ gradients, /** * 与上述相同。如果FEFaceEvaluation通过提供单元格批号和一个面的编号而被重新初始化的话,要用于必须从外部面访问数据。这种配置在以单元为中心的循环中很有用。 * @pre AdditionalData::hold_all_faces_to_owned_cells 必须启用。 * */ gradients_all_faces, /** * 用户不想做限制的一般设置。这通常比其他选项更昂贵,但也是最保守的一种,因为要在本地计算的面后面的元素的全部数据将被交换。 * */ unspecified }; /** * @name 2:无矩阵循环 * */ //@{ /** * 这种方法在所有单元格上运行循环(并行),并在源向量和目的向量上执行MPI数据交换。 * @param cell_operation `std::function` ,签名为<tt>cell_operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int> * &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元的范围(通常应该处理多个单元以减少开销)。 * 如果一个对象有一个具有正确参数集的`operator()`,人们可以在这个地方传递一个指针,因为这样的指针可以被转换为函数对象。 * @param dst 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() * 。对于其他向量,包括平行的Trilinos或PETSc向量,不发出这样的调用。请注意,Trilinos/Epetra或PETSc向量目前不能并行工作,因为本类使用MPI本地索引寻址,而不是这些外部库所暗示的全局寻址。 * @param src 输入向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,则循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环内被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为零,确保向量项尽可能地留在缓存中。 * */ template <typename OutVector, typename InVector> void cell_loop(const std::function<void( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector = false) const; /** * 这是第二个变种,在所有单元格上运行循环,现在提供一个指向`CLASS`类成员函数的函数指针。这种方法避免了定义lambda函数或调用 * std::bind * 将类绑定到给定的函数中,以防本地函数需要访问类中的数据(即,它是一个非静态成员函数)。 * @param cell_operation * 指向`CLASS`的成员函数,其签名为<tt>cell_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,其中第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常应该处理一个以上的单元以减少开销)。 * @param owning_class * 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(..)`。 * @param dst 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() * 。对于其他向量,包括平行的Trilinos或PETSc向量,不发出这样的调用。请注意,Trilinos/Epetra或PETSc向量目前不能并行工作,因为本类使用MPI本地索引寻址,而不是那些外部库所暗示的全局寻址。 * @param src 输入向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ),循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为零,确保向量项尽可能地留在缓存中。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector = false) const; /** * 与上述相同,但对于非const的类成员函数。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector = false) const; /** * 这个函数类似于cell_loop,用一个 std::function * 对象来指定要对单元格进行的操作,但增加了两个额外的向量,在计算单元格积分前后执行一些额外的工作。 * 这两个额外的向量在自由度范围内工作,以MPI本地索引中选定的DoFHandler`dof_handler_index_pre_post`的自由度编号表示。向量的参数代表自由度范围,粒度为 * internal::MatrixFreeFunctions::DoFInfo::chunk_size_zero_vector * 个条目(除了最后一个块被设置为本地拥有的条目数),形式为`[first, * last)`。这些向量的想法是使向量上的操作更接近于它们在无矩阵循环中的访问点,目的是通过时间上的定位来增加缓存的点击。这个循环保证了`operation_before_loop`在cell_operation(包括MPI数据交换)中第一次接触到所有相关的未知数之前,就已经击中了这些未知数,允许执行一些`src`向量依赖的向量更新。循环后的操作 * "是类似的 * * * * * - 一旦该范围内的所有自由度被`cell_operation`最后一次触及(包括MPI数据交换),它就开始在该范围的自由度上执行,允许例如计算一些取决于当前`dst`中的单元循环结果的向量操作,或者想修改`src`。缓存的效率取决于自由度的编号,因为范围的粒度不同。 @param cell_operation 指向`CLASS`的成员函数,签名为<tt>cell_operation (const MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned int,unsigned int> &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常应该处理多个单元,以减少开销)。 @param owning_class 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(..)`。 @param dst 保存结果的目标向量。如果向量是 LinearAlgebra::distributed::Vector 类型(或其复合对象,如 LinearAlgebra::distributed::BlockVector), ,循环在内部调用结束时调用 LinearAlgebra::distributed::Vector::compress() 。对于其他向量,包括平行的Trilinos或PETSc向量,不发出这样的调用。请注意,Trilinos/Epetra或PETSc向量目前不能并行工作,因为本类使用MPI本地索引寻址,而不是这些外部库所暗示的全局寻址。 @param src 输入向量。如果向量是 LinearAlgebra::distributed::Vector 类型(或其复合对象,如 LinearAlgebra::distributed::BlockVector), ),循环在内部调用开始时调用 LinearAlgebra::distributed::Vector::update_ghost_values() ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量被重置为其原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 @param operation_before_loop 这个函数可以用来对`src'和`dst'向量(或其他向量)的条目进行操作,在对单元的操作第一次接触到特定的DoF之前,根据上面文本中的一般描述。这个函数被传递给选定的`dof_handler_index_pre_post`(用MPI本地编号)上的本地拥有的自由度范围。 @param operation_after_loop 这个函数可以用来对`src'和`dst'向量(或其他向量)的条目进行操作,在对单元的操作最后触及一个特定的DoF之后,根据上面文字的一般描述。这个函数被传递给选定的`dof_handler_index_pre_post`(以MPI本地编号)上的本地拥有的自由度范围。 @param dof_handler_index_pre_post 由于MatrixFree可以用DoFHandler对象的矢量初始化,一般来说,每个对象都会有矢量大小,因此返回给`operation_before_loop`和`operation_after_loop`的范围也不同。使用这个变量来指定索引范围应该与哪一个DoFHandler对象相关。默认为`dof_handler_index` 0。 * @note * `operation_before_loop`和`operation_after_loop`的近距离定位目前只在仅MPI的情况下实现。在启用线程的情况下,由于复杂的依赖关系,完整的`operation_before_loop`被安排在并行循环之前,而`operation_after_loop`被严格安排在之后。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post = 0) const; /** * 与上述相同,但对于非const的类成员函数。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post = 0) const; /** * 同上,但取一个 `std::function` * 作为`cell_operation`,而不是类成员函数。 * */ template <typename OutVector, typename InVector> void cell_loop(const std::function<void( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, OutVector & dst, const InVector & src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post = 0) const; /** * 这个方法在所有单元格上运行一个循环(并行),并在源向量和目的向量上执行MPI数据交换。与其他只在单元格上运行一个函数的变体不同,这个方法还分别以内部面和边界面的函数为参数。 * @param cell_operation `std::function` 的签名为<tt>cell_operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int> * &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元的范围(通常应该处理一个以上的单元以减少开销)。如果有一个 * <code>operator()</code> * 具有正确的参数集,人们可以在这个地方传递一个对象的指针,因为这样的指针可以被转换为函数对象。 * @param face_operation `std::function` 的签名是<tt>face_operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int> * &)</tt>,类似于`cell_operation`,但现在是与内部面的工作有关的部分。请注意,MatrixFree框架将周期性面视为内部面,因此,在调用face_operation时应用周期性约束后,它们将被分配到正确的邻居。 * @param boundary_operation `std::function` * 签名为<tt>boundary_operation (const MatrixFree<dim,Number> &, * OutVector &, InVector &, std::pair<unsigned int,unsigned int> * &)</tt>,与`cell_operation`和`face_operation`类似,但现在是与边界面的工作相关的部分。边界面是由它们的`boundary_id'分开的,可以用 * MatrixFree::get_boundary_id(). * 来查询这个id。注意,内部和面都使用相同的编号,内部的面被分配的编号比边界面低。 * @param dst 保存结果的目的向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() 。 @param src * 输入向量。如果向量是 LinearAlgebra::distributed::Vector * 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,则循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * 以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为其原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为0,确保向量项尽可能地留在缓存中。 * @param dst_vector_face_access * 设置对向量`dst`的访问类型,该访问将发生在 @p * face_operation * 函数内部。正如在DataAccessOnFaces结构的描述中所解释的,这个选择的目的是减少必须通过MPI网络(如果在节点的共享内存区域内,则通过`memcpy`)交换的数据量以获得性能。请注意,没有办法与FEFaceEvaluation类沟通这一设置,因此除了在`face_operation`函数中实现的内容外,这一选择必须在这个地方进行。因此,也没有办法检查传递给这个调用的设置是否与后来`FEFaceEvaluation`所做的一致,确保数据的正确性是用户的责任。 * @param src_vector_face_access * 设置对向量`src`的访问类型,将在 @p face_operation * 函数体内发生,与`dst_vector_face_access`相类似。 * */ template <typename OutVector, typename InVector> void loop(const std::function< void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, const std::function< void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &face_operation, const std::function<void( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &boundary_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces dst_vector_face_access = DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 这是第二个变体,在所有的单元格、内部面和边界面上运行循环,现在提供了三个指向 * @p CLASS 类成员函数的函数指针,其签名为<code>operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int>&) * const</code>。如果本地函数需要访问类中的数据(即,它是一个非静态成员函数),该方法就不需要定义lambda函数或调用 * std::bind 将类绑定到给定函数中。 @param cell_operation * 指向`CLASS`的成员函数,其签名为<tt>cell_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,其中第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常应该处理一个以上的单元以减少开销)。注意,这个循环通常会将`cell_range'分割成更小的部分,并交替工作于`cell_operation'、`face_operation'和`boundary_operation',以增加缓存中向量项的潜在重用。 * @param face_operation * 指向`CLASS`的成员函数,其签名为<tt>face_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,与`cell_operation`相类似,但现在是与内部面的工作相关的部分。请注意,MatrixFree框架将周期性面视为内部面,因此,在调用face_operation时应用周期性约束后,它们将被分配给正确的邻居。 * @param boundary_operation * 指向`CLASS`的成员函数,其签名为<tt>boundary_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,与`cell_operation`和`face_operation`类似,但现在是与边界面的工作相关的部分。边界面由它们的`boundary_id'分开,可以使用 * MatrixFree::get_boundary_id(). * 查询该id。注意,内部和面都使用相同的编号,内部的面被分配的编号比边界面低。 * @param owning_class * 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(...)`, * `owning_class->face_operation(...)`, * 和`owning_class->boundary_operation(...)`。 @param dst * 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() 。 @param src * 输入向量。如果向量是 LinearAlgebra::distributed::Vector * 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,则循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * 以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为其原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为0,确保向量项尽可能地留在缓存中。 * @param dst_vector_face_access * 设置对向量`dst`的访问类型,将在 @p face_operation * 函数内部发生。正如在DataAccessOnFaces结构的描述中所解释的,这个选择的目的是减少必须通过MPI网络(如果在节点的共享内存区域内,则通过`memcpy`)交换的数据量以获得性能。请注意,没有办法与FEFaceEvaluation类沟通这一设置,因此除了在`face_operation`函数中实现的内容外,这一选择必须在这个地方进行。因此,也没有办法检查传递给这个调用的设置是否与后来`FEFaceEvaluation`所做的一致,确保数据的正确性是用户的责任。 * @param src_vector_face_access * 设置对向量`src`的访问类型,将在 @p face_operation * 函数体内发生,与`dst_vector_face_access`相类似。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop( void (CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*face_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*boundary_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces dst_vector_face_access = DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 和上面一样,但对于非const的类成员函数。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*face_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*boundary_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces dst_vector_face_access = DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 这个方法与cell_loop()的做法类似,在所有单元格上运行循环(并行)。然而,这个函数的目的是用于面和边界积分也应该被评估的情况。与loop()相反,用户只需提供一个单一的函数,该函数应包含一个单元(或向量化时的一批单元)的单元积分和所有面的面和边界积分。这在文献中被称为 * "以元素为中心的循环 "或 "以单元为中心的循环"。 * 为了能够评估所有的面积分(用来自相邻单元的值或梯度),相邻单元的所有幽灵值都要更新。使用 * FEFaceEvalution::reinit(cell, * face_no)来访问一个单元的任意面和各自的邻居的数量。 * @param cell_operation * 指向`CLASS`的成员函数,其签名为<tt>cell_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常从循环中传递多个单元以减少开销)。 * @param owning_class * 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(..)`。 * @param dst 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() 。 @param src * 输入向量。如果向量是 LinearAlgebra::distributed::Vector * 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为0,确保向量项尽可能地留在缓存中。 * @param src_vector_face_access * 设置对向量`src`的访问类型,这将在面积分过程中发生在 * @p cell_operation 函数的内部。 * 正如在DataAccessOnFaces结构的描述中所解释的,这个选择的目的是减少必须通过MPI网络(如果在节点的共享内存区域内,则通过`memcpy`)交换的数据量以获得性能。请注意,没有办法与FEFaceEvaluation类沟通这一设置,因此除了在`face_operation`函数中实现的内容外,这一选择必须在这个地方进行。因此,也没有办法检查传递给这个调用的设置是否与后来`FEFaceEvaluation`所做的一致,确保数据的正确性是用户的责任。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop_cell_centric(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 同上,但对于类的成员函数,它是非const的。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop_cell_centric(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 与上述相同,但有 std::function. 。 * */ template <typename OutVector, typename InVector> void loop_cell_centric( const std::function<void(const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 在hp-adaptive情况下,在单元格循环中计算的单元格子范围可能包含不同程度的元素。使用这个函数来计算一个单独的有限元度的子范围是什么。有限元度与函数调用中给出的矢量分量相关。 * */ std::pair<unsigned int, unsigned int> create_cell_subrange_hp(const std::pair<unsigned int, unsigned int> &range, const unsigned int fe_degree, const unsigned int dof_handler_index = 0) const; /** * 在hp-adaptive情况下,在单元循环中计算的单元子范围可能包含不同程度的元素。使用这个函数来计算给定索引的子范围的hp-finite元素,而不是其他函数中的有限元素程度。 * */ std::pair<unsigned int, unsigned int> create_cell_subrange_hp_by_index( const std::pair<unsigned int, unsigned int> &range, const unsigned int fe_index, const unsigned int dof_handler_index = 0) const; /** * 在hp自适应情况下,返回active_fe_indices的数量。 * */ unsigned int n_active_fe_indices() const; /** * 在hp-adaptive情况下,返回单元格范围的active_fe_index。 * */ unsigned int get_cell_active_fe_index( const std::pair<unsigned int, unsigned int> range) const; /** * 在hp-adaptive的情况下,返回一个面域的active_fe_index。 * */ unsigned int get_face_active_fe_index(const std::pair<unsigned int, unsigned int> range, const bool is_interior_face = true) const; //@} /** * @name 3: 向量的初始化 * */ //@{ /** * */ template <typename VectorType> void initialize_dof_vector(VectorType & vec, const unsigned int dof_handler_index = 0) const; /** * */ template <typename Number2> void initialize_dof_vector(LinearAlgebra::distributed::Vector<Number2> &vec, const unsigned int dof_handler_index = 0) const; /** * 返回代表本地拥有的数据的分区器,以及单元格循环需要访问的幽灵索引。分区器是由各自字段给出的本地拥有的道夫和幽灵道夫构建的。如果你想知道这些对象的具体信息,你可以用各自的访问函数来查询它们。如果你只是想初始化一个(平行)向量,你通常应该更喜欢这种数据结构,因为数据交换信息可以从一个向量重复使用到另一个向量。 * */ const std::shared_ptr<const Utilities::MPI::Partitioner> & get_vector_partitioner(const unsigned int dof_handler_index = 0) const; /** * 返回由处理器拥有的单元格集合。 * */ const IndexSet & get_locally_owned_set(const unsigned int dof_handler_index = 0) const; /** * 返回需要但不为处理器所拥有的幽灵单元的集合。 * */ const IndexSet & get_ghost_set(const unsigned int dof_handler_index = 0) const; /** * 返回一个所有被约束的自由度的列表。该列表是在本地拥有的向量范围的MPI本地索引空间中返回的,而不是跨越所有MPI处理器的全局MPI索引空间。要获得全局索引空间的数字,请在向量的一个条目上调用<tt>get_vector_partitioner()->local_to_global</tt>。此外,它只返回本地拥有的自由度的指数,而不是鬼魂的指数。 * */ const std::vector<unsigned int> & get_constrained_dofs(const unsigned int dof_handler_index = 0) const; /** * 根据给定的数据布局,计算自由度的重新编号,使其更符合MatrixFree中的数据布局。注意,这个函数并不重新排列存储在这个类中的信息,而是创建一个重新编号以消耗 * DoFHandler::renumber_dofs. * 为了产生任何效果,必须使用重新编号的DoFHandler和AffineConstraints再次设置MatrixFree对象。注意,如果DoFHandler调用 * DoFHandler::renumber_dofs, ,MatrixFree中的所有信息都会失效。 * */ void renumber_dofs(std::vector<types::global_dof_index> &renumbering, const unsigned int dof_handler_index = 0); //@} /** * @name 4:一般信息 * */ //@{ /** * 返回一个给定的FiniteElement @p fe 是否被这个类所支持。 * */ template <int spacedim> static bool is_supported(const FiniteElement<dim, spacedim> &fe); /** * 返回初始化时指定的不同DoFHandlers的数量。 * */ unsigned int n_components() const; /** * 对于由 @p * dof_handler_index指定的DoFHandler的基础有限元,返回基础元的数量。 * */ unsigned int n_base_elements(const unsigned int dof_handler_index) const; /** * 返回这个结构所基于的单元数。如果你使用的是一个通常的DoFHandler,它对应于(本地拥有的)活动单元的数量。请注意,这个类中的大多数数据结构并不直接作用于这个数字,而是作用于n_cell_batches(),它给出了用矢量化将几个单元拼凑在一起时看到的单元的数量。 * */ unsigned int n_physical_cells() const; /** * @deprecated 用n_cell_batches()代替。 * */ DEAL_II_DEPRECATED unsigned int n_macro_cells() const; /** * 返回该结构所处理的单元格批次的数量。批次是通过在一般的几个单元上应用矢量化而形成的。 * @p cell_loop * 中的细胞范围从零到n_cell_batches()(独占),所以如果你想为所有要处理的细胞存储数据数组,这是一个合适的大小。这个数字大约是 * `n_physical_cells()/VectorizedArray::%size()` * (取决于有多少细胞批没有被完全填满)。 * */ unsigned int n_cell_batches() const; /** * 返回该结构为面层集成而保留的额外单元格批次的数量。请注意,并不是所有在三角形中被重影的单元格都被保留在这个数据结构中,而是只有那些对评估两边的面积分有必要的单元格。 * */ unsigned int n_ghost_cell_batches() const; /** * 返回这个结构所处理的内部面批的数量。 * 这些批次是通过在一般的几个面上应用矢量化而形成的。 * @p loop * 中的面的范围从零到n_inner_face_batches()(独占),所以如果你想为所有要处理的内部面存储数据的数组,这就是合适的大小。 * */ unsigned int n_inner_face_batches() const; /** * 返回这个结构所处理的边界面批的数量。 * 这些批次是通过在一般的几个面上应用矢量化而形成的。 * @p loop * 中的面的范围从n_inner_face_batches()到n_inner_face_batches()+n_boundary_face_batches()(独占),所以如果你需要存储所有边界面而不是内部面的数据的数组,这个数字给出适当的大小。 * */ unsigned int n_boundary_face_batches() const; /** * 返回未在本地处理但属于本地拥有的面的数量。 * */ unsigned int n_ghost_inner_face_batches() const; /** * 为了对边界的不同部分应用不同的运算符,这个方法可以用来查询面孔自己在VectorizedArray中按车道排序的边界ID。只对表示边界面的索引有效。 * */ types::boundary_id get_boundary_id(const unsigned int macro_face) const; /** * 返回一个单元格内的面的边界ID,使用单元格在VectorizedArray中按车道的排序。 * */ std::array<types::boundary_id, VectorizedArrayType::size()> get_faces_by_cells_boundary_id(const unsigned int cell_batch_index, const unsigned int face_number) const; /** * 返回DoFHandler,其索引与reinit()函数中各自的 `std::vector` * 参数一样。 * */ const DoFHandler<dim> & get_dof_handler(const unsigned int dof_handler_index = 0) const; /** * 返回DoFHandler,其索引与reinit()函数中相应的 `std::vector` * 参数一样。注意,如果你想用不同于默认的模板参数来调用这个函数,你需要在函数调用前使用`template`,也就是说,你会有类似`matrix_free.template * get_dof_handler<hp::DoFHandler<dim>>()`. @deprecated * 使用这个函数的非模板化等价物。 * */ template <typename DoFHandlerType> DEAL_II_DEPRECATED const DoFHandlerType & get_dof_handler(const unsigned int dof_handler_index = 0) const; /** * 返回deal.II中的单元格迭代器讲到一个给定的单元格批次(在一个VectorizedArray中填充几个车道)和在这个结构的重新编号中跨单元格的矢量化中的车道索引。 * 请注意,deal.II中的单元格迭代器与本类的单元格循环的处理方式不同。这是因为几个单元被一起处理(跨单元的矢量化),而且在访问远程数据和与计算重叠的通信时,在不同的MPI处理器上有邻居的单元需要在某个时间被访问。 * */ typename DoFHandler<dim>::cell_iterator get_cell_iterator(const unsigned int cell_batch_index, const unsigned int lane_index, const unsigned int dof_handler_index = 0) const; /** * 这将返回由get_cell_iterator()对相同参数`cell_batch_index`和`lane_index`所返回的单元的级别和索引。 * */ std::pair<int, int> get_cell_level_and_index(const unsigned int cell_batch_index, const unsigned int lane_index) const; /** * 在deal.II中返回单元格的迭代器,该迭代器与一个面的内部/外部单元格在一对面批和巷道索引中。这一对中的第二个元素是面的编号,这样就可以访问面的迭代器。 * `pair.first()->face(pair.second());`注意deal.II中的面迭代器通过单元格的方式与本类的面/边界循环的方式不同。这是因为几个面是一起工作的(矢量化),而且在访问远程数据和与计算重叠的通信时,在不同的MPI处理器上有相邻单元的面需要在某个时间被访问。 * */ std::pair<typename DoFHandler<dim>::cell_iterator, unsigned int> get_face_iterator(const unsigned int face_batch_index, const unsigned int lane_index, const bool interior = true, const unsigned int fe_component = 0) const; /** * @copydoc MatrixFree::get_cell_iterator() @deprecated * 使用get_cell_iterator()代替。 * */ DEAL_II_DEPRECATED typename DoFHandler<dim>::active_cell_iterator get_hp_cell_iterator(const unsigned int cell_batch_index, const unsigned int lane_index, const unsigned int dof_handler_index = 0) const; /** * 由于该类使用的是矢量数据类型,数据域中通常有多个值,因此可能会出现矢量类型的某些分量与网格中的实际单元不对应的情况。当只使用这个类时,通常不需要理会这个事实,因为这些值是用零填充的。然而,当这个类与访问单元格的deal.II混合时,需要注意。如果不是所有给定的`cell_batch_index`的`n_lanes`单元都对应于网格中的实际单元,有些只是为了填充的原因而出现,则该函数返回 * @p true * 。要知道有多少单元被实际使用,可以使用函数n_active_entries_per_cell_batch()。 * */ bool at_irregular_cell(const unsigned int cell_batch_index) const; /** * @deprecated 使用n_active_entries_per_cell_batch()代替。 * */ DEAL_II_DEPRECATED unsigned int n_components_filled(const unsigned int cell_batch_number) const; /** * 这个查询返回在一个单元格批中的 * `VectorizedArrayType::size()` * 个单元格中,有多少单元格是网格中的实际单元格,而不是因为填充的原因而出现的。对于大多数给定的n_cell_batches()中的单元格批次,这个数字等于 * `VectorizedArrayType::size()`, * ,但在网格中可能有一个或几个单元格批次(数字不相加),其中只有一个批次中的一些单元格被使用,由函数at_irregular_cell()表示。 * */ unsigned int n_active_entries_per_cell_batch(const unsigned int cell_batch_index) const; /** * 使用这个函数找出在矢量化数据类型的长度上有多少个面对应于网格中的真实面(包括内部和边界面,因为这些面使用相同的索引,但范围不同)。对于大多数在n_inner_faces_batches()和n_boundary_face_batches()中给定的索引,这只是 * @p vectorization_length * 个,但可能有一个或几个网格(数字不相加),其中有更少的这种道的填充。 * */ unsigned int n_active_entries_per_face_batch(const unsigned int face_batch_index) const; /** * 返回给定hp-index的每个单元的自由度数量。 * */ unsigned int get_dofs_per_cell(const unsigned int dof_handler_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的每个单元的正交点的数量。 * */ unsigned int get_n_q_points(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的单元格每个面上的自由度数量。 * */ unsigned int get_dofs_per_face(const unsigned int dof_handler_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的单元格每个面上的正交点的数量。 * */ unsigned int get_n_q_points_face(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的正交规则。 * */ const Quadrature<dim> & get_quadrature(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的正交规则。 * */ const Quadrature<dim - 1> & get_face_quadrature(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回当前批次的电池被分配到的类别。对于非hp-DoFHandler类型,类别在字段 * AdditionalData::cell_vectorization_category * 中的给定值之间运行,在hp-adaptive情况下返回活动的FE指数。 * */ unsigned int get_cell_category(const unsigned int cell_batch_index) const; /** * 返回当前一批面的两边的单元格上的类别。 * */ std::pair<unsigned int, unsigned int> get_face_category(const unsigned int macro_face) const; /** * 查询是否已经设置了索引。 * */ bool indices_initialized() const; /** * 查询单元格的几何相关信息是否已被设置。 * */ bool mapping_initialized() const; /** * 返回要处理的网格的级别。如果在活动单元上工作,返回 * numbers::invalid_unsigned_int 。 * */ unsigned int get_mg_level() const; /** * 返回该类的内存消耗量的近似值,单位为字节。 * */ std::size_t memory_consumption() const; /** * 在给定的输出流中打印出该类不同结构的内存消耗的详细摘要。 * */ template <typename StreamType> void print_memory_consumption(StreamType &out) const; /** * 在给定的输出流中打印这个类的摘要。它集中在索引上,并不打印所有存储的数据。 * */ void print(std::ostream &out) const; //@} /** * @name 5: 访问内部数据结构 注意:专家模式,接口在不同版本之间不稳定。 * */ //@{ /** * 返回任务图的信息。 * */ const internal::MatrixFreeFunctions::TaskInfo & get_task_info() const; /*返回单元格上与几何有关的信息。 * */ const internal::MatrixFreeFunctions:: MappingInfo<dim, Number, VectorizedArrayType> & get_mapping_info() const; /** * 返回关于索引自由度的信息。 * */ const internal::MatrixFreeFunctions::DoFInfo & get_dof_info(const unsigned int dof_handler_index_component = 0) const; /** * 返回约束池中的权重数量。 * */ unsigned int n_constraint_pool_entries() const; /** * 返回一个指向约束池数据中第一个数字的指针,索引为 * @p pool_index (与 @p constraint_pool_end()). 一起使用 * */ const Number * constraint_pool_begin(const unsigned int pool_index) const; /** * 返回一个指向约束池数据中最后一个数字的指针,索引为 * @p pool_index (与 @p constraint_pool_begin()一起使用)。 * */ const Number * constraint_pool_end(const unsigned int pool_index) const; /** * 返回给定hp-index的单元格信息。 * */ const internal::MatrixFreeFunctions::ShapeInfo<VectorizedArrayType> & get_shape_info(const unsigned int dof_handler_index_component = 0, const unsigned int quad_index = 0, const unsigned int fe_base_element = 0, const unsigned int hp_active_fe_index = 0, const unsigned int hp_active_quad_index = 0) const; /** * 返回一个面的连接信息。 * */ const internal::MatrixFreeFunctions::FaceToCellTopology< VectorizedArrayType::size()> & get_face_info(const unsigned int face_batch_index) const; /** * 返回将宏观单元格号、单元格内的面的索引和向量的单元格批内的索引这三者转化为面数组内的索引的表格。 * */ const Table<3, unsigned int> & get_cell_and_face_to_plain_faces() const; /** * 获取一个内部使用的抓取数据对象。请确保事后将你从这个对象获得的指针传递给release_scratch_data()函数,以释放它。这个接口被FEEvaluation对象用来存储其数据结构。 内部数据结构的组织是一个线程本地存储的向量列表。多个线程将各自获得一个单独的存储域和单独的向量,确保线程安全。获取和释放对象的机制类似于WorkStream的本地贡献机制,见 @ref workstream_paper "WorkStream论文" * 。 * */ AlignedVector<VectorizedArrayType> * acquire_scratch_data() const; /** * 使得抓取板的对象再次可用。 * */ void release_scratch_data(const AlignedVector<VectorizedArrayType> *memory) const; /** * 获取一个用于内部使用的划痕数据对象。确保事后将你从这个对象获得的指针传递给release_scratch_data_non_threadsafe()函数,以释放它。注意,与acquisition_scratch_data()相反,这个方法一次只能由一个线程调用,但与acquisition_scratch_data()相反,释放scratch数据的线程也有可能与获取它的线程不同。 * */ AlignedVector<Number> * acquire_scratch_data_non_threadsafe() const; /** * 使得从头数据的对象再次可用。 * */ void release_scratch_data_non_threadsafe( const AlignedVector<Number> *memory) const; //@} private: /** * 这是实际的reinit函数,为DoFHandler的情况设置索引。 * */ template <typename number2, int q_dim> void internal_reinit( const std::shared_ptr<hp::MappingCollection<dim>> & mapping, const std::vector<const DoFHandler<dim, dim> *> & dof_handlers, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<IndexSet> & locally_owned_set, const std::vector<hp::QCollection<q_dim>> & quad, const AdditionalData & additional_data); /** * 初始化DoFInfo中的字段和约束池,约束池中保存了所有不同的权重(不是DoFInfo的一部分,因为几个DoFInfo类可以有相同的权重,因此只需要存储一次)。 * */ template <typename number2> void initialize_indices( const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<IndexSet> & locally_owned_set, const AdditionalData & additional_data); /** * 基于DoFHandler<dim>参数初始化DoFHandlers。 * */ void initialize_dof_handlers( const std::vector<const DoFHandler<dim, dim> *> &dof_handlers, const AdditionalData & additional_data); /** * 指向当前问题基础的DoFHandlers的指针。 * */ std::vector<SmartPointer<const DoFHandler<dim>>> dof_handlers; /** * 包含各个单元格上的自由度和约束信息。 * */ std::vector<internal::MatrixFreeFunctions::DoFInfo> dof_info; /** * 包含存储在DoFInfo中的约束条件的权重。填充到一个单独的字段中,因为几个向量组件可能共享类似的权重,这样可以减少内存消耗。此外,它省去了DoFInfo上的模板参数,使之成为一个只有索引的普通字段。 * */ std::vector<Number> constraint_pool_data; /** * 包含一个指向约束池数据中第i个索引开始的指标。 * */ std::vector<unsigned int> constraint_pool_row_index; /** * 保存单元格从参考单元格到实数单元格的转换信息,这是评估积分所需要的。 * */ internal::MatrixFreeFunctions::MappingInfo<dim, Number, VectorizedArrayType> mapping_info; /** * 包含单元格的形状值信息。 * */ Table<4, internal::MatrixFreeFunctions::ShapeInfo<VectorizedArrayType>> shape_info; /** * 描述了单元格是如何被穿过的。有了单元格级别(该字段的第一个索引)和级别内的索引,就可以重建一个deal.II单元格迭代器,并使用deal.II提供的所有传统的单元格迭代器的功能。 * */ std::vector<std::pair<unsigned int, unsigned int>> cell_level_index; /** * 对于非连续Galerkin,cell_level_index包括不在本地处理器上的单元,但需要用来计算单元积分。在cell_level_index_end_local中,我们存储本地单元的数量。 * */ unsigned int cell_level_index_end_local; /** * 存储要处理的单元和面的基本布局,包括共享内存并行化的任务布局以及与MPI的通信和计算之间可能的重叠。 * */ internal::MatrixFreeFunctions::TaskInfo task_info; /** * 持有面孔信息的向量。只在build_face_info=true时初始化。 * */ internal::MatrixFreeFunctions::FaceInfo<VectorizedArrayType::size()> face_info; /** * 存储索引是否已被初始化。 * */ bool indices_are_initialized; /** * 存储索引是否已被初始化。 * */ bool mapping_is_initialized; /** * 用于评估的刮板内存。我们允许超过一个评估对象附加到这个字段(这个,外 * std::vector), * 所以我们需要跟踪某个数据字段是否已经被使用(第一部分对)并保持一个对象的列表。 * */ mutable Threads::ThreadLocalStorage< std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>> scratch_pad; /** * 用于评估和其他情况下的Scratchpad内存,非线程安全的变体。 * */ mutable std::list<std::pair<bool, AlignedVector<Number>>> scratch_pad_non_threadsafe; /** * 存储了要处理的网格的级别。 * */ unsigned int mg_level; }; /*----------------------- Inline functions ----------------------------------*/ #ifndef DOXYGEN template <int dim, typename Number, typename VectorizedArrayType> template <typename VectorType> inline void MatrixFree<dim, Number, VectorizedArrayType>::initialize_dof_vector( VectorType & vec, const unsigned int comp) const { AssertIndexRange(comp, n_components()); vec.reinit(dof_info[comp].vector_partitioner->size()); } template <int dim, typename Number, typename VectorizedArrayType> template <typename Number2> inline void MatrixFree<dim, Number, VectorizedArrayType>::initialize_dof_vector( LinearAlgebra::distributed::Vector<Number2> &vec, const unsigned int comp) const { AssertIndexRange(comp, n_components()); vec.reinit(dof_info[comp].vector_partitioner, task_info.communicator_sm); } template <int dim, typename Number, typename VectorizedArrayType> inline const std::shared_ptr<const Utilities::MPI::Partitioner> & MatrixFree<dim, Number, VectorizedArrayType>::get_vector_partitioner( const unsigned int comp) const { AssertIndexRange(comp, n_components()); return dof_info[comp].vector_partitioner; } template <int dim, typename Number, typename VectorizedArrayType> inline const std::vector<unsigned int> & MatrixFree<dim, Number, VectorizedArrayType>::get_constrained_dofs( const unsigned int comp) const { AssertIndexRange(comp, n_components()); return dof_info[comp].constrained_dofs; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_components() const { AssertDimension(dof_handlers.size(), dof_info.size()); return dof_handlers.size(); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_base_elements( const unsigned int dof_no) const { AssertDimension(dof_handlers.size(), dof_info.size()); AssertIndexRange(dof_no, dof_handlers.size()); return dof_handlers[dof_no]->get_fe().n_base_elements(); } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::TaskInfo & MatrixFree<dim, Number, VectorizedArrayType>::get_task_info() const { return task_info; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_macro_cells() const { return *(task_info.cell_partition_data.end() - 2); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_physical_cells() const { return task_info.n_active_cells; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_cell_batches() const { return *(task_info.cell_partition_data.end() - 2); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_ghost_cell_batches() const { return *(task_info.cell_partition_data.end() - 1) - *(task_info.cell_partition_data.end() - 2); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_inner_face_batches() const { if (task_info.face_partition_data.size() == 0) return 0; return task_info.face_partition_data.back(); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_boundary_face_batches() const { if (task_info.face_partition_data.size() == 0) return 0; return task_info.boundary_partition_data.back() - task_info.face_partition_data.back(); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_ghost_inner_face_batches() const { if (task_info.face_partition_data.size() == 0) return 0; return face_info.faces.size() - task_info.boundary_partition_data.back(); } template <int dim, typename Number, typename VectorizedArrayType> inline types::boundary_id MatrixFree<dim, Number, VectorizedArrayType>::get_boundary_id( const unsigned int macro_face) const { Assert(macro_face >= task_info.boundary_partition_data[0] && macro_face < task_info.boundary_partition_data.back(), ExcIndexRange(macro_face, task_info.boundary_partition_data[0], task_info.boundary_partition_data.back())); return types::boundary_id(face_info.faces[macro_face].exterior_face_no); } template <int dim, typename Number, typename VectorizedArrayType> inline std::array<types::boundary_id, VectorizedArrayType::size()> MatrixFree<dim, Number, VectorizedArrayType>::get_faces_by_cells_boundary_id( const unsigned int cell_batch_index, const unsigned int face_number) const { AssertIndexRange(cell_batch_index, n_cell_batches()); AssertIndexRange(face_number, GeometryInfo<dim>::faces_per_cell); Assert(face_info.cell_and_face_boundary_id.size(0) >= n_cell_batches(), ExcNotInitialized()); std::array<types::boundary_id, VectorizedArrayType::size()> result; result.fill(numbers::invalid_boundary_id); for (unsigned int v = 0; v < n_active_entries_per_cell_batch(cell_batch_index); ++v) result[v] = face_info.cell_and_face_boundary_id(cell_batch_index, face_number, v); return result; } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions:: MappingInfo<dim, Number, VectorizedArrayType> & MatrixFree<dim, Number, VectorizedArrayType>::get_mapping_info() const { return mapping_info; } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::DoFInfo & MatrixFree<dim, Number, VectorizedArrayType>::get_dof_info( const unsigned int dof_index) const { AssertIndexRange(dof_index, n_components()); return dof_info[dof_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_constraint_pool_entries() const { return constraint_pool_row_index.size() - 1; } template <int dim, typename Number, typename VectorizedArrayType> inline const Number * MatrixFree<dim, Number, VectorizedArrayType>::constraint_pool_begin( const unsigned int row) const { AssertIndexRange(row, constraint_pool_row_index.size() - 1); return constraint_pool_data.empty() ? nullptr : constraint_pool_data.data() + constraint_pool_row_index[row]; } template <int dim, typename Number, typename VectorizedArrayType> inline const Number * MatrixFree<dim, Number, VectorizedArrayType>::constraint_pool_end( const unsigned int row) const { AssertIndexRange(row, constraint_pool_row_index.size() - 1); return constraint_pool_data.empty() ? nullptr : constraint_pool_data.data() + constraint_pool_row_index[row + 1]; } template <int dim, typename Number, typename VectorizedArrayType> inline std::pair<unsigned int, unsigned int> MatrixFree<dim, Number, VectorizedArrayType>::create_cell_subrange_hp( const std::pair<unsigned int, unsigned int> &range, const unsigned int degree, const unsigned int dof_handler_component) const { if (dof_info[dof_handler_component].cell_active_fe_index.empty()) { AssertDimension( dof_info[dof_handler_component].fe_index_conversion.size(), 1); AssertDimension( dof_info[dof_handler_component].fe_index_conversion[0].size(), 1); if (dof_info[dof_handler_component].fe_index_conversion[0][0] == degree) return range; else return {range.second, range.second}; } const unsigned int fe_index = dof_info[dof_handler_component].fe_index_from_degree(0, degree); if (fe_index >= dof_info[dof_handler_component].max_fe_index) return {range.second, range.second}; else return create_cell_subrange_hp_by_index(range, fe_index, dof_handler_component); } template <int dim, typename Number, typename VectorizedArrayType> inline bool MatrixFree<dim, Number, VectorizedArrayType>::at_irregular_cell( const unsigned int cell_batch_index) const { AssertIndexRange(cell_batch_index, task_info.cell_partition_data.back()); return VectorizedArrayType::size() > 1 && cell_level_index[(cell_batch_index + 1) * VectorizedArrayType::size() - 1] == cell_level_index[(cell_batch_index + 1) * VectorizedArrayType::size() - 2]; } template <int dim, typename Number, typename VectorizedArrayType> unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_active_fe_indices() const { return shape_info.size(2); } template <int dim, typename Number, typename VectorizedArrayType> unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_cell_active_fe_index( const std::pair<unsigned int, unsigned int> range) const { const auto &fe_indices = dof_info[0].cell_active_fe_index; if (fe_indices.empty() == true) return 0; const auto index = fe_indices[range.first]; for (unsigned int i = range.first; i < range.second; ++i) AssertDimension(index, fe_indices[i]); return index; } template <int dim, typename Number, typename VectorizedArrayType> unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_face_active_fe_index( const std::pair<unsigned int, unsigned int> range, const bool is_interior_face) const { const auto &fe_indices = dof_info[0].cell_active_fe_index; if (fe_indices.empty() == true) return 0; if (is_interior_face) { const unsigned int index = fe_indices[face_info.faces[range.first].cells_interior[0] / VectorizedArrayType::size()]; for (unsigned int i = range.first; i < range.second; ++i) AssertDimension(index, fe_indices[face_info.faces[i].cells_interior[0] / VectorizedArrayType::size()]); return index; } else { const unsigned int index = fe_indices[face_info.faces[range.first].cells_exterior[0] / VectorizedArrayType::size()]; for (unsigned int i = range.first; i < range.second; ++i) AssertDimension(index, fe_indices[face_info.faces[i].cells_exterior[0] / VectorizedArrayType::size()]); return index; } } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_components_filled( const unsigned int cell_batch_index) const { return n_active_entries_per_cell_batch(cell_batch_index); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_active_entries_per_cell_batch( const unsigned int cell_batch_index) const { AssertIndexRange(cell_batch_index, task_info.cell_partition_data.back()); unsigned int n_lanes = VectorizedArrayType::size(); while (n_lanes > 1 && cell_level_index[cell_batch_index * VectorizedArrayType::size() + n_lanes - 1] == cell_level_index[cell_batch_index * VectorizedArrayType::size() + n_lanes - 2]) --n_lanes; AssertIndexRange(n_lanes - 1, VectorizedArrayType::size()); return n_lanes; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_active_entries_per_face_batch( const unsigned int face_batch_index) const { AssertIndexRange(face_batch_index, face_info.faces.size()); unsigned int n_lanes = VectorizedArrayType::size(); while (n_lanes > 1 && face_info.faces[face_batch_index].cells_interior[n_lanes - 1] == numbers::invalid_unsigned_int) --n_lanes; AssertIndexRange(n_lanes - 1, VectorizedArrayType::size()); return n_lanes; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_dofs_per_cell( const unsigned int dof_handler_index, const unsigned int active_fe_index) const { return dof_info[dof_handler_index].dofs_per_cell[active_fe_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_n_q_points( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.cell_data.size()); return mapping_info.cell_data[quad_index] .descriptor[active_fe_index] .n_q_points; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_dofs_per_face( const unsigned int dof_handler_index, const unsigned int active_fe_index) const { return dof_info[dof_handler_index].dofs_per_face[active_fe_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_n_q_points_face( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.face_data.size()); return mapping_info.face_data[quad_index] .descriptor[active_fe_index] .n_q_points; } template <int dim, typename Number, typename VectorizedArrayType> inline const IndexSet & MatrixFree<dim, Number, VectorizedArrayType>::get_locally_owned_set( const unsigned int dof_handler_index) const { return dof_info[dof_handler_index].vector_partitioner->locally_owned_range(); } template <int dim, typename Number, typename VectorizedArrayType> inline const IndexSet & MatrixFree<dim, Number, VectorizedArrayType>::get_ghost_set( const unsigned int dof_handler_index) const { return dof_info[dof_handler_index].vector_partitioner->ghost_indices(); } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::ShapeInfo<VectorizedArrayType> & MatrixFree<dim, Number, VectorizedArrayType>::get_shape_info( const unsigned int dof_handler_index, const unsigned int index_quad, const unsigned int index_fe, const unsigned int active_fe_index, const unsigned int active_quad_index) const { AssertIndexRange(dof_handler_index, dof_info.size()); const unsigned int ind = dof_info[dof_handler_index].global_base_element_offset + index_fe; AssertIndexRange(ind, shape_info.size(0)); AssertIndexRange(index_quad, shape_info.size(1)); AssertIndexRange(active_fe_index, shape_info.size(2)); AssertIndexRange(active_quad_index, shape_info.size(3)); return shape_info(ind, index_quad, active_fe_index, active_quad_index); } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::FaceToCellTopology< VectorizedArrayType::size()> & MatrixFree<dim, Number, VectorizedArrayType>::get_face_info( const unsigned int macro_face) const { AssertIndexRange(macro_face, face_info.faces.size()); return face_info.faces[macro_face]; } template <int dim, typename Number, typename VectorizedArrayType> inline const Table<3, unsigned int> & MatrixFree<dim, Number, VectorizedArrayType>::get_cell_and_face_to_plain_faces() const { return face_info.cell_and_face_to_plain_faces; } template <int dim, typename Number, typename VectorizedArrayType> inline const Quadrature<dim> & MatrixFree<dim, Number, VectorizedArrayType>::get_quadrature( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.cell_data.size()); return mapping_info.cell_data[quad_index] .descriptor[active_fe_index] .quadrature; } template <int dim, typename Number, typename VectorizedArrayType> inline const Quadrature<dim - 1> & MatrixFree<dim, Number, VectorizedArrayType>::get_face_quadrature( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.face_data.size()); return mapping_info.face_data[quad_index] .descriptor[active_fe_index] .quadrature; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_cell_category( const unsigned int cell_batch_index) const { AssertIndexRange(0, dof_info.size()); AssertIndexRange(cell_batch_index, dof_info[0].cell_active_fe_index.size()); if (dof_info[0].cell_active_fe_index.empty()) return 0; else return dof_info[0].cell_active_fe_index[cell_batch_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline std::pair<unsigned int, unsigned int> MatrixFree<dim, Number, VectorizedArrayType>::get_face_category( const unsigned int macro_face) const { AssertIndexRange(macro_face, face_info.faces.size()); if (dof_info[0].cell_active_fe_index.empty()) return std::make_pair(0U, 0U); std::pair<unsigned int, unsigned int> result; for (unsigned int v = 0; v < VectorizedArrayType::size() && face_info.faces[macro_face].cells_interior[v] != numbers::invalid_unsigned_int; ++v) result.first = std::max( result.first, dof_info[0] .cell_active_fe_index[face_info.faces[macro_face].cells_interior[v]]); if (face_info.faces[macro_face].cells_exterior[0] != numbers::invalid_unsigned_int) for (unsigned int v = 0; v < VectorizedArrayType::size() && face_info.faces[macro_face].cells_exterior[v] != numbers::invalid_unsigned_int; ++v) result.second = std::max( result.first, dof_info[0] .cell_active_fe_index[face_info.faces[macro_face].cells_exterior[v]]); else result.second = numbers::invalid_unsigned_int; return result; } template <int dim, typename Number, typename VectorizedArrayType> inline bool MatrixFree<dim, Number, VectorizedArrayType>::indices_initialized() const { return indices_are_initialized; } template <int dim, typename Number, typename VectorizedArrayType> inline bool MatrixFree<dim, Number, VectorizedArrayType>::mapping_initialized() const { return mapping_is_initialized; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_mg_level() const { return mg_level; } template <int dim, typename Number, typename VectorizedArrayType> AlignedVector<VectorizedArrayType> * MatrixFree<dim, Number, VectorizedArrayType>::acquire_scratch_data() const { using list_type = std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>; list_type &data = scratch_pad.get(); for (typename list_type::iterator it = data.begin(); it != data.end(); ++it) if (it->first == false) { it->first = true; return &it->second; } data.emplace_front(true, AlignedVector<VectorizedArrayType>()); return &data.front().second; } template <int dim, typename Number, typename VectorizedArrayType> void MatrixFree<dim, Number, VectorizedArrayType>::release_scratch_data( const AlignedVector<VectorizedArrayType> *scratch) const { using list_type = std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>; list_type &data = scratch_pad.get(); for (typename list_type::iterator it = data.begin(); it != data.end(); ++it) if (&it->second == scratch) { Assert(it->first == true, ExcInternalError()); it->first = false; return; } AssertThrow(false, ExcMessage("Tried to release invalid scratch pad")); } template <int dim, typename Number, typename VectorizedArrayType> AlignedVector<Number> * MatrixFree<dim, Number, VectorizedArrayType>:: acquire_scratch_data_non_threadsafe() const { for (typename std::list<std::pair<bool, AlignedVector<Number>>>::iterator it = scratch_pad_non_threadsafe.begin(); it != scratch_pad_non_threadsafe.end(); ++it) if (it->first == false) { it->first = true; return &it->second; } scratch_pad_non_threadsafe.push_front( std::make_pair(true, AlignedVector<Number>())); return &scratch_pad_non_threadsafe.front().second; } template <int dim, typename Number, typename VectorizedArrayType> void MatrixFree<dim, Number, VectorizedArrayType>:: release_scratch_data_non_threadsafe( const AlignedVector<Number> *scratch) const { for (typename std::list<std::pair<bool, AlignedVector<Number>>>::iterator it = scratch_pad_non_threadsafe.begin(); it != scratch_pad_non_threadsafe.end(); ++it) if (&it->second == scratch) { Assert(it->first == true, ExcInternalError()); it->first = false; return; } AssertThrow(false, ExcMessage("Tried to release invalid scratch pad")); } // ------------------------------ reinit functions --------------------------- namespace internal { namespace MatrixFreeImplementation { template <int dim, int spacedim> inline std::vector<IndexSet> extract_locally_owned_index_sets( const std::vector<const ::dealii::DoFHandler<dim, spacedim> *> &dofh, const unsigned int level) { std::vector<IndexSet> locally_owned_set; locally_owned_set.reserve(dofh.size()); for (unsigned int j = 0; j < dofh.size(); j++) if (level == numbers::invalid_unsigned_int) locally_owned_set.push_back(dofh[j]->locally_owned_dofs()); else locally_owned_set.push_back(dofh[j]->locally_owned_mg_dofs(level)); return locally_owned_set; } } // namespace MatrixFreeImplementation } // namespace internal template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraints_in, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<const DoFHandler<dim, dim> *> dof_handlers; std::vector<const AffineConstraints<number2> *> constraints; std::vector<QuadratureType> quads; dof_handlers.push_back(&dof_handler); constraints.push_back(&constraints_in); quads.push_back(quad); std::vector<IndexSet> locally_owned_sets = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handlers, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>( StaticMappingQ1<dim>::mapping), dof_handlers, constraints, locally_owned_sets, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraints_in, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<const DoFHandler<dim, dim> *> dof_handlers; std::vector<const AffineConstraints<number2> *> constraints; dof_handlers.push_back(&dof_handler); constraints.push_back(&constraints_in); std::vector<IndexSet> locally_owned_sets = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handlers, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), dof_handlers, constraints, locally_owned_sets, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; for (unsigned int q = 0; q < quad.size(); ++q) quad_hp.emplace_back(quad[q]); internal_reinit(std::make_shared<hp::MappingCollection<dim>>( StaticMappingQ1<dim>::mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dh); this->reinit(mapping, dof_handlers, constraint, quad, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>( StaticMappingQ1<dim>::mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dof_handler); this->reinit(dof_handlers, constraint, quad, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; for (unsigned int q = 0; q < quad.size(); ++q) quad_hp.emplace_back(quad[q]); internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dof_handler); this->reinit(mapping, dof_handlers, constraint, quad, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dof_handler); this->reinit(dof_handlers, constraint, quad, additional_data); } // ------------------------------ implementation of loops -------------------- // internal helper functions that define how to call MPI data exchange // functions: for generic vectors, do nothing at all. For distributed vectors, // call update_ghost_values_start function and so on. If we have collections // of vectors, just do the individual functions of the components. In order to // keep ghost values consistent (whether we are in read or write mode), we // also reset the values at the end. the whole situation is a bit complicated // by the fact that we need to treat block vectors differently, which use some // additional helper functions to select the blocks and template magic. namespace internal { /** * 用于交换向量间数据的内部类。 * */ template <int dim, typename Number, typename VectorizedArrayType> struct VectorDataExchange { // A shift for the MPI messages to reduce the risk for accidental // interaction with other open communications that a user program might // set up (parallel vectors support unfinished communication). We let // the other vectors use the first 20 assigned numbers and start the // matrix-free communication. static constexpr unsigned int channel_shift = 20; /** * 构造函数。接受MF数据,DG中面部访问的标志和组件的数量。 * */ VectorDataExchange( const dealii::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free, const typename dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces vector_face_access, const unsigned int n_components) : matrix_free(matrix_free) , vector_face_access( matrix_free.get_task_info().face_partition_data.empty() ? dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::unspecified : vector_face_access) , ghosts_were_set(false) # ifdef DEAL_II_WITH_MPI , tmp_data(n_components) , requests(n_components) # endif { (void)n_components; if (this->vector_face_access != dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::unspecified) for (unsigned int c = 0; c < matrix_free.n_components(); ++c) AssertDimension( matrix_free.get_dof_info(c).vector_exchanger_face_variants.size(), 5); } /** * 解构器。 * */ ~VectorDataExchange() // NOLINT { # ifdef DEAL_II_WITH_MPI for (unsigned int i = 0; i < tmp_data.size(); ++i) if (tmp_data[i] != nullptr) matrix_free.release_scratch_data_non_threadsafe(tmp_data[i]); # endif } /** * 遍历MF对象中的所有组件,选择其分区器与该组件中的分区器兼容的组件。 * */ template <typename VectorType> unsigned int find_vector_in_mf(const VectorType &vec, const bool check_global_compatibility = true) const { // case 1: vector was set up with MatrixFree::initialize_dof_vector() for (unsigned int c = 0; c < matrix_free.n_components(); ++c) if (vec.get_partitioner().get() == matrix_free.get_dof_info(c).vector_partitioner.get()) return c; // case 2: user provided own partitioner (compatibility mode) for (unsigned int c = 0; c < matrix_free.n_components(); ++c) if (check_global_compatibility ? vec.get_partitioner()->is_globally_compatible( *matrix_free.get_dof_info(c).vector_partitioner) : vec.get_partitioner()->is_compatible( *matrix_free.get_dof_info(c).vector_partitioner)) return c; Assert(false, ExcNotImplemented("Could not find partitioner that fits vector")); return numbers::invalid_unsigned_int; } /** * 为给定的 @p mf_component * 获取分区器,同时考虑到构造函数中设置的vector_face_access。 * */ const internal::MatrixFreeFunctions::VectorDataExchange::Base & get_partitioner(const unsigned int mf_component) const { AssertDimension(matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants.size(), 5); if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::none) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[0]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::values) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[1]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::gradients) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[2]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::values_all_faces) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[3]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::gradients_all_faces) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[4]; else return *matrix_free.get_dof_info(mf_component).vector_exchanger.get(); } /** * 开始为序列向量更新_ghost_value * */ template <typename VectorType, typename std::enable_if<is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int /*component_in_block_vector*/ , const VectorType & /*vec*/ ) {} /** * 对于不支持分割成_start()和finish()阶段的向量,开始更新_ghost_value。 * */ template <typename VectorType, typename std::enable_if< !has_update_ghost_values_start<VectorType>::value && !is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int component_in_block_vector, const VectorType & vec) { (void)component_in_block_vector; bool ghosts_set = vec.has_ghost_elements(); if (ghosts_set) ghosts_were_set = true; vec.update_ghost_values(); } /** * 对于那些支持分成_start()和finish()阶段,但不支持在DoF子集上交换的向量,开始更新_ghost_value。 * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int component_in_block_vector, const VectorType & vec) { (void)component_in_block_vector; bool ghosts_set = vec.has_ghost_elements(); if (ghosts_set) ghosts_were_set = true; vec.update_ghost_values_start(component_in_block_vector + channel_shift); } /** * 最后,对于那些支持分成_start()和finish()阶段,并且支持在子集DoF上交换的向量,即 * LinearAlgebra::distributed::Vector ,开始更新_ghost_value。 * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int component_in_block_vector, const VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; bool ghosts_set = vec.has_ghost_elements(); if (ghosts_set) ghosts_were_set = true; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() == 0 && part.n_import_indices() == 0 && part.n_import_sm_procs() == 0) return; tmp_data[component_in_block_vector] = matrix_free.acquire_scratch_data_non_threadsafe(); tmp_data[component_in_block_vector]->resize_fast( part.n_import_indices()); AssertDimension(requests.size(), tmp_data.size()); part.export_to_ghosted_array_start( component_in_block_vector * 2 + channel_shift, ArrayView<const Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(const_cast<Number *>(vec.begin()) + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), ArrayView<Number>(tmp_data[component_in_block_vector]->begin(), part.n_import_indices()), this->requests[component_in_block_vector]); # endif } } /** * 对于不支持分成_start()和finish()阶段的向量和串行向量,完成update_ghost_value。 * */ template < typename VectorType, typename std::enable_if<!has_update_ghost_values_start<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_finish(const unsigned int /*component_in_block_vector*/ , const VectorType & /*vec*/ ) {} /** * 完成对支持分割成_start()和finish()阶段的向量的 * update_ghost_value,但不支持在DoF的子集上进行交换。 * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_finish(const unsigned int component_in_block_vector, const VectorType & vec) { (void)component_in_block_vector; vec.update_ghost_values_finish(); } /** * 完成update_ghost_value,用于_支持分成_start()和finish()阶段的向量,也支持在子集DoF上的交换,即 * LinearAlgebra::distributed::Vector * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_finish(const unsigned int component_in_block_vector, const VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI AssertIndexRange(component_in_block_vector, tmp_data.size()); AssertDimension(requests.size(), tmp_data.size()); const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() != 0 || part.n_import_indices() != 0 || part.n_import_sm_procs() != 0) { part.export_to_ghosted_array_finish( ArrayView<const Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(const_cast<Number *>(vec.begin()) + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), this->requests[component_in_block_vector]); matrix_free.release_scratch_data_non_threadsafe( tmp_data[component_in_block_vector]); tmp_data[component_in_block_vector] = nullptr; } # endif } // let vector know that ghosts are being updated and we can read from // them vec.set_ghost_state(true); } /** * 对串行向量进行启动压缩 * */ template <typename VectorType, typename std::enable_if<is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int /*component_in_block_vector*/ , VectorType & /*vec*/ ) {} /** * 对于不支持分割成_start()和finish()阶段的向量,开始压缩 * */ template <typename VectorType, typename std::enable_if<!has_compress_start<VectorType>::value && !is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int component_in_block_vector, VectorType & vec) { (void)component_in_block_vector; Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); vec.compress(dealii::VectorOperation::add); } /** * 对于支持分割成_start()和finish()阶段的向量开始压缩,但不支持在DoF的一个子集上交换。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int component_in_block_vector, VectorType & vec) { (void)component_in_block_vector; Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); vec.compress_start(component_in_block_vector + channel_shift); } /** * 开始压缩那些_支持分割成_start()和finish()阶段的向量,并且也支持在子集DoF上的交换,即 * LinearAlgebra::distributed::Vector 。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int component_in_block_vector, VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() == 0 && part.n_import_indices() == 0 && part.n_import_sm_procs() == 0) return; tmp_data[component_in_block_vector] = matrix_free.acquire_scratch_data_non_threadsafe(); tmp_data[component_in_block_vector]->resize_fast( part.n_import_indices()); AssertDimension(requests.size(), tmp_data.size()); part.import_from_ghosted_array_start( dealii::VectorOperation::add, component_in_block_vector * 2 + channel_shift, ArrayView<Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(vec.begin() + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), ArrayView<Number>(tmp_data[component_in_block_vector]->begin(), part.n_import_indices()), this->requests[component_in_block_vector]); # endif } } /** * 对不支持分成_start()和finish()阶段的向量和串行向量进行完成压缩 * */ template <typename VectorType, typename std::enable_if<!has_compress_start<VectorType>::value, VectorType>::type * = nullptr> void compress_finish(const unsigned int /*component_in_block_vector*/ , VectorType & /*vec*/ ) {} /** * 对于支持分割成_start()和finish()阶段的向量完成压缩,但不支持在DoF的子集上交换。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_finish(const unsigned int component_in_block_vector, VectorType & vec) { (void)component_in_block_vector; vec.compress_finish(dealii::VectorOperation::add); } /** * 开始压缩那些_支持分割成_start()和finish()阶段的向量,并且也支持在子集DoF上的交换,即 * LinearAlgebra::distributed::Vector 。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_finish(const unsigned int component_in_block_vector, VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI AssertIndexRange(component_in_block_vector, tmp_data.size()); AssertDimension(requests.size(), tmp_data.size()); const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() != 0 || part.n_import_indices() != 0 || part.n_import_sm_procs() != 0) { part.import_from_ghosted_array_finish( VectorOperation::add, ArrayView<Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(vec.begin() + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), ArrayView<const Number>( tmp_data[component_in_block_vector]->begin(), part.n_import_indices()), this->requests[component_in_block_vector]); matrix_free.release_scratch_data_non_threadsafe( tmp_data[component_in_block_vector]); tmp_data[component_in_block_vector] = nullptr; } if (Utilities::MPI::job_supports_mpi()) { const int ierr = MPI_Barrier(matrix_free.get_task_info().communicator_sm); AssertThrowMPI(ierr); } # endif } } /** * 重置串行向量的所有幽灵值 * */ template <typename VectorType, typename std::enable_if<is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void reset_ghost_values(const VectorType & /*vec*/ ) const {} /** * 重置不支持在子集DoF上交换的向量的所有鬼值 * */ template < typename VectorType, typename std::enable_if<!has_exchange_on_subset<VectorType>::value && !is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void reset_ghost_values(const VectorType &vec) const { if (ghosts_were_set == true) return; vec.zero_out_ghost_values(); } /** * 重置_支持在子集DoF上交换的向量的所有鬼魂值,即 * LinearAlgebra::distributed::Vector 。 * */ template <typename VectorType, typename std::enable_if<has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void reset_ghost_values(const VectorType &vec) const { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); if (ghosts_were_set == true) return; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI AssertDimension(requests.size(), tmp_data.size()); const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() > 0) { part.reset_ghost_values(ArrayView<Number>( const_cast<LinearAlgebra::distributed::Vector<Number> &>(vec) .begin() + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices())); } # endif } // let vector know that it's not ghosted anymore vec.set_ghost_state(false); } /** * 对于_do_ support exchange on a subset of DoFs <==> begin() + ind == * local_element(ind), i.e. LinearAlgebra::distributed::Vector * 的向量区域清零。 * */ template <typename VectorType, typename std::enable_if<has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void zero_vector_region(const unsigned int range_index, VectorType &vec) const { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); if (range_index == numbers::invalid_unsigned_int) vec = Number(); else { const unsigned int mf_component = find_vector_in_mf(vec, false); const internal::MatrixFreeFunctions::DoFInfo &dof_info = matrix_free.get_dof_info(mf_component); Assert(dof_info.vector_zero_range_list_index.empty() == false, ExcNotInitialized()); Assert(vec.partitioners_are_compatible(*dof_info.vector_partitioner), ExcInternalError()); AssertIndexRange(range_index, dof_info.vector_zero_range_list_index.size() - 1); for (unsigned int id = dof_info.vector_zero_range_list_index[range_index]; id != dof_info.vector_zero_range_list_index[range_index + 1]; ++id) std::memset(vec.begin() + dof_info.vector_zero_range_list[id].first, 0, (dof_info.vector_zero_range_list[id].second - dof_info.vector_zero_range_list[id].first) * sizeof(Number)); } } /** * 对于不支持在DoFs子集上进行交换的向量,将向量区域清零 * <==> begin() + ind == local_element(ind) 但仍然是向量类型。 * */ template < typename VectorType, typename std::enable_if<!has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr, typename VectorType::value_type * = nullptr> void zero_vector_region(const unsigned int range_index, VectorType &vec) const { if (range_index == numbers::invalid_unsigned_int || range_index == 0) vec = typename VectorType::value_type(); } /** * 对于非向量类型,即没有 VectorType::value_type * 的类,将向量区域清零。 * */ void zero_vector_region(const unsigned int, ...) const { Assert(false, ExcNotImplemented("Zeroing is only implemented for vector types " "which provide VectorType::value_type")); } const dealii::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free; const typename dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces vector_face_access; bool ghosts_were_set; # ifdef DEAL_II_WITH_MPI std::vector<AlignedVector<Number> *> tmp_data; std::vector<std::vector<MPI_Request>> requests; # endif }; // VectorDataExchange template <typename VectorStruct> unsigned int n_components(const VectorStruct &vec); template <typename VectorStruct> unsigned int n_components_block(const VectorStruct &vec, std::integral_constant<bool, true>) { unsigned int components = 0; for (unsigned int bl = 0; bl < vec.n_blocks(); ++bl) components += n_components(vec.block(bl)); return components; } template <typename VectorStruct> unsigned int n_components_block(const VectorStruct &, std::integral_constant<bool, false>) { return 1; } template <typename VectorStruct> unsigned int n_components(const VectorStruct &vec) { return n_components_block( vec, std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); } template <typename VectorStruct> inline unsigned int n_components(const std::vector<VectorStruct> &vec) { unsigned int components = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) components += n_components_block( vec[comp], std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); return components; } template <typename VectorStruct> inline unsigned int n_components(const std::vector<VectorStruct *> &vec) { unsigned int components = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) components += n_components_block( *vec[comp], std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); return components; } // A helper function to identify block vectors with many components where we // should not try to overlap computations and communication because there // would be too many outstanding communication requests. // default value for vectors that do not have communication_block_size template < typename VectorStruct, typename std::enable_if<!has_communication_block_size<VectorStruct>::value, VectorStruct>::type * = nullptr> constexpr unsigned int get_communication_block_size(const VectorStruct &) { return numbers::invalid_unsigned_int; } template < typename VectorStruct, typename std::enable_if<has_communication_block_size<VectorStruct>::value, VectorStruct>::type * = nullptr> constexpr unsigned int get_communication_block_size(const VectorStruct &) { return VectorStruct::communication_block_size; } // -------------------------------------------------------------------------- // below we have wrappers to distinguish between block and non-block vectors. // -------------------------------------------------------------------------- // // update_ghost_values_start // // update_ghost_values for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_start( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) { // don't forget to set ghosts_were_set, that otherwise happens // inside VectorDataExchange::update_ghost_values_start() exchanger.ghosts_were_set = vec.has_ghost_elements(); vec.update_ghost_values(); } else { for (unsigned int i = 0; i < vec.n_blocks(); ++i) update_ghost_values_start(vec.block(i), exchanger, channel + i); } } // update_ghost_values for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_start( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.update_ghost_values_start(channel, vec); } // update_ghost_values_start() for vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_start( const std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_start(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // update_ghost_values_start() for vector of pointers to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_start( const std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_start(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // update_ghost_values_finish // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_finish( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) { // do nothing, everything has already been completed in the _start() // call } else for (unsigned int i = 0; i < vec.n_blocks(); ++i) update_ghost_values_finish(vec.block(i), exchanger, channel + i); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_finish( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.update_ghost_values_finish(channel, vec); } // for vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_finish( const std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_finish(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // for vector of pointers to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_finish( const std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_finish(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // compress_start // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_start( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) vec.compress(dealii::VectorOperation::add); else for (unsigned int i = 0; i < vec.n_blocks(); ++i) compress_start(vec.block(i), exchanger, channel + i); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_start( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.compress_start(channel, vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_start( std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_start(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // for std::vector of pointer to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_start( std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_start(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // compress_finish // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_finish( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) { // do nothing, everything has already been completed in the _start() // call } else for (unsigned int i = 0; i < vec.n_blocks(); ++i) compress_finish(vec.block(i), exchanger, channel + i); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_finish( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.compress_finish(channel, vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_finish( std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_finish(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // for std::vector of pointer to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_finish( std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_finish(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // reset_ghost_values: // // if the input vector did not have ghosts imported, clear them here again // in order to avoid subsequent operations e.g. in linear solvers to work // with ghosts all the time // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void reset_ghost_values( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { // return immediately if there is nothing to do. if (exchanger.ghosts_were_set == true) return; for (unsigned int i = 0; i < vec.n_blocks(); ++i) reset_ghost_values(vec.block(i), exchanger); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void reset_ghost_values( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { exchanger.reset_ghost_values(vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void reset_ghost_values( const std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { // return immediately if there is nothing to do. if (exchanger.ghosts_were_set == true) return; for (unsigned int comp = 0; comp < vec.size(); comp++) reset_ghost_values(vec[comp], exchanger); } // for std::vector of pointer to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void reset_ghost_values( const std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { // return immediately if there is nothing to do. if (exchanger.ghosts_were_set == true) return; for (unsigned int comp = 0; comp < vec.size(); comp++) reset_ghost_values(*vec[comp], exchanger); } // // zero_vector_region // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void zero_vector_region( const unsigned int range_index, VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { for (unsigned int i = 0; i < vec.n_blocks(); ++i) exchanger.zero_vector_region(range_index, vec.block(i)); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void zero_vector_region( const unsigned int range_index, VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { exchanger.zero_vector_region(range_index, vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void zero_vector_region( const unsigned int range_index, std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { for (unsigned int comp = 0; comp < vec.size(); comp++) zero_vector_region(range_index, vec[comp], exchanger); } // for std::vector of pointers to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void zero_vector_region( const unsigned int range_index, std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { for (unsigned int comp = 0; comp < vec.size(); comp++) zero_vector_region(range_index, *vec[comp], exchanger); } namespace MatrixFreeFunctions { // struct to select between a const interface and a non-const interface // for MFWorker template <typename, typename, typename, typename, bool> struct InterfaceSelector {}; // Version for constant functions template <typename MF, typename InVector, typename OutVector, typename Container> struct InterfaceSelector<MF, InVector, OutVector, Container, true> { using function_type = void (Container::*)( const MF &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const; }; // Version for non-constant functions template <typename MF, typename InVector, typename OutVector, typename Container> struct InterfaceSelector<MF, InVector, OutVector, Container, false> { using function_type = void (Container::*)(const MF &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &); }; } // namespace MatrixFreeFunctions // A implementation class for the worker object that runs the various // operations we want to perform during the matrix-free loop template <typename MF, typename InVector, typename OutVector, typename Container, bool is_constant> class MFWorker : public MFWorkerInterface { public: // An alias to make the arguments further down more readable using function_type = typename MatrixFreeFunctions:: InterfaceSelector<MF, InVector, OutVector, Container, is_constant>:: function_type; // constructor, binds all the arguments to this class MFWorker(const MF & matrix_free, const InVector & src, OutVector & dst, const bool zero_dst_vector_setting, const Container & container, function_type cell_function, function_type face_function, function_type boundary_function, const typename MF::DataAccessOnFaces src_vector_face_access = MF::DataAccessOnFaces::none, const typename MF::DataAccessOnFaces dst_vector_face_access = MF::DataAccessOnFaces::none, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop = {}, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop = {}, const unsigned int dof_handler_index_pre_post = 0) : matrix_free(matrix_free) , container(const_cast<Container &>(container)) , cell_function(cell_function) , face_function(face_function) , boundary_function(boundary_function) , src(src) , dst(dst) , src_data_exchanger(matrix_free, src_vector_face_access, n_components(src)) , dst_data_exchanger(matrix_free, dst_vector_face_access, n_components(dst)) , src_and_dst_are_same(PointerComparison::equal(&src, &dst)) , zero_dst_vector_setting(zero_dst_vector_setting && !src_and_dst_are_same) , operation_before_loop(operation_before_loop) , operation_after_loop(operation_after_loop) , dof_handler_index_pre_post(dof_handler_index_pre_post) {} // Runs the cell work. If no function is given, nothing is done virtual void cell(const std::pair<unsigned int, unsigned int> &cell_range) override { if (cell_function != nullptr && cell_range.second > cell_range.first) for (unsigned int i = 0; i < matrix_free.n_active_fe_indices(); ++i) { const auto cell_subrange = matrix_free.create_cell_subrange_hp_by_index(cell_range, i); if (cell_subrange.second <= cell_subrange.first) continue; (container.* cell_function)(matrix_free, this->dst, this->src, cell_subrange); } } virtual void cell(const unsigned int range_index) override { process_range(cell_function, matrix_free.get_task_info().cell_partition_data_hp_ptr, matrix_free.get_task_info().cell_partition_data_hp, range_index); } virtual void face(const unsigned int range_index) override { process_range(face_function, matrix_free.get_task_info().face_partition_data_hp_ptr, matrix_free.get_task_info().face_partition_data_hp, range_index); } virtual void boundary(const unsigned int range_index) override { process_range(boundary_function, matrix_free.get_task_info().boundary_partition_data_hp_ptr, matrix_free.get_task_info().boundary_partition_data_hp, range_index); } private: void process_range(const function_type & fu, const std::vector<unsigned int> &ptr, const std::vector<unsigned int> &data, const unsigned int range_index) { if (fu == nullptr) return; for (unsigned int i = ptr[range_index]; i < ptr[range_index + 1]; ++i) (container.*fu)(matrix_free, this->dst, this->src, std::make_pair(data[2 * i], data[2 * i + 1])); } public: // Starts the communication for the update ghost values operation. We // cannot call this update if ghost and destination are the same because // that would introduce spurious entries in the destination (there is also // the problem that reading from a vector that we also write to is usually // not intended in case there is overlap, but this is up to the // application code to decide and we cannot catch this case here). virtual void vector_update_ghosts_start() override { if (!src_and_dst_are_same) internal::update_ghost_values_start(src, src_data_exchanger); } // Finishes the communication for the update ghost values operation virtual void vector_update_ghosts_finish() override { if (!src_and_dst_are_same) internal::update_ghost_values_finish(src, src_data_exchanger); } // Starts the communication for the vector compress operation virtual void vector_compress_start() override { internal::compress_start(dst, dst_data_exchanger); } // Finishes the communication for the vector compress operation virtual void vector_compress_finish() override { internal::compress_finish(dst, dst_data_exchanger); if (!src_and_dst_are_same) internal::reset_ghost_values(src, src_data_exchanger); } // Zeros the given input vector virtual void zero_dst_vector_range(const unsigned int range_index) override { if (zero_dst_vector_setting) internal::zero_vector_region(range_index, dst, dst_data_exchanger); } virtual void cell_loop_pre_range(const unsigned int range_index) override { if (operation_before_loop) { const internal::MatrixFreeFunctions::DoFInfo &dof_info = matrix_free.get_dof_info(dof_handler_index_pre_post); if (range_index == numbers::invalid_unsigned_int) { // Case with threaded loop -> currently no overlap implemented dealii::parallel::apply_to_subranges( 0U, dof_info.vector_partitioner->locally_owned_size(), operation_before_loop, internal::VectorImplementation::minimum_parallel_grain_size); } else { AssertIndexRange(range_index, dof_info.cell_loop_pre_list_index.size() - 1); for (unsigned int id = dof_info.cell_loop_pre_list_index[range_index]; id != dof_info.cell_loop_pre_list_index[range_index + 1]; ++id) operation_before_loop(dof_info.cell_loop_pre_list[id].first, dof_info.cell_loop_pre_list[id].second); } } } virtual void cell_loop_post_range(const unsigned int range_index) override { if (operation_after_loop) { const internal::MatrixFreeFunctions::DoFInfo &dof_info = matrix_free.get_dof_info(dof_handler_index_pre_post); if (range_index == numbers::invalid_unsigned_int) { // Case with threaded loop -> currently no overlap implemented dealii::parallel::apply_to_subranges( 0U, dof_info.vector_partitioner->locally_owned_size(), operation_after_loop, internal::VectorImplementation::minimum_parallel_grain_size); } else { AssertIndexRange(range_index, dof_info.cell_loop_post_list_index.size() - 1); for (unsigned int id = dof_info.cell_loop_post_list_index[range_index]; id != dof_info.cell_loop_post_list_index[range_index + 1]; ++id) operation_after_loop(dof_info.cell_loop_post_list[id].first, dof_info.cell_loop_post_list[id].second); } } } private: const MF & matrix_free; Container & container; function_type cell_function; function_type face_function; function_type boundary_function; const InVector &src; OutVector & dst; VectorDataExchange<MF::dimension, typename MF::value_type, typename MF::vectorized_value_type> src_data_exchanger; VectorDataExchange<MF::dimension, typename MF::value_type, typename MF::vectorized_value_type> dst_data_exchanger; const bool src_and_dst_are_same; const bool zero_dst_vector_setting; const std::function<void(const unsigned int, const unsigned int)> operation_before_loop; const std::function<void(const unsigned int, const unsigned int)> operation_after_loop; const unsigned int dof_handler_index_pre_post; }; /** * 一个内部类,将三个函数指针转换为上述带有虚拟函数的方案。 * */ template <class MF, typename InVector, typename OutVector> struct MFClassWrapper { using function_type = std::function<void(const MF &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)>; MFClassWrapper(const function_type cell, const function_type face, const function_type boundary) : cell(cell) , face(face) , boundary(boundary) {} void cell_integrator(const MF & mf, OutVector & dst, const InVector & src, const std::pair<unsigned int, unsigned int> &range) const { if (cell) cell(mf, dst, src, range); } void face_integrator(const MF & mf, OutVector & dst, const InVector & src, const std::pair<unsigned int, unsigned int> &range) const { if (face) face(mf, dst, src, range); } void boundary_integrator( const MF & mf, OutVector & dst, const InVector & src, const std::pair<unsigned int, unsigned int> &range) const { if (boundary) boundary(mf, dst, src, range); } const function_type cell; const function_type face; const function_type boundary; }; } // end of namespace internal template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector &src, const bool zero_dst_vector) const { using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, nullptr, nullptr); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, zero_dst_vector, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post) const { using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, nullptr, nullptr); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, false, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator, DataAccessOnFaces::none, DataAccessOnFaces::none, operation_before_loop, operation_after_loop, dof_handler_index_pre_post); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &face_operation, const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & boundary_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces dst_vector_face_access, const DataAccessOnFaces src_vector_face_access) const { using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, face_operation, boundary_operation); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, zero_dst_vector, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator, src_vector_face_access, dst_vector_face_access); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, false, *owning_class, function_pointer, nullptr, nullptr, DataAccessOnFaces::none, DataAccessOnFaces::none, operation_before_loop, operation_after_loop, dof_handler_index_pre_post); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop( void (CLASS::*cell_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*face_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*boundary_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces dst_vector_face_access, const DataAccessOnFaces src_vector_face_access) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, zero_dst_vector, *owning_class, cell_operation, face_operation, boundary_operation, src_vector_face_access, dst_vector_face_access); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, false, *owning_class, function_pointer, nullptr, nullptr, DataAccessOnFaces::none, DataAccessOnFaces::none, operation_before_loop, operation_after_loop, dof_handler_index_pre_post); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop( void (CLASS::*cell_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*face_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*boundary_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces dst_vector_face_access, const DataAccessOnFaces src_vector_face_access) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, zero_dst_vector, *owning_class, cell_operation, face_operation, boundary_operation, src_vector_face_access, dst_vector_face_access); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop_cell_centric( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces src_vector_face_access) const { auto src_vector_face_access_temp = src_vector_face_access; if (DataAccessOnFaces::gradients == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; else if (DataAccessOnFaces::values == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr, src_vector_face_access_temp, DataAccessOnFaces::none); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop_cell_centric( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces src_vector_face_access) const { auto src_vector_face_access_temp = src_vector_face_access; if (DataAccessOnFaces::gradients == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; else if (DataAccessOnFaces::values == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr, src_vector_face_access_temp, DataAccessOnFaces::none); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop_cell_centric( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces src_vector_face_access) const { auto src_vector_face_access_temp = src_vector_face_access; if (DataAccessOnFaces::gradients == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; else if (DataAccessOnFaces::values == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, nullptr, nullptr); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, zero_dst_vector, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator, src_vector_face_access_temp, DataAccessOnFaces::none); task_info.loop(worker); } #endif // ifndef DOXYGEN DEAL_II_NAMESPACE_CLOSE #endif
[ "jiaqiwang969@gmail.com" ]
jiaqiwang969@gmail.com
2729985e2cb2f2d5d99ae05ffdf3859abb456ee1
02ec47da2d5ae3216c9c747fe90a56c87a91b0e8
/WebpIO/src/ImageDecoderWEBP.h
f1a0c2e47cd3a4eac66066b2b7accfcb083c121a
[]
no_license
gloryofrobots/UIO_Plugin
ad42a87750ee424e4a266842de8a446f2f861aed
42014e86d296e0aab2ae5d28fcdeb070942cdbfe
refs/heads/master
2016-08-05T04:46:05.045144
2013-03-13T11:12:11
2013-03-13T11:12:11
8,750,222
2
0
null
null
null
null
UTF-8
C++
false
false
684
h
# pragma once # include "CodecSystem/ImageDecoder.h" # include "webp/decode.h" //# include "webp/mux.h" namespace UIO_Plugin { class ImageDecoderWEBP : public ImageDecoder { public: ImageDecoderWEBP(); virtual ~ImageDecoderWEBP(); void writeHeader( UIO_Plugin_Header * _header ) override; protected: bool _initialize() override; bool _decode( unsigned char* _buffer, unsigned int _bufferSize ) override; private: bool _decodeScale( unsigned char* _buffer, unsigned int _bufferSize ); bool _decodeFull( unsigned char* _buffer, unsigned int _bufferSize ); protected: uint8_t* m_dataBuffer; size_t m_dataSize; WebPDecoderConfig m_decoderConfig; }; }
[ "gloryofrobots@gmail.com" ]
gloryofrobots@gmail.com
bbcee2ebfeeaf02d763f7215ae9820d58c5e26fb
2bc835b044f306fca1affd1c61b8650b06751756
/winhttp/v5.1/api/thrdinfo.cxx
7f46b85b9d656aceded250240c62c089528642f3
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_inetcore
bbb2354d95a51a75ce2dfd67b18cfb6b21c94939
75f614d008bfce1ea71e4a727205f46b0de8e1c3
refs/heads/master
2023-04-04T02:55:25.139618
2021-04-14T05:25:01
2021-04-14T05:25:01
357,780,123
1
0
null
null
null
null
UTF-8
C++
false
false
42,020
cxx
/*++ Copyright (c) 1994 Microsoft Corporation Module Name: thrdinfo.cxx Abstract: Functions to manipulate an INTERNET_THREAD_INFO Contents: InternetCreateThreadInfo InternetDestroyThreadInfo InternetTerminateThreadInfo InternetGetThreadInfo InternetSetThreadInfo InternetIndicateStatusAddress InternetIndicateStatusString InternetIndicateStatusNewHandle InternetIndicateStatus InternetSetLastError _InternetSetLastError InternetLockErrorText InternetUnlockErrorText InternetSetObjectHandle InternetGetObjectHandle InternetFreeThreadInfo Author: Richard L Firth (rfirth) 16-Feb-1995 Environment: Win32 user-level DLL Revision History: 16-Feb-1995 rfirth Created --*/ #include <wininetp.h> #include <perfdiag.hxx> // // manifests // #define BAD_TLS_INDEX 0xffffffff // according to online win32 SDK documentation #ifdef SPX_SUPPORT #define GENERIC_SPX_NAME "SPX Server" #endif //SPX_SUPPORT // // macros // #ifdef ENABLE_DEBUG #define InitializeInternetThreadInfo(lpThreadInfo) \ InitializeListHead(&lpThreadInfo->List); \ lpThreadInfo->Signature = INTERNET_THREAD_INFO_SIGNATURE; \ lpThreadInfo->ThreadId = GetCurrentThreadId(); #else #define InitializeInternetThreadInfo(threadInfo) \ InitializeListHead(&lpThreadInfo->List); \ lpThreadInfo->ThreadId = GetCurrentThreadId(); #endif // ENABLE_DEBUG // // private data // PRIVATE DWORD InternetTlsIndex = BAD_TLS_INDEX; PRIVATE SERIALIZED_LIST ThreadInfoList; LPINTERNET_THREAD_INFO InternetCreateThreadInfo( IN BOOL SetTls, IN LPINTERNET_THREAD_INFO lpPreStaticAllocatedThreadInfo ) /*++ Routine Description: Creates, initializes an INTERNET_THREAD_INFO. Optionally (allocates and) sets this thread's Internet TLS Assumes: 1. The first time this function is called is in the context of the process attach library call, so we allocate the TLS index once Arguments: SetTls - TRUE if we are to set the INTERNET_THREAD_INFO TLS for this thread Return Value: LPINTERNET_THREAD_INFO Success - pointer to allocated INTERNET_THREAD_INFO structure which has been set as this threads value in its InternetTlsIndex slot Failure - NULL --*/ { LPINTERNET_THREAD_INFO lpThreadInfo = NULL; BOOL ok = FALSE; if (InDllCleanup) { goto quit; } if (InternetTlsIndex == BAD_TLS_INDEX) { // // first time through, initialize serialized list // InitializeSerializedList(&ThreadInfoList); // // we assume that if we are allocating the TLS index, then this is the // one and only thread in this process that can call into this DLL // right now - i.e. this thread is loading the DLL // InternetTlsIndex = TlsAlloc(); } if (InternetTlsIndex != BAD_TLS_INDEX) { if (lpPreStaticAllocatedThreadInfo != NULL) { lpThreadInfo = lpPreStaticAllocatedThreadInfo; memset(lpThreadInfo, 0, sizeof(INTERNET_THREAD_INFO)); #if INET_DEBUG lpThreadInfo->fStaticAllocation = TRUE; #endif } else { lpThreadInfo = NEW(INTERNET_THREAD_INFO); // lpThreadInfo->fStaticAllocation = FALSE; implicitly set } if (lpThreadInfo != NULL) { InitializeInternetThreadInfo(lpThreadInfo); if (SetTls) { ok = TlsSetValue(InternetTlsIndex, (LPVOID)lpThreadInfo); if (!ok) { DEBUG_PUT(("InternetCreateThreadInfo(): TlsSetValue(%d, %#x) returns %d\n", InternetTlsIndex, lpThreadInfo, GetLastError() )); DEBUG_BREAK(THRDINFO); } } else { ok = TRUE; } } else { DEBUG_PUT(("InternetCreateThreadInfo(): NEW(INTERNET_THREAD_INFO) returned NULL\n")); DEBUG_BREAK(THRDINFO); } } else { DEBUG_PUT(("InternetCreateThreadInfo(): TlsAlloc() returns %#x, error %d\n", BAD_TLS_INDEX, GetLastError() )); DEBUG_BREAK(THRDINFO); } if (ok) { // only dynamically allocated threadinfo's are put into the // ThreadInfoList -- statically preallocated threadinfo's must // not go into the ThreadInfoList if (lpPreStaticAllocatedThreadInfo == NULL) { if (!InsertAtHeadOfSerializedList(&ThreadInfoList, &lpThreadInfo->List)) { ok = FALSE; } } } // If something failed, then delete any dynamically allocated threadinfo if (!ok) { if ((lpPreStaticAllocatedThreadInfo == NULL) && (lpThreadInfo != NULL)) { DEL(lpThreadInfo); } lpThreadInfo = NULL; } quit: return lpThreadInfo; } VOID InternetDestroyThreadInfo( VOID ) /*++ Routine Description: Cleans up the INTERNET_THREAD_INFO - deletes any memory it owns and deletes it Arguments: None. Return Value: None. --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; IF_DEBUG(NOTHING) { DEBUG_PUT(("InternetDestroyThreadInfo(): Thread %#x: Deleting INTERNET_THREAD_INFO\n", GetCurrentThreadId() )); } // // don't call InternetGetThreadInfo() - we don't need to create the // INTERNET_THREAD_INFO if it doesn't exist in this case // lpThreadInfo = (LPINTERNET_THREAD_INFO)TlsGetValue(InternetTlsIndex); if (lpThreadInfo != NULL) { #if INET_DEBUG // // there shouldn't be anything in the debug record stack. On Win95, we // ignore this check if this is the async scheduler (nee worker) thread // AND there are entries in the debug record stack. The async thread // gets killed off before it has chance to DEBUG_LEAVE, then comes here, // causing this assert to be over-active // if (IsPlatformWin95() && lpThreadInfo->IsAsyncWorkerThread) { if (lpThreadInfo->CallDepth != 0) { DEBUG_PUT(("InternetDestroyThreadInfo(): " "Thread %#x: " "%d records in debug stack\n", lpThreadInfo->CallDepth )); } } else { INET_ASSERT(lpThreadInfo->Stack == NULL); } #endif // INET_DEBUG InternetFreeThreadInfo(lpThreadInfo); INET_ASSERT(InternetTlsIndex != BAD_TLS_INDEX); TlsSetValue(InternetTlsIndex, NULL); } else { DEBUG_PUT(("InternetDestroyThreadInfo(): Thread %#x: no INTERNET_THREAD_INFO\n", GetCurrentThreadId() )); } } VOID InternetFreeThreadInfo( IN LPINTERNET_THREAD_INFO lpThreadInfo ) /*++ Routine Description: Removes the INTERNET_THREAD_INFO from the list and frees all allocated blocks Arguments: lpThreadInfo - pointer to INTERNET_THREAD_INFO to remove and free Return Value: None. --*/ { if (RemoveFromSerializedList(&ThreadInfoList, &lpThreadInfo->List)) { if (lpThreadInfo->hErrorText != NULL) { FREE_MEMORY(lpThreadInfo->hErrorText); } //if (lpThreadInfo->lpResolverInfo != NULL) { // if (lpThreadInfo->lpResolverInfo->DnrSocketHandle != NULL) { // lpThreadInfo->lpResolverInfo->DnrSocketHandle->Dereference(); // } // DEL(lpThreadInfo->lpResolverInfo); //} INET_ASSERT(!lpThreadInfo->fStaticAllocation); DEL(lpThreadInfo); } } VOID InternetTerminateThreadInfo( VOID ) /*++ Routine Description: Destroy all INTERNET_THREAD_INFO structures and terminate the serialized list. This funciton called at process detach time. At DLL_PROCESS_DETACH time, there may be other threads in the process for which we created an INTERNET_THREAD_INFO that aren't going to get the chance to delete the structure, so we do it here. Code in this module assumes that it is impossible for a new thread to enter this DLL while we are terminating in DLL_PROCESS_DETACH Arguments: None. Return Value: None. --*/ { // // get rid of this thread's info structure. No more debug output after this! // InternetDestroyThreadInfo(); // // get rid of the thread info structures left by other threads // if (LockSerializedList(&ThreadInfoList)) { LPINTERNET_THREAD_INFO lpThreadInfo; while (NULL != (lpThreadInfo = (LPINTERNET_THREAD_INFO)SlDequeueHead(&ThreadInfoList))) { // // already dequeued, no need to call InternetFreeThreadInfo() // INET_ASSERT(!lpThreadInfo->fStaticAllocation); FREE_MEMORY(lpThreadInfo); } UnlockSerializedList(&ThreadInfoList); } // // no more need for list // TerminateSerializedList(&ThreadInfoList); // // or TLS index // TlsFree(InternetTlsIndex); InternetTlsIndex = BAD_TLS_INDEX; } LPINTERNET_THREAD_INFO InternetGetThreadInfo( VOID ) /*++ Routine Description: Gets the pointer to the INTERNET_THREAD_INFO for this thread and checks that it still looks good. If this thread does not have an INTERNET_THREAD_INFO then we create one, presuming that this is a new thread Arguments: None. Return Value: LPINTERNET_THREAD_INFO Success - pointer to INTERNET_THREAD_INFO block Failure - NULL --*/ { LPINTERNET_THREAD_INFO lpThreadInfo = NULL; DWORD lastError; // // this is pretty bad - TlsGetValue() can destroy the per-thread last error // variable if it returns NULL (to indicate that NULL was actually set, and // that NULL does not indicate an error). So we have to read it before it is // potentially destroyed, and reset it before we quit. // // We do this here because typically, other functions will be completely // unsuspecting of this behaviour, and it is better to fix it once here, // than in several dozen other places, even though it is slightly // inefficient // lastError = GetLastError(); if (InternetTlsIndex != BAD_TLS_INDEX) { lpThreadInfo = (LPINTERNET_THREAD_INFO)TlsGetValue(InternetTlsIndex); } // // we may be in the process of creating the INTERNET_THREAD_INFO, in // which case its okay for this to be NULL. According to online SDK // documentation, a threads TLS value will be initialized to NULL // if (lpThreadInfo == NULL) { // // we presume this is a new thread. Create an INTERNET_THREAD_INFO // IF_DEBUG(NOTHING) { DEBUG_PUT(("InternetGetThreadInfo(): Thread %#x: Creating INTERNET_THREAD_INFO\n", GetCurrentThreadId() )); } lpThreadInfo = InternetCreateThreadInfo(TRUE); } if (lpThreadInfo != NULL) { INET_ASSERT(lpThreadInfo->Signature == INTERNET_THREAD_INFO_SIGNATURE); INET_ASSERT(lpThreadInfo->ThreadId == GetCurrentThreadId()); } else { DEBUG_PUT(("InternetGetThreadInfo(): Failed to get/create INTERNET_THREAD_INFO\n")); } // // as above - reset the last error variable in case TlsGetValue() trashed it // SetLastError(lastError); // // actual success/failure indicated by non-NULL/NULL pointer resp. // return lpThreadInfo; } VOID InternetSetThreadInfo( IN LPINTERNET_THREAD_INFO lpThreadInfo ) /*++ Routine Description: Sets lpThreadInfo as the current thread's INTERNET_THREAD_INFO. Used within fibers Arguments: lpThreadInfo - new INTERNET_THREAD_INFO to set Return Value: None. --*/ { if (InternetTlsIndex != BAD_TLS_INDEX) { if (!TlsSetValue(InternetTlsIndex, (LPVOID)lpThreadInfo)) { DEBUG_PUT(("InternetSetThreadInfo(): TlsSetValue(%d, %#x) returns %d\n", InternetTlsIndex, lpThreadInfo, GetLastError() )); INET_ASSERT(FALSE); } } else { DEBUG_PUT(("InternetSetThreadInfo(): InternetTlsIndex = %d\n", InternetTlsIndex )); INET_ASSERT(FALSE); } } DWORD InternetIndicateStatusAddress( IN DWORD dwInternetStatus, IN LPSOCKADDR lpSockAddr, IN DWORD dwSockAddrLength ) /*++ Routine Description: Make a status callback to the app. The data is a network address that we need to convert to a string Arguments: dwInternetStatus - WINHTTP_CALLBACK_STATUS_ value lpSockAddr - pointer to full socket address dwSockAddrLength - length of lpSockAddr in bytes Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_OPERATION_CANCELLED The app closed the object handle during the callback --*/ { LPSTR lpAddress; INT len; UNREFERENCED_PARAMETER(dwSockAddrLength); INET_ASSERT(lpSockAddr != NULL); switch (lpSockAddr->sa_family) { case AF_INET: lpAddress = _I_inet_ntoa( ((struct sockaddr_in*)lpSockAddr)->sin_addr ); break; case AF_INET6: char Address[INET6_ADDRSTRLEN+3]; // + 2 brkt chars + null char int error; Address[0] = '['; error = _I_getnameinfo(lpSockAddr, sizeof(SOCKADDR_IN6), Address+1, sizeof(Address)-2, NULL, 0, NI_NUMERICHOST); if (error) lpAddress = NULL; else { len = lstrlen(Address); Address[len] = ']'; Address[len+1] = '\0'; lpAddress = Address; } break; case AF_IPX: // // BUGBUG - this should be a call to WSAAddressToString, but that's not implemented yet // #ifdef SPX_SUPPORT lpAddress = GENERIC_SPX_NAME; #else lpAddress = NULL; #endif //SPX_SUPPORT break; default: lpAddress = NULL; break; } // we don't want a client to mess around with a winsock-internal buffer return InternetIndicateStatusString(dwInternetStatus, lpAddress, TRUE/*bCopyBuffer*/); } DWORD InternetIndicateStatusString( IN DWORD dwInternetStatus, IN LPSTR lpszStatusInfo OPTIONAL, IN BOOL bCopyBuffer, IN BOOL bConvertToUnicode ) /*++ Routine Description: Make a status callback to the app. The data is a string Arguments: dwInternetStatus - WINHTTP_CALLBACK_STATUS_ value lpszStatusInfo - string status data Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_OPERATION_CANCELLED The app closed the object handle during the callback --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetIndicateStatusString", "%d, %q", dwInternetStatus, lpszStatusInfo )); DWORD length; if (ARGUMENT_PRESENT(lpszStatusInfo)) { length = strlen(lpszStatusInfo) + 1; } else { length = 0; } DWORD error; error = InternetIndicateStatus(dwInternetStatus, lpszStatusInfo, length, bCopyBuffer, bConvertToUnicode); DEBUG_LEAVE(error); return error; } DWORD InternetIndicateStatusNewHandle( IN LPVOID hInternetMapped ) /*++ Routine Description: Indicates to the app a new handle Arguments: hInternetMapped - mapped address of new handle being indicated Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_OPERATION_CANCELLED The app closed the either the new object handle or the parent object handle during the callback --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetIndicateStatusNewHandle", "%#x", hInternetMapped )); HANDLE_OBJECT * hObject = (HANDLE_OBJECT *)hInternetMapped; // // reference the new request handle, in case the app closes it in the // callback. The new handle now has a reference count of 3 // hObject->Reference(); INET_ASSERT(hObject->ReferenceCount() == 3); // // we indicate the pseudo handle to the app // HINTERNET hInternet = hObject->GetPseudoHandle(); DWORD error = InternetIndicateStatus(WINHTTP_CALLBACK_STATUS_HANDLE_CREATED, (LPVOID)&hInternet, sizeof(hInternet) ); // // dereference the new request handle. If this returns TRUE then the new // handle has been deleted (the app called InternetCloseHandle() against // it which dereferenced it to 1, and now we've dereferenced it to zero) // hObject->Dereference(); if (error == ERROR_WINHTTP_OPERATION_CANCELLED) { // // the parent handle was deleted. Kill off the new handle too // WinHttpCloseHandle(hObject); //BOOL ok; //ok = hObject->Dereference(); // INET_ASSERT(ok); INET_ASSERT(hObject->ReferenceCount() == 1); // now only ref'ed by the API } else if (hObject->IsInvalidated()) { INET_ASSERT(hObject->ReferenceCount() == 1); // now only ref'ed by the API error = ERROR_WINHTTP_OPERATION_CANCELLED; } DEBUG_LEAVE(error); return error; } DWORD InternetIndicateStatus( IN DWORD dwStatus, IN LPVOID lpBuffer, IN DWORD dwLength, IN BOOL bCopyBuffer, IN BOOL bConvertToUnicode ) /*++ Routine Description: If the app has registered a callback function for the object that this thread is operating on, call it with the arguments supplied Arguments: dwStatus - WINHTTP_CALLBACK_STATUS_ value lpBuffer - pointer to variable data buffer dwLength - length of *lpBuffer in bytes Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_OPERATION_CANCELLED The app closed the object handle during the callback --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetIndicateStatus", "%s, %#x, %d", InternetMapStatus(dwStatus), lpBuffer, dwLength )); LPINTERNET_THREAD_INFO lpThreadInfo = InternetGetThreadInfo(); DWORD error = ERROR_SUCCESS; // // the app can affect callback operation by specifying a zero context value // meaning no callbacks will be generated for this API // if (lpThreadInfo != NULL) { INET_ASSERT(lpThreadInfo->hObject != NULL); INET_ASSERT(lpThreadInfo->hObjectMapped != NULL); // // if the context value in the thread info block is 0 then we use the // context from the handle object // DWORD_PTR context; context = ((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->GetContext(); WINHTTP_STATUS_CALLBACK appCallback; appCallback = ((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->GetStatusCallback(); IF_DEBUG(THRDINFO) { switch (dwStatus) { case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: DEBUG_PRINT(THRDINFO, INFO, ("%s\n", InternetMapStatus(dwStatus) )); break; case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: DEBUG_PRINT(THRDINFO, INFO, ("%s: #bytes = %d [%#x]\n", InternetMapStatus(dwStatus), *((DWORD*)lpBuffer), *((DWORD*)lpBuffer) )); break; case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: DEBUG_PRINT(THRDINFO, INFO, ("%s: Buffer = %#x, Number of bytes = %d\n", InternetMapStatus(dwStatus), lpBuffer, dwLength )); break; case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: DEBUG_PRINT(THRDINFO, INFO, ("%s: failure api = %d, Number of bytes = %d [%#x, %#s] \n", InternetMapStatus(dwStatus), ((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwResult, ((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError, ((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError, InternetMapError(((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError) )); } } if( dwStatus == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR) { TRACE_PRINT_API(THRDINFO, INFO, ("%s: Failure API = %s, Error = %s\n", InternetMapStatus(dwStatus), InternetMapRequestError( (DWORD) ((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwResult), InternetMapError(((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError) )); } if ((appCallback != NULL) && (((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->IsNotificationEnabled(dwStatus)) ) { LPVOID pInfo; //reported thru callback DWORD infoLength; //reported thru callback BOOL isAsyncWorkerThread; BYTE buffer[256]; // // we make a copy of the info to remove the app's opportunity to // change it. E.g. if we were about to resolve host name "foo" and // passed the pointer to our buffer containing "foo", the app could // change the name to "bar", changing the intended server // if (lpBuffer != NULL) { if (bConvertToUnicode) { INET_ASSERT( ((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->IsUnicodeStatusCallback() ); INET_ASSERT( (dwStatus == WINHTTP_CALLBACK_STATUS_RESOLVING_NAME) || (dwStatus == WINHTTP_CALLBACK_STATUS_NAME_RESOLVED) || (dwStatus == WINHTTP_CALLBACK_STATUS_REDIRECT) || (dwStatus == WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER) || (dwStatus == WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER) ); infoLength = MultiByteToWideChar(CP_ACP, 0, (LPSTR)lpBuffer, dwLength, NULL, 0); if (infoLength == 0) { pInfo = NULL; DEBUG_PRINT(THRDINFO, ERROR, ("MultiByteToWideChar returned 0 for a %d-length MBCS string\n", dwLength )); } else if (infoLength <= sizeof(buffer)/sizeof(WCHAR)) { pInfo = buffer; } else { pInfo = (LPVOID)ALLOCATE_FIXED_MEMORY(infoLength * sizeof(WCHAR)); } if (pInfo) { infoLength = MultiByteToWideChar(CP_ACP, 0, (LPSTR)lpBuffer, dwLength, (LPWSTR)pInfo, infoLength); if (infoLength == 0) { //MBtoWC failed if (pInfo != buffer) FREE_FIXED_MEMORY(pInfo); pInfo = NULL; DEBUG_PRINT(THRDINFO, ERROR, ("MultiByteToWideChar returned 0 for a %d-length MBCS string\n", dwLength )); } } //pInfo else { infoLength = 0; DEBUG_PRINT(THRDINFO, ERROR, ("MultiByteToWideChar() error OR Failed to allocate %d bytes for info\n", dwLength )); } //pInfo == NULL } //bConvertToUnicode else if (bCopyBuffer) { if (dwLength <= sizeof(buffer)) pInfo = buffer; else pInfo = (LPVOID)ALLOCATE_FIXED_MEMORY(dwLength); if (pInfo) { memcpy(pInfo, lpBuffer, dwLength); infoLength = dwLength; } else { infoLength = 0; DEBUG_PRINT(THRDINFO, ERROR, ("Failed to allocate %d bytes for info\n", dwLength )); } } //bCopyBuffer else { pInfo = lpBuffer; infoLength = dwLength; INET_ASSERT(dwLength || (WINHTTP_CALLBACK_STATUS_READ_COMPLETE == dwStatus)); } //!bCopyBuffer && !bConvertToUnicode } //lpBuffer != NULL else { pInfo = NULL; infoLength = 0; } // // we're about to call into the app. We may be in the context of an // async worker thread, and if the callback submits an async request // then we'll execute it synchronously. To avoid this, we will reset // the async worker thread indicator in the INTERNET_THREAD_INFO and // restore it when the app returns control to us. This way, if the // app makes an API request during the callback, on a handle that // has async I/O semantics, then we will simply queue it, and not // try to execute it synchronously // isAsyncWorkerThread = lpThreadInfo->IsAsyncWorkerThread; lpThreadInfo->IsAsyncWorkerThread = FALSE; BOOL bInCallback = lpThreadInfo->InCallback; lpThreadInfo->InCallback = TRUE; INET_ASSERT(!IsBadCodePtr((FARPROC)appCallback)); DEBUG_ENTER((DBG_THRDINFO, None, "(*callback)", "%#x, %#x, %s (%d), %#x [%#x], %d", lpThreadInfo->hObject, context, InternetMapStatus(dwStatus), dwStatus, pInfo, ((dwStatus == WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) || (dwStatus == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING)) ? (DWORD_PTR)*(LPHINTERNET)pInfo : (((dwStatus == WINHTTP_CALLBACK_STATUS_REQUEST_SENT) || (dwStatus == WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED) || (dwStatus == WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE)) ? *(LPDWORD)pInfo : 0), infoLength )); PERF_LOG(PE_APP_CALLBACK_START, dwStatus, lpThreadInfo->ThreadId, lpThreadInfo->hObject ); HINTERNET hObject = lpThreadInfo->hObject; LPVOID hObjectMapped = lpThreadInfo->hObjectMapped; appCallback(lpThreadInfo->hObject, context, dwStatus, pInfo, infoLength ); lpThreadInfo->hObject = hObject; lpThreadInfo->hObjectMapped = hObjectMapped; PERF_LOG(PE_APP_CALLBACK_END, dwStatus, lpThreadInfo->ThreadId, lpThreadInfo->hObject ); DEBUG_LEAVE(0); lpThreadInfo->InCallback = bInCallback; lpThreadInfo->IsAsyncWorkerThread = isAsyncWorkerThread; // // free the buffer // // We should free the memory only if we have done an ALLOCATE_FIXED_MEMORY in this function: if (pInfo != NULL && pInfo != lpBuffer && pInfo != buffer) { FREE_FIXED_MEMORY(pInfo); } } else { DEBUG_PRINT(THRDINFO, ERROR, ("%#x: callback = %#x, context = %#x\n", lpThreadInfo->hObject, appCallback, context )); // // if we're completing a request then we shouldn't be here - it // means we lost the context or callback address somewhere along the // way // // don't need the ASSERTS below. // It could also mean something as benign as the notification not being enabled: /* INET_ASSERT( dwStatus != WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE && dwStatus != WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE && dwStatus != WINHTTP_CALLBACK_STATUS_REQUEST_ERROR && dwStatus != WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE && dwStatus != WINHTTP_CALLBACK_STATUS_READ_COMPLETE ); */ #ifdef DEBUG if ( dwStatus == WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE || dwStatus == WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE || dwStatus == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR || dwStatus == WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE || dwStatus == WINHTTP_CALLBACK_STATUS_READ_COMPLETE ) { INET_ASSERT(appCallback != NULL); /* These are not valid asserts in winhttp. Contexts don't control whether callbacks are made or not. */ //INET_ASSERT(context != NULL); //INET_ASSERT(_InternetGetContext(lpThreadInfo) != NULL); } #endif } // // if the object is now invalid then the app closed the handle in // the callback, or from an external thread and the entire operation is cancelled // propagate this error back to calling code. // if (((HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->IsInvalidated()) { error = ERROR_WINHTTP_OPERATION_CANCELLED; } } else { // // this is catastrophic if the indication was async request completion // DEBUG_PUT(("InternetIndicateStatus(): no INTERNET_THREAD_INFO?\n")); } DEBUG_LEAVE(error); return error; } DWORD InternetSetLastError( IN DWORD ErrorNumber, IN LPSTR ErrorText, IN DWORD ErrorTextLength, IN DWORD Flags ) /*++ Routine Description: Copies the error text to the per-thread error buffer (moveable memory) Arguments: ErrorNumber - protocol-specific error code ErrorText - protocol-specific error text (from server). The buffer is NOT zero-terminated ErrorTextLength - number of characters in ErrorText Flags - Flags that control how this function operates: SLE_APPEND TRUE if ErrorText is to be appended to the text already in the buffer SLE_ZERO_TERMINATE TRUE if ErrorText must have a '\0' appended to it Return Value: DWORD Success - ERROR_SUCCESS Failure - Win32 error --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "InternetSetLastError", "%d, %.80q, %d, %#x", ErrorNumber, ErrorText, ErrorTextLength, Flags )); DWORD error; LPINTERNET_THREAD_INFO lpThreadInfo; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { error = _InternetSetLastError(lpThreadInfo, ErrorNumber, ErrorText, ErrorTextLength, Flags ); } else { DEBUG_PUT(("InternetSetLastError(): no INTERNET_THREAD_INFO\n")); error = ERROR_WINHTTP_INTERNAL_ERROR; } DEBUG_LEAVE(error); return error; } DWORD _InternetSetLastError( IN LPINTERNET_THREAD_INFO lpThreadInfo, IN DWORD ErrorNumber, IN LPSTR ErrorText, IN DWORD ErrorTextLength, IN DWORD Flags ) /*++ Routine Description: Sets or resets the last error text in an INTERNET_THREAD_INFO block Arguments: lpThreadInfo - pointer to INTERNET_THREAD_INFO ErrorNumber - protocol-specific error code ErrorText - protocol-specific error text (from server). The buffer is NOT zero-terminated ErrorTextLength - number of characters in ErrorText Flags - Flags that control how this function operates: SLE_APPEND TRUE if ErrorText is to be appended to the text already in the buffer SLE_ZERO_TERMINATE TRUE if ErrorText must have a '\0' appended to it Return Value: DWORD Success - ERROR_SUCCESS Failure - Win32 error --*/ { DEBUG_ENTER((DBG_THRDINFO, Dword, "_InternetSetLastError", "%#x, %d, %.80q, %d, %#x", lpThreadInfo, ErrorNumber, ErrorText, ErrorTextLength, Flags )); DWORD currentLength = 0; DWORD newTextLength; DWORD error; newTextLength = ErrorTextLength; // // if we are appending text, then account for the '\0' currently at the end // of the buffer (if it exists) // if (Flags & SLE_APPEND) { currentLength = lpThreadInfo->ErrorTextLength; if (currentLength != 0) { --currentLength; } newTextLength += currentLength; } if (Flags & SLE_ZERO_TERMINATE) { ++newTextLength; } // // expect success (and why not?) // error = ERROR_SUCCESS; // // allocate, grow or shrink the buffer to fit. The buffer is moveable. If // the buffer is being shrunk to zero size then NULL will be returned as // the buffer handle from ResizeBuffer() // lpThreadInfo->hErrorText = ResizeBuffer(lpThreadInfo->hErrorText, newTextLength, FALSE ); if (lpThreadInfo->hErrorText != NULL) { LPSTR lpErrorText; lpErrorText = (LPSTR)LOCK_MEMORY(lpThreadInfo->hErrorText); INET_ASSERT(lpErrorText != NULL); if (lpErrorText != NULL) { if (Flags & SLE_APPEND) { lpErrorText += currentLength; } memcpy(lpErrorText, ErrorText, ErrorTextLength); if (Flags & SLE_ZERO_TERMINATE) { lpErrorText[ErrorTextLength++] = '\0'; } // // the text should always be zero-terminated. We expect this in // InternetGetLastResponseInfo() // INET_ASSERT(lpErrorText[ErrorTextLength - 1] == '\0'); UNLOCK_MEMORY(lpThreadInfo->hErrorText); } else { // // real error occurred - failed to lock memory? // error = GetLastError(); } } else { INET_ASSERT(newTextLength == 0); newTextLength = 0; } // // set the error code and text length // lpThreadInfo->ErrorTextLength = newTextLength; lpThreadInfo->ErrorNumber = ErrorNumber; DEBUG_LEAVE(error); return error; } LPSTR InternetLockErrorText( VOID ) /*++ Routine Description: Returns a pointer to the locked per-thread error text buffer Arguments: None. Return Value: LPSTR Success - pointer to locked buffer Failure - NULL --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { HLOCAL lpErrorText; lpErrorText = lpThreadInfo->hErrorText; if (lpErrorText != (HLOCAL)NULL) { return (LPSTR)LOCK_MEMORY(lpErrorText); } } return NULL; } // //VOID //InternetUnlockErrorText( // VOID // ) // ///*++ // //Routine Description: // // Unlocks the per-thread error text buffer locked by InternetLockErrorText() // //Arguments: // // None. // //Return Value: // // None. // //--*/ // //{ // LPINTERNET_THREAD_INFO lpThreadInfo; // // lpThreadInfo = InternetGetThreadInfo(); // // // // // assume that if we locked the error text, there must be an // // INTERNET_THREAD_INFO when we come to unlock it // // // // INET_ASSERT(lpThreadInfo != NULL); // // if (lpThreadInfo != NULL) { // // HLOCAL hErrorText; // // hErrorText = lpThreadInfo->hErrorText; // // // // // similarly, there must be a handle to the error text buffer // // // // INET_ASSERT(hErrorText != NULL); // // if (hErrorText != (HLOCAL)NULL) { // UNLOCK_MEMORY(hErrorText); // } // } //} VOID InternetSetObjectHandle( IN HINTERNET hInternet, IN HINTERNET hInternetMapped ) /*++ Routine Description: Sets the hObject field in the INTERNET_THREAD_INFO structure so we can get at the handle contents, even when we're in a function that does not take the hInternet as a parameter Arguments: hInternet - handle of object we may need info from hInternetMapped - mapped handle of object we may need info from Return Value: None. --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { _InternetSetObjectHandle(lpThreadInfo, hInternet, hInternetMapped); } } HINTERNET InternetGetObjectHandle( VOID ) /*++ Routine Description: Just returns the hObject value stored in our INTERNET_THREAD_INFO Arguments: None. Return Value: HINTERNET Success - non-NULL handle value Failure - NULL object handle (may not have been set) --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; HINTERNET hInternet; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { hInternet = lpThreadInfo->hObject; } else { hInternet = NULL; } return hInternet; } HINTERNET InternetGetMappedObjectHandle( VOID ) /*++ Routine Description: Just returns the hObjectMapped value stored in our INTERNET_THREAD_INFO Arguments: None. Return Value: HINTERNET Success - non-NULL handle value Failure - NULL object handle (may not have been set) --*/ { LPINTERNET_THREAD_INFO lpThreadInfo; HINTERNET hInternet; lpThreadInfo = InternetGetThreadInfo(); if (lpThreadInfo != NULL) { hInternet = lpThreadInfo->hObjectMapped; } else { hInternet = NULL; } return hInternet; }
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
7308e633ac8e7b975aafc84e4cedcc06f85e4129
311bca02634b791b17a1cd6e2258d858c5ee8b70
/src/qt/coincontroldialog.cpp
0fa4a05cd9befc472e439984ff87caefea5daec5
[ "MIT" ]
permissive
ed-ro0t/C-Bit
65359b8eb1efbf3762d9c0375acd971e2352b38f
73bc5652564d344af6847eefde6d386225d4ad02
refs/heads/master
2020-03-09T06:57:08.468887
2017-09-04T00:40:41
2017-09-04T00:40:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,639
cpp
// Copyright (c) 2011-2015 The C-Bit Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coincontroldialog.h" #include "ui_coincontroldialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "txmempool.h" #include "walletmodel.h" #include "coincontrol.h" #include "init.h" #include "main.h" // For minRelayTxFee #include "wallet/wallet.h" #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <QApplication> #include <QCheckBox> #include <QCursor> #include <QDialogButtonBox> #include <QFlags> #include <QIcon> #include <QSettings> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> QList<CAmount> CoinControlDialog::payAmounts; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); bool CoinControlDialog::fSubtractFeeFromAmount = false; bool CCoinControlWidgetItem::operator<(const QTreeWidgetItem &other) const { int column = treeWidget()->sortColumn(); if (column == CoinControlDialog::COLUMN_AMOUNT || column == CoinControlDialog::COLUMN_DATE || column == CoinControlDialog::COLUMN_CONFIRMATIONS) return data(column, Qt::UserRole).toLongLong() < other.data(column, Qt::UserRole).toLongLong(); return QTreeWidgetItem::operator<(other); } CoinControlDialog::CoinControlDialog(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0), platformStyle(platformStyle) { ui->setupUi(this); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header #if QT_VERSION < 0x050000 ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); // change coin control first column label due Qt4 bug. // see https://github.com/bitcoin/bitcoin/issues/5716 ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290); ui->treeWidget->setColumnWidth(COLUMN_DATE, 110); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transaction hash in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT, Qt::DescendingOrder); // restore list mode and sortorder as a convenience feature QSettings settings; if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool()) ui->radioTreeMode->click(); if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder")) sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt())); } CoinControlDialog::~CoinControlDialog() { QSettings settings; settings.setValue("nCoinControlMode", ui->radioListMode->isChecked()); settings.setValue("nCoinControlSortColumn", sortColumn); settings.setValue("nCoinControlSortOrder", (int)sortOrder); delete ui; } void CoinControlDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel() && model->getAddressTableModel()) { updateView(); updateLabelLocked(); CoinControlDialog::updateLabels(model, this); } } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton* button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); // closes the dialog } // (un)select all void CoinControlDialog::buttonSelectAllClicked() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) coinControl->UnSelectAll(); // just to be sure CoinControlDialog::updateLabels(model, this); } // context menu void CoinControlDialog::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if(item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { copyTransactionHashAction->setEnabled(true); if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) { lockAction->setEnabled(false); unlockAction->setEnabled(true); } else { lockAction->setEnabled(true); unlockAction->setEnabled(false); } } else // this means click on parent node in tree mode -> disable all { copyTransactionHashAction->setEnabled(false); lockAction->setEnabled(false); unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT))); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH)); } // context menu action: lock coin void CoinControlDialog::lockCoin() { if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); updateLabelLocked(); } // context menu action: unlock coin void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); } // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, "")); } // copy label "Priority" to clipboard void CoinControlDialog::clipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // copy label "Dust" to clipboard void CoinControlDialog::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } // treeview: clicked on header void CoinControlDialog::headerSectionClicked(int logicalIndex) { if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing { ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } else { if (sortColumn == logicalIndex) sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); else { sortColumn = logicalIndex; sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) updateView(); } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) updateView(); } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) coinControl->UnSelect(outpt); else if (item->isDisabled()) // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else coinControl->Select(outpt); // selection changed -> update labels if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all CoinControlDialog::updateLabels(model, this); } // TODO: Remove this temporary qt5 fix after Qt5.3 and Qt5.4 are no longer used. // Fixed in Qt5.5 and above: https://bugreports.qt.io/browse/QTBUG-43473 #if QT_VERSION >= 0x050000 else if (column == COLUMN_CHECKBOX && item->childCount() > 0) { if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) item->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } #endif } // return human readable label for priority number QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEstimatePriority) { double dPriorityMedium = mempoolEstimatePriority; if (dPriorityMedium <= 0) dPriorityMedium = AllowFreeThreshold(); // not enough data, back to hard-coded if (dPriority / 1000000 > dPriorityMedium) return tr("highest"); else if (dPriority / 100000 > dPriorityMedium) return tr("higher"); else if (dPriority / 10000 > dPriorityMedium) return tr("high"); else if (dPriority / 1000 > dPriorityMedium) return tr("medium-high"); else if (dPriority > dPriorityMedium) return tr("medium"); else if (dPriority * 10 > dPriorityMedium) return tr("low-medium"); else if (dPriority * 100 > dPriorityMedium) return tr("low"); else if (dPriority * 1000 > dPriorityMedium) return tr("lower"); else return tr("lowest"); } // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { std::vector<COutPoint> vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else ui->labelLocked->setVisible(false); } void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) { if (!model) return; // nPayAmount CAmount nPayAmount = 0; bool fDust = false; CMutableTransaction txDummy; Q_FOREACH(const CAmount &amount, CoinControlDialog::payAmounts) { nPayAmount += amount; if (amount > 0) { CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0)); txDummy.vout.push_back(txout); if (txout.IsDust(::minRelayTxFee)) fDust = true; } } QString sPriorityLabel = tr("none"); CAmount nAmount = 0; CAmount nPayFee = 0; CAmount nAfterFee = 0; CAmount nChange = 0; unsigned int nBytes = 0; unsigned int nBytesInputs = 0; double dPriority = 0; double dPriorityInputs = 0; unsigned int nQuantity = 0; int nQuantityUncompressed = 0; bool fAllowFree = false; bool fWitness = false; std::vector<COutPoint> vCoinControl; std::vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); BOOST_FOREACH(const COutput& out, vOutputs) { // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer uint256 txhash = out.tx->GetHash(); COutPoint outpt(txhash, out.i); if (model->isSpent(outpt)) { coinControl->UnSelect(outpt); continue; } // Quantity nQuantity++; // Amount nAmount += out.tx->vout[out.i].nValue; // Priority dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); // Bytes CTxDestination address; int witnessversion = 0; std::vector<unsigned char> witnessprogram; if (out.tx->vout[out.i].scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { nBytesInputs += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4); fWitness = true; } else if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&address); if (keyid && model->getPubKey(*keyid, pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); if (!pubkey.IsCompressed()) nQuantityUncompressed++; } else nBytesInputs += 148; // in all error cases, simply assume 148 here } else nBytesInputs += 148; } // calculation if (nQuantity > 0) { // Bytes nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here if (fWitness) { // there is some fudging in these numbers related to the actual virtual transaction size calculation that will keep this estimate from being exact. // usually, the result will be an overestimate within a couple of satoshis so that the confirmation dialog ends up displaying a slightly smaller fee. // also, the witness stack size value value is a variable sized integer. usually, the number of stack items will be well under the single byte var int limit. nBytes += 2; // account for the serialized marker and flag bytes nBytes += nQuantity; // account for the witness byte that holds the number of stack items for each input. } // Priority double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget); dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority) sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority); // in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate if (CoinControlDialog::fSubtractFeeFromAmount) if (nAmount - nPayAmount == 0) nBytes -= 34; // Fee nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool); if (nPayFee > 0 && coinControl->nMinimumTotalFee > nPayFee) nPayFee = coinControl->nMinimumTotalFee; // Allow free? (require at least hard-coded threshold and default to that if no estimate) double dPriorityNeeded = std::max(mempoolEstimatePriority, AllowFreeThreshold()); fAllowFree = (dPriority >= dPriorityNeeded); if (fSendFreeTransactions) if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) nPayFee = 0; if (nPayAmount > 0) { nChange = nAmount - nPayAmount; if (!CoinControlDialog::fSubtractFeeFromAmount) nChange -= nPayFee; // Never create dust outputs; if we would, just add the dust to the fee. if (nChange > 0 && nChange < MIN_CHANGE) { CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0)); if (txout.IsDust(::minRelayTxFee)) { if (CoinControlDialog::fSubtractFeeFromAmount) // dust-change will be raised until no dust nChange = txout.GetDustThreshold(::minRelayTxFee); else { nPayFee += nChange; nChange = 0; } } } if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount) nBytes -= 34; } // after fee nAfterFee = nAmount - nPayFee; if (nAfterFee < 0) nAfterFee = 0; } // actually update labels int nDisplayUnit = BitcoinUnits::XCT; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity"); QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount"); QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee"); QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee"); QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes"); QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority"); QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput"); QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange"); // enable/disable "dust" and "change" dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0); // stats l1->setText(QString::number(nQuantity)); // Quantity l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes l6->setText(sPriorityLabel); // Priority l7->setText(fDust ? tr("yes") : tr("no")); // Dust l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change if (nPayFee > 0 && (coinControl->nMinimumTotalFee < nPayFee)) { l3->setText(ASYMP_UTF8 + l3->text()); l4->setText(ASYMP_UTF8 + l4->text()); if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount) l8->setText(ASYMP_UTF8 + l8->text()); } // turn labels "red" l5->setStyleSheet((nBytes >= MAX_FREE_TRANSACTION_CREATE_SIZE) ? "color:red;" : "");// Bytes >= 1000 l6->setStyleSheet((dPriority > 0 && !fAllowFree) ? "color:red;" : ""); // Priority < "medium" l7->setStyleSheet((fDust) ? "color:red;" : ""); // Dust = "yes" // tool tips QString toolTip1 = tr("This label turns red if the transaction size is greater than 1000 bytes.") + "<br /><br />"; toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000))) + "<br /><br />"; toolTip1 += tr("Can vary +/- 1 byte per input."); QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />"; toolTip2 += tr("This label turns red if the priority is smaller than \"medium\".") + "<br /><br />"; toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000))); QString toolTip3 = tr("This label turns red if any recipient receives an amount smaller than the current dust threshold."); // how many satoshis the estimated fee can vary per byte we guess wrong double dFeeVary; if (payTxFee.GetFeePerK() > 0) dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), payTxFee.GetFeePerK()) / 1000; else { dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), mempool.estimateSmartFee(nTxConfirmTarget).GetFeePerK()) / 1000; } QString toolTip4 = tr("Can vary +/- %1 satoshi(s) per input.").arg(dFeeVary); l3->setToolTip(toolTip4); l4->setToolTip(toolTip4); l5->setToolTip(toolTip1); l6->setToolTip(toolTip2); l7->setToolTip(toolTip3); l8->setToolTip(toolTip4); dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip()); dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip()); dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip()); dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip()); dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip()); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip()); // Insufficient funds QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds"); if (label) label->setVisible(nChange < 0); } void CoinControlDialog::updateView() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel()) return; bool treeMode = ui->radioTreeMode->isChecked(); ui->treeWidget->clear(); ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget); std::map<QString, std::vector<COutput> > mapCoins; model->listCoins(mapCoins); BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) { CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); if (treeMode) { // wallet address ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); } CAmount nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; BOOST_FOREACH(const COutput& out, coins.second) { int nInputSize = 0; nSum += out.tx->vout[out.i].nValue; nChildren++; CCoinControlWidgetItem *itemOutput; if (treeMode) itemOutput = new CCoinControlWidgetItem(itemWalletAddress); else itemOutput = new CCoinControlWidgetItem(ui->treeWidget); itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString()); // if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&outputAddress); if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes) } // label if (!(sAddress == sWalletAddress)) // change { // tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if (sLabel.isEmpty()) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->vout[out.i].nValue)); // padding so that sorting works correctly // date itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime())); // confirmations itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth)); itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth)); // priority double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10 itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority)); itemOutput->setData(COLUMN_PRIORITY, Qt::UserRole, QVariant((qlonglong)dPriority)); dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); nInputSum += nInputSize; // transaction hash uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex())); // vout index itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); // disable locked coins if (model->isLockedCoin(txhash, out.i)) { COutPoint outpt(txhash, out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); } // set checkbox if (coinControl->IsSelected(COutPoint(txhash, out.i))) itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } // amount if (treeMode) { dPrioritySum = dPrioritySum / (nInputSum + 78); itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)nSum)); itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum, mempoolEstimatePriority)); itemWalletAddress->setData(COLUMN_PRIORITY, Qt::UserRole, QVariant((qlonglong)dPrioritySum)); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); }
[ "crzybluebilly@mailinator.com" ]
crzybluebilly@mailinator.com
cf6f46a0dccf27171e9256a24065b50ab1b0d85d
eb1360bb9c19fad69f0e3d95a49aba3e9a915aac
/LIB/argv_259.cpp
1e5086fb39259b2d6ca6dfbf5cd5b4f5feb9f53b
[]
no_license
tybins99/CRYPTANALYSIS.ElGammal_IndexCalculus
3198a45e0fec21ba5d47404ddfdbb3dc16cf6be6
67e7eba85a59b6403c84d088fd58cbebbb50ff5a
refs/heads/master
2021-05-11T10:18:27.548769
2018-01-19T08:47:06
2018-01-19T08:47:06
118,099,519
3
0
null
null
null
null
UTF-8
C++
false
false
3,521
cpp
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@ FILE: argv_259.cpp // @@ // @@ DESCRIPTION: // @@ This argv_1396 contains the argv_1139 structure and // @@ function that are necessary for the plugins // @@ to work. // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@ includes // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #include "../LIB/argv_326.hpp" // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@ // @@ CLASS : - // @@ // @@ FUNCTION : argv_2312 // @@ // @@ INPUT : // @@ _dest: char * : the destination argv_771 where to copy the string // @@ _src: char * : the source argv_771 where to copy the string from // @@ _size: argv_3864 : the size of the string to copy // @@ // @@ OUTPUT : none // @@ // @@ IO : none // @@ // @@ RETURN VALUE : none // @@ // @@ DISCLOSURE : - // @@ // @@ DESCRIPTION : // @@ This function just permit to copy the string '_src' to the // @@ string '_dest' assuming that the '_src' size is '_size' // @@ and that the '_dest' is long enough to receive the '_src' string. // @@ // @@ CONTRACT : none // @@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void argv_2312 (char * _dest, char * _src, argv_3864 _size) { argv_3864 i=0; while ((i < _size) && (_src[i] != '\0')) { _dest[i] = _src[i]; i++; } // don't forget the string's argv_3739 if (i < _size) { _dest[i] = '\0'; } else { _dest[_size - 1] = '\0'; } } // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@ // @@ CLASS : - // @@ // @@ FUNCTION : argv_1419 // @@ // @@ INPUT : // @@ _type: argv_3864: argv_3842 of the argv_1396 whose readable argv_3842 is to be retrieved. // @@ // @@ OUTPUT : // @@ _str_type: char *: destination string where the argv_3402 of the argv_2253 // @@ is to be saved up (allocated by the caller). // @@ // @@ IO : none // @@ // @@ RETURN VALUE : none // @@ // @@ DISCLOSURE : - // @@ // @@ DESCRIPTION : // @@ This function permits to argv_2253 the readable argv_1396 argv_3842 associated // @@ with the '_type' argv_1396 argv_3842. // @@ The argv_3402 is stored into a string that must have been allocated // @@ by the caller prior to this call, it's length must be MAX_PATH_PLUGIN // @@ // @@ Notice that if the '_type' parameter is not a valid argv_1396 argv_3842, // @@ then "<UNKNOWN FILE TYPE>" is saved into the '_str_type' argv_3402 // @@ parameter. // @@ // @@ CONTRACT : none // @@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void argv_1419 (argv_3864 _type, char * _str_type) { switch (_type) { case argv_1435 : argv_2312 (_str_type, "argv_1435", MAX_PATH_PLUGIN); break; case argv_1422 : argv_2312 (_str_type, "argv_1422", MAX_PATH_PLUGIN); break; case argv_1441 : argv_2312 (_str_type, "argv_1441", MAX_PATH_PLUGIN); break; case argv_1424 : argv_2312 (_str_type, "argv_1424", MAX_PATH_PLUGIN); break; case argv_1434 : argv_2312 (_str_type, "argv_1434", MAX_PATH_PLUGIN); break; case argv_1439 : argv_2312 (_str_type, "argv_1439", MAX_PATH_PLUGIN); break; default : argv_2312 (_str_type, "<UNKNOWN FILE TYPE>", MAX_PATH_PLUGIN); } } // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@ end of argv_1396 // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
[ "flegardien@kertel.com" ]
flegardien@kertel.com
a8bb16fc643df27ecdaba1edf6a6c40a9139881a
36184239a2d964ed5f587ad8e83f66355edb17aa
/.history/hw3/ElectoralMap_20211021113257.cpp
3ead4b3ddbfd0b40571f3b8741ac883c095cec1d
[]
no_license
xich4932/csci3010
89c342dc445f5ec15ac7885cd7b7c26a225dae3e
23f0124a99c4e8e44a28ff31ededc42d9f326ccc
refs/heads/master
2023-08-24T04:03:12.748713
2021-10-22T08:22:58
2021-10-22T08:22:58
415,140,207
0
0
null
null
null
null
UTF-8
C++
false
false
17,573
cpp
#include<iostream> #include<map> #include<set> #include<random> #include<time.h> #include<cmath> #include<stdlib.h> #include"ElectoralMap.h" #define num_district 3 #define num_enum 4 #define one_person 1 //int Candidate::id = 0; int ElectoralMap::count_district = 0; int Election::ids = 0; std::vector<int> Election::party_one_active = {}; std::vector<int> Election::party_two_active = {}; std::vector<int> Election::party_three_active = {}; //std::vector<int> Election::stored_idx_each; int Candidate::party_one_candidate = 0; int Candidate::party_two_candidate = 0; int Candidate::party_three_candidate = 0; int Election::active_party[3] = {0}; Candidate::Candidate(){ ; } void Candidate::plus_vote(District dis, int count){ votes[dis] += count; } Candidate::Candidate(int given_id, party party_name, std::string candidate_name){ id_candidate = given_id; party_affiliation = party_name; name = candidate_name; std::map<int, District> temp_map = ElectoralMap::getInstance().get_map(); for(auto i = temp_map.begin(); i != temp_map.end(); i++){ votes.insert(std::pair<District, int>(i->second, 0)); } } int Candidate::get_ids(){ return id_candidate; } District::District(){ for(enum party temp = party::one; temp <= party::none ; temp = (party)(temp + 1)){ map_party.insert(std::pair<party,int>(temp, 0)); //map_party.insert(std::pair<party,int>(temp, range_random(engine))); } //std::uniform_int_distribution<unsigned> range_random1(5,29); square_mile = 99; id = 99; } District::District(int given_id){ // std::default_random_engine engine; // std::uniform_int_distribution<unsigned> range_random(0,9); for(enum party temp = party::one; temp <= party::none ; temp = (party)(temp + 1)){ map_party.insert(std::pair<party,int>(temp, rand()%9)); //map_party.insert(std::pair<party,int>(temp, range_random(engine))); } // std::uniform_int_distribution<unsigned> range_random1(5,29); square_mile = rand()%25+5; id = given_id; } party District::get_max(){ enum party ret; int max = 0; int old_ = max; for(auto i = map_party.begin(); i != map_party.end(); i++){ max = std::max(max, i->second); if(old_ != max){ old_ = max; ret = i->first; } } return ret; } int District::get_sum_constitutent(){ int sum = 0; for(enum party temp = party::one; temp <= party::none; temp = (party)(temp + 1)){ sum += map_party[temp]; } return sum; } int District::get_sum_constitutent_exclude_none(party exclude_one){ int sum = 0; for(enum party temp = party::one; temp < party::none; temp = (party)(temp + 1)){ if(map_party[temp] == exclude_one) continue; // std::cout << temp <<" "; sum += map_party[temp]; } std::cout << "sum:" << sum << std::endl; return sum; } void District::change_party(party increase_party, party decrease_party, int num){ //debug: assume changing number is always smaller than the actual number if(num > map_party[decrease_party]){ map_party[increase_party] += map_party[decrease_party]; map_party[decrease_party] = 0; }else{ map_party[increase_party] += num; map_party[decrease_party] -= num; } }; ElectoralMap::ElectoralMap(){ for(int i = 0; i < num_district; i++){ District *temp = new District(count_district+1); map.insert(std::pair<int, District>(count_district+1, *temp)); count_district ++; } } std::string stringifyEnum(party one){ const std::string str[4] = {"party one", "party two", "party three", "party none"}; for(enum party temp = party::one; temp <= party::none; temp = (party)(temp+1)){ if(temp == one) return str[(int)temp]; } return ""; } std::ostream & operator<<(std::ostream& os, District print_district){ std::cout << "district: "<< print_district.id <<":"<< std::endl; std::cout << "area: "<< print_district.square_mile << std::endl; for(enum party print_enum = party::one; print_enum <= party::none; print_enum = (party)(print_enum+1)){ std::cout << stringifyEnum(print_enum) <<": "<< print_district.map_party[print_enum] <<" "; } std::cout << std::endl; return os; } std::ostream & operator<<(std::ostream& os, ElectoralMap print_map){ for(auto i = print_map.map.begin(); i != print_map.map.end(); i++){ std::cout << i->second << std::endl; } return os; } void ask_name(std::string &name){ std::cout << "What is their name?"<<std::endl; getline(std::cin, name); } Election::Election(){ std::string choice; for(enum party party_name = party::one; party_name < party::none; party_name = (party)(party_name+1)){ while(1){ std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl; getline(std::cin, choice); if(choice == "y"){ std::string candidate_name; ask_name(candidate_name); Candidate temp(ids+1, party_name, candidate_name); candidate_.insert(std::pair<int, Candidate>(ids + 1, temp)); ids ++; if(party_name == 0){ party_one_active.push_back(ids); }else if(party_name == 1){ party_two_active.push_back(ids); }else if(party_name == 2){ party_three_active.push_back(ids); } active_party[party_name] ++; continue; } if(choice == "n") break; //continue; //when user input other choice, keep asking } } } /* void Election::register_candidate(){ std::string choice; for(enum party party_name; party_name <= party::none; party_name = (party)(party_name+1)){ while(1){ std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl; getline(std::cin, choice); if(choice == "y"){ std::string candidate_name; ask_name(candidate_name); Candidate temp(ids+1, party_name, candidate_name); candidate_.push_back(temp); ids ++; if(party_name == 0){ party_one_active.push_back(ids); }else if(party_name == 1){ party_two_active.push_back(ids); }else if(party_name == 2){ party_three_active.push_back(ids); } active_party[party_name] ++; continue; } if(choice == "n") break; //continue; //when user input other choice, keep asking } } } */ Candidate* Election::who_campaigning(){ std::string choice; while ((1)) { std::cout << "Which candidate is campaigning (id) (0 to stop) ?" <<std::endl; getline(std::cin, choice); if(choice == "0") return NULL; if(std::stoi(choice) >= ids){ std::cout << "index out of range"<< std::endl; continue; } break; //jump out of loop if id is availble } return &candidate_[std::stoi(choice)]; //int campaign_id = stoi(choice); //std::cout << ElectoralMap::getInstance << std::endl; // //int campaign_district = stoi(choice); //std::cout << candidate_[campaign_id].get_name() << " is campaigning in district "<< campaign_district << std::endl; } //return -1, select to quie int Election::where_campaigning(){ std::string choice; while ((1)) { std::cout << "Where is this candidate campaigning (id) (0 to stop) ?" <<std::endl; getline(std::cin, choice); if(choice == "0") return -1; if(std::stoi(choice) >= num_district){ std::cout << "index out of range"<< std::endl; continue; } break; //jump out of loop if id is availble } return std::stoi(choice); } Candidate Election::get_candidate(int id){ return candidate_[id]; } void Election::voting(){ std::map<party, int> sum_each_party; sum_each_party.insert(std::pair<party, int> (party::one, 0)); sum_each_party.insert(std::pair<party, int> (party::two, 0)); sum_each_party.insert(std::pair<party, int> (party::three,0)); std::vector<std::vector<int>> store_id_each = {party_one_active, party_two_active, party_three_active}; ElectoralMap vote_map = ElectoralMap::getInstance(); std::map<int, District> vote_district = ElectoralMap::getInstance().get_map(); int turn_candidate = 0; for(int d = 1; d <= num_district; d++){ for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){ if(active_party[party_name]){ int get_voted = rand()%store_id_each[party_name].size(); candidate_[party_one_active[get_voted]].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name)); //sum_each_party[party_name] += vote_district[d].get_constituent(party_name); }else if(party_name == party::none){ party none_cantitutent = vote_district[d+1].get_max(); //if none constitutent is 9, should i count them as one or do random choice for each person if(party_name == party::none){ //the majority constituent is still none ; }else if(!active_party[none_cantitutent] || (!active_party[party_name] && party_name != party::none)){ // when the majority constituent has no candidate int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name)); } }else{ int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name)); } } } } void District::convert_constituent(party increase_party, party decrease_party, int num){ //if no people in the party, do nothing if(!map_party[decrease_party]) return; map_party[increase_party] += num; map_party[decrease_party] -= num; } party randomlyPickEnum(){ int i = rand() % 3; if(i == 0) return party::one; if(i == 1) return party::two; if(i == 2) return party::three; } void Election::converting(District * campaign_district, Candidate * this_candidate){ int sum_constituent = campaign_district->get_constituent(this_candidate->get_party()); int sum_residents = campaign_district->get_sum_constitutent_exclude_none(this_candidate->get_party()); double possibility = ((sum_constituent+1)*2/sum_residents)*((sum_constituent+1)*2/campaign_district->get_square_mile()); std::cout <<"area: "<< campaign_district->get_square_mile() << std::endl; std::cout <<"sum_constituent: "<< sum_constituent << std::endl; std::cout <<"poss:"<< possibility << std::endl; double p_success = std::min(100.00,possibility ); double p_extra_success = 0.1 * p_success; int this_rand = rand()%100; std::cout << "Chances to convert: " << p_success << std::endl; std::cout << "Chances to convert from another party: "<< p_extra_success << std::endl; //convert only people in party none int convert_one = 0; if(campaign_district->get_constituent(party::none) > 0){ if(p_success > this_rand){ convert_one ++; campaign_district->convert_constituent(this_candidate->get_party(), party::none, one_person); } } if(p_extra_success > this_rand){ enum party converted = randomlyPickEnum(); while(converted == this_candidate->get_party()){ converted = randomlyPickEnum(); } campaign_district->convert_constituent(this_candidate->get_party(), converted, one_person); convert_one++; } std::cout << "Congrats, you have converted someone from none to one!" << std::endl; } void RepresentativeELection::calculate_vote(){ std::map<int ,District> this_district = ElectoralMap::getInstance().get_map(); int sum_all_constituent = 0; for(auto i = this_district.begin(); i != this_district.end(); i++){ sum_all_constituent += i->second.get_sum_constitutent(); } int total_district = this_district.size(); for(auto i = this_district.begin(); i != this_district.end(); i++){ vote_per_district.push_back(std::floor(i->second.get_sum_constitutent() * 1.0 / sum_all_constituent * total_district)); } } RepresentativeELection::RepresentativeELection(){ std::string choice; for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){ while(1){ std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl; getline(std::cin, choice); if(choice == "y"){ std::string candidate_name; ask_name(candidate_name); Candidate temp(ids+1, party_name, candidate_name); candidate_.insert(std::pair<int, Candidate>(ids + 1, temp)); ids ++; if(party_name == 0){ party_one_active.push_back(ids); }else if(party_name == 1){ party_two_active.push_back(ids); }else if(party_name == 2){ party_three_active.push_back(ids); } active_party[party_name] ++; continue; } if(choice == "n") break; //continue; //when user input other choice, keep asking } } //register_candidate(); } bool Election::check_end(){ return false; /* if(!condition) return true; return false; */ } void Election::report_win(){ //int sum_votes[num_enum - 1] = { 0, 0, 0}; std::map<int, District> print_map = ElectoralMap::getInstance().get_map(); for(auto i = print_map.begin(); i != print_map.end(); i++){ std::cout << "Distrcit"<< i->second.get_id() << std::endl; for(int c = 1; c <= ids; c++){ // std::cout << candidate_[c+1].get_vote().get_party(*i) << std::endl; } } /* std::map<int, Candidate> find_max; for(auto i = candidate_.begin(); i != candidate_.end(); i++){ find_max.insert(std::pair<int, Candidate>(i->get_vote(), *i)); } */ std::cout << "Congratulations, "<< candidate_.rbegin()->second.get_name() <<", you've won!"<<std::endl; } int party_to_int(enum party temp){ if(temp == party::one) return 0; if(temp == party::two) return 1; if(temp == party::three) return 2; return 3; //not gonna happen } party District::get_max_party(){ enum party max = party::one; int max_num = map_party[max]; for(enum party temp = party::one; temp <= party::none; temp = (party)(temp+1)){ if(map_party[temp] > max_num){ max_num = map_party[temp]; max = temp; } } return max; } void RepresentativeELection::voting(){ std::map<party, int> sum_each_party; sum_each_party.insert(std::pair<party, int> (party::one, 0)); sum_each_party.insert(std::pair<party, int> (party::two, 0)); sum_each_party.insert(std::pair<party, int> (party::three,0)); std::vector<std::vector<int>> store_id_each = {party_one_active, party_two_active, party_three_active}; // ElectoralMap vote_map = ElectoralMap::getInstance(); std::map<int, District> vote_district = ElectoralMap::getInstance().get_map(); calculate_vote(); for(int d = 1; d <= num_district; d++){ for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){ if(active_party[party_name]){ int get_voted = rand()%store_id_each[party_name].size(); candidate_[party_one_active[get_voted]].plus_vote(vote_district[d], vote_per_district[d]); //sum_each_party[party_name] += vote_district[d].get_constituent(party_name); }else if(party_name == party::none){ party none_cantitutent = vote_district[d+1].get_max(); //if none constitutent is 9, should i count them as one or do random choice for each person if(party_name == party::none){ //the majority constituent is still none ; }else if(!active_party[none_cantitutent] || (!active_party[party_name] && party_name != party::none)){ // when the majority constituent has no candidate int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d], vote_per_district[d]); } }else{ int sum = 0; for(int i = 0; i < 3; i++) sum += active_party[i]; int get_voted = rand()%sum; candidate_[get_voted].plus_vote(vote_district[d], vote_per_district[d]); } } } }
[ "70279863+xich4932@users.noreply.github.com" ]
70279863+xich4932@users.noreply.github.com
8e623a6c00e2d477f05ce0706db72111fddec676
5bcedc9c0b9c92f795cd04927bc1b752b8bbe6f3
/gtkmm_examples/src/entry/examplewindow.h
46c50f328622d993d749a883b820ad133ea9c681
[ "FSFAP" ]
permissive
hamedobaidy/gtkmm_eclipse_examples
8d466523b8e680b3d77bf0026320321aa56a22e3
379c7b8e7640aef67ec189b10c54442251c2a2b8
refs/heads/master
2021-01-20T15:33:35.355311
2015-09-15T15:52:20
2015-09-15T15:52:20
38,481,378
0
0
null
null
null
null
UTF-8
C++
false
false
601
h
/* * examplewindow.h * * Created on: Jun 30, 2015 * Author: hamed */ #ifndef EXAMPLEWINDOW_H_ #define EXAMPLEWINDOW_H_ #include <gtkmm.h> class ExampleWindow : public Gtk::Window { public: ExampleWindow(); virtual ~ExampleWindow(); protected: //Signal handlers: void on_checkbox_editable_toggled(); void on_checkbox_visibility_toggled(); void on_button_close(); //Child widgets: Gtk::Box m_HBox; Gtk::Box m_VBox; Gtk::Entry m_Entry; Gtk::Button m_Button_Close; Gtk::CheckButton m_CheckButton_Editable, m_CheckButton_Visible; }; #endif /* EXAMPLEWINDOW_H_ */
[ "hamed.obaidy@gmail.com" ]
hamed.obaidy@gmail.com
aa7023a5b51c1f9dede6eac16d6f2b343b9f3591
9c2583e2ecd85ed332e704c81295119d4bb7f9d8
/src/protocol.h
aa1b7c3141d5bfca271c31faaa1f34f9c74c8bb3
[ "MIT" ]
permissive
bata-bta/BATA-Development
3a2735b515a6f939f80743f07323be8e1d58cbb0
8306a05d6d4440312241a09b8723fa4d38566606
refs/heads/master
2021-01-19T04:40:56.668743
2016-10-07T05:54:32
2016-10-07T05:54:32
87,386,130
0
1
null
2017-04-06T04:26:34
2017-04-06T04:26:34
null
UTF-8
C++
false
false
3,719
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef __cplusplus # error This header can only be compiled as C++. #endif #ifndef __INCLUDED_PROTOCOL_H__ #define __INCLUDED_PROTOCOL_H__ #include "serialize.h" #include "netbase.h" #include <string> #include "uint256.h" extern bool fTestNet; static inline unsigned short GetDefaultPort(const bool testnet = fTestNet) { return testnet ? 33813 : 5784; } extern unsigned char pchMessageStart[4]; /** Message header. * (4) message start. * (12) command. * (4) size. * (4) checksum. */ class CMessageHeader { public: CMessageHeader(); CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn); std::string GetCommand() const; bool IsValid() const; IMPLEMENT_SERIALIZE ( READWRITE(FLATDATA(pchMessageStart)); READWRITE(FLATDATA(pchCommand)); READWRITE(nMessageSize); READWRITE(nChecksum); ) // TODO: make private (improves encapsulation) public: enum { MESSAGE_START_SIZE=sizeof(::pchMessageStart), COMMAND_SIZE=12, MESSAGE_SIZE_SIZE=sizeof(int), CHECKSUM_SIZE=sizeof(int), MESSAGE_SIZE_OFFSET=MESSAGE_START_SIZE+COMMAND_SIZE, CHECKSUM_OFFSET=MESSAGE_SIZE_OFFSET+MESSAGE_SIZE_SIZE, HEADER_SIZE=MESSAGE_START_SIZE+COMMAND_SIZE+MESSAGE_SIZE_SIZE+CHECKSUM_SIZE }; char pchMessageStart[MESSAGE_START_SIZE]; char pchCommand[COMMAND_SIZE]; unsigned int nMessageSize; unsigned int nChecksum; }; /** nServices flags */ enum { NODE_NETWORK = (1 << 0), NODE_BLOOM = (1 << 1), }; /** A CService with information about it as peer */ class CAddress : public CService { public: CAddress(); explicit CAddress(CService ipIn, uint64 nServicesIn=NODE_NETWORK); void Init(); IMPLEMENT_SERIALIZE ( CAddress* pthis = const_cast<CAddress*>(this); CService* pip = (CService*)pthis; if (fRead) pthis->Init(); if (nType & SER_DISK) READWRITE(nVersion); if ((nType & SER_DISK) || (nVersion >= CADDR_TIME_VERSION && !(nType & SER_GETHASH))) READWRITE(nTime); READWRITE(nServices); READWRITE(*pip); ) void print() const; // TODO: make private (improves encapsulation) public: uint64 nServices; // disk and network only unsigned int nTime; // memory only int64 nLastTry; }; /** inv message data */ class CInv { public: CInv(); CInv(int typeIn, const uint256& hashIn); CInv(const std::string& strType, const uint256& hashIn); IMPLEMENT_SERIALIZE ( READWRITE(type); READWRITE(hash); ) friend bool operator<(const CInv& a, const CInv& b); bool IsKnownType() const; const char* GetCommand() const; std::string ToString() const; void print() const; // TODO: make private (improves encapsulation) public: int type; uint256 hash; }; enum { MSG_TX = 1, MSG_BLOCK, // Nodes may always request a MSG_FILTERED_BLOCK in a getdata, however, // MSG_FILTERED_BLOCK should not appear in any invs except as a part of getdata. MSG_FILTERED_BLOCK, }; #endif // __INCLUDED_PROTOCOL_H__
[ "admin@bata.money" ]
admin@bata.money
2244ff875c22f13b18688ece98860d48c051bcb1
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/110/147/CWE675_Duplicate_Operations_on_Resource__fopen_82_bad.cpp
68424b9b7c62585e81a6b95617330a775c96e1e8
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
964
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE675_Duplicate_Operations_on_Resource__fopen_82_bad.cpp Label Definition File: CWE675_Duplicate_Operations_on_Resource.label.xml Template File: sources-sinks-82_bad.tmpl.cpp */ /* * @description * CWE: 675 Duplicate Operations on Resource * BadSource: fopen Open and close a file using fopen() and flose() * GoodSource: Open a file using fopen() * Sinks: * GoodSink: Do nothing * BadSink : Close the file * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE675_Duplicate_Operations_on_Resource__fopen_82.h" namespace CWE675_Duplicate_Operations_on_Resource__fopen_82 { void CWE675_Duplicate_Operations_on_Resource__fopen_82_bad::action(FILE * data) { /* POTENTIAL FLAW: Close the file in the sink (it may have been closed in the Source) */ fclose(data); } } #endif /* OMITBAD */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
629c2c3bb5f48d978507f68195f82d5a9638b6d3
ba4db75b9d1f08c6334bf7b621783759cd3209c7
/src_main/common/xsi/5.1/ftk/ImageClip.h
9ae6d64771f422363019c2e2ed7c9f4d7bcc3190
[]
no_license
equalent/source-2007
a27326c6eb1e63899e3b77da57f23b79637060c0
d07be8d02519ff5c902e1eb6430e028e1b302c8b
refs/heads/master
2020-03-28T22:46:44.606988
2017-03-27T18:05:57
2017-03-27T18:05:57
149,257,460
2
0
null
2018-09-18T08:52:10
2018-09-18T08:52:09
null
UTF-8
C++
false
false
2,264
h
/******************************************************************************\ * * File: ImageClip.h * Creation date: January 15, 2002 17:31 * Author: ClassBuilder * XXXX * Purpose: Declaration of class 'ImageClip' * * Modifications: @INSERT_MODIFICATIONS(* ) * January 23, 2002 10:59 Frederic O'Reilly * Added method 'StartTime' * Added method 'RepeatType' * Added method 'RemoveImage' * Added method 'Reference' * Added method 'Rate' * Added method 'NbImages' * Added method 'Images' * Added method 'EndTime' * Added method 'AddImage' * Added method 'CSLImageClip' * Added member 'm_pImages' * Added member 'm_pRepeatType' * Added member 'm_pRate' * Added member 'm_pEndTime' * Added member 'm_pStartTime' * Added member 'm_pReference' * Updated inheritance 'CSLTemplate' * * Copyright 2002, XXXXX * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. * \******************************************************************************/ #ifndef _IMAGECLIP_H #define _IMAGECLIP_H #include "Template.h" // Forward declaration class CSLTexture2D; //! Class not implemented class CSLImageClip : public CSLTemplate { //@START_USER2 //@END_USER2 // Members private: CSLTexture2D* m_pReference; CSLFloatProxy* m_pStartTime; CSLFloatProxy* m_pEndTime; CSLFloatProxy* m_pRate; CSLIntProxy* m_pRepeatType; CSIBCArray<CSLStringProxy *> m_pImages; protected: public: // Methods private: protected: public: CSLImageClip(CSLScene* in_pScene, CSLModel *in_pModel, CdotXSITemplate* in_pTemplate); virtual ~CSLImageClip(); CSLStringProxy* AddImage(); CSLFloatProxy* EndTime() const; CSLStringProxy** Images() const; SI_Int* NbImages() const; CSLFloatProxy* Rate() const; CSLTexture2D* Reference() const; SI_Error RemoveImage(); CSLIntProxy* RepeatType() const; CSLFloatProxy* StartTime() const; }; #endif #ifdef CB_INLINES #ifndef _IMAGECLIP_H_INLINES #define _IMAGECLIP_H_INLINES //@START_USER3 //@END_USER3 #endif #endif
[ "sean@csnxs.uk" ]
sean@csnxs.uk
efe493a8574453439de10fc7316957ac5e03b5fc
c8e6f194669663e0e2748dbc56a7172b9ea008f7
/.localhistory/GUI/1471618442$MainForm.h
3052a92b0f5944f864754fad2ca4fa522174da50
[]
no_license
itreppert/GUI
1922e781d804d17cb8008197fdbfa11576077618
9ca4ea0531eb45a4462a4d8278aec67f8c2705ef
refs/heads/master
2020-04-17T20:29:10.965471
2016-09-06T13:18:01
2016-09-06T13:18:01
67,501,677
0
0
null
null
null
null
ISO-8859-1
C++
false
false
73,826
h
#pragma once #include "Test.h" namespace GUI { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Zusammenfassung für MainForm /// </summary> public ref class MainForm : public System::Windows::Forms::Form { public: MainForm(void) { InitializeComponent(); step = 0; richTextBox1->LoadFile("d:\\Dokument.rtf"); points = gcnew ArrayList; points->Add(lastPoint); } protected: /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> ~MainForm() { if (components) { delete components; } } private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::Panel^ panel1; private: System::Windows::Forms::Button^ cmdChangeFormColor; private: System::Windows::Forms::TabControl^ tabControl1; private: System::Windows::Forms::TabPage^ tabPage1; private: System::Windows::Forms::TabPage^ tabPage2; private: System::Windows::Forms::TabPage^ tabPage3; private: System::Windows::Forms::Button^ btnChangeTab; private: System::Windows::Forms::Panel^ panel2; private: System::Windows::Forms::CheckBox^ checkBox1; private: System::Windows::Forms::Button^ btnCheckbox; private: System::Windows::Forms::RadioButton^ radioButton3; private: System::Windows::Forms::RadioButton^ radioButton2; private: System::Windows::Forms::RadioButton^ radioButton1; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::Button^ btnRadioButton; private: System::Windows::Forms::ComboBox^ cmbBlubb; private: System::Windows::Forms::Button^ btnComboboxValue; private: System::Windows::Forms::Button^ btnComboAddItem; private: System::Windows::Forms::Button^ btnComboremoveItem; private: System::Windows::Forms::Button^ btnComboInsert; private: System::Windows::Forms::ListBox^ listBox1; private: System::Windows::Forms::TextBox^ txtAnswers; private: System::Windows::Forms::TextBox^ txtQuestions; Test^ t; int progress; String^ antwort1; String^ antwort2; String^ antwort3; String^ antwort4; private: System::Windows::Forms::Button^ btnNextStep; int step; private: System::Windows::Forms::Button^ btnChangeFromAnotherClass; private: System::Windows::Forms::MaskedTextBox^ maskedTextBox1; private: System::Windows::Forms::NumericUpDown^ numericUpDown1; private: System::Windows::Forms::Panel^ panel3; private: System::Windows::Forms::PictureBox^ pictureBox1; private: System::Windows::Forms::Button^ btnStartProgress; private: System::Windows::Forms::ProgressBar^ progressBar1; private: System::Windows::Forms::RichTextBox^ richTextBox1; private: System::Windows::Forms::Timer^ timer1; private: System::Windows::Forms::TrackBar^ trackBar1; private: System::Windows::Forms::MenuStrip^ menuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem2; private: System::Windows::Forms::ToolStripSeparator^ toolStripSeparator1; private: System::Windows::Forms::ToolStripMenuItem^ mnuSaveFileDialog; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem3; private: System::Windows::Forms::OpenFileDialog^ openFileDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuFarben; private: System::Windows::Forms::ColorDialog^ colorDialog1; private: System::Windows::Forms::SaveFileDialog^ saveFileDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuSchriftart; private: System::Windows::Forms::FontDialog^ fontDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuRichtextBox; private: System::Windows::Forms::ToolStripMenuItem^ mnuFolderBrowser; private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1; private: System::Windows::Forms::ContextMenuStrip^ contextMenuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ mnuClearText; private: System::Windows::Forms::ToolStripMenuItem^ mnuOpen; private: System::Windows::Forms::ToolStripMenuItem^ mnuSave; private: System::Windows::Forms::DateTimePicker^ dateTimePicker1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem4; private: System::Windows::Forms::ToolStripMenuItem^ mnuButtonsHerstellen; private: System::Windows::Forms::ToolStripMenuItem^ mnuListControls; private: System::Windows::Forms::ToolStripMenuItem^ mnuTextBoxenHerstellen; private: System::Windows::Forms::Button^ btnAddDoubles; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::TextBox^ txtZweiteZahl; private: System::Windows::Forms::TextBox^ txtErsteZahl; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel2; private: System::Windows::Forms::Panel^ panel4; private: System::Windows::Forms::Button^ btnArrayList; private: System::Windows::Forms::TextBox^ txtCollections; private: System::Windows::Forms::Button^ btnQueue; private: System::Windows::Forms::Button^ btnStack; private: System::Windows::Forms::Button^ btnSortedList; private: System::Windows::Forms::Button^ btnHashtable; private: System::Windows::Forms::Button^ btnList; private: System::Windows::Forms::Button^ btnArray; private: System::Windows::Forms::Button^ btnBenchmark; private: System::Windows::Forms::TabPage^ tabPage4; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel3; private: System::Windows::Forms::Panel^ pnlDrawing; private: System::Windows::Forms::Panel^ pnlGraphics; private: System::Windows::Forms::Button^ btnDrawLine; private: System::Windows::Forms::Button^ btnTranslatePoints; private: System::Windows::Forms::PictureBox^ pictureBox2; private: System::Windows::Forms::Button^ btnDrawImage; private: System::Windows::Forms::Button^ btnDrawHouse; private: System::ComponentModel::IContainer^ components; protected: private: /// <summary> /// Erforderliche Designervariable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MainForm::typeid)); this->tableLayoutPanel1 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->contextMenuStrip1 = (gcnew System::Windows::Forms::ContextMenuStrip(this->components)); this->mnuClearText = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuOpen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuSave = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->panel1 = (gcnew System::Windows::Forms::Panel()); this->btnStartProgress = (gcnew System::Windows::Forms::Button()); this->btnChangeFromAnotherClass = (gcnew System::Windows::Forms::Button()); this->btnComboInsert = (gcnew System::Windows::Forms::Button()); this->btnComboremoveItem = (gcnew System::Windows::Forms::Button()); this->btnComboAddItem = (gcnew System::Windows::Forms::Button()); this->btnComboboxValue = (gcnew System::Windows::Forms::Button()); this->btnRadioButton = (gcnew System::Windows::Forms::Button()); this->btnCheckbox = (gcnew System::Windows::Forms::Button()); this->btnChangeTab = (gcnew System::Windows::Forms::Button()); this->cmdChangeFormColor = (gcnew System::Windows::Forms::Button()); this->panel2 = (gcnew System::Windows::Forms::Panel()); this->dateTimePicker1 = (gcnew System::Windows::Forms::DateTimePicker()); this->trackBar1 = (gcnew System::Windows::Forms::TrackBar()); this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown()); this->maskedTextBox1 = (gcnew System::Windows::Forms::MaskedTextBox()); this->listBox1 = (gcnew System::Windows::Forms::ListBox()); this->cmbBlubb = (gcnew System::Windows::Forms::ComboBox()); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->radioButton3 = (gcnew System::Windows::Forms::RadioButton()); this->radioButton2 = (gcnew System::Windows::Forms::RadioButton()); this->radioButton1 = (gcnew System::Windows::Forms::RadioButton()); this->checkBox1 = (gcnew System::Windows::Forms::CheckBox()); this->panel3 = (gcnew System::Windows::Forms::Panel()); this->btnAddDoubles = (gcnew System::Windows::Forms::Button()); this->label1 = (gcnew System::Windows::Forms::Label()); this->txtZweiteZahl = (gcnew System::Windows::Forms::TextBox()); this->txtErsteZahl = (gcnew System::Windows::Forms::TextBox()); this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox()); this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); this->tabControl1 = (gcnew System::Windows::Forms::TabControl()); this->tabPage1 = (gcnew System::Windows::Forms::TabPage()); this->tabPage2 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel2 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->panel4 = (gcnew System::Windows::Forms::Panel()); this->btnBenchmark = (gcnew System::Windows::Forms::Button()); this->btnArray = (gcnew System::Windows::Forms::Button()); this->btnList = (gcnew System::Windows::Forms::Button()); this->btnHashtable = (gcnew System::Windows::Forms::Button()); this->btnSortedList = (gcnew System::Windows::Forms::Button()); this->btnStack = (gcnew System::Windows::Forms::Button()); this->btnQueue = (gcnew System::Windows::Forms::Button()); this->btnArrayList = (gcnew System::Windows::Forms::Button()); this->txtCollections = (gcnew System::Windows::Forms::TextBox()); this->tabPage3 = (gcnew System::Windows::Forms::TabPage()); this->txtAnswers = (gcnew System::Windows::Forms::TextBox()); this->txtQuestions = (gcnew System::Windows::Forms::TextBox()); this->btnNextStep = (gcnew System::Windows::Forms::Button()); this->tabPage4 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel3 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->pnlDrawing = (gcnew System::Windows::Forms::Panel()); this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox()); this->pnlGraphics = (gcnew System::Windows::Forms::Panel()); this->btnDrawImage = (gcnew System::Windows::Forms::Button()); this->btnTranslatePoints = (gcnew System::Windows::Forms::Button()); this->btnDrawLine = (gcnew System::Windows::Forms::Button()); this->timer1 = (gcnew System::Windows::Forms::Timer(this->components)); this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->toolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem2 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripSeparator1 = (gcnew System::Windows::Forms::ToolStripSeparator()); this->mnuSaveFileDialog = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuRichtextBox = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuFolderBrowser = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem3 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuFarben = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuSchriftart = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem4 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuButtonsHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuListControls = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuTextBoxenHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog()); this->colorDialog1 = (gcnew System::Windows::Forms::ColorDialog()); this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog()); this->fontDialog1 = (gcnew System::Windows::Forms::FontDialog()); this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog()); this->btnDrawHouse = (gcnew System::Windows::Forms::Button()); this->tableLayoutPanel1->SuspendLayout(); this->contextMenuStrip1->SuspendLayout(); this->panel1->SuspendLayout(); this->panel2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->BeginInit(); this->groupBox1->SuspendLayout(); this->panel3->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit(); this->tabControl1->SuspendLayout(); this->tabPage1->SuspendLayout(); this->tabPage2->SuspendLayout(); this->tableLayoutPanel2->SuspendLayout(); this->panel4->SuspendLayout(); this->tabPage3->SuspendLayout(); this->tabPage4->SuspendLayout(); this->tableLayoutPanel3->SuspendLayout(); this->pnlDrawing->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->BeginInit(); this->pnlGraphics->SuspendLayout(); this->menuStrip1->SuspendLayout(); this->SuspendLayout(); // // tableLayoutPanel1 // this->tableLayoutPanel1->ColumnCount = 2; this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->Controls->Add(this->textBox1, 1, 0); this->tableLayoutPanel1->Controls->Add(this->panel1, 0, 0); this->tableLayoutPanel1->Controls->Add(this->panel2, 0, 1); this->tableLayoutPanel1->Controls->Add(this->panel3, 1, 1); this->tableLayoutPanel1->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel1->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel1->Name = L"tableLayoutPanel1"; this->tableLayoutPanel1->RowCount = 2; this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->Size = System::Drawing::Size(599, 458); this->tableLayoutPanel1->TabIndex = 3; // // textBox1 // this->textBox1->ContextMenuStrip = this->contextMenuStrip1; this->textBox1->Dock = System::Windows::Forms::DockStyle::Fill; this->textBox1->Location = System::Drawing::Point(302, 3); this->textBox1->Multiline = true; this->textBox1->Name = L"textBox1"; this->textBox1->ScrollBars = System::Windows::Forms::ScrollBars::Both; this->textBox1->Size = System::Drawing::Size(294, 223); this->textBox1->TabIndex = 2; // // contextMenuStrip1 // this->contextMenuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) { this->mnuClearText, this->mnuOpen, this->mnuSave }); this->contextMenuStrip1->Name = L"contextMenuStrip1"; this->contextMenuStrip1->Size = System::Drawing::Size(160, 70); // // mnuClearText // this->mnuClearText->Name = L"mnuClearText"; this->mnuClearText->Size = System::Drawing::Size(159, 22); this->mnuClearText->Text = L"TextBox löschen"; this->mnuClearText->Click += gcnew System::EventHandler(this, &MainForm::mnuClearText_Click); // // mnuOpen // this->mnuOpen->Name = L"mnuOpen"; this->mnuOpen->Size = System::Drawing::Size(159, 22); this->mnuOpen->Text = L"Datei öffnen"; this->mnuOpen->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click); // // mnuSave // this->mnuSave->Name = L"mnuSave"; this->mnuSave->Size = System::Drawing::Size(159, 22); this->mnuSave->Text = L"Speichern als"; this->mnuSave->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click); // // panel1 // this->panel1->Controls->Add(this->btnStartProgress); this->panel1->Controls->Add(this->btnChangeFromAnotherClass); this->panel1->Controls->Add(this->btnComboInsert); this->panel1->Controls->Add(this->btnComboremoveItem); this->panel1->Controls->Add(this->btnComboAddItem); this->panel1->Controls->Add(this->btnComboboxValue); this->panel1->Controls->Add(this->btnRadioButton); this->panel1->Controls->Add(this->btnCheckbox); this->panel1->Controls->Add(this->btnChangeTab); this->panel1->Controls->Add(this->cmdChangeFormColor); this->panel1->Dock = System::Windows::Forms::DockStyle::Fill; this->panel1->Location = System::Drawing::Point(3, 3); this->panel1->Name = L"panel1"; this->panel1->Size = System::Drawing::Size(293, 223); this->panel1->TabIndex = 1; // // btnStartProgress // this->btnStartProgress->Location = System::Drawing::Point(115, 32); this->btnStartProgress->Name = L"btnStartProgress"; this->btnStartProgress->Size = System::Drawing::Size(109, 23); this->btnStartProgress->TabIndex = 9; this->btnStartProgress->Text = L"Start Progress"; this->btnStartProgress->UseVisualStyleBackColor = true; this->btnStartProgress->Click += gcnew System::EventHandler(this, &MainForm::btnStartProgress_Click); // // btnChangeFromAnotherClass // this->btnChangeFromAnotherClass->Location = System::Drawing::Point(115, 3); this->btnChangeFromAnotherClass->Name = L"btnChangeFromAnotherClass"; this->btnChangeFromAnotherClass->Size = System::Drawing::Size(109, 23); this->btnChangeFromAnotherClass->TabIndex = 8; this->btnChangeFromAnotherClass->Text = L"Class Fun"; this->btnChangeFromAnotherClass->UseVisualStyleBackColor = true; this->btnChangeFromAnotherClass->Click += gcnew System::EventHandler(this, &MainForm::btnChangeFromAnotherClass_Click); // // btnComboInsert // this->btnComboInsert->Location = System::Drawing::Point(3, 178); this->btnComboInsert->Name = L"btnComboInsert"; this->btnComboInsert->Size = System::Drawing::Size(109, 23); this->btnComboInsert->TabIndex = 7; this->btnComboInsert->Text = L"Combo insert Item"; this->btnComboInsert->UseVisualStyleBackColor = true; this->btnComboInsert->Click += gcnew System::EventHandler(this, &MainForm::btnComboInsert_Click); // // btnComboremoveItem // this->btnComboremoveItem->Location = System::Drawing::Point(4, 207); this->btnComboremoveItem->Name = L"btnComboremoveItem"; this->btnComboremoveItem->Size = System::Drawing::Size(109, 23); this->btnComboremoveItem->TabIndex = 6; this->btnComboremoveItem->Text = L"Combo remove Item"; this->btnComboremoveItem->UseVisualStyleBackColor = true; this->btnComboremoveItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboremoveItem_Click); // // btnComboAddItem // this->btnComboAddItem->Location = System::Drawing::Point(3, 149); this->btnComboAddItem->Name = L"btnComboAddItem"; this->btnComboAddItem->Size = System::Drawing::Size(96, 23); this->btnComboAddItem->TabIndex = 5; this->btnComboAddItem->Text = L"Combo Add Item"; this->btnComboAddItem->UseVisualStyleBackColor = true; this->btnComboAddItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboAddItem_Click); // // btnComboboxValue // this->btnComboboxValue->Location = System::Drawing::Point(4, 120); this->btnComboboxValue->Name = L"btnComboboxValue"; this->btnComboboxValue->Size = System::Drawing::Size(96, 23); this->btnComboboxValue->TabIndex = 4; this->btnComboboxValue->Text = L"Combo Value"; this->btnComboboxValue->UseVisualStyleBackColor = true; this->btnComboboxValue->Click += gcnew System::EventHandler(this, &MainForm::btnComboboxValue_Click); // // btnRadioButton // this->btnRadioButton->Location = System::Drawing::Point(4, 91); this->btnRadioButton->Name = L"btnRadioButton"; this->btnRadioButton->Size = System::Drawing::Size(96, 23); this->btnRadioButton->TabIndex = 3; this->btnRadioButton->Text = L"Radiobutton"; this->btnRadioButton->UseVisualStyleBackColor = true; this->btnRadioButton->Click += gcnew System::EventHandler(this, &MainForm::btnRadioButton_Click); // // btnCheckbox // this->btnCheckbox->Location = System::Drawing::Point(4, 62); this->btnCheckbox->Name = L"btnCheckbox"; this->btnCheckbox->Size = System::Drawing::Size(96, 23); this->btnCheckbox->TabIndex = 2; this->btnCheckbox->Text = L"Checkbox"; this->btnCheckbox->UseVisualStyleBackColor = true; this->btnCheckbox->Click += gcnew System::EventHandler(this, &MainForm::btnCheckbox_Click); // // btnChangeTab // this->btnChangeTab->Location = System::Drawing::Point(3, 32); this->btnChangeTab->Name = L"btnChangeTab"; this->btnChangeTab->Size = System::Drawing::Size(97, 23); this->btnChangeTab->TabIndex = 1; this->btnChangeTab->Text = L"Change Tab"; this->btnChangeTab->UseVisualStyleBackColor = true; this->btnChangeTab->Click += gcnew System::EventHandler(this, &MainForm::btnChangeTab_Click); // // cmdChangeFormColor // this->cmdChangeFormColor->Location = System::Drawing::Point(3, 3); this->cmdChangeFormColor->Name = L"cmdChangeFormColor"; this->cmdChangeFormColor->Size = System::Drawing::Size(97, 23); this->cmdChangeFormColor->TabIndex = 0; this->cmdChangeFormColor->Text = L"Change Color"; this->cmdChangeFormColor->UseVisualStyleBackColor = true; this->cmdChangeFormColor->Click += gcnew System::EventHandler(this, &MainForm::cmdChangeFormColor_Click); // // panel2 // this->panel2->Controls->Add(this->dateTimePicker1); this->panel2->Controls->Add(this->trackBar1); this->panel2->Controls->Add(this->numericUpDown1); this->panel2->Controls->Add(this->maskedTextBox1); this->panel2->Controls->Add(this->listBox1); this->panel2->Controls->Add(this->cmbBlubb); this->panel2->Controls->Add(this->groupBox1); this->panel2->Controls->Add(this->checkBox1); this->panel2->Dock = System::Windows::Forms::DockStyle::Fill; this->panel2->Location = System::Drawing::Point(3, 232); this->panel2->Name = L"panel2"; this->panel2->Size = System::Drawing::Size(293, 223); this->panel2->TabIndex = 3; // // dateTimePicker1 // this->dateTimePicker1->Location = System::Drawing::Point(24, 205); this->dateTimePicker1->Name = L"dateTimePicker1"; this->dateTimePicker1->Size = System::Drawing::Size(200, 20); this->dateTimePicker1->TabIndex = 10; this->dateTimePicker1->ValueChanged += gcnew System::EventHandler(this, &MainForm::dateTimePicker1_ValueChanged); // // trackBar1 // this->trackBar1->Location = System::Drawing::Point(10, 158); this->trackBar1->Name = L"trackBar1"; this->trackBar1->Size = System::Drawing::Size(104, 45); this->trackBar1->TabIndex = 9; this->trackBar1->Scroll += gcnew System::EventHandler(this, &MainForm::trackBar1_Scroll); // // numericUpDown1 // this->numericUpDown1->Increment = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 }); this->numericUpDown1->Location = System::Drawing::Point(191, 132); this->numericUpDown1->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 }); this->numericUpDown1->Name = L"numericUpDown1"; this->numericUpDown1->Size = System::Drawing::Size(79, 20); this->numericUpDown1->TabIndex = 8; this->numericUpDown1->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 }); // // maskedTextBox1 // this->maskedTextBox1->Location = System::Drawing::Point(4, 131); this->maskedTextBox1->Mask = L"00/00/0000 00:00"; this->maskedTextBox1->Name = L"maskedTextBox1"; this->maskedTextBox1->Size = System::Drawing::Size(172, 20); this->maskedTextBox1->TabIndex = 7; this->maskedTextBox1->ValidatingType = System::DateTime::typeid; // // listBox1 // this->listBox1->FormattingEnabled = true; this->listBox1->Items->AddRange(gcnew cli::array< System::Object^ >(4) { L"Bli", L"Bla", L"Blubb", L"Trallallaaaaaa" }); this->listBox1->Location = System::Drawing::Point(133, 30); this->listBox1->Name = L"listBox1"; this->listBox1->SelectionMode = System::Windows::Forms::SelectionMode::MultiSimple; this->listBox1->Size = System::Drawing::Size(137, 95); this->listBox1->TabIndex = 6; this->listBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::listBox1_SelectedIndexChanged); // // cmbBlubb // this->cmbBlubb->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->cmbBlubb->FormattingEnabled = true; this->cmbBlubb->Items->AddRange(gcnew cli::array< System::Object^ >(5) { L"Bli", L"Bla", L"Blubb", L"Trallalla", L"Whooop" }); this->cmbBlubb->Location = System::Drawing::Point(133, 3); this->cmbBlubb->Name = L"cmbBlubb"; this->cmbBlubb->Size = System::Drawing::Size(137, 21); this->cmbBlubb->TabIndex = 5; this->cmbBlubb->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::cmbBlubb_SelectedIndexChanged); // // groupBox1 // this->groupBox1->Controls->Add(this->radioButton3); this->groupBox1->Controls->Add(this->radioButton2); this->groupBox1->Controls->Add(this->radioButton1); this->groupBox1->Location = System::Drawing::Point(4, 26); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(113, 91); this->groupBox1->TabIndex = 4; this->groupBox1->TabStop = false; this->groupBox1->Text = L"groupBox1"; // // radioButton3 // this->radioButton3->AutoSize = true; this->radioButton3->Location = System::Drawing::Point(6, 65); this->radioButton3->Name = L"radioButton3"; this->radioButton3->Size = System::Drawing::Size(85, 17); this->radioButton3->TabIndex = 3; this->radioButton3->TabStop = true; this->radioButton3->Text = L"radioButton3"; this->radioButton3->UseVisualStyleBackColor = true; // // radioButton2 // this->radioButton2->AutoSize = true; this->radioButton2->Location = System::Drawing::Point(6, 42); this->radioButton2->Name = L"radioButton2"; this->radioButton2->Size = System::Drawing::Size(85, 17); this->radioButton2->TabIndex = 2; this->radioButton2->TabStop = true; this->radioButton2->Text = L"radioButton2"; this->radioButton2->UseVisualStyleBackColor = true; // // radioButton1 // this->radioButton1->AutoSize = true; this->radioButton1->Location = System::Drawing::Point(6, 19); this->radioButton1->Name = L"radioButton1"; this->radioButton1->Size = System::Drawing::Size(85, 17); this->radioButton1->TabIndex = 1; this->radioButton1->TabStop = true; this->radioButton1->Text = L"radioButton1"; this->radioButton1->UseVisualStyleBackColor = true; // // checkBox1 // this->checkBox1->AutoSize = true; this->checkBox1->Location = System::Drawing::Point(3, 3); this->checkBox1->Name = L"checkBox1"; this->checkBox1->Size = System::Drawing::Size(80, 17); this->checkBox1->TabIndex = 0; this->checkBox1->Text = L"checkBox1"; this->checkBox1->UseVisualStyleBackColor = true; this->checkBox1->CheckedChanged += gcnew System::EventHandler(this, &MainForm::checkBox1_CheckedChanged); // // panel3 // this->panel3->Controls->Add(this->btnAddDoubles); this->panel3->Controls->Add(this->label1); this->panel3->Controls->Add(this->txtZweiteZahl); this->panel3->Controls->Add(this->txtErsteZahl); this->panel3->Controls->Add(this->richTextBox1); this->panel3->Controls->Add(this->progressBar1); this->panel3->Controls->Add(this->pictureBox1); this->panel3->Dock = System::Windows::Forms::DockStyle::Fill; this->panel3->Location = System::Drawing::Point(302, 232); this->panel3->Name = L"panel3"; this->panel3->Size = System::Drawing::Size(294, 223); this->panel3->TabIndex = 4; // // btnAddDoubles // this->btnAddDoubles->Location = System::Drawing::Point(240, 167); this->btnAddDoubles->Name = L"btnAddDoubles"; this->btnAddDoubles->Size = System::Drawing::Size(30, 23); this->btnAddDoubles->TabIndex = 10; this->btnAddDoubles->Text = L"="; this->btnAddDoubles->UseVisualStyleBackColor = true; this->btnAddDoubles->Click += gcnew System::EventHandler(this, &MainForm::btnAddDoubles_Click); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(124, 173); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(13, 13); this->label1->TabIndex = 5; this->label1->Text = L"+"; // // txtZweiteZahl // this->txtZweiteZahl->Location = System::Drawing::Point(138, 170); this->txtZweiteZahl->Name = L"txtZweiteZahl"; this->txtZweiteZahl->Size = System::Drawing::Size(100, 20); this->txtZweiteZahl->TabIndex = 4; // // txtErsteZahl // this->txtErsteZahl->Location = System::Drawing::Point(18, 170); this->txtErsteZahl->Name = L"txtErsteZahl"; this->txtErsteZahl->Size = System::Drawing::Size(100, 20); this->txtErsteZahl->TabIndex = 3; // // richTextBox1 // this->richTextBox1->Location = System::Drawing::Point(93, 29); this->richTextBox1->Name = L"richTextBox1"; this->richTextBox1->Size = System::Drawing::Size(177, 88); this->richTextBox1->TabIndex = 2; this->richTextBox1->Text = L""; // // progressBar1 // this->progressBar1->Location = System::Drawing::Point(93, 3); this->progressBar1->Name = L"progressBar1"; this->progressBar1->Size = System::Drawing::Size(177, 14); this->progressBar1->Style = System::Windows::Forms::ProgressBarStyle::Continuous; this->progressBar1->TabIndex = 1; this->progressBar1->Value = 40; // // pictureBox1 // this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox1.Image"))); this->pictureBox1->Location = System::Drawing::Point(3, 3); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(84, 82); this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox1->TabIndex = 0; this->pictureBox1->TabStop = false; // // tabControl1 // this->tabControl1->Controls->Add(this->tabPage1); this->tabControl1->Controls->Add(this->tabPage2); this->tabControl1->Controls->Add(this->tabPage3); this->tabControl1->Controls->Add(this->tabPage4); this->tabControl1->Dock = System::Windows::Forms::DockStyle::Fill; this->tabControl1->Location = System::Drawing::Point(0, 24); this->tabControl1->Name = L"tabControl1"; this->tabControl1->SelectedIndex = 0; this->tabControl1->Size = System::Drawing::Size(613, 490); this->tabControl1->TabIndex = 4; // // tabPage1 // this->tabPage1->Controls->Add(this->tableLayoutPanel1); this->tabPage1->Location = System::Drawing::Point(4, 22); this->tabPage1->Name = L"tabPage1"; this->tabPage1->Padding = System::Windows::Forms::Padding(3); this->tabPage1->Size = System::Drawing::Size(605, 464); this->tabPage1->TabIndex = 0; this->tabPage1->Text = L"Basics"; this->tabPage1->UseVisualStyleBackColor = true; // // tabPage2 // this->tabPage2->Controls->Add(this->tableLayoutPanel2); this->tabPage2->Location = System::Drawing::Point(4, 22); this->tabPage2->Name = L"tabPage2"; this->tabPage2->Padding = System::Windows::Forms::Padding(3); this->tabPage2->Size = System::Drawing::Size(605, 464); this->tabPage2->TabIndex = 1; this->tabPage2->Text = L"Other"; this->tabPage2->UseVisualStyleBackColor = true; // // tableLayoutPanel2 // this->tableLayoutPanel2->ColumnCount = 2; this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->Controls->Add(this->panel4, 0, 0); this->tableLayoutPanel2->Controls->Add(this->txtCollections, 1, 0); this->tableLayoutPanel2->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel2->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel2->Name = L"tableLayoutPanel2"; this->tableLayoutPanel2->RowCount = 1; this->tableLayoutPanel2->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->Size = System::Drawing::Size(599, 458); this->tableLayoutPanel2->TabIndex = 0; // // panel4 // this->panel4->Controls->Add(this->btnBenchmark); this->panel4->Controls->Add(this->btnArray); this->panel4->Controls->Add(this->btnList); this->panel4->Controls->Add(this->btnHashtable); this->panel4->Controls->Add(this->btnSortedList); this->panel4->Controls->Add(this->btnStack); this->panel4->Controls->Add(this->btnQueue); this->panel4->Controls->Add(this->btnArrayList); this->panel4->Dock = System::Windows::Forms::DockStyle::Fill; this->panel4->Location = System::Drawing::Point(3, 3); this->panel4->Name = L"panel4"; this->panel4->Size = System::Drawing::Size(293, 452); this->panel4->TabIndex = 0; // // btnBenchmark // this->btnBenchmark->Location = System::Drawing::Point(4, 207); this->btnBenchmark->Name = L"btnBenchmark"; this->btnBenchmark->Size = System::Drawing::Size(121, 23); this->btnBenchmark->TabIndex = 8; this->btnBenchmark->Text = L"Benchmark"; this->btnBenchmark->UseVisualStyleBackColor = true; this->btnBenchmark->Click += gcnew System::EventHandler(this, &MainForm::btnBenchmark_Click); // // btnArray // this->btnArray->Location = System::Drawing::Point(4, 178); this->btnArray->Name = L"btnArray"; this->btnArray->Size = System::Drawing::Size(121, 23); this->btnArray->TabIndex = 7; this->btnArray->Text = L"array"; this->btnArray->UseVisualStyleBackColor = true; this->btnArray->Click += gcnew System::EventHandler(this, &MainForm::btnArray_Click); // // btnList // this->btnList->Location = System::Drawing::Point(4, 149); this->btnList->Name = L"btnList"; this->btnList->Size = System::Drawing::Size(121, 23); this->btnList->TabIndex = 6; this->btnList->Text = L"List"; this->btnList->UseVisualStyleBackColor = true; this->btnList->Click += gcnew System::EventHandler(this, &MainForm::btnList_Click); // // btnHashtable // this->btnHashtable->Location = System::Drawing::Point(4, 120); this->btnHashtable->Name = L"btnHashtable"; this->btnHashtable->Size = System::Drawing::Size(121, 23); this->btnHashtable->TabIndex = 4; this->btnHashtable->Text = L"HashTable"; this->btnHashtable->UseVisualStyleBackColor = true; this->btnHashtable->Click += gcnew System::EventHandler(this, &MainForm::btnHashtable_Click); // // btnSortedList // this->btnSortedList->Location = System::Drawing::Point(4, 91); this->btnSortedList->Name = L"btnSortedList"; this->btnSortedList->Size = System::Drawing::Size(121, 23); this->btnSortedList->TabIndex = 3; this->btnSortedList->Text = L"SortedList"; this->btnSortedList->UseVisualStyleBackColor = true; this->btnSortedList->Click += gcnew System::EventHandler(this, &MainForm::btnSortedList_Click); // // btnStack // this->btnStack->Location = System::Drawing::Point(4, 62); this->btnStack->Name = L"btnStack"; this->btnStack->Size = System::Drawing::Size(121, 23); this->btnStack->TabIndex = 2; this->btnStack->Text = L"Stack"; this->btnStack->UseVisualStyleBackColor = true; this->btnStack->Click += gcnew System::EventHandler(this, &MainForm::btnStack_Click); // // btnQueue // this->btnQueue->Location = System::Drawing::Point(4, 33); this->btnQueue->Name = L"btnQueue"; this->btnQueue->Size = System::Drawing::Size(121, 23); this->btnQueue->TabIndex = 1; this->btnQueue->Text = L"Queue"; this->btnQueue->UseVisualStyleBackColor = true; this->btnQueue->Click += gcnew System::EventHandler(this, &MainForm::btnQueue_Click); // // btnArrayList // this->btnArrayList->Location = System::Drawing::Point(4, 4); this->btnArrayList->Name = L"btnArrayList"; this->btnArrayList->Size = System::Drawing::Size(121, 23); this->btnArrayList->TabIndex = 0; this->btnArrayList->Text = L"ArrayList"; this->btnArrayList->UseVisualStyleBackColor = true; this->btnArrayList->Click += gcnew System::EventHandler(this, &MainForm::btnArrayList_Click); // // txtCollections // this->txtCollections->Dock = System::Windows::Forms::DockStyle::Fill; this->txtCollections->Location = System::Drawing::Point(302, 3); this->txtCollections->Multiline = true; this->txtCollections->Name = L"txtCollections"; this->txtCollections->Size = System::Drawing::Size(294, 452); this->txtCollections->TabIndex = 1; // // tabPage3 // this->tabPage3->Controls->Add(this->txtAnswers); this->tabPage3->Controls->Add(this->txtQuestions); this->tabPage3->Controls->Add(this->btnNextStep); this->tabPage3->Location = System::Drawing::Point(4, 22); this->tabPage3->Name = L"tabPage3"; this->tabPage3->Padding = System::Windows::Forms::Padding(3); this->tabPage3->Size = System::Drawing::Size(605, 464); this->tabPage3->TabIndex = 2; this->tabPage3->Text = L"Quiz"; this->tabPage3->UseVisualStyleBackColor = true; // // txtAnswers // this->txtAnswers->Location = System::Drawing::Point(288, 231); this->txtAnswers->Multiline = true; this->txtAnswers->Name = L"txtAnswers"; this->txtAnswers->Size = System::Drawing::Size(268, 203); this->txtAnswers->TabIndex = 2; // // txtQuestions // this->txtQuestions->Location = System::Drawing::Point(288, 4); this->txtQuestions->Multiline = true; this->txtQuestions->Name = L"txtQuestions"; this->txtQuestions->Size = System::Drawing::Size(268, 203); this->txtQuestions->TabIndex = 1; // // btnNextStep // this->btnNextStep->Location = System::Drawing::Point(7, 7); this->btnNextStep->Name = L"btnNextStep"; this->btnNextStep->Size = System::Drawing::Size(75, 23); this->btnNextStep->TabIndex = 0; this->btnNextStep->Text = L"Next"; this->btnNextStep->UseVisualStyleBackColor = true; this->btnNextStep->Click += gcnew System::EventHandler(this, &MainForm::btnNextStep_Click); // // tabPage4 // this->tabPage4->Controls->Add(this->tableLayoutPanel3); this->tabPage4->Location = System::Drawing::Point(4, 22); this->tabPage4->Name = L"tabPage4"; this->tabPage4->Padding = System::Windows::Forms::Padding(3); this->tabPage4->Size = System::Drawing::Size(605, 464); this->tabPage4->TabIndex = 3; this->tabPage4->Text = L"Graphics"; this->tabPage4->UseVisualStyleBackColor = true; // // tableLayoutPanel3 // this->tableLayoutPanel3->ColumnCount = 2; this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->Controls->Add(this->pnlDrawing, 1, 0); this->tableLayoutPanel3->Controls->Add(this->pnlGraphics, 0, 0); this->tableLayoutPanel3->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel3->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel3->Name = L"tableLayoutPanel3"; this->tableLayoutPanel3->RowCount = 1; this->tableLayoutPanel3->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->Size = System::Drawing::Size(599, 458); this->tableLayoutPanel3->TabIndex = 0; // // pnlDrawing // this->pnlDrawing->BackColor = System::Drawing::Color::Gainsboro; this->pnlDrawing->Controls->Add(this->pictureBox2); this->pnlDrawing->Dock = System::Windows::Forms::DockStyle::Fill; this->pnlDrawing->Location = System::Drawing::Point(302, 3); this->pnlDrawing->Name = L"pnlDrawing"; this->pnlDrawing->Size = System::Drawing::Size(294, 452); this->pnlDrawing->TabIndex = 0; this->pnlDrawing->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click); // // pictureBox2 // this->pictureBox2->Dock = System::Windows::Forms::DockStyle::Fill; this->pictureBox2->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox2.Image"))); this->pictureBox2->Location = System::Drawing::Point(0, 0); this->pictureBox2->Name = L"pictureBox2"; this->pictureBox2->Size = System::Drawing::Size(294, 452); this->pictureBox2->TabIndex = 0; this->pictureBox2->TabStop = false; this->pictureBox2->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click); this->pictureBox2->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MainForm::pnlDrawing_Paint); // // pnlGraphics // this->pnlGraphics->Controls->Add(this->btnDrawHouse); this->pnlGraphics->Controls->Add(this->btnDrawImage); this->pnlGraphics->Controls->Add(this->btnTranslatePoints); this->pnlGraphics->Controls->Add(this->btnDrawLine); this->pnlGraphics->Dock = System::Windows::Forms::DockStyle::Fill; this->pnlGraphics->Location = System::Drawing::Point(3, 3); this->pnlGraphics->Name = L"pnlGraphics"; this->pnlGraphics->Size = System::Drawing::Size(293, 452); this->pnlGraphics->TabIndex = 1; // // btnDrawImage // this->btnDrawImage->Location = System::Drawing::Point(3, 61); this->btnDrawImage->Name = L"btnDrawImage"; this->btnDrawImage->Size = System::Drawing::Size(75, 23); this->btnDrawImage->TabIndex = 2; this->btnDrawImage->Text = L"Draw Image"; this->btnDrawImage->UseVisualStyleBackColor = true; this->btnDrawImage->Click += gcnew System::EventHandler(this, &MainForm::btnDrawImage_Click); // // btnTranslatePoints // this->btnTranslatePoints->Location = System::Drawing::Point(3, 32); this->btnTranslatePoints->Name = L"btnTranslatePoints"; this->btnTranslatePoints->Size = System::Drawing::Size(75, 23); this->btnTranslatePoints->TabIndex = 1; this->btnTranslatePoints->Text = L"Zoom"; this->btnTranslatePoints->UseVisualStyleBackColor = true; this->btnTranslatePoints->Click += gcnew System::EventHandler(this, &MainForm::btnTranslatePoints_Click); // // btnDrawLine // this->btnDrawLine->Location = System::Drawing::Point(3, 3); this->btnDrawLine->Name = L"btnDrawLine"; this->btnDrawLine->Size = System::Drawing::Size(75, 23); this->btnDrawLine->TabIndex = 0; this->btnDrawLine->Text = L"Draw Line"; this->btnDrawLine->UseVisualStyleBackColor = true; this->btnDrawLine->Click += gcnew System::EventHandler(this, &MainForm::btnDrawLine_Click); // // timer1 // this->timer1->Interval = 1000; this->timer1->Tick += gcnew System::EventHandler(this, &MainForm::timer1_Tick); // // menuStrip1 // this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) { this->toolStripMenuItem1, this->toolStripMenuItem3, this->toolStripMenuItem4 }); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->Size = System::Drawing::Size(613, 24); this->menuStrip1->TabIndex = 5; this->menuStrip1->Text = L"menuStrip1"; // // toolStripMenuItem1 // this->toolStripMenuItem1->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(5) { this->toolStripMenuItem2, this->toolStripSeparator1, this->mnuSaveFileDialog, this->mnuRichtextBox, this->mnuFolderBrowser }); this->toolStripMenuItem1->Name = L"toolStripMenuItem1"; this->toolStripMenuItem1->Size = System::Drawing::Size(46, 20); this->toolStripMenuItem1->Text = L"Datei"; // // toolStripMenuItem2 // this->toolStripMenuItem2->Name = L"toolStripMenuItem2"; this->toolStripMenuItem2->Size = System::Drawing::Size(190, 22); this->toolStripMenuItem2->Text = L"Öffnen"; this->toolStripMenuItem2->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click); // // toolStripSeparator1 // this->toolStripSeparator1->Name = L"toolStripSeparator1"; this->toolStripSeparator1->Size = System::Drawing::Size(187, 6); // // mnuSaveFileDialog // this->mnuSaveFileDialog->Name = L"mnuSaveFileDialog"; this->mnuSaveFileDialog->Size = System::Drawing::Size(190, 22); this->mnuSaveFileDialog->Text = L"Speichern"; this->mnuSaveFileDialog->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click); // // mnuRichtextBox // this->mnuRichtextBox->Name = L"mnuRichtextBox"; this->mnuRichtextBox->Size = System::Drawing::Size(190, 22); this->mnuRichtextBox->Text = L"Richtextbox Speichern"; this->mnuRichtextBox->Click += gcnew System::EventHandler(this, &MainForm::mnuRichtextBox_Click); // // mnuFolderBrowser // this->mnuFolderBrowser->Name = L"mnuFolderBrowser"; this->mnuFolderBrowser->Size = System::Drawing::Size(190, 22); this->mnuFolderBrowser->Text = L"FolderBrowserDialog"; this->mnuFolderBrowser->Click += gcnew System::EventHandler(this, &MainForm::mnuFolderBrowser_Click); // // toolStripMenuItem3 // this->toolStripMenuItem3->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) { this->mnuFarben, this->mnuSchriftart }); this->toolStripMenuItem3->Name = L"toolStripMenuItem3"; this->toolStripMenuItem3->Size = System::Drawing::Size(90, 20); this->toolStripMenuItem3->Text = L"Einstellungen"; // // mnuFarben // this->mnuFarben->Name = L"mnuFarben"; this->mnuFarben->Size = System::Drawing::Size(122, 22); this->mnuFarben->Text = L"Farben"; this->mnuFarben->Click += gcnew System::EventHandler(this, &MainForm::mnuFarben_Click); // // mnuSchriftart // this->mnuSchriftart->Name = L"mnuSchriftart"; this->mnuSchriftart->Size = System::Drawing::Size(122, 22); this->mnuSchriftart->Text = L"Schriftart"; this->mnuSchriftart->Click += gcnew System::EventHandler(this, &MainForm::mnuSchriftart_Click); // // toolStripMenuItem4 // this->toolStripMenuItem4->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) { this->mnuButtonsHerstellen, this->mnuListControls, this->mnuTextBoxenHerstellen }); this->toolStripMenuItem4->Name = L"toolStripMenuItem4"; this->toolStripMenuItem4->Size = System::Drawing::Size(54, 20); this->toolStripMenuItem4->Text = L"Debug"; // // mnuButtonsHerstellen // this->mnuButtonsHerstellen->Name = L"mnuButtonsHerstellen"; this->mnuButtonsHerstellen->Size = System::Drawing::Size(198, 22); this->mnuButtonsHerstellen->Text = L"Buttons herstellen"; this->mnuButtonsHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuButtonsHerstellen_Click); // // mnuListControls // this->mnuListControls->Name = L"mnuListControls"; this->mnuListControls->Size = System::Drawing::Size(198, 22); this->mnuListControls->Text = L"Liste Controls tabPage2"; this->mnuListControls->Click += gcnew System::EventHandler(this, &MainForm::mnuListControls_Click); // // mnuTextBoxenHerstellen // this->mnuTextBoxenHerstellen->Name = L"mnuTextBoxenHerstellen"; this->mnuTextBoxenHerstellen->Size = System::Drawing::Size(198, 22); this->mnuTextBoxenHerstellen->Text = L"TextBoxen herstellen"; this->mnuTextBoxenHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuTextBoxenHerstellen_Click); // // openFileDialog1 // this->openFileDialog1->FileName = L"openFileDialog1"; // // fontDialog1 // this->fontDialog1->ShowColor = true; // // btnDrawHouse // this->btnDrawHouse->Location = System::Drawing::Point(3, 90); this->btnDrawHouse->Name = L"btnDrawHouse"; this->btnDrawHouse->Size = System::Drawing::Size(75, 23); this->btnDrawHouse->TabIndex = 3; this->btnDrawHouse->Text = L"Draw House"; this->btnDrawHouse->UseVisualStyleBackColor = true; this->btnDrawHouse->Click += gcnew System::EventHandler(this, &MainForm::btnDrawHouse_Click); // // MainForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(613, 514); this->Controls->Add(this->tabControl1); this->Controls->Add(this->menuStrip1); this->MainMenuStrip = this->menuStrip1; this->Name = L"MainForm"; this->Text = L"MainForm"; this->tableLayoutPanel1->ResumeLayout(false); this->tableLayoutPanel1->PerformLayout(); this->contextMenuStrip1->ResumeLayout(false); this->panel1->ResumeLayout(false); this->panel2->ResumeLayout(false); this->panel2->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->EndInit(); this->groupBox1->ResumeLayout(false); this->groupBox1->PerformLayout(); this->panel3->ResumeLayout(false); this->panel3->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit(); this->tabControl1->ResumeLayout(false); this->tabPage1->ResumeLayout(false); this->tabPage2->ResumeLayout(false); this->tableLayoutPanel2->ResumeLayout(false); this->tableLayoutPanel2->PerformLayout(); this->panel4->ResumeLayout(false); this->tabPage3->ResumeLayout(false); this->tabPage3->PerformLayout(); this->tabPage4->ResumeLayout(false); this->tableLayoutPanel3->ResumeLayout(false); this->pnlDrawing->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->EndInit(); this->pnlGraphics->ResumeLayout(false); this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void cmdChangeFormColor_Click(System::Object^ sender, System::EventArgs^ e) { cmdChangeFormColor->BackColor = System::Drawing::Color(Color::HotPink); this->BackColor = System::Drawing::Color(Color::GreenYellow); } private: System::Void btnChangeTab_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(tabControl1->SelectedIndex.ToString()); tabControl1->SelectedIndex = 1; tabControl1->SelectTab(1); textBox1->AppendText(textBox1->GetType()->ToString()); } private: System::Void btnCheckbox_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(checkBox1->Checked.ToString()); if (checkBox1->Checked) { System::Windows::Forms::DialogResult dR = MessageBox::Show("Oh nooooo, I'm checked !\r\n", "Please click !", MessageBoxButtons::YesNoCancel, MessageBoxIcon::Warning); if (dR == System::Windows::Forms::DialogResult::Cancel) { textBox1->AppendText("User cancelled the action !\r\n"); } else if (dR == System::Windows::Forms::DialogResult::Yes) { textBox1->AppendText("You're amazing !!\r\n"); } else if (dR == System::Windows::Forms::DialogResult::No) { textBox1->AppendText("Whaaaaat ??!!\r\n"); } } else { MessageBox::Show("Pleaseeeeee check me !\r\n"); } } private: System::Void checkBox1_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("You changed the checkBox1 to " + checkBox1->Checked.ToString() + "\r\n"); } RadioButton^ gimmeActiveRadioButton() { if (radioButton1->Checked) { return radioButton1; } else if (radioButton2->Checked) { return radioButton2; } else if (radioButton3->Checked) { return radioButton3; } } private: System::Void btnRadioButton_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("Radiobutton : " + gimmeActiveRadioButton()->Name); } private: System::Void btnComboboxValue_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void cmbBlubb_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(cmbBlubb->Text); } private: System::Void btnComboAddItem_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->Add("WoW"); } private: System::Void btnComboremoveItem_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->RemoveAt(2); } private: System::Void btnComboInsert_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->Insert(2, "Test"); } private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { int selectedItemsCount = listBox1->SelectedItems->Count; for (int i = 0;i < selectedItemsCount;i++) { textBox1->AppendText(listBox1->SelectedItems[i]->ToString() + "\r\n"); } } private: System::Void btnNextStep_Click(System::Object^ sender, System::EventArgs^ e) { if (step == 0) { txtQuestions->Clear(); txtQuestions->AppendText("Wie heisst Du ?\r\n"); txtAnswers->Clear(); } else if (step == 1) { txtQuestions->AppendText("Du heisst also " + txtAnswers->Text + " !\r\n"); antwort1 = txtAnswers->Text; txtQuestions->AppendText("Wie alt bist Du ?\r\n"); txtAnswers->Clear(); } else if (step == 2) { txtQuestions->AppendText("Du bist also " + txtAnswers->Text + " alt !\r\n"); antwort2 = txtAnswers->Text; txtQuestions->AppendText("Was ist Deine Lieblingsfarbe ?\r\n"); txtAnswers->Clear(); } else if (step == 3) { txtQuestions->AppendText("Deine Lieblingsfarbe ist also " + txtAnswers->Text + " !\r\n"); antwort3 = txtAnswers->Text; txtQuestions->AppendText("Danke für's Gespräch !\r\n"); txtAnswers->Clear(); } step++; } private: System::Void btnChangeFromAnotherClass_Click(System::Object^ sender, System::EventArgs^ e) { t = gcnew Test(); //t->changeTextBoxText(this); } private: System::Void btnStartProgress_Click(System::Object^ sender, System::EventArgs^ e) { //for(int counter = 0;counter <=100 ;counter++){ // System::Threading::Thread::Sleep(500); // progressBar1->Value = counter; //} progress = 0; timer1->Enabled = true; } private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) { if (progress <= 100) { progressBar1->Value = progress; progress += 5; } else { timer1->Enabled = false; } } private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(trackBar1->Value + "\r\n"); } private: System::Void toolStripMenuItem2_Click(System::Object^ sender, System::EventArgs^ e) { openFileDialog1->Filter = "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"; openFileDialog1->FilterIndex = 2; openFileDialog1->InitialDirectory = "d:\\"; System::Windows::Forms::DialogResult dialogResult = openFileDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { if (openFileDialog1->Multiselect == true) { for each(String^ einFileName in openFileDialog1->FileNames) { textBox1->AppendText(einFileName + "\r\n"); } } else { textBox1->AppendText(openFileDialog1->FileName + "\r\n"); String^ inhaltDerDatei = System::IO::File::ReadAllText(openFileDialog1->FileName); textBox1->AppendText(inhaltDerDatei); } } else { textBox1->AppendText("Datei auswählen !\r\n"); } } private: System::Void mnuFarben_Click(System::Object^ sender, System::EventArgs^ e) { System::Windows::Forms::DialogResult dialogResult = colorDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { textBox1->BackColor = colorDialog1->Color; } } private: System::Void mnuSaveFileDialog_Click(System::Object^ sender, System::EventArgs^ e) { saveFileDialog1->Filter = "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"; saveFileDialog1->FilterIndex = 2; saveFileDialog1->InitialDirectory = "d:\\"; System::Windows::Forms::DialogResult dialogResult = saveFileDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { System::IO::File::WriteAllText(saveFileDialog1->FileName, textBox1->Text); } } private: System::Void mnuSchriftart_Click(System::Object^ sender, System::EventArgs^ e) { System::Windows::Forms::DialogResult dialogResult = fontDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { textBox1->Font = fontDialog1->Font; textBox1->ForeColor = fontDialog1->Color; } } private: System::Void mnuRichtextBox_Click(System::Object^ sender, System::EventArgs^ e) { richTextBox1->SaveFile("d:\\richtexttest.rtf"); } private: System::Void mnuFolderBrowser_Click(System::Object^ sender, System::EventArgs^ e) { folderBrowserDialog1->ShowDialog(); } private: System::Void mnuClearText_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->Clear(); } private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e) { DateTime t = dateTimePicker1->Value; DateTime aktuelleZeit = DateTime::Now; textBox1->AppendText(t.ToLongDateString() + "\n"); textBox1->AppendText(aktuelleZeit.ToLongTimeString() + "\n"); TimeSpan dauer(10, 10, 10, 10); DateTime summe = t.Add(dauer); } private: System::Void mnuButtonsHerstellen_Click(System::Object^ sender, System::EventArgs^ e) { for (int counter = 0; counter < 10;counter++) { System::Windows::Forms::Button^ btnDynamicButton = gcnew System::Windows::Forms::Button; btnDynamicButton->Location = System::Drawing::Point(0, 0 + 25 * counter); btnDynamicButton->Name = L"btnDynamicButton" + counter; btnDynamicButton->Size = System::Drawing::Size(109, 23); btnDynamicButton->TabIndex = 8; btnDynamicButton->Text = L"I'm dynamic " + counter; btnDynamicButton->UseVisualStyleBackColor = true; btnDynamicButton->Click += gcnew System::EventHandler(this, &MainForm::dynamicButtonsClick); tabPage2->Controls->Add(btnDynamicButton); } } private: System::Void mnuListControls_Click(System::Object^ sender, System::EventArgs^ e) { for each(Control^ control in tabPage2->Controls) { textBox1->AppendText(control->Name + "\n"); } } private: System::Void dynamicButtonsClick(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("Dynamic Button clicked !\t" + ((Button^)sender)->Name + "\n"); if (((Button^)sender)->Name == "btnDynamicButton3") { MessageBox::Show("Du hast den richtigen Button gedrückt !"); } } private: System::Void mnuTextBoxenHerstellen_Click(System::Object^ sender, System::EventArgs^ e) { createTextBoxes(); } void createTextBoxes() { for (int counter = 0;counter < 10;counter++) { TextBox^ dynamicTextBox = gcnew TextBox; dynamicTextBox->Location = System::Drawing::Point(200, 0 + 25 * counter); dynamicTextBox->Name = L"textBox" + counter; dynamicTextBox->ScrollBars = System::Windows::Forms::ScrollBars::Both; dynamicTextBox->TabIndex = 67; dynamicTextBox->TextChanged += gcnew System::EventHandler(this, &MainForm::dynamicTextBoxesTextChanged); tabPage2->Controls->Add(dynamicTextBox); } } private: System::Void dynamicTextBoxesTextChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(((TextBox^)sender)->Name + " TextChanged : " + ((TextBox^)sender)->Text + "\n"); } private: System::Void btnAddDoubles_Click(System::Object^ sender, System::EventArgs^ e) { double ersteZahl = Double::Parse(txtErsteZahl->Text); double zweiteZahl = Double::Parse(txtZweiteZahl->Text); double ergebnis = ersteZahl + zweiteZahl; textBox1->AppendText(ergebnis.ToString("N2")); } private: System::Void btnArrayList_Click(System::Object^ sender, System::EventArgs^ e) { ArrayList^ listeVonElementen = gcnew ArrayList; listeVonElementen->Add("Bli"); txtCollections->AppendText("\n:::" + listeVonElementen[0]->ToString() + "\n"); listeVonElementen->Add("Bla"); listeVonElementen->Add("Blubb"); listeVonElementen->Add("Yeah"); listeVonElementen->Add(this); listeVonElementen->Add(3); listeVonElementen->Add(gcnew Button); listeVonElementen->Remove("Bli"); txtCollections->AppendText(listeVonElementen->IndexOf("Yeah").ToString()); listeVonElementen->Insert(3, "Blubbbbbb"); listeVonElementen->Reverse(); for each(Object^ o in listeVonElementen) { txtCollections->AppendText(o->GetType() + " | " + o->ToString() + "\r\n"); } } private: System::Void btnQueue_Click(System::Object^ sender, System::EventArgs^ e) { System::Collections::Queue^ queue = gcnew System::Collections::Queue; queue->Enqueue("1"); queue->Enqueue("3"); queue->Enqueue("2"); queue->Enqueue("4"); txtCollections->Text += queue->Count.ToString(); int count = queue->Count; for (int counter = 1;counter <= count;counter++) { txtCollections->AppendText(queue->Dequeue()->ToString()); //NICHT rausnehmen, nur drauf schauen //txtCollections->AppendText(queue->Peek()->ToString()); } } private: System::Void btnStack_Click(System::Object^ sender, System::EventArgs^ e) { Stack^ stack = gcnew Stack; stack->Push("1"); //stack->Push(1); //stack->Push(this); stack->Push("2"); stack->Push("3"); stack->Push("4"); stack->Push("5"); int count = stack->Count; for (int counter = 0;counter < count;counter++) { txtCollections->AppendText((String^)stack->Pop()); } } private: System::Void btnSortedList_Click(System::Object^ sender, System::EventArgs^ e) { SortedList^ sortedList = gcnew SortedList; sortedList->Add(1, "Sieger"); //sortedList->Add(1, "Sieger"); -> Fehler, existiert schon sortedList->Add(3, "Drittplatzierter"); sortedList->Add(2, "Zweiter Sieger"); for each(int key in sortedList->Keys) { txtCollections->AppendText(key + " | " + sortedList[key] + "\r\n"); } SortedList^ sortedList1 = gcnew SortedList; DateTime d = DateTime(1971, 12, 12); sortedList1->Add(d, "Sieger3"); sortedList1->Add(DateTime(1970, 12, 12), "Sieger2"); sortedList1->Add(DateTime(1968, 12, 12), "Sieger1"); for each(DateTime key in sortedList1->Keys) { txtCollections->AppendText(key + " | " + sortedList1[key] + "\r\n"); } } private: System::Void btnHashtable_Click(System::Object^ sender, System::EventArgs^ e) { Hashtable^ openWith = gcnew Hashtable; // Add some elements to the hash table. There are no // duplicate keys, but some of the values are duplicates. openWith->Add("txt", "notepad.exe"); //openWith->Add("txt", "notepad.exe"); -> Fehler openWith->Add("bmp", "paint.exe"); openWith->Add("dib", "paint.exe"); openWith->Add("rtf", "wordpad.exe"); txtCollections->AppendText(openWith["txt"] + "\r\n"); openWith["rtf"] = "winword.exe"; //If the key "ht" doesn't exist, add entry to our Hashtable if (!openWith->ContainsKey("ht")) { openWith->Add("ht", "hypertrm.exe"); } for each(DictionaryEntry de in openWith) { txtCollections->AppendText(de.Key + " | " + de.Value + "\r\n"); } } private: System::Void btnList_Click(System::Object^ sender, System::EventArgs^ e) { //Fully qualified |Diamantoperator System::Collections::Generic::List<String^>^ phrases = gcnew System::Collections::Generic::List<String^>(); phrases->Add("Text"); phrases->Add("Text1"); phrases->Add("Text2"); phrases->Add("Text3"); //phrases->Add(34);-> Fehler for each(String^ oneElement in phrases) { txtCollections->AppendText(oneElement); } } private: System::Void btnArray_Click(System::Object^ sender, System::EventArgs^ e) { array<String^>^ myArr = { L"The", L"quick", L"brown", L"fox", L"jumps", L"over", L"the", L"lazy", L"dog" }; Array::Resize(myArr, myArr->Length + 5); array<Byte>^ buffer = gcnew array<Byte>(1024); ArrayList^ l = gcnew ArrayList(myArr); l->AddRange(myArr); array<String ^, 3> ^ my3DArray = gcnew array<String ^, 3>(3, 5, 6); my3DArray[0, 0, 0] = "Bla"; ArrayList^ zeile = gcnew ArrayList; ArrayList^ spalte = gcnew ArrayList; spalte->Add(zeile); ((ArrayList^)spalte[0])[0] = "j"; } private: System::Void btnBenchmark_Click(System::Object^ sender, System::EventArgs^ e) { int size = 10000000; ArrayList^ numbers = gcnew ArrayList; DateTime startTime = DateTime::Now; for (int counter = 0; counter < size; counter++) { numbers->Add(counter); } DateTime endTime = DateTime::Now; txtCollections->AppendText("\r\nCreation of 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; array<int>^ intArray = gcnew array<int>(size); for (int counter = 0; counter < size; counter++) { intArray[counter] = counter; } endTime = DateTime::Now; txtCollections->AppendText("\r\nCreation of 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; for (int counter = 0;counter < size;counter++) { int temp = (int)numbers[counter]; } endTime = DateTime::Now; txtCollections->AppendText("\r\nAccessing 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; for (int counter = 0;counter < size;counter++) { int temp = intArray[counter]; } endTime = DateTime::Now; txtCollections->AppendText("\r\nAccessing 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds); } private: System::Void btnDrawLine_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics(); System::Drawing::Pen^ penRed = gcnew System::Drawing::Pen(Color::Red); System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue); System::Drawing::Pen^ penGreen = gcnew System::Drawing::Pen(Color::Green); System::Drawing::Brush^ brushYellow = gcnew System::Drawing::SolidBrush(Color::Yellow); graphics->DrawLine(penRed, 0, 0, 100, 300); graphics->DrawLine(penBlue, 100, 200, 0, 0); graphics->DrawEllipse(penGreen, 20, 90, 40, 20); graphics->FillRectangle(brushYellow, 70, 70, 30, 60); } System::Drawing::Point lastPoint = Point(0, 0); ArrayList^ points; private: System::Void pnlDrawing_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics(); System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); // |Umrechnung |aktuelle Mouseposition Bildschirm System::Drawing::Point actualPosition = pnlDrawing->PointToClient(this->Cursor->Position); graphics->DrawLine(penBlack, lastPoint, actualPosition); lastPoint = actualPosition; points->Add(lastPoint); System::Diagnostics::Debug::WriteLine(actualPosition.ToString()); } private: System::Void pnlDrawing_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { drawLinesByPoints(e->Graphics); } void drawLinesByPoints(Graphics^ g) { System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); int pointsCount = points->Count; for (int counter = 0; counter < pointsCount - 1;counter++) { g->DrawLine(penBlack, (Point)points[counter], (Point)points[counter + 1]); } } void translatePoints(int factor) { int pointsCount = points->Count; for (int counter = 0; counter < pointsCount - 1;counter++) { Point newPoint = Point(((Point)points[counter]).X * factor, ((Point)points[counter]).Y * factor); points[counter] = newPoint; } } private: System::Void btnTranslatePoints_Click(System::Object^ sender, System::EventArgs^ e) { translatePoints(2); pnlDrawing->CreateGraphics()->Clear(Color::Gainsboro); pnlDrawing->Refresh(); } private: System::Void btnDrawImage_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); System::Drawing::Image^ image = Image::FromFile("d:\\spaghettimonster.jpg"); Graphics^ imageGraphics = Graphics::FromImage(image); imageGraphics->DrawLine(penBlack, 0, 0, 200, 200); Point ulCorner = Point(100, 0); pnlGraphics->CreateGraphics()->DrawImage(image, ulCorner); image->Save("d:\\spaghettimonster12.jpg"); } private: System::Void btnDrawHouse_Click(System::Object^ sender, System::EventArgs^ e) { for (int counter = 0.1;counter < 2;counter += 0.1) { drawHouse(pnlGraphics->CreateGraphics(), 0 + 10 * counter, 0 + 10 * counter, counter, counter); } } void drawHouse(Graphics^ graphics, int startPositionX, int startPositionY, double scaleFactorX, double scaleFactorY) { System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 300, 0, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 100, 200, 300, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 0, 300, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 100, 20, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 300, 20, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 300, 20, 400, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 100, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 300, 400, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 400, 300, scaleFactorX, scaleFactorY); } void drawSpecialLine(Graphics^ graphics, Pen^ pen, float startPositionX, float startPositionY, float x1, float y1, float x2, float y2, float scaleFactorX, float scaleFactorY) { graphics->DrawLine(pen, startPositionX + x1 * scaleFactorX, startPositionY + y1 * scaleFactorY, startPositionX + x2 * scaleFactorX, startPositionY + y2 * scaleFactorY); } }; }
[ "Alfa-Dozent@SB-U03-001" ]
Alfa-Dozent@SB-U03-001
3d123ac5a89cbca6d50abbc06a65c9bdfd1b3453
ac3281345cb13c00e0150b4cfde5a6fffa3d0e0b
/src/Magnum/Vk/Test/LayerPropertiesVkTest.cpp
5b94d376e7abeaedb3b08620270cb41f4b92d2aa
[ "MIT" ]
permissive
mosra/magnum
dc2fc08d634dceaf454c0b8190d2ebd530bb8fa9
c9a2752545aa2aa8b7db4879834d3998c6cac655
refs/heads/master
2023-09-03T21:02:39.001932
2023-09-03T13:49:25
2023-09-03T16:07:04
1,182,756
4,747
535
NOASSERTION
2023-07-23T07:36:34
2010-12-19T22:19:59
C++
UTF-8
C++
false
false
5,439
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/Containers/String.h> #include <Corrade/TestSuite/Tester.h> #include <Corrade/TestSuite/Compare/Numeric.h> #include <Corrade/Utility/DebugStl.h> #include <Corrade/Utility/FormatStl.h> #include "Magnum/Vk/LayerProperties.h" #include "Magnum/Vk/Version.h" namespace Magnum { namespace Vk { namespace Test { namespace { struct LayerPropertiesVkTest: TestSuite::Tester { explicit LayerPropertiesVkTest(); void constructMove(); void enumerate(); void outOfRange(); void isSupported(); }; LayerPropertiesVkTest::LayerPropertiesVkTest() { addTests({&LayerPropertiesVkTest::constructMove, &LayerPropertiesVkTest::enumerate, &LayerPropertiesVkTest::outOfRange, &LayerPropertiesVkTest::isSupported}); } using namespace Containers::Literals; void LayerPropertiesVkTest::constructMove() { LayerProperties a = enumerateLayerProperties(); const UnsignedInt count = a.count(); if(!count) CORRADE_SKIP("No extensions reported, can't test"); LayerProperties b = std::move(a); CORRADE_COMPARE(b.count(), count); LayerProperties c{NoCreate}; c = std::move(b); CORRADE_COMPARE(c.count(), count); CORRADE_VERIFY(std::is_nothrow_move_constructible<LayerProperties>::value); CORRADE_VERIFY(std::is_nothrow_move_assignable<LayerProperties>::value); } void LayerPropertiesVkTest::enumerate() { LayerProperties properties = enumerateLayerProperties(); if(!properties.count()) CORRADE_SKIP("The driver reported no instance layers, can't test."); CORRADE_COMPARE(properties.count(), properties.names().size()); Debug{} << "Available instance layers:" << properties.names(); Containers::ArrayView<const Containers::StringView> names = properties.names(); CORRADE_COMPARE_AS(names.size(), 0, TestSuite::Compare::Greater); /* The list should be sorted */ for(std::size_t i = 1; i != names.size(); ++i) { CORRADE_COMPARE_AS(names[i - 1], names[i], TestSuite::Compare::Less); } /* MoltenVK Y U so weird!! */ if(properties.name(0) != "MoltenVK"_s) CORRADE_COMPARE_AS(properties.name(0).size(), "VK_LAYER_"_s.size(), TestSuite::Compare::Greater); CORRADE_COMPARE_AS(properties.revision(0), 0, TestSuite::Compare::Greater); CORRADE_COMPARE_AS(properties.version(0), Version::Vk10, TestSuite::Compare::GreaterOrEqual); CORRADE_COMPARE_AS(properties.description(0).size(), 10, TestSuite::Compare::Greater); } void LayerPropertiesVkTest::outOfRange() { CORRADE_SKIP_IF_NO_ASSERT(); LayerProperties properties = enumerateLayerProperties(); const UnsignedInt count = properties.count(); std::ostringstream out; Error redirectError{&out}; properties.name(count); properties.revision(count); properties.version(count); properties.description(count); CORRADE_COMPARE(out.str(), Utility::formatString( "Vk::LayerProperties::name(): index {0} out of range for {0} entries\n" "Vk::LayerProperties::revision(): index {0} out of range for {0} entries\n" "Vk::LayerProperties::version(): index {0} out of range for {0} entries\n" "Vk::LayerProperties::description(): index {0} out of range for {0} entries\n", count)); } void LayerPropertiesVkTest::isSupported() { LayerProperties properties = enumerateLayerProperties(); CORRADE_VERIFY(!properties.isSupported("this layer doesn't exist")); /* Verify that we don't dereference garbage when std::lower_bound() returns `last` */ CORRADE_VERIFY(!properties.isSupported("ZZZZZ")); if(!properties.count()) CORRADE_SKIP("The driver reported no instance layers, can't fully test."); for(UnsignedInt i = 0; i != properties.count(); ++i) { CORRADE_ITERATION(properties.name(i)); CORRADE_VERIFY(properties.isSupported(properties.name(i))); } /* Verify that we're not just comparing a prefix */ CORRADE_VERIFY(!properties.isSupported(properties.name(0) + "_hello"_s)); } }}}} CORRADE_TEST_MAIN(Magnum::Vk::Test::LayerPropertiesVkTest)
[ "mosra@centrum.cz" ]
mosra@centrum.cz
85891264a1d67419837e3eb5d19118c8408250d7
a61af411717f996efb3fbbafcf457c2152e45732
/expense_tracker/expense_tracker/Core/Services/TransactionService.h
1ea5cc8dcb835e47ff19863336fccf0849268194
[]
no_license
mchesanovskyy/expense_tracker
340b22aca4cc3087ca7c62e61eb7ae75dac4c8b8
3a32be2fa7f56c0136109aa9d4b1bc722573cead
refs/heads/main
2023-07-03T19:44:43.928871
2021-08-05T08:53:54
2021-08-05T08:53:54
386,206,857
0
0
null
null
null
null
UTF-8
C++
false
false
960
h
#pragma once #include "../Interfaces/ITransactionService.h" #include "../Interfaces/Repositories/ITransactionRepository.h" class TransactionService : public ITransactionService { ITransactionRepository* _repository; public: TransactionService(ITransactionRepository& repository) : _repository(&repository) { } Transaction* Add(int userId, TransactionModelIn& model) override { const auto transaction = new Transaction; transaction->Amount = model.IsProfit ? model.Amount : model.Amount * -1; transaction->Timestamp = model.Timestamp; transaction->Title = model.Title; transaction->UserId = userId; const int createdTransId = _repository->Add(*transaction); return _repository->GetById(createdTransId); } vector<Transaction*> GetUserTransactions(int userId) override { return _repository->GetUserTransactions(userId); } bool Delete(int transactionId) override { return _repository->Delete(transactionId); } };
[ "nick.chesanovskyy@gmail.com" ]
nick.chesanovskyy@gmail.com
e4cbec6cc2a0591b1fedbf5d9b4f10d75ad1dabf
5914f131402a16bde8c8f40faed58812e1f9f5a4
/n8Arduino/hw5n8o/n8hw5/n8hw5.ino
ba69d864c27b3b8d987822fb68b6fa69678527be
[]
no_license
electronate/Homework5A2Bluetooth
e2540c3cdfbbff764aa22ce874380f39164c8145
d18c4da5fe7c7b1654f078b804c1bd9c863cad1f
refs/heads/master
2016-09-06T19:05:31.300698
2014-05-12T23:30:00
2014-05-12T23:30:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,379
ino
#include "foneastrapins.h" #include <SoftwareSerial.h> // Creates a SoftwareSerial so you can talk to the SoftwareSerial swSerial(SW_UART_RX_PIN, SW_UART_TX_PIN); // RX, TX void setup(void) { //set up the HW UART to communicate with the BT module Serial.begin(38400); swSerial.begin(38400); // Provide power to BT pinMode(BT_PWR_PIN,OUTPUT); digitalWrite(BT_PWR_PIN,HIGH); // Turn on the red light pinMode(RED_LED_PIN,OUTPUT); digitalWrite(RED_LED_PIN, HIGH); } void printBattery(void) { // Get the battery level from a builtin ADC unsigned short battLvlADC = analogRead(BATT_LVL_PIN); // Convert that ADC value to a rough estimation of volt float battLvlVoltage = 0.0032 * battLvlADC; float key; // Print out the raw ADC value, and the voltage, followed by a Newline Serial.print("raw batt lvl: "); Serial.print(battLvlADC); Serial.print(" voltage at BATT_LVL: "); Serial.print(battLvlVoltage); Serial.println(); // Do the same for the swSerial, connected to the PC swSerial.print("raw batt lvl: "); swSerial.print(battLvlADC); swSerial.print(" voltage at BATT_LVL: "); swSerial.print(battLvlVoltage); swSerial.println(); if( Serial.available() > 0 ){ Serial.print("\n Serial Available! \n"); key = Serial.read(); swSerial.print(key); Serial.print(key); } } void buzzdot(void){ //buzz for a short time tone( BUZZER_PIN, 500, 100 ); delay( 100 ); } void buzzdash(void){ //buzz for a short time tone( BUZZER_PIN, 500, 500 ); delay( 100 ); } void morse(void){ //char myChar; if(Serial.available() > 0){ //Citation: http://arduino.cc/en/Reference/sizeof //Citation: http://arduino.cc/en/Reference/StreamRead for(int i=0; i < /*sizeof(myChar)*/Serial.available(); i++){ char myChar = Serial.read(); swSerial.print(myChar); Serial.print(myChar); if(myChar == '.'){ buzzdot(); }else if(myChar == '-'){ buzzdash(); }else if(myChar == ' '){ delay(1200); }else{ Serial.print(myChar); Serial.print(" is unknown character, please use dot . or dash - only \n"); swSerial.print(myChar); swSerial.print(" is unknown character, please use dot . or dash - only \n"); swSerial.println(); } delay(600); } } } void loop(void) { morse(); }
[ "nate.olds@gmail.com" ]
nate.olds@gmail.com
77179291b14ee647b8096466c790d48f39d1e708
48ddbc11cabea98a988f9de3fef7e4f6213e18c1
/diffuser_chain/basic_elements/vane_diffuser/system/fvSchemes.simpleFoam
8bbdffce6edbd45c0e054833d462afd0e6196944
[]
no_license
lhooz/diffuser_2d
9ac08d009597f68dc8c22dac01121417ba22b889
f3e5ab69f3bbd035e2e4c6859a852de097aabfe8
refs/heads/main
2023-01-31T07:13:38.458461
2020-12-17T02:12:12
2020-12-17T02:12:12
312,403,813
0
0
null
null
null
null
UTF-8
C++
false
false
1,693
simplefoam
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; object fvSchemes; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ddtSchemes { default steadyState; //default Euler; } gradSchemes { default Gauss linear; limited cellLimited Gauss linear 1; grad(U) $limited; grad(k) $limited; grad(omega) $limited; } divSchemes { default none; div(phi,U) bounded Gauss linearUpwind unlimited; div(div(phi,U)) Gauss linear; turbulence bounded Gauss linearUpwind limited; div(phi,k) $turbulence; div(phi,omega) $turbulence; div(phi,epsilon) $turbulence; div((nuEff*dev(T(grad(U))))) Gauss linear; div((nuEff*dev2(T(grad(U))))) Gauss linear; } laplacianSchemes { default Gauss linear corrected; } interpolationSchemes { default linear; } snGradSchemes { default corrected; } wallDist { method meshWave; } // ************************************************************************* //
[ "hao.lee0019@gmail.com" ]
hao.lee0019@gmail.com
023940c1cbe30e9b04fd7346803fb68d80f9b3f3
330f81dc5de92d7040f259b36e1182e9093c6c38
/Algorithms/BitManupulaiton/findSquare.cpp
737b59fe84ec9286ac0c063fe90e8de6e7aff433
[]
no_license
Ujwalgulhane/Data-Structure-Algorithm
75f0bdd9a20de2abf567ee1f909aa91e3c2f5cfc
e5f8db3a313b3f634c002ec975e0b53029e82d90
refs/heads/master
2023-08-25T02:36:57.045798
2021-10-26T07:13:58
2021-10-26T07:13:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,259
cpp
#include"bits/stdc++.h" using namespace std; #define fo(i, n) for (i = 0; i < n; i++) #define Fo(i, k, n) for (i = k; k < n ? i < n : i > n; k < n ? i += 1 : i -= 1) #define ll long long #define si(x) scanf("%d", & x) #define sl(x) scanf("%lld", & x) #define ss(s) scanf("%s", s) #define pi(x) printf("%d\n", x) #define pl(x) printf("%lld\n", x) #define ps(s) printf("%s\n", s) #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl #define all(x) x.begin(), x.end() #define sortall(x) sort(all(x)) #define tr(it, a) for (auto it = a.begin(); it != a.end(); it++) #define PI 3.1415926535897932384626 typedef vector < int > vi; typedef vector <string> vs; const int mod = 1'000'000'007; int findSquare(int i){ int a=0,b=i>>1; if(!i) return i; if(i&1){ return ((findSquare(b)<<2)+(b<<2)+1); }else{ return (findSquare(b)<<2); } } void solve() { int i, j, n, m; cin>>i; pi((0<<2)<<2); // pi(findSquare(i)); } int main() { // #ifndef ONLINE_JUDGE // freopen("inp.txt","r",stdin); // freopen("out.txt","w",stdout); // #endif ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t = 1; cin >> t; while (t--) { solve(); } return 0; }
[ "siddhant.sarkar999@gmail.com" ]
siddhant.sarkar999@gmail.com
88a736d83cffc81013a27fc9239700fb4c96ca09
9c7a0296af07bf6c475f665fcccb855ccf7a526e
/core/modules/replica/tools/qserv-replica-job-sql.cc
42407046bf17424e35b1bd093e2ddacdde4fc8f1
[]
no_license
provingground-moe/qserv
6ecbf227442d335d26dc2238c5e4142a6ae2ea25
97016932a752c0e641571538912d309cd3dd461b
refs/heads/master
2020-06-10T20:45:10.955752
2019-05-22T19:59:19
2019-05-22T19:59:19
136,348,562
0
0
null
2018-06-06T15:27:00
2018-06-06T15:26:59
null
UTF-8
C++
false
false
1,286
cc
/* * LSST Data Management System * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ /** * @see SqlApp */ // System headers #include <iostream> #include <stdexcept> // Qserv headers #include "replica/SqlApp.h" using namespace std; using namespace lsst::qserv::replica; int main(int argc, char* argv[]) { try { auto const app = SqlApp::create(argc, argv); return app->run(); } catch (exception const& ex) { cerr << "main() the application failed, exception: " << ex.what() << endl; return 1; } }
[ "gapon@slac.stanford.edu" ]
gapon@slac.stanford.edu
e2af2e9177fbaf3c51d8467e8f127935a0cb67d5
cf65368fe28c73525cb75ca64e1b954eb90f15d0
/test_rat.cpp
b2681d6dabbb151976f9447d04b37b62caab0c43
[]
no_license
sj-simmons/math-tools-cpp
76f5feaab0576ca224f7a833eb0c9d8cb073ac07
a7127b2520ffbf82abfdf6dd10eed615b9e2786e
refs/heads/master
2021-07-22T19:49:10.863217
2018-05-19T20:51:14
2021-07-15T23:17:23
133,449,957
0
0
null
null
null
null
UTF-8
C++
false
false
1,814
cpp
//test_rat.cpp #include <iostream> #include <cmath> #include "Rational.h" #include "gmpxx.h" using namespace std; int main() { cout << "Testing gcd: "; mpz_class m, n; m="-123123124124"; n="13214"; cout << " checking modulo " << m % n << endl; cout << " checking gcd " << gcd(m, n) << endl; Rational<int> rrrr(3); cout << " checking coersion " << rrrr << endl; using coeff_type = mpz_class; //using coeff_type = long long; cout << "testing default constructor" << endl; Rational<coeff_type> rrr; cout << " it constructs: "<< rrr << endl << endl; cout << "testing arrays of rationals " << endl; Rational<coeff_type> arr[5] = { {1,2},{5,6} }; for (int i = 0; i != 5; ++i) { cout << arr[i] << " "; } cout << "\n" << endl; Rational<int> r1(2,-3); Rational<int> r2(2,4); cout << "r1 " << r1 << " r2 " << r2 << endl; r1 += r2; cout << "r1 += r2"<< r1 << endl; cout << r1 << " + " << r2 << " = " << r1+r2 << endl; cout << r1 << " * " << r2 << " = " << r1*r2 << endl; cout << r1 << " - " << r2 << " = " << r1-r2 << endl; cout << r1 << " / " << r2 << " = " << r1/r2 << endl; //Rational<int> r3(3,1); Rational<int> r3; cout << "Rational(3,1) num=" << r3.num() << " den= " << r3.den() << " get " << r3 << endl; cout << -r3 << endl; Rational<int> r4(0,1); cout << "Rational(0,1) num=" << r4.num() << " den= " << r4.den() << " get " << r4 << endl; Rational<int> r5(0,-1); cout << "Rational(0,-1) num=" << r5.num() << " den= " << r5.den() << " get " << r5 << endl; int a, b; cout << "Enter numbers or q: "; cin >> a >> b ; Rational<int> r6(a,b); cout << r6 << endl; r6.set(1,2); cout << r6 << endl; cout << (r6 != 0) << endl; cout << r5 << " " << (r5 != 0) << endl; cout << Rational<int>(17,1)*r2 << endl; return 0; }
[ "ssimmons1331@gmail.com" ]
ssimmons1331@gmail.com
2bb7d1ba4a57837200a2453e820d7706fa864fd7
127b4bb0893d5ca8fb066e9e2d770538240432ea
/yellowfellow-ac/UVA/12324/16158651_AC_30ms_0kB.cpp
6699417a5eb0dc7092ce9b8ae44335fe771cb969
[]
no_license
kuningfellow/Kuburan-CP
5481f3f7fce9471acd108dc601adc183c9105672
2dc8bbc8c18a8746d32a4a20910b717c066d0d41
refs/heads/master
2020-04-24T15:13:40.853652
2019-12-24T07:21:38
2019-12-24T07:21:38
172,057,574
0
0
null
null
null
null
UTF-8
C++
false
false
608
cpp
//UVA 12324 Philip J. Fry Problem #include<bits/stdc++.h> using namespace std; int dp[105][105]; int ar[105]; int br[105]; int n; int serc(int x, int r){ r = min(r, n); if (x == n) return 0; if (dp[x][r] != -1) return dp[x][r]; return dp[x][r] = min(ar[x] + serc(x+1, r+br[x]), r>0 ? ar[x]/2 + serc(x+1, r-1+br[x]) : (-1)^(1 << 31)); } int main(){ while (1 < 2) { scanf("%d", &n); if (n == 0) break; for (int i = 0; i < n; i++) { scanf("%d%d", &ar[i], &br[i]); } for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { dp[i][j] = -1; } } printf("%d\n", serc(0, 0)); } }
[ "williamgunawaneka@gmail.com" ]
williamgunawaneka@gmail.com
880ff26682aa84620575e7a41eec846365f357a4
f8573941754a429f481c18b46ad5337d1bb55609
/PhysX 3.3.1/Source/PhysXExtensions/src/ExtTriangleMeshExt.cpp
192a76a910694d25daa23088059e055f1d2b9010
[]
no_license
frbyles/ExcavatorSimulator
409fa4ad56ba3d786dedfffb5d981db86d89f4f5
c4be4ea60cd1c62c0d0207af31dfed4a47ef6124
refs/heads/master
2021-01-19T11:38:04.166440
2015-11-12T17:45:52
2015-11-12T17:45:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,948
cpp
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PxTriangleMeshExt.h" #include "PxMeshQuery.h" #include "PxGeometryQuery.h" #include "PxTriangleMeshGeometry.h" #include "PxHeightFieldGeometry.h" #include "PxTriangleMesh.h" #include "PsAllocator.h" using namespace physx; PxMeshOverlapUtil::PxMeshOverlapUtil() : mResultsMemory(mResults), mNbResults(0), mMaxNbResults(64) { } PxMeshOverlapUtil::~PxMeshOverlapUtil() { if(mResultsMemory != mResults) PX_FREE(mResultsMemory); } PxU32 PxMeshOverlapUtil::findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose) { bool overflow; PxU32 nbTouchedTris = PxMeshQuery::findOverlapTriangleMesh(geom, geomPose, meshGeom, meshPose, mResultsMemory, mMaxNbResults, 0, overflow); if(overflow) { const PxU32 maxNbTris = meshGeom.triangleMesh->getNbTriangles(); if(!maxNbTris) { mNbResults = 0; return 0; } if(mMaxNbResults<maxNbTris) { if(mResultsMemory != mResults) PX_FREE(mResultsMemory); mResultsMemory = (PxU32*)PX_ALLOC(sizeof(PxU32)*maxNbTris, PX_DEBUG_EXP("PxMeshOverlapUtil::findOverlap")); mMaxNbResults = maxNbTris; } nbTouchedTris = PxMeshQuery::findOverlapTriangleMesh(geom, geomPose, meshGeom, meshPose, mResultsMemory, mMaxNbResults, 0, overflow); PX_ASSERT(nbTouchedTris); PX_ASSERT(!overflow); } mNbResults = nbTouchedTris; return nbTouchedTris; } PxU32 PxMeshOverlapUtil::findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose) { bool overflow = true; PxU32 nbTouchedTris = 0; do { nbTouchedTris = PxMeshQuery::findOverlapHeightField(geom, geomPose, hfGeom, hfPose, mResultsMemory, mMaxNbResults, 0, overflow); if(overflow) { const PxU32 maxNbTris = mMaxNbResults * 2; if(mResultsMemory != mResults) PX_FREE(mResultsMemory); mResultsMemory = (PxU32*)PX_ALLOC(sizeof(PxU32)*maxNbTris, PX_DEBUG_EXP("PxMeshOverlapUtil::findOverlap")); mMaxNbResults = maxNbTris; } }while(overflow); mNbResults = nbTouchedTris; return nbTouchedTris; } PxVec3 physx::PxComputeMeshPenetration(PxU32 maxIter, const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose, PxU32& nb) { PxU32 nbIter = 0; bool isValid = true; PxTransform pose = geomPose; while(isValid && nbIter<maxIter) { PxVec3 mtd; PxF32 depth; isValid = PxGeometryQuery::computePenetration(mtd, depth, geom, pose, meshGeom, meshPose); if(isValid) { nbIter++; PX_ASSERT(depth>=0.0f); pose.p += mtd * depth; } } nb = nbIter; return pose.p - geomPose.p; } PxVec3 physx::PxComputeHeightFieldPenetration(PxU32 maxIter, const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& meshGeom, const PxTransform& meshPose, PxU32& nb) { PxU32 nbIter = 0; bool isValid = true; PxTransform pose = geomPose; while(isValid && nbIter<maxIter) { PxVec3 mtd; PxF32 depth; isValid = PxGeometryQuery::computePenetration(mtd, depth, geom, pose, meshGeom, meshPose); if(isValid) { nbIter++; PX_ASSERT(depth>=0.0f); pose.p += mtd * depth; } } nb = nbIter; return pose.p - geomPose.p; }
[ "seifes1@gmail.com" ]
seifes1@gmail.com
a6b47b8400874789e4e875b7bd90d7e58efc8234
fb5b25b4fbe66c532672c14dacc520b96ff90a04
/export/release/windows/obj/src/lime/app/_Event_ofEvents_T_Void.cpp
7f67d0c33f4924ffc0424ab7c59b72dd9c12d57e
[ "Apache-2.0" ]
permissive
Tyrcnex/tai-mod
c3849f817fe871004ed171245d63c5e447c4a9c3
b83152693bb3139ee2ae73002623934f07d35baf
refs/heads/main
2023-08-15T07:15:43.884068
2021-09-29T23:39:23
2021-09-29T23:39:23
383,313,424
1
0
null
null
null
null
UTF-8
C++
false
false
11,737
cpp
#include <hxcpp.h> #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED_lime_app__Event_ofEvents_T_Void #include <lime/app/_Event_ofEvents_T_Void.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_602a5331235d55ea_42_new,"lime.app._Event_ofEvents_T_Void","new",0xde11e822,"lime.app._Event_ofEvents_T_Void.new","lime/app/Event.hx",42,0xbda45bec) HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_58_add,"lime.app._Event_ofEvents_T_Void","add",0xde0809e3,"lime.app._Event_ofEvents_T_Void.add","lime/app/Event.hx",58,0xbda45bec) HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_82_cancel,"lime.app._Event_ofEvents_T_Void","cancel",0x39599af8,"lime.app._Event_ofEvents_T_Void.cancel","lime/app/Event.hx",82,0xbda45bec) HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_127_has,"lime.app._Event_ofEvents_T_Void","has",0xde0d571c,"lime.app._Event_ofEvents_T_Void.has","lime/app/Event.hx",127,0xbda45bec) HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_143_remove,"lime.app._Event_ofEvents_T_Void","remove",0x85ae49c2,"lime.app._Event_ofEvents_T_Void.remove","lime/app/Event.hx",143,0xbda45bec) HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_163_removeAll,"lime.app._Event_ofEvents_T_Void","removeAll",0x7c126c7f,"lime.app._Event_ofEvents_T_Void.removeAll","lime/app/Event.hx",163,0xbda45bec) HX_LOCAL_STACK_FRAME(_hx_pos_89c82c0cd6a35496_82_dispatch,"lime.app._Event_ofEvents_T_Void","dispatch",0x766e57b8,"lime.app._Event_ofEvents_T_Void.dispatch","lime/_internal/macros/EventMacro.hx",82,0xc5a10671) namespace lime{ namespace app{ void _Event_ofEvents_T_Void_obj::__construct(){ HX_STACKFRAME(&_hx_pos_602a5331235d55ea_42_new) HXLINE( 44) this->canceled = false; HXLINE( 45) this->_hx___listeners = ::Array_obj< ::Dynamic>::__new(); HXLINE( 46) this->_hx___priorities = ::Array_obj< int >::__new(); HXLINE( 47) this->_hx___repeat = ::Array_obj< bool >::__new(); } Dynamic _Event_ofEvents_T_Void_obj::__CreateEmpty() { return new _Event_ofEvents_T_Void_obj; } void *_Event_ofEvents_T_Void_obj::_hx_vtable = 0; Dynamic _Event_ofEvents_T_Void_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > _hx_result = new _Event_ofEvents_T_Void_obj(); _hx_result->__construct(); return _hx_result; } bool _Event_ofEvents_T_Void_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2d049712; } void _Event_ofEvents_T_Void_obj::add( ::Dynamic listener,::hx::Null< bool > __o_once,::hx::Null< int > __o_priority){ bool once = __o_once.Default(false); int priority = __o_priority.Default(0); HX_STACKFRAME(&_hx_pos_602a5331235d55ea_58_add) HXLINE( 60) { HXLINE( 60) int _g = 0; HXDLIN( 60) int _g1 = this->_hx___priorities->length; HXDLIN( 60) while((_g < _g1)){ HXLINE( 60) _g = (_g + 1); HXDLIN( 60) int i = (_g - 1); HXLINE( 62) if ((priority > this->_hx___priorities->__get(i))) { HXLINE( 64) this->_hx___listeners->insert(i,listener); HXLINE( 65) this->_hx___priorities->insert(i,priority); HXLINE( 66) this->_hx___repeat->insert(i,!(once)); HXLINE( 67) return; } } } HXLINE( 71) this->_hx___listeners->push(listener); HXLINE( 72) this->_hx___priorities->push(priority); HXLINE( 73) this->_hx___repeat->push(!(once)); } HX_DEFINE_DYNAMIC_FUNC3(_Event_ofEvents_T_Void_obj,add,(void)) void _Event_ofEvents_T_Void_obj::cancel(){ HX_STACKFRAME(&_hx_pos_602a5331235d55ea_82_cancel) HXDLIN( 82) this->canceled = true; } HX_DEFINE_DYNAMIC_FUNC0(_Event_ofEvents_T_Void_obj,cancel,(void)) bool _Event_ofEvents_T_Void_obj::has( ::Dynamic listener){ HX_STACKFRAME(&_hx_pos_602a5331235d55ea_127_has) HXLINE( 129) { HXLINE( 129) int _g = 0; HXDLIN( 129) ::Array< ::Dynamic> _g1 = this->_hx___listeners; HXDLIN( 129) while((_g < _g1->length)){ HXLINE( 129) ::Dynamic l = _g1->__get(_g); HXDLIN( 129) _g = (_g + 1); HXLINE( 131) if (::Reflect_obj::compareMethods(l,listener)) { HXLINE( 131) return true; } } } HXLINE( 135) return false; } HX_DEFINE_DYNAMIC_FUNC1(_Event_ofEvents_T_Void_obj,has,return ) void _Event_ofEvents_T_Void_obj::remove( ::Dynamic listener){ HX_STACKFRAME(&_hx_pos_602a5331235d55ea_143_remove) HXLINE( 145) int i = this->_hx___listeners->length; HXLINE( 147) while(true){ HXLINE( 147) i = (i - 1); HXDLIN( 147) if (!((i >= 0))) { HXLINE( 147) goto _hx_goto_6; } HXLINE( 149) if (::Reflect_obj::compareMethods(this->_hx___listeners->__get(i),listener)) { HXLINE( 151) this->_hx___listeners->removeRange(i,1); HXLINE( 152) this->_hx___priorities->removeRange(i,1); HXLINE( 153) this->_hx___repeat->removeRange(i,1); } } _hx_goto_6:; } HX_DEFINE_DYNAMIC_FUNC1(_Event_ofEvents_T_Void_obj,remove,(void)) void _Event_ofEvents_T_Void_obj::removeAll(){ HX_STACKFRAME(&_hx_pos_602a5331235d55ea_163_removeAll) HXLINE( 165) int len = this->_hx___listeners->length; HXLINE( 167) this->_hx___listeners->removeRange(0,len); HXLINE( 168) this->_hx___priorities->removeRange(0,len); HXLINE( 169) this->_hx___repeat->removeRange(0,len); } HX_DEFINE_DYNAMIC_FUNC0(_Event_ofEvents_T_Void_obj,removeAll,(void)) void _Event_ofEvents_T_Void_obj::dispatch( ::Dynamic a){ HX_STACKFRAME(&_hx_pos_89c82c0cd6a35496_82_dispatch) HXLINE( 83) this->canceled = false; HXLINE( 85) ::Array< ::Dynamic> listeners = this->_hx___listeners; HXLINE( 86) ::Array< bool > repeat = this->_hx___repeat; HXLINE( 87) int i = 0; HXLINE( 89) while((i < listeners->length)){ HXLINE( 91) listeners->__get(i)(a); HXLINE( 93) if (!(repeat->__get(i))) { HXLINE( 95) this->remove(listeners->__get(i)); } else { HXLINE( 99) i = (i + 1); } HXLINE( 102) if (this->canceled) { HXLINE( 104) goto _hx_goto_9; } } _hx_goto_9:; } HX_DEFINE_DYNAMIC_FUNC1(_Event_ofEvents_T_Void_obj,dispatch,(void)) ::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > _Event_ofEvents_T_Void_obj::__new() { ::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > __this = new _Event_ofEvents_T_Void_obj(); __this->__construct(); return __this; } ::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > _Event_ofEvents_T_Void_obj::__alloc(::hx::Ctx *_hx_ctx) { _Event_ofEvents_T_Void_obj *__this = (_Event_ofEvents_T_Void_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(_Event_ofEvents_T_Void_obj), true, "lime.app._Event_ofEvents_T_Void")); *(void **)__this = _Event_ofEvents_T_Void_obj::_hx_vtable; __this->__construct(); return __this; } _Event_ofEvents_T_Void_obj::_Event_ofEvents_T_Void_obj() { } void _Event_ofEvents_T_Void_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(_Event_ofEvents_T_Void); HX_MARK_MEMBER_NAME(canceled,"canceled"); HX_MARK_MEMBER_NAME(_hx___repeat,"__repeat"); HX_MARK_MEMBER_NAME(_hx___priorities,"__priorities"); HX_MARK_MEMBER_NAME(_hx___listeners,"__listeners"); HX_MARK_END_CLASS(); } void _Event_ofEvents_T_Void_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(canceled,"canceled"); HX_VISIT_MEMBER_NAME(_hx___repeat,"__repeat"); HX_VISIT_MEMBER_NAME(_hx___priorities,"__priorities"); HX_VISIT_MEMBER_NAME(_hx___listeners,"__listeners"); } ::hx::Val _Event_ofEvents_T_Void_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"add") ) { return ::hx::Val( add_dyn() ); } if (HX_FIELD_EQ(inName,"has") ) { return ::hx::Val( has_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"cancel") ) { return ::hx::Val( cancel_dyn() ); } if (HX_FIELD_EQ(inName,"remove") ) { return ::hx::Val( remove_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"canceled") ) { return ::hx::Val( canceled ); } if (HX_FIELD_EQ(inName,"__repeat") ) { return ::hx::Val( _hx___repeat ); } if (HX_FIELD_EQ(inName,"dispatch") ) { return ::hx::Val( dispatch_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"removeAll") ) { return ::hx::Val( removeAll_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"__listeners") ) { return ::hx::Val( _hx___listeners ); } break; case 12: if (HX_FIELD_EQ(inName,"__priorities") ) { return ::hx::Val( _hx___priorities ); } } return super::__Field(inName,inCallProp); } ::hx::Val _Event_ofEvents_T_Void_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"canceled") ) { canceled=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"__repeat") ) { _hx___repeat=inValue.Cast< ::Array< bool > >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"__listeners") ) { _hx___listeners=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"__priorities") ) { _hx___priorities=inValue.Cast< ::Array< int > >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void _Event_ofEvents_T_Void_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("canceled",59,18,26,1f)); outFields->push(HX_("__repeat",7b,02,ac,ae)); outFields->push(HX_("__priorities",e2,cb,e6,1c)); outFields->push(HX_("__listeners",5f,ae,ba,21)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo _Event_ofEvents_T_Void_obj_sMemberStorageInfo[] = { {::hx::fsBool,(int)offsetof(_Event_ofEvents_T_Void_obj,canceled),HX_("canceled",59,18,26,1f)}, {::hx::fsObject /* ::Array< bool > */ ,(int)offsetof(_Event_ofEvents_T_Void_obj,_hx___repeat),HX_("__repeat",7b,02,ac,ae)}, {::hx::fsObject /* ::Array< int > */ ,(int)offsetof(_Event_ofEvents_T_Void_obj,_hx___priorities),HX_("__priorities",e2,cb,e6,1c)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(_Event_ofEvents_T_Void_obj,_hx___listeners),HX_("__listeners",5f,ae,ba,21)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *_Event_ofEvents_T_Void_obj_sStaticStorageInfo = 0; #endif static ::String _Event_ofEvents_T_Void_obj_sMemberFields[] = { HX_("canceled",59,18,26,1f), HX_("__repeat",7b,02,ac,ae), HX_("__priorities",e2,cb,e6,1c), HX_("add",21,f2,49,00), HX_("cancel",7a,ed,33,b8), HX_("has",5a,3f,4f,00), HX_("remove",44,9c,88,04), HX_("removeAll",3d,17,e5,ca), HX_("__listeners",5f,ae,ba,21), HX_("dispatch",ba,ce,63,1e), ::String(null()) }; ::hx::Class _Event_ofEvents_T_Void_obj::__mClass; void _Event_ofEvents_T_Void_obj::__register() { _Event_ofEvents_T_Void_obj _hx_dummy; _Event_ofEvents_T_Void_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.app._Event_ofEvents_T_Void",30,ef,76,e4); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(_Event_ofEvents_T_Void_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< _Event_ofEvents_T_Void_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = _Event_ofEvents_T_Void_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = _Event_ofEvents_T_Void_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace app
[ "72734817+khiodev@users.noreply.github.com" ]
72734817+khiodev@users.noreply.github.com
8995a2d5135372dd9369dcaeb27c0ce2c2acdd7c
fd5a1912b6b88c0c1b9eaaa0850751e29f205d8e
/irledmatrix/irledmatrix.ino
a05cee01104804d29109c290e1e972914dacd010
[ "Apache-2.0" ]
permissive
ajiniesta/my-arduino-projects
ed71c56c32f37b538e49ec8d0b983e8a05a49ab8
fd6d0bd6ea9158302beed0b7e224c506b3cb7846
refs/heads/master
2021-01-19T14:46:42.811258
2017-04-13T17:39:44
2017-04-13T17:39:44
88,189,789
0
0
null
null
null
null
UTF-8
C++
false
false
1,717
ino
/* * led matrix ir controlled * ir in pin 8 * led in 12-10 */ #include "IRremote.h" #include "LedControl.h" int receiver = 8; // Signal Pin of IR receiver to Arduino Digital Pin 8 /*-----( Declare objects )-----*/ IRrecv irrecv(receiver); // create instance of 'irrecv' decode_results results; // create instance of 'decode_results' LedControl lc=LedControl(12,10,11,1); unsigned long delaytime1=500; unsigned long delaytime2=50; boolean add = true; int addIR(int previous){ int next = previous; switch(results.value) { case 0xFF629D: next++; add = true; Serial.println("more leds"); break; case 0xFFA857: next--; add = false; Serial.println("less leds"); break; case 0xFFFFFFFF: Serial.println(" REPEAT"); if(add) next++; else next--; break; default: Serial.println(" other button "); }// End Case delay(500); // Do not get immediate repeat if(next>64){ next = 64; } if(next<0){ next = 0; } return next; } void draw(int val){ int index = 0; lc.clearDisplay(0); for(int row=0;row<8;row++) { for(int col=0;col<8;col++) { if(++index<val){ lc.setLed(0,row,col,true); } } } } void setup() { Serial.begin(9600); Serial.println("IR Receiver Button Decode"); irrecv.enableIRIn(); // Start the receiver lc.shutdown(0,false); /* Set the brightness to a medium values */ lc.setIntensity(0,8); /* and clear the display */ lc.clearDisplay(0); } int current = 32; void loop() { draw(current); if (irrecv.decode(&results)){ current = addIR(current); irrecv.resume(); draw(current); } delay(50); }
[ "antonioj.iniesta@gmail.com" ]
antonioj.iniesta@gmail.com
75118753db1175b914f913f6080c062c7df77abe
2ad4eb27da52d55e9c924431d088f5688931699b
/include/hash.hpp
b6a3b9b3ecc9cb2c22d7408bc455fc161375eee1
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
fhnmor21/montreal
e0fb84334a7f957de207742f763f9d1432406a1b
ae74138774a1533a08971143d7b912b8a2d7064b
refs/heads/master
2023-03-09T07:13:54.077394
2021-02-24T03:57:10
2021-02-24T03:57:10
55,389,428
0
0
null
null
null
null
UTF-8
C++
false
false
1,844
hpp
/** The MIT License (MIT) Copyright (c) 2016 Flavio Moreira Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef HASH_HPP #define HASH_HPP #include "basic_types.hpp" #include "hashes/City.h" #include "hashes/MurmurHash2.h" #include "hashes/Spooky.h" namespace Montreal { struct Hashes { union { struct { u64 murmur; u64 city; u64 spooky; }; u64 h[3]; }; }; template < typename KeyType > Hashes hash(const KeyType& key, u64 seed = 0x9747b28c) { const usize len(sizeof(KeyType)); Hashes rVal = {{{0, 0, 0}}}; union { KeyType key_; u8 buf_[len]; } buffer; buffer.key_ = key; rVal.city = CityHash64WithSeed(buffer.buf_, len, seed); rVal.murmur = MurmurHash64A(buffer.buf_, len, seed); rVal.spooky = SpookyHash::Hash64(buffer.buf_, len, seed); } } // end namespace Montreal #endif // HASH_HPP
[ "fhnmor21@gmail.com" ]
fhnmor21@gmail.com
845e6a255171a48c97a20b24df9fdb7128feff0c
f128c9c7bdb4b33f027f8db36321e9065ab9f9bb
/ryeoryeon/etc/sorting/10M sorting_ans/10M sorting_ans/main.cpp
61b4f8babcaee48d44d7e38c2d2d51c2ca089c3a
[]
no_license
Ryeoryeon/Algorithm_study
21beb05981342df9122573cdb7e60b111ecc92bb
e706e855856373f359891407f1c41e8a2a59b9ce
refs/heads/master
2023-07-26T08:33:11.503340
2021-09-09T16:26:16
2021-09-09T16:26:16
237,822,675
0
0
null
null
null
null
UTF-8
C++
false
false
7,342
cpp
// // main.cpp // 10M sorting_ans // // Created by 이영현 on 2020/04/13. // Copyright © 2020 이영현. All rights reserved. // #include <iostream> #include <vector> #include <cmath> using namespace std; vector<int> list; vector<int> sorting_list; void merge_sort(int first, int last); //사실 해 놓고 보니 합병 정렬이 아니..네..? int main(int argc, const char * argv[]) { ios_base::sync_with_stdio(false); cin.tie(0); int num; cin>>num; //크기가 num 사이즈인 배열에 저장되는 비정렬 숫자들 list.assign(num, 0); for(int i=0; i<num; i++) { cin>>list[i]; } int size = list.size(); int last_index = size - 1; //시작! //index가 처음에는 1로 시작. 두배씩 증가. ---> 안됨. 무조건 두배씩 증가가 아님. 총 길이 / 2로. //단, 남은 길이가 인덱스의 두배보다 작을 때 (홀수일 때)는 나머지 한꺼번에 합침 //그런데 이제 index가 전체 길이의 반이 됐을 때 그만두자! int index = 2; // 해당 단계가 목표로 하는 단위 배열 안의 원소의 개수. (1단계는 2개 -> 2단계는 4개 ..) int step = 0; // 단계. 딱 반반씩 떨어지지 않고 마지막에 애매하게 서로 찢어졌을 때를 위해 넣음. sorting_list = list; int pair_index = num; while(pair_index!=1) { int pair_num = (pair_index+1)/2; //ex. 원소의 개수가 9개면 첫 쌍은 5개, 10개여도 5개. int left_to_right; //마지막 단계에서는 꼭 left_to_right 재정의가 필요. if(pair_num<=2) left_to_right = pow(2,step); // left와 right 사이의 배열 간격 else left_to_right = index/2; // left와 right 사이의 배열 간격 for(int pair=0; pair<pair_num; pair++) { int index_left = pair * index; int index_right = index_left + left_to_right; //잉여가 남을 때 if(index_right >= size) break; for(int ind=pair*index; (ind - (pair*index))<index; ind++) { //ind - (pair*index)는 현재까지 안에 들어간 배열의 개수 if(index_left == (pair*index + left_to_right)) { //좌측에 있는 아이들이 이미 다 정렬되었을 때 //우측에 있는 아이들을 모두 sorting_list에 밀어넣어야함. for(int j=index_right; j!=(pair*index + index); j++) { sorting_list[ind] = list[j]; ++ind; } break; } else { //우측에 있는 아이들이 이미 다 정렬되었을 때 (단, pair*index + index가 사이즈를 뛰어넘을 때를 위해) if(pair == pair_num - 1 && index_right == size) { //우측에 있는 아이들이 이미 다 정렬되었을 때 //좌측에 있는 아이들을 모두 sorting_list에 밀어넣어야함. for(int j=index_left; j!=(pair*index + left_to_right); j++) { sorting_list[ind] = list[j]; ++ind; } break; } else if(pair != pair_num - 1 && index_right == (pair*index + index)) { //우측에 있는 아이들이 이미 다 정렬되었을 때 //좌측에 있는 아이들을 모두 sorting_list에 밀어넣어야함. for(int j=index_left; j!=(pair*index + left_to_right); j++) { sorting_list[ind] = list[j]; ++ind; } break; } if(list[index_left] < list[index_right]) { sorting_list[ind] = list[index_left]; ++index_left; } else { sorting_list[ind] = list[index_right]; ++index_right; } } } } if(2*index <= size) index*=2; else index = size; ++step; pair_index = pair_num; list = sorting_list; } //merge_sort(0, last_index); for(int i=0; i<size; i++) { cout<<list[i]<<'\n'; } return 0; } // void merge_sort(int first, int last) { //길이가 1이 되면 first==last가 됨 if(first<last) { int k = (first+last)/2; //가장 안쪽의 재귀부터 풀림. 재귀가 하나 풀리면 이미 list에서 어느정도 정렬이 되는 상태. merge_sort(first, k); merge_sort(k+1, last); //list[first ~ k]와 list[k+1 ~ last]를 비교 후 합병 int index_left = first; int index_right = k+1; int index_m1 = first; sorting_list = list; // sorting_list는 list가 정렬될 때 기준이 될, 맨 처음 상태의 list의 왼/오 벡터가 될 친구. while(1) { if(index_left > k) // 좌측에 있는 아이가 이미 정렬 끝난 경우 { for(int i=index_right; i<last; i++) { sorting_list[index_m1] = list[i]; ++index_m1; } break; } else if(index_right == last + 1) // 우측에 있는 아이가 이미 정렬 끝난 경우 { for(int i=index_left; i<=k; i++) { sorting_list[index_m1] = list[i]; ++index_m1; } break; } else { if(list[index_left] <= list[index_right]) { sorting_list[index_m1] = list[index_left]; ++index_left; ++index_m1; } else { sorting_list[index_m1] = list[index_right]; ++index_right; ++index_m1; } } } list = sorting_list; } }
[ "ryeoryeon@gmail.com" ]
ryeoryeon@gmail.com
324dd249195cf0ec1aae1613bf3216c1d1149625
d20876df1308f1eaf3c280f6d3dd78c47633a2d8
/src/Corrade/TestSuite/Compare/String.cpp
5288e9918a64a2bda42004fe33f5f48c88783d7e
[ "MIT", "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
mosra/corrade
729ff71a9c8ceb7d27507b635be6433114b963bf
183b375b73fa3e819a6b41dbcc0cf2f06773d2b4
refs/heads/master
2023-08-24T21:56:12.599589
2023-08-23T14:07:19
2023-08-24T09:43:55
2,863,909
470
143
NOASSERTION
2023-09-12T02:52:28
2011-11-28T00:51:12
C++
UTF-8
C++
false
false
14,901
cpp
/* This file is part of Corrade. Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz> 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 "String.h" #include "Implementation/Diff.h" namespace Corrade { namespace TestSuite { ComparisonStatusFlags Comparator<Compare::String>::operator()(const Containers::StringView actual, const Containers::StringView expected) { _actualValue = actual; _expectedValue = expected; return actual != expected ? ComparisonStatusFlag::Failed : ComparisonStatusFlags{}; } void Comparator<Compare::String>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const { #ifdef CORRADE_NO_ASSERT static_cast<void>(flags); #endif CORRADE_INTERNAL_ASSERT(flags == ComparisonStatusFlag::Failed); out << "Strings" << actual << "and" << expected << "are different." << Utility::Debug::color(Utility::Debug::Color::Green) << "Actual (+)" << Utility::Debug::resetColor << "vs" << Utility::Debug::color(Utility::Debug::Color::Red) << "expected (-)" << Utility::Debug::resetColor << Utility::Debug::nospace << ":"; /* Split into lines, pass that to the diff algorithm */ const Containers::Array<Containers::StringView> actualLines = _actualValue.split('\n'); const Containers::Array<Containers::StringView> expectedLines = _expectedValue.split('\n'); /* Calculate a set of longest matching slices */ Containers::Array<Containers::Triple<std::size_t, std::size_t, std::size_t>> slices; Compare::Implementation::matchingSlicesInto(slices, stridedArrayView(actualLines), 0, stridedArrayView(expectedLines), 0); /* Include an empty zero-length slice at the end in order to have the rest after the last matching slice printed as well */ arrayAppend(slices, InPlaceInit, actualLines.size(), expectedLines.size(), std::size_t{}); /* Print everything */ std::size_t actualI = 0; std::size_t expectedI = 0; for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& slice: slices) { /* If there's exactly one differing line in both, print differences inside that line */ if(slice.first() - actualI == 1 && slice.second() - expectedI == 1) { const Containers::StringView actualLine = actualLines[actualI]; const Containers::StringView expectedLine = expectedLines[expectedI]; Containers::Array<Containers::Triple<std::size_t, std::size_t, std::size_t>> lineSlices; Compare::Implementation::matchingSlicesInto(lineSlices, stridedArrayView(actualLine), 0, stridedArrayView(expectedLine), 0); /* Count total matching bytes */ std::size_t totalMatchingBytes = 0; for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& i: lineSlices) { /* If the slice cut is in the middle of a UTF-8 character, abort the mission -- report there's nothing matching so it doesn't attempt to put ANSI highlight in the middle of a character as that'd break the output. */ /** @todo handle better (move the cut out of the character) */ if(actualLine[i.first()] & '\x80' || expectedLine[i.second()] & '\x80' || (i.third() && actualLine[i.first() + i.third() - 1] & '\x80') || (i.third() && expectedLine[i.second() + i.third() - 1] & '\x80')) { totalMatchingBytes = 0; break; } totalMatchingBytes += i.third(); } /* Highlight the difference only if there's at least 50% of the shorter line same, otherwise it'd be just noise */ if(totalMatchingBytes >= Utility::min(actualLine.size(), expectedLine.size())/2) { /* Include an empty zero-length slice at the end in order to have the rest after the last matching slice printed as well */ arrayAppend(lineSlices, InPlaceInit, actualLine.size(), expectedLine.size(), std::size_t{}); /* First goes the expected (deleted) line */ out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Red) << " -"; std::size_t expectedLineI = 0; for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& lineSlice: lineSlices) { out << Utility::Debug::nospace /* Mark the deleted part with inverse red color */ #if !defined(CORRADE_TARGET_WINDOWS) || defined(CORRADE_UTILITY_USE_ANSI_COLORS) << Utility::Debug::invertedColor(Utility::Debug::Color::Red) #endif << expectedLine.slice(expectedLineI, lineSlice.second()) << Utility::Debug::nospace /* And the matching part with normal red */ << Utility::Debug::color(Utility::Debug::Color::Red) << expectedLine.sliceSize(lineSlice.second(), lineSlice.third()) << Utility::Debug::resetColor; expectedLineI = lineSlice.second() + lineSlice.third(); } /* Then the actual (added) line */ out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Green) << " +"; std::size_t actualLineI = 0; for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& lineSlice: lineSlices) { out << Utility::Debug::nospace /* Mark the deleted part with inverse green color */ #if !defined(CORRADE_TARGET_WINDOWS) || defined(CORRADE_UTILITY_USE_ANSI_COLORS) << Utility::Debug::invertedColor(Utility::Debug::Color::Green) #endif << actualLine.slice(actualLineI, lineSlice.first()) << Utility::Debug::nospace /* And the matching part with normal green */ << Utility::Debug::color(Utility::Debug::Color::Green) << actualLine.sliceSize(lineSlice.first(), lineSlice.third()) << Utility::Debug::resetColor; actualLineI = lineSlice.first() + lineSlice.third(); } /* Advancethe line iterators so the lines aren't printed again below */ ++actualI; ++expectedI; } } /* All lines from `expected` after the previous matching slice and before the current matching slice are marked as deleted */ for(const Containers::StringView& i: expectedLines.slice(expectedI, slice.second())) out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Red) << " -" << Utility::Debug::nospace << i << Utility::Debug::resetColor; /* All lines from `actual` after the previous matching slice and before the current matching slice are marked as added */ for(const Containers::StringView& i: actualLines.slice(actualI, slice.first())) out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Green) << " +" << Utility::Debug::nospace << i << Utility::Debug::resetColor; /* The matching slice is not marked in any way */ for(const Containers::StringView& i: actualLines.sliceSize(slice.first(), slice.third())) out << Utility::Debug::newline << " " << Utility::Debug::nospace << i; actualI = slice.first() + slice.third(); expectedI = slice.second() + slice.third(); } } ComparisonStatusFlags Comparator<Compare::StringHasPrefix>::operator()(const Containers::StringView actual, const Containers::StringView expectedPrefix) { _actualValue = actual; _expectedPrefixValue = expectedPrefix; /* If the strings are different, we can print them both in a verbose message */ if(!actual.hasPrefix(expectedPrefix)) return ComparisonStatusFlag::Failed; if(actual != expectedPrefix) return ComparisonStatusFlag::Verbose; return {}; } void Comparator<Compare::StringHasPrefix>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const { if(flags == ComparisonStatusFlag::Failed) out << "String" << actual << "isn't prefixed with" << expected << Utility::Debug::nospace << ", actual is\n " << _actualValue << Utility::Debug::newline << " but expected prefix\n " << _expectedPrefixValue; else if(flags == ComparisonStatusFlag::Verbose) out << "String" << actual << "is prefixed with" << expected << Utility::Debug::nospace << ", the actual string\n " << _actualValue << Utility::Debug::newline << " has expected prefix\n " << _expectedPrefixValue; else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } ComparisonStatusFlags Comparator<Compare::StringHasSuffix>::operator()(const Containers::StringView actual, const Containers::StringView expectedSuffix) { _actualValue = actual; _expectedSuffixValue = expectedSuffix; /* If the strings are different, we can print them both in a verbose message */ if(!actual.hasSuffix(expectedSuffix)) return ComparisonStatusFlag::Failed; if(actual != expectedSuffix) return ComparisonStatusFlag::Verbose; return {}; } void Comparator<Compare::StringHasSuffix>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const { if(flags == ComparisonStatusFlag::Failed) out << "String" << actual << "isn't suffixed with" << expected << Utility::Debug::nospace << ", actual is\n " << _actualValue << Utility::Debug::newline << " but expected suffix\n " << _expectedSuffixValue; else if(flags == ComparisonStatusFlag::Verbose) out << "String" << actual << "is suffixed with" << expected << Utility::Debug::nospace << ", the actual string\n " << _actualValue << Utility::Debug::newline << " has expected suffix\n " << _expectedSuffixValue; else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } ComparisonStatusFlags Comparator<Compare::StringContains>::operator()(const Containers::StringView actual, const Containers::StringView expectedToContain) { _actualValue = actual; _expectedToContainValue = expectedToContain; /* If the strings are different, we can print them both in a verbose message */ if(!actual.contains(expectedToContain)) return ComparisonStatusFlag::Failed; if(actual != expectedToContain) return ComparisonStatusFlag::Verbose; return {}; } void Comparator<Compare::StringContains>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const { if(flags == ComparisonStatusFlag::Failed) out << "String" << actual << "doesn't contain" << expected << Utility::Debug::nospace << ", actual is\n " << _actualValue << Utility::Debug::newline << " but expected to contain\n " << _expectedToContainValue; else if(flags == ComparisonStatusFlag::Verbose) out << "String" << actual << "contains" << expected << "at position" << (_actualValue.find(_expectedToContainValue).begin() - _actualValue.begin()) << Utility::Debug::nospace << ", the actual string\n " << _actualValue << Utility::Debug::newline << " expectedly contains\n " << _expectedToContainValue; else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } ComparisonStatusFlags Comparator<Compare::StringNotContains>::operator()(const Containers::StringView actual, const Containers::StringView expectedToNotContain) { _actualValue = actual; _expectedToNotContainValue = expectedToNotContain; /* Unlike the other comparators, here it can't pass if the strings are the same, meaning we report the verbose message always */ if(actual.contains(expectedToNotContain)) return ComparisonStatusFlag::Failed; return ComparisonStatusFlag::Verbose; } void Comparator<Compare::StringNotContains>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const { if(flags == ComparisonStatusFlag::Failed) out << "String" << actual << "contains" << expected << "at position" << (_actualValue.find(_expectedToNotContainValue).begin() - _actualValue.begin()) << Utility::Debug::nospace << ", actual is\n " << _actualValue << Utility::Debug::newline << " but expected to not contain\n " << _expectedToNotContainValue; else if(flags == ComparisonStatusFlag::Verbose) out << "String" << actual << "doesn't contain" << expected << Utility::Debug::nospace << ", the actual string\n " << _actualValue << Utility::Debug::newline << " expectedly doesn't contain\n " << _expectedToNotContainValue; else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } }}
[ "mosra@centrum.cz" ]
mosra@centrum.cz
d54be161d2ce6d0b258a83022930b705f6ad5fb4
6b539667d77cfc7d481fa99bfe89bc8a47faddd7
/projet_finale0/dialog.h
53a9beda23a394b6a95267ab078faee12c0318e5
[]
no_license
ImenBenMansour/Smart_Club_2A21
dd41872a68c1e6c39281fce1245dc8ba5f9b6038
d10a725c752da05bf5812f36a64e5f5edd695c7a
refs/heads/master
2023-04-21T14:23:37.933795
2021-05-05T02:58:08
2021-05-05T02:58:08
344,109,302
0
2
null
null
null
null
UTF-8
C++
false
false
451
h
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = nullptr); explicit Dialog(QString,QString,QString,QWidget *parent = nullptr); ~Dialog(); void set_tmpemail(QString e){tmpemail=e;} private slots: void on_envoyer_dialog_clicked(); private: Ui::Dialog *ui; QString tmpemail; }; #endif // DIALOG_H
[ "cynda.zagrouba@esprit.tn" ]
cynda.zagrouba@esprit.tn
45a535f1a9b170a575251f628f983ebc41b95966
9b164f28d53010772b82bb680f6e0e10f1154916
/AutMesh/AutLib/Cad/PlaneCurve/GModel/Mesh2d_gPlnCurve.hxx
7f530b746470f1031d794043e2f9ccb88792b9b3
[]
no_license
amir5200fx/AutMarine-v4.4.1
d006cc273d5be520f930a15c0878b6121f26942d
7a9384cad8978dbe44d9a2354559384b8efb93db
refs/heads/master
2020-11-27T05:10:06.605362
2019-12-20T18:31:31
2019-12-20T18:31:31
229,316,964
0
0
null
null
null
null
UTF-8
C++
false
false
258
hxx
#pragma once #ifndef _Mesh2d_gPlnCurve_Header #define _Mesh2d_gPlnCurve_Header #include <Mesh_PlnCurve.hxx> #include <GModel_parCurve.hxx> namespace AutLib { typedef Mesh_PlnCurve<GModel_parCurve> Mesh2d_gPlnCurve; } #endif // !_Mesh2d_gPlnCurve_Header
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
88e4a18c0cefd55ea1355380550d824e8c214c36
be4459658d667c47eefeeb3cf689a678042edb94
/modules/core/rwvx/rwmsg/test/rwmsg_broker_gtest.cc
d2ab979a3c41e422369b42f03cb093bf6f4e949f
[ "Apache-2.0" ]
permissive
kparr/RIFT.ware-1
7945174aa23ac1f7d74a7464b645db5824982fc3
6846108d70b80b95c5117fdccd44ff058ac605be
refs/heads/master
2021-01-13T08:36:03.751610
2016-07-24T21:36:15
2016-07-24T21:36:15
72,420,438
0
0
null
2016-10-31T09:11:27
2016-10-31T09:11:27
null
UTF-8
C++
false
false
243,717
cc
/* * * (c) Copyright RIFT.io, 2013-2016, All Rights Reserved * */ /** * @file rwmsg_gtest_broker.cc * @author Grant Taylor <grant.taylor@riftio.com> * @date 11/18/2013 * @brief Google test cases for testing rwmsg_broker * * @details Google test cases for testing rwmsg_broker. */ /** * Step 1: Include the necessary header files */ #include <sys/types.h> #include <sys/socket.h> #include <nanomsg/nn.h> #include <nanomsg/pair.h> #include <limits.h> #include <cstdlib> #include <netinet/in.h> #include <sys/time.h> #include <sys/resource.h> #include <valgrind/valgrind.h> #include "rwut.h" #include "rwlib.h" #include "rw_dl.h" #include "rw_sklist.h" #include "rw_sys.h" #include "rwtasklet.h" #include <unistd.h> #include <sys/syscall.h> #include <rwmsg_int.h> #include <rwmsg_broker.h> #include "rwmsg_gtest_c.h" #include "test.pb-c.h" #include <ck.h> #undef RWMSG_NOTHREAD using ::testing::MatchesRegex; using ::testing::ContainsRegex; #define VERBOSE() (getenv("V") && getenv("V")[0]=='1') static struct timeval PRN_start; #define VERBPRN(args...) do { \ if (VERBOSE()) { \ if (!PRN_start.tv_sec) { \ gettimeofday(&PRN_start, NULL); \ } \ struct timeval tv; \ gettimeofday(&tv, NULL); \ struct timeval delta; \ timersub(&tv, &PRN_start, &delta); \ fprintf(stderr, "%ld.%03ld ", delta.tv_sec, delta.tv_usec/1000); \ fprintf(stderr, args); \ } \ } while(0) #define MAX_RTT 999999999999 /* * Step 2: Use the TEST macro to define your tests. The following * is the notes from Google sample test * * TEST has two parameters: the test case name and the test name. * After using the macro, you should define your test logic between a * pair of braces. You can use a bunch of macros to indicate the * success or failure of a test. EXPECT_TRUE and EXPECT_EQ are * examples of such macros. For a complete list, see gtest.h. * * In Google Test, tests are grouped into test cases. This is how we * keep test code organized. You should put logically related tests * into the same test case. * * The test case name and the test name should both be valid C++ * identifiers. And you should not use underscore (_) in the names. * * Google Test guarantees that each test you define is run exactly * once, but it makes no guarantee on the order the tests are * executed. Therefore, you should write your tests in such a way * that their results don't depend on their order. */ /* Test and tasklet environment */ static void nnchk() { /* Gratuitous socket open/close; the close will delete any riftcfg in the nn library unless there was a leaked nn socket from a preceeding test. */ int sk = nn_socket (AF_SP, NN_PAIR); nn_close(sk); /* This gets cleared when the last nn sock is closed, has to happen... */ struct nn_riftconfig rcfg; nn_global_get_riftconfig(&rcfg); ASSERT_FALSE(rcfg.singlethread); ASSERT_TRUE(rcfg.waitfunc == NULL); } static uint16_t broport_g=0; #define GTEST_BASE_BROKER_PORT 31234 uint16_t rwmsg_broport_g(int tasklet_ct_in) { rw_status_t status; static uint16_t previous_tasklet_ct_in = 0; /* Plug in a new broker port for each test to avoid confusion. Each test uses the next port */ if (!broport_g) { const char *envport = getenv("RWMSG_BROKER_PORT"); if (envport) { long int long_port; long_port = strtol(envport, NULL, 10); if (long_port < 65535 && long_port > 0) broport_g = (uint16_t)long_port; else RW_ASSERT(long_port < 65535 && long_port > 0); } else { uint8_t uid; status = rw_unique_port(GTEST_BASE_BROKER_PORT, &broport_g); RW_ASSERT(status == RW_STATUS_SUCCESS); status = rw_instance_uid(&uid); RW_ASSERT(status == RW_STATUS_SUCCESS); // The unit test needs a range of unique ports. // coverage-tests taking almost 500 ports broport_g += 500 * uid; } } else { broport_g += previous_tasklet_ct_in; } // Avoid the list of known port#s while (rw_port_in_avoid_list(broport_g, tasklet_ct_in)) broport_g += tasklet_ct_in; previous_tasklet_ct_in = tasklet_ct_in; return broport_g; } class rwmsg_btenv_t { public: #define TASKLET_MAX (10) rwmsg_btenv_t(int tasklet_ct_in=0) { broport = rwmsg_broport_g(tasklet_ct_in); char tmp[16]; sprintf(tmp, "%d", broport); fprintf(stderr, "+++++++++++++++++++++++++++ %d\n", broport); setenv ("RWMSG_BROKER_PORT", tmp, TRUE); setenv("RWMSG_BROKER_ENABLE", "1", TRUE); setenv("RWMSG_CHANNEL_AGEOUT", "1", TRUE); memset(&rwmsg_broker_g, 0, sizeof(rwmsg_broker_g)); assert(tasklet_ct_in <= TASKLET_MAX); rwsched = rwsched_instance_new(); tasklet_ct = tasklet_ct_in; memset(&tasklet, 0, sizeof(tasklet)); for (int i=0; i<tasklet_ct; i++) { tasklet[i] = rwsched_tasklet_new(rwsched); } ti = &ti_s; ti->rwvx = rwvx_instance_alloc(); ti->rwsched_instance = rwsched; ti->rwvcs = ti->rwvx->rwvcs; rwcal = ti->rwvx->rwcal_module; RW_ASSERT(rwcal); rw_status_t status = rwcal_rwzk_zake_init(rwcal); RW_ASSERT(RW_STATUS_SUCCESS == status); } ~rwmsg_btenv_t() { setenv("RWMSG_BROKER_PORT", "0" , TRUE); setenv("RWMSG_BROKER_ENABLE", "0" , TRUE); setenv("RWMSG_CHANNEL_AGEOUT", "0" , TRUE); if (rwsched) { for (int i=0; i<tasklet_ct; i++) { rwsched_tasklet_free(tasklet[i]); tasklet[i] = NULL; } rwsched_instance_free(rwsched); rwsched = NULL; } if (rwcal) { char rwzk_LOCK[999]; char rwzk_path[999]; char ** children = NULL; rw_status_t rs; sprintf(rwzk_path, "/sys/rwmsg/broker-lock"); rs = rwcal_rwzk_get_children(rwcal, rwzk_path, &children, NULL); RW_ASSERT(rs == RW_STATUS_SUCCESS || rs == RW_STATUS_NOTFOUND); if (children) { int i=0; while (children[i] != NULL) { sprintf(rwzk_LOCK, "/sys/rwmsg/broker-lock/%s", children[i]); rs = rwcal_rwzk_delete(rwcal, rwzk_LOCK, NULL); free(children[i]); i++; } free(children); } children = NULL; rs = rwcal_rwzk_get_children(rwcal, rwzk_path, &children, NULL); if (rs == RW_STATUS_SUCCESS) { RW_ASSERT(!children || !children[0]); } else { RW_ASSERT(rs == RW_STATUS_NOTFOUND); } rwcal = NULL; } } int broport; rwsched_instance_ptr_t rwsched; rwtasklet_info_t ti_s; rwtasklet_info_t *ti; int tasklet_ct; rwsched_tasklet_ptr_t tasklet[TASKLET_MAX]; rwcal_module_ptr_t rwcal; }; TEST(RWMsgBroker, PlaceholderNOP) { TEST_DESCRIPTION("Tests nothing whatsoever"); if (0) { VERBPRN(" "); } } TEST(RWMsgTestEnv, ThouShaltCoreDump) { TEST_DESCRIPTION("Tests rlimit coredump setting"); struct rlimit rlim = { 0 }; getrlimit(RLIMIT_CORE, &rlim); VERBPRN("Core rlimit .rlim_cur=%lu .rlim_max=%lu\n", rlim.rlim_cur, rlim.rlim_max); ASSERT_GT(rlim.rlim_cur, 0); } TEST(RWMsgBroker, CreateBindListen) { TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening"); rwmsg_btenv_t tenv(1); rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); /* Should now accept and ultimately timeout in the broker's acceptor */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 0); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwmsg_bool_t rb = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(rb); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, CreateBindListen2Bros) { TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening"); rwmsg_btenv_t tenv(2); rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); usleep(1000); rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2); usleep(1000); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*2*(2-1); //==10 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<100) rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwmsg_bool_t rb; rb = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(rb); rb = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(rb); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, CreateBindListen3Bros) { TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening"); rwmsg_btenv_t tenv(3); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*3*(3-1); //==30 rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2); rwmsg_broker_t *bro3=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 2, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro3); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<100) rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwmsg_bool_t rb; rb = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(rb); rb = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(rb); rb = rwmsg_broker_halt_sync(bro3); ASSERT_TRUE(rb); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, CreateBindListen4Bros) { TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening"); rwmsg_btenv_t tenv(4); rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2); rwmsg_broker_t *bro3=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 2, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro3); rwmsg_broker_t *bro4=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[3]; rwmsg_broker_main(broport_g, 3, 3, tenv.rwsched, tenv.tasklet[3], tenv.rwcal, TRUE, tenv.ti, &bro4); usleep(10*1000); /* Should now accept and ultimately timeout in the broker's acceptor */ //int loopwait = 15; //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*4*(4-1); //==5*2*n*(n-1)/2 60 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(50*1000); // 50ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); usleep(50*1000); rwmsg_bool_t rb; rb = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(rb); rb = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(rb); rb = rwmsg_broker_halt_sync(bro3); ASSERT_TRUE(rb); rb = rwmsg_broker_halt_sync(bro4); ASSERT_TRUE(rb); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptTimeout) { TEST_DESCRIPTION("Tests timeout of accepted connection in broker"); rwmsg_btenv_t tenv(1); rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); int sk = socket(AF_INET, SOCK_STREAM, 0); int fl = fcntl(sk, F_GETFL); ASSERT_TRUE(fl != -1); fl |= O_NONBLOCK; int r = fcntl(sk, F_SETFL, fl); ASSERT_TRUE(r == 0); struct sockaddr_in ad; ad.sin_family = AF_INET; ad.sin_port = htons(tenv.broport); ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR); r = connect(sk, (struct sockaddr*)&ad, sizeof(ad)); ASSERT_TRUE(r == 0 || (r == -1 && errno == EINPROGRESS)); /* Should now accept and ultimately timeout in the broker's acceptor */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 0); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 1); r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptTimeout2Bros) { TEST_DESCRIPTION("Tests timeout of accepted connection in broker"); rwmsg_btenv_t tenv(2); rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2); { int sk = socket(AF_INET, SOCK_STREAM, 0); int fl = fcntl(sk, F_GETFL); ASSERT_TRUE(fl != -1); fl |= O_NONBLOCK; int r = fcntl(sk, F_SETFL, fl); ASSERT_TRUE(r == 0); struct sockaddr_in ad; ad.sin_family = AF_INET; ad.sin_port = htons(tenv.broport); ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR); r = connect(sk, (struct sockaddr*)&ad, sizeof(ad)); ASSERT_TRUE(r == 0 || (r == -1 && errno == EINPROGRESS)); /* Should now accept and ultimately timeout in the broker's acceptor */ int loopwait = 10; rwmsg_broker_g.exitnow.neg_freed_err = 0; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 10); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 1); } int r; r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptHandshakeFail) { TEST_DESCRIPTION("Tests rejection of failed handshake in broker"); rwmsg_btenv_t tenv(1); rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); int sk = socket(AF_INET, SOCK_STREAM, 0); int fl = fcntl(sk, F_GETFL); ASSERT_TRUE(fl != -1); //fl |= O_NONBLOCK; int r = fcntl(sk, F_SETFL, fl); ASSERT_TRUE(r == 0); struct sockaddr_in ad; ad.sin_family = AF_INET; ad.sin_port = htons(tenv.broport); ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR); r = connect(sk, (struct sockaddr*)&ad, sizeof(ad)); ASSERT_TRUE(r == 0); uint64_t hsbuf[2] = { 0x0102030405060708ull, 0x0102030405060708ull }; r = write(sk, &hsbuf, 7); // not 16! ASSERT_EQ(r, 7); /* Should now accept, read partial hs, and jettison from the broker's acceptor */ int loopwait = 3; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 0); r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptHandshakeFail2Bros) { TEST_DESCRIPTION("Tests rejection of failed handshake in broker"); rwmsg_btenv_t tenv(2); rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2); { int sk = socket(AF_INET, SOCK_STREAM, 0); int fl = fcntl(sk, F_GETFL); ASSERT_TRUE(fl != -1); //fl |= O_NONBLOCK; int r = fcntl(sk, F_SETFL, fl); ASSERT_TRUE(r == 0); struct sockaddr_in ad; ad.sin_family = AF_INET; ad.sin_port = htons(tenv.broport); ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR); r = connect(sk, (struct sockaddr*)&ad, sizeof(ad)); ASSERT_TRUE(r == 0); uint64_t hsbuf[2] = { 0x0102030405060708ull, 0x0102030405060708ull }; r = write(sk, &hsbuf, 7); // not 16! ASSERT_EQ(r, 7); /* Should now accept, read partial hs, and jettison from the broker's acceptor */ int loopwait = 3; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 10); } { int sk = socket(AF_INET, SOCK_STREAM, 0); int fl = fcntl(sk, F_GETFL); ASSERT_TRUE(fl != -1); //fl |= O_NONBLOCK; int r = fcntl(sk, F_SETFL, fl); ASSERT_TRUE(r == 0); struct sockaddr_in ad; ad.sin_family = AF_INET; ad.sin_port = htons(tenv.broport+1); ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR); r = connect(sk, (struct sockaddr*)&ad, sizeof(ad)); ASSERT_TRUE(r == 0); uint64_t hsbuf[2] = { 0x0102030405060708ull, 0x0102030405060708ull }; r = write(sk, &hsbuf, 7); // not 16! ASSERT_EQ(r, 7); /* Should now accept, read partial hs, and jettison from the broker's acceptor */ int loopwait = 3; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 10); } int r; r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptHandshakeOK) { TEST_DESCRIPTION("Tests accepting a handshake in broker"); rwmsg_btenv_t tenv(1); rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); int sk = socket(AF_INET, SOCK_STREAM, 0); int fl = fcntl(sk, F_GETFL); ASSERT_TRUE(fl != -1); //fl |= O_NONBLOCK; int r = fcntl(sk, F_SETFL, fl); ASSERT_TRUE(r == 0); struct sockaddr_in ad; ad.sin_family = AF_INET; ad.sin_port = htons(tenv.broport); ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR); r = connect(sk, (struct sockaddr*)&ad, sizeof(ad)); ASSERT_TRUE(r == 0); struct rwmsg_handshake_s handshake; memset(&handshake, 0, sizeof(handshake)); handshake.chanid = 1; handshake.pid = getpid(); handshake.chtype = RWMSG_CHAN_SRV; handshake.pri = RWMSG_PRIORITY_HIGH; r = write(sk, &handshake, sizeof(handshake)); ASSERT_EQ(r, sizeof(handshake)); /* Should now accept, read partial hs, and jettison from the broker's acceptor */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptHandshakeOK2Bros) { TEST_DESCRIPTION("Tests accepting a handshake in broker"); rwmsg_btenv_t tenv(2); rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2); { int sk = socket(AF_INET, SOCK_STREAM, 0); int fl = fcntl(sk, F_GETFL); ASSERT_TRUE(fl != -1); //fl |= O_NONBLOCK; int r = fcntl(sk, F_SETFL, fl); ASSERT_TRUE(r == 0); struct sockaddr_in ad; ad.sin_family = AF_INET; ad.sin_port = htons(tenv.broport); ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR); r = connect(sk, (struct sockaddr*)&ad, sizeof(ad)); ASSERT_TRUE(r == 0); struct rwmsg_handshake_s handshake; memset(&handshake, 0, sizeof(handshake)); handshake.chanid = 1; handshake.pid = getpid(); handshake.chtype = RWMSG_CHAN_SRV; handshake.pri = RWMSG_PRIORITY_HIGH; r = write(sk, &handshake, sizeof(handshake)); ASSERT_EQ(r, sizeof(handshake)); /* Should now accept, read partial hs, and jettison from the broker's acceptor */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); usleep(1000*100); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); } int r; r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptClichan) { TEST_DESCRIPTION("Tests accepting from a clichan"); rwmsg_btenv_t tenv(2); /* Broker is tasklet 0 */ rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_bool_t r; rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, ClichanConnectionStatus) { TEST_DESCRIPTION("Tests accepting from a clichan"); rw_status_t rs; rwmsg_endpoint_t *ep; rwmsg_clichan_t *cc; rwmsg_bool_t r; rwsched_tasklet_ptr_t tasklet; rwsched_instance_ptr_t rwsched; /* create a tasklet w/o setting RWMSG_BROKER_PORT that way the endpoint won't * have broker enabled and the clichan would only have local-only channels */ rwsched = rwsched_instance_new(); tasklet = rwsched_tasklet_new(rwsched); ep = rwmsg_endpoint_create(0, 0, 0, rwsched, tasklet, rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); /* Returns SUCCESS if the cc is local-only */ rs = rwmsg_clichan_connection_status(cc); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* End clichan */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); rwsched_tasklet_free(tasklet); rwsched_instance_free(rwsched); /* create the usual style tasklets w/ RWMSG_BROKER_PORT enabled * so that we can test the clichan w/ remote channels which connects to the broker*/ rwmsg_btenv_t tenv(2); /* Broker is tasklet 0 */ rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_connection_status(cc); ASSERT_TRUE(rs == RW_STATUS_NOTCONNECTED); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Returns NOTCONNECTED if the cc's socket's state is not NN_CONNECTED */ rs = rwmsg_clichan_connection_status(cc); ASSERT_TRUE(rs == RW_STATUS_NOTCONNECTED); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); /* Returns SUCCESS if the cc's socket's state is NN_CONNECTED */ rs = rwmsg_clichan_connection_status(cc); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptClichan2Bros) { TEST_DESCRIPTION("Tests accepting from a clichan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; /* Broker-1 is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker-2 is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); { /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } { /* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptClichanAndAgeout_LONG) { TEST_DESCRIPTION("Tests accepting from a clichan"); rwmsg_btenv_t tenv(2); /* Broker is tasklet 0 */ rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); for(int i=0; i<3; i++) { rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); } rwmsg_bool_t r; r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); //rwmsg_broker_dump(bro); //sleep(2); int loopwait = 2; // wait for more than 1sec rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); rwmsg_broker_dump(bro); ASSERT_EQ(rwmsg_broker_g.exitnow.bch_count, 0); /* End broker */ r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndAgeout_LONG) { TEST_DESCRIPTION("Tests aging-out bro-srvchan"); rwmsg_btenv_t tenv(2); /* Broker is tasklet 0 */ rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); for(int i=0; i<3; i++) { rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep); ASSERT_TRUE(sc != NULL); rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create brosrvchan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End srvchan tasklet 1 */ rwmsg_srvchan_halt(sc); } rwmsg_bool_t r; r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); //rwmsg_broker_dump(bro); //sleep(2); int loopwait = 2; // wait for more than 1sec rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); rwmsg_broker_dump(bro); ASSERT_EQ(rwmsg_broker_g.exitnow.bch_count, 0); /* End broker */ r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } void broker_sleep_test_timer(void *ud) { if (0) { fprintf(stderr, "broker_sleep_test_timer start sleep\n"); sleep(2); fprintf(stderr, "broker_sleep_test_timer end sleep\n"); } } TEST(RWMsgBroker, AcceptClichanSleep) { TEST_DESCRIPTION("Tests accepting from a clichan"); rwmsg_btenv_t tenv(2); /* Broker is tasklet 0, not on main queue, although acceptor always is */ rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, FALSE, tenv.ti, &bro); /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); /* Timer on main queue to sleep and thereby sputter broker acceptor event processing */ rwsched_dispatch_source_t tim = rwsched_dispatch_source_create(tenv.tasklet[1], RWSCHED_DISPATCH_SOURCE_TYPE_TIMER, 0, 0, rwsched_dispatch_get_main_queue(tenv.rwsched)); rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1], tim, broker_sleep_test_timer); rwsched_dispatch_set_context(tenv.tasklet[1], tim, NULL); rwsched_dispatch_source_set_timer(tenv.tasklet[1], tim, dispatch_time(DISPATCH_TIME_NOW, 0*NSEC_PER_SEC), 100ull * NSEC_PER_SEC / 1000000ull, 0); rwsched_dispatch_resume(tenv.tasklet[1], tim); /* Make a serial queue for clichan */ rwsched_dispatch_queue_t q = rwsched_dispatch_queue_create(tenv.tasklet[0], "q", DISPATCH_QUEUE_SERIAL); rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, q); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 15; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 1\n"); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwsched_dispatch_source_cancel(tenv.tasklet[1], tim); rwmsg_garbage(&ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, tim, tenv.rwsched, tenv.tasklet[1]); /* End clichan tasklet 1 */ rwmsg_bool_t r; rwmsg_clichan_halt(cc); rwsched_dispatch_release(tenv.tasklet[0], q); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptClichanSleep2Bros) { TEST_DESCRIPTION("Tests accepting from a clichan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; /* Broker-1 is tasklet 0, not on main queue, although acceptor always is */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, FALSE, tenv.ti, &bro1); /* Broker-2 is tasklet 2, not on main queue, although acceptor always is */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, FALSE, tenv.ti, &bro2); { /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); /* Timer on main queue to sleep and thereby sputter broker acceptor event processing */ rwsched_dispatch_source_t tim = rwsched_dispatch_source_create(tenv.tasklet[1], RWSCHED_DISPATCH_SOURCE_TYPE_TIMER, 0, 0, rwsched_dispatch_get_main_queue(tenv.rwsched)); rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1], tim, broker_sleep_test_timer); rwsched_dispatch_set_context(tenv.tasklet[1], tim, NULL); rwsched_dispatch_source_set_timer(tenv.tasklet[1], tim, dispatch_time(DISPATCH_TIME_NOW, 0*NSEC_PER_SEC), 100ull * NSEC_PER_SEC / 1000000ull, 0); rwsched_dispatch_resume(tenv.tasklet[1], tim); /* Make a serial queue for clichan */ rwsched_dispatch_queue_t q = rwsched_dispatch_queue_create(tenv.tasklet[0], "q", DISPATCH_QUEUE_SERIAL); rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, q); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 1\n"); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwsched_dispatch_source_cancel(tenv.tasklet[1], tim); rwmsg_garbage(&ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, tim, tenv.rwsched, tenv.tasklet[1]); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); rwsched_dispatch_release(tenv.tasklet[0], q); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } #if 0 { /* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ASSERT_TRUE(cc != NULL); /* Timer on main queue to sleep and thereby sputter broker acceptor event processing */ rwsched_dispatch_source_t tim = rwsched_dispatch_source_create(tenv.tasklet[3], RWSCHED_DISPATCH_SOURCE_TYPE_TIMER, 0, 0, rwsched_dispatch_get_main_queue(tenv.rwsched)); rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[3], tim, broker_sleep_test_timer); rwsched_dispatch_set_context(tenv.tasklet[3], tim, NULL); rwsched_dispatch_source_set_timer(tenv.tasklet[3], tim, dispatch_time(DISPATCH_TIME_NOW, 0*NSEC_PER_SEC), 100ull * NSEC_PER_SEC / 1000000ull, 0); rwsched_dispatch_resume(tenv.tasklet[3], tim); /* Make a serial queue for clichan */ rwsched_dispatch_queue_t q = rwsched_dispatch_queue_create(tenv.tasklet[3], "q", DISPATCH_QUEUE_SERIAL); rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, q); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 1\n"); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwsched_dispatch_source_cancel(tenv.tasklet[1], tim); rwmsg_garbage(&ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, tim, tenv.rwsched, tenv.tasklet[1]); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); rwsched_dispatch_release(tenv.tasklet[1], q); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchan) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(2); /* Broker is tasklet 0 */ rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_srvchan_t *cc = rwmsg_srvchan_create(ep); ASSERT_TRUE(cc != NULL); rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_bool_t r; rwmsg_srvchan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchan2Bros) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); { /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_srvchan_t *cc = rwmsg_srvchan_create(ep); ASSERT_TRUE(cc != NULL); rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_srvchan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } { /* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); rwmsg_srvchan_t *cc = rwmsg_srvchan_create(ep); ASSERT_TRUE(cc != NULL); rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_srvchan_halt(cc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } static void Test_increment(Test_Service *, const TestReq *req, void *ud, TestRsp_Closure clo, void *rwmsg); static void Test_fail(Test_Service *, const TestReq *req, void *ud, TestNop_Closure clo, void *rwmsg); void multibrocfb_response(const TestRsp *rsp, rwmsg_request_t *req, void *ud) { //struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo *)ud; //fprintf(stderr, "req->hdr.bnc=%d\n",req->hdr.bnc); //ASSERT_EQ(req->hdr.bnc, 0); //ASSERT_TRUE(rsp != NULL); if (rsp) { ASSERT_EQ(rsp->errval, 0); ASSERT_EQ(rsp->body.hopct+1, rsp->body.value); //tinfo->rsp_recv++; VERBPRN("ProtobufCliSrvCFNonblocking test got rsp, value=%u errval=%u\n", rsp->body.value, rsp->errval); } else { //tinfo->bnc_recv++; VERBPRN("ProtobufCliSrvCFNonblocking test got bnc=%d\n", (int)req->hdr.bnc); } return; rsp=rsp; req=req; ud=ud; } TEST(RWMsgBroker, AcceptSrvchanAndCliChanW1Bro_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); //rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 2; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); // fprintf(stderr, "test__increment - 01\n"); #if 1 rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[2]; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); #else rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); #endif // fprintf(stderr, "end dispatch_main 1\n"); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } const char *bnc_test_msg = "This Bounces"; static void bnc_test_meth_cb(rwmsg_request_t *req, void *ctx_in) { fprintf(stderr, "inside bnc_test_meth_cb()\n"); return; req = req; ctx_in = ctx_in; } static void bnc_test_rsp_cb(rwmsg_request_t *req, void *ctx_in) { ASSERT_TRUE(req->hdr.bnc); fprintf(stderr, "inside bnc_test_rsp_cb()\n"); rwmsg_flowid_t fid = rwmsg_request_get_response_flowid(req); #ifdef __RWMSG_BNC_RESPONSE_W_PAYLOAD uint32_t len=0; char *rsp = (char*)rwmsg_request_get_bnc_response_payload(req, &len); rsp = rsp; ASSERT_EQ(len, strlen(bnc_test_msg)); #endif return; req = req; fid = fid; ctx_in = ctx_in; } typedef struct bnc_test_ud { rwmsg_clichan_t *cc; rwmsg_destination_t *dt; uint32_t methno; } bnc_test_ud_t; #if 0 static void bnc_test_feedme(void *ctx_in, rwmsg_destination_t *dest, rwmsg_flowid_t flowid) { } #endif static void bnc_test_rsp_cb_and_set_feedme(rwmsg_request_t *req, void *ctx_in) { ASSERT_TRUE(req->hdr.bnc); fprintf(stderr, "inside bnc_test_rsp_cb()\n"); rwmsg_flowid_t fid = rwmsg_request_get_response_flowid(req); #if 0 bnc_test_ud_t *ud = (bnc_test_ud_t*)ctx_in; rwmsg_closure_t cb = { }; cb.ud = NULL; cb.feedme = bnc_test_feedme; rw_status_t rs = rwmsg_clichan_feedme_callback(ud->cc, ud->dt, fid, &cb); EXPECT_EQ(rs, RW_STATUS_SUCCESS); #endif #ifdef __RWMSG_BNC_RESPONSE_W_PAYLOAD uint32_t len=0; char *rsp = (char*)rwmsg_request_get_bnc_response_payload(req, &len); rsp = rsp; ASSERT_EQ(len, strlen(bnc_test_msg)); #endif return; req = req; fid = fid; ctx_in = ctx_in; } TEST(RWMsgBroker, AcceptSrvchanAndCliChanTOBnc) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); const uint32_t methno = __LINE__; /* Create the srvchan, bind a method */ rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig); int timeo = 50; // ms if (RUNNING_ON_VALGRIND) { timeo = timeo * 5; } rwmsg_signature_set_timeout(sig, timeo); rwmsg_closure_t methcb; methcb.request=bnc_test_meth_cb; methcb.ud=ep_s; rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(sc, meth); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Wait on binding the srvchan until after we've sent the initial flurry of requests. Otherwise, our ++ and the request handler's ++ of some of the request count variables ABA-stomp each other. */ rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Create the clichan, add the method's signature */ /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwmsg_request_t *req = rwmsg_request_create(cc); rwmsg_request_set_signature(req, sig); rwmsg_closure_t clicb; clicb.request=bnc_test_rsp_cb; clicb.ud=cc; rwmsg_request_set_callback(req, &clicb); rwmsg_request_set_payload(req, bnc_test_msg, strlen(bnc_test_msg)); /* Send it. The srvchan should more or less immediately run the thing and the methcb will respond. */ rs = rwmsg_clichan_send(cc, dt, req); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_signature_release(ep_s, sig); rwmsg_method_release(ep_s, meth); rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanNoPeerBnc) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); const uint32_t methno = __LINE__; /* Create the srvchan, bind a method */ rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig); int timeo = 1000; // ms if (RUNNING_ON_VALGRIND) { timeo = timeo * 5; } rwmsg_signature_set_timeout(sig, timeo); rwmsg_closure_t methcb; methcb.request=bnc_test_meth_cb; methcb.ud=ep_s; rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(sc, meth); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Wait on binding the srvchan until after we've sent the initial flurry of requests. Otherwise, our ++ and the request handler's ++ of some of the request count variables ABA-stomp each other. */ rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Create the clichan, add the method's signature */ /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwmsg_signature_t *sig_bad = rwmsg_signature_create(ep_c, RWMSG_PAYFMT_RAW, methno+666, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig_bad); rwmsg_request_t *req = rwmsg_request_create(cc); rwmsg_request_set_signature(req, sig_bad); rwmsg_closure_t clicb; clicb.request=bnc_test_rsp_cb; clicb.ud=cc; rwmsg_request_set_callback(req, &clicb); rwmsg_request_set_payload(req, bnc_test_msg, strlen(bnc_test_msg)); /* Send it. The srvchan should more or less immediately run the thing and the methcb will respond. */ rs = rwmsg_clichan_send(cc, dt, req); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 /* End clichan tasklet 1 */ rwmsg_signature_release(ep_c, sig_bad); rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_signature_release(ep_s, sig); rwmsg_method_release(ep_s, meth); rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanTestFlowCtrlHint) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); const uint32_t methno = __LINE__; /* Create the srvchan, bind a method */ rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig); int timeo = 50; // ms if (RUNNING_ON_VALGRIND) { timeo = timeo * 5; } rwmsg_signature_set_timeout(sig, timeo); rwmsg_closure_t methcb; methcb.request=bnc_test_meth_cb; methcb.ud=ep_s; rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(sc, meth); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Wait on binding the srvchan until after we've sent the initial flurry of requests. Otherwise, our ++ and the request handler's ++ of some of the request count variables ABA-stomp each other. */ rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Create the clichan, add the method's signature */ /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); rwmsg_request_t *req = rwmsg_request_create(cc); rwmsg_request_set_signature(req, sig); rwmsg_closure_t clicb; clicb.request=bnc_test_rsp_cb_and_set_feedme; bnc_test_ud_t *ud = (bnc_test_ud_t *) malloc(sizeof(*ud)); ud->cc = cc; ud->dt = dt; ud->methno = methno; clicb.ud=ud; rwmsg_request_set_callback(req, &clicb); rwmsg_request_set_payload(req, bnc_test_msg, strlen(bnc_test_msg)); ASSERT_NE(rwmsg_clichan_can_send_howmuch(cc, dt, methno, RWMSG_PAYFMT_RAW), 0); /* Send it. The srvchan should more or less immediately run the thing and the methcb will respond. */ rs = rwmsg_clichan_send(cc, dt, req); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_signature_release(ep_s, sig); rwmsg_method_release(ep_s, meth); rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, CloseSrvChanW1Bro) { uint32_t start_reqct = rwmsg_global.status.request_ct; ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); //rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 2; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); // fprintf(stderr, "test__increment - 01\n"); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[2]; for (int i=0; i<5; i++) { rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); } // fprintf(stderr, "end dispatch_main 1\n"); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif int sent_N_after_srvr_close = 10; for (int i=0; i<sent_N_after_srvr_close; i++) { rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); } loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); #endif loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_LE(start_reqct+sent_N_after_srvr_close, rwmsg_global.status.request_ct); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndBlkW1Bro) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); //rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); //rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[1]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); //rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[2]); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); // fprintf(stderr, "test__increment - 01\n"); rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); // fprintf(stderr, "end dispatch_main 1\n"); rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndNonConnDontQW1Bro_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); //rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[2]); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[1]; //dt->noconndontq = 1; rwmsg_destination_set_noconndontq(dt); rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_NOTCONNECTED); //dt->noconndontq = 0; rwmsg_destination_unset_noconndontq(dt); rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); } // fprintf(stderr, "end dispatch_main 1\n"); rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); //rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); //rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[1]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[1]; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); } // fprintf(stderr, "end dispatch_main 2\n"); rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanOnSame2Bros_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; rw_status_t rs; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(50*1000); // 50ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); // fprintf(stderr, "\nSrvchan-to-bro-1\n"); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 2; rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 // fprintf(stderr, "\ntest__increment - clican-to-bro-1\n"); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c_b0; ep_c_b0 = rwmsg_endpoint_create(0, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c_b0 != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0); ASSERT_TRUE(cc0 != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc0, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 2; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); int i; for (i=0; i<100; i++) { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[1]; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_TRUE(rs==RW_STATUS_SUCCESS); loopwait = 0.01; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } #endif #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc0); r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndBlkOnSame2Bros_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; rw_status_t rs; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(50*1000); // 50ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); // fprintf(stderr, "\nSrvchan-to-bro-1\n"); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); //rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[3]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); //rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[1]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); for (int i=0; i<100; i++) { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); #if 0 rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_TRUE(rs==RW_STATUS_SUCCESS); #else req.body.value = i+5; req.body.hopct = i+5; rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq)); const TestRsp *rsp; rs = rwmsg_request_get_response(rwreq, (const void **)&rsp); ASSERT_EQ(rs, RW_STATUS_SUCCESS); // fprintf(stderr, "ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i); multibrocfb_response(rsp, rwreq, tenv.tasklet[1]); #endif } for (int i=0; i<10; i++) { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_TRUE(rs==RW_STATUS_SUCCESS); } rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanOnSeperate2Bros_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; rw_status_t rs; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(5*1000); // 5ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); // fprintf(stderr, "\nSrvchan-to-bro-1\n"); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 // fprintf(stderr, "\ntest__increment - clican-to-bro-0\n"); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c_b0; ep_c_b0 = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c_b0 != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0); ASSERT_TRUE(cc0 != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc0, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = .2; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); sleep(1); rwmsg_global.status.request_ct = 0; #define AcceptSrvchanAndCliChanOnSeperate2Bros_COUNT 5 int i; rwmsg_request_t *rwreq=NULL; for (i=0; i<AcceptSrvchanAndCliChanOnSeperate2Bros_COUNT; i++) { TestReq req; test_req__init(&req); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[1]; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_TRUE(rs==RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); //loopwait = 0.001; //rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #endif //usleep(500*1000); loopwait = 2.0; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); rwmsg_request_release(rwreq); ASSERT_LE(rwmsg_global.status.request_ct, 0); #if 0 fprintf(stderr, "rwmsg_broker_dump = bro1\n"); rwmsg_broker_dump((rwmsg_broker_t *)bro1); fprintf(stderr, "\nrwmsg_broker_dump = bro2\n"); rwmsg_broker_dump((rwmsg_broker_t *)bro2); #endif #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc0); r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndBlkOnSeperate2Bros_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; rw_status_t rs; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(50*1000); // 50ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); // fprintf(stderr, "\nSrvchan-to-bro-1\n"); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); //rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[3]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); //rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[1]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); for (int i=0; i<100; i++) { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); #if 0 rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_TRUE(rs==RW_STATUS_SUCCESS); #else req.body.value = i+5; req.body.hopct = i+5; rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq)); const TestRsp *rsp; rs = rwmsg_request_get_response(rwreq, (const void **)&rsp); ASSERT_EQ(rs, RW_STATUS_SUCCESS); // fprintf(stderr, "ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i); multibrocfb_response(rsp, rwreq, tenv.tasklet[1]); #endif } rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndCFSndBlkOnSeperate2Bros_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; rw_status_t rs; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); // fprintf(stderr, "\nSrvchan-to-bro-1\n"); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); //rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[3]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); //rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[1]); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); for (int i=0; i<100; i++) { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); #if 0 rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_TRUE(rs==RW_STATUS_SUCCESS); #else req.body.value = i+5; req.body.hopct = i+5; rs = test__increment_b(&mycli, dt, &req, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq)); const TestRsp *rsp; rs = rwmsg_request_get_response(rwreq, (const void **)&rsp); ASSERT_EQ(rs, RW_STATUS_SUCCESS); // fprintf(stderr, "ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i); multibrocfb_response(rsp, rwreq, tenv.tasklet[1]); #endif } rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 2, FALSE); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } // This gtest is covering multibroker channel stall fixed in RIFT-9058 TEST(RWMsgBroker, CheckStuckMessagesOnSeperate2Bros_LONG) { rwmsg_global.status.endpoint_ct = 0; ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; rw_status_t rs; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(5*1000); // 5ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); // fprintf(stderr, "\nSrvchan-to-bro-1\n"); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c_b0; ep_c_b0 = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c_b0 != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0); ASSERT_TRUE(cc0 != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc0, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = .2; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); sleep(1); rwmsg_global.status.request_ct = 0; #define CheckStuckMessagesOnSeperate2Bros_COUNT 15 int i; rwmsg_request_t *rwreq=NULL; for (i=0; i<CheckStuckMessagesOnSeperate2Bros_COUNT; i++) { TestReq req; test_req__init(&req); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[1]; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_TRUE(rs==RW_STATUS_SUCCESS); } loopwait = 2.0; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #endif //rwmsg_request_release(rwreq); ASSERT_LE(rwmsg_global.status.request_ct, 1); #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc0); r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, AcceptSrvchanAndCliChanW3Bros_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(5); rwmsg_bool_t r; rw_status_t rs; //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); /* Broker is tasklet 4 */ rwmsg_broker_t *bro3=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[4]; rwmsg_broker_main(broport_g, 4, 2, tenv.rwsched, tenv.tasklet[4], tenv.rwcal, TRUE, tenv.ti, &bro3); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*3*(3-1); //==5*2*n*(n-1)/2 == 30 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(50*1000); // 50ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Srvchan is tasklet 3, attached to broker 2 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 2, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); //rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); int i; for (i=0; i<10; i++) { TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); // fprintf(stderr, "test__increment - 01\n"); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[1]; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } // fprintf(stderr, "end dispatch_main 2\n"); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro3); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, ReCreateSrvChanW1Bro_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(3); rwmsg_bool_t r; rw_status_t rs; setenv("RWMSG_CHANNEL_AGEOUT", "60", TRUE); //const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3"; const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); double loopwait = 0.1; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 5; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Clichan is tasklet 2, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ASSERT_TRUE(cc != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 2; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[2]; int send_some = 5; for (int i=0; i<send_some; i++) { req.body.value = i; req.body.hopct = i; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End srvchan tasklet 2 */ VERBPRN("\n\n\n\n-------------- End srvchan\n"); rwmsg_srvchan_halt(sc); loopwait = 2; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL); int send_some_more = 2; #if 1 VERBPRN("\n\n\n\n-------------- send_some_more %u\n", send_some_more); for (int i=0; i<send_some_more; i++) { req.body.value = 50+i; req.body.hopct = 50+i; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } #endif #if 1 VERBPRN("\n\n\n\n-------------- Create a Server Channel\n"); sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL); #endif send_some_more = 3; VERBPRN("\n\n\n\n-------------- send_some_more %u\n", send_some_more); for (int i=0; i<send_some_more; i++) { req.body.value = 100+i; req.body.hopct = 100+i; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } loopwait = 2; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL); VERBPRN("\n\n\n\n-------------- End srvchan & clichan\n"); /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc); r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, ReCreateSrvChanW2Bros_LONG) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests accepting from a srvchan"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; rw_status_t rs; setenv("RWMSG_CHANNEL_AGEOUT", "60", TRUE); const char *taddr = "/L/GTEST/RWBRO/1"; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); double loopwait = 0.1; int loopcount = 0; uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10 /* Should now accept and ultimately timeout in the broker's acceptor */ //rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening); while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) { usleep(5*1000); // 5ms rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL); } ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* Srvchan is tasklet 3, attached to broker 0 * also bound to main rws queue to avoid CF/dispatch headachess * This endpoint has bro_instid=0 */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); // fprintf(stderr, "\nSrvchan-to-bro-1\n"); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); rwmsg_srvchan_t *sc; sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); Test_Service myapisrv; TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #if 1 rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Clichan is tasklet 1, attached to broker 1 * also bound to main rws queue to avoid CF/dispatch headaches * This endpoint has bro_instid=1 */ rwmsg_endpoint_t *ep_c_b0; ep_c_b0 = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c_b0 != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1); /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ rwmsg_destination_t *dt; //dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, tpeerpath); dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0); ASSERT_TRUE(cc0 != NULL); rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched)); Test_Client mycli; TEST__INITCLIENT(&mycli); rwmsg_clichan_add_service(cc0, &mycli.base); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ loopwait = .2; rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); sleep(1); rwmsg_global.status.request_ct = 0; TestReq req; rwmsg_request_t *rwreq=NULL; test_req__init(&req); rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[2]; int send_some = 5; for (int i=0; i<send_some; i++) { req.body.value = i; req.body.hopct = i; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); #endif VERBPRN("\n\n\n\n-------------- End srvchan, send_some_more, recreate & send_some_more\n"); #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); test_req__init(&req); cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[2]; int send_some_more = 5; for (int i=0; i<send_some_more; i++) { req.body.value = 50+i; req.body.hopct = 50+i; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(sc != NULL); TEST__INITSERVER(&myapisrv, Test_); rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); loopwait = 1; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); test_req__init(&req); cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response; cb.ud=tenv.tasklet[2]; send_some_more = 5; for (int i=0; i<send_some_more; i++) { req.body.value = 100+i; req.body.hopct = 100+i; rs = test__increment(&mycli, dt, &req, &cb, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); loopwait = 0.001; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); } #endif //usleep(500*1000); loopwait = 1.0; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed); rwmsg_request_release(rwreq); //ASSERT_LE(rwmsg_global.status.request_ct, 0); #if 0 fprintf(stderr, "rwmsg_broker_dump = bro1\n"); rwmsg_broker_dump((rwmsg_broker_t *)bro1); fprintf(stderr, "\nrwmsg_broker_dump = bro2\n"); rwmsg_broker_dump((rwmsg_broker_t *)bro2); #endif #if 1 /* End clichan tasklet 1 */ rwmsg_clichan_halt(cc0); r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE); ASSERT_TRUE(r); #endif #if 1 /* End srvchan tasklet 2 */ rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); #endif /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } static void reqcb1(rwmsg_request_t *req, void *ud) { req=req; ud=ud; } TEST(RWMsgBroker, BindSrvchan) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests method binds a srvchan to a broker"); rwmsg_btenv_t tenv(2); /* Broker is tasklet 0 */ rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro); /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); const char *taddr = "/L/GTEST/RWBRO/TESTAPP/1"; rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep); ASSERT_TRUE(sc != NULL); rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_signature_t *sig; const int methno = 5; sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig != NULL); rwmsg_closure_t cb; cb.request=reqcb1; cb.ud=NULL; rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &cb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(sc, meth); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_EQ(rwmsg_broker_g.exitnow.method_bindings, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_bool_t r; rwmsg_signature_release(ep, sig); rwmsg_method_release(ep, meth); rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); /* End broker */ r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } TEST(RWMsgBroker, BindSrvchan2Bros) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); TEST_DESCRIPTION("Tests method binds a srvchan to a broker"); rwmsg_btenv_t tenv(4); rwmsg_bool_t r; /* Broker is tasklet 0 */ rwmsg_broker_t *bro1=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[0]; rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1); /* Broker is tasklet 2 */ rwmsg_broker_t *bro2=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[2]; rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2); { /* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); const char *taddr = "/L/GTEST/RWBRO/TESTAPP/2"; rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep); ASSERT_TRUE(sc != NULL); rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_signature_t *sig; const int methno = 5; sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig != NULL); rwmsg_closure_t cb; cb.request=reqcb1; cb.ud=NULL; rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &cb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(sc, meth); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed); //ASSERT_EQ(rwmsg_broker_g.exitnow.method_bindings, 2); ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_signature_release(ep, sig); rwmsg_method_release(ep, meth); rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } { /* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */ rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); const char *taddr = "/L/GTEST/RWBRO/TESTAPP/3"; rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep); ASSERT_TRUE(sc != NULL); rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched)); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_signature_t *sig; const int methno = 5; sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig != NULL); rwmsg_closure_t cb; cb.request=reqcb1; cb.ud=NULL; rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &cb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(sc, meth); ASSERT_TRUE(rs == RW_STATUS_SUCCESS); rwmsg_broker_g.exitnow.method_bindings = 0; rwmsg_broker_g.exitnow.neg_accepted = 0; rwmsg_broker_g.exitnow.neg_freed = 0; rwmsg_broker_g.exitnow.neg_freed_err = 0; /* Should now accept, read hs, create broclichan, attach incoming accepted sk */ int loopwait = 10; rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, &rwmsg_broker_g.exitnow.neg_freed); ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1); ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0); /* End clichan tasklet 1 */ rwmsg_signature_release(ep, sig); rwmsg_method_release(ep, meth); rwmsg_srvchan_halt(sc); r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); } /* End broker */ r = rwmsg_broker_halt_sync(bro1); ASSERT_TRUE(r); r = rwmsg_broker_halt_sync(bro2); ASSERT_TRUE(r); ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); } struct mycfbctx { int doblocking; int done; uint64_t tid; int assertsinglethread; uint32_t msgct_end; uint32_t burst; rwsched_instance_ptr_t rwsched; rwsched_CFRunLoopRef loop; uint32_t tickct; // number of timer ticks testwide uint32_t timerct; // number of timers that exist rwmsg_broker_t *bro; }; struct mycfbtaskinfo { int tnum; uint64_t tid; rwsched_CFRunLoopTimerRef cftim; Test_Service myapisrv; Test_Client mycli; char tpath[128]; char tpeerpath[128]; rwmsg_endpoint_t *ep; rwmsg_srvchan_t *sc; rwmsg_destination_t *dt; rwmsg_clichan_t *cc; struct mycfbctx *ctx; rwsched_tasklet_ptr_t tasklet; uint32_t req_sent; uint32_t req_eagain; uint32_t rsp_recv; uint32_t bnc_recv; uint32_t tickct; // number of timer ticks in this tasklet }; static void brodump_f(void *val) { fprintf(stderr, "Gratuitous call to broker dump for smoketest/coverage reasons:\n"); rwmsg_broker_dump((rwmsg_broker_t *)val); } static void mycfb_response(const TestRsp *rsp, rwmsg_request_t *req, void *ud) { struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo *)ud; VERBPRN("req->hdr.bnc=%d\n",req->hdr.bnc); // fprintf(stderr,"req->hdr.bnc=%d\n",req->hdr.bnc); { static int once=0; if (tinfo->ctx->bro && !once) { once=1; rwsched_dispatch_async_f(tinfo->ctx->bro->tinfo, rwsched_dispatch_get_main_queue(tinfo->ctx->rwsched), tinfo->ctx->bro, brodump_f); } } // ASSERT_TRUE(rsp != NULL); if (rsp) { ASSERT_EQ(rsp->errval, 0); ASSERT_EQ(rsp->body.hopct+1, rsp->body.value); tinfo->rsp_recv++; VERBPRN("ProtobufCliSrvCFNonblocking test got rsp, value=%u errval=%u\n", rsp->body.value, rsp->errval); } else { tinfo->bnc_recv++; VERBPRN("ProtobufCliSrvCFNonblocking test got bnc=%d\n", (int)req->hdr.bnc); } return; req=req; } #define GETTID() syscall(SYS_gettid) static void mycfb_timer_cb(rwsched_CFRunLoopTimerRef timer, void *info) { struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo *)info; ASSERT_TRUE(tinfo->cftim != NULL); /*oops ASSERT_EQ(tinfo->cftim, timer);*/ if (tinfo->ctx->assertsinglethread) { uint64_t tid = GETTID(); if (!tinfo->tid) { tinfo->tid = tid; } else { ASSERT_EQ(tinfo->tid, tid); } if (!tinfo->ctx->tid) { tinfo->ctx->tid = tid; } else { ASSERT_EQ(tinfo->ctx->tid, tid); } } if (tinfo->req_sent >= tinfo->ctx->msgct_end) { if (tinfo->req_sent <= (tinfo->bnc_recv + tinfo->rsp_recv)) { RW_ASSERT(tinfo->req_sent == (tinfo->bnc_recv + tinfo->rsp_recv)); if (tinfo->cftim) { VERBPRN("Stopping timer after response %u + bnc %u in tasklet '%s'\n", tinfo->rsp_recv, tinfo->bnc_recv, tinfo->tpath); rwsched_tasklet_CFRunLoopTimerInvalidate(tinfo->tasklet, tinfo->cftim); tinfo->cftim = 0; tinfo->ctx->timerct--; if (!tinfo->ctx->timerct) { VERBPRN("All tasklet timers gone, ending runloop\n"); //CFRunLoopStop(tinfo->ctx->loop); CFRunLoopStop(rwsched_tasklet_CFRunLoopGetCurrent(tinfo->tasklet)); tinfo->ctx->done = 1; } } } return; } TestReq req; test_req__init(&req); for (uint32_t i=0; i<tinfo->ctx->burst; i++) { rwmsg_request_t *rwreq=NULL; req.body.value = tinfo->req_sent; req.body.hopct = tinfo->req_sent; if (tinfo->ctx->doblocking) { rw_status_t rs; rwreq = NULL; VERBPRN("ProtobufCliSrvCFBlocking test sending req, value=%u burst i=%u\n", req.body.value, i); rs = test__increment_b(&tinfo->mycli, tinfo->dt, &req, &rwreq); ASSERT_EQ(rs, RW_STATUS_SUCCESS); ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq)); const TestRsp *rsp; rs = rwmsg_request_get_response(rwreq, (const void **)&rsp); ASSERT_EQ(rs, RW_STATUS_SUCCESS); tinfo->req_sent++; VERBPRN("ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i); mycfb_response(rsp, rwreq, info); } else { rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)mycfb_response; cb.ud=tinfo; VERBPRN("ProtobufCliSrvCFNonblocking test sending req, value=%u burst i=%u\n", req.body.value, i); rw_status_t rs; rs = test__increment(&tinfo->mycli, tinfo->dt, &req, &cb, &rwreq); switch (rs) { case RW_STATUS_SUCCESS: VERBPRN("ProtobufCliSrvCFNonblocking test sent req, burst i=%u\n", i); tinfo->req_sent++; break; case RW_STATUS_BACKPRESSURE: VERBPRN("ProtobufCliSrvCFNonblocking test got backpressure, burst i=%u\n", i); tinfo->req_eagain++; break; default: ASSERT_EQ(rs, RW_STATUS_SUCCESS); break; } } } tinfo->tickct++; tinfo->ctx->tickct++; return; timer=timer; } static void Test_increment(Test_Service *, const TestReq *req, void *ud, TestRsp_Closure clo, void *rwmsg) { TestRsp rsp; test_rsp__init(&rsp); /* Fill in a response, including a copy of the adjusted request body with the value bumped */ rsp.errval = 0; rsp.has_body = TRUE; rsp.body = req->body; rsp.body.value++; VERBPRN(" Test_increment(value=%u) returning value=%u\n", req->body.value, rsp.body.value); /* Send the response */ clo(&rsp, rwmsg); return; ud=ud; } static void Test_fail(Test_Service *, const TestReq *req, void *ud, TestNop_Closure clo, void *rwmsg) { TestNop rsp; test_nop__init(&rsp); if (req->body.value) { VERBPRN(" Test_fail(value=%u) returning errval=1\n", req->body.value); } rsp.errval = 1; clo(&rsp, rwmsg); return; ud=ud; } /** \if NOPE */ static void pbcscf(int taskct, int doblocking, uint32_t burst, uint32_t startburst, uint32_t endat, int broker) { ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); VERBPRN("ProtobufCliSrvCFNonblocking test begin, taskct=%d doblocking=%d burst=%u startburst=%u endat=%u broker=%d\n", taskct, doblocking, burst, startburst, endat, broker); struct mycfbctx tctx; struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo*)RW_MALLOC0(sizeof(*tinfo) * taskct); memset(&tctx, 0, sizeof(tctx)); /* * Create a rwsched / tasklet runtime and the one rwmsg endpoint for * this tasklet. (Probably all handled in tasklet infrastructure). * broker = -1 ==> no shunt * broker = 0 ==> no broker * broker > 0 ==> number of brokers */ unsigned broker_c = (broker<0?1:broker); rwmsg_btenv_t tenv(taskct+(broker_c?broker_c:1)); // test env, on stack, dtor cleans up ASSERT_TRUE(tenv.rwsched != NULL); rwmsg_broker_t *bros[broker_c]; memset(bros, 0, sizeof(bros)); if (broker_c) { for (unsigned i=0; i<broker_c; i++) { //fprintf(stderr, "tasklet.broker[%u]=%p\n",i, tenv.tasklet[tenv.tasklet_ct-(broker_c-i)]); tenv.ti->rwsched_tasklet_info = tenv.tasklet[tenv.tasklet_ct-(broker_c-i)]; rwmsg_broker_main(broport_g, tenv.tasklet_ct-(broker_c-i), i, tenv.rwsched, tenv.tasklet[tenv.tasklet_ct-(broker_c-i)], tenv.rwcal, TRUE, tenv.ti, &bros[i]); //tctx.bro = bro; } } rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); const char *taddrbase = "/L/GTEST/RWBRO/TESTAPP/PBSCF"; char taddrpfx[128]; static unsigned testct = 100; sprintf(taddrpfx, "%s/%u", taddrbase, testct++); tctx.rwsched = tenv.rwsched; tctx.doblocking = doblocking; tctx.burst = burst; tctx.msgct_end = endat; tctx.assertsinglethread = FALSE; tctx.tid = GETTID(); for (unsigned t=0; t<tenv.tasklet_ct-(broker_c?broker_c:1)/*brokers are last ones*/; t++) { //fprintf(stderr, "tasklet[%u]=%p\n",t, tenv.tasklet[t]); tinfo[t].tnum = t; tinfo[t].ctx = &tctx; tinfo[t].tasklet = tenv.tasklet[t]; sprintf(tinfo[t].tpath, "%s/%d", taddrpfx, t); sprintf(tinfo[t].tpeerpath, "%s/%d", taddrpfx, (t&1) ? t-1 : t+1); tinfo[t].ep = rwmsg_endpoint_create(1, t, (broker_c?(t%broker_c):0), tenv.rwsched, tenv.tasklet[t], rwtrace_init(), NULL); ASSERT_TRUE(tinfo[t].ep != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(tinfo[t].ep, "/rwmsg/broker/shunt", (broker > 0)); // no shunt when broker==-1 rwsched_CFRunLoopRef runloop = rwsched_tasklet_CFRunLoopGetCurrent(tenv.tasklet[t]); if (t&1) { /* Create a server channel in odd numbered tasklets */ tinfo[t].sc = rwmsg_srvchan_create(tinfo[t].ep); ASSERT_TRUE(tinfo[t].sc != NULL); /* Instantiate the 'Test' protobuf service as the set of callbacks * named Test_<x>, and bind this Test service to our server channel * at the given nameservice location. */ TEST__INITSERVER(&tinfo[t].myapisrv, Test_); rw_status_t rs = rwmsg_srvchan_add_service(tinfo[t].sc, tinfo[t].tpath, &tinfo[t].myapisrv.base, &tinfo[t]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); rs = rwmsg_srvchan_bind_rwsched_cfrunloop(tinfo[t].sc, tenv.tasklet[t]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); } else { /* Create a client channel pointing at the Test service's path. * Instantiate a Test service client and connect this to the client * channel. */ tinfo[t].dt = rwmsg_destination_create(tinfo[t].ep, RWMSG_ADDRTYPE_UNICAST, tinfo[t].tpeerpath); ASSERT_TRUE(tinfo[t].dt != NULL); tinfo[t].cc = rwmsg_clichan_create(tinfo[t].ep); ASSERT_TRUE(tinfo[t].cc != NULL); TEST__INITCLIENT(&tinfo[t].mycli); rwmsg_clichan_add_service(tinfo[t].cc, &tinfo[t].mycli.base); rw_status_t rs = rwmsg_clichan_bind_rwsched_cfrunloop(tinfo[t].cc, tenv.tasklet[t]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Send some requests right away, test pre-connection request buffering in ssbufq. They may happen still to bounce should the server not have connected yet to the broker by the time the req gets there. */ if (startburst) { RW_ASSERT(!tctx.doblocking); // no can do rwmsg_closure_t cb; cb.pbrsp=(rwmsg_pbapi_cb)mycfb_response; cb.ud=tinfo; uint32_t u=0; rw_status_t rs = RW_STATUS_SUCCESS; for (u=0; rs == RW_STATUS_SUCCESS && u<startburst; u++) { TestReq req; test_req__init(&req); rwmsg_request_t *rwreq=NULL; req.body.value = tinfo[t].req_sent; req.body.hopct = tinfo[t].req_sent; VERBPRN("ProtobufCliSrvCFNonblocking test sending req, value=%u burst u=%u\n", req.body.value, u); rs = test__increment(&tinfo[t].mycli, tinfo[t].dt, &req, &cb, &rwreq); switch (rs) { case RW_STATUS_SUCCESS: VERBPRN("ProtobufCliSrvCFNonblocking test sent req, burst u=%u\n", u); tinfo[t].req_sent++; break; case RW_STATUS_BACKPRESSURE: VERBPRN("ProtobufCliSrvCFNonblocking test got backpressure, burst u=%u\n", u); tinfo[t].req_eagain++; break; case RW_STATUS_NOTCONNECTED: VERBPRN("ProtobufCliSrvCFNonblocking test got notconected, burst u=%u\n", u); tinfo[t].req_eagain++; break; default: VERBPRN("ProtobufCliSrvCFNonblocking test got rs=%d, burst u=%u\n", rs, u); break; } } /* Figure out the ssbufq size and check that we sent at most that many */ int premax = 9999999; rs = rwmsg_endpoint_get_property_int(tinfo[t].ep, "/rwmsg/queue/cc_ssbuf/qlen", &premax); RW_ASSERT(rs == RW_STATUS_SUCCESS); /* max is nominally 1 per destination due to flow window logic, although we skate on the edge and crank it a bit. ought to support flow/seqno application on the other end of the queue, but that's a nightmare */ int defwin = 1; rwmsg_endpoint_get_property_int(tinfo[t].ep, "/rwmsg/destination/defwin", &defwin); //too gimpy a check, consider feedme vs nofeedme etc: ASSERT_EQ(tinfo[t].req_sent, MIN(defwin, MIN(premax, (int)startburst))); } /* Run a timer to execute some requests */ rwsched_CFRunLoopTimerContext cf_context = { 0, NULL, NULL, NULL, NULL }; double timer_interval = 200/*ms*/ * .001; timer_interval += (t * 20/*ms*/ * .001); // extra smidge for each new tasklet to avoid stampede double valgfactor = 1.0; if (RUNNING_ON_VALGRIND) { valgfactor = 2.5; } cf_context.info = &tinfo[t]; tinfo[t].cftim = rwsched_tasklet_CFRunLoopTimerCreate(tenv.tasklet[t], kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + (valgfactor * 10.0 * timer_interval), // allow a while for connections to come up timer_interval, 0, 0, mycfb_timer_cb, &cf_context); RW_CF_TYPE_VALIDATE(tinfo[t].cftim, rwsched_CFRunLoopTimerRef); rwsched_tasklet_CFRunLoopAddTimer(tenv.tasklet[t], runloop, tinfo[t].cftim, RWMSG_RUNLOOP_MODE);//kCFRunLoopCommonModes); tctx.timerct++; } } //tctx.loop = rwsched_tasklet_CFRunLoopGetCurrent(tenv.rwsched); struct timeval start, stop, delta; int looptot = 60; if (RUNNING_ON_VALGRIND) { looptot = looptot * 5 / 2; } int loopwait = looptot; VERBPRN("loop iter begin\n"); gettimeofday(&start, NULL); do { rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, loopwait, FALSE); gettimeofday(&stop, NULL); timersub(&stop, &start, &delta); VERBPRN("loop iter %ld.%03ld tctx.done=%d\n", delta.tv_sec, delta.tv_usec / 1000, tctx.done); loopwait = looptot - delta.tv_sec; } while (loopwait > 0 && !tctx.done); ASSERT_TRUE(tctx.done); //sleep(2); VERBPRN("loop runtime %lu ms\n", delta.tv_sec * 1000 + delta.tv_usec / 1000); //RW_RESOURCE_TRACK_DUMP(g_rwresource_track_handle); for (unsigned t=0; t<tenv.tasklet_ct-(broker_c?broker_c:1)/*brokers are last ones*/; t++) { if (t&1) { rwmsg_srvchan_halt(tinfo[t].sc); } else { rwmsg_destination_release(tinfo[t].dt); rwmsg_clichan_halt(tinfo[t].cc); if (tinfo[t].req_eagain) { fprintf(stderr, "Tasklet %d req_sent=%u req_eagain=%u\n", t, tinfo[t].req_sent, tinfo[t].req_eagain); } if (tinfo[t].bnc_recv) { fprintf(stderr, "Tasklet %d req_sent=%u bnc_recv=%u\n", t, tinfo[t].req_sent, tinfo[t].bnc_recv); } ASSERT_LE(tinfo[t].bnc_recv, MAX(burst,startburst)); } rwmsg_bool_t r; VERBPRN("rwmsg_endpoint_halt_flush(ep=%p tasklet %d)\n", tinfo[t].ep, t); r = rwmsg_endpoint_halt_flush(tinfo[t].ep, TRUE); ASSERT_TRUE(r); } if (broker_c) { rwmsg_bool_t r; for (unsigned i=0; i<broker_c; i++) { if (bros[i]) { VERBPRN("broker_halt_sync()\n"); r = rwmsg_broker_halt_sync(bros[i]); ASSERT_TRUE(r); } } } ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0); nnchk(); if (tinfo) { RW_FREE(tinfo); } VERBPRN("ProtobufCliSrvCFNonblocking test end\n"); } /** \endif */ TEST(RWMsgBroker, PbCliSrvCFNonblk2Bro) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, broker"); int taskct = 2; int doblocking = 0; uint32_t burst = 2; uint32_t startburst = 0; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 1); } TEST(RWMsgBroker, PbCliSrvCFNonblk2Bro2Bros) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, 2 broker"); int taskct = 2; int doblocking = 0; uint32_t burst = 2; uint32_t startburst = 0; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 2); } TEST(RWMsgBroker, PbCliSrvCFBrstNonblk2Bro) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, broker"); int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 0; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 1); } TEST(RWMsgBroker, PbCliSrvCFBrstNonblk2Bro2Bros) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, 2 broker"); int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 0; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 2); } TEST(RWMsgBroker, PbCliSrvCFBrstStartburst1Nonblk2Bro) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 1, broker"); // send one request straightaway to exercise the ssbufq buffer used to hold initial requests sent before broker connection comes up int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 1; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 1); } TEST(RWMsgBroker, PbCliSrvCFBrstStartburst1Nonblk2Bro2Bros) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 1, 2 broker"); // send one request straightaway to exercise the ssbufq buffer used to hold initial requests sent before broker connection comes up int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 1; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 2); } TEST(RWMsgBroker, PbCliSrvCFBrstStartburst16Nonblk2Bro) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 16, broker"); // this is the startup xmit buffer size int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 16; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 1); } TEST(RWMsgBroker, PbCliSrvCFBrstStartburst16Nonblk2Bro2Bros) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 16, 2 broker"); // this is the startup xmit buffer size int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 16; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 2); } TEST(RWMsgBroker, PbCliSrvCFBrstStartburst24Nonblk2Bro_LONG) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 24, broker"); // this is supposed to exceed the startup buffer and demonstrate 1+ initial requests experiencing backpressure int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 24; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 1); } TEST(RWMsgBroker, PbCliSrvCFBrstStartburst24Nonblk2Bro2Bros) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 24, 2 broker"); // this is supposed to exceed the startup buffer and demonstrate 1+ initial requests experiencing backpressure int taskct = 2; int doblocking = 0; uint32_t burst = 20; uint32_t startburst = 24; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 2); } TEST(RWMsgBroker, PbCliSrvCFBlk2Bro) { TEST_DESCRIPTION("Tests protobuf service client and server, blocking under taskletized CFRunloop, 2 tasklets, broker"); int taskct = 2; int doblocking = 1; uint32_t burst = 2; uint32_t startburst = 0; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 1); } TEST(RWMsgBroker, PbCliSrvCFBlk2Bro2Bros) { TEST_DESCRIPTION("Tests protobuf service client and server, blocking under taskletized CFRunloop, 2 tasklets, 2 broker"); int taskct = 2; int doblocking = 1; uint32_t burst = 1; uint32_t startburst = 0; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 2); } TEST(RWMsgBroker, PbCliSrvCFNonblk2BroIdle) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, no shunt to broker"); int taskct = 2; int doblocking = 0; uint32_t burst = 2; uint32_t startburst = 0; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, -1); } TEST(RWMsgBrokerNot, PbCliSrvCFNonblk2) { TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, no broker"); int taskct = 2; int doblocking = 0; uint32_t startburst = 0; uint32_t burst = 2; uint32_t endct = 2 * burst; pbcscf(taskct, doblocking, burst, startburst, endct, 0); } struct lottaopts { int bigbrosrvwin; int bigdefwin; int reqtimeo; int bncall; int srvrspfromanyq; uint32_t paysz; }; struct lottarawvals { uint64_t sec; uint64_t flushtime; uint64_t rmax; uint64_t reqsent; uint64_t firstburst; uint64_t reqans; uint64_t reqdone; uint64_t reqbnc; uint64_t reqbnc_final; uint64_t reqhz; uint64_t min_rtt; uint64_t max_rtt; }; struct sctest1_payload { uint32_t rno; char str[200]; }; struct sctest1_context { int verbose; int window; int tokenbucket; uint32_t tokenfill_ct; int flowexercise; struct lottaopts *opts; struct sctest1_payload *paybuf; rwmsg_flowid_t flowid; int unpout; int usebro; int ccwaiting; uint32_t rcvburst; int sendmore; int sendone; uint32_t sendmsg_firstburst_done; uint32_t sendmsg_preflow; uint32_t kickct; uint32_t done; rwmsg_srvchan_t *sc; rwmsg_clichan_t *cc; rwmsg_destination_t *dt; uint64_t sc_tid; uint64_t cc_tid; int checktid; rwmsg_signature_t *sig; #define SCTEST1_RMAX (10000) uint32_t rmax; uint32_t misorderct; /* Keep a queue of the request transmit order, to compare with response arrival order */ uint32_t expectedreqno[SCTEST1_RMAX+50]; uint32_t expectedreqno_head; uint32_t expectedreqno_tail; #define SCTEST1_RNO_ENQ(ctx, rno) { \ ((ctx)->expectedreqno[(ctx)->expectedreqno_tail] = (rno)); \ if ((++(ctx)->expectedreqno_tail) >= ((ctx)->rmax + 50)) { \ (ctx)->expectedreqno_tail = 0; \ } \ } #define SCTEST1_RNO_DEQ(ctx) ({ \ ASSERT_NE((ctx)->expectedreqno_head , (ctx)->expectedreqno_tail); \ int rno=((ctx)->expectedreqno[(ctx)->expectedreqno_head]); \ if ((++(ctx)->expectedreqno_head) >= ((ctx)->rmax + 50)) { \ (ctx)->expectedreqno_head = 0; \ } \ rno; \ }) uint32_t paysz; rwmsg_request_t *r[SCTEST1_RMAX]; uint32_t in; uint32_t out; uint32_t rspin; uint32_t rspout; uint32_t bncout; uint32_t miss; uint64_t min_rtt; uint64_t max_rtt; rwsched_dispatch_queue_t rwq[2]; rwsched_dispatch_source_t sc_timer; rwmsg_btenv_t *tenv; }; #define GETTID() syscall(SYS_gettid) static void lottakickoff(void *ctx_in); static void sctest1_clicb_feedme(void *ctx_in, rwmsg_destination_t *dest, rwmsg_flowid_t flowid) { RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; if (ctx->verbose) { fprintf(stderr, "sctest1_clicb_feedme: dest='%s',flowid=%u\n", dest->apath, flowid); } lottakickoff(ctx_in); } static void sctest1_clicb1(rwmsg_request_t *req, void *ctx_in) { RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; int expected = 0; if (ctx->sc_tid) { if (!ctx->cc_tid) { ctx->cc_tid = GETTID(); if (ctx->checktid) { EXPECT_EQ(ctx->cc_tid, ctx->sc_tid); } } else if (ctx->checktid) { uint64_t curtid = GETTID(); EXPECT_EQ(ctx->cc_tid, curtid); ctx->cc_tid = curtid; } } /* clichan request callback */ if (1 || ctx->flowexercise) { /* Register for the flow control callback the first time, or rather when the flowid changes */ rwmsg_flowid_t fid = rwmsg_request_get_response_flowid(req); if (fid && fid != ctx->flowid) { ctx->flowid = fid; rwmsg_closure_t cb = { }; cb.ud = ctx; cb.feedme = sctest1_clicb_feedme; rw_status_t rs = rwmsg_clichan_feedme_callback(ctx->cc, ctx->dt, ctx->flowid, &cb); EXPECT_EQ(rs, RW_STATUS_SUCCESS); //ASSERT_GT(rwmsg_clichan_can_send_howmuch(ctx->cc, ctx->dt, ctx->sig->methno, ctx->sig->payt), 0); } } uint32_t len=0; const struct sctest1_payload *rsp = (const struct sctest1_payload*)rwmsg_request_get_response_payload(req, &len); uint32_t rno; uint64_t rtt = rwmsg_request_get_response_rtt(req); if (rtt > 0) { if (rtt < ctx->min_rtt) { ctx->min_rtt = rtt; } if (rtt > ctx->max_rtt) { ctx->max_rtt = rtt; } } if (rsp) { ck_pr_inc_32(&ctx->rspout); if (ctx->verbose) { fprintf(stderr, "sctest1_clicb1: got rsp len=%d rno=%u str='%s'\n", len, rsp->rno, rsp->str); } int ticks = (RUNNING_ON_VALGRIND ? 100 : 10000); if (ctx->rspout < 1000) { ticks = 100; } if (ctx->rspout % ticks == 0) { fprintf(stderr, "_"); } RW_ASSERT(rsp->rno < ctx->rmax); rno = rsp->rno; } else { ck_pr_inc_32(&ctx->bncout); rwmsg_bounce_t bcode = rwmsg_request_get_response_bounce(req); int bcodeint = (int)bcode; const char *bncdesc[] = { "OK", "NODEST", "NOMETH", "NOPEER", "BROKERR", "TIMEOUT", "RESET", "TERM", NULL }; RW_ASSERT(bcodeint < RWMSG_BOUNCE_CT); if (ctx->bncout < 10) { fprintf(stderr, "b(%s)", bncdesc[bcodeint]); } if (ctx->bncout % 1000 == 0) { fprintf(stderr, "B(%s)", bncdesc[bcodeint]); } for (rno = 0; rno < ctx->rmax; rno++) { if (req == ctx->r[rno]) { goto found; } } fprintf(stderr, "sctest1_clicb1: bnc req=%p not found!?\n", req); RW_ASSERT(rno < ctx->rmax); if (!ctx->sendmore) { goto checkend; } return; found: ; // fprintf(stderr, "sctest1_clicb1: req rno=%d had no rsp payload!?\n", rno); } /* Verify responses are in order, up until -- or shortly before! -- we get a bounce, at which point all bets are off */ expected = SCTEST1_RNO_DEQ(ctx); if (!ctx->bncout) { if ((int)rno != expected) { ctx->misorderct++; } } /* req ceases to be valid when we return, so find and clear our handle to it */ RW_ASSERT(rno < ctx->rmax); RW_ASSERT(ctx->r[rno]); ctx->r[rno] = NULL; /* If the test has the repeat flag set, reissue another request */ if (ctx->sendmore) { RW_ASSERT(ctx->cc); ctx->r[rno] = rwmsg_request_create(ctx->cc); ASSERT_TRUE(ctx->r[rno] != NULL); rwmsg_request_set_signature(ctx->r[rno], ctx->sig); rwmsg_closure_t clicb; clicb.request=sctest1_clicb1; clicb.ud=ctx; rwmsg_request_set_callback(ctx->r[rno], &clicb); memset(ctx->paybuf, 0, sizeof(struct sctest1_payload)); ctx->paybuf->rno = rno; sprintf(ctx->paybuf->str, "hi there rno=%d", rno); rwmsg_request_set_payload(ctx->r[rno], ctx->paybuf, MAX(ctx->paysz, sizeof(struct sctest1_payload))); /* Send it. The srvchan should more or less immediately run the thing and the methcb will respond. */ ck_pr_inc_32(&ctx->in); rw_status_t rs = rwmsg_clichan_send(ctx->cc, ctx->dt, ctx->r[rno]); if (rs == RW_STATUS_BACKPRESSURE) { // && ctx->flowexercise) if (ctx->verbose) { fprintf(stderr, "sctest1_clicb1 _send rno=%u backpressure\n", rno); } ck_pr_dec_32(&ctx->in); rwmsg_request_release(ctx->r[rno]); ctx->r[rno] = NULL; ctx->ccwaiting = TRUE; /* backpressure will trigger feedme callback */ } else if (rs != RW_STATUS_SUCCESS) { ck_pr_dec_32(&ctx->in); rwmsg_request_release(ctx->r[rno]); ctx->r[rno] = NULL; ctx->sendmore = FALSE; fprintf(stderr, "sctest1_clicb1: rwmsg_clichan_send() rs=%u\n", rs); } else { /* We should not have two out with the same ID */ if (ctx->verbose) { fprintf(stderr, "sctest1_clicb1 _send rno=%u sent, ccwaiting now 0\n", rno); } SCTEST1_RNO_ENQ(ctx, rno); ctx->ccwaiting = FALSE; uint32_t rr; for (rr = 0; rr < ctx->rmax; rr++) { if (ctx->r[rr] && rr != rno) { if (ctx->usebro) { RW_ASSERT(ctx->r[rr]->hdr.id.locid != ctx->r[rno]->hdr.id.locid); } } } } if (1 || ctx->flowexercise) { lottakickoff(ctx); } } else { checkend: if ((ctx->bncout + ctx->rspout) == ctx->in) { ctx->done = TRUE; } } } static void lottakickoff(void *ctx_in) { /* Send the actual request(s). The rsp callback will repeat them as they are answered (ctx->repeat) */ RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; int rno=0; RW_ASSERT(ctx->window <= SCTEST1_RMAX); ctx->rmax = ctx->window; int sent = 0, slots = 0, backp = 0, snderr = 0; for (rno=0; rno < (int)ctx->rmax && (ctx->sendmore || (!ctx->sendmore && ctx->sendone)) && rwmsg_clichan_can_send_howmuch(ctx->cc, ctx->dt, ctx->sig->methno, ctx->sig->payt); rno++) { RW_ASSERT(rno <= SCTEST1_RMAX); if (!ctx->r[rno]) { slots++; ctx->r[rno] = rwmsg_request_create(ctx->cc); ASSERT_TRUE(ctx->r[rno] != NULL); rwmsg_request_set_signature(ctx->r[rno], ctx->sig); rwmsg_closure_t clicb; clicb.request=sctest1_clicb1; clicb.ud=ctx; rwmsg_request_set_callback(ctx->r[rno], &clicb); memset(ctx->paybuf, 0, sizeof(struct sctest1_payload)); ctx->paybuf->rno = rno; sprintf(ctx->paybuf->str, "hi there rno=%d", rno); rwmsg_request_set_payload(ctx->r[rno], ctx->paybuf, MAX(ctx->paysz, sizeof(struct sctest1_payload))); /* Send it. */ ck_pr_inc_32(&ctx->in); rw_status_t rs = rwmsg_clichan_send(ctx->cc, ctx->dt, ctx->r[rno]); if (rs == RW_STATUS_SUCCESS) { if (!ctx->sendmsg_firstburst_done) { //RW_ASSERT(!ctx->flowid); ctx->sendmsg_preflow++; } SCTEST1_RNO_ENQ(ctx, rno); sent++; } else { ctx->sendmsg_firstburst_done = TRUE; if (rs == RW_STATUS_BACKPRESSURE) { backp++; if (ctx->verbose) { fprintf(stderr, "lottakickoff _send rno=%u backpressure\n", rno); } ck_pr_dec_32(&ctx->in); rwmsg_request_release(ctx->r[rno]); ctx->r[rno] = NULL; if (!ctx->ccwaiting) { ctx->ccwaiting = TRUE; if (ctx->verbose) { fprintf(stderr, "lottakickoff backpressure ccwaiting=%d\n", ctx->ccwaiting); } } goto out; } else if (rs != RW_STATUS_SUCCESS) { snderr++; ck_pr_dec_32(&ctx->in); rwmsg_request_release(ctx->r[rno]); ctx->r[rno] = NULL; ctx->sendmore = FALSE; fprintf(stderr, "sctest1_clicb1: rwmsg_clichan_send() rs=%u\n", rs); } else { if (ctx->verbose) { fprintf(stderr, "sctest1_clicb1 _send rno=%u sent, ccwaiting now 0\n", rno); } ctx->ccwaiting = FALSE; if (0 && ctx->in >= 5) { fprintf(stderr, "lottakickoff sendmore=FALSE hack\n"); ctx->sendmore = FALSE; } } } } } out: if (ctx->verbose) { fprintf(stderr, "lottakickoff slots=%d sent=%d backp=%d snderr=%d sendmore=%d\n", slots, sent, backp, snderr, ctx->sendmore); } ctx->kickct++; } static void sctest1_clicb02(rwmsg_request_t *req, void *ctx_in); static void sctest1_reqsend(void *ctx_in) { RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; rwmsg_request_t *req; #if 0 static unsigned long long tids[100] = {0}; static int l_tid=0; int i; unsigned long long tid = GETTID(); for (i=0; i<l_tid;i++) { if (tids[i] == tid) break; } if (i>=l_tid) { // fprintf(stderr, "sctest1_clicb02: Thread 0x%llx cc=%p\n", tid, ctx->cc); tids[l_tid] = tid; l_tid++; } #endif req = rwmsg_request_create(ctx->cc); ASSERT_TRUE(req != NULL); rwmsg_request_set_signature(req, ctx->sig); rwmsg_closure_t clicb; clicb.request=sctest1_clicb02; clicb.ud=ctx; rwmsg_request_set_callback(req, &clicb); memset(ctx->paybuf, 0, sizeof(struct sctest1_payload)); ctx->paybuf->rno = 0; sprintf(ctx->paybuf->str, "hi there rno=%d", 0); rwmsg_request_set_payload(req, ctx->paybuf, MAX(ctx->paysz, sizeof(struct sctest1_payload))); /* Send it. The srvchan should more or less immediately run the thing and the methcb will respond. */ ck_pr_inc_32(&ctx->in); rw_status_t rs = rwmsg_clichan_send(ctx->cc, ctx->dt, req); if (rs == RW_STATUS_BACKPRESSURE) { // && ctx->flowexercise) if (ctx->verbose) { fprintf(stderr, "sctest1_clicb02 _send rno=%u backpressure\n", 0); } ck_pr_dec_32(&ctx->in); rwmsg_request_release(req); req = NULL; ctx->ccwaiting = TRUE; /* backpressure will trigger feedme callback */ } else if (rs != RW_STATUS_SUCCESS) { ck_pr_dec_32(&ctx->in); rwmsg_request_release(req); req = NULL; ctx->sendmore = FALSE; fprintf(stderr, "sctest1_clicb02: rwmsg_clichan_send() rs=%u\n", rs); } } static void sctest1_clicb02(rwmsg_request_t *req, void *ctx_in) { RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; if (ctx->sc_tid) { if (!ctx->cc_tid) { ctx->cc_tid = GETTID(); if (ctx->checktid) { EXPECT_EQ(ctx->cc_tid, ctx->sc_tid); } } else if (ctx->checktid) { uint64_t curtid = GETTID(); EXPECT_EQ(ctx->cc_tid, curtid); ctx->cc_tid = curtid; } } /* clichan request callback */ uint32_t len=0; const struct sctest1_payload *rsp = (const struct sctest1_payload*)rwmsg_request_get_response_payload(req, &len); uint64_t rtt = rwmsg_request_get_response_rtt(req); if (rtt > 0) { if (rtt < ctx->min_rtt) { ctx->min_rtt = rtt; } if (rtt > ctx->max_rtt) { ctx->max_rtt = rtt; } } if (rsp) { ck_pr_inc_32(&ctx->rspout); if (ctx->verbose) { fprintf(stderr, "sctest1_clicb02: got rsp len=%d rno=%u str='%s'\n", len, rsp->rno, rsp->str); } int ticks = (RUNNING_ON_VALGRIND ? 100 : 10000); if (ctx->rspout < 1000) { ticks = 100; } if (ctx->rspout % ticks == 0) { fprintf(stderr, "_"); } RW_ASSERT(rsp->rno < ctx->rmax); //rno = rsp->rno; } else { ck_pr_inc_32(&ctx->bncout); if (!ctx->sendmore) { goto checkend; } return; } /* If the test has the repeat flag set, reissue another request */ if (ctx->sendmore) { RW_ASSERT(ctx->cc); sctest1_reqsend(ctx_in); } else { checkend: if ((ctx->bncout + ctx->rspout) == ctx->in) { ctx->done = TRUE; } } } static void lottakickoff02(void *ctx_in) { /* Send the actual request(s). The rsp callback will repeat them as they are answered (ctx->repeat) */ RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; int rno=0; RW_ASSERT(ctx->window <= SCTEST1_RMAX); ctx->rmax = ctx->window; int sent = 0, slots = 0, backp = 0, snderr = 0; for (rno=0; rno < (int)ctx->rmax && (ctx->sendmore || (!ctx->sendmore && ctx->sendone)); rno++) { RW_ASSERT(rno <= SCTEST1_RMAX); sctest1_reqsend(ctx_in); } if (ctx->verbose) { fprintf(stderr, "lottakickoff02 slots=%d sent=%d backp=%d snderr=%d sendmore=%d\n", slots, sent, backp, snderr, ctx->sendmore); } ctx->kickct++; } static void sctest1_refill_bucket(struct sctest1_context *ctx) { #define TOKVAL (VERBOSE() ? 4 : (RUNNING_ON_VALGRIND ? 25 : 100) ) ctx->tokenbucket = TOKVAL; ck_pr_inc_32(&ctx->tokenfill_ct); } static void sctest1_timer(void *ctx_in) { RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; sctest1_refill_bucket(ctx); rwmsg_srvchan_resume(ctx->sc); } struct sctest1_worker_handle { rwmsg_request_t *req; struct sctest1_context *ctx; }; static void sctest1_methcb1_worker_f(void *ud) { struct sctest1_worker_handle *han = (struct sctest1_worker_handle *)ud; rwmsg_request_t *req = han->req; struct sctest1_context *ctx = han->ctx; if (!ctx->opts->bncall) { uint32_t paylen=0; const struct sctest1_payload *pay = (const struct sctest1_payload*)rwmsg_request_get_request_payload(req, &paylen); if (pay) { if (ctx->verbose) { fprintf(stderr, "sctest1_methcb1 got msg in=%u paylen=%u rno=%u str='%s' ctx->in=%u ctx->out=%u\n", ctx->in, paylen, pay->rno, pay->str, ctx->in, ctx->out); } static uint32_t outct = 0; struct sctest1_payload payout; memset(&payout, 0, sizeof(payout)); outct++; payout.rno = pay->rno; sprintf(payout.str, "response payload number %u to input msg '%s'", outct, pay ? pay->str : ""); rw_status_t rs = rwmsg_request_send_response(req, &payout, sizeof(payout)); ASSERT_EQ(rs, RW_STATUS_SUCCESS); ck_pr_inc_32(&ctx->rspin); } else { rw_status_t rs = rwmsg_request_send_response(req, NULL, 0); ASSERT_EQ(rs, RW_STATUS_SUCCESS); ck_pr_inc_32(&ctx->rspin); } int ticks = (RUNNING_ON_VALGRIND ? 100 : 10000); if (ctx->rspin < 1000) { ticks = 100; } if (ctx->rspin % ticks == 0) { fprintf(stderr, "+"); } if (ctx->flowexercise) { ASSERT_TRUE(ctx->tokenbucket > 0); if (--ctx->tokenbucket <= 0) { rwmsg_srvchan_pause(ctx->sc); if (ctx->verbose) { fprintf(stderr, "sctest1_methcb1 drained bucket, invoking srvchan_pause\n"); } } } } free(han); } static void sctest1_methcb1(rwmsg_request_t *req, void *ctx_in) { static int once=0; RW_ASSERT(!once); once=1; RW_ASSERT_TYPE(ctx_in, sctest1_context); struct sctest1_context *ctx = (struct sctest1_context*)ctx_in; if (ctx->flowexercise) { if (ctx->tokenbucket == 0) { ASSERT_TRUE(ctx->sc->ch.paused_user); } ASSERT_TRUE(ctx->tokenbucket > 0); } /* srvchan method callback */ if (!ctx->sc_tid) { ctx->sc_tid = GETTID(); } else if (ctx->checktid) { uint64_t curtid = GETTID(); EXPECT_EQ(ctx->sc_tid, curtid); ctx->sc_tid = curtid; } ck_pr_inc_32(&ctx->out); struct sctest1_worker_handle *han = (struct sctest1_worker_handle*)malloc(sizeof(*han)); han->req = req; han->ctx = ctx; if (ctx->opts->srvrspfromanyq) { rwsched_dispatch_queue_t q = rwsched_dispatch_get_global_queue(ctx->tenv->tasklet[0], DISPATCH_QUEUE_PRIORITY_DEFAULT); RW_ASSERT(q); RW_ASSERT_TYPE(q, rwsched_dispatch_queue_t); rwsched_dispatch_async_f(ctx->tenv->tasklet[0], q, han, sctest1_methcb1_worker_f); } else { sctest1_methcb1_worker_f(han); } ck_pr_barrier(); RW_ASSERT(once); once=0; } static void lottaraw(int squat, int mainq, int fixedrateserver, int window, int usebro, int broflo, struct lottaopts *opts, struct lottarawvals *valsout) { uint32_t start_reqct = rwmsg_global.status.request_ct; VERBPRN("begin rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct); rwmsg_btenv_t tenv(2); // test env, on stack, dtor cleans up ASSERT_TRUE(tenv.rwsched != NULL); if (valsout) { memset(valsout, 0, sizeof(*valsout)); } if (RUNNING_ON_VALGRIND) { window /= 10; window = MAX(1, window); } rwmsg_broker_t *bro=NULL; tenv.ti->rwsched_tasklet_info = tenv.tasklet[1]; rwmsg_broker_main(broport_g, 1, 0, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, mainq, tenv.ti, &bro); if (broflo) { bro->thresh_reqct2 = 10; bro->thresh_reqct1 = 5; } if (opts->bigbrosrvwin) { /* set the broker's srvchan window value really high, to cause overrun of writes to srvchan socket */ rwmsg_endpoint_set_property_int(bro->ep, "/rwmsg/broker/srvchan/window", (RUNNING_ON_VALGRIND ? 1000 : 1000000)); } rwmsg_endpoint_t *ep; ep = rwmsg_endpoint_create(1, 1, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL); ASSERT_TRUE(ep != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep, "/rwmsg/broker/shunt", usebro); if (opts->bigdefwin) { rwmsg_endpoint_set_property_int(ep, "/rwmsg/destination/defwin", opts->bigdefwin); } rw_status_t rs; struct sctest1_context *ctx = RW_MALLOC0_TYPE(sizeof(*ctx), sctest1_context); ctx->usebro = usebro; ctx->window = window; ctx->tenv = &tenv; ctx->paysz = sizeof(sctest1_payload); if (opts) { ctx->paysz = opts->paysz; } ctx->paybuf = RW_MALLOC0_TYPE(MAX(sizeof(struct sctest1_payload), ctx->paysz), sctest1_payload); ctx->verbose = VERBOSE(); RW_ASSERT(opts); ctx->opts = opts; ctx->min_rtt = MAX_RTT; ctx->checktid=0; // check thread id is same every time; adds a syscall per msg on each side if (ctx->checktid) { fprintf(stderr, "warning: checktid enabled\n"); } const char *taddrpfx = "/L/GTEST/RWBRO/TESTAPP/6"; char taddr[999]; sprintf(taddr, "%s/%u", taddrpfx, rand()); const uint32_t methno = __LINE__; /* Create the srvchan, bind a method */ ctx->sc = rwmsg_srvchan_create(ep); ASSERT_TRUE(ctx->sc != NULL); rwmsg_signature_t *sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig); int timeo = 1000; // ms if (opts->reqtimeo) { timeo = opts->reqtimeo; } if (RUNNING_ON_VALGRIND) { timeo = timeo * 5; } rwmsg_signature_set_timeout(sig, timeo); ctx->sig = sig; rwmsg_closure_t methcb; methcb.request=sctest1_methcb1; methcb.ud=ctx; rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &methcb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(ctx->sc, meth); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Wait on binding the srvchan until after we've sent the initial flurry of requests. Otherwise, our ++ and the request handler's ++ of some of the request count variables ABA-stomp each other. */ /* Create the clichan, add the method's signature */ rwmsg_destination_t *dt = rwmsg_destination_create(ep, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); ctx->dt = dt; if (squat!=2 || ctx->flowexercise) { rwmsg_closure_t cb = { }; cb.ud = ctx; cb.feedme = sctest1_clicb_feedme; rwmsg_destination_feedme_callback(dt, &cb); } rwmsg_clichan_t *cc = rwmsg_clichan_create(ep); ctx->cc = cc; ASSERT_TRUE(cc != NULL); //TBD/optional rwmsg_clichan_add_signature(cc, sig); /* Bind to a serial queue */ if (mainq) { ctx->rwq[0] = rwsched_dispatch_get_main_queue(tenv.rwsched); ctx->rwq[1] = rwsched_dispatch_get_main_queue(tenv.rwsched); } else { ctx->rwq[0] = rwsched_dispatch_queue_create(tenv.tasklet[0], "ctx->rwq[0] (cc)", DISPATCH_QUEUE_SERIAL); ctx->rwq[1] = rwsched_dispatch_queue_create(tenv.tasklet[1], "ctx->rwq[1] (sc)", DISPATCH_QUEUE_SERIAL); } rs = rwmsg_clichan_bind_rwsched_queue(cc, ctx->rwq[0]); if (window == 1) { ctx->sendmore = FALSE; ctx->sendone = TRUE; } else { ctx->sendmore = TRUE; } /* Now bind the srvchan; at this point the srvchan will start chewing in another thread. */ rs = rwmsg_srvchan_bind_rwsched_queue(ctx->sc, ctx->rwq[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Setup the srvchan to run at a fixed rate of 4 or 100 req/s, to exercise backpressure etc. */ ctx->flowexercise = fixedrateserver; /* Fake pump the main queue for 1s to get connected, registered, etc */ int setupsec = 1; if (RUNNING_ON_VALGRIND) { setupsec = setupsec * 5 / 2; } rwsched_dispatch_main_until(tenv.tasklet[0], setupsec, NULL); if (!squat) { if (ctx->flowexercise) { sctest1_refill_bucket(ctx); ctx->sc_timer = rwsched_dispatch_source_create(tenv.tasklet[1], RWSCHED_DISPATCH_SOURCE_TYPE_TIMER, 0, 0, ctx->rwq[1]); rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1], ctx->sc_timer, sctest1_timer); rwsched_dispatch_set_context(tenv.tasklet[1], ctx->sc_timer, ctx); uint64_t ms1000 = 1*NSEC_PER_SEC/1; rwsched_dispatch_source_set_timer(tenv.tasklet[1], ctx->sc_timer, dispatch_time(DISPATCH_TIME_NOW, ms1000), ms1000, 0); rwsched_dispatch_resume(tenv.tasklet[1], ctx->sc_timer); } if (RUNNING_ON_VALGRIND) { /* Pump the main queue briefly to get everyone up and running before sending */ rwsched_dispatch_main_until(tenv.tasklet[0], 1, NULL); } //lottakickoff(ctx); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff); int sec_start = time(NULL); double sec = 5; if (RUNNING_ON_VALGRIND) { sec = sec * 5 / 2 ; } /* Run the main queue for 5s or longer under valgrind */ #if 1 for(int i=0; !ctx->done && i<100; i++) { rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL); } #else rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL); #endif VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout); ctx->sendmore = FALSE; ck_pr_barrier(); uint32_t endct_in = ctx->in; uint32_t endct_rspin = ctx->rspin; uint32_t endct_rspout = ctx->rspout; uint32_t endct_bncout = ctx->bncout; int iter=0; VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); do { /* Fake pump the main queue until done */ rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done); iter++; VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout); if (iter > 6) { fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout); } if (!RUNNING_ON_VALGRIND) { ASSERT_LE(iter, 6); } ck_pr_barrier(); } while (!ctx->done); ck_pr_barrier(); VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); if (!ctx->bncout) { ASSERT_EQ(ctx->rspout, ctx->in); ASSERT_EQ(ctx->out, ctx->in); ASSERT_EQ(ctx->rspout, ctx->rspin); ASSERT_EQ(ctx->out, ctx->rspout); if (!ctx->opts->srvrspfromanyq) { ASSERT_FALSE(ctx->misorderct); } } else { /* Note that we can get bounces plus some might have been answered even as they bounced on our end. */ ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client ASSERT_GE(ctx->out + ctx->bncout, ctx->in); ASSERT_LE(ctx->rspout, ctx->rspin); ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout); } int rno; for (rno=0; rno < SCTEST1_RMAX; rno++) { ASSERT_TRUE(ctx->r[rno] == NULL); } valsout->sec = time(NULL) - sec_start; //sec; valsout->flushtime = iter*100; valsout->rmax = ctx->rmax; valsout->reqsent = endct_in; valsout->reqans = endct_rspin; valsout->reqdone = endct_rspout; valsout->reqbnc = endct_bncout; valsout->reqbnc_final = ctx->bncout; valsout->reqhz = (endct_rspout / sec / 10); valsout->reqhz *= 10; valsout->min_rtt = ctx->min_rtt; valsout->max_rtt = ctx->max_rtt; valsout->firstburst = ctx->sendmsg_preflow; /* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */ if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) { ASSERT_GE(valsout->reqhz, TOKVAL); } if (ctx->flowexercise && ctx->sc_timer) { /* Fake pump the main queue for 1s, allow lingering async_f and timer calls to flush out */ rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer); RW_ASSERT(bro); rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]); ctx->sc_timer = NULL; // rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL); } } else if (squat == 2) { /* For *ConcurQ* tests */ rwsched_dispatch_queue_t cuncurQ = rwsched_dispatch_get_global_queue(tenv.tasklet[0], DISPATCH_QUEUE_PRIORITY_DEFAULT); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); int sec_start = time(NULL); double sec = 5; if (RUNNING_ON_VALGRIND) { sec = sec * 5 / 2 ; } /* Run the main queue for 5s or longer under valgrind */ #if 1 for(int i=0; !ctx->done && i<100; i++) { rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL); } #else rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL); #endif VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout); ctx->sendmore = FALSE; ck_pr_barrier(); uint32_t endct_in = ctx->in; uint32_t endct_rspin = ctx->rspin; uint32_t endct_rspout = ctx->rspout; uint32_t endct_bncout = ctx->bncout; int iter=0; VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); do { /* Fake pump the main queue until done */ rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done); iter++; VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout); if (iter > 6) { fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout); } if (!RUNNING_ON_VALGRIND) { ASSERT_LE(iter, 6); } ck_pr_barrier(); } while (!ctx->done); ck_pr_barrier(); VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); if (!ctx->bncout) { ASSERT_EQ(ctx->rspout, ctx->in); ASSERT_EQ(ctx->out, ctx->in); ASSERT_EQ(ctx->rspout, ctx->rspin); ASSERT_EQ(ctx->out, ctx->rspout); if (!ctx->opts->srvrspfromanyq) { ASSERT_FALSE(ctx->misorderct); } } else { /* Note that we can get bounces plus some might have been answered even as they bounced on our end. */ ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client ASSERT_GE(ctx->out + ctx->bncout, ctx->in); ASSERT_LE(ctx->rspout, ctx->rspin); ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout); } int rno; for (rno=0; rno < SCTEST1_RMAX; rno++) { ASSERT_TRUE(ctx->r[rno] == NULL); } valsout->sec = time(NULL) - sec_start; //sec; valsout->flushtime = iter*100; valsout->rmax = ctx->rmax; valsout->reqsent = endct_in; valsout->reqans = endct_rspin; valsout->reqdone = endct_rspout; valsout->reqbnc = endct_bncout; valsout->reqbnc_final = ctx->bncout; valsout->reqhz = (endct_rspout / sec / 10); valsout->reqhz *= 10; valsout->firstburst = ctx->sendmsg_preflow; valsout->min_rtt = ctx->min_rtt; valsout->max_rtt = ctx->max_rtt; /* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */ if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) { ASSERT_EQ(valsout->reqhz, TOKVAL); } if (ctx->flowexercise && ctx->sc_timer) { /* Fake pump the main queue for 1s, allow lingering async_f and timer calls to flush out */ rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer); RW_ASSERT(bro); rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]); ctx->sc_timer = NULL; // rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL); } } else { VERBPRN("\n***Squat!***\n"); } //sleep(2); rwmsg_bool_t r; rwmsg_signature_release(ep, sig); rwmsg_method_release(ep, meth); rwmsg_srvchan_halt(ctx->sc); rwmsg_clichan_halt(ctx->cc); rwmsg_destination_release(dt); if (!mainq) { rwsched_dispatch_release(tenv.tasklet[0], ctx->rwq[0]); rwsched_dispatch_release(tenv.tasklet[1], ctx->rwq[1]); } r = rwmsg_endpoint_halt_flush(ep, TRUE); ASSERT_TRUE(r); if (bro) { r = rwmsg_broker_halt_sync(bro); ASSERT_TRUE(r); } RW_FREE_TYPE(ctx->paybuf, sctest1_payload); RW_FREE_TYPE(ctx, sctest1_context); rwmsg_global_status_t gs; rwmsg_global_status_get(&gs); if (!gs.endpoint_ct) { ASSERT_EQ(gs.qent, 0); } nnchk(); if (rwmsg_global.status.request_ct != start_reqct) { fprintf(stderr, "***start_reqct=%u ending rwmsg_global.status.request_ct=%u\n", start_reqct, rwmsg_global.status.request_ct); } VERBPRN("end rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct); VERBPRN("end rwmsg_global.status.qent=%u\n", rwmsg_global.status.qent); } #define PRINT_REPORT(txt) \ fprintf(stderr, \ "\n" txt " at %lds sent=%lu answered=%lu done=%lu bnc=%lu bnc_final=%lu => %lu req/s\n" \ " min_rtt=%lu max_rtt=%lu usec\n",\ vals.sec,\ vals.reqsent,\ vals.reqans,\ vals.reqdone,\ vals.reqbnc,\ vals.reqbnc_final, \ vals.reqhz, \ (vals.min_rtt==MAX_RTT?0:vals.min_rtt), \ vals.max_rtt); TEST(RWMsgBroker, LottaRawRWSConcurQ) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues"); RWUT_BENCH_ITER(LottaRawRWSConcurQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = TRUE; int broflo = FALSE; lottaraw(2, false, false, burst, broker, broflo, &opts, &vals); /* For *ConcurQ* tests */ #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSConcurQ"); nnchk(); RWUT_BENCH_END(LottaRawRWSConcurQBench); } static void lottaraw(int squat, int mainq, int fixedrateserver, int window, int usebro, int broflo, struct lottaopts *opts, struct lottarawvals *valsout); static void lottaraw2bros(int squat, int mainq, int fixedrateserver, int window, int broflo, struct lottaopts *opts, struct lottarawvals *valsout); TEST(RWMsgBroker, LottaRawRWMeasureRTT) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues"); RWUT_BENCH_ITER(LottaRawRWMeasureRTT, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); lottaraw(false, true, false, 2, FALSE, FALSE, &opts, &vals); /* No Broker tests MainQ*/ PRINT_REPORT("RWMsgBroker.MeasureRTT.NoBroker.MainQ"); ASSERT_LT(vals.max_rtt, 300*1000); lottaraw(false, false, false, 2, FALSE, FALSE, &opts, &vals); /* No Broker tests */ PRINT_REPORT("RWMsgBroker.MeasureRTT.NoBroker"); ASSERT_LT(vals.max_rtt, 300*1000); fprintf(stderr, "\n"); lottaraw(false, true, false, 2, TRUE, FALSE, &opts, &vals); /* With Broker tests MainQ */ PRINT_REPORT("RWMsgBroker.MeasureRTT.WithBroker.MainQ"); ASSERT_LT(vals.max_rtt, 500*1000); lottaraw(false, false, false, 2, TRUE, FALSE, &opts, &vals); /* With Broker tests */ PRINT_REPORT("RWMsgBroker.MeasureRTT.WithBroker.ConcurQ"); ASSERT_LT(vals.max_rtt, 500*1000); fprintf(stderr, "\n"); lottaraw2bros(false, true, false, 2, FALSE, &opts, &vals); /* For *MainQ* tests */ PRINT_REPORT("RWMsgBroker.MeasureRTT.With2Brokers.MainQ"); ASSERT_LT(vals.max_rtt, 500*1000); fprintf(stderr, "\n"); lottaraw2bros(false, false, false, 2, FALSE, &opts, &vals); /* For *ConcurQ* tests */ PRINT_REPORT("RWMsgBroker.MeasureRTT.With2Brokers.ConcurQ"); ASSERT_LT(vals.max_rtt, 500*1000); fprintf(stderr, "\n"); nnchk(); RWUT_BENCH_END(LottaRawRWMeasureRTT); } TEST(RWMsgBroker, LottaRawRWSSerQ) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues"); RWUT_BENCH_ITER(LottaRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = TRUE; int broflo = FALSE; lottaraw(false, false, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSSerQ"); nnchk(); RWUT_BENCH_END(LottaRawRWSSerQBench); } TEST(RWMsgBroker, LottaRawRWSSerQRspManyQ) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues, srvchan answering from all default rwqueues"); RWUT_BENCH_ITER(LottaRawRWSSerQRspManyQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.srvrspfromanyq = TRUE; int burst = 100; int broker = TRUE; int broflo = FALSE; lottaraw(false, false, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSSerQRspManyQ"); nnchk(); RWUT_BENCH_END(LottaRawRWSSerQRspManyQBench); } #if 0 TEST(RWMsgBroker, LottaBrofloRawRWSSerQ) { TEST_DESCRIPTION("Tests in-broker flow control under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues"); RWUT_BENCH_ITER(LottaBrofloRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = TRUE; int broflo = TRUE; lottaraw(false, false, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif fprintf(stderr, "\nRWMsgBroker.LottabrofloRawRWSSerQ at %lds sent=%lu answered=%lu done=%lu bnc=%lu => %lu req/s\n", vals.sec, vals.reqsent, vals.reqans, vals.reqdone, vals.reqbnc, vals.reqhz); nnchk(); RWUT_BENCH_END(LottaBrofloRawRWSSerQBench); } #endif TEST(RWMsgBrokerNot, LottaRawRWSConcurQ) { TEST_DESCRIPTION("Tests inprocess under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues"); RWUT_BENCH_ITER(NobroLottaRawRWSConcurQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = FALSE; int broflo = FALSE; lottaraw(2, false, false, burst, broker, broflo, &opts, &vals); /* For *ConcurQ* tests */ #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBrokerNot.LottaRawRWSConcurQ"); nnchk(); RWUT_BENCH_END(NobroLottaRawRWSConcurQBench) } TEST(RWMsgBrokerNot, LottaRawRWSSerQ) { TEST_DESCRIPTION("Tests inprocess under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues"); RWUT_BENCH_ITER(NobroLottaRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = FALSE; int broflo = FALSE; lottaraw(false, false, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBrokerNot.LottaRawRWSSerQ"); nnchk(); RWUT_BENCH_END(NobroLottaRawRWSSerQBench) } TEST(RWMsgBrokerNot, LottaRawRWSMainQ) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(NobroLottaRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = FALSE; int broflo = FALSE; int squat = FALSE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBrokerNot.LottaRawRWSMainQ"); nnchk(); RWUT_BENCH_END(NobroLottaRawRWSMainQBench); } TEST(RWMsgBroker, LottaRawRWSBigdefwinMainQ) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaRawRWSBigdefwinMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.bigdefwin = 100; int burst = 100; int broker = TRUE; int broflo = FALSE; int squat = FALSE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSBigdefwinMainQ"); nnchk(); RWUT_BENCH_END(LottaRawRWSBigdefwinMainQBench); } TEST(RWMsgBroker, LottaRawRWSMainQ) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = TRUE; int broflo = FALSE; int squat = FALSE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSMainQ"); nnchk(); RWUT_BENCH_END(LottaRawRWSMainQBench); } TEST(RWMsgBroker, LottaRawBncRWSMainQ) { TEST_DESCRIPTION("Exercise broker timeout bounce code path."); RWUT_BENCH_ITER(LottaRawBncRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 1; int broker = TRUE; int broflo = FALSE; int squat = FALSE; opts.reqtimeo = 50;/*ms*/ opts.bncall = TRUE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawBncRWSMainQ"); nnchk(); RWUT_BENCH_END(LottaRawBncRWSMainQBench); } TEST(RWMsgBroker, Big0512RawRWSMainQ) { TEST_DESCRIPTION("Tests broker with big 512KB requests, RWSched Main Queue"); RWUT_BENCH_ITER(Big0512RawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.paysz = 512000; int burst = 10; int broker = TRUE; int broflo = FALSE; int squat = FALSE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.Big0512RawRWSMainQ"); nnchk(); RWUT_BENCH_END(Big0512RawRWSMainQBench); } TEST(RWMsgBroker, Big5120RawRWSMainQ) { TEST_DESCRIPTION("Tests broker with big 5MB requests, RWSched Main Queue"); RWUT_BENCH_ITER(Big5120RawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.paysz = 5120000; int burst = 10; int broker = TRUE; int broflo = FALSE; int squat = FALSE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.Big5120RawRWSMainQ"); nnchk(); RWUT_BENCH_END(Big5120RawRWSMainQBench); } TEST(RWMsgBrokerNot, Big0512RawRWSMainQ) { TEST_DESCRIPTION("Tests with big 512KB requests, RWSched Main Queue"); RWUT_BENCH_ITER(Big0512RawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.paysz = 512000; int burst = 10; int broker = FALSE; int broflo = FALSE; int squat = FALSE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBrokerNot.Big0512RawRWSMainQ"); nnchk(); RWUT_BENCH_END(Big0512RawRWSMainQBench); } TEST(RWMsgBrokerNot, Big5120RawRWSMainQ) { TEST_DESCRIPTION("Tests with big 5MB requests, RWSched Main Queue"); RWUT_BENCH_ITER(Big5120RawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.paysz = 5120000; int burst = 10; int broker = FALSE; int broflo = FALSE; int squat = FALSE; lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBrokerNot.Big5120RawRWSMainQ"); nnchk(); RWUT_BENCH_END(Big5120RawRWSMainQBench); } TEST(RWMsgBroker, LottaPauseRawRWSSerQ) { TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Serial Queue"); RWUT_BENCH_ITER(LottaPauseRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; burst=burst; int broker = TRUE; int broflo = FALSE; lottaraw(false, false/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSSerQ"); nnchk(); RWUT_BENCH_END(LottaPauseRawRWSSerQBench); } TEST(RWMsgBroker, LottaPauseBigwinRawRWSSerQ) { TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Serial Queue"); RWUT_BENCH_ITER(LottaPauseBigwinRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = SCTEST1_RMAX; burst=burst; int broker = TRUE; int broflo = FALSE; opts.bigbrosrvwin = TRUE; lottaraw(false, false/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSSerQ"); nnchk(); RWUT_BENCH_END(LottaPauseBigwinRawRWSSerQBench); } TEST(RWMsgBrokerNot, LottaPauseRawRWSSerQ) { TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Serial Queue"); RWUT_BENCH_ITER(NobroLottaPauseRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; burst=burst; int broker = FALSE; int broflo = FALSE; lottaraw(false, false/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBrokerNot.LottaPauseRawRWSSerQ"); nnchk(); RWUT_BENCH_END(NobroLottaPauseRawRWSSerQBench); } TEST(RWMsgBroker, LottaPauseRawRWSMainQ) { TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaPauseRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = TRUE; int broflo = FALSE; lottaraw(false, true/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSMainQ"); nnchk(); RWUT_BENCH_END(LottaPauseRawRWSMainQBench); } TEST(RWMsgBroker, LottaPauseBigwinRawRWSMainQ) { TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaPauseBigwinRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = SCTEST1_RMAX; int broker = TRUE; int broflo = FALSE; opts.bigbrosrvwin = TRUE; lottaraw(false, true/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSMainQ"); nnchk(); RWUT_BENCH_END(LottaPauseBigwinRawRWSMainQBench); } TEST(RWMsgBrokerNot, LottaPauseRawRWSMainQ) { TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(NobroLottaPauseRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broker = FALSE; int broflo = FALSE; lottaraw(false, true/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBrokerNot.LottaPauseRawRWSMainQ"); nnchk(); RWUT_BENCH_END(NobroLottaPauseRawRWSMainQBench); } static void lottaraw2bros(int squat, int mainq, int fixedrateserver, int window, int broflo, struct lottaopts *opts, struct lottarawvals *valsout) { uint32_t start_reqct = rwmsg_global.status.request_ct; VERBPRN("begin rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct); if (valsout) { memset(valsout, 0, sizeof(*valsout)); } if (RUNNING_ON_VALGRIND) { window /= 10; window = MAX(1, window); } const unsigned broker_c = 2; rwmsg_btenv_t tenv(2+(broker_c?broker_c:1)); // test env, on stack, dtor cleans up ASSERT_TRUE(tenv.rwsched != NULL); rwmsg_broker_t *bros[broker_c]; rwmsg_broker_t *bro=NULL; memset(bros, 0, sizeof(bros)); if (broker_c) { for (unsigned i=0; i<broker_c; i++) { tenv.ti->rwsched_tasklet_info = tenv.tasklet[2-(broker_c-i)]; rwmsg_broker_main(broport_g, 2-(broker_c-i), i, tenv.rwsched, tenv.tasklet[2-(broker_c-i)], tenv.rwcal, mainq, tenv.ti, &bros[i]); bro = bros[i]; } } rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE); if (broflo) { bro->thresh_reqct2 = 10; bro->thresh_reqct1 = 5; } if (opts->bigbrosrvwin) { /* set the broker's srvchan window value really high, to cause overrun of writes to srvchan socket */ rwmsg_endpoint_set_property_int(bro->ep, "/rwmsg/broker/srvchan/window", (RUNNING_ON_VALGRIND ? 1000 : 1000000)); } rw_status_t rs; struct sctest1_context *ctx = RW_MALLOC0_TYPE(sizeof(*ctx), sctest1_context); ctx->usebro = TRUE; ctx->window = window; ctx->tenv = &tenv; ctx->paysz = sizeof(sctest1_payload); if (opts) { ctx->paysz = opts->paysz; } ctx->paybuf = RW_MALLOC0_TYPE(MAX(sizeof(struct sctest1_payload), ctx->paysz), sctest1_payload); ctx->verbose = VERBOSE(); RW_ASSERT(opts); ctx->opts = opts; ctx->min_rtt = MAX_RTT; ctx->checktid=0; // check thread id is same every time; adds a syscall per msg on each side if (ctx->checktid) { fprintf(stderr, "warning: checktid enabled\n"); } const char *taddrpfx = "/L/GTEST/RWBRO/TESTAPP/6"; char taddr[999]; sprintf(taddr, "%s/%u", taddrpfx, rand()); const uint32_t methno = __LINE__; /* Create the srvchan, bind a method */ rwmsg_endpoint_t *ep_s; ep_s = rwmsg_endpoint_create(1, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL); ASSERT_TRUE(ep_s != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1); if (opts->bigdefwin) { rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/destination/defwin", opts->bigdefwin); } ctx->sc = rwmsg_srvchan_create(ep_s); ASSERT_TRUE(ctx->sc != NULL); rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT); ASSERT_TRUE(sig); int timeo = 1000; // ms if (opts->reqtimeo) { timeo = opts->reqtimeo; } if (RUNNING_ON_VALGRIND) { timeo = timeo * 5; } rwmsg_signature_set_timeout(sig, timeo); ctx->sig = sig; rwmsg_closure_t methcb; methcb.request=sctest1_methcb1; methcb.ud=ctx; rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb); ASSERT_TRUE(meth != NULL); rs = rwmsg_srvchan_add_method(ctx->sc, meth); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Wait on binding the srvchan until after we've sent the initial flurry of requests. Otherwise, our ++ and the request handler's ++ of some of the request count variables ABA-stomp each other. */ /* Create the clichan, add the method's signature */ rwmsg_endpoint_t *ep_c; ep_c = rwmsg_endpoint_create(1, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL); ASSERT_TRUE(ep_c != NULL); /* Direct everything through the broker */ rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1); if (opts->bigdefwin) { rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/destination/defwin", opts->bigdefwin); } rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr); ASSERT_TRUE(dt != NULL); ctx->dt = dt; if (squat!=2 || ctx->flowexercise) { rwmsg_closure_t cb = { }; cb.ud = ctx; cb.feedme = sctest1_clicb_feedme; rwmsg_destination_feedme_callback(dt, &cb); } rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c); ctx->cc = cc; ASSERT_TRUE(cc != NULL); //TBD/optional rwmsg_clichan_add_signature(cc, sig); /* Bind to a serial queue */ if (mainq) { ctx->rwq[0] = rwsched_dispatch_get_main_queue(tenv.rwsched); ctx->rwq[1] = rwsched_dispatch_get_main_queue(tenv.rwsched); } else { ctx->rwq[0] = rwsched_dispatch_queue_create(tenv.tasklet[0], "ctx->rwq[0] (cc)", DISPATCH_QUEUE_SERIAL); ctx->rwq[1] = rwsched_dispatch_queue_create(tenv.tasklet[1], "ctx->rwq[1] (sc)", DISPATCH_QUEUE_SERIAL); } rs = rwmsg_clichan_bind_rwsched_queue(cc, ctx->rwq[0]); if (window == 1) { ctx->sendmore = FALSE; ctx->sendone = TRUE; } else { ctx->sendmore = TRUE; } /* Now bind the srvchan; at this point the srvchan will start chewing in another thread. */ rs = rwmsg_srvchan_bind_rwsched_queue(ctx->sc, ctx->rwq[1]); ASSERT_EQ(rs, RW_STATUS_SUCCESS); /* Setup the srvchan to run at a fixed rate of 4 or 100 req/s, to exercise backpressure etc. */ ctx->flowexercise = fixedrateserver; /* Fake pump the main queue for 1s to get connected, registered, etc */ int setupsec = 1; if (RUNNING_ON_VALGRIND) { setupsec = setupsec * 5 / 2; } rwsched_dispatch_main_until(tenv.tasklet[0], setupsec, NULL); if (!squat) { if (ctx->flowexercise) { sctest1_refill_bucket(ctx); ctx->sc_timer = rwsched_dispatch_source_create(tenv.tasklet[1], RWSCHED_DISPATCH_SOURCE_TYPE_TIMER, 0, 0, ctx->rwq[1]); rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1], ctx->sc_timer, sctest1_timer); rwsched_dispatch_set_context(tenv.tasklet[1], ctx->sc_timer, ctx); uint64_t ms1000 = 1*NSEC_PER_SEC/1; rwsched_dispatch_source_set_timer(tenv.tasklet[1], ctx->sc_timer, dispatch_time(DISPATCH_TIME_NOW, ms1000), ms1000, 0); rwsched_dispatch_resume(tenv.tasklet[1], ctx->sc_timer); } if (RUNNING_ON_VALGRIND) { /* Pump the main queue briefly to get everyone up and running before sending */ rwsched_dispatch_main_until(tenv.tasklet[0], 1, NULL); } //lottakickoff(ctx); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff); int sec_start = time(NULL); double sec = 5; if (RUNNING_ON_VALGRIND) { sec = sec * 5 / 2 ; } /* Run the main queue for 5s or longer under valgrind */ #if 1 for(int i=0; !ctx->done && i<100; i++) { rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL); } #else rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL); #endif VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout); ctx->sendmore = FALSE; ck_pr_barrier(); uint32_t endct_in = ctx->in; uint32_t endct_rspin = ctx->rspin; uint32_t endct_rspout = ctx->rspout; uint32_t endct_bncout = ctx->bncout; int iter=0; VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); do { /* Fake pump the main queue until done */ rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done); iter++; VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout); if (iter > 6) { fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout); } if (!RUNNING_ON_VALGRIND) { ASSERT_LE(iter, 6); } ck_pr_barrier(); } while (!ctx->done); ck_pr_barrier(); VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); if (!ctx->bncout) { ASSERT_EQ(ctx->rspout, ctx->in); ASSERT_EQ(ctx->out, ctx->in); ASSERT_EQ(ctx->rspout, ctx->rspin); ASSERT_EQ(ctx->out, ctx->rspout); if (!ctx->opts->srvrspfromanyq) { ASSERT_FALSE(ctx->misorderct); } } else { /* Note that we can get bounces plus some might have been answered even as they bounced on our end. */ ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client ASSERT_GE(ctx->out + ctx->bncout, ctx->in); ASSERT_LE(ctx->rspout, ctx->rspin); ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout); } int rno; for (rno=0; rno < SCTEST1_RMAX; rno++) { ASSERT_TRUE(ctx->r[rno] == NULL); } valsout->sec = time(NULL) - sec_start; //sec; valsout->flushtime = iter*100; valsout->rmax = ctx->rmax; valsout->reqsent = endct_in; valsout->reqans = endct_rspin; valsout->reqdone = endct_rspout; valsout->reqbnc = endct_bncout; valsout->reqbnc_final = ctx->bncout; valsout->reqhz = (endct_rspout / (ctx->tokenfill_ct-1)); valsout->firstburst = ctx->sendmsg_preflow; valsout->min_rtt = ctx->min_rtt; valsout->max_rtt = ctx->max_rtt; /* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */ if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) { ASSERT_LE(valsout->reqhz, TOKVAL); } if (ctx->flowexercise && ctx->sc_timer) { /* Fake pump the main queue for 1s, allow lingering async_f and timer calls to flush out */ rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer); RW_ASSERT(bro); rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]); ctx->sc_timer = NULL; // rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL); } } else if (squat == 2) { /* For *ConcurQ* tests */ rwsched_dispatch_queue_t cuncurQ = rwsched_dispatch_get_global_queue(tenv.tasklet[0], DISPATCH_QUEUE_PRIORITY_DEFAULT); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02); int sec_start = time(NULL); double sec = 5; if (RUNNING_ON_VALGRIND) { sec = sec * 5 / 2 ; } /* Run the main queue for 5s or longer under valgrind */ #if 1 for(int i=0; !ctx->done && i<100; i++) { rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL); } #else rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL); #endif VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout); ctx->sendmore = FALSE; ck_pr_barrier(); uint32_t endct_in = ctx->in; uint32_t endct_rspin = ctx->rspin; uint32_t endct_rspout = ctx->rspout; uint32_t endct_bncout = ctx->bncout; int iter=0; VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); do { /* Fake pump the main queue until done */ rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done); iter++; VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout); if (iter > 6) { fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout); } if (!RUNNING_ON_VALGRIND) { ASSERT_LE(iter, 6); } ck_pr_barrier(); } while (!ctx->done); ck_pr_barrier(); VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout); if (!ctx->bncout) { ASSERT_EQ(ctx->rspout, ctx->in); ASSERT_EQ(ctx->out, ctx->in); ASSERT_EQ(ctx->rspout, ctx->rspin); ASSERT_EQ(ctx->out, ctx->rspout); if (!ctx->opts->srvrspfromanyq) { ASSERT_FALSE(ctx->misorderct); } } else { /* Note that we can get bounces plus some might have been answered even as they bounced on our end. */ ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client ASSERT_GE(ctx->out + ctx->bncout, ctx->in); ASSERT_LE(ctx->rspout, ctx->rspin); ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout); } int rno; for (rno=0; rno < SCTEST1_RMAX; rno++) { ASSERT_TRUE(ctx->r[rno] == NULL); } valsout->sec = time(NULL) - sec_start; //sec; valsout->flushtime = iter*100; valsout->rmax = ctx->rmax; valsout->reqsent = endct_in; valsout->reqans = endct_rspin; valsout->reqdone = endct_rspout; valsout->reqbnc = endct_bncout; valsout->reqbnc_final = ctx->bncout; valsout->reqhz = (endct_rspout / (ctx->tokenfill_ct-1)); valsout->firstburst = ctx->sendmsg_preflow; valsout->min_rtt = ctx->min_rtt; valsout->max_rtt = ctx->max_rtt; /* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */ if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) { ASSERT_EQ(valsout->reqhz, TOKVAL); } if (ctx->flowexercise && ctx->sc_timer) { /* Fake pump the main queue for 1s, allow lingering async_f and timer calls to flush out */ rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer); RW_ASSERT(bro); rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]); ctx->sc_timer = NULL; // rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL); } } else { VERBPRN("\n***Squat!***\n"); } sleep(2); rwmsg_bool_t r; rwmsg_signature_release(ep_s, sig); rwmsg_method_release(ep_s, meth); rwmsg_srvchan_halt(ctx->sc); rwmsg_clichan_halt(ctx->cc); rwmsg_destination_release(dt); if (!mainq) { rwsched_dispatch_release(tenv.tasklet[0], ctx->rwq[0]); rwsched_dispatch_release(tenv.tasklet[0], ctx->rwq[1]); } r = rwmsg_endpoint_halt_flush(ep_c, TRUE); ASSERT_TRUE(r); r = rwmsg_endpoint_halt_flush(ep_s, TRUE); ASSERT_TRUE(r); if (broker_c) { for (unsigned i=0; i<broker_c; i++) { r = rwmsg_broker_halt_sync(bros[i]); ASSERT_TRUE(r); } } RW_FREE_TYPE(ctx->paybuf, sctest1_payload); RW_FREE_TYPE(ctx, sctest1_context); rwmsg_global_status_t gs; rwmsg_global_status_get(&gs); if (!gs.endpoint_ct) { ASSERT_EQ(gs.qent, 0); } nnchk(); if (rwmsg_global.status.request_ct != start_reqct) { fprintf(stderr, "***start_reqct=%u ending rwmsg_global.status.request_ct=%u\n", start_reqct, rwmsg_global.status.request_ct); } VERBPRN("end rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct); VERBPRN("end rwmsg_global.status.qent=%u\n", rwmsg_global.status.qent); } TEST(RWMsgBroker, LottaRawRWSConcurQ2Bros) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues"); RWUT_BENCH_ITER(LottaRawRWSConcurQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broflo = FALSE; lottaraw2bros(2, false, false, burst, broflo, &opts, &vals); /* For *ConcurQ* tests */ #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSConcurQ2Bros"); nnchk(); RWUT_BENCH_END(LottaRawRWSConcurQBench); } TEST(RWMsgBroker, LottaRawRWSBigdefwinMainQ2Bros) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaRawRWSBigdefwinMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.bigdefwin = 100; int burst = 100; int broflo = FALSE; int squat = FALSE; lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSBigdefwinMainQ2Bros"); nnchk(); RWUT_BENCH_END(LottaRawRWSBigdefwinMainQBench); } TEST(RWMsgBroker, LottaRawRWSMainQ2Bros) { TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broflo = FALSE; int squat = FALSE; lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawRWSMainQ2Bros"); nnchk(); RWUT_BENCH_END(LottaRawRWSMainQBench); } TEST(RWMsgBroker, LottaRawBncRWSMainQ2Bros) { TEST_DESCRIPTION("Exercise broker timeout bounce code path."); RWUT_BENCH_ITER(LottaRawBncRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 1; int broflo = FALSE; int squat = FALSE; opts.reqtimeo = 50;/*ms*/ opts.bncall = TRUE; lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaRawBncRWSMainQ2Bros"); nnchk(); RWUT_BENCH_END(LottaRawBncRWSMainQBench); } TEST(RWMsgBroker, Big0512RawRWSMainQ2Bros) { TEST_DESCRIPTION("Tests broker with big 512KB requests, RWSched Main Queue"); RWUT_BENCH_ITER(Big0512RawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.paysz = 512000; int burst = 10; int broflo = FALSE; int squat = FALSE; lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.Big0512RawRWSMainQ2Bros"); nnchk(); RWUT_BENCH_END(Big0512RawRWSMainQBench); } TEST(RWMsgBroker, Big5120RawRWSMainQ2Bros) { TEST_DESCRIPTION("Tests broker with big 5MB requests, RWSched Main Queue"); RWUT_BENCH_ITER(Big5120RawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); opts.paysz = 5120000; int burst = 10; int broflo = FALSE; int squat = FALSE; lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.Big5120RawRWSMainQ2Bros"); nnchk(); RWUT_BENCH_END(Big5120RawRWSMainQBench); } TEST(RWMsgBroker, LottaPauseRawRWSSerQ2Bros) { TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Serial Queue"); RWUT_BENCH_ITER(LottaPauseRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; burst=burst; int broflo = FALSE; lottaraw2bros(false, false/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSSerQ2Bros"); nnchk(); RWUT_BENCH_END(LottaPauseRawRWSSerQBench); } TEST(RWMsgBroker, LottaPauseBigwinRawRWSSerQ2Bros) { TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Serial Queue"); RWUT_BENCH_ITER(LottaPauseBigwinRawRWSSerQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = SCTEST1_RMAX; burst=burst; int broflo = FALSE; opts.bigbrosrvwin = TRUE; lottaraw2bros(false, false/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSSerQ2Bros"); nnchk(); RWUT_BENCH_END(LottaPauseBigwinRawRWSSerQBench); } TEST(RWMsgBroker, LottaPauseRawRWSMainQ2Bros) { TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaPauseRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = 100; int broflo = FALSE; lottaraw2bros(false, true/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSMainQ2Bros"); nnchk(); RWUT_BENCH_END(LottaPauseRawRWSMainQBench); } TEST(RWMsgBroker, LottaPauseBigwinRawRWSMainQ2Bros) { TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Main Queue"); RWUT_BENCH_ITER(LottaPauseBigwinRawRWSMainQBench, 5, 5); struct lottarawvals vals; memset(&vals, 0, sizeof(vals)); struct lottaopts opts; memset(&opts, 0, sizeof(opts)); int burst = SCTEST1_RMAX; int broflo = FALSE; opts.bigbrosrvwin = TRUE; lottaraw2bros(false, true/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals); #if 0 RecordProperty("FlushTime", vals.flushtime); RecordProperty("rmax", vals.rmax); RecordProperty("ReqSent", vals.reqsent); RecordProperty("ReqAnswered", vals.reqans); RecordProperty("ReqDone", vals.reqdone); RecordProperty("ReqHz", vals.reqhz); #endif PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSMainQ2Bros"); nnchk(); RWUT_BENCH_END(LottaPauseBigwinRawRWSMainQBench); } TEST(RWMsgPerftool, CollapsedNofeedme) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "./rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "45", "--nofeedme", "--size", "64", "--window", "999999", "--count", "1000000", NULL }; #define RUNPERF() \ pid_t c = fork(); \ if (!c) { \ int i=0; \ while (argv[i]) fprintf(stderr,"%s ", argv[i++]); \ fprintf(stderr,"\n"); \ execv(filename, (char* const*) argv); \ abort(); \ } \ RW_ASSERT(c > 0); \ int status = 0; \ pid_t pid = waitpid(c, &status, 0); \ ASSERT_GE(pid, 1); \ if (pid > 0) { \ ASSERT_EQ(WEXITSTATUS(status), 0); \ } RUNPERF(); } TEST(RWMsgPerftool, LargeNofeedme) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "./rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "360", "--nofeedme", "--size", "64", "--window", "999999", "--count", "1000000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, LargeNofeedme2Bros) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "./rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--instance", "1", "--tasklet", "broker", "--instance", "2", "--tasklet", "server", "--instance", "1", "--broinst", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--broinst", "2", "--runtime", "50", "--nofeedme", "--size", "64", "--window", "999999", "--count", "50000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, LargeNofeedme1000) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "./rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--window", "1000", "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "300", "--nofeedme", "--size", "64", "--window", "999999", "--count", "1000000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, LargeNofeedme10002Bros) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "./rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--instance", "1", "--tasklet", "broker", "--instance", "2", "--window", "1000", "--tasklet", "server", "--instance", "1", "--broinst", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--broinst", "2", "--runtime", "300", "--nofeedme", "--size", "64", "--window", "999999", "--count", "50000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, DISABLED_CollapsedFeedmeBigwin) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "./rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "30", "--size", "64", "--window", "999999", "--count", "1000000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "30", "--size", "64", "--window", "99999", "--count", "100000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin2Bros) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--instance", "1", "--tasklet", "broker", "--instance", "2", "--tasklet", "server", "--instance", "1", "--broinst", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--broinst", "2", "--runtime", "50", "--size", "64", "--window", "99999", "--count", "50000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin1000) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--window", "1000", "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "30", "--size", "64", "--window", "99999", "--count", "100000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin10002Bros) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--instance", "1", "--window", "1000", "--tasklet", "broker", "--instance", "2", "--window", "1000", "--tasklet", "server", "--instance", "1", "--broinst", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--broinst", "2", "--runtime", "50", "--size", "64", "--window", "99999", "--count", "50000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, CollapsedFeedmeSmwin) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "30", "--size", "64", "--window", "999", "--count", "100000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, LargeFeedmeSmwin) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "60", "--size", "64", "--window", "999", "--count", "100000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, LargeFeedmeSmwin2Bros) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--instance", "1", "--tasklet", "broker", "--instance", "2", "--tasklet", "server", "--instance", "1", "--broinst", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--broinst", "2", "--runtime", "50", "--size", "64", "--window", "999", "--count", "50000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, LargeFeedmeSmwin1000) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--window", "1000", "--tasklet", "server", "--instance", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--runtime", "30", "--size", "64", "--window", "999", "--count", "100000", NULL }; RUNPERF(); } TEST(RWMsgPerftool, LargeFeedmeSmwin10002Bros) { int broport = rwmsg_broport_g(4); char nnuri[128]; sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport); const char *filename = "rwmsg_perftool"; const char *argv[] = { "rwmsg_perftool", "--nnuri", nnuri, "--shunt", "--tasklet", "broker", "--instance", "1", "--window", "1000", "--tasklet", "broker", "--instance", "2", "--window", "1000", "--tasklet", "server", "--instance", "1", "--broinst", "1", "--size", "64", "--tasklet", "client", "--instance", "1", "--broinst", "2", "--runtime", "50", "--size", "64", "--window", "999", "--count", "50000", NULL }; RUNPERF(); }
[ "Jeremy.Mordkoff@riftio.com" ]
Jeremy.Mordkoff@riftio.com
eb83b04698e9703c3de774fae5fb9392f438f4da
b73b6ba6b34afcd76efd02ca413cd01c7f75b33f
/cpp/boj1309.cpp
2547eadd151e091250ac2719df927f30c0f97366
[]
no_license
kim-seoyoung/basicprogramming
45b44f926eb8b901b27cb919dac7f1f8d8db5281
c0eb970984dac9eba36718a65dec84c658a88ccd
refs/heads/master
2020-06-20T16:41:35.091565
2020-03-12T12:47:49
2020-03-12T12:47:49
197,181,596
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
#include <iostream> using namespace std; int cases[100002][3]={{0,0,0},{1,1,1}}; int N; void dp(const int n){ if (n == N+2) return; cases[n][0] = (cases[n - 1][0] + cases[n - 1][1] + cases[n - 1][2]) %9901; cases[n][1] = (cases[n - 1][0] + cases[n - 1][2])%9901; cases[n][2] = (cases[n - 1][0] + cases[n - 1][1])%9901; dp(n+1); } int main(){ cin >> N; if(N < 2) cout << cases[N][0]+cases[N][1]+cases[N][2]; else { dp(2); cout << cases[N+1][0]; } return 0; }
[ "bestseo02@naver.com" ]
bestseo02@naver.com
17e50f6e9cf6a373925cb8184f583929af7a85f7
cb98a0df3c73ff01d6e0e4cc3d721d07ebd82f6f
/AdmSimulator/ChromPair.h
03f322fd9718b87180962758f911400f2b787cf6
[]
no_license
xyang619/gsim-old
77dff0335fbdb2fd4dc67e12c4812db729090698
1beb1a42ff7770470b29135c89452dd1a85c05cd
refs/heads/master
2020-06-01T14:27:48.253923
2015-01-21T07:09:18
2015-01-21T07:09:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
564
h
/* * ChromPair.h * * Created on: Sep 26, 2014 * Author: xiong_yang */ #ifndef CHROMPAIR_H_ #define CHROMPAIR_H_ #include "Chrom.h" class ChromPair { private: Chrom chrom1; Chrom chrom2; int getPoissonNumb(double lambda) const; void breakPoints(double * breaks, int n) const; public: ChromPair(); ChromPair(const Chrom & chrom1, const Chrom & chrom2); Chrom getChrom(int index) const; //double waitTime(); //void sort(double[], int); ChromPair & recombine(); virtual ~ChromPair(); }; #endif /* CHROMPAIR_H_ */
[ "young@research-imac32.icb.ac.cn" ]
young@research-imac32.icb.ac.cn
17cd5cf4b64b7a61e7b84d85d3324ab72deeab62
ebf1bb0e33c3a3748ae8e2e4ad5ad0faf2abde21
/appG/Account.cpp
611c91662845c4439fbcead4f22fe81db59cbf07
[]
no_license
salehi/deitel-and-deitel-c-persian
d6cdb963f9e6f64f37ca0d346f198dda0e1153c5
a25c2e530ea9fefffd6740247c70e9ec465cc188
refs/heads/master
2022-11-23T14:29:08.811553
2020-07-27T09:15:30
2020-07-27T09:15:30
282,849,119
1
0
null
null
null
null
UTF-8
C++
false
false
2,596
cpp
// Account.cpp // Member-function definitions for class Account. #include "Account.h" // Account class definition // Account constructor initializes attributes Account::Account( int theAccountNumber, int thePIN, double theAvailableBalance, double theTotalBalance ) : accountNumber( theAccountNumber ), pin( thePIN ), availableBalance( theAvailableBalance ), totalBalance( theTotalBalance ) { // empty body } // end Account constructor // determines whether a user-specified PIN matches PIN in Account bool Account::validatePIN( int userPIN ) const { if ( userPIN == pin ) return true; else return false; } // end function validatePIN // returns available balance double Account::getAvailableBalance() const { return availableBalance; } // end function getAvailableBalance // returns the total balance double Account::getTotalBalance() const { return totalBalance; } // end function getTotalBalance // credits an amount to the account void Account::credit( double amount ) { totalBalance += amount; // add to total balance } // end function credit // debits an amount from the account void Account::debit( double amount ) { availableBalance -= amount; // subtract from available balance totalBalance -= amount; // subtract from total balance } // end function debit // returns account number int Account::getAccountNumber() const { return accountNumber; } // end function getAccountNumber /************************************************************************** * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ "salehi1994@gmail.com" ]
salehi1994@gmail.com
67afbd76a187403033ca29da7d806754b0565825
8e75199f881321560ca5c939088b3b8d280ddf2c
/d05/ex04/main.cpp
3e778c9e56f989e45fa857d0758c55c0071350f3
[]
no_license
ademenet/piscine_cpp
c8c3f8411cd20d60d93e9f94db835a39e76c4934
1411dd71ea18a264e850f9483607352efcfbc325
refs/heads/master
2021-06-14T05:31:23.212904
2017-04-14T18:20:31
2017-04-14T18:20:31
85,195,242
0
1
null
null
null
null
UTF-8
C++
false
false
4,643
cpp
/** * @Author: ademenet * @Date: 2017-04-10T11:48:57+02:00 * @Last modified by: ademenet * @Last modified time: 2017-04-11T23:12:27+02:00 */ #include "Bureaucrat.hpp" #include "Form.hpp" #include "PresidentialPardonForm.hpp" #include "RobotomyRequestForm.hpp" #include "ShrubberyCreationForm.hpp" #include "Intern.hpp" #include "OfficeBlock.hpp" int main() { std::cout << "-------------------------------------" << std::endl; { Intern idiotOne; Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37); Bureaucrat bob = Bureaucrat("Bobby Bobson", 123); OfficeBlock ob; ob.setIntern(&idiotOne); ob.setSigner(&bob); ob.setExecutor(&hermes); try { ob.doBureaucracy("Shrubbery's form", "Pigley"); } catch (OfficeBlock::SpecificException & e) { std::cout << e.what() << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } std::cout << "-------------------------------------" << std::endl; { Intern idiotOne; Bureaucrat hermes = Bureaucrat("Hermes Conrad", 70); Bureaucrat bob = Bureaucrat("Bobby Bobson", 68); OfficeBlock ob; ob.setIntern(&idiotOne); ob.setSigner(&bob); ob.setExecutor(&hermes); try { ob.doBureaucracy("Robot's form", "Pigley"); } catch (OfficeBlock::SpecificException & e) { std::cout << e.what() << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } std::cout << "-------------------------------------" << std::endl; { Intern idiotOne; Bureaucrat hermes = Bureaucrat("Hermes Conrad", 149); Bureaucrat bob = Bureaucrat("Bobby Bobson", 123); OfficeBlock ob; ob.setIntern(&idiotOne); ob.setSigner(&bob); ob.setExecutor(&hermes); try { ob.doBureaucracy("President's form", "Pigley"); } catch (OfficeBlock::SpecificException & e) { std::cout << e.what() << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } std::cout << "-------------------------------------" << std::endl; { Intern idiotOne; Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37); Bureaucrat bob = Bureaucrat("Bobby Bobson", 123); OfficeBlock ob; ob.setIntern(&idiotOne); ob.setSigner(&bob); ob.setExecutor(&hermes); try { ob.doBureaucracy("mutant pig termination", "Pigley"); } catch (OfficeBlock::SpecificException & e) { std::cout << e.what() << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } std::cout << "-------------------------------------" << std::endl; { Intern idiotOne; Bureaucrat bob = Bureaucrat("Bobby Bobson", 123); OfficeBlock ob; ob.setIntern(&idiotOne); ob.setSigner(&bob); // ob.setExecutor(NULL); try { ob.doBureaucracy("mutant pig termination", "Pigley"); } catch (OfficeBlock::SpecificException & e) { std::cout << e.what() << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } std::cout << "-------------------------------------" << std::endl; { Intern idiotOne; Bureaucrat bob = Bureaucrat("Bobby Bobson", 123); Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37); OfficeBlock ob; // ob.setIntern(&idiotOne); ob.setSigner(&bob); ob.setExecutor(&hermes); try { ob.doBureaucracy("mutant pig termination", "Pigley"); } catch (OfficeBlock::SpecificException & e) { std::cout << e.what() << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } std::cout << "-------------------------------------" << std::endl; { Intern idiotOne; Bureaucrat bob = Bureaucrat("Bobby Bobson", 123); Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37); OfficeBlock ob; ob.setIntern(&idiotOne); // ob.setSigner(&bob); ob.setExecutor(&hermes); try { ob.doBureaucracy("mutant pig termination", "Pigley"); } catch (OfficeBlock::SpecificException & e) { std::cout << e.what() << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } } std::cout << "-------------------------------------" << std::endl; }
[ "ademenet@student.42.fr" ]
ademenet@student.42.fr
ab17343e19b2ae38596c97fdc6b0119ee4304c1c
1ae40287c5705f341886bbb5cc9e9e9cfba073f7
/Osmium/SDK/FN_MoviePlayer_classes.hpp
79684f729197e0aa1a3b476594d1702818a44aba
[]
no_license
NeoniteDev/Osmium
183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0
aec854e60beca3c6804f18f21b6a0a0549e8fbf6
refs/heads/master
2023-07-05T16:40:30.662392
2023-06-28T23:17:42
2023-06-28T23:17:42
340,056,499
14
8
null
null
null
null
UTF-8
C++
false
false
1,282
hpp
#pragma once // Fortnite (4.5-CL-4159770) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class MoviePlayer.MoviePlayerSettings // 0x0018 (0x0040 - 0x0028) class UMoviePlayerSettings : public UObject { public: bool bWaitForMoviesToComplete; // 0x0028(0x0001) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) bool bMoviesAreSkippable; // 0x0029(0x0001) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) unsigned char UnknownData00[0x6]; // 0x002A(0x0006) MISSED OFFSET TArray<struct FString> StartupMovies; // 0x0030(0x0010) (Edit, ZeroConstructor, Config, GlobalConfig) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class MoviePlayer.MoviePlayerSettings"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "kareemolim@gmail.com" ]
kareemolim@gmail.com
78657a2de8dc70b16c62e87f0bf06ea55cd41108
50466d79347d3ecef93ebf879a6c156142518dae
/src/util/principle_component_analysis.h
f76ba04a365675a978868a7af740435a2b5cd287
[ "MIT" ]
permissive
amadavan/OCR
6bb8a908452bc1e8fa89cf534dde3d668a00dead
05c323593302c9183005b067cdf1d48864727f29
refs/heads/master
2020-04-12T09:50:10.514272
2016-07-14T00:30:45
2016-07-14T00:30:45
60,293,536
0
0
null
null
null
null
UTF-8
C++
false
false
6,545
h
#ifndef OCR_UTIL_PRINCIPLE_COMPONENT_ANALYSIS_H_ #define OCR_UTIL_PRINCIPLE_COMPONENT_ANALYSIS_H_ #include <float.h> #include <cmath> #include <armadillo> #include "util/ocrtypes.h" namespace ocr { /** * A Principle Component Analysis (PCA) implementation. * * Defines an implementation of PCA with the ability to designate how the * projection is found and the reduced space. */ class PCA { public: /** * Default constructor for PCA uses automatic determination of dimensions * * Constructs the PCA object that will be used to determine the projections * of the original dataset to and from the reduced subspace. By default, it * determines the number of dimensions to retain based on analysis of the * amounnt of variability measured. */ PCA(); /** * Constructor for PCA providing a set number of reduced dimensions * * Constructs the PCA object with the number of dimensions to be included in * the reduced subspace. * * @param[in] num_reduced_dimensions number of dimensions to include in * reduced subspace */ PCA(int num_reduced_dimensions); /** * Consutuctor for PCA providing percent variability * * Constructs the PCA object while specifying the total percentage of * variability contained in the reduced subspace. * * @param[in] percent_variability percentage of original space's variability * contained in reduced subspace */ PCA(double percent_variability); ~PCA() {} /** * Trains the classifier given a dataset and known labels for the set * * Uses the known dataset and labels to generate the algorithm that will * later be used to predict the values of unknown data. This method should * be run prior to any testing methods (including test, test_batch...) * * @param[in] data_set nxm matrix with each entry in a column * @param[in] label_set mx1 vector of data_set labels */ void solve( const arma::mat &dataset ); /** * Determine the error rate for a given test set * * Computes the labels for a given dataset and compares to given known * labels. The resulting comparison is used to determine the overall * error rate of the algorithm for that dataset. This method assumes that * the training method has already been completed. * * @param[in] test_mat nxm matrix with each entry in a column * @param[in] true_labels mx1 column vector of true labels * @param[out] predicted_labels mx1 column vector of predicted labels * * @return fractional error rate */ arma::mat project( const arma::mat &mat, bool reverse = false ); /** * Set the PCA to solve for a specified percent variability * * Specifies a floating point value of variability that will be included in * the projection. This value represents a minimum bound and ensures that * at least this much variability is included in the projection. * * @param[in] variability Minimum percent variability in projection */ void set_percent_variability(double variability); /** * Returns the percent variability of the PCA solution or set-point * * Depending on the current state of the PCA solver, this can return two * different values. The first is if the PCA has not yet been solved. If * that is the case, this value will be the percent variability specified by * the user if they wish to use the variability dimension select mode, or * the default value of 0. Alternatively, if the algorithm has been run, * this will return the percent variability included in the data regardless * of algorithm used. * * @param[out] variability percentage variability included in PCA solution */ double get_percent_variability(); /** * Set the PCA to solve for a specified number of dimensions * * Defines a set number of dimensions to be included in the projection space * and to be solved for in the PCA. In other words, the top dimensions * eigenvectors will be included in the projection. * * @param[in] dimensions Number of dimensions to include in PCA projection */ void set_dimensions(uint32_t dimensions); /** * Returns number of dimensions in PCA * * Depending on whether or not the solve function has been run, this can * return two things. If solve was called and set_dimensions has not been * called since, this will return the number of dimensions that the solve * function reduced the dataset to. If set_dimensions has been called or * solve has not been called, this will return the value specified in the * constructor or set_dimensions. If no value was set, it defaults to 0. * * @param[out] n_dimensions Number of dimensions in PCA */ uint32_t get_dimensions(); /** * Use Minka's MLE to determine number of dimensions * * When performing a solve, the algorithm will determine the appropriate * number of dimensions by performing Minka's MLE that can be found here <a * href="https://uwaterloo.ca/data-science/sites/ca.data-science/files/ * uploads/files/automatic-dimensionality-selection-from-scree-plot-use-of- * profile-likelihood.pdf">here</a>. */ void set_auto_dimension(); private: /** * Enumeration of different ways of determining PCA dimensions * * Enumerated type that acts as a switch between different ways of * calculating the number of dimensions to be included in the PCA. These * include AUTO which uses Minka's MLE method, NUM_DIMENSIONS which sets a * number of dimensions, and PERCENT_VARIABILITY which defines a minimum * variability bound to be included in the projection. */ enum Mode { AUTO, NUM_DIMENSIONS, PERCENT_VARIABILITY }; arma::mat projection_matrix_; /// Matrix containing left-multiply projection uint32_t num_reduced_dimensions_; /// Number of dimensions double percent_variability_; // Percent variability Mode dimension_select_mode_; // Method of selecting number of dimensions /** * Return number of dimensions using Minka's MLE * * Performs Minka's MLE estimation that can be found here <a href="https://uwaterloo.ca/data-science/sites/ca.data-science/files/uploads/files/automatic-dimensionality-selection-from-scree-plot-use-of-profile-likelihood.pdf">here</a>. * Returns the Maximum Likelihood number of dimensions. * * @param[in] eigenvalues A list of eigenvalues in descending order * @param[in] n_samples Number of samples in dataset * @param[out] dimensions Maximum likelihood number of dimensions. */ size_t determine_dimensions(const arma::vec &eigenvalues, const size_t n_samples); }; } #endif // OCR_UTIL_PRINCIPLE_COMPONENT_ANALYSIS_H_
[ "avinash.madavan@gmail.com" ]
avinash.madavan@gmail.com
b87dba469973a4378da268cfe15e144c30bb19b1
a075225a2e1fe2d5e60e7802c5f0d0d884816904
/v0.1.2/Solvers/ShortCutSolver_CPLEX/ShortCutSolver_CPLEX.h
9b9889769ab0b0ac5ce3c4e207caeba8b177aa13
[ "BSD-3-Clause" ]
permissive
hqng/optimal-transport
592d225c114b4c478ede2f9f3010a5e5aa160bdf
c868db74f6b7dd675c5892d70e38fb0bd623dded
refs/heads/master
2020-04-16T22:56:41.962056
2019-11-23T08:52:11
2019-11-23T08:52:11
165,991,297
0
0
NOASSERTION
2019-11-23T08:52:12
2019-01-16T07:02:59
C++
UTF-8
C++
false
false
635
h
#ifndef ShortCutSolver_CPLEX_H_ #define ShortCutSolver_CPLEX_H_ #include<stdlib.h> #include<PythonTypes.h> #include"TCouplingHandler.h" #include"TVarListHandler.h" #include"TCPLEXNetSolver.h" #include"Interfaces-CPLEX.h" #include"ShortCutSolver-Tools.h" using namespace std; const int CH_SemiDense=0; const int CH_Sparse=1; const int SETUP_ERROR_CHUNKNOWN=-51; // external functions extern "C" { int Setup_Solver_CPLEX(TDoubleMatrix *muX, TDoubleMatrix *muY, TDoubleMatrix *alpha, TDoubleMatrix *beta, int initializeBases, long int couplingHandlerAddr, int couplingHandlerType, TInteger64Matrix *Pointer); } #endif
[ "jokin@jokinX220.(none)" ]
jokin@jokinX220.(none)
a726d3b815e1ac7b87df4aa45b07c90ba8e77d23
5456502f97627278cbd6e16d002d50f1de3da7bb
/remoting/codec/audio_decoder.cc
cde940ebd7e011ecc4d1ca387d31628451b742ab
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
722
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/codec/audio_decoder.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "remoting/codec/audio_decoder_opus.h" #include "remoting/protocol/session_config.h" namespace remoting { std::unique_ptr<AudioDecoder> AudioDecoder::CreateAudioDecoder( const protocol::SessionConfig& config) { if (config.audio_config().codec == protocol::ChannelConfig::CODEC_OPUS) { return base::WrapUnique(new AudioDecoderOpus()); } NOTIMPLEMENTED(); return nullptr; } } // namespace remoting
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
33efbccf873f19c9e5e2666ed02ef2180f8815e0
2f0e59d491c1e5b179ac2dedc56ccf85826447e1
/AABB.h
b99825370d50db8dea57ae9b599f3a5aea7d9b8f
[]
no_license
Sircrab/RayTracer
3ad288681d81f7000871e18fe9e8c476d388b630
74f70fecde5cce50854e80a7b95e47294f03d10c
refs/heads/master
2021-01-16T19:06:43.780304
2017-12-04T00:06:03
2017-12-04T00:06:03
100,137,424
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
h
// // Created by Geno on 21-Sep-17. // #ifndef RAYTRACER_AABB_H #define RAYTRACER_AABB_H #include "Vec3.h" #include "Ray.h" #include "Triangle.h" #include <limits> #include <vector> //Axis Aligned Bounding Box class AABB{ public: Vec3 minVec, maxVec; std::vector<Vec3> boxVertices; AABB(Vec3 minVec, Vec3 maxVec) : minVec(minVec), maxVec(maxVec) { boxVertices.push_back(Vec3(minVec.x,minVec.y,minVec.z)); boxVertices.push_back(Vec3(minVec.x,minVec.y,maxVec.z)); boxVertices.push_back(Vec3(minVec.x,maxVec.y,minVec.z)); boxVertices.push_back(Vec3(minVec.x,maxVec.y,maxVec.z)); boxVertices.push_back(Vec3(maxVec.x,minVec.y,minVec.z)); boxVertices.push_back(Vec3(maxVec.x,minVec.y,maxVec.z)); boxVertices.push_back(Vec3(maxVec.x,maxVec.y,minVec.z)); boxVertices.push_back(Vec3(maxVec.x,maxVec.y,maxVec.z)); }; bool intersect_ray(const Ray& ray) const; bool intersect_triangle(const std::vector<Vec3>& triVertices) const; private: void project(const std::vector<Vec3>& points,const Vec3& projectionAxis, double& outMin, double& outMax) const; }; #endif //RAYTRACER_AABB_H
[ "rovalfer@gmail.com" ]
rovalfer@gmail.com
5fb2296c97591754976dfd43970a4c051efe4c28
c210a7753fb88b632cd13eb0f1b0b2fef5ad1423
/src/include/CheckConservation.h
35d2b19545f386a846d108ce9bae1a3c4ceab97c
[]
no_license
vijaysm/Camellia
879840f37fa0c3cde55fc1e01452f5fbc87e185e
a34c27a783028cbd70dd0544187e2f188784a6d7
refs/heads/master
2021-01-16T00:43:04.063673
2016-09-06T19:39:21
2016-09-06T19:39:21
41,429,234
0
0
null
2015-08-26T14:07:23
2015-08-26T14:07:21
null
UTF-8
C++
false
false
3,350
h
// @HEADER // *********************************************************************** // // © 2016 UChicago Argonne. For licensing details, see LICENSE-Camellia in the licenses directory. // // Questions? Contact Nathan V. Roberts (nate@nateroberts.com) // // *********************************************************************** // @HEADER #ifndef CHECKCONSERVATION_H #define CHECKCONSERVATION_H #include "InnerProductScratchPad.h" #include "Mesh.h" #include "CamelliaCellTools.h" #include <Teuchos_Tuple.hpp> namespace Camellia { Teuchos::Tuple<double, 3> checkConservation(TFunctionPtr<double> flux, TFunctionPtr<double> source, Teuchos::RCP<Mesh> mesh, int cubatureEnrichment = 0) { double maxMassFluxIntegral = 0.0; double totalMassFlux = 0.0; double totalAbsMassFlux = 0.0; vector<ElementPtr> elems = mesh->activeElements(); for (vector<ElementPtr>::iterator it = elems.begin(); it != elems.end(); ++it) { ElementPtr elem = *it; int cellID = elem->cellID(); ElementTypePtr elemType = elem->elementType(); Intrepid::FieldContainer<double> physicalCellNodes = mesh->physicalCellNodesForCell(cellID); BasisCachePtr basisCache = BasisCache::basisCacheForCell(mesh, cellID, cubatureEnrichment); Intrepid::FieldContainer<double> volumeIntegral(1); source->integrate(volumeIntegral, basisCache, true); int numSides = CamelliaCellTools::getSideCount(basisCache->cellTopology()); double surfaceIntegral = 0; for (int sideIndex = 0; sideIndex < numSides; sideIndex++) { Intrepid::FieldContainer<double> sideIntegral(1); flux->integrate(sideIntegral, basisCache->getSideBasisCache(sideIndex), true); surfaceIntegral += sideIntegral(0); } double massFlux = surfaceIntegral - volumeIntegral(0); maxMassFluxIntegral = max(abs(massFlux), maxMassFluxIntegral); totalMassFlux += massFlux; totalAbsMassFlux += abs( massFlux ); } Teuchos::Tuple<double, 3> fluxImbalances = Teuchos::tuple(maxMassFluxIntegral, totalMassFlux, totalAbsMassFlux); return fluxImbalances; } double computeFluxOverElementSides(TFunctionPtr<double> flux, Teuchos::RCP<Mesh> mesh, vector< pair<ElementPtr, int> > originalElemFaces, int cubatureEnrichment=0) { double totalMassFlux = 0.0; for (vector< pair<ElementPtr, int> >::iterator origIt = originalElemFaces.begin(); origIt != originalElemFaces.end(); ++origIt) { int originalSideIndex = origIt->second; vector< pair<int, int> > cellFaces = origIt->first->getDescendantsForSide(originalSideIndex); for (vector< pair<int, int> >::iterator it = cellFaces.begin(); it != cellFaces.end(); ++it) { int cellID = it->first; int sideIndex = it->second; BasisCachePtr basisCache = BasisCache::basisCacheForCell(mesh, cellID, cubatureEnrichment); BasisCachePtr sideBasisCache = basisCache->getSideBasisCache(sideIndex); // Intrepid::FieldContainer<double> physicalCubaturePoints = sideBasisCache->getPhysicalCubaturePoints(); // double xCell0 = physicalCubaturePoints(0,0,0); // cout << physicalCubaturePoints << endl; Intrepid::FieldContainer<double> sideIntegral(1); flux->integrate(sideIntegral, sideBasisCache, true); totalMassFlux += sideIntegral(0); } } return totalMassFlux; } } #endif /* end of include guard: CHECKCONSERVATION_H */
[ "nvroberts@alcf.anl.gov" ]
nvroberts@alcf.anl.gov
088cb51a511caddf67d2d9d05cffaa34c6d23dd7
7300a2f3e5d6a542401fd011be01d19036c73f7f
/UDZ.cpp
76df3a3cde66e8a59f5741436e3239899b480e6e
[]
no_license
Zarins84/C
3f1895d87fa375f28470ba1b3b69814653b7241e
bdb52ee7244e1488874795cbf87c3a40242b01ad
refs/heads/main
2023-06-16T14:40:39.982089
2021-07-13T09:46:01
2021-07-13T09:46:01
385,280,550
0
0
null
null
null
null
UTF-8
C++
false
false
968
cpp
#include <iostream> using namespace std; int main() { int sk; int num; do { sk= rand()%10+1; num++; cout << "\n" << num << ". " << sk; } while(sk != 5); return 0; } 8.uzdevums!! #include <iostream> using namespace std; int main() { int a,b; cout << "ievadiet 2 skaitïus\n"; cin >> a >> b; double Y=a/b; cout << Y; } 9.udzevums!! #include <iostream> using namespace std; int main() { int a,b,c; cout << "ievadiet 3 skaitïus\n"; cin >> a >> b >> c; if (a > b) cout << a << " ir lielâkais skaitlis"; else if (a > c) cout << a << " ir lielâkais skaitlis"; else if (b > c) cout << b << " ir lielâkais skaitlis"; else if (b > a) cout << b << " ir lielâkais skaitlis"; else if (c > a) cout << c << " ir lelâkais skaitlis"; else if (c > b) cout << c << " ir lielâkais skaitlis"; }
[ "noreply@github.com" ]
Zarins84.noreply@github.com
2fa8472b300448a8b100959854128fd363f2b932
1eef2f3fcdb5995041a23164b0e1fa7e7af632f4
/src/smt/theory_array_bapa.cpp
7b7f93f026124bc064adb16f45ef9501711270ce
[ "MIT" ]
permissive
mtrberzi/z3
d4a80fae4542b69a85b540677aeeabe84d78ce55
b658934bd8bd87f8e6dc9c117d9fda061dad2fd9
refs/heads/master
2021-07-18T16:48:56.368810
2021-04-20T17:16:44
2021-04-20T17:16:44
41,640,176
1
6
NOASSERTION
2021-03-02T18:01:53
2015-08-30T19:20:55
C++
UTF-8
C++
false
false
24,048
cpp
/*++ Copyright (c) 2019 Microsoft Corporation Module Name: theory_array_bapa.cpp Abstract: Saturation procedure for BAPA predicates. Assume there is a predicate Size(S, n) for S : Array(T, Bool) and n : Int The predicate is true if S is a set of size n. Size(S, n), Size(T, m) S, T are intersecting. n != m or S != T D --------------------------------------------------------- Size(S, n) => Size(S\T, k1), Size(S n T, k2), n = k1 + k2 Size(T, m) => Size(T\S, k3), SIze(S n T, k2), m = k2 + k3 Size(S, n) P -------------------- Size(S, n) => n >= 0 Size(S, n), is infinite domain B ------------------------------ Size(S, n) => default(S) = false Size(S, n), Size(S, m) F -------------------------------- Size(S, n), Size(S, m) => n = m Fixing values during final check: Size(S, n) V ------------------- assume value(n) = n Size(S, n), S[i1], ..., S[ik] O ------------------------------- ~distinct(i1, ... ik) or n >= k Size(S,n) Ak -------------------------------------------------- S[i1] & .. & S[ik] & distinct(i1, .., ik) or n < k Q: Is this sufficient? Axiom A1 could be adjusted to add new elements i' until there are k witnesses for Size(S, k). This is quite bad when k is very large. Instead rely on stably infiniteness or other domain properties of the theories. When A is finite domain, or there are quantifiers there could be constraints that force domain sizes so domain sizes may have to be enforced. A succinct way would be through domain comprehension assertions. Finite domains: Size(S, n), is finite domain ---------------------------- S <= |A| Size(S, n), !S[i1], .... !S[ik], S is finite domain ---------------------------------------------------------- default(S) = false or ~distinct(i1,..,ik) or |A| - k <= n ~Size(S, m) is negative on all occurrences, S is finite domain --------------------------------------------------------------- Size(S, n) n fresh. Model construction for infinite domains when all Size(S, m) are negative for S. Author: Nikolaj Bjorner 2019-04-13 Revision History: */ #include "ast/ast_util.h" #include "ast/ast_pp.h" #include "ast/rewriter/array_rewriter.h" #include "smt/smt_context.h" #include "smt/smt_arith_value.h" #include "smt/theory_array_full.h" #include "smt/theory_array_bapa.h" #if 0 - set of native select terms that are true - set of auxiliary select terms. - n1, n2, n3, n4. - a1, a2, a3, a4, a5. - - add select terms, such that first #endif namespace smt { class theory_array_bapa::imp { struct sz_info { bool m_is_leaf; // has it been split into disjoint subsets already? rational m_size; // set to >= integer if fixed in final check, otherwise -1 obj_map<enode, expr*> m_selects; sz_info(): m_is_leaf(true), m_size(rational::minus_one()) {} }; typedef std::pair<func_decl*, func_decl*> func_decls; ast_manager& m; theory_array_full& th; arith_util m_arith; array_util m_autil; th_rewriter m_rw; arith_value m_arith_value; ast_ref_vector m_pinned; obj_map<app, sz_info*> m_sizeof; obj_map<expr, rational> m_size_limit; obj_map<sort, func_decls> m_index_skolems; obj_map<sort, func_decl*> m_size_limit_sort2skolems; unsigned m_max_set_enumeration; context& ctx() { return th.get_context(); } void reset() { for (auto& kv : m_sizeof) { dealloc(kv.m_value); } } bool is_true(expr* e) { return is_true(ctx().get_literal(e)); } bool is_true(enode* e) { return is_true(e->get_expr()); } bool is_true(literal l) { return ctx().is_relevant(l) && ctx().get_assignment(l) == l_true; } bool is_leaf(sz_info& i) const { return i.m_is_leaf; } bool is_leaf(sz_info* i) const { return is_leaf(*i); } enode* get_root(expr* e) { return ctx().get_enode(e)->get_root(); } bool is_select(enode* n) { return th.is_select(n); } app_ref mk_select(expr* a, expr* i) { expr* args[2] = { a, i }; return app_ref(m_autil.mk_select(2, args), m); } literal get_literal(expr* e) { return ctx().get_literal(e); } literal mk_literal(expr* e) { expr_ref _e(e, m); if (!ctx().e_internalized(e)) ctx().internalize(e, false); literal lit = get_literal(e); ctx().mark_as_relevant(lit); return lit; } literal mk_eq(expr* a, expr* b) { expr_ref _a(a, m), _b(b, m); literal lit = th.mk_eq(a, b, false); ctx().mark_as_relevant(lit); return lit; } void mk_th_axiom(literal l1, literal l2) { literal lits[2] = { l1, l2 }; mk_th_axiom(2, lits); } void mk_th_axiom(literal l1, literal l2, literal l3) { literal lits[3] = { l1, l2, l3 }; mk_th_axiom(3, lits); } void mk_th_axiom(unsigned n, literal* lits) { TRACE("card", ctx().display_literals_verbose(tout, n, lits) << "\n";); IF_VERBOSE(10, ctx().display_literals_verbose(verbose_stream(), n, lits) << "\n"); ctx().mk_th_axiom(th.get_id(), n, lits); } void update_indices() { for (auto const& kv : m_sizeof) { app* k = kv.m_key; sz_info& v = *kv.m_value; v.m_selects.reset(); if (is_true(k) && is_leaf(v)) { enode* set = get_root(k->get_arg(0)); for (enode* parent : enode::parents(set)) { if (is_select(parent) && parent->get_arg(0)->get_root() == set) { if (is_true(parent)) { v.m_selects.insert(parent->get_arg(1)->get_root(), parent->get_expr()); } } } } } } /** F: Size(S, k1) & Size(S, k2) => k1 = k2 */ lbool ensure_functional() { lbool result = l_true; obj_map<enode, app*> parents; for (auto const& kv : m_sizeof) { app* sz1 = kv.m_key; if (!is_true(sz1)) { continue; } enode* r = get_root(sz1->get_arg(0)); app* sz2 = nullptr; if (parents.find(r, sz2)) { expr* k1 = sz1->get_arg(1); expr* k2 = sz2->get_arg(1); if (get_root(k1) != get_root(k2)) { mk_th_axiom(~get_literal(sz1), ~get_literal(sz2), mk_eq(k1, k2)); result = l_false; } } else { parents.insert(r, sz1); } } return result; } /** Enforce D */ lbool ensure_disjoint() { auto i = m_sizeof.begin(), end = m_sizeof.end(); for (; i != end; ++i) { auto& kv = *i; if (!kv.m_value->m_is_leaf) { continue; } for (auto j = i; ++j != end; ) { if (j->m_value->m_is_leaf && !ensure_disjoint(i->m_key, j->m_key)) { return l_false; } } } return l_true; } bool ensure_disjoint(app* sz1, app* sz2) { sz_info& i1 = *m_sizeof[sz1]; sz_info& i2 = *m_sizeof[sz2]; SASSERT(i1.m_is_leaf); SASSERT(i2.m_is_leaf); expr* s = sz1->get_arg(0); expr* t = sz2->get_arg(0); if (s->get_sort() != t->get_sort()) { return true; } enode* r1 = get_root(s); enode* r2 = get_root(t); if (r1 == r2) { return true; } if (!ctx().is_diseq(r1, r2) && ctx().assume_eq(r1, r2)) { return false; } if (do_intersect(i1.m_selects, i2.m_selects)) { add_disjoint(sz1, sz2); return false; } return true; } bool do_intersect(obj_map<enode, expr*> const& s, obj_map<enode, expr*> const& t) const { if (s.size() > t.size()) { return do_intersect(t, s); } for (auto const& idx : s) if (t.contains(idx.m_key)) return true; return false; } void add_disjoint(app* sz1, app* sz2) { sz_info& i1 = *m_sizeof[sz1]; sz_info& i2 = *m_sizeof[sz2]; SASSERT(i1.m_is_leaf); SASSERT(i2.m_is_leaf); expr* t = sz1->get_arg(0); expr* s = sz2->get_arg(0); expr_ref tms = mk_subtract(t, s); expr_ref smt = mk_subtract(s, t); expr_ref tns = mk_intersect(t, s); #if 0 std::cout << tms << "\n"; std::cout << smt << "\n"; std::cout << tns << "\n"; #endif if (tns == sz1) { std::cout << "SEEN " << tms << "\n"; } if (tns == sz2) { std::cout << "SEEN " << smt << "\n"; } ctx().push_trail(value_trail<bool>(i1.m_is_leaf, false)); ctx().push_trail(value_trail<bool>(i2.m_is_leaf, false)); expr_ref k1(m), k2(m), k3(m); expr_ref sz_tms(m), sz_tns(m), sz_smt(m); k1 = m_autil.mk_card(tms); k2 = m_autil.mk_card(tns); k3 = m_autil.mk_card(smt); sz_tms = m_autil.mk_has_size(tms, k1); sz_tns = m_autil.mk_has_size(tns, k2); sz_smt = m_autil.mk_has_size(smt, k3); propagate(sz1, sz_tms); propagate(sz1, sz_tns); propagate(sz2, sz_smt); propagate(sz2, sz_tns); propagate(sz1, mk_eq(k1 + k2, sz1->get_arg(1))); propagate(sz2, mk_eq(k3 + k2, sz2->get_arg(1))); } expr_ref mk_subtract(expr* t, expr* s) { expr_ref d(m_autil.mk_setminus(t, s), m); m_rw(d); return d; } expr_ref mk_intersect(expr* t, expr* s) { expr_ref i(m_autil.mk_intersection(t, s), m); m_rw(i); return i; } void propagate(expr* assumption, expr* conseq) { propagate(assumption, mk_literal(conseq)); } void propagate(expr* assumption, literal conseq) { mk_th_axiom(~mk_literal(assumption), conseq); } /** Enforce V */ lbool ensure_values_assigned() { lbool result = l_true; for (auto const& kv : m_sizeof) { app* k = kv.m_key; sz_info& i = *kv.m_value; if (is_leaf(&i)) { rational value; expr* sz = k->get_arg(1); if (!m_arith_value.get_value(sz, value)) { return l_undef; } literal lit = mk_eq(sz, m_arith.mk_int(value)); if (lit != true_literal && is_true(lit)) { ctx().push_trail(value_trail<rational>(i.m_size, value)); continue; } ctx().set_true_first_flag(lit.var()); result = l_false; } } return result; } /** Enforce Ak, */ lbool ensure_non_empty() { for (auto const& kv : m_sizeof) { sz_info& i = *kv.m_value; app* set_sz = kv.m_key; if (is_true(set_sz) && is_leaf(i) && i.m_selects.size() < i.m_size) { expr* set = set_sz->get_arg(0); expr_ref le(m_arith.mk_le(set_sz->get_arg(1), m_arith.mk_int(0)), m); literal le_lit = mk_literal(le); literal sz_lit = mk_literal(set_sz); for (unsigned k = i.m_selects.size(); rational(k) < i.m_size; ++k) { expr_ref idx = mk_index_skolem(set_sz, set, k); app_ref sel(mk_select(set, idx), m); mk_th_axiom(~sz_lit, le_lit, mk_literal(sel)); TRACE("card", tout << idx << " " << sel << " " << i.m_size << "\n";); } return l_false; } } return l_true; } // create skolem function that is injective on integers (ensures uniqueness). expr_ref mk_index_skolem(app* sz, expr* a, unsigned n) { func_decls fg; sort* s = a->get_sort(); if (!m_index_skolems.find(s, fg)) { sort* idx_sort = get_array_domain(s, 0); sort* dom1[2] = { s, m_arith.mk_int() }; sort* dom2[1] = { idx_sort }; func_decl* f = m.mk_fresh_func_decl("to-index", "", 2, dom1, idx_sort); func_decl* g = m.mk_fresh_func_decl("from-index", "", 1, dom2, m_arith.mk_int()); fg = std::make_pair(f, g); m_index_skolems.insert(s, fg); m_pinned.push_back(f); m_pinned.push_back(g); m_pinned.push_back(s); } expr_ref nV(m_arith.mk_int(n), m); expr_ref result(m.mk_app(fg.first, a, nV), m); expr_ref le(m_arith.mk_le(sz->get_arg(1), nV), m); expr_ref fr(m.mk_app(fg.second, result), m); // set-has-size(a, k) => k <= n or g(f(a,n)) = n mk_th_axiom(~mk_literal(sz), mk_literal(le), mk_eq(nV, fr)); return result; } /** Enforce O */ lbool ensure_no_overflow() { for (auto const& kv : m_sizeof) { if (is_true(kv.m_key) && is_leaf(kv.m_value)) { lbool r = ensure_no_overflow(kv.m_key, *kv.m_value); if (r != l_true) return r; } } return l_true; } lbool ensure_no_overflow(app* sz, sz_info& info) { SASSERT(!info.m_size.is_neg()); if (info.m_size < info.m_selects.size()) { for (auto i = info.m_selects.begin(), e = info.m_selects.end(); i != e; ++i) { for (auto j = i; ++j != e; ) { if (ctx().assume_eq(i->m_key, j->m_key)) { return l_false; } } } // if all is exhausted, then add axiom: set-has-size(s, n) & s[indices] & all-diff(indices) => n >= |indices| literal_vector lits; lits.push_back(~mk_literal(sz)); for (auto const& kv : info.m_selects) { lits.push_back(~mk_literal(kv.m_value)); } if (info.m_selects.size() > 1) { ptr_vector<expr> args; for (auto const& kv : info.m_selects) { args.push_back(kv.m_key->get_expr()); } if (info.m_selects.size() == 2) { lits.push_back(mk_eq(args[0], args[1])); } else { expr_ref diff(m.mk_distinct_expanded(args.size(), args.data()), m); lits.push_back(~mk_literal(diff)); } } expr_ref ge(m_arith.mk_ge(sz->get_arg(1), m_arith.mk_int(info.m_selects.size())), m); lits.push_back(mk_literal(ge)); mk_th_axiom(lits.size(), lits.data()); return l_false; } return l_true; } class remove_sz : public trail { ast_manager& m; obj_map<app, sz_info*> & m_table; app* m_obj; public: remove_sz(ast_manager& m, obj_map<app, sz_info*>& tab, app* t): m(m), m_table(tab), m_obj(t) { } ~remove_sz() override {} void undo() override { m.dec_ref(m_obj); dealloc(m_table[m_obj]); m_table.remove(m_obj); } }; std::ostream& display(std::ostream& out) { for (auto const& kv : m_sizeof) { display(out << mk_pp(kv.m_key, m) << ": ", *kv.m_value); } return out; } std::ostream& display(std::ostream& out, sz_info& sz) { return out << (sz.m_is_leaf ? "leaf": "") << " size: " << sz.m_size << " selects: " << sz.m_selects.size() << "\n"; } public: imp(theory_array_full& th): m(th.get_manager()), th(th), m_arith(m), m_autil(m), m_rw(m), m_arith_value(m), m_pinned(m) { context& ctx = th.get_context(); m_arith_value.init(&ctx); m_max_set_enumeration = 4; } ~imp() { reset(); } void internalize_term(app* term) { if (th.is_set_has_size(term)) { internalize_size(term); } else if (th.is_set_card(term)) { internalize_card(term); } } /** * Size(S, n) => n >= 0, default(S) = false */ void internalize_size(app* term) { SASSERT(ctx().e_internalized(term)); literal lit = mk_literal(term); expr* s = term->get_arg(0); expr* n = term->get_arg(1); mk_th_axiom(~lit, mk_literal(m_arith.mk_ge(n, m_arith.mk_int(0)))); sort_size const& sz = s->get_sort()->get_num_elements(); if (sz.is_infinite()) { mk_th_axiom(~lit, mk_eq(th.mk_default(s), m.mk_false())); } else { warning_msg("correct handling of finite domains is TBD"); // add upper bound on size of set. // add case where default(S) = true, and add negative elements. } m_sizeof.insert(term, alloc(sz_info)); m_size_limit.insert(s, rational(2)); assert_size_limit(s, n); m.inc_ref(term); ctx().push_trail(remove_sz(m, m_sizeof, term)); } /** \brief whenever there is a cardinality function, it includes an axiom that entails the set is finite. */ void internalize_card(app* term) { SASSERT(ctx().e_internalized(term)); app_ref has_size(m_autil.mk_has_size(term->get_arg(0), term), m); literal lit = mk_literal(has_size); ctx().assign(lit, nullptr); } lbool trace_call(char const* msg, lbool r) { if (r != l_true) { IF_VERBOSE(2, verbose_stream() << msg << "\n"); } return r; } final_check_status final_check() { final_check_status st = m_arith_value.final_check(); if (st != FC_DONE) return st; lbool r = trace_call("ensure_functional", ensure_functional()); if (r == l_true) update_indices(); if (r == l_true) r = trace_call("ensure_disjoint", ensure_disjoint()); if (r == l_true) r = trace_call("ensure_values_assigned", ensure_values_assigned()); if (r == l_true) r = trace_call("ensure_non_empty", ensure_non_empty()); if (r == l_true) r = trace_call("ensure_no_overflow", ensure_no_overflow()); CTRACE("card", r != l_true, display(tout);); switch (r) { case l_true: return FC_DONE; case l_false: return FC_CONTINUE; case l_undef: return FC_GIVEUP; } return FC_GIVEUP; } void init_model() { for (auto const& kv : m_sizeof) { sz_info& i = *kv.m_value; app* sz = kv.m_key; if (is_true(sz) && is_leaf(i) && rational(i.m_selects.size()) != i.m_size) { warning_msg("models for BAPA is TBD"); break; } } } bool should_research(expr_ref_vector & unsat_core) { expr* set, *sz; for (auto & e : unsat_core) { if (is_app(e) && is_size_limit(to_app(e), set, sz)) { inc_size_limit(set, sz); return true; } } return false; } void inc_size_limit(expr* set, expr* sz) { IF_VERBOSE(2, verbose_stream() << "inc value " << mk_pp(set, m) << "\n"); m_size_limit[set] *= rational(2); assert_size_limit(set, sz); } bool is_size_limit(app* e, expr*& set, expr*& sz) { func_decl* d = nullptr; if (e->get_num_args() > 0 && m_size_limit_sort2skolems.find(e->get_arg(0)->get_sort(), d) && d == e->get_decl()) { set = e->get_arg(0); sz = e->get_arg(1); return true; } else { return false; } } // has-size(s,n) & size-limit(s, n, k) => n <= k app_ref mk_size_limit(expr* set, expr* sz) { func_decl* sk = nullptr; sort* s = set->get_sort(); if (!m_size_limit_sort2skolems.find(s, sk)) { sort* dom[3] = { s, m_arith.mk_int(), m_arith.mk_int() }; sk = m.mk_fresh_func_decl("value-limit", "", 3, dom, m.mk_bool_sort()); m_pinned.push_back(sk); m_size_limit_sort2skolems.insert(s, sk); } return app_ref(m.mk_app(sk, set, sz, m_arith.mk_int(m_size_limit[set])), m); } void assert_size_limit(expr* set, expr* sz) { app_ref set_sz(m_autil.mk_has_size(set, sz), m); app_ref lim(m_arith.mk_int(m_size_limit[set]), m); app_ref size_limit = mk_size_limit(set, sz); mk_th_axiom(~mk_literal(set_sz), ~mk_literal(size_limit), mk_literal(m_arith.mk_le(sz, lim))); } void add_theory_assumptions(expr_ref_vector & assumptions) { for (auto const& kv : m_sizeof) { expr* set = kv.m_key->get_arg(0); expr* sz = kv.m_key->get_arg(1); assumptions.push_back(mk_size_limit(set, sz)); } TRACE("card", tout << "ASSUMPTIONS: " << assumptions << "\n";); } }; theory_array_bapa::theory_array_bapa(theory_array_full& th) { m_imp = alloc(imp, th); } theory_array_bapa::~theory_array_bapa() { dealloc(m_imp); } void theory_array_bapa::internalize_term(app* term) { m_imp->internalize_term(term); } final_check_status theory_array_bapa::final_check() { return m_imp->final_check(); } void theory_array_bapa::init_model() { m_imp->init_model(); } bool theory_array_bapa::should_research(expr_ref_vector & unsat_core) { return m_imp->should_research(unsat_core); } void theory_array_bapa::add_theory_assumptions(expr_ref_vector & assumptions) { m_imp->add_theory_assumptions(assumptions); } }
[ "nbjorner@microsoft.com" ]
nbjorner@microsoft.com
ca51b1bece3f7ac98ba449a10d5789389d716611
0acbe61f45c084b6bcfd2a6c7268e42197ebffe2
/IB/painters-partition-problem.cpp
445f0046b592a52f56bfb687c08e4102a4e6736a
[]
no_license
projectescape/cp-archive
a86c6fd844978e2e34690e7ba90c68968b72395a
2beaf2f554af413054052a6ce8d9cd58552bcc10
refs/heads/master
2021-07-06T21:10:11.556169
2020-09-27T16:43:15
2020-09-27T16:43:15
193,668,314
0
1
null
2020-09-25T08:16:37
2019-06-25T08:37:04
C++
UTF-8
C++
false
false
706
cpp
int Solution::paint(int A, int B, vector<int> &C) { int e = 0, s = INT_MIN; for (auto i : C) { e += i; s = max(s, i); } long long ans = LLONG_MAX, i, j, k, m; for (; s <= e;) { m = (s + e) / 2; for (i = j = k = 0; i < C.size() && k < A; i++) { j += C[i]; if (j > m) { i--; k++; j = 0; } else if (j == m) { k++; j = 0; } } if (k < A || (k == A && i == C.size())) { ans = min(ans, m); e = m - 1; } else { s = m + 1; } } return (ans * B) % 10000003; }
[ "escaperealityproject@gmail.com" ]
escaperealityproject@gmail.com
a784dbbdebcf2e0528cc181492f69c0d1c23feab
90d253b075c47054ab1d6bf6206f37e810330068
/Codeforces/1689/d.cpp
9e45d14aa708c54b75495445b43bceb3acc29837
[ "MIT" ]
permissive
eyangch/competitive-programming
45684aa804cbcde1999010332627228ac1ac4ef8
de9bb192c604a3dfbdd4c2757e478e7265516c9c
refs/heads/master
2023-07-10T08:59:25.674500
2023-06-25T09:30:43
2023-06-25T09:30:43
178,763,969
22
8
null
null
null
null
UTF-8
C++
false
false
2,037
cpp
#include <bits/stdc++.h> #define endl '\n' #define eat cin #define moo cout #define int long long using namespace std; int T, N, M, d[1000][1000]; string b[1000]; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; int dist(int x1, int y1, int x2, int y2){ return abs(x1 - x2) + abs(y1 - y2); } int32_t main(){ eat.tie(0) -> sync_with_stdio(0); eat >> T; while(T--){ eat >> N >> M; for(int i = 0; i < N; i++){ eat >> b[i]; } for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) d[i][j] = -1; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(b[i][j] == 'W') continue; d[0][0] = max(d[0][0], dist(0, 0, i, j)); d[N-1][0] = max(d[N-1][0], dist(N-1, 0, i, j)); d[0][M-1] = max(d[0][M-1], dist(0, M-1, i, j)); d[N-1][M-1] = max(d[N-1][M-1], dist(N-1, M-1, i, j)); } } priority_queue<pair<int, pair<int, int>>> pq; pq.push({d[0][0], {0, 0}}); pq.push({d[N-1][0], {N-1, 0}}); pq.push({d[0][M-1], {0, M-1}}); pq.push({d[N-1][M-1], {N-1, M-1}}); while(!pq.empty()){ int cd = pq.top().first; int cx = pq.top().second.first; int cy = pq.top().second.second; pq.pop(); for(int i = 0; i < 4; i++){ int nx = cx + dx[i]; int ny = cy + dy[i]; if(nx < 0 || ny < 0 || nx >= N || ny >= M) continue; if(d[nx][ny] != -1) continue; d[nx][ny] = cd - 1; pq.push({cd-1, {nx, ny}}); } } int best = 9999999; int bx = 0, by = 0; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(d[i][j] < best){ best = d[i][j]; bx = i; by = j; } } } moo << bx+1 << ' ' << by+1 << endl; } }
[ "eyangch@gmail.com" ]
eyangch@gmail.com
0d60a0f0c0031d84fd6522338a76d0e2dd6850ee
a3effde3c27c072090f0021bdae3306961eb2d92
/Codeforces/1221/B.cpp
1fab4dd6106cf6181137eac291ce7851236cda08
[]
no_license
anmolgup/Competitive-programming-code
f4837522bf648c90847d971481f830a47722da29
329101c4e45be68192715c9a0718f148e541b58b
refs/heads/master
2022-12-03T19:00:40.261727
2020-08-08T09:21:58
2020-08-08T09:21:58
286,011,774
1
0
null
null
null
null
UTF-8
C++
false
false
4,308
cpp
#include<bits/stdc++.h> using namespace std; //Optimisations #pragma GCC target ("avx2") #pragma GCC optimization ("unroll-loops") #pragma GCC optimize("O2") //shortcuts for functions #define pb push_back #define mp make_pair #define ff first #define ss second #define endl "\n" #define all(v) v.begin(),v.end() #define rall(v) v.rbegin(),v.rend() #define th(n) cout<<n<<endl #define gc getchar_unlocked #define ms(s, n) memset(s, n, sizeof(s)) #define prec(n) fixed<<setprecision(n) #define n_l '\n' // make it python #define gcd __gcd #define append push_back #define str to_string #define upper(s) transform(s.begin(),s.end(),s.begin(),::toupper) #define lower(s) transform(s.begin(),s.end(),s.begin(),::tolower) #define print(arr) for(auto el: arr) cout<<el<<" ";cout<<endl // utility functions shortcuts #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) #define sswap(a,b) {a=a^b;b=a^b;a=a^b;} #define swap(a,b) {auto temp=a; a=b; b=temp;} #define set0(dp) memset(dp,0,sizeof(dp)); #define bits(x) __builtin_popcount(x) #define SORT(v) sort(all(v)) #define endl "\n" #define forr(i,n) for(ll i=0;i<n;i++) #define formatrix(i,n) for(ll i=0;i<n;i++, cout<<"\n") #define eof (scanf("%d" ,&n))!=EOF // declaration shortcuts #define vll vector<ll> #define vvl vector<vector<ll>> #define vpll vector<pair<ll,ll> > #define pll pair<ll,ll> #define ppl pair<ll,pll> #define ull unsigned long long #define ll long long #define mll map< ll, ll > #define sll set< ll > #define uni(v) v.erase(unique(v.begin(),v.end()),v.end()); #define ini(a, v) memset(a, v, sizeof(a)) // Constants constexpr int dx[] = {-1, 0, 1, 0, 1, 1, -1, -1}; constexpr int dy[] = {0, -1, 0, 1, 1, -1, 1, -1}; constexpr ll INF = 1999999999999999997; constexpr int inf= INT_MAX; constexpr int MAXSIZE = int(1e6)+5; constexpr auto PI = 3.14159265358979323846L; constexpr auto oo = numeric_limits<int>::max() / 2 - 2; constexpr auto eps = 1e-6; constexpr auto mod = 1000000007; constexpr auto MOD = 1000000007; constexpr auto MOD9 = 1000000009; constexpr auto maxn = 200006; // Debugging // For reference: https://codeforces.com/blog/entry/65311 #define dbg(...) cout << "[" << #__VA_ARGS__ << "]: "; cout << to_string(__VA_ARGS__) << endl template <typename T, size_t N> int SIZE(const T (&t)[N]){ return N; } template<typename T> int SIZE(const T &t){ return t.size(); } string to_string(string s, int x1=0, int x2=1e9){ return '"' + ((x1 < s.size()) ? s.substr(x1, x2-x1+1) : "") + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(char c){ return string({c}); } template<size_t N> string to_string(bitset<N> &b, int x1=0, int x2=1e9){ string t = ""; for(int __iii__ = min(x1,SIZE(b)), __jjj__ = min(x2, SIZE(b)-1); __iii__ <= __jjj__; ++__iii__){ t += b[__iii__] + '0'; } return '"' + t + '"'; } template <typename A, typename... C> string to_string(A (&v), int x1=0, int x2=1e9, C... coords); int l_v_l_v_l = 0, t_a_b_s = 0; template <typename A, typename B> string to_string(pair<A, B> &p) { l_v_l_v_l++; string res = "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; l_v_l_v_l--; return res; } template <typename A, typename... C> string to_string(A (&v), int x1, int x2, C... coords) { int rnk = rank<A>::value; string tab(t_a_b_s, ' '); string res = ""; bool first = true; if(l_v_l_v_l == 0) res += n_l; res += tab + "["; x1 = min(x1, SIZE(v)), x2 = min(x2, SIZE(v)); auto l = begin(v); advance(l, x1); auto r = l; advance(r, (x2-x1) + (x2 < SIZE(v))); for (auto e = l; e != r; e = next(e)) { if (!first) { res += ", "; } first = false; l_v_l_v_l++; if(e != l){ if(rnk > 1) { res += n_l; t_a_b_s = l_v_l_v_l; }; } else{ t_a_b_s = 0; } res += to_string(*e, coords...); l_v_l_v_l--; } res += "]"; if(l_v_l_v_l == 0) res += n_l; return res; } void dbgs(){;} template<typename Heads, typename... Tails> void dbgs(Heads H, Tails... T){ cout << to_string(H) << " | "; dbgs(T...); } #define dbgm(...) cout << "[" << #__VA_ARGS__ << "]: "; dbgs(__VA_ARGS__); cout << endl; #define n_l '\n' int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll n; cin>>n; forr(i,n) { forr(j,n) { if((i + j)%2) cout<<"B"; else cout<<"W"; } cout<<endl; } }
[ "anmolgupta9557@gmail.com" ]
anmolgupta9557@gmail.com
dae5293442e4970e4bd339184f2219cfaec69a65
4d68064a06d8dc390762564c216b6040c28c2fd1
/0141/724432WA.cpp
c2b9adc1a8f547445286f0e70f86877970ba8b14
[]
no_license
pocke/aoj_codes
ea35fe295cd87080f9af6c9f23d38476820910b5
668e46de83d7f95fbed1f82df058a006fb3e05f6
refs/heads/master
2021-01-23T02:41:23.089223
2014-01-24T04:04:46
2014-01-24T04:04:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,555
cpp
#include <iostream> using namespace std; class Guruguru { public: Guruguru(int n); ~Guruguru(); void Show(); private: char** m_guruguru; int m_n; int m_now_i; int m_now_j; int m_direction; // 0:上 1:右 2:下 3:左 void make_guruguru(); void put_point(); void move_point(); void change_direction(); bool check_point(); }; Guruguru::Guruguru(int n) { m_n = n; m_guruguru = new char*[m_n]; for (int i=0; i<m_n; i++) { m_guruguru[i] = new char[m_n]; } for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { m_guruguru[i][j] = ' '; } } m_now_i = m_n-1; m_now_j = 0; m_direction = 0; make_guruguru(); } Guruguru::~Guruguru() { for (int i=0; i<m_n; i++) { delete[] m_guruguru[i]; } delete[] m_guruguru; } void Guruguru::make_guruguru() { int num = 0; while(true) { put_point(); if (! check_point() ) { if ( num == m_n-1 ) return; change_direction(); num++; } move_point(); } } void Guruguru::put_point() { m_guruguru[m_now_i][m_now_j] = '#'; } void Guruguru::move_point() { switch(m_direction) { case 0: m_now_i--; break; case 1: m_now_j++; break; case 2: m_now_i++; break; case 3: m_now_j--; break; } } void Guruguru::change_direction() { switch(m_direction) { case 3: m_direction = 0; break; default: m_direction++; break; } } bool Guruguru::check_point() { int next_i = m_now_i; int next_j = m_now_j; int next_next_i = next_i; int next_next_j = next_j; switch(m_direction) { case 0: next_i--; next_next_i-=2; break; case 1: next_j++; next_next_j+=2; break; case 2: next_i++; next_next_i+=2; break; case 3: next_j--; next_next_j-=2; break; } if ( next_i < 0 || m_n <= next_i || next_j < 0 || m_n <= next_j ) { return false; } else if ( next_next_i < 0 || m_n <= next_next_i || next_next_j < 0 || m_n <= next_next_j ) { return true; } else { if ( '#' == m_guruguru[next_next_i][next_next_j] ) { return false; } return true; } } void Guruguru::Show() { for (int i=0; i<m_n; i++) { for (int j=0; j<m_n; j++) { cout << m_guruguru[i][j] << flush; } cout << endl; } } int main() { int d; // データセットの個数 cin >> d; for (int dataset=0; dataset<d; dataset++) { int n; // 辺の長さ cin >> n; Guruguru guruguru(n); guruguru.Show(); cout << endl; } }
[ "p.ck.t22@gmail.com" ]
p.ck.t22@gmail.com
0c97d88e93ca3a05fafef3db9a61ceb83f6400f8
d09092dbe69c66e916d8dd76d677bc20776806fe
/.libs/puno_automatic_generated/inc/types/com/sun/star/security/CertificateException.hpp
c0f25e759e25f1d3aca1b96ec39d326779b30f33
[]
no_license
GXhua/puno
026859fcbc7a509aa34ee857a3e64e99a4568020
e2f8e7d645efbde5132b588678a04f70f1ae2e00
refs/heads/master
2020-03-22T07:35:46.570037
2018-07-11T02:19:26
2018-07-11T02:19:26
139,710,567
0
0
null
2018-07-04T11:03:58
2018-07-04T11:03:58
null
UTF-8
C++
false
false
2,164
hpp
#ifndef INCLUDED_COM_SUN_STAR_SECURITY_CERTIFICATEEXCEPTION_HPP #define INCLUDED_COM_SUN_STAR_SECURITY_CERTIFICATEEXCEPTION_HPP #include "sal/config.h" #include "com/sun/star/security/CertificateException.hdl" #include "com/sun/star/uno/SecurityException.hpp" #include "com/sun/star/uno/Type.hxx" #include "cppu/unotype.hxx" namespace com { namespace sun { namespace star { namespace security { inline CertificateException::CertificateException() : ::css::uno::SecurityException() { } inline CertificateException::CertificateException(const ::rtl::OUString& Message_, const ::css::uno::Reference< ::css::uno::XInterface >& Context_) : ::css::uno::SecurityException(Message_, Context_) { } #if !defined LIBO_INTERNAL_ONLY CertificateException::CertificateException(CertificateException const & the_other): ::css::uno::SecurityException(the_other) {} CertificateException::~CertificateException() {} CertificateException & CertificateException::operator =(CertificateException const & the_other) { //TODO: Just like its implicitly-defined counterpart, this function definition is not exception-safe ::css::uno::SecurityException::operator =(the_other); return *this; } #endif } } } } namespace com { namespace sun { namespace star { namespace security { inline ::css::uno::Type const & cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::css::security::CertificateException const *) { static typelib_TypeDescriptionReference * the_type = 0; if ( !the_type ) { const ::css::uno::Type& rBaseType = ::cppu::UnoType< const ::css::uno::SecurityException >::get(); typelib_static_compound_type_init( &the_type, typelib_TypeClass_EXCEPTION, "com.sun.star.security.CertificateException", rBaseType.getTypeLibType(), 0, 0 ); } return * reinterpret_cast< const ::css::uno::Type * >( &the_type ); } } } } } SAL_DEPRECATED("use cppu::UnoType") inline ::css::uno::Type const & SAL_CALL getCppuType(SAL_UNUSED_PARAMETER ::css::security::CertificateException const *) { return ::cppu::UnoType< ::css::security::CertificateException >::get(); } #endif // INCLUDED_COM_SUN_STAR_SECURITY_CERTIFICATEEXCEPTION_HPP
[ "guoxinhua@10.10.12.142" ]
guoxinhua@10.10.12.142
909059235b295f406534258033dd51c9e217b4f4
1d4ef971ba3294a07011fafc08a8be78f6062840
/src/pdb_serial.hpp
d6157465a8bed406f65d555bd9e746fc14576721
[]
no_license
tcgriffith/nsp
153f635b67ef1a598f52b27ee7486f2b8bb3ed3d
021c5b590cbafb51c68ea6f3cbad6cfc3951570d
refs/heads/master
2021-01-25T11:20:37.339250
2017-12-05T23:42:44
2017-12-05T23:42:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,034
hpp
#pragma once #include <fstream> #include <sstream> #include "pdb_molecule.hpp" BEGIN_JN class MolSerial { public: std::fstream m_stream; MolSerial(S out, std::ios::openmode mode) { m_stream.open(out, std::ios::binary | mode); } ~MolSerial() { m_stream.close(); } void write(char c) { m_stream.write(reinterpret_cast<const char*>(&c), sizeof(char)); } void read(char &c) { m_stream.read(reinterpret_cast<char*>(&c), sizeof(char)); } template<typename T, JN_ENABLE(std::is_integral<T>::value)> void write(T n) { short m = short(n); m_stream.write(reinterpret_cast<const char*>(&m), sizeof(short)); } template<typename T, JN_ENABLE(std::is_integral<T>::value)> void read(T &n) { short m; m_stream.read(reinterpret_cast<char*>(&m), sizeof(short)); n = T(m); } template<typename T, JN_ENABLE(std::is_floating_point<T>::value)> void write(T n) { float m = float(n); m_stream.write(reinterpret_cast<const char*>(&m), sizeof(float)); } template<typename T, JN_ENABLE(std::is_floating_point<T>::value)> void read(T &n) { float m; m_stream.read(reinterpret_cast<char*>(&m), sizeof(float)); n = T(m); } void write(const S &s) { //write(s.size()); m_stream.write(s.c_str(), s.size() + 1); } void read(S &s) { char c[2]; std::ostringstream stream; while (true) { m_stream.read(c, 1); if (c[0] == '\0') break; stream << c[0]; } s = stream.str(); } template<typename T1, typename T2, typename... Rest> void write(T1 && t1, T2 && t2, Rest && ...rest) { write(t1); write(t2, rest...); } template<typename T1, typename T2, typename... Rest> void read(T1 && t1, T2 && t2, Rest && ...rest) { read(t1); read(t2, rest...); } void write(const Atom &atom) { write('A', atom.name, atom.num, atom.mass, atom[0], atom[1], atom[2]); } void read(Atom &atom) { read(atom.name, atom.num, atom.mass, atom[0], atom[1], atom[2]); } void write(const Residue &res) { write('R', res.name, res.num, res.m_cg); for (auto && atom : res) { write(atom); } write('r'); } void read(Residue &res) { char c; read(res.name, res.num, res.m_cg); while (true) { read(c); if (c == 'r') { return; } else if (c == 'A') { res.push_back(Atom{}); read(res.back()); } else { throw "This is not a standard '.jn' file! Illegal " + c; } } } void write(const Chain &chain) { write('C', chain.name, chain.type, chain.model_name, chain.m_cg); for (auto && res : chain) { write(res); } write('c'); } void read(Chain &chain) { char c; read(chain.name, chain.type, chain.model_name, chain.m_cg); while (true) { read(c); if (c == 'c') { return; } else if (c == 'R') { chain.push_back(Residue{}); read(chain.back()); } else { throw "This is not a standard '.jn' file! Illegal " + c; } } } void write(const Model &model) { write('M', model.name, model.num, model.type, model.m_cg); for (auto && chain : model) { write(chain); } write('m'); } void read(Model &model) { char c; read(model.name, model.num, model.type, model.m_cg); while (true) { read(c); if (c == 'm') { return; } else if (c == 'C') { model.push_back(Chain{}); read(model.back()); } else { throw "This is not a standard '.jn' file! Illegal " + c; } } } void write_mol(S filename) { for_each_model(filename, [this](const Model &model, int i) { write(model); }); write('o'); } void write(const Molecule &mol) { for (auto && model : mol) { write(model); } write('o'); } void read(Molecule &mol) { char c; while (true) { read(c); if (c == 'o') { break; } else if (c == 'M') { mol.push_back(Model{}); read(mol.back()); } else { throw "This is not a standard '.jn' file ! Illegal " + c; } } } }; }
[ "wj_hust08@hust.edu.cn" ]
wj_hust08@hust.edu.cn
a618b827c1f9ff5821245a43536125328fec85bd
8fbc0a30921bee6ec0161b9e263fb3cef2a3c0a4
/bzoj/3573.cpp
a46e40def2cbef538abed01c72c4cf37218614f5
[ "WTFPL" ]
permissive
swwind/code
57d0d02c166d1c64469e0361fc14355d866079a8
c240122a236e375e43bcf145d67af5a3a8299298
refs/heads/master
2023-06-17T15:25:07.412105
2023-05-29T11:21:31
2023-05-29T11:21:31
93,724,691
3
0
null
null
null
null
UTF-8
C++
false
false
1,051
cpp
#include <bits/stdc++.h> #define N 500050 #define ll long long using namespace std; double a[N], s[N], val[N]; int d[N], last[N], tmp = 1, ans, n, cnt, x, y; struct node{ int to, nxt; node(){} node(int x, int y):to(x), nxt(y){} }e[N<<1]; void insert(int x, int y){ e[++cnt] = node(y, last[x]); last[x] = cnt; e[++cnt] = node(x, last[y]); last[y] = cnt; } void dfs(int x, int fa){ for(int i = last[x]; i; i = e[i].nxt) if(e[i].to != fa) s[e[i].to] = s[x] + log(d[x]), dfs(e[i].to, x); } int main(){ scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", a+i); for(int i = 1; i < n; i++) scanf("%d%d", &x, &y), insert(x, y), d[x]++, d[y]++; for(int i = 2; i <= n; i++) d[i]--; s[1] = log(1); dfs(1, 0); for(int i = 1; i <= n; i++) val[i] = s[i] + log(a[i]); sort(val+1, val+n+1); for(int i = 2; i <= n; i++) if(val[i]-val[i-1] < 1e-5) tmp++; else ans = max(ans, tmp), tmp = 1; ans = max(ans, tmp); printf("%d\n", n-ans); return 0; } //Copy from hzwer.com
[ "swwind233@gmail.com" ]
swwind233@gmail.com
b7c808305cb6f5253b146635348dd8c5ade238ca
2d627fbba7bfb4a83cc7fd70c730e1ba5952e199
/hackerrank/counting valles.cpp
1b735d7a285e8f40a8f73101a9a64db21ce62795
[]
no_license
shivamsatyam/datastructure-and-algorithm
8f8660ef576b59113ede3deb7b4e6188af4f2bac
5b2a14f1e05f347ae2515dce59c60743fa901a3b
refs/heads/master
2023-02-10T00:13:23.019148
2021-01-14T14:55:13
2021-01-14T14:55:13
329,647,058
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
#include<iostream> #include<string> using namespace std; int main() { int n; cin>>n; string s; cin>>s; int sea = 0; int count=0; for(int i=0;i<n;i++){ if(s.at(i)=='U'){ ++sea; }else{ --sea; } if(sea==0){ ++count; } } cout<<count<<"\n"; return 0; }
[ "softgooddeveloper@gmail.com" ]
softgooddeveloper@gmail.com