blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
29f60a9cda5c00aabf4a5f90c88b8018c1c030d4
f13e5bf7cbb3ebaf59090df33d87a082398136e9
/Chapter3/STACK.h
b9273a6ccd114f8a8ce516ee69e1c66770a06de1
[]
no_license
LGHigh/DSAAC
0f45499f55094ce243a5b5d73bb0bd359ac1808f
6cd0a21ca7cc90f06c91656d4d35dba9955baf87
refs/heads/master
2021-07-12T06:20:16.510653
2017-10-12T08:48:36
2017-10-12T08:48:36
105,109,292
0
0
null
null
null
null
UTF-8
C++
false
false
515
h
STACK.h
/*Dedication to public interests, Acquisition of all-round capability, Aspiration for progress with each passing day.*/ /*using List*/ #ifndef _Stack_h #define _Stack_h class Stack; typedef class Stack* PStack; typedef int ElementType; class Stack{ public: Stack(); bool IsEmpty(PStack S); void DisposeStack(PStack S); void MakeEmpty(PStack S); void Push(ElementType X,PStack S); ElementType Top(PStack S); void Pop(PStack); private: ElementType Element; PStack Next; }; #endif /*_Stack_h*/
93add5d9d5badfdde3284d449b61a28efdbd985d
01de08ef090cbb633f36389a815c0ff101b72fc1
/HEEPeScale/highMassRes.h
7ba4510db356d155dfb5080fd8a61f1a21171baf
[]
no_license
thomreis/myCmsCode
9cb2a961c081c08434716670842dcdb915fafb0b
b987e3c01207047131ccbf0037c6a4280f65437f
refs/heads/master
2021-01-10T21:07:29.832064
2015-02-09T14:52:06
2015-02-09T14:52:06
11,369,806
0
1
null
null
null
null
UTF-8
C++
false
false
22,287
h
highMassRes.h
//=============================================================== // RooFit Macro to perform unbinned likelihood fit //================================================================ #ifndef HighMassRes_h #define HighMassRes_h #include <sstream> #include <iostream> #include <utility> #include <vector> #include "RooAbsPdf.h" #include "RooAddPdf.h" #include "RooArgList.h" #include "RooBreitWigner.h" #include "RooCBShape.h" #include "RooDataHist.h" #include "RooDataSet.h" #include "RooExponential.h" #include "RooFFTConvPdf.h" #include "RooFitResult.h" #include "RooFormula.h" #include "RooGaussian.h" #include "RooGenericPdf.h" #include "RooHist.h" #include "RooPlot.h" #include "RooRealVar.h" #include "RooWorkspace.h" #include "TFile.h" #include "TCanvas.h" #include "TTree.h" #include "THashTable.h" #include "TH1F.h" #include "TF1.h" #include "TROOT.h" #include "TStopwatch.h" #include "TStyle.h" #include "TLatex.h" #include "TString.h" #include "TPaveText.h" #include "TLegend.h" #include "TLegendEntry.h" #include "tdrstyle.C" #ifndef __CINT__ #include "RooGlobalFunc.h" #include "RooDCBShape.h" #endif using namespace RooFit; class HighMassRes { public: HighMassRes(const char *_inFile = "./eScaleEvents19712pb-1.root", const int _lumi = 19712); inline virtual ~HighMassRes() {}; void RunCryBall(); void PlotRes(); void CompareCryBall(); protected: const char *inFile; int lumi; const unsigned int fitModelType; // (0, 1) = (CB, double CB) const unsigned int fitModelType2; // (0, 1) = (CB, double CB) double cutoff_cb; const char *plotOpt; const int nBins; bool plotReg[7]; bool mcOnly; int eleEbReg; const int font; const bool plotPull; const bool saveFitsAsPdf; const bool saveFitsAsPng; const bool saveFitsAsRoot; const bool saveResAsPdf; const bool saveResAsPng; const bool saveResAsRoot; const char *fileNameExtra; const char *plotDir; const bool useRootTermForFit; std::vector<std::pair<Float_t, Float_t> > sigmaExtras; std::vector<const char *> dyTreeNames; std::vector<Float_t> dyFitRanges; std::vector<std::pair<Int_t, const char *> > zPrimeGenMasses; unsigned int ssmStart; const int fitColorDy; const int fitColorZpPsi; const int fitColorZpSsm; const int fitColorRes; const int fit2ColorDy; const int fit2ColorZpPsi; const int fit2ColorZpSsm; const int fitColorRes2; std::vector<TString> regTxt; std::vector<TString> regFileNameSuffix; TString biasName; TString sigmaName; TString cutLName; TString cutRName; TString powerLName; TString powerRName; // histos for the DY samples std::vector<TH1F *> sigmaHistos; std::vector<TH1F *> dmHistos; std::vector<TH1F *> dmHistosRel; std::vector<TH1F *> acbHistos; std::vector<TH1F *> ncbHistos; std::vector<TH1F *> ardcbHistos; std::vector<TH1F *> nrdcbHistos; // histos for the Z'PSI signal samples std::vector<TH1F *> sigmaHistosZpPsi; std::vector<TH1F *> dmHistosZpPsi; std::vector<TH1F *> dmHistosRelZpPsi; std::vector<TH1F *> acbHistosZpPsi; std::vector<TH1F *> ncbHistosZpPsi; std::vector<TH1F *> ardcbHistosZpPsi; std::vector<TH1F *> nrdcbHistosZpPsi; // histos for the Z'SSM signal samples std::vector<TH1F *> sigmaHistosZpSsm; std::vector<TH1F *> dmHistosZpSsm; std::vector<TH1F *> dmHistosRelZpSsm; std::vector<TH1F *> acbHistosZpSsm; std::vector<TH1F *> ncbHistosZpSsm; std::vector<TH1F *> ardcbHistosZpSsm; std::vector<TH1F *> nrdcbHistosZpSsm; std::vector<TH1F *> sigmaDCBHistos; std::vector<TH1F *> sigmaDCBHistosZpPsi; std::vector<TH1F *> sigmaDCBHistosZpSsm; RooWorkspace * cryBall( TTree* tree, const int regions = 3, double minMass = 500, double maxMass = 600, double trueMassMin = 500, double trueMassMax = 600, double cutoff_cb = 1.0, const char* plotOpt = "NEU", const int nBins = 80, const unsigned int fitModelType = 1); // (0, 1) = (CB, double CB) }; #endif HighMassRes::HighMassRes(const char *_inFile, const int _lumi) : fitModelType(1), // (0, 1) = (CB, double CB) fitModelType2(1), // (0, 1) = (CB, double CB) cutoff_cb(2.), plotOpt("NEU"), nBins(80), font(42), plotPull(true), saveFitsAsPdf(1), saveFitsAsPng(1), saveFitsAsRoot(1), saveResAsPdf(1), saveResAsPng(1), saveResAsRoot(1), fileNameExtra(""), plotDir("./plots_20141014_res_splitRangeFit/"), //plotDir("./plots_20141014_bb_noSigmaExtra/"), //plotDir("./plots_20141014_bb_eleEtaSmaller0p7/"), //plotDir("./plots_20141014_bb_eleEtaLarger0p7/"), //plotDir("./plots_20141014_bb_oneEleEtaSmaller0p7/"), //plotDir("./plots_20141014_bb_oneEleEtaLarger0p7/"), //plotDir("./plots_20141014_bb_oneEleEtaLargerOneSmaller0p7/"), useRootTermForFit(0), fitColorDy(kRed), fitColorZpPsi(kGreen+1), fitColorZpSsm(kMagenta+1), fitColorRes(kBlue), fit2ColorDy(kCyan+1), fit2ColorZpPsi(kOrange+7), fit2ColorZpSsm(kOrange), fitColorRes2(kOrange-3), biasName("#Deltam_{CB}"), sigmaName("#sigma_{CB}"), cutLName("#alpha_{CB}"), cutRName("#alpha_{CB}"), powerLName("n_{CB}"), powerRName("n_{CB}") { inFile = _inFile; lumi = _lumi; mcOnly = 0; // no use of sigma_extra eleEbReg = 0; // electron eta regions. 0: full, 1: 2e<0.7, 2: 2e>=0.7, 3: 1e<0.7, 4: 1e>=0.7, 5: 1e<0.7 && 1e>=0.7 plotReg[0] = 1; // EB-EB plotReg[1] = 1; // EB-EE plotReg[2] = 0; // EB-EB + EB-EE plotReg[3] = 1; // EE-EE plotReg[4] = 0; // EB-EB + EE-EE plotReg[5] = 0; // EB-EE + EE-EE plotReg[6] = 0; // EB-EB + EB-EE + EE-EE // powheg START53 19.7fb-1 HEEP v4.1 double Crystal Ball sigmaExtras.reserve(7); if (mcOnly) { sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); } else { if (eleEbReg == 1) sigmaExtras.push_back(std::pair<Float_t, Float_t> (0.70, 0.01)); // for |eta_e1| < 0.7 && |eta_e2| < 0.7 else if (eleEbReg == 2) sigmaExtras.push_back(std::pair<Float_t, Float_t> (0.96, 0.01)); // for |eta_e1| >= 0.7 && |eta_e2| >= 0.7 else if (eleEbReg == 3) sigmaExtras.push_back(std::pair<Float_t, Float_t> (0.69, 0.01)); // for |eta_e1| < 0.7 || |eta_e2| < 0.7 else if (eleEbReg == 4) sigmaExtras.push_back(std::pair<Float_t, Float_t> (0.84, 0.01)); // for |eta_e1| >= 0.7 || |eta_e2| >= 0.7 else if (eleEbReg == 5) sigmaExtras.push_back(std::pair<Float_t, Float_t> (0.84, 0.01)); // for (|eta_e1| < 0.7 && |eta_e2| >= 0.7) || (|eta_e1| >= 0.7 && |eta_e2| < 0.7) else sigmaExtras.push_back(std::pair<Float_t, Float_t> (0.73, 0.01)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0.93, 0.01)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (1.2, 0.01)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); sigmaExtras.push_back(std::pair<Float_t, Float_t> (0., 0.)); } dyFitRanges.reserve(16); dyFitRanges.push_back(100.); dyFitRanges.push_back(120.); dyFitRanges.push_back(200.); dyFitRanges.push_back(300.); dyFitRanges.push_back(400.); dyFitRanges.push_back(500.); dyFitRanges.push_back(600.); dyFitRanges.push_back(700.); dyFitRanges.push_back(800.); dyFitRanges.push_back(1000.); dyFitRanges.push_back(1250.); dyFitRanges.push_back(1500.); dyFitRanges.push_back(1750.); dyFitRanges.push_back(2000.); dyFitRanges.push_back(2250.); dyFitRanges.push_back(2500.); dyFitRanges.push_back(3500.); zPrimeGenMasses.reserve(9); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (750, "eleZp750Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (1000, "eleZp1000Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (1250, "eleZp1250Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (1500, "eleZp1500Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (1750, "eleZp1750Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (2000, "eleZp2000Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (2250, "eleZp2250Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (3000, "eleZp3000Tree")); zPrimeGenMasses.push_back(std::pair<Int_t, const char *> (2250, "eleZpSsm2250Tree")); ssmStart = 8; dyTreeNames.reserve(10); dyTreeNames.push_back("eleDY20Tree"); dyTreeNames.push_back("eleDY120Tree"); dyTreeNames.push_back("eleDY200Tree"); dyTreeNames.push_back("eleDY400Tree"); dyTreeNames.push_back("eleDY500Tree"); dyTreeNames.push_back("eleDY700Tree"); dyTreeNames.push_back("eleDY800Tree"); dyTreeNames.push_back("eleDY1000Tree"); dyTreeNames.push_back("eleDY1500Tree"); dyTreeNames.push_back("eleDY2000Tree"); regTxt.reserve(7); regTxt.push_back("EB-EB"); regTxt.push_back("EB-EE"); regTxt.push_back("EB-EB + EB-EE"); regTxt.push_back("EE-EE"); regTxt.push_back("EB-EB + EE-EE"); regTxt.push_back("EB-EE + EE-EE"); regTxt.push_back("EB-EB + EB-EE + EE-EE"); regFileNameSuffix.reserve(7); regFileNameSuffix.push_back("BB"); regFileNameSuffix.push_back("BE"); regFileNameSuffix.push_back("BBBE"); regFileNameSuffix.push_back("EE"); regFileNameSuffix.push_back("BBEE"); regFileNameSuffix.push_back("BEEE"); regFileNameSuffix.push_back("BBBEEE"); if (fitModelType > 0) { biasName = "#Deltam_{DCB}"; sigmaName = "#sigma_{DCB}"; cutLName = "#alpha_{L}^{DCB}"; cutRName = "#alpha_{R}^{DCB}"; powerLName = "n_{L}^{DCB}"; powerRName = "n_{R}^{DCB}"; } // set up histograms for the high mass resolution parametrisation Int_t nBinsHisto = dyFitRanges.size() - 1; Float_t binArray[16]; for (Int_t it = 0; it <= nBinsHisto; ++it) binArray[it] = dyFitRanges[it]; // histos for the DY samples sigmaHistos.reserve(4); sigmaHistos.push_back(new TH1F("sigmaBB", "sigma of fitted function EB-EB", nBinsHisto, binArray)); sigmaHistos.push_back(new TH1F("sigmaBE", "sigma of fitted function EB-EE", nBinsHisto, binArray)); sigmaHistos.push_back(new TH1F("sigmaBBBE", "sigma of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); sigmaHistos.push_back(new TH1F("sigmaEE", "sigma of fitted function EE-EE", nBinsHisto, binArray)); dmHistos.reserve(4); dmHistos.push_back(new TH1F("dmBB", "dm of fitted function EB-EB", nBinsHisto, binArray)); dmHistos.push_back(new TH1F("dmBE", "dm of fitted function EB-EE", nBinsHisto, binArray)); dmHistos.push_back(new TH1F("dmBBBE", "dm of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); dmHistos.push_back(new TH1F("dmEE", "dm of fitted function EE-EE", nBinsHisto, binArray)); dmHistosRel.reserve(4); dmHistosRel.push_back(new TH1F("dmRelBB", "relative dm of fitted function EB-EB", nBinsHisto, binArray)); dmHistosRel.push_back(new TH1F("dmRelBE", "relative dm of fitted function EB-EE", nBinsHisto, binArray)); dmHistosRel.push_back(new TH1F("dmRelBBBE", "relative dm of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); dmHistosRel.push_back(new TH1F("dmRelEE", "relative dm of fitted function EE-EE", nBinsHisto, binArray)); acbHistos.reserve(4); acbHistos.push_back(new TH1F("acbBB", "acb of fitted function EB-EB", nBinsHisto, binArray)); acbHistos.push_back(new TH1F("acbBE", "acb of fitted function EB-EE", nBinsHisto, binArray)); acbHistos.push_back(new TH1F("acbBBBE", "acb of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); acbHistos.push_back(new TH1F("acbEE", "acb of fitted function EE-EE", nBinsHisto, binArray)); ncbHistos.reserve(4); ncbHistos.push_back(new TH1F("ncbBB", "ncb of fitted function EB-EB", nBinsHisto, binArray)); ncbHistos.push_back(new TH1F("ncbBE", "ncb of fitted function EB-EE", nBinsHisto, binArray)); ncbHistos.push_back(new TH1F("ncbBBBE", "ncb of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); ncbHistos.push_back(new TH1F("ncbEE", "ncb of fitted function EE-EE", nBinsHisto, binArray)); ardcbHistos.reserve(4); ardcbHistos.push_back(new TH1F("ardcbBB", "ardcb of fitted function EB-EB", nBinsHisto, binArray)); ardcbHistos.push_back(new TH1F("ardcbBE", "ardcb of fitted function EB-EE", nBinsHisto, binArray)); ardcbHistos.push_back(new TH1F("ardcbBBBE", "ardcb of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); ardcbHistos.push_back(new TH1F("ardcbEE", "ardcb of fitted function EE-EE", nBinsHisto, binArray)); nrdcbHistos.reserve(4); nrdcbHistos.push_back(new TH1F("nrdcbBB", "nrdcb of fitted function EB-EB", nBinsHisto, binArray)); nrdcbHistos.push_back(new TH1F("nrdcbBE", "nrdcb of fitted function EB-EE", nBinsHisto, binArray)); nrdcbHistos.push_back(new TH1F("nrdcbBBBE", "nrdcb of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); nrdcbHistos.push_back(new TH1F("nrdcbEE", "nrdcb of fitted function EE-EE", nBinsHisto, binArray)); // histos for the Z'PSI signal samples sigmaHistosZpPsi.reserve(4); sigmaHistosZpPsi.push_back(new TH1F("sigmaZpPsiBB", "sigma of fitted function for Signal MC EB-EB", 338, 120., 3500.)); sigmaHistosZpPsi.push_back(new TH1F("sigmaZpPsiBE", "sigma of fitted function for Signal MC EB-EE", 338, 120., 3500.)); sigmaHistosZpPsi.push_back(new TH1F("sigmaZpPsiBBBE", "sigma of fitted function for Signal MC EB-EB + EB-EE", 338, 120., 3500.)); sigmaHistosZpPsi.push_back(new TH1F("sigmaZpPsiEE", "sigma of fitted function for Signal MC EE-EE", 338, 120., 3500.)); dmHistosZpPsi.reserve(4); dmHistosZpPsi.push_back(new TH1F("dmZpPsiBB", "dm of fitted function EB-EB", 338, 120., 3500.)); dmHistosZpPsi.push_back(new TH1F("dmZpPsiBE", "dm of fitted function EB-EE", 338, 120., 3500.)); dmHistosZpPsi.push_back(new TH1F("dmZpPsiBBBE", "dm of fitted function EB-EB + EB-EE", 338, 120., 3500.)); dmHistosZpPsi.push_back(new TH1F("dmZpPsiEE", "dm of fitted function EE-EE", 338, 120., 3500.)); dmHistosRelZpPsi.reserve(4); dmHistosRelZpPsi.push_back(new TH1F("dmRelZpPsiBB", "relative dm of fitted function EB-EB", 338, 120., 3500.)); dmHistosRelZpPsi.push_back(new TH1F("dmRelZpPsiBE", "relative dm of fitted function EB-EE", 338, 120., 3500.)); dmHistosRelZpPsi.push_back(new TH1F("dmRelZpPsiBBBE", "relative dm of fitted function EB-EB + EB-EE", 338, 120., 3500.)); dmHistosRelZpPsi.push_back(new TH1F("dmRelZpPsiEE", "relative dm of fitted function EE-EE", 338, 120., 3500.)); acbHistosZpPsi.reserve(4); acbHistosZpPsi.push_back(new TH1F("acbZpPsiBB", "acb of fitted function EB-EB", 338, 120., 3500.)); acbHistosZpPsi.push_back(new TH1F("acbZpPsiBE", "acb of fitted function EB-EE", 338, 120., 3500.)); acbHistosZpPsi.push_back(new TH1F("acbZpPsiBBBE", "acb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); acbHistosZpPsi.push_back(new TH1F("acbZpPsiEE", "acb of fitted function EE-EE", 338, 120., 3500.)); ncbHistosZpPsi.reserve(4); ncbHistosZpPsi.push_back(new TH1F("ncbZpPsiBB", "ncb of fitted function EB-EB", 338, 120., 3500.)); ncbHistosZpPsi.push_back(new TH1F("ncbZpPsiBE", "ncb of fitted function EB-EE", 338, 120., 3500.)); ncbHistosZpPsi.push_back(new TH1F("ncbZpPsiBBBE", "ncb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); ncbHistosZpPsi.push_back(new TH1F("ncbZpPsiEE", "ncb of fitted function EE-EE", 338, 120., 3500.)); ardcbHistosZpPsi.reserve(4); ardcbHistosZpPsi.push_back(new TH1F("ardcbZpPsiBB", "ardcb of fitted function EB-EB", 338, 120., 3500.)); ardcbHistosZpPsi.push_back(new TH1F("ardcbZpPsiBE", "ardcb of fitted function EB-EE", 338, 120., 3500.)); ardcbHistosZpPsi.push_back(new TH1F("ardcbZpPsiBBBE", "ardcb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); ardcbHistosZpPsi.push_back(new TH1F("ardcbZpPsiEE", "ardcb of fitted function EE-EE", 338, 120., 3500.)); nrdcbHistosZpPsi.reserve(4); nrdcbHistosZpPsi.push_back(new TH1F("nrdcbZpPsiBB", "nrdcb of fitted function EB-EB", 338, 120., 3500.)); nrdcbHistosZpPsi.push_back(new TH1F("nrdcbZpPsiBE", "nrdcb of fitted function EB-EE", 338, 120., 3500.)); nrdcbHistosZpPsi.push_back(new TH1F("nrdcbZpPsiBBBE", "nrdcb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); nrdcbHistosZpPsi.push_back(new TH1F("nrdcbZpPsiEE", "nrdcb of fitted function EE-EE", 338, 120., 3500.)); // histos for the Z'SSM signal samples sigmaHistosZpSsm.reserve(4); sigmaHistosZpSsm.push_back(new TH1F("sigmaZpSsmBB", "sigma of fitted function for Signal MC EB-EB", 338, 120., 3500.)); sigmaHistosZpSsm.push_back(new TH1F("sigmaZpSsmBE", "sigma of fitted function for Signal MC EB-EE", 338, 120., 3500.)); sigmaHistosZpSsm.push_back(new TH1F("sigmaZpSsmBBBE", "sigma of fitted function for Signal MC EB-EB + EB-EE", 338, 120., 3500.)); sigmaHistosZpSsm.push_back(new TH1F("sigmaZpSsmEE", "sigma of fitted function for Signal MC EE-EE", 338, 120., 3500.)); dmHistosZpSsm.reserve(4); dmHistosZpSsm.push_back(new TH1F("dmZpSsmBB", "dm of fitted function EB-EB", 338, 120., 3500.)); dmHistosZpSsm.push_back(new TH1F("dmZpSsmBE", "dm of fitted function EB-EE", 338, 120., 3500.)); dmHistosZpSsm.push_back(new TH1F("dmZpSsmBBBE", "dm of fitted function EB-EB + EB-EE", 338, 120., 3500.)); dmHistosZpSsm.push_back(new TH1F("dmZpSsmEE", "dm of fitted function EE-EE", 338, 120., 3500.)); dmHistosRelZpSsm.reserve(4); dmHistosRelZpSsm.push_back(new TH1F("dmRelZpSsmBB", "relative dm of fitted function EB-EB", 338, 120., 3500.)); dmHistosRelZpSsm.push_back(new TH1F("dmRelZpSsmBE", "relative dm of fitted function EB-EE", 338, 120., 3500.)); dmHistosRelZpSsm.push_back(new TH1F("dmRelZpSsmBBBE", "relative dm of fitted function EB-EB + EB-EE", 338, 120., 3500.)); dmHistosRelZpSsm.push_back(new TH1F("dmRelZpSsmEE", "relative dm of fitted function EE-EE", 338, 120., 3500.)); acbHistosZpSsm.reserve(4); acbHistosZpSsm.push_back(new TH1F("acbZpSsmBB", "acb of fitted function EB-EB", 338, 120., 3500.)); acbHistosZpSsm.push_back(new TH1F("acbZpSsmBE", "acb of fitted function EB-EE", 338, 120., 3500.)); acbHistosZpSsm.push_back(new TH1F("acbZpSsmBBBE", "acb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); acbHistosZpSsm.push_back(new TH1F("acbZpSsmEE", "acb of fitted function EE-EE", 338, 120., 3500.)); ncbHistosZpSsm.reserve(4); ncbHistosZpSsm.push_back(new TH1F("ncbZpSsmBB", "ncb of fitted function EB-EB", 338, 120., 3500.)); ncbHistosZpSsm.push_back(new TH1F("ncbZpSsmBE", "ncb of fitted function EB-EE", 338, 120., 3500.)); ncbHistosZpSsm.push_back(new TH1F("ncbZpSsmBBBE", "ncb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); ncbHistosZpSsm.push_back(new TH1F("ncbZpSsmEE", "ncb of fitted function EE-EE", 338, 120., 3500.)); ardcbHistosZpSsm.reserve(4); ardcbHistosZpSsm.push_back(new TH1F("ardcbZpSsmBB", "ardcb of fitted function EB-EB", 338, 120., 3500.)); ardcbHistosZpSsm.push_back(new TH1F("ardcbZpSsmBE", "ardcb of fitted function EB-EE", 338, 120., 3500.)); ardcbHistosZpSsm.push_back(new TH1F("ardcbZpSsmBBBE", "ardcb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); ardcbHistosZpSsm.push_back(new TH1F("ardcbZpSsmEE", "ardcb of fitted function EE-EE", 338, 120., 3500.)); nrdcbHistosZpSsm.reserve(4); nrdcbHistosZpSsm.push_back(new TH1F("nrdcbZpSsmBB", "nrdcb of fitted function EB-EB", 338, 120., 3500.)); nrdcbHistosZpSsm.push_back(new TH1F("nrdcbZpSsmBE", "nrdcb of fitted function EB-EE", 338, 120., 3500.)); nrdcbHistosZpSsm.push_back(new TH1F("nrdcbZpSsmBBBE", "nrdcb of fitted function EB-EB + EB-EE", 338, 120., 3500.)); nrdcbHistosZpSsm.push_back(new TH1F("nrdcbZpSsmEE", "nrdcb of fitted function EE-EE", 338, 120., 3500.)); /////// sigmaDCBHistos.reserve(4); sigmaDCBHistos.push_back(new TH1F("sigmaDCBBB", "sigma of fitted function EB-EB", nBinsHisto, binArray)); sigmaDCBHistos.push_back(new TH1F("sigmaDCBBE", "sigma of fitted function EB-EE", nBinsHisto, binArray)); sigmaDCBHistos.push_back(new TH1F("sigmaDCBBBBE", "sigma of fitted function EB-EB + EB-EE", nBinsHisto, binArray)); sigmaDCBHistos.push_back(new TH1F("sigmaDCBEE", "sigma of fitted function EE-EE", nBinsHisto, binArray)); sigmaDCBHistosZpPsi.reserve(4); sigmaDCBHistosZpPsi.push_back(new TH1F("sigmaDCBZpPsiBB", "sigma of fitted function for Signal MC EB-EB", 338, 120., 3500.)); sigmaDCBHistosZpPsi.push_back(new TH1F("sigmaDCBZpPsiBE", "sigma of fitted function for Signal MC EB-EE", 338, 120., 3500.)); sigmaDCBHistosZpPsi.push_back(new TH1F("sigmaDCBZpPsiBBBE", "sigma of fitted function for Signal MC EB-EB + EB-EE", 338, 120., 3500.)); sigmaDCBHistosZpPsi.push_back(new TH1F("sigmaDCBZpPsiEE", "sigma of fitted function for Signal MC EE-EE", 338, 120., 3500.)); sigmaDCBHistosZpSsm.reserve(4); sigmaDCBHistosZpSsm.push_back(new TH1F("sigmaDCBZpSsmBB", "sigma of fitted function for Signal MC EB-EB", 338, 120., 3500.)); sigmaDCBHistosZpSsm.push_back(new TH1F("sigmaDCBZpSsmBE", "sigma of fitted function for Signal MC EB-EE", 338, 120., 3500.)); sigmaDCBHistosZpSsm.push_back(new TH1F("sigmaDCBZpSsmBBBE", "sigma of fitted function for Signal MC EB-EB + EB-EE", 338, 120., 3500.)); sigmaDCBHistosZpSsm.push_back(new TH1F("sigmaDCBZpSsmEE", "sigma of fitted function for Signal MC EE-EE", 338, 120., 3500.)); TH1::SetDefaultSumw2(kTRUE); }
9442b3fb7008421cfc992bcaf4f816626bc08ac5
5ecb9e70525969cea8862ab666592c8316afee86
/obj/virtural2.cpp
68257b95c12d37301eb0c6bf060f3a0c4a606df1
[ "MIT" ]
permissive
fengpf/loveCplusplus
c4e5d6f57641fb61faa005d8d0298c8ed978fe8b
44d95727df75dbe770c96fda1f512e1dd9157b89
refs/heads/master
2020-09-24T13:55:14.532489
2019-12-04T11:55:18
2019-12-04T11:55:18
225,773,862
0
0
null
null
null
null
UTF-8
C++
false
false
619
cpp
virtural2.cpp
// // Created by fpf on 2019-12-04. // //class 类名{//类体 // //virtual 返回类型 函数名(形参列表)// 虚函数 // ... //}; #include <iostream> using namespace std; class Base{ public:virtual void print(){ cout<<"Base"<<endl; } }; class Derived:public Base{ public:void print(){ cout<<"Derived"<<endl; } }; // pf 指针指向基类成员函数的指针 void display(Base *p, void(Base::*pf)()){ (p->*pf)();//p指向的对象 } int main(){ Derived d; Base b; display(&d, &Base::print); display(&b, &Base::print); return 0; }
c74e77680f06e3a6f3fc460c3607daf51d3ac16b
b8eb357354eeef47b1675031a0b350dd297a81ef
/1249. Minimum Remove to Make Valid Parentheses - Medium - LowPass/cpp2.cpp
7543a8136db98b3c97cac02bc82578efb6ef5979
[]
no_license
wsyzxxxx/LeetcodeGOGOGO
3e9dd70f01db220048683688f71e7b88d3921d08
48418ce917baf05390f1bc8df35aba9e0516f97b
refs/heads/master
2021-11-26T17:29:23.065653
2021-10-29T18:23:32
2021-10-29T18:23:32
195,494,436
0
0
null
null
null
null
UTF-8
C++
false
false
872
cpp
cpp2.cpp
class Solution { public: string minRemoveToMakeValid(string s) { std::string tmp; int count = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == ')' && count == 0) { continue; } else if (s[i] == '(') { count++; } else if (s[i] == ')') { count--; } tmp += s[i]; } std::string result; count = 0; for (int i = tmp.size()-1; i >= 0; i--) { if (tmp[i] == '(' && count == 0) { continue; } else if (tmp[i] == '(') { count++; } else if (tmp[i] == ')') { count--; } result += tmp[i]; } std::reverse(result.begin(), result.end()); return result; } };
d280de46a1851a1766742aa52242eacf767b3df5
772a44ecf4bbea6c6d25c568844b94fd9b4509ce
/util.h
76e3e70535c5b50fb431d45b8f8733691780fa03
[]
no_license
DreadWingKnight/cwsa
6887fb98f03d10b38c59d840bd957dd3e6769e36
9cffc3a9090374e0132cc064926126df00212111
refs/heads/master
2016-08-06T12:22:08.336766
2006-02-08T20:10:37
2006-02-08T20:10:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
456
h
util.h
#ifndef UTIL_H #define UTIL_H #include <stdio.h> #include <time.h> #include <map> #include <string> #include <vector> #include <utility> using namespace std; #ifdef WIN32 typedef __int64 int64; typedef unsigned __int64 uint64; #else typedef long long int64; typedef unsigned long long uint64; #endif void UTIL_MakeFile( const char *szFile, string strContents ); string UTIL_StringToHash( const string &strString ); #endif
486688a1e1206bee23fe5adebe66628b90cde742
fc2d01d1afa08ffc46c23901163c37e679c3beaf
/Renderer/MaterialAnimationFactory.h
e47ac7a70450b95bea29aac8ce70c8f2e74a9aab
[]
no_license
seblef/ShadowEngine
a9428607b49cdd41eb22dcbd8504555454e26a0c
fba95e910c63269bfe0a05ab639dc78b6c16ab8b
refs/heads/master
2023-02-14T19:08:25.878492
2021-01-08T16:16:44
2021-01-08T16:16:44
113,681,956
1
0
null
null
null
null
UTF-8
C++
false
false
440
h
MaterialAnimationFactory.h
#ifndef _MATERIALANIMATIONFACTORY_H_ #define _MATERIALANIMATIONFACTORY_H_ #include "MaterialAnimation.h" class MaterialAnimationFactory { public: MaterialAnimationFactory() {} static MaterialAnimation* createAnimation(const string& animName, Material *m); static MaterialAnimation* parseAnimation(ScriptFile& sf, Material *m); static MaterialAnimation* copyAnimation(const MaterialAnimation* a); }; #endif
c2663e67db45356ab0e54cc02126fc7850f95d65
efa2f7b6749c915f970c749adf0be4334d2a917f
/UIElement.cpp
b74e0d6dec6b9f3d20897be95515f718d35b92c7
[]
no_license
ChaytonMoore/2DSpaceGame
e7ef38555528f9d7724b5c66a5123e920e974981
576b1930fdb02236091dd704c1550b70d5cf42fa
refs/heads/master
2023-08-19T09:58:00.618312
2021-10-24T21:35:10
2021-10-24T21:35:10
395,780,968
0
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
UIElement.cpp
#include "UIElement.h" #include <iostream> int UIElement::ClickedOn() { std::cout << "a"; return 0; } bool UIElement::IsClicked(sf::Vector2i MouseLoc) { float Distance = sqrt(abs(MouseLoc.x - (LocalPosition.x+UISize/2)) + abs(MouseLoc.y - (LocalPosition.y+UISize/2))); return (Distance < ClickRadius); } void UIElement::EventTick(double DeltaTime) { }
5bd33429a0009439efc2e0e25c110005cec7f508
d802032cd60cc583210df0f77d3858a39ec1baf0
/0052.cpp
a987bab72092c77a1cf905faf0a31f0a45ab5298
[ "CC0-1.0" ]
permissive
excript/curso_cpp
840c4154cec064816f483d74f61eb768df00c5a7
070d0bd1163c1252b7bf736fedb3370208c30811
refs/heads/master
2021-01-22T19:18:05.464431
2015-07-11T07:49:04
2015-07-11T07:49:04
38,587,664
1
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
0052.cpp
#include <iostream> /*==================================== * eXcript.com * fb.com/eXcript * ====================================*/ using namespace std; int main(){ int nums[3]; nums[0] = 900; nums[1] = 1000; nums[2] = 1100; int nums2[] = {1, 3, 5, 7, 11, 13, 17}; cout << nums2[0] << endl; cout << nums2[1] << endl; cout << nums2[2] << endl; cout << nums2[3] << endl; cout << nums2[4] << endl; return 0; }
3e1a94ee8731c945a9d4c943c553d2687a826204
d4d4e9c9b22bdbc7af03e79af3559e6effe4f63e
/HackerRank/GraphTheory/RoadsAndLibraries.cpp
421dae1a9d2d2a252f9c3e0b2350a395d73eb679
[]
no_license
deeepeshthakur/CodeFiles
ea8d9c4a2b7a21c853ba8fc953c532e74576a791
3c9f08770a2628fa6eaef28fff212bfa1db96d16
refs/heads/master
2021-07-09T20:08:30.258607
2020-07-06T03:50:57
2020-07-06T03:50:57
160,020,105
2
1
null
2020-07-06T03:44:02
2018-12-02T06:26:50
C++
UTF-8
C++
false
false
1,721
cpp
RoadsAndLibraries.cpp
#include <bits/stdc++.h> using namespace std; void modified_dfs_call( int city, std::vector<bool> &dfsCheck, std::vector < std::vector <int> > &cityRoads, long& temp_ans){ temp_ans++; dfsCheck[city] = true; int roads_from_curr_city = cityRoads[city].size(); for(int index = 0; index < roads_from_curr_city; index++){ if(dfsCheck[cityRoads[city][index]] == false){ modified_dfs_call( cityRoads[city][index], dfsCheck, cityRoads, temp_ans); } } } void solverFuntion( int cities, int roads, long repairRoad, long repairLibrary){ std::vector< std::vector < int > > cityRoads(cities); for(int index = 0; index < roads; index++){ int cityOne = 0, cityTwo = 0; std::cin >> cityOne >> cityTwo; cityRoads[cityOne - 1].push_back(cityTwo - 1); cityRoads[cityTwo - 1].push_back(cityOne - 1); } std::vector <bool> dfsCheck( cities, false); long ans = 0; for(int index = 0; index < cities; index++) { long temp_ans = 0; if(!dfsCheck[index]) { temp_ans = 0; modified_dfs_call( index, dfsCheck, cityRoads, temp_ans); ans += (repairRoad*(temp_ans-1)); ans += repairLibrary; } } std::cout << ans << endl; } void solve(){ int cities = 0, roads = 0; long repairRoad = 0, repairLibrary = 0; std::cin >> cities >> roads >> repairLibrary >> repairRoad; if(repairRoad >= repairLibrary) { int ignore = 0; for(int index = 0; index < 2*roads; index++) std::cin >> ignore; std::cout << (repairLibrary*((long)cities)) << std::endl; } else { solverFuntion( cities, roads, repairRoad, repairLibrary); } } int main(){ int queries; std::cin >> queries; while(queries-- > 0){ solve(); } return 0; }
e4e801fe4d289a6fb133bad80ec13e871cd16b45
0a233295302a4a0160963ae835aad6fc3f1ac683
/Dp/303.cpp
3199617fa22d3fc0e0fa5b8191d51b7a8ff04714
[]
no_license
MregXN/Leetcode
90e4851699d1275416c21ce53623cfcba43d1a32
fa570fb744d7b97d600e3254ba17121deecee959
refs/heads/master
2023-01-13T01:22:40.835827
2020-10-30T11:53:17
2020-10-30T11:53:17
267,321,023
0
0
null
null
null
null
UTF-8
C++
false
false
715
cpp
303.cpp
// 给定一个整数数组  nums,求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点。 // 示例: // 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() // sumRange(0, 2) -> 1 // sumRange(2, 5) -> -1 // sumRange(0, 5) -> -3 // 说明: // 你可以假设数组不可变。 // 会多次调用 sumRange 方法。 class NumArray { private: vector<int> _nums; public: NumArray(vector<int>& nums) { _nums = nums; } int sumRange(int i, int j) { int sum = 0; for (int index = i; index <= j; index++) { sum += _nums[index]; } return sum; } };
ae6f9935eeeeeddde5e48562ddd3e32be9a75e4b
dc25b23f8132469fd95cee14189672cebc06aa56
/vendor/mediatek/proprietary/hardware/mtkcam/legacy/platform/mt6795/core/camnode/FeaturePipe/FeaturePipe.Nodes.cpp
ebba24cb2e0d69ef5f5c9a30de2aa55ff4879d1f
[]
no_license
nofearnohappy/alps_mm
b407d3ab2ea9fa0a36d09333a2af480b42cfe65c
9907611f8c2298fe4a45767df91276ec3118dd27
refs/heads/master
2020-04-23T08:46:58.421689
2019-03-28T21:19:33
2019-03-28T21:19:33
171,048,255
1
5
null
2020-03-08T03:49:37
2019-02-16T20:25:00
Java
UTF-8
C++
false
false
177,485
cpp
FeaturePipe.Nodes.cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ //#define LOG_TAG "MtkCam/PostProc.PipeWrapper" /************************************************************************************* * Log Utility *************************************************************************************/ #undef LOG_TAG // Decide a Log TAG for current file. #define LOG_TAG "MtkCam/FeaturePipe" #include <mtkcam/Log.h> #include <aee.h> #include "camera_custom_3dnr.h" // Clear previous define, use our own define. #undef LOG_VRB #undef LOG_DBG #undef LOG_INF #undef LOG_WRN #undef LOG_ERR #undef LOG_AST // #if defined(__func__) #undef __func__ #endif #define __func__ __FUNCTION__ #define LOG_VRB(fmt, arg...) CAM_LOGV("[%s] " fmt, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGD("[%s] " fmt, __func__, ##arg) #define LOG_INF(fmt, arg...) CAM_LOGI("[%s] " fmt, __func__, ##arg) #define LOG_WRN(fmt, arg...) CAM_LOGW("[%s] " fmt, __func__, ##arg) #define LOG_ERR(fmt, arg...) CAM_LOGE("[ERROR][%s] " fmt, __func__, ##arg) #define LOG_AST(cond, fmt, arg...) do{ if(!cond) CAM_LOGA("[%s] " fmt, __func__, ##arg); } while(0) #define FUNCTION_LOG_START LOG_DBG("+"); #define FUNCTION_LOG_END LOG_DBG("-"); #define ERROR_LOG LOG_ERR("Error"); // Added by Marx's request. #define AEE_ASSERT(String) \ do { \ aee_system_exception( \ LOG_TAG, \ NULL, \ DB_OPT_DEFAULT | DB_OPT_FTRACE, \ String); \ } while(0) // #include <sys/time.h> #include <mtkcam/imageio/IPipe.h> #include <mtkcam/imageio/IPostProcPipe.h> #include <mtkcam/ispio_sw_scenario.h> #include <mtkcam/iopipe/PostProc/INormalStream.h> #include <mtkcam/iopipe/PostProc/IFeatureStream.h> #include <vector> #include <queue> #include <cutils/atomic.h> #include <semaphore.h> #include <ui/GraphicBuffer.h> #include "FeaturePipe.BufHandler.h" #include "FeaturePipe.h" #include "MTKWarp.h" #include "MTKFeatureSet.h" #include "DpBlitStream.h" #include "DpIspStream.h" #include <mtkcam/hwutils/HwMisc.h> #include <mtkcam/utils/Format.h> #include <mtkcam/common.h> #include <mtkcam/common/faces.h> #include "vfb_hal_base.h" #include "eis_hal.h" // For EisHal in FeaturePipeNode.h. #include "eis_type.h" // For EIS_P1_RESULT struct. #include "vhdr_hal.h" #include <fd_hal_base.h> #include <mtkcam/featureio/IHal3A.h> #include "mtkcam/hal/IHalSensor.h" #include "FeaturePipeNode.h" #include "FeaturePipe.vFB.h" #include "FeaturePipe.EIS.h" //#include "aaa_hal_common.h" #include "PortMap.h" #include <cutils/properties.h> // For property_get(). using namespace NSCam; using namespace NSIoPipe; using namespace NSPostProc; using namespace NSCamNode; using namespace NSCam::Utils::Format; //#define _CPUWARP //#define _WORKAROUND_P2B //#define _WORKAROUND_GPU_FLASH #define NR3D_FORCE_GMV_ZERO 0 #define NR3D_NO_HW_POWER_OFF 0 #define ROUND_TO_2X(x) ((x) & (~0x1)) static inline MUINT32 getMagicNo(QParams const& rParams) { if (rParams.mvMagicNo.size()) return rParams.mvMagicNo[0]; else return rParams.mFrameNo; } static MINT32 convertRGBA8888toYV12(MINTPTR srcBufAddr, int srcBufWidth, int srcBufHeight, IImageBuffer* dstIImageBuffer) { bool ret = true; FUNCTION_LOG_START; DpBlitStream dpBlit; //***************************src RGBA8888****************************// MINTPTR src_addr_list[3] = {0, 0, 0}; unsigned int src_size_list[3] = {0, 0, 0}; int plane_num = 1; src_addr_list[0] = srcBufAddr; src_size_list[0] = FULL_IMAGE_MAX_WIDTH * srcBufHeight * 4; dpBlit.setSrcBuffer((void **)src_addr_list, src_size_list, plane_num); dpBlit.setSrcConfig(srcBufWidth, srcBufHeight, FULL_IMAGE_MAX_WIDTH * 4, 0, DP_COLOR_RGBA8888, DP_PROFILE_FULL_BT601, eInterlace_None, 0, DP_SECURE_NONE, false); //***************************dst YV12********************************// MINTPTR dst_addr_list[3] = {0, 0, 0}; unsigned int dst_size_list[3] = {0, 0, 0}; plane_num = 3; dst_addr_list[0] = dstIImageBuffer->getBufVA(0); dst_addr_list[1] = dstIImageBuffer->getBufVA(1); dst_addr_list[2] = dstIImageBuffer->getBufVA(2); dst_size_list[0] = dstIImageBuffer->getBufSizeInBytes(0); dst_size_list[1] = dstIImageBuffer->getBufSizeInBytes(1); dst_size_list[2] = dstIImageBuffer->getBufSizeInBytes(2); dpBlit.setDstBuffer((void**)dst_addr_list, dst_size_list, plane_num); dpBlit.setDstConfig(dstIImageBuffer->getImgSize().w, dstIImageBuffer->getImgSize().h, dstIImageBuffer->getBufStridesInBytes(0), dstIImageBuffer->getBufStridesInBytes(1), DP_COLOR_YV12, DP_PROFILE_FULL_BT601, eInterlace_None, 0, DP_SECURE_NONE, false); dpBlit.setRotate(0); // set & add pipe to stream if (dpBlit.invalidate()) //trigger HW { LOG_ERR("[convertRGBA8888toYV12] FDstream invalidate failed"); return false; } FUNCTION_LOG_END; return ret; } #if 1//def _DEBUG_DUMP #include <fcntl.h> #include <sys/stat.h> static bool saveBufToFile(char const*const fname, MUINT8 *const buf, MUINT32 const size) { int nw, cnt = 0; uint32_t written = 0; //LOG_DBG("(name, buf, size) = (%s, %x, %d)", fname, buf, size); //LOG_DBG("opening file [%s]\n", fname); int fd = ::open(fname, O_RDWR | O_CREAT | O_TRUNC, S_IRWXU); if (fd < 0) { LOG_ERR("failed to create file [%s]: %s", fname, ::strerror(errno)); return false; } //LOG_DBG("writing %d bytes to file [%s]\n", size, fname); while (written < size) { nw = ::write(fd, buf + written, size - written); if (nw < 0) { LOG_ERR("failed to write to file [%s]: %s", fname, ::strerror(errno)); break; } written += nw; cnt++; } LOG_DBG("done writing %d bytes to file [%s]\n", size, fname); ::close(fd); return true; } #endif #ifdef _UNITTEST /****************************************************************************** * read the file to the buffer *******************************************************************************/ static uint32_t loadFileToBuf(char const*const fname, uint8_t*const buf, uint32_t size) { int nr, cnt = 0; uint32_t readCnt = 0; LOG_DBG("opening file [%s] adr 0x%x\n", fname,buf); int fd = ::open(fname, O_RDONLY); if (fd < 0) { LOG_ERR("failed to create file [%s]: %s", fname, strerror(errno)); return readCnt; } // if (size == 0) { size = ::lseek(fd, 0, SEEK_END); ::lseek(fd, 0, SEEK_SET); } // LOG_DBG("read %d bytes from file [%s]\n", size, fname); while (readCnt < size) { nr = ::read(fd, buf + readCnt, size - readCnt); if (nr < 0) { LOG_ERR("failed to read from file [%s]: %s", fname, strerror(errno)); break; } readCnt += nr; cnt++; } LOG_DBG("done reading %d bytes to file [%s] in %d passes\n", size, fname, cnt); ::close(fd); return readCnt; } #endif /****************************************************************************** * ******************************************************************************/ MBOOL FeaturePipe::initFeatureGraph() { FUNCTION_LOG_START; bool ret = MTRUE; CPTLog(Event_FeaturePipe, CPTFlagStart); CPTLog(Event_FeaturePipe_init, CPTFlagStart); /* Create nodes */ //mpControlNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_CONTROL, mFeatureOnMask, mOpenedSensorIndex); mpP2aNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_P2A, mFeatureOnMask, mOpenedSensorIndex, this); if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { mpGpuNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_GPU, mFeatureOnMask, mOpenedSensorIndex, this); mpMdpNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_MDP, mFeatureOnMask, mOpenedSensorIndex, this); } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { mpVfbSwNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_VFBSW, mFeatureOnMask, mOpenedSensorIndex, this); mpFdNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_FD, mFeatureOnMask, mOpenedSensorIndex, this); mpP2bNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_P2B, mFeatureOnMask, mOpenedSensorIndex, this); mpSwitcherNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_SWITCHER, mFeatureOnMask, mOpenedSensorIndex, this); } if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { mpEisSwNode = FeaturePipeNode::createInstance(FEATURE_STREAM_NODE_EISSW, mFeatureOnMask, mOpenedSensorIndex, this); } mpAllocBufHdl = FeaturePipeBufHandler::createInstance(); mpAllocBufHdl->init(); /* Connect nodes */ //mpCamGraph->connect(0x1, mpControlNode, mpP2aNode); if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { mpCamGraph->setBufferHandler(P2A_TO_VFBSW_DSIMG, mpAllocBufHdl); mpCamGraph->setBufferHandler(P2A_TO_SWITCHER, mpAllocBufHdl); mpCamGraph->setBufferHandler(P2A_TO_FD_DSIMG, mpAllocBufHdl); mpCamGraph->setBufferHandler(FD_TO_VFBSW, mpAllocBufHdl); mpCamGraph->setBufferHandler(VFBSW_TO_GPU, mpAllocBufHdl); mpCamGraph->setBufferHandler(VFBSW_TO_P2B_DSIMG, mpAllocBufHdl); mpCamGraph->setBufferHandler(VFBSW_TO_P2B_ALPCL, mpAllocBufHdl); mpCamGraph->setBufferHandler(VFBSW_TO_P2B_ALPNR, mpAllocBufHdl); mpCamGraph->setBufferHandler(VFBSW_TO_P2B_PCA, mpAllocBufHdl); mpCamGraph->setBufferHandler(GPU_TO_MDP, mpAllocBufHdl); mpCamGraph->setBufferHandler(MDP_TO_SWITCHER, mpAllocBufHdl); mpCamGraph->connectData(P2A_TO_VFBSW_DSIMG, P2A_TO_VFBSW_DSIMG, mpP2aNode, mpVfbSwNode); mpCamGraph->connectData(P2A_TO_SWITCHER, P2A_TO_SWITCHER, mpP2aNode, mpSwitcherNode); mpCamGraph->connectData(P2A_TO_FD_DSIMG, P2A_TO_FD_DSIMG, mpP2aNode, mpFdNode); mpCamGraph->connectData(FD_TO_VFBSW, FD_TO_VFBSW, mpFdNode, mpVfbSwNode); mpCamGraph->connectData(VFBSW_TO_GPU, VFBSW_TO_GPU, mpVfbSwNode, mpGpuNode); mpCamGraph->connectData(VFBSW_TO_P2B_DSIMG, VFBSW_TO_P2B_DSIMG, mpVfbSwNode, mpP2bNode); mpCamGraph->connectData(VFBSW_TO_P2B_ALPCL, VFBSW_TO_P2B_ALPCL, mpVfbSwNode, mpP2bNode); mpCamGraph->connectData(VFBSW_TO_P2B_ALPNR, VFBSW_TO_P2B_ALPNR, mpVfbSwNode, mpP2bNode); mpCamGraph->connectData(VFBSW_TO_P2B_PCA, VFBSW_TO_P2B_PCA, mpVfbSwNode, mpP2bNode); mpCamGraph->connectData(GPU_TO_MDP, GPU_TO_MDP, mpGpuNode, mpMdpNode); mpCamGraph->connectData(MDP_TO_SWITCHER, MDP_TO_SWITCHER, mpMdpNode, mpSwitcherNode); mpCamGraph->connectData(P2A_TO_P2B, P2A_TO_P2B, mpP2aNode, mpP2bNode); mpCamGraph->connectData(SWITCHER_TO_GPU, SWITCHER_TO_GPU, mpSwitcherNode, mpGpuNode); mpCamGraph->connectData(SWITCHER_TO_VFBSW, SWITCHER_TO_VFBSW, mpSwitcherNode, mpVfbSwNode); mpCamGraph->connectData(SWITCHER_TO_P2B, SWITCHER_TO_P2B, mpSwitcherNode, mpP2bNode); mpCamGraph->connectNotify(FEATURE_MASK_CHANGE, mpP2aNode, mpFdNode); } if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { mpCamGraph->setBufferHandler(P2A_TO_EISSW, mpAllocBufHdl); mpCamGraph->connectData(P2A_TO_EISSW, P2A_TO_EISSW, mpP2aNode, mpEisSwNode); if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { mpCamGraph->setBufferHandler(EISSW_TO_VFBSW, mpAllocBufHdl); mpCamGraph->connectData(EISSW_TO_VFBSW, EISSW_TO_VFBSW, mpEisSwNode, mpVfbSwNode); } else { mpCamGraph->setBufferHandler(P2A_TO_GPU, mpAllocBufHdl); mpCamGraph->setBufferHandler(EISSW_TO_GPU, mpAllocBufHdl); mpCamGraph->setBufferHandler(GPU_TO_MDP, mpAllocBufHdl); mpCamGraph->connectData(P2A_TO_GPU, P2A_TO_GPU, mpP2aNode, mpGpuNode); mpCamGraph->connectData(P2A_TO_MDP_QPARAMS, P2A_TO_MDP_QPARAMS, mpP2aNode, mpMdpNode); mpCamGraph->connectData(EISSW_TO_GPU, EISSW_TO_GPU, mpEisSwNode, mpGpuNode); mpCamGraph->connectData(GPU_TO_MDP, GPU_TO_MDP, mpGpuNode, mpMdpNode); char gpuDebug[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpgpu", gpuDebug, "0"); if(gpuDebug[0] == '2' || gpuDebug[0] == '3') { mpCamGraph->setBufferHandler(8001,mpAllocBufHdl); } char mdpDebug[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpmdp", mdpDebug, "0"); if(mdpDebug[0] == '1' || mdpDebug[0] == '3') { mpCamGraph->setBufferHandler(8001,mpAllocBufHdl); } } } if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { mpCamGraph->setBufferHandler(P2A_TO_GPU, mpAllocBufHdl); } if (!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { mpCamGraph->connectData(0, 0, mpP2aNode, NULL); } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { #ifdef MTK_CAM_VIDEO_FACEBEAUTY_SUPPORT reinterpret_cast<FeaturePipeVfbNode*>(mpVfbSwNode)->set(RECORDING_HINT, (MINTPTR) mRecordingHint); #endif } /* Init graph */ mpCamGraph->init(); mpCamGraph->start(); CPTLog(Event_FeaturePipe_init, CPTFlagEnd); FUNCTION_LOG_END; return ret; } /****************************************************************************** * ******************************************************************************/ MBOOL FeaturePipe::uninitFeatureGraph() { FUNCTION_LOG_START; bool ret = true; CPTLog(Event_FeaturePipe_uninit, CPTFlagStart); /* Uninit graph */ mpCamGraph->stop(); mpCamGraph->uninit(); /* Disconnect nodes */ mpCamGraph->disconnect(); /* Destroy nodes */ mpP2aNode->destroyInstance(); if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { //mpControlNode->destroyInstance(); mpGpuNode->destroyInstance(); mpMdpNode->destroyInstance(); } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { mpVfbSwNode->destroyInstance(); mpP2bNode->destroyInstance(); mpSwitcherNode->destroyInstance(); } if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { mpEisSwNode->destroyInstance(); } mpAllocBufHdl->uninit(); mpAllocBufHdl->destroyInstance(); CPTLog(Event_FeaturePipe_uninit, CPTFlagEnd); CPTLog(Event_FeaturePipe, CPTFlagEnd); FUNCTION_LOG_END; return ret; } MBOOL FeaturePipe::startVideoRecord(MINT32 wd,MINT32 ht,MINT32 fps) { FUNCTION_LOG_START; MBOOL ret = reinterpret_cast<FeaturePipeP2aNode*>(mpP2aNode)->startVideoRecord(wd, ht,fps); FUNCTION_LOG_END; return ret; } MBOOL FeaturePipe::stopVideoRecord() { FUNCTION_LOG_START; MBOOL ret = reinterpret_cast<FeaturePipeP2aNode*>(mpP2aNode)->stopVideoRecord(); FUNCTION_LOG_END; return ret; } MBOOL FeaturePipe::enqueFeatureGraph(QParams const& rParams) { //FUNCTION_LOG_START; CAM_TRACE_FMT_BEGIN("FPipeEnq:%d", rParams.mFrameNo); Mutex::Autolock autoLock(mReconfigMtx); //Lock to make sure no more is enqued into FeatureGraph bool ret = true; ::android_atomic_inc(&mEnqueCount); LOG_DBG("FrameNo(%d)", getMagicNo(rParams)); ret = reinterpret_cast<FeaturePipeP2aNode*>(mpP2aNode)->enqueWrapper(0, (MUINTPTR) &rParams, getMagicNo(rParams)); CAM_TRACE_FMT_END(); //FUNCTION_LOG_END; return ret; } MBOOL FeaturePipe::dequeFeatureGraph(QParams& rParams, MINT64 i8TimeoutNs) { FUNCTION_LOG_START; bool ret = true; if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { ret = reinterpret_cast<FeaturePipeP2bNode*>(mpP2bNode)->dequeWrapper(rParams, i8TimeoutNs); } else if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { ret = reinterpret_cast<FeaturePipeMdpNode*>(mpMdpNode)->dequeWrapper(rParams, i8TimeoutNs); } else { ret = reinterpret_cast<FeaturePipeP2aNode*>(mpP2aNode)->dequeWrapper(rParams, i8TimeoutNs); } LOG_DBG("FrameNo(%d)", getMagicNo(rParams)); ::android_atomic_dec(&mEnqueCount); FUNCTION_LOG_END; return ret; } void FeaturePipe::performCallback(QParams& rParams) { //FUNCTION_LOG_START; CAM_TRACE_FMT_BEGIN("FPipeCb:%d", rParams.mFrameNo); LOG_DBG("FeatureGraph callback FrameNo(%d)", getMagicNo(rParams)); ::android_atomic_dec(&mEnqueCount); rParams.mpfnCallback(rParams); CAM_TRACE_FMT_END(); //FUNCTION_LOG_END; } MBOOL FeaturePipe::setFeature(MUINT32 featureMask) { bool ret = MTRUE; if (featureMask == mFeatureOnMask) { return ret; } FUNCTION_LOG_START; LOG_DBG("SetFeature: %x->%x", mFeatureOnMask, featureMask); MUINT32 featureDiff = featureMask ^ mFeatureOnMask; if (FEATURE_MASK_IS_3DNR_ENABLED(featureDiff) || FEATURE_MASK_IS_VFB_ENABLED(featureDiff) || FEATURE_MASK_IS_EIS_ENABLED(featureDiff) || FEATURE_MASK_IS_VHDR_ENABLED(featureDiff) || FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(featureDiff)) { /* Change feature(s) that affect the node graph */ Mutex::Autolock autoLock(mReconfigMtx); //Lock to make sure no more is enqued into FeatureGraph /* Wait till enqued are all dequed */ while (mEnqueCount) { usleep(50000); } if(mInited) { uninitFeatureGraph(); } mFeatureOnMask = featureMask; ret = initFeatureGraph(); } else if(FEATURE_MASK_IS_GESTURE_SHOT_ENABLED(featureDiff) || FEATURE_MASK_IS_VHDR_ENABLED(featureDiff) || FEATURE_MASK_IS_SMILE_SHOT_ENABLED(featureDiff)) { /* Change feature(s) that do not affect the node graph */ mFeatureOnMask = featureMask; if (mpP2aNode != NULL) { ret = reinterpret_cast<FeaturePipeP2aNode*>(mpP2aNode)->notifyGraphNodes(FEATURE_MASK_CHANGE, mFeatureOnMask, 0); } } LOG_AST(ret, "Set features (0x%x) failed!", featureMask); FUNCTION_LOG_END; return ret; } MBOOL FeaturePipe::setTuning(FeaturePipeTuningInfo& tuningInfo) { if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { #ifdef MTK_CAM_VIDEO_FACEBEAUTY_SUPPORT reinterpret_cast<FeaturePipeVfbNode*>(mpVfbSwNode)->setTuning(tuningInfo); reinterpret_cast<FeaturePipeFdNode*>(mpFdNode)->setRotation(tuningInfo.Rotation); reinterpret_cast<FeaturePipeSwitcherNode*>(mpSwitcherNode)->setVfbExtreme(tuningInfo.ExtremeBeauty); #endif } return MTRUE; } MBOOL FeaturePipe::setTouch(MINT32 touchX, MINT32 touchY) { if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { #ifdef MTK_CAM_VIDEO_FACEBEAUTY_SUPPORT return reinterpret_cast<FeaturePipeVfbNode*>(mpVfbSwNode)->setTouch(touchX, touchY); #endif } return MTRUE; } MBOOL FeaturePipe::set(FeaturePipeSetType setType, const MINTPTR setData) { //LOG_DBG("setType(%d), setData(0x%08x)", setType, (MUINT32) setData); switch (setType) { case MAX_INPUT_IMAGE_SIZE: case RECORDING_HINT: mRecordingHint = (MBOOL) setData; break; } return MTRUE; } /****************************************************************************** * ******************************************************************************/ FeaturePipeNode* FeaturePipeNode::createInstance(FeaturePipeNodeObject_e eobject, MUINT32 featureOnMask, MUINT32 mOpenedSensorIndex, FeaturePipe *pFeaturePipeObj) { if (eobject == FEATURE_STREAM_NODE_CONTROL) { return NULL;//TODO:FeaturePipeControlNode::createInstance(featureOnMask); } else if (eobject == FEATURE_STREAM_NODE_P2A) { return FeaturePipeP2aNode::createInstance(featureOnMask, mOpenedSensorIndex, pFeaturePipeObj); } else if (eobject == FEATURE_STREAM_NODE_P2B) { return FeaturePipeP2bNode::createInstance(featureOnMask, mOpenedSensorIndex, pFeaturePipeObj); } else if (eobject == FEATURE_STREAM_NODE_EISSW) { return FeaturePipeEisNode::createInstance(featureOnMask,mOpenedSensorIndex); } #ifdef MTK_CAM_VIDEO_FACEBEAUTY_SUPPORT else if (eobject == FEATURE_STREAM_NODE_VFBSW) { return FeaturePipeVfbNode::createInstance(featureOnMask, pFeaturePipeObj); } #endif #ifdef MTK_CAM_VIDEO_FACEBEAUTY_SUPPORT else if (eobject == FEATURE_STREAM_NODE_FD) { return FeaturePipeFdNode::createInstance(featureOnMask, mOpenedSensorIndex, pFeaturePipeObj); } #endif else if (eobject == FEATURE_STREAM_NODE_GPU) { return FeaturePipeGpuNode::createInstance(featureOnMask, pFeaturePipeObj); } else if (eobject == FEATURE_STREAM_NODE_MDP) { return FeaturePipeMdpNode::createInstance(featureOnMask, pFeaturePipeObj); } else if (eobject == FEATURE_STREAM_NODE_SWITCHER) { return FeaturePipeSwitcherNode::createInstance(featureOnMask, pFeaturePipeObj); } else return 0; } /****************************************************************************** * ******************************************************************************/ #undef LOG_VRB #undef LOG_DBG #undef LOG_DBG #undef LOG_WRN #undef LOG_ERR #undef LOG_AST #define LOG_VRB(fmt, arg...) CAM_LOGV("[%d:P2A:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGD("[%d:P2A:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGI("[%d:P2A:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_WRN(fmt, arg...) CAM_LOGW("[%d:P2A:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_ERR(fmt, arg...) CAM_LOGE("[%d:P2A:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_AST(cond, fmt, arg...) do{ if(!cond) CAM_LOGA("[%d:P2A:%s] " fmt, mOpenedSensorIndex, __func__, ##arg); } while(0) FeaturePipeP2aNode* FeaturePipeP2aNode::createInstance(MUINT32 featureOnMask, MUINT32 mOpenedSensorIndex, FeaturePipe *pFeaturePipeObj) { return new FeaturePipeP2aNode("FeaturePipeP2aNode", SingleTrigger, SCHED_POLICY, SCHED_PRIORITY, featureOnMask, mOpenedSensorIndex, pFeaturePipeObj); } MVOID FeaturePipeP2aNode::destroyInstance() { delete this; } FeaturePipeP2aNode::FeaturePipeP2aNode( const char* name, eThreadNodeType type, int policy, int priority, MUINT32 featureOnMask, MUINT32 mOpenedSensorIndex, FeaturePipe *pFeaturePipeObj ) : FeaturePipeNode(name, type, policy, priority, featureOnMask, mOpenedSensorIndex, pFeaturePipeObj), mpIFeatureStream(NULL), mpINormalStream(NULL) { if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_DST, P2A_TO_SWITCHER); addDataSupport(ENDPOINT_DST, P2A_TO_VFBSW_DSIMG); addDataSupport(ENDPOINT_DST, P2A_TO_P2B); addDataSupport(ENDPOINT_DST, P2A_TO_FD_DSIMG); addNotifySupport(FEATURE_MASK_CHANGE); } if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_DST, P2A_TO_EISSW); if (!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_DST, P2A_TO_GPU); addDataSupport(ENDPOINT_DST, P2A_TO_MDP_QPARAMS); } } mpVHdrObj = NULL; } MBOOL FeaturePipeP2aNode::onInit() { FUNCTION_LOG_START; MRESULT mret; MUINT8 imemBufInfoIdx = 0; LOG_DBG("mFeatureOnMask 0x%08x", mFeatureOnMask); mpNr3dParam = new NSCam::NSIoPipe::NSPostProc::NR3D; mpFeoParam = new NSCam::NSIoPipe::NSPostProc::StaData; if(FEATURE_MASK_IS_VHDR_ENABLED(mFeatureOnMask)) { mpLceiParam = new NSCam::NSIoPipe::NSPostProc::StaData; } mPrevFrameWidth = 0; mPrevFrameHeight = 0; m3dnrGainZeroCount = 0; m3dnrErrorStatus = NR3D_ERROR_NONE; m3dnrStateMachine = NR3D_STATE_PREPARING; if( FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) // For 3DNR only case. { /* Create IFeatureStream */ mpIFeatureStream = NSCam::NSIoPipe::NSPostProc::IFeatureStream::createInstance("FeaturePipe_FeatureP2", EFeatureStreamTag_Stream, mOpenedSensorIndex); if (mpIFeatureStream == NULL) { LOG_ERR("IFeatureStream create instance for FeaturePipe_FeatureP2 failed!"); goto _Exit; } mpIFeatureStream->init(); } else if(FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask)) // For Stereo Camera case { /* Create IFeatureStream */ IHalSensorList* const pHalSensorList = IHalSensorList::get(); EFeatureStreamTag eTag = ( SENSOR_DEV_MAIN_2 == pHalSensorList->querySensorDevIdx(mOpenedSensorIndex) ) ? EFeatureStreamTag_N3D_Stream_M2 : EFeatureStreamTag_vFB_Stream; char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("debug.stereovfb.enable", EnableOption, "0"); if(EnableOption[0] == '1') { eTag = ( SENSOR_DEV_SUB == pHalSensorList->querySensorDevIdx(mOpenedSensorIndex) ) ? EFeatureStreamTag_N3D_Stream_M2 : eTag; } if (eTag == EFeatureStreamTag_N3D_Stream_M2) LOG_DBG("Creating IFeatureStream stereo sub-sensor instance"); mpIFeatureStream = NSCam::NSIoPipe::NSPostProc::IFeatureStream::createInstance("FeaturePipe_FeatureP2", eTag, mOpenedSensorIndex); if (mpIFeatureStream == NULL) { LOG_ERR("IFeatureStream create instance for FeaturePipe_FeatureP2 failed!"); goto _Exit; } mpIFeatureStream->init(); } else if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) { /* Create IFeatureStream */ mpIFeatureStream = NSCam::NSIoPipe::NSPostProc::IFeatureStream::createInstance("FeaturePipe_VfbP2A", EFeatureStreamTag_vFB_Stream, mOpenedSensorIndex); if (mpIFeatureStream == NULL) { LOG_ERR("IFeatureStream create instance failed!"); goto _Exit; } mpIFeatureStream->init(); } else { /* Create INormalStream */ mpINormalStream = NSCam::NSIoPipe::NSPostProc::INormalStream::createInstance("FeaturePipe_NormalP2", ENormalStreamTag_Prv, mOpenedSensorIndex); mpINormalStream->init(); } mpEisHalFor3DNR = EisHal::CreateInstance("FeaturePipe_3DNR", mOpenedSensorIndex); if (mpEisHalFor3DNR == NULL) { LOG_ERR("mpEisHalFor3DNR CreateInstance failed"); goto _Exit; } // Can't unmark, will cause hang. Because under current code architecture, // when pass 2 thread is up and this line is executed, Pass 1 thread might // not be ready yet, which will cause hang because not correct TG/sensor // information for EIS. //if(EIS_RETURN_NO_ERROR != mpEisHalFor3DNR->Init()) //{ // LOG_ERR("mpEisHalFor3DNR init failed"); // goto _Exit; //} //if(FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) // Workaround for EIS GMV Queue can't unregister user => Pass 2 always register user (in FeaturePipeP2aNode::onInit()), Pass 1 EIS always set GMV, Pass 2 always get GMV. { // Can't unmark, will cause hang. Because under current code architecture, // when pass 2 thread is up and this line is executed, Pass 1 thread might // not be ready yet, which will cause hang because not correct TG/sensor // information for EIS. //if (mpEisHalFor3DNR->GetEisSupportInfo(mOpenedSensorIndex)) // This sensor support EIS. { mpEisHalFor3DNR->SetEisP2User("FeaturePipe_3DNR"); } } #ifdef MTK_CAM_VHDR_SUPPORT if(FEATURE_MASK_IS_VHDR_ENABLED(mFeatureOnMask)) { mpVHdrObj = VHdrHal::CreateInstance("FPipeVHdr",mOpenedSensorIndex); if(mpVHdrObj != NULL) { mpVHdrObj->Init(SENSOR_VHDR_MODE_IVHDR); } } #endif mp3AHal = NS3A::IHal3A::createInstance(NS3A::IHal3A::E_Camera_1, mOpenedSensorIndex, "FeaturePipe_FeatureP2"); if (!mp3AHal) { LOG_ERR("IHal3A::createInstance failed!"); goto _Exit; } sem_init(&mModuleSem, 0, 0); /* Allocate buffer for next node */ if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { NodeDataTypes dType = FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)? P2A_TO_SWITCHER: P2A_TO_GPU; pBufHandler = getBufferHandler(dType); if (pBufHandler == NULL) { LOG_ERR("ICamBufHandler getBufferHandler(P2A_TO_GPU) failed!"); goto _Exit; } LOG_DBG("Allocate P2A buffer %dx%d", NR3D_WORKING_BUFF_WIDTH, NR3D_WORKING_BUFF_HEIGHT); AllocInfo allocinfo(NR3D_WORKING_BUFF_WIDTH, NR3D_WORKING_BUFF_HEIGHT, eImgFmt_YV12, eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN | eBUFFER_USAGE_SW_WRITE_RARELY); for (MUINT8 i = 0; i < P2A_FULLIMG_BUFFER_NUM; i++) { mFullImgGB[i] = new GraphicBuffer(NR3D_WORKING_BUFF_WIDTH, NR3D_WORKING_BUFF_HEIGHT, HAL_PIXEL_FORMAT_YV12, GraphicBuffer::USAGE_HW_TEXTURE | GraphicBuffer::USAGE_SW_READ_OFTEN | GraphicBuffer::USAGE_SW_WRITE_OFTEN); if (mFullImgGB[i] == NULL) { LOG_ERR("P2A GraphicBuffer allocation for YV12 failed!"); goto _Exit; } if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->requestBuffer_GB(dType, allocinfo, &(mFullImgGB[i])) ) { LOG_ERR("Request P2A_TO_GPU full image buffer failed"); goto _Exit; } } } else if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) //3DNR only { pBufHandler = getBufferHandler(P2A_TO_GPU); if (pBufHandler == NULL) { LOG_ERR("ICamBufHandler getBufferHandler(P2A_TO_GPU) failed!"); goto _Exit; } LOG_DBG("Allocate P2A buffer %dx%d", NR3D_WORKING_BUFF_WIDTH, NR3D_WORKING_BUFF_HEIGHT); AllocInfo allocinfo(NR3D_WORKING_BUFF_WIDTH, NR3D_WORKING_BUFF_HEIGHT, eImgFmt_YV12, eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN | eBUFFER_USAGE_SW_WRITE_RARELY); for (MUINT8 i = 0; i < P2A_FULLIMG_BUFFER_NUM; i++) { if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->requestBuffer(P2A_TO_GPU, allocinfo) ) { LOG_ERR("Request P2A_TO_GPU full image buffer failed"); goto _Exit; } } } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { LOG_DBG("Allocate DS image buffer %dx%d", VFB_DS_IMAGE_MAX_WIDTH, VFB_DS_IMAGE_MAX_HEIGHT); if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { AllocInfo allocinfo(VFB_DS_IMAGE_MAX_WIDTH, VFB_DS_IMAGE_MAX_HEIGHT, eImgFmt_YUY2, eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN | eBUFFER_USAGE_SW_WRITE_RARELY); for(MUINT32 i = 0; i < P2A_DSIMG_BUFFER_NUM; i++) { if( !pBufHandler->requestBuffer(P2A_TO_VFBSW_DSIMG, allocinfo) ) goto _Exit; } } } sem_init(&mCallbackSem, 0, 0); FUNCTION_LOG_END; return true; _Exit: if (mpIFeatureStream != NULL) { mpIFeatureStream->destroyInstance("FeaturePipe_VfbP2A"); } if (mpINormalStream != NULL) { mpINormalStream->destroyInstance("FeaturePipe_NormalP2"); } return false; } MBOOL FeaturePipeP2aNode:: onUninit() { Mutex::Autolock autoLock(mUninitMtx); FUNCTION_LOG_START; // Return (enque) all buffers before leaving. if( FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) && //Vent@20140228: For 3DNR only case. !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) { FeaturePipeNodeImgReqJob_s jobFullImg; // enqueBuffer. while (!m3dnrPrvFrmQueue.empty()) { jobFullImg = m3dnrPrvFrmQueue.front(); pBufHandler->enqueBuffer(P2A_TO_GPU, jobFullImg.imgReq.mBuffer); LOG_DBG("m3dnrPrvFrmQueue[size %d]: mem<va(0x%x)/pa(0x%x)>", m3dnrPrvFrmQueue.size(), jobFullImg.imgReq.mBuffer->getBufVA(0), jobFullImg.imgReq.mBuffer->getBufPA(0)); m3dnrPrvFrmQueue.pop(); } } delete mpNr3dParam; // Return allocated memory. delete mpFeoParam; if(FEATURE_MASK_IS_VHDR_ENABLED(mFeatureOnMask)) { delete mpLceiParam; } mPrevFrameWidth = 0; mPrevFrameHeight = 0; m3dnrGainZeroCount = 0; m3dnrErrorStatus = NR3D_ERROR_NONE; m3dnrStateMachine = NR3D_STATE_PREPARING; if (mpEisHalFor3DNR != NULL) { // mpEisHalFor3DNR->Uninit(); mpEisHalFor3DNR->DestroyInstance("FeaturePipe_3DNR"); mpEisHalFor3DNR = NULL; } #ifdef MTK_CAM_VHDR_SUPPORT if(mpVHdrObj != NULL) { mpVHdrObj->Uninit(); mpVHdrObj->DestroyInstance("FPipeVHdr"); } #endif if (mp3AHal != NULL) { // Restore AE ISO limit. (Leaving feature pipe, so don't need 3DNR raise ISO limit.) // Parameter meaning: MTRUE: Enable the function. MTRUE: Need to equivalent for orginal BV range. 100: it means don't need to increase. 100: it means don't need to increase. mp3AHal->modifyPlineTableLimitation(MTRUE, MTRUE, 100, 100); LOG_DBG("Restore 3DNR AE ISO limit."); mp3AHal->destroyInstance("FeaturePipe_FeatureP2"); mp3AHal = NULL; } if (mpIFeatureStream != NULL) { mpIFeatureStream->uninit(); mpIFeatureStream->destroyInstance("FeaturePipe_VfbP2A"); } if (mpINormalStream != NULL) { mpINormalStream->uninit(); mpINormalStream->destroyInstance("FeaturePipe_NormalP2"); sem_destroy(&mModuleSem); } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { LOG_DBG("Freeing GraphicBuffer"); for (MUINT8 i = 0; i < P2A_FULLIMG_BUFFER_NUM; i++) { mFullImgGB[i]->unlock(); mFullImgGB[i] = NULL; } } FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2aNode:: onStart() { FUNCTION_LOG_START; FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2aNode:: onStop() { FUNCTION_LOG_START; MBOOL ret = syncWithThread(); // wait for jobs done FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2aNode:: onNotify(MUINT32 const datamsg, MUINT32 const ext1, MUINT32 const ext2) { FUNCTION_LOG_START; LOG_DBG("datamsg(0x%x), ext1(0x%x), ext2(0x%x)", datamsg, ext1, ext2); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2aNode:: enqueWrapper(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { #if 0 return handlePostBuffer(data, buf, ext); } MBOOL FeaturePipeP2aNode:: onPostBuffer(MUINT32 const data, MUINT32 const buf, MUINT32 const ext) { #endif //FUNCTION_LOG_START; //LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); MBOOL ret = MTRUE; if(!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) ) //Vent@20140228: Add for 3DNR. { QParams* pQParams = reinterpret_cast<QParams*>(buf); if (pQParams->mpfnCallback != NULL) { Mutex::Autolock lock(mLock); /* Change to P2A callback func */ mqCookie.push(pQParams->mpCookie); mqfnCallback.push(pQParams->mpfnCallback); pQParams->mpCookie = (void*) this; pQParams->mpfnCallback = p2aCbFunc; } CAM_TRACE_FMT_BEGIN("P2ANStrm:%d", getMagicNo((*pQParams))); #ifdef MTK_CAM_VHDR_SUPPORT if(FEATURE_MASK_IS_VHDR_ENABLED(mFeatureOnMask)) { LCEI_DMA_INFO aLceiDma; ModuleInfo vhdrLceiModuleinfo; //> get LCEI info mpVHdrObj->GetLceiDmaInfo(&aLceiDma,pQParams->mvIn[0].mBuffer->getTimestamp()); if(aLceiDma.memID == VHDR_LCSO_SYNC_FAIL) { LOG_ERR("[FPipe_N] VHDR_LCSO_SYNC_FAIL"); } //> prepare info and push to QParam mpLceiParam->bufInfo.size = aLceiDma.size; mpLceiParam->bufInfo.memID = aLceiDma.memID; mpLceiParam->bufInfo.virtAddr = aLceiDma.va; mpLceiParam->bufInfo.phyAddr = aLceiDma.pa; mpLceiParam->bufInfo.bufSecu = aLceiDma.bufSecu; mpLceiParam->bufInfo.bufCohe = aLceiDma.bufCohe; mpLceiParam->bufInfo.useNoncache = aLceiDma.useNoncache; mpLceiParam->w = aLceiDma.xSize; mpLceiParam->h = aLceiDma.ySize; mpLceiParam->stride = aLceiDma.stride; mpLceiParam->port_idx = NSImageio::NSIspio::EPortIndex_LCEI; mpLceiParam->port_type = NSIoPipe::EPortType_Memory; mpLceiParam->port_inout = 1; vhdrLceiModuleinfo.moduleTag = EFeatureModule_STA_LCEI; vhdrLceiModuleinfo.moduleStruct = reinterpret_cast<MVOID*>(mpLceiParam); LOG_DBG("[FPipe_N] LCEI_PA(0x%08x)",mpLceiParam->bufInfo.phyAddr); pQParams->mvModuleData.push_back(vhdrLceiModuleinfo); } #endif ret = mpINormalStream->enque(*pQParams); CAM_TRACE_FMT_END(); } else { Mutex::Autolock lock(mLock); mqJob.push(*(reinterpret_cast<QParams*>(buf))); triggerLoop(); } //FUNCTION_LOG_END; return ret; } MBOOL FeaturePipeP2aNode:: notifyGraphNodes(MUINT32 const msg, MUINT32 const ext1, MUINT32 const ext2) { LOG_DBG("msg(%d), ext1(0x%x), ext2(0x%x)", msg, ext1, ext2); handleNotify(msg, ext1, ext2); return MTRUE; } void FeaturePipeP2aNode:: getGraphicBuffer(vector< sp<GraphicBuffer>* >& vpGB) { for (int i=0; i<P2A_FULLIMG_BUFFER_NUM; i++) vpGB.push_back(&(mFullImgGB[i])); } MBOOL FeaturePipeP2aNode:: set(FeaturePipeSetType setType, const MINTPTR setData) { switch (setType) { case MAX_INPUT_IMAGE_SIZE: mMaxInputImageSize = *((MSize*) setData); break; } return MTRUE; } MBOOL FeaturePipeP2aNode::startVideoRecord(MINT32 wd,MINT32 ht,MINT32 fps) { FUNCTION_LOG_START; MBOOL ret = MFALSE; if(!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) ) { ret = mpINormalStream->startVideoRecord(wd, ht, fps); } else { ret = mpIFeatureStream->startVideoRecord(wd, ht, fps); } FUNCTION_LOG_END; return ret; } MBOOL FeaturePipeP2aNode::stopVideoRecord() { FUNCTION_LOG_START; MBOOL ret = MFALSE; if(!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) ) { ret = mpINormalStream->stopVideoRecord(); } else { ret = mpIFeatureStream->stopVideoRecord(); } FUNCTION_LOG_END; return ret; } MBOOL FeaturePipeP2aNode:: dequeWrapper(QParams& rParams, MINT64 i8TimeoutNs) { FUNCTION_LOG_START; MRESULT mret = MTRUE; if(!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) ) //Vent@20140228: Add for 3DNR. { mret = mpINormalStream->deque(rParams, i8TimeoutNs); if (!mret) { LOG_ERR("INormalStream deque failed! (frame %d)", getMagicNo(rParams)); } else { LOG_DBG("INormalStream deque succeeds! (frame %d)", getMagicNo(rParams)); } } else { sem_wait(&mModuleSem); Mutex::Autolock lock(mLock); rParams = qCallerQParams.front(); qCallerQParams.pop(); } FUNCTION_LOG_END; return mret; } MVOID FeaturePipeP2aNode:: p2aCbFunc(QParams& rParams) { //FUNCTION_LOG_START; CAM_TRACE_FMT_BEGIN("P2ACb:%d", getMagicNo(rParams)); CPTLog(Event_FeaturePipe_P2A_FeatureStream, CPTFlagEnd); FeaturePipeP2aNode* pP2ANodeObj = (FeaturePipeP2aNode*)(rParams.mpCookie); if(!FEATURE_MASK_IS_VFB_ENABLED(pP2ANodeObj->mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(pP2ANodeObj->mFeatureOnMask) && !FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(pP2ANodeObj->mFeatureOnMask) && !FEATURE_MASK_IS_3DNR_ENABLED(pP2ANodeObj->mFeatureOnMask)) { Mutex::Autolock lock(pP2ANodeObj->mLock); /* Normal Stream: callback by enqued QParams */ rParams.mpCookie = pP2ANodeObj->mqCookie.front(); pP2ANodeObj->mqCookie.pop(); rParams.mpfnCallback = pP2ANodeObj->mqfnCallback.front(); pP2ANodeObj->mqfnCallback.pop(); pP2ANodeObj->mpFeaturePipeObj->performCallback(rParams); } else if ( (FEATURE_MASK_IS_3DNR_ENABLED(pP2ANodeObj->mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(pP2ANodeObj->mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(pP2ANodeObj->mFeatureOnMask) ) || (FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(pP2ANodeObj->mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(pP2ANodeObj->mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(pP2ANodeObj->mFeatureOnMask) ) ) { Mutex::Autolock lock(pP2ANodeObj->mLock); /* P2A-only Feature Stream: callback by enqued QParams */ MBOOL dequeSuccess = rParams.mDequeSuccess; rParams = pP2ANodeObj->mqCallbackQParams.front(); pP2ANodeObj->mqCallbackQParams.pop(); rParams.mDequeSuccess = dequeSuccess; pP2ANodeObj->handleP2Done(rParams); pP2ANodeObj->mpFeaturePipeObj->performCallback(rParams); } else { if(FEATURE_MASK_IS_EIS_ENABLED(pP2ANodeObj->mFeatureOnMask)) { reinterpret_cast<FeaturePipeEisNode*>(pP2ANodeObj->mpFeaturePipeObj->mpEisSwNode)->FlushMemory(EIS_DMA_FEO,EIS_FLUSH_SW); } pP2ANodeObj->handleP2Done(rParams); } CAM_TRACE_FMT_END(); //FUNCTION_LOG_END; } MBOOL FeaturePipeP2aNode:: handleP2Done(QParams& rParams) { LOG_DBG("Callback of frame %d", getMagicNo(rParams)); IImageBuffer* pFullImgBuffer = NULL; IImageBuffer* pDsImgBuffer = NULL; for(MUINT32 i = 0; i < rParams.mvOut.size(); i++) { if (rParams.mvOut[i].mPortID.index == NSImageio::NSIspio::EPortIndex_IMG3O) { pFullImgBuffer = rParams.mvOut[i].mBuffer; } else if (rParams.mvOut[i].mPortID.index == NSImageio::NSIspio::EPortIndex_WDMAO) { pDsImgBuffer = rParams.mvOut[i].mBuffer; } } // Flush for CPU read later if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { pDsImgBuffer->syncCache(eCACHECTRL_INVALID); } #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpp2a", EnableOption, "0"); if(EnableOption[0] == '2' || EnableOption[0] == '3') #endif { char szFileName[100]; if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)|| FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { ::sprintf(szFileName, "/sdcard/p2ao_%dx%d_%04d.yuv", NR3D_WORKING_BUFF_WIDTH, NR3D_WORKING_BUFF_HEIGHT, getMagicNo(rParams)); saveBufToFile(szFileName, (MUINT8*) pFullImgBuffer->getBufVA(0), NR3D_WORKING_BUFF_WIDTH * NR3D_WORKING_BUFF_HEIGHT * 3 / 2); } if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { ::sprintf(szFileName, "/sdcard/p2ao_%dx%d_%04d.yuv", pDsImgBuffer->getImgSize().w, pDsImgBuffer->getImgSize().h, getMagicNo(rParams)); pDsImgBuffer->saveToFile(szFileName); } } ImgRequest fullImgReq(pFullImgBuffer); ImgRequest dsImgReq(pDsImgBuffer); /* Post buffer to next node */ if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { LOG_DBG("Posting P2A->Switcher node full image buffer of frame %d", getMagicNo(rParams)); handlePostBuffer(P2A_TO_SWITCHER, (MUINTPTR) &fullImgReq, getMagicNo(rParams)); LOG_DBG("Posting P2A->VFB node DS image of frame %d", getMagicNo(rParams)); handlePostBuffer(P2A_TO_VFBSW_DSIMG, (MUINTPTR) &dsImgReq, getMagicNo(rParams)); LOG_DBG("Posting P2A->FD node DS image of frame %d", getMagicNo(rParams)); handlePostBuffer(P2A_TO_FD_DSIMG, (MUINTPTR) &dsImgReq, getMagicNo(rParams)); } if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { LOG_DBG("Posting P2A->EIS node full image buffer of frame %d", getMagicNo(rParams)); handlePostBuffer(P2A_TO_EISSW, (MUINTPTR) &fullImgReq, getMagicNo(rParams)); if (!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { LOG_DBG("Posting P2A->GPU node full image buffer of frame %d", getMagicNo(rParams)); handlePostBuffer(P2A_TO_GPU, (MUINTPTR) &fullImgReq, getMagicNo(rParams)); } } if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { /* 3DNR must wait for P2 H/W done so that its output can be input of next frame */ sem_post(&mCallbackSem); } return MTRUE; } MBOOL FeaturePipeP2aNode:: onPostBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { LOG_AST(false, "Never call P2A onPostBuffer!", 0); return false; } MBOOL FeaturePipeP2aNode:: threadLoopUpdate() { Mutex::Autolock autoLock(mUninitMtx); //FUNCTION_LOG_START; MRESULT mret = MFALSE; CPTLog(Event_FeaturePipe_P2AThread, CPTFlagStart); char aInputValue[PROPERTY_VALUE_MAX] = {'\0'}; MINT32 i4TempInputValue = 0; MUINT32 u4Img3oOffset_X = 0; MUINT32 u4Img3oOffset_Y = 0; MUINT32 eisFeBlock = 0; MUINT32 u4Img3oWidth = 0; MUINT32 u4Img3oHeight = 0; MUINT32 u4VipiWidth = 0; MUINT32 u4VipiHeight = 0; MUINT32 u4VipiStartAddrOffset = 0; MSize imgSize, TempImgSize; /************************************************************************/ /* Preprocessing */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // Process special request (e.g. adb command) // ////////////////////////////////////////////////////////////////////////// char p2aDebugFlag[PROPERTY_VALUE_MAX] = {'\0'}; property_get("debug.fpipe.p2a", p2aDebugFlag, "0"); ////////////////////////////////////////////////////////////////////////// // Get settings from MW // ////////////////////////////////////////////////////////////////////////// QParams InQParams; { Mutex::Autolock lock(mLock); InQParams = mqJob.front(); mqJob.pop(); } CAM_TRACE_FMT_BEGIN("P2AThread:%d", getMagicNo(InQParams)); if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { ////////////////////////////////////////////////////////////////////////// // 3DNR State Machine operation // ////////////////////////////////////////////////////////////////////////// if (m3dnrStateMachine == NR3D_STATE_PREPARING) // Last frame is NR3D_STATE_PREPARING. { m3dnrStateMachine = NR3D_STATE_WORKING; // NR3D, IMG3O, VIPI all enabled. } // Reset m3dnrErrorStatus. m3dnrErrorStatus = NR3D_ERROR_NONE; ////////////////////////////////////////////////////////////////////////// // 3DNR HW module on/off according Nr3dGain // ////////////////////////////////////////////////////////////////////////// MUINT32 u43dnrHwPowerOffThreshold = get_3dnr_hw_power_off_threshold(); MUINT32 u43dnrHwPowerReopenDelay = get_3dnr_hw_power_reopen_delay(); MINT32 i4Nr3dGain = 0; mpIFeatureStream->sendCommand(EPIPECmd_GET_NR3D_GAIN, getMagicNo(InQParams), (MINTPTR)&i4Nr3dGain); if (i4Nr3dGain) { if (m3dnrGainZeroCount > 0) // limit at 0. m3dnrGainZeroCount--; } else // i4Nr3dGain0 is 0. { m3dnrGainZeroCount++; if (m3dnrGainZeroCount > u43dnrHwPowerOffThreshold) // Cap at u43dnrHwPowerOffThreshold. m3dnrGainZeroCount = u43dnrHwPowerOffThreshold; } #if NR3D_NO_HW_POWER_OFF m3dnrGainZeroCount = 0; // For m3dnrGainZeroCount to be 0, so it won't change m3dnrStateMachine. #endif // NR3D_NO_HW_POWER_OFF if (m3dnrGainZeroCount >= u43dnrHwPowerOffThreshold) { m3dnrStateMachine = NR3D_STATE_STOP; } else if (m3dnrGainZeroCount > (u43dnrHwPowerOffThreshold - u43dnrHwPowerReopenDelay)) { // StateMachine stays the same. } else // (u43dnrHwPowerOffThreshold - u43dnrHwPowerReopenDelay) > m3dnrGainZeroCount > 0 { if (m3dnrStateMachine == NR3D_STATE_STOP) { m3dnrStateMachine = NR3D_STATE_PREPARING; m3dnrGainZeroCount = 0; // Reset m3dnrGainZeroCount. } } //LOG_DBG("i4Nr3dGain(%d), 3dnrGnZoCnt(%d), StateMachine(%d S0P1W2)", i4Nr3dGain, m3dnrGainZeroCount, m3dnrStateMachine); } ////////////////////////////////////////////////////////////////////////// // 3DNR GMV Calculation // ////////////////////////////////////////////////////////////////////////// // Get GMV from EIS HAL. // if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) // Workaround for EIS GMV Queue can't unregister user => Pass 2 always register user (in FeaturePipeP2aNode::onInit()), Pass 1 EIS always set GMV, Pass 2 always get GMV. if (!FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask)) //TODO { MINT32 i4TempNmvXFromQueue = 0, i4TempNmvYFromQueue = 0; EIS_P1_RESULT_INFO rEisResult; MBOOL fIsSupportEis = mpEisHalFor3DNR->GetEisSupportInfo(mOpenedSensorIndex); if (fIsSupportEis) // This sensor support EIS. { mpEisHalFor3DNR->GetEisInfoAtP2("FeaturePipe_3DNR", &rEisResult, InQParams.mvIn[0].mBuffer->getTimestamp(), MTRUE); //LOG_DBG("3DNR TS[%3d]: DoEisCount(%d), %s, EisTS(%lld), ImgiTS(%lld)", getMagicNo(InQParams), rEisResult.DoEisCount, ((rEisResult.timeStamp == InQParams.mvIn[0].mBuffer->getTimestamp()) ? ("==") : ("!=")), rEisResult.timeStamp, ((InQParams.mvIn.size()) ? (InQParams.mvIn[0].mBuffer->getTimestamp()) : (0)) ); // Check whether InQParams.mvIn.size() is not 0, if not 0, print IMGI TS, else print 0. if (rEisResult.timeStamp != InQParams.mvIn[0].mBuffer->getTimestamp()) // GMV is invalid, set GMV to 0. { m3dnrErrorStatus |= NR3D_ERROR_INVALID_GMV; if (m3dnrStateMachine == NR3D_STATE_WORKING) m3dnrStateMachine = NR3D_STATE_PREPARING; // Current frame don't do 3DNR, but IMG3O still needs to output current frame for next run use. i4TempNmvXFromQueue = 0; i4TempNmvYFromQueue = 0; } else { //i4TempNmvXFromQueue = (rEisResult.gmvX / 256); // The unit of Gmv is 256x 'pixel', so /256 to change unit to 'pixel'. >> 1 << 1: nr3d_on_w must be even, so make mNmvX even. Discussed with James Liang. //i4TempNmvYFromQueue = (rEisResult.gmvY / 256); // The unit of Gmv is 256x 'pixel', so /256 to change unit to 'pixel'. >> 1 << 1: nr3d_on_h must be even when image format is 420, so make mNmvX even. Discussed with TC & Christopher. i4TempNmvXFromQueue = (-(rEisResult.gmvX) / 256); // The unit of Gmv is 256x 'pixel', so /256 to change unit to 'pixel'. >> 1 << 1: nr3d_on_w must be even, so make mNmvX even. Discussed with James Liang. i4TempNmvYFromQueue = (-(rEisResult.gmvY) / 256); // The unit of Gmv is 256x 'pixel', so /256 to change unit to 'pixel'. >> 1 << 1: nr3d_on_h must be even when image format is 420, so make mNmvX even. Discussed with TC & Christopher. } } else // This sensor not support EIS. { i4TempNmvXFromQueue = 0; i4TempNmvYFromQueue = 0; } property_get("camera.3dnr.forcegmv.enable", aInputValue, "0"); if (aInputValue[0] == '1') { property_get("camera.3dnr.forcegmv.x", aInputValue, "0"); i4TempNmvXFromQueue = atoi(aInputValue); property_get("camera.3dnr.forcegmv.y", aInputValue, "0"); i4TempNmvYFromQueue = atoi(aInputValue); LOG_DBG("Force GMV X/Y (%d, %d)", i4TempNmvXFromQueue, i4TempNmvYFromQueue); } #if (NR3D_FORCE_GMV_ZERO) // Force GMV to be 0. mNmvX = 0; mNmvY = 0; #else // Normal flow. mNmvX = i4TempNmvXFromQueue & ~1; // Make it even. mNmvY = i4TempNmvYFromQueue & ~1; // Make it even. #endif // NR3D_FORCE_GMV_ZERO if ((abs(mNmvX) >= 28) || (abs(mNmvY) >= 28)) { m3dnrErrorStatus |= NR3D_ERROR_GMV_TOO_LARGE; if (m3dnrStateMachine == NR3D_STATE_WORKING) m3dnrStateMachine = NR3D_STATE_PREPARING; // Current frame don't do 3DNR, but IMG3O still needs to output current frame for next run use. } if(p2aDebugFlag[0] != '0') {LOG_DBG("mFeatureOnMask 0x%08x", mFeatureOnMask);} #if 0 // Special request for James. LOG_DBG("gmv_ana,frm[%3d],NmvX/Y(%3d,%3d),ConfidX/y(%3d,%3d)", getMagicNo(InQParams), mNmvX, mNmvY, rEisResult.gmvConfidX, rEisResult.gmvConfidY ); #else // Original LOG_DBG("gmv_ana,frm[%3d],gmv(x,y)=[%5d,%5d],IsSupportEis(%d),SenorIdx(%d),NmvX/Y(%5d,%5d)(ori %5d,%5d),x/yInt(%5d,%5d),x/yFlt(%9d,%9d),DoEisCount(%d),ConfidX/y(%d,%d),EisTS(%lld),ImgiTS(%lld),GnZoCnt(%d)", getMagicNo(InQParams), rEisResult.gmvX, rEisResult.gmvY, fIsSupportEis, mOpenedSensorIndex, mNmvX, mNmvY, i4TempNmvXFromQueue, i4TempNmvYFromQueue, rEisResult.cmvX_Int, rEisResult.cmvY_Int, rEisResult.cmvX_Flt, rEisResult.cmvY_Flt, rEisResult.DoEisCount, rEisResult.gmvConfidX, rEisResult.gmvConfidY, rEisResult.timeStamp, ((InQParams.mvIn.size()) ? (InQParams.mvIn[0].mBuffer->getTimestamp()) : (0)), // Check whether InQParams.mvIn.size() is not 0, if not 0, print IMGI TS, else print 0. m3dnrGainZeroCount ); #endif } /************************************************************************/ /* Config Input DMA (mvIn) according to infomation passed down by MW */ /************************************************************************/ #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpp2a", EnableOption, "0"); if (EnableOption[0] == '1' || EnableOption[0] == '3') #endif { char szFileName[100]; ::sprintf(szFileName, "/sdcard/p2ai_%dx%d_%04d.yuv", InQParams.mvIn[0].mBuffer->getImgSize().w, InQParams.mvIn[0].mBuffer->getImgSize().h, getMagicNo(InQParams)); LOG_DBG("DUMP p2ai(%s)",szFileName); InQParams.mvIn[0].mBuffer->saveToFile(szFileName); } MUINT32 eisCrop2Idx = 0; for (int i=0; i < InQParams.mvCropRsInfo.size(); i++) { if(p2aDebugFlag[0] != '0') { LOG_DBG("[Given mCropRsInfo] groupid(%d),crop w(%d),h(%d),p_int(%d,%d),p_fra(%d,%d), resize w(%d),h(%d)", InQParams.mvCropRsInfo[i].mGroupID,InQParams.mvCropRsInfo[i].mCropRect.s.w,InQParams.mvCropRsInfo[i].mCropRect.s.h,InQParams.mvCropRsInfo[i].mCropRect.p_integral.x,InQParams.mvCropRsInfo[i].mCropRect.p_integral.y, InQParams.mvCropRsInfo[i].mCropRect.p_fractional.x,InQParams.mvCropRsInfo[i].mCropRect.p_fractional.y,InQParams.mvCropRsInfo[i].mResizeDst.w,InQParams.mvCropRsInfo[i].mResizeDst.h); } if (InQParams.mvCropRsInfo[i].mGroupID == 2) { eisCrop2Idx = i; } } EIS_HAL_CONFIG_DATA eisConfigData; // Config mQParams. QParams mQParams; mQParams.mvIn.clear(); mQParams.mvIn.reserve(InQParams.mvIn.size()); mQParams.mvOut.clear(); mQParams.mFrameNo = getMagicNo(InQParams); if (InQParams.mvMagicNo.size()) mQParams.mvMagicNo.push_back(InQParams.mvMagicNo[0]); mQParams.mFrameNo = InQParams.mFrameNo; mQParams.mpPrivaData = InQParams.mpPrivaData; if (InQParams.mvPrivaData.size()) mQParams.mvPrivaData.push_back(InQParams.mvPrivaData[0]); if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { mQParams.mvOut.reserve(2); } else { mQParams.mvOut.reserve(1); } for (int i=0; i < InQParams.mvIn.size(); i++) { if(p2aDebugFlag[0] != '0') { LOG_DBG("[P2A sets mvIn (%d)] imgfmt(%d),w(%d),h(%d),type(%d),index(%d),inout(%d),mem( va(0x%x)/pa(0x%x)/size(0x%x) ),p2pxlid(%d),magicnum(%d),stride(%d)",i, InQParams.mvIn[i].mBuffer->getImgFormat(),InQParams.mvIn[i].mBuffer->getImgSize().w,InQParams.mvIn[i].mBuffer->getImgSize().h, InQParams.mvIn[i].mPortID.type,InQParams.mvIn[i].mPortID.index,InQParams.mvIn[i].mPortID.inout, InQParams.mvIn[i].mBuffer->getBufVA(0),InQParams.mvIn[i].mBuffer->getBufPA(0), InQParams.mvIn[i].mBuffer->getBufSizeInBytes(0),InQParams.mvIn[i].mExtraParams.p2pxlID,getMagicNo(InQParams), InQParams.mvIn[0].mBuffer->getBufStridesInBytes(0)); } mQParams.mvIn.push_back(InQParams.mvIn[i]); } /************************************************************************/ /* Config Output DMAs */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // Calculate target width/height to set IMG3O // ////////////////////////////////////////////////////////////////////////// // Set IMG3O info. ImgRequest fullImgReq; /* vFB and EIS have to use node buffer; otherwise, just use middleware buffer */ if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) ) { /* Calculate P2A output width and height */ MUINT32 PostProcOutWidth = 0, PostProcOutHeight = 0; // Decide W/H of the buffer for IMG3O use. for (int i=0; i < InQParams.mvOut.size(); i++) { if(p2aDebugFlag[0] != '0') { LOG_DBG("[P2A gets mvOut (%d)] imgfmt(%d),w(%d),h(%d),type(%d),index(%d),inout(%d),mem( va(0x%x)/pa(0x%x)/size(0x%x) ),p2pxlid(%d),magicnum(%d)",i, InQParams.mvOut[i].mBuffer->getImgFormat(),InQParams.mvOut[i].mBuffer->getImgSize().w,InQParams.mvOut[i].mBuffer->getImgSize().h, InQParams.mvOut[i].mPortID.type,InQParams.mvOut[i].mPortID.index,InQParams.mvOut[i].mPortID.inout, InQParams.mvOut[i].mBuffer->getBufVA(0),InQParams.mvOut[i].mBuffer->getBufPA(0), InQParams.mvOut[i].mBuffer->getBufSizeInBytes(0),InQParams.mvOut[i].mExtraParams.p2pxlID,getMagicNo(InQParams)); } // Use largest size of pass 2 output. if (PostProcOutWidth < InQParams.mvOut[i].mBuffer->getImgSize().w || PostProcOutHeight < InQParams.mvOut[i].mBuffer->getImgSize().h) { PostProcOutWidth = InQParams.mvOut[i].mBuffer->getImgSize().w; PostProcOutHeight = InQParams.mvOut[i].mBuffer->getImgSize().h; } } // EIS has special rules for deciding W/H of the buffer for IMG3O use. NSCamHW::Rect eisCropRect; if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { NSCamHW::Rect srcRect(InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.p_integral.x, InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.p_integral.y, InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.s.w, InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.s.h); NSCamHW::Rect dstRect(0, 0,InQParams.mvOut[0].mBuffer->getImgSize().w,InQParams.mvOut[0].mBuffer->getImgSize().h); // only use display ratio eisCropRect = android::MtkCamUtils::calCrop(srcRect,dstRect,100); eisCropRect.x += srcRect.x; eisCropRect.y += srcRect.y; LOG_DBG("[EIS]Idx(%u),ROI(%u,%u,%u,%u),Dst(0,0,%u,%u),Crop(%u,%u,%u,%u)",eisCrop2Idx, InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.p_integral.x, InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.p_integral.y, InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.s.w, InQParams.mvCropRsInfo[eisCrop2Idx].mCropRect.s.h, InQParams.mvOut[0].mBuffer->getImgSize().w, InQParams.mvOut[0].mBuffer->getImgSize().h, eisCropRect.x, eisCropRect.y, eisCropRect.w, eisCropRect.h); // if ROI is bigger than EIS limitation if((eisCropRect.w*eisCropRect.h) > (FULL_IMAGE_MAX_WIDTH*FULL_IMAGE_MAX_HEIGHT) || eisCropRect.w > FULL_IMAGE_MAX_WIDTH || eisCropRect.h > FULL_IMAGE_MAX_HEIGHT) { NSCamHW::Rect tempEisDstRect(0, 0,FULL_IMAGE_MAX_WIDTH,FULL_IMAGE_MAX_HEIGHT); NSCamHW::Rect tempEisSrcRect = android::MtkCamUtils::calCrop(srcRect,tempEisDstRect,100); NSCamHW::Rect tempEisCropRect = android::MtkCamUtils::calCrop(tempEisSrcRect,dstRect,100); tempEisCropRect.x += (srcRect.x+tempEisSrcRect.x); tempEisCropRect.y += (srcRect.y+tempEisSrcRect.y); LOG_DBG("[EIS]p2a out:(%u,%u,%u,%u)->(%u,%u,%u,%u)",eisCropRect.x,eisCropRect.y,eisCropRect.w,eisCropRect.h, tempEisCropRect.x,tempEisCropRect.y,tempEisCropRect.w,tempEisCropRect.h); eisCropRect.x = tempEisCropRect.x; eisCropRect.y = tempEisCropRect.y; eisCropRect.w = tempEisCropRect.w; eisCropRect.h = tempEisCropRect.h; } if(eisCropRect.w <= D1_WIDTH && eisCropRect.h <= D1_HEIGHT) { eisFeBlock = 8; } else if(eisCropRect.w <= EIS_FE_MAX_INPUT_W && eisCropRect.h <= EIS_FE_MAX_INPUT_H) { eisFeBlock = 16; } else { eisFeBlock = 32; LOG_WRN("FE should not use 32"); } eisCropRect.w = ALIGN_SIZE(eisCropRect.w,eisFeBlock); eisCropRect.h = ALIGN_SIZE(eisCropRect.h,eisFeBlock); PostProcOutWidth = eisCropRect.w; PostProcOutHeight = eisCropRect.h; eisConfigData.gpuTargetW=PostProcOutWidth/(reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->GetEisPlusCropRatio()/100.0); eisConfigData.gpuTargetH=PostProcOutHeight/(reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->GetEisPlusCropRatio()/100.0); eisConfigData.gpuTargetW = ROUND_TO_2X(eisConfigData.gpuTargetW); eisConfigData.gpuTargetH = ROUND_TO_2X(eisConfigData.gpuTargetH); // TODO-Need to modified for N3D/stereo eisConfigData.feTargetW = eisConfigData.gpuTargetW; eisConfigData.feTargetH = eisConfigData.gpuTargetH; LOG_DBG("[EIS]p2a final out(%u,%u),feBlock(%u)",PostProcOutWidth,PostProcOutHeight,eisFeBlock); } // If 3DNR+vFB/EIS2.0, follow vFB/EIS2.0 size. If 3DNR only, overwrite PostProcOutWidth/PostProcOutHeight. if ( FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) // When 3DNR only. { // Acquire IMG3O buffer size from MDP input crop size. MCrpRsInfo crop = InQParams.mvCropRsInfo[1]; // copy given group 2 (align mdp crop) PostProcOutWidth = crop.mCropRect.s.w; PostProcOutHeight = crop.mCropRect.s.h; } // W/H of buffer (i.e. Current frame size) is decided, so deque a buffer and resize it to calculated W/H. /* Prepare buffer for next node */ NodeDataTypes dType = FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)? P2A_TO_SWITCHER: P2A_TO_GPU; if(!pBufHandler->dequeBuffer(dType, &fullImgReq)) { LOG_AST(false, "dequeBuffer fail. Out of P2A_TO_GPU buffer", 0); return MFALSE; } // W/H of buffer (i.e. Current frame size) is determined, so check previous vs. current frame size for 3DNR. if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { if ( (mPrevFrameWidth != PostProcOutWidth) || (mPrevFrameHeight != PostProcOutHeight) ) { m3dnrErrorStatus |= NR3D_ERROR_FRAME_SIZE_CHANGED; if (m3dnrStateMachine == NR3D_STATE_WORKING) m3dnrStateMachine = NR3D_STATE_PREPARING; // Current frame don't do 3DNR, but IMG3O still needs to output current frame for next run use. } } if((fullImgReq.mBuffer->getImgSize().w != PostProcOutWidth) || (fullImgReq.mBuffer->getImgSize().h != PostProcOutHeight)) { LOG_DBG("Resize full image buffer from %dx%d to %dx%d", fullImgReq.mBuffer->getImgSize().w, fullImgReq.mBuffer->getImgSize().h, PostProcOutWidth, PostProcOutHeight); if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->resizeBuffer(dType, &fullImgReq.mBuffer, PostProcOutWidth, PostProcOutHeight) ) { LOG_ERR("Resize P2A_TO_GPU full image buffer failed"); return MFALSE; } } if ( FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) // When 3DNR only. { /* Output */ for (int i=0; i < InQParams.mvOut.size(); i++) { if(p2aDebugFlag[0] != '0') { LOG_DBG("[P2A 3DNR sets mvOut (%d)] imgfmt(%d),w(%d),h(%d),type(%d),index(%d),inout(%d),mem( va(0x%x)/pa(0x%x)/size(0x%x) ),p2pxlid(%d),magicnum(%d)",i, InQParams.mvOut[i].mBuffer->getImgFormat(), InQParams.mvOut[i].mBuffer->getImgSize().w, InQParams.mvOut[i].mBuffer->getImgSize().h, InQParams.mvOut[i].mPortID.type, InQParams.mvOut[i].mPortID.index, InQParams.mvOut[i].mPortID.inout, InQParams.mvOut[i].mBuffer->getBufVA(0), InQParams.mvOut[i].mBuffer->getBufPA(0), InQParams.mvOut[i].mBuffer->getBufSizeInBytes(0), InQParams.mvOut[i].mExtraParams.p2pxlID, getMagicNo(InQParams) ); } mQParams.mvOut.push_back(InQParams.mvOut[i]); } for (int i=0; i < InQParams.mvCropRsInfo.size(); i++) { MCrpRsInfo crop = InQParams.mvCropRsInfo[i]; if(p2aDebugFlag[0] != '0') { LOG_DBG("[P2A 3DNR sets mCropRsInfo] groupid(%d),crop w(%d),h(%d),p_int(%d,%d),p_fra(%d,%d), resize w(%d),h(%d)", crop.mGroupID,crop.mCropRect.s.w,crop.mCropRect.s.h,crop.mCropRect.p_integral.x,crop.mCropRect.p_integral.y, crop.mCropRect.p_fractional.x,crop.mCropRect.p_fractional.y,crop.mResizeDst.w,crop.mResizeDst.h); } mQParams.mvCropRsInfo.push_back(crop); } } // Set mCropRsInfo for cropGroup 1. if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { MCrpRsInfo eisCrop = InQParams.mvCropRsInfo[eisCrop2Idx]; eisCrop.mGroupID = 1; eisCrop.mCropRect.p_integral.x = eisCropRect.x; eisCrop.mCropRect.p_integral.y = eisCropRect.y; eisCrop.mCropRect.s.w = PostProcOutWidth; eisCrop.mCropRect.s.h = PostProcOutHeight; eisCrop.mResizeDst.w = PostProcOutWidth; eisCrop.mResizeDst.h = PostProcOutHeight; eisConfigData.crzOutW = eisCrop.mCropRect.s.w; eisConfigData.crzOutH = eisCrop.mCropRect.s.h; eisConfigData.srzOutW = eisCrop.mCropRect.s.w; //TODO : need to modified for stereo eisConfigData.srzOutH = eisCrop.mCropRect.s.h; //TODO : need to modified for stereo eisConfigData.cropX = eisCrop.mCropRect.p_integral.x; eisConfigData.cropY = eisCrop.mCropRect.p_integral.y; mQParams.mvCropRsInfo.push_back(eisCrop); LOG_DBG("[EIS crop]ID(%d),crop(%d,%d),p_int(%d,%d),p_fra(%d,%d),resize(%d,%d)", eisCrop.mGroupID,eisCrop.mCropRect.s.w,eisCrop.mCropRect.s.h,eisCrop.mCropRect.p_integral.x,eisCrop.mCropRect.p_integral.y, eisCrop.mCropRect.p_fractional.x,eisCrop.mCropRect.p_fractional.y,eisCrop.mResizeDst.w,eisCrop.mResizeDst.h); } else if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) // For non-EIS case, mCropRsInfo will not be changed, so use the mCropRsInfo MW passed down (InQParams.mvCropRsInfo[1]). { LOG_AST(InQParams.mvCropRsInfo.size() > 0, "Not given any crop info", 0); MCrpRsInfo crop = InQParams.mvCropRsInfo[1]; //copy given group 2 crop.mGroupID = 1; crop.mResizeDst = fullImgReq.mBuffer->getImgSize(); mQParams.mvCropRsInfo.push_back(crop); LOG_DBG("[P2A vFB sets mCropRsInfo] groupid(%d),crop w(%d),h(%d),p_int(%d,%d),p_fra(%d,%d), resize w(%d),h(%d)", crop.mGroupID,crop.mCropRect.s.w,crop.mCropRect.s.h,crop.mCropRect.p_integral.x,crop.mCropRect.p_integral.y, crop.mCropRect.p_fractional.x,crop.mCropRect.p_fractional.y,crop.mResizeDst.w,crop.mResizeDst.h); } } /************************************************************************/ /* Config WDMAO */ /************************************************************************/ ImgRequest dsImgReq; if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { static const NSCam::NSIoPipe::PortID WDMAO( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_WDMAO, 1); if(!pBufHandler->dequeBuffer(P2A_TO_VFBSW_DSIMG, &dsImgReq)) { LOG_AST(false, "Out of P2A_TO_VFBSW_DSIMG buffer", 0); return MFALSE; } MSize fullImgSize = fullImgReq.mBuffer->getImgSize(); MSize dsImgSize; #ifdef MTK_CAM_VIDEO_FACEBEAUTY_SUPPORT reinterpret_cast<FeaturePipeVfbNode*>(mpFeaturePipeObj->mpVfbSwNode)->getDSImgSize(fullImgSize, dsImgSize); #endif if ((dsImgReq.mBuffer->getImgSize().w != dsImgSize.w) || (dsImgReq.mBuffer->getImgSize().h != dsImgSize.h)) { LOG_DBG("Resize DS image buffer to %dx%d", dsImgSize.w, dsImgSize.h); if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->resizeBuffer(P2A_TO_VFBSW_DSIMG, &dsImgReq.mBuffer, dsImgSize.w, dsImgSize.h) ) { LOG_ERR("Resize full image buffer failed"); return MFALSE; } } NSCam::NSIoPipe::NSPostProc::Output moutput; /* PRZO */ moutput.mPortID = WDMAO; moutput.mBuffer = const_cast<IImageBuffer*>(dsImgReq.mBuffer); mQParams.mvOut.push_back(moutput); LOG_DBG("[P2A sets WDMAO mvOut] imgfmt(%d),w(%d),h(%d),type(%d),index(%d),inout(%d),mem( va(0x%x)/pa(0x%x)/size(0x%x) ),p2pxlid(%d)", moutput.mBuffer->getImgFormat(),moutput.mBuffer->getImgSize().w,moutput.mBuffer->getImgSize().h, moutput.mPortID.type,moutput.mPortID.index,moutput.mPortID.inout, moutput.mBuffer->getBufVA(0),moutput.mBuffer->getBufPA(0), moutput.mBuffer->getBufSizeInBytes(0),moutput.mExtraParams.p2pxlID); // MCrpRsInfo crop; crop.mGroupID = 2; crop.mCropRect.s = fullImgReq.mBuffer->getImgSize(); crop.mCropRect.p_integral.x = 0; crop.mCropRect.p_integral.y = 0; crop.mCropRect.p_fractional.x = 0; crop.mCropRect.p_fractional.y = 0; crop.mResizeDst = {0,0}; mQParams.mvCropRsInfo.push_back(crop); LOG_DBG("[P2A sets mCropRsInfo] groupid(%d),crop w(%d),h(%d),p_int(%d,%d),p_fra(%d,%d), resize w(%d),h(%d)", crop.mGroupID,crop.mCropRect.s.w,crop.mCropRect.s.h,crop.mCropRect.p_integral.x,crop.mCropRect.p_integral.y, crop.mCropRect.p_fractional.x,crop.mCropRect.p_fractional.y,crop.mResizeDst.w,crop.mResizeDst.h); } /************************************************************************/ /* Config IMG3O */ /************************************************************************/ if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) ) { // Config P2A output DMA(IMG3O) for 3DNR. IMG3O uses 3DNR output current frame setting. Other output DMAs use original setting pass down from MiddleWare. static const NSCam::NSIoPipe::PortID IMG3O( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_IMG3O, 1); NSCam::NSIoPipe::NSPostProc::Output moutput; moutput.mPortID = IMG3O; moutput.mBuffer = const_cast<IImageBuffer*>(fullImgReq.mBuffer); // IMG3O Offset #if 0 MCrpRsInfo MdpCrop; MdpCrop = mQParams.mvCropRsInfo[1]; // copy given group 2 (align mdp crop) #else // Modified. MCrpRsInfo MdpCrop; if ( !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) && FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) ) // For 3DNR+EIS2.0 { //MdpCrop = mQParams.mvCropRsInfo[0]; // copy given group 1 (align crz) u4Img3oOffset_X = 0; // MDP crop offset (unit of crop.mCropRect.p_integral.x is pixel) u4Img3oOffset_Y = 0; // MDP crop offset (unit of crop.mCropRect.p_integral.y is pixel) } else // For 3DNR only, vFB only, EIS2.0 only, 3DNR+vFB, or 3DNR+vFB+EIS2.0 { MdpCrop = mQParams.mvCropRsInfo[1]; // copy given group 2 (align mdp crop) u4Img3oOffset_X = MdpCrop.mCropRect.p_integral.x & ~1; // MDP crop offset (unit of crop.mCropRect.p_integral.x is pixel) u4Img3oOffset_Y = MdpCrop.mCropRect.p_integral.y & ~1; // MDP crop offset (unit of crop.mCropRect.p_integral.y is pixel) } #endif // Assign IMG3O buffer with current frame time stamp. moutput.mBuffer->setTimestamp(InQParams.mvIn[0].mBuffer->getTimestamp()); if ( !FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) || m3dnrStateMachine != NR3D_STATE_STOP ) // If not 3DNR only or 3DNR State Machine is not NR3D_STATE_STOP. { mQParams.mvOut.push_back(moutput); // Only don't enable IMG3O when 3DNR only and 3DNR state machine is NR3D_STATE_STOP. LOG_DBG("[P2A sets IMG3O mvOut] 3dnrSM0(%d S0P1W2),ES(0x%02X FsSzDfLrIn),WH(%d,%d),OfstXY(%d,%d),mem<va(0x%x)/pa(0x%x)/TS(%lld)/size(0x%x)>", m3dnrStateMachine, m3dnrErrorStatus, moutput.mBuffer->getImgSize().w, moutput.mBuffer->getImgSize().h, u4Img3oOffset_X, u4Img3oOffset_Y, moutput.mBuffer->getBufVA(0), moutput.mBuffer->getBufPA(0), moutput.mBuffer->getTimestamp(), moutput.mBuffer->getBufSizeInBytes(0) //moutput.mBuffer->getImgFormat(), //moutput.mPortID.type, moutput.mPortID.index, moutput.mPortID.inout, //moutput.mExtraParams.p2pxlID, //moutput.mBuffer->getBufStridesInBytes(0) ); // Record IMG3O W/H for later use. u4Img3oWidth = moutput.mBuffer->getImgSize().w; u4Img3oHeight = moutput.mBuffer->getImgSize().h; } else { LOG_DBG("[P2A not sets IMG3O mvOut] 3dnrSM0(%d S0P1W2),ES(0x%02X FsSzDfLrIn),WH(%d,%d),OfstXY(%d,%d),mem<va(0x%x)/pa(0x%x)/TS(%lld)/size(0x%x)>", m3dnrStateMachine, m3dnrErrorStatus, moutput.mBuffer->getImgSize().w, moutput.mBuffer->getImgSize().h, u4Img3oOffset_X, u4Img3oOffset_Y, moutput.mBuffer->getBufVA(0), moutput.mBuffer->getBufPA(0), moutput.mBuffer->getTimestamp(), moutput.mBuffer->getBufSizeInBytes(0) //moutput.mBuffer->getImgFormat(), //moutput.mPortID.type, moutput.mPortID.index, moutput.mPortID.inout, //moutput.mExtraParams.p2pxlID, //moutput.mBuffer->getBufStridesInBytes(0) ); // Record IMG3O W/H for later use. u4Img3oWidth = moutput.mBuffer->getImgSize().w; u4Img3oHeight = moutput.mBuffer->getImgSize().h; } } /************************************************************************/ /* ??? */ /************************************************************************/ //>> EIS if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { eisConfigData.imgiW = InQParams.mvIn[0].mBuffer->getImgSize().w; eisConfigData.imgiH = InQParams.mvIn[0].mBuffer->getImgSize().h; eisConfigData.configSce = EIS_SCE_EIS_PLUS; LOG_DBG("[FPipe ConfigEis] imgi(%u,%u),crz(%u,%u),srz(%u,%u),feT(%u,%u),gpuT(%u,%u),crop(%u,%u),sce(%d)",eisConfigData.imgiW, eisConfigData.imgiH, eisConfigData.crzOutW, eisConfigData.crzOutH, eisConfigData.srzOutW, eisConfigData.srzOutH, eisConfigData.feTargetW, eisConfigData.feTargetH, eisConfigData.gpuTargetW, eisConfigData.gpuTargetH, eisConfigData.cropX, eisConfigData.cropY, eisConfigData.configSce); if(MTRUE != reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->ConfigEis(EIS_PASS_2,eisConfigData)) { LOG_ERR("FPipe ConfigEis fail"); return MFALSE; } } /************************************************************************/ /* Config VIPI */ /************************************************************************/ // Config VIPI for 3DNR previous frame input. if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { MUINT32 u4VipiOffset_X = 0; MUINT32 u4VipiOffset_Y = 0; MUINT32 u4PixelToBytes = 0; /* VIPI */ static const NSCam::NSIoPipe::PortID VIPI( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_VIPI, 0/*in*/); NSCam::NSIoPipe::NSPostProc::Input minput; minput.mPortID = VIPI; if (!m3dnrPrvFrmQueue.empty()) { FeaturePipeNodeImgReqJob_s jobFullImg; // Get previous frame from mqJobFullImg. jobFullImg = m3dnrPrvFrmQueue.front(); minput.mBuffer = const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer); // Calculate VIPI Start Address = nmv_x + nmv_y * vipi_stride. Unit: bytes. // Calculate Offset X/Y according to NMV X/Y. u4VipiOffset_X = (mNmvX >= 0) ? (mNmvX): (0); u4VipiOffset_Y = (mNmvY >= 0) ? (mNmvY): (0); // Calculate u4PixelToBytes. if (minput.mBuffer->getImgFormat() == eImgFmt_YUY2) u4PixelToBytes = 2; if (minput.mBuffer->getImgFormat() == eImgFmt_YV12) u4PixelToBytes = 1; // Calculate VIPI start addr offset. u4VipiStartAddrOffset = u4VipiOffset_Y * minput.mBuffer->getBufStridesInBytes(0) + u4VipiOffset_X * u4PixelToBytes; // Calculate VIPI valid region w/h. TempImgSize.w = minput.mBuffer->getImgSize().w - abs(mNmvX); // valid region w TempImgSize.h = minput.mBuffer->getImgSize().h - abs(mNmvY); // valid region h imgSize.w = TempImgSize.w & ~1; // valid region w imgSize.h = TempImgSize.h & ~1; // valid region h // Set VIPI start addr offset and region w/h. //minput.mBuffer->setExtParam(imgSize, u4VipiStartAddrOffset); // Check whether current frame size is equal to last frame size. property_get("camera.3dnr.forceskip", aInputValue, "0"); if (aInputValue[0] == '1') { m3dnrErrorStatus |= NR3D_ERROR_FORCE_SKIP; if (m3dnrStateMachine == NR3D_STATE_WORKING) m3dnrStateMachine = NR3D_STATE_PREPARING; // Current frame don't do 3DNR, but IMG3O still needs to output current frame for next run use. } if (m3dnrStateMachine == NR3D_STATE_WORKING) { mQParams.mvIn.push_back(minput); // Only push_back VIPI when N3RD state machine is NR3D_STATE_WORKING. //LOG_DBG("push_back VIPI buffer."); LOG_DBG("[P2A sets VIPI mvIn ] 3dnrSM1(%d S0P1W2),ES(0x%02X FsSzDfLrIn),WH(%d,%d),OfstXY(%d,%d),mem<va(0x%x)/pa(0x%x)/TS(%lld)/size(0x%x)>,mPrvQueSz(%d),imgSizeWH(%d,%d),PrvWH(%d,%d),ExtOfstByte(%d)", m3dnrStateMachine, m3dnrErrorStatus, minput.mBuffer->getImgSize().w, minput.mBuffer->getImgSize().h, u4VipiOffset_X, u4VipiOffset_Y, minput.mBuffer->getBufVA(0), minput.mBuffer->getBufPA(0), minput.mBuffer->getTimestamp(), minput.mBuffer->getBufSizeInBytes(0), (m3dnrPrvFrmQueue.empty()) ? (0) : (m3dnrPrvFrmQueue.size()), imgSize.w,imgSize.h, mPrevFrameWidth, mPrevFrameHeight, minput.mBuffer->getExtOffsetInBytes(0) ); // Record VIPI W/H for later use. u4VipiWidth = imgSize.w;//minput.mBuffer->getImgSize().w; u4VipiHeight = imgSize.h;//minput.mBuffer->getImgSize().h; } else // Not NR3D_STATE_WORKING. { LOG_DBG("[P2A not sets VIPI mvIn ] 3dnrSM1(%d S0P1W2),ES(0x%02X FsSzDfLrIn),WH(%d,%d),OfstXY(%d,%d),mem<va(0x%x)/pa(0x%x)/TS(%lld)/size(0x%x)>,mPrvQueSz(%d),imgSizeWH(%d,%d),PrvWH(%d,%d),ExtOfstByte(%d)", m3dnrStateMachine, m3dnrErrorStatus, minput.mBuffer->getImgSize().w, minput.mBuffer->getImgSize().h, u4VipiOffset_X, u4VipiOffset_Y, minput.mBuffer->getBufVA(0), minput.mBuffer->getBufPA(0), minput.mBuffer->getTimestamp(), minput.mBuffer->getBufSizeInBytes(0), (m3dnrPrvFrmQueue.empty()) ? (0) : (m3dnrPrvFrmQueue.size()), imgSize.w,imgSize.h, mPrevFrameWidth, mPrevFrameHeight, minput.mBuffer->getExtOffsetInBytes(0) ); // Record VIPI W/H for later use. u4VipiWidth = 0; u4VipiHeight = 0; } } else { LOG_DBG("[P2A not sets VIPI mvIn ] 3dnrSM1(%d S0P1W2),ES(0x%02X FsSzDfLrIn). m3dnrPrvFrmQueue is empty", m3dnrStateMachine, m3dnrErrorStatus); // m3dnrPrvFrmQueue is empty => maybe first run. // Record VIPI W/H for later use. u4VipiWidth = 0; u4VipiHeight = 0; } } /************************************************************************/ /* Config enque parameters for 3DNR */ /************************************************************************/ ModuleInfo moduleinfo; //set for nr3d module if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { if (m3dnrStateMachine == NR3D_STATE_WORKING) // Only set NR3D register when N3RD state machine is NR3D_STATE_WORKING. { mpNr3dParam->ctrl_onEn = 1; mpNr3dParam->onOff_onOfStX = ((mNmvX >= 0) ? (0) : (-mNmvX)) + u4Img3oOffset_X; // Must be even. mpNr3dParam->onOff_onOfStY = ((mNmvY >= 0) ? (0) : (-mNmvY)) + u4Img3oOffset_Y; mpNr3dParam->onSiz_onWd = u4VipiWidth & ~1; // Must be even. mpNr3dParam->onSiz_onHt = u4VipiHeight & ~1; mpNr3dParam->vipi_offst = u4VipiStartAddrOffset; //in byte mpNr3dParam->vipi_readW = imgSize.w; //in pixel mpNr3dParam->vipi_readH = imgSize.h; //in pixel moduleinfo.moduleTag = EFeatureModule_NR3D; moduleinfo.moduleStruct = reinterpret_cast<MVOID*> (mpNr3dParam); mQParams.mvModuleData.push_back(moduleinfo); // Only push_back moduleinfo (i.e. driver will enable NR3D HW module) when N3RD status is normal. // Raise AE ISO limit to 130%. Parameter meaning: MTRUE: Enable the function. MTRUE: Need to equivalent for orginal BV range. 130: Raise Increase ISO Limit to 130% (increase 30%). 100: it means don't need to increase. mp3AHal->modifyPlineTableLimitation(MTRUE, MTRUE, get_3dnr_max_iso_increase_percentage(), 100); } else // 3DNR not in working state, don't do 3DNR. { mpNr3dParam->ctrl_onEn = 1; mpNr3dParam->onOff_onOfStX = 0; // Must be even. mpNr3dParam->onOff_onOfStY = 0; mpNr3dParam->onSiz_onWd = 0; // Must be even. mpNr3dParam->onSiz_onHt = 0; mpNr3dParam->vipi_offst = 0; //in byte mpNr3dParam->vipi_readW = 0; //in pixel mpNr3dParam->vipi_readH = 0; //in pixel // Restore AE ISO limit to 100%. Parameter meaning: MTRUE: Enable the function. MTRUE: Need to equivalent for orginal BV range. 100: it means don't need to increase. 100: it means don't need to increase. mp3AHal->modifyPlineTableLimitation(MTRUE, MTRUE, 100, 100); } LOG_DBG("3dnrSM2(%d S0P1W2),ES(0x%02X FsSzDfLrIn),NmvX/Y(%d, %d).Img3oOfX/Y(%d, %d),onOfX/Y(%d, %d).onW/H(%d, %d).VipiOff/W/H(%d, %d, %d).MaxIsoInc(%d)", m3dnrStateMachine, m3dnrErrorStatus, mNmvX, mNmvY, u4Img3oOffset_X, u4Img3oOffset_Y, mpNr3dParam->onOff_onOfStX, mpNr3dParam->onOff_onOfStY, mpNr3dParam->onSiz_onWd, mpNr3dParam->onSiz_onHt, mpNr3dParam->vipi_offst, mpNr3dParam->vipi_readW, mpNr3dParam->vipi_readH, get_3dnr_max_iso_increase_percentage() ); // Recordng mPrevFrameWidth/mPrevFrameHeight for next frame. mPrevFrameWidth = u4Img3oWidth; mPrevFrameHeight = u4Img3oHeight; } // Config enque parameters for EIS. ModuleInfo eisFeoModuleinfo; if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { //> get feo info FEO_REG_INFO feoRegInfo; reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->GetFeoRegInfo(&feoRegInfo); mpFeoParam->bufInfo.size = feoRegInfo.size; mpFeoParam->bufInfo.memID = feoRegInfo.memID; mpFeoParam->bufInfo.virtAddr = feoRegInfo.va; mpFeoParam->bufInfo.phyAddr = feoRegInfo.pa; mpFeoParam->bufInfo.bufSecu = feoRegInfo.bufSecu; mpFeoParam->bufInfo.bufCohe = feoRegInfo.bufCohe; mpFeoParam->bufInfo.useNoncache = feoRegInfo.useNoncache; for(MUINT32 i = 0; i < mQParams.mvOut.size(); i++) { if(mQParams.mvOut[i].mPortID.index == NSImageio::NSIspio::EPortIndex_IMG3O) { mpFeoParam->w = (mQParams.mvOut[i].mBuffer->getImgSize().w / eisFeBlock) * 56; mpFeoParam->h = mQParams.mvOut[i].mBuffer->getImgSize().h / eisFeBlock; LOG_DBG("[FPipeEis](%d,%d),block(%u)",mQParams.mvOut[i].mBuffer->getImgSize().w,mQParams.mvOut[i].mBuffer->getImgSize().h,eisFeBlock); break; } } mpFeoParam->stride = feoRegInfo.stride; mpFeoParam->port_idx = NSImageio::NSIspio::EPortIndex_FEO; mpFeoParam->port_type = NSIoPipe::EPortType_Memory; mpFeoParam->port_inout = 1; eisFeoModuleinfo.moduleTag = EFeatureModule_STA_FEO; eisFeoModuleinfo.moduleStruct = reinterpret_cast<MVOID*>(mpFeoParam); mQParams.mvModuleData.push_back(eisFeoModuleinfo); } #ifdef MTK_CAM_VHDR_SUPPORT if(FEATURE_MASK_IS_VHDR_ENABLED(mFeatureOnMask)) { LCEI_DMA_INFO aLceiDma; ModuleInfo vhdrLceiModuleinfo; //> get LCEI info mpVHdrObj->GetLceiDmaInfo(&aLceiDma,InQParams.mvIn[0].mBuffer->getTimestamp()); if(aLceiDma.memID == VHDR_LCSO_SYNC_FAIL) { LOG_ERR("[FPipe] VHDR_LCSO_SYNC_FAIL"); } //> prepare info and push to QParam mpLceiParam->bufInfo.size = aLceiDma.size; mpLceiParam->bufInfo.memID = aLceiDma.memID; mpLceiParam->bufInfo.virtAddr = aLceiDma.va; mpLceiParam->bufInfo.phyAddr = aLceiDma.pa; mpLceiParam->bufInfo.bufSecu = aLceiDma.bufSecu; mpLceiParam->bufInfo.bufCohe = aLceiDma.bufCohe; mpLceiParam->bufInfo.useNoncache = aLceiDma.useNoncache; mpLceiParam->w = aLceiDma.xSize; mpLceiParam->h = aLceiDma.ySize; mpLceiParam->stride = aLceiDma.stride; mpLceiParam->port_idx = NSImageio::NSIspio::EPortIndex_LCEI; mpLceiParam->port_type = NSIoPipe::EPortType_Memory; mpLceiParam->port_inout = 1; vhdrLceiModuleinfo.moduleTag = EFeatureModule_STA_LCEI; vhdrLceiModuleinfo.moduleStruct = reinterpret_cast<MVOID*>(mpLceiParam); LOG_DBG("[FPipe] LCEI_PA(0x%08x)",mpLceiParam->bufInfo.phyAddr); mQParams.mvModuleData.push_back(vhdrLceiModuleinfo); } #endif /************************************************************************/ /* Config enque parameters for Stereo Camera */ /************************************************************************/ if (FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask)) { if (!FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) // When Stereo Camera only { for (int i=0; i < InQParams.mvOut.size(); i++) { mQParams.mvOut.push_back(InQParams.mvOut[i]); } for (int i=0; i < InQParams.mvCropRsInfo.size(); i++) { MCrpRsInfo crop = InQParams.mvCropRsInfo[i]; mQParams.mvCropRsInfo.push_back(crop); } } for(int i=0; i<InQParams.mvModuleData.size(); i++) { if(InQParams.mvModuleData[i].moduleTag == (MINT32)(EFeatureModule_STA_FEO) || InQParams.mvModuleData[i].moduleTag == (MINT32)(EFeatureModule_SRZ1) || InQParams.mvModuleData[i].moduleTag == (MINT32)(EFeatureModule_FE)) { LOG_DBG("[FPipe] Stereo pushing %s data", (InQParams.mvModuleData[i].moduleTag == (MINT32)(EFeatureModule_STA_FEO))? "FEO": ((InQParams.mvModuleData[i].moduleTag == (MINT32)(EFeatureModule_SRZ1))?"SRZ":"FE")); mQParams.mvModuleData.push_back(InQParams.mvModuleData[i]); } } } /* Enque */ CPTLog(Event_FeaturePipe_P2A_FeatureStream, CPTFlagStart); if (InQParams.mpfnCallback != NULL) { mQParams.mpCookie = this; mQParams.mpfnCallback = p2aCbFunc; if ( ( FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) || ( FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) ) ) { Mutex::Autolock lock(mLock); mqCallbackQParams.push(InQParams); } } // mpIFeatureStream enque for 3DNR/EIS. if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_STEREO_CAMERA_ENABLED(mFeatureOnMask)) { LOG_DBG("FStrm enq (frame %d)", getMagicNo(mQParams)); if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->FlushMemory(EIS_DMA_FEO,EIS_FLUSH_HW); } CAM_TRACE_FMT_BEGIN("P2AFStrm:%d", getMagicNo(InQParams)); MBOOL ret = mpIFeatureStream->enque(mQParams); CAM_TRACE_FMT_END(); if (!ret) { LOG_ERR("IFeatureStream enque failed!"); AEE_ASSERT("IFeatureStream enque failed"); return MFALSE; } } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { handlePostBuffer(P2A_TO_P2B, (MUINTPTR) &InQParams, getMagicNo(InQParams)); } else if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { handlePostBuffer(P2A_TO_MDP_QPARAMS, (MUINTPTR) &InQParams, getMagicNo(InQParams)); } /* Deque */ if (InQParams.mpfnCallback == NULL) { QParams outParams; if(FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { //MBOOL ret = mpIFeatureStream->deque(outParams, -1/*TODO*/, mQFeatureData); MBOOL ret = mpIFeatureStream->deque(outParams, -1/*TODO*/); if (!ret) { LOG_ERR("IFeatureStream deque failed(frame %d)", getMagicNo(outParams)); return MFALSE; } if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->FlushMemory(EIS_DMA_FEO,EIS_FLUSH_SW); } LOG_DBG("IFeatureStream deque succeeds(frame %d)", getMagicNo(outParams)); if (InQParams.mpfnCallback == NULL) { Mutex::Autolock lock(mLock); InQParams.mDequeSuccess = outParams.mDequeSuccess; qCallerQParams.push(InQParams); sem_post(&mModuleSem); } } else { if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { MBOOL ret = mpIFeatureStream->deque(outParams, -1/*TODO*/); reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->FlushMemory(EIS_DMA_FEO,EIS_FLUSH_SW); if (!ret) { LOG_ERR("IFeatureStream EisPlus deque failed(frame %d)", getMagicNo(outParams)); return MFALSE; } LOG_DBG("IFeatureStream EisPlus deque succeeds(frame %d)", getMagicNo(outParams)); } else //vFB { MBOOL ret = mpIFeatureStream->deque(outParams, -1/*TODO*/); if (!ret) { LOG_ERR("IFeatureStream deque failed! (frame %d)", getMagicNo(outParams)); return MFALSE; } LOG_DBG("IFeatureStream deque succeeds! (frame %d)", getMagicNo(outParams)); } } CPTLog(Event_FeaturePipe_P2A_FeatureStream, CPTFlagEnd); handleP2Done(outParams); } // When 3DNR only, return (i.e. enque) previous frame buffer because it won't be used anymore. if (FEATURE_MASK_IS_3DNR_ENABLED(mFeatureOnMask)) { sem_wait(&mCallbackSem); FeaturePipeNodeImgReqJob_s jobFullImg; if (!m3dnrPrvFrmQueue.empty()) { jobFullImg = m3dnrPrvFrmQueue.front(); m3dnrPrvFrmQueue.pop(); if (!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && !FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { pBufHandler->enqueBuffer(P2A_TO_GPU, jobFullImg.imgReq.mBuffer); } } // Push current frame for next run use as previous frame. FeaturePipeNodeImgReqJob_s job; job.imgReq = fullImgReq; job.mFrameNo = getMagicNo(mQParams); m3dnrPrvFrmQueue.push(job); } CPTLog(Event_FeaturePipe_P2AThread, CPTFlagEnd); CAM_TRACE_FMT_END(); //FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2aNode:: onReturnBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { //FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); switch (data) { case P2A_TO_VFBSW_DSIMG: case P2A_TO_SWITCHER: case P2A_TO_GPU: LOG_DBG("Recycling P2A node %s image of frame %d", (data == P2A_TO_VFBSW_DSIMG)? "DS": "full", ext); pBufHandler->enqueBuffer(data, ((ImgRequest*)buf)->mBuffer); break; case P2A_TO_EISSW: case P2A_TO_FD_DSIMG: /* Do nothing. Wait until VFB returns DS image buffer */ break; } //FUNCTION_LOG_END; return MTRUE; } MVOID FeaturePipeP2aNode:: onDumpBuffer(const char* usr, MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { } /****************************************************************************** * ******************************************************************************/ #undef LOG_VRB #undef LOG_DBG #undef LOG_DBG #undef LOG_WRN #undef LOG_ERR #undef LOG_AST #define LOG_VRB(fmt, arg...) CAM_LOGV("[SWT:%s] " fmt, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGD("[SWT:%s] " fmt, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGI("[SWT:%s] " fmt, __func__, ##arg) #define LOG_WRN(fmt, arg...) CAM_LOGW("[SWT:%s] " fmt, __func__, ##arg) #define LOG_ERR(fmt, arg...) CAM_LOGE("[SWT:%s] " fmt, __func__, ##arg) #define LOG_AST(cond, fmt, arg...) do{ if(!cond) CAM_LOGA("[SWT:%s] " fmt, __func__, ##arg); } while(0) FeaturePipeSwitcherNode* FeaturePipeSwitcherNode::createInstance(MUINT32 featureOnMask, FeaturePipe *pFeaturePipeObj) { return new FeaturePipeSwitcherNode("FeaturePipeSwitcherNode", SingleTrigger, SCHED_POLICY, SCHED_PRIORITY, featureOnMask, pFeaturePipeObj); } MVOID FeaturePipeSwitcherNode::destroyInstance() { delete this; } FeaturePipeSwitcherNode::FeaturePipeSwitcherNode( const char* name, eThreadNodeType type, int policy, int priority, MUINT32 featureOnMask, FeaturePipe *pFeaturePipeObj ) : FeaturePipeNode(name, type, policy, priority, featureOnMask, 0, pFeaturePipeObj), mVfbExtreme(true), mGpuProcCount(0) { if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_SRC, P2A_TO_SWITCHER); addDataSupport(ENDPOINT_SRC, MDP_TO_SWITCHER); addDataSupport(ENDPOINT_DST, SWITCHER_TO_GPU); addDataSupport(ENDPOINT_DST, SWITCHER_TO_VFBSW); addDataSupport(ENDPOINT_DST, SWITCHER_TO_P2B); addNotifySupport(FEATURE_MASK_CHANGE); } } MBOOL FeaturePipeSwitcherNode::onInit() { FUNCTION_LOG_START; FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeSwitcherNode:: onUninit() { FUNCTION_LOG_START; FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeSwitcherNode:: onStart() { FUNCTION_LOG_START; FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeSwitcherNode:: onStop() { FUNCTION_LOG_START; MBOOL ret = syncWithThread(); // wait for jobs done FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeSwitcherNode:: onNotify(MUINT32 const datamsg, MUINT32 const ext1, MUINT32 const ext2) { FUNCTION_LOG_START; LOG_DBG("datamsg(0x%x), ext1(0x%x), ext2(0x%x)", datamsg, ext1, ext2); FUNCTION_LOG_END; return MTRUE; } MVOID FeaturePipeSwitcherNode:: setVfbExtreme(MBOOL mode) { Mutex::Autolock lock(mVfbExtremeLock); mVfbExtreme = mode; } MBOOL FeaturePipeSwitcherNode:: onPostBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); Mutex::Autolock lock(mLock); FeaturePipeNodeImgReqJob_s job; job.imgReq = *(ImgRequest*) buf; job.mFrameNo = ext; switch (data) { case P2A_TO_SWITCHER: mqJobFromP2a.push(job); triggerLoop(); break; case MDP_TO_SWITCHER: mqJobFromGpu.push(job); triggerLoop(); break; } FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeSwitcherNode:: threadLoopUpdate() { FUNCTION_LOG_START; if (mqJobFromGpu.empty() && mqJobFromP2a.empty()) return MTRUE; if (!mqJobFromGpu.empty()) { FeaturePipeNodeImgReqJob_s job; { Mutex::Autolock lock(mLock); /* Get full image job */ job = mqJobFromGpu.front(); mqJobFromGpu.pop(); mqGpuToP2b.push(MTRUE); } /* Post buffer to next node */ LOG_DBG("Posting SWITCHER(GPU)->P2B node full image of frame %d", job.mFrameNo); handlePostBuffer(SWITCHER_TO_P2B, (MUINTPTR) &job.imgReq, job.mFrameNo); LOG_AST(mGpuProcCount>0, "Switcher GPU-processing counter is wrong", 0); mGpuProcCount--; } { Mutex::Autolock lock(mVfbExtremeLock); if (mVfbExtreme || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask) || (mGpuProcCount == 0)) { while(!mqJobFromP2a.empty()) { FeaturePipeNodeImgReqJob_s job; { Mutex::Autolock lock(mLock); /* Get full image job */ job = mqJobFromP2a.front(); mqJobFromP2a.pop(); } LOG_DBG("vFB %s mode", mVfbExtreme? "Extreme": "Normal"); if (mVfbExtreme || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { LOG_DBG("Posting SWITCHER->GPU node full image of frame %d", job.mFrameNo); handlePostBuffer(SWITCHER_TO_GPU, (MUINTPTR) &job.imgReq, job.mFrameNo); mGpuProcCount++; } else { { Mutex::Autolock lock(mLock); mqGpuToP2b.push(MFALSE); } LOG_DBG("Posting SWITCHER(P2A)->P2B node full image of frame %d", job.mFrameNo); handlePostBuffer(SWITCHER_TO_P2B, (MUINTPTR) &job.imgReq, job.mFrameNo); } TagImgRequest tagImgReq; tagImgReq.imgReq = job.imgReq; tagImgReq.vfbExtreme = mVfbExtreme; LOG_DBG("Posting SWITCHER->VFB node full image of frame %d", job.mFrameNo); handlePostBuffer(SWITCHER_TO_VFBSW, (MUINTPTR) &tagImgReq, job.mFrameNo); } } } FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeSwitcherNode:: onReturnBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { //FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); MBOOL bGpuTo_P2b; switch (data) { case SWITCHER_TO_P2B: { Mutex::Autolock lock(mLock); bGpuTo_P2b = mqGpuToP2b.front(); mqGpuToP2b.pop(); } if (bGpuTo_P2b) { handleReturnBuffer(MDP_TO_SWITCHER, buf, ext); break; } /* Else, then it's from P2A; continue to next case... */ case SWITCHER_TO_GPU: handleReturnBuffer(P2A_TO_SWITCHER, buf, ext); break; case SWITCHER_TO_VFBSW: /* Do nothing. Wait until GPU or P2B returns full image buffer */ break; } //FUNCTION_LOG_END; return MTRUE; } MVOID FeaturePipeSwitcherNode:: onDumpBuffer(const char* usr, MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { } /****************************************************************************** * ******************************************************************************/ #undef LOG_VRB #undef LOG_DBG #undef LOG_DBG #undef LOG_WRN #undef LOG_ERR #undef LOG_AST #define LOG_VRB(fmt, arg...) CAM_LOGV("[GPU:%s] " fmt, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGD("[GPU:%s] " fmt, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGI("[GPU:%s] " fmt, __func__, ##arg) #define LOG_WRN(fmt, arg...) CAM_LOGW("[GPU:%s] " fmt, __func__, ##arg) #define LOG_ERR(fmt, arg...) CAM_LOGE("[GPU:%s] " fmt, __func__, ##arg) #define LOG_AST(cond, fmt, arg...) do{ if(!cond) CAM_LOGA("[GPU:%s] " fmt, __func__, ##arg); } while(0) FeaturePipeGpuNode* FeaturePipeGpuNode::createInstance(MUINT32 featureOnMask, FeaturePipe *pFeaturePipeObj) { return new FeaturePipeGpuNode("FeaturePipeGpuNode", SingleTrigger, SCHED_POLICY, SCHED_PRIORITY, featureOnMask, pFeaturePipeObj); } MVOID FeaturePipeGpuNode::destroyInstance() { delete this; } FeaturePipeGpuNode::FeaturePipeGpuNode( const char* name, eThreadNodeType type, int policy, int priority, MUINT32 featureOnMask, FeaturePipe *pFeaturePipeObj) : FeaturePipeNode(name, type, policy, priority, featureOnMask, 0, pFeaturePipeObj), mWarpWorkBufSize(0), mpWorkingBuffer(NULL), mpGpuWarp(NULL), mInputImageWidth(0), mInputImageHeight(0), mOutputImageWidth(0), mOutputImageHeight(0) { if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_SRC, SWITCHER_TO_GPU); addDataSupport(ENDPOINT_SRC, VFBSW_TO_GPU); addDataSupport(ENDPOINT_DST, GPU_TO_MDP); } if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_SRC, EISSW_TO_GPU); if(!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_SRC, P2A_TO_GPU); } addDataSupport(ENDPOINT_DST, GPU_TO_MDP); } } MBOOL FeaturePipeGpuNode::onInit() { FUNCTION_LOG_START; pBufHandler = getBufferHandler(P2A_TO_GPU); /* Allocate buffer for next node */ if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpgpu", EnableOption, "0"); if(EnableOption[0] == '2' || EnableOption[0] == '3') { pBufHandler = getBufferHandler(8001); if (pBufHandler == NULL) { LOG_ERR("EIS gfxo pBufHandler failed!"); goto _Exit; } LOG_DBG("EIS gfxo buffer(%dx%d)", FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT); AllocInfo allocinfo(FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, eImgFmt_YV12, eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN | eBUFFER_USAGE_SW_WRITE_RARELY); if( !pBufHandler->requestBuffer(8001, allocinfo) ) { LOG_ERR("EIS gfxo buffer fail"); return MFALSE; } } } sem_init(&mModuleSem, 0, 0); FUNCTION_LOG_END; return true; _Exit: return false; } MBOOL FeaturePipeGpuNode:: onUninit() { Mutex::Autolock autoLock(mUninitMtx); FUNCTION_LOG_START; sem_destroy(&mModuleSem); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeGpuNode:: threadInit() { FUNCTION_LOG_START; MRESULT mret; vector< sp<GraphicBuffer>* > vpGB; #ifndef _WORKAROUND_GPU_FLASH reinterpret_cast<FeaturePipeP2aNode*>(mpFeaturePipeObj->mpP2aNode)->getGraphicBuffer(vpGB); LOG_AST(vpGB.size(), "P2A does not provide any GB", 0); sp<GraphicBuffer>* srcGBArray[vpGB.size()]; #else sp<GraphicBuffer>* srcGBArray[1]; /* Allocate Graphic buffer */ mGfxYuvBuffer = new GraphicBuffer(FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, PIXEL_FORMAT_RGBA_8888, GraphicBuffer::USAGE_HW_TEXTURE | GraphicBuffer::USAGE_SW_READ_OFTEN | GraphicBuffer::USAGE_SW_WRITE_OFTEN); if (mGfxYuvBuffer == NULL) { LOG_ERR("GraphicBuffer allocation for YV12 failed!"); goto _Exit; } #endif //_WORKAROUND_GPU_FLASH /* Create MTKWarp instance */ mpGpuWarp = MTKWarp::createInstance( #ifndef _CPUWARP DRV_WARP_OBJ_GLES #else DRV_WARP_OBJ_CPU #endif ); if (mpGpuWarp == NULL) { LOG_ERR("MTKWarp create instance failed!"); goto _Exit; } { pBufHandler = getBufferHandler(GPU_TO_MDP); if (pBufHandler == NULL) { LOG_ERR("ICamBufHandler getBufferHandler(GPU_TO_MDP) failed!"); goto _Exit; } for (MUINT8 i = 0; i < GPU_NODE_BUFFER_NUM; i++) { AllocInfo allocinfo(FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, eImgFmt_RGBA8888, eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN | eBUFFER_USAGE_SW_WRITE_RARELY); mGfxRgbaBuffer[i] = new GraphicBuffer(FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, PIXEL_FORMAT_RGBA_8888, GraphicBuffer::USAGE_HW_RENDER | GraphicBuffer::USAGE_SW_READ_OFTEN | GraphicBuffer::USAGE_SW_WRITE_OFTEN); if (mGfxRgbaBuffer[i] == NULL) { LOG_ERR("GraphicBuffer allocation for RGBA8888 failed!"); goto _Exit; } if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->requestBuffer_GB(GPU_TO_MDP, allocinfo, &(mGfxRgbaBuffer[i])) ) { LOG_ERR("Request GPU_TO_MDP full image buffer failed"); goto _Exit; } } } #ifdef _CPUWARP mpCpuWarpInputBuffer = malloc(FULL_IMAGE_MAX_WIDTH * FULL_IMAGE_MAX_HEIGHT * 3 / 2); mpCpuWarpOutputBuffer = malloc(FULL_IMAGE_MAX_WIDTH * FULL_IMAGE_MAX_HEIGHT * 4); #endif /* Create GPU context and shader program */ struct WarpImageExtInfo warp_info; GpuTuning gpu_tuning; sp<GraphicBuffer>* dstGBArray[GPU_NODE_BUFFER_NUM]; gpu_tuning.GLESVersion = 2; gpu_tuning.Demo = 0; warp_info.Features = 0; if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { ADD_FEATURE(warp_info.Features, MTK_VFB_BIT); } if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { ADD_FEATURE(warp_info.Features, MTK_EIS2_BIT); } #ifndef _WORKAROUND_GPU_FLASH warp_info.ImgFmt = WARP_IMAGE_YV12; { int i = 0; { for (vector< sp<GraphicBuffer>* >::iterator it=vpGB.begin(); it!=vpGB.end(); it++) srcGBArray[i++] = *it; } } #else warp_info.ImgFmt = WARP_IMAGE_RGBA8888; srcGBArray[0] = &mGfxYuvBuffer; #endif //_WORKAROUND_GPU_FLASH warp_info.OutImgFmt = WARP_IMAGE_RGBA8888; #ifndef _CPUWARP for (MUINT8 i = 0; i < GPU_NODE_BUFFER_NUM; i++) dstGBArray[i] = &(mGfxRgbaBuffer[i]); warp_info.SrcGraphicBuffer = (void*) &srcGBArray; warp_info.DstGraphicBuffer = (void*) &dstGBArray; #ifndef _WORKAROUND_GPU_FLASH warp_info.InputGBNum = vpGB.size(); #else warp_info.InputGBNum = 1; #endif //_WORKAROUND_GPU_FLASH warp_info.OutputGBNum = GPU_NODE_BUFFER_NUM; #else warp_info.SrcGraphicBuffer = mpCpuWarpInputBuffer; warp_info.DstGraphicBuffer = mpCpuWarpOutputBuffer; #endif // warp_info.Width = FULL_IMAGE_MAX_WIDTH; // warp_info.Height = FULL_IMAGE_MAX_HEIGHT; warp_info.Width = NR3D_WORKING_BUFF_WIDTH; // For 3DNR/EIS/VFB co-exist. warp_info.Height = NR3D_WORKING_BUFF_HEIGHT; // For 3DNR/EIS/VFB co-exist warp_info.pTuningPara = &gpu_tuning; warp_info.WarpMapNum = 1; warp_info.WarpMatrixNum = 0; warp_info.MaxWarpMapSize[0] = VFB_DS_IMAGE_MAX_WIDTH; warp_info.MaxWarpMapSize[1] = VFB_DS_IMAGE_MAX_HEIGHT; //warp_info.demo = 0; LOG_DBG("WarpInit features=0x%x, src buffer=0x%p, dst buffer=0x%p, width=%d, height=%d", warp_info.Features, warp_info.SrcGraphicBuffer, warp_info.DstGraphicBuffer, warp_info.Width, warp_info.Height); mret = mpGpuWarp->WarpInit((MUINT32*) &warp_info, (MUINT32*) NULL); if (mret != S_WARP_OK) { LOG_ERR("MTKWarp init failed! (%d)", mret); goto _Exit; } /* Allocate working memory */ unsigned int warpWorkBufSize; mret = mpGpuWarp->WarpFeatureCtrl(WARP_FEATURE_GET_WORKBUF_SIZE, NULL, &warpWorkBufSize); if (mret != S_WARP_OK) { LOG_ERR("MTKWarp WARP_FEATURE_GET_WORKBUF_ADDR failed! (%d)", mret); goto _Exit; } if ((mpWorkingBuffer != NULL) && (mWarpWorkBufSize != warpWorkBufSize)) { free(mpWorkingBuffer); mpWorkingBuffer = NULL; } if (mpWorkingBuffer == NULL) { mpWorkingBuffer = (MUINT8*) malloc(warpWorkBufSize); if (mpWorkingBuffer == NULL) { LOG_ERR("Warp working buffer allocation failed!"); goto _Exit; } } mret = mpGpuWarp->WarpFeatureCtrl(WARP_FEATURE_SET_WORKBUF_ADDR, &mpWorkingBuffer, NULL); if (mret != S_WARP_OK) { LOG_ERR("MTKWarp WARP_FEATURE_SET_WORKBUF_ADDR failed! (%d)", mret); goto _Exit; } mWarpWorkBufSize = warpWorkBufSize; FUNCTION_LOG_END; return MTRUE; _Exit: if (mpGpuWarp != NULL) { mpGpuWarp->WarpReset(); mpGpuWarp->destroyInstance(mpGpuWarp); } #ifdef _CPUWARP free(mpCpuWarpInputBuffer); free(mpCpuWarpOutputBuffer); #endif for (MUINT8 i = 0; i < GPU_NODE_BUFFER_NUM; i++) { LOG_DBG("Freeing GPU Node output GraphicBuffer"); mGfxRgbaBuffer[i]->unlock(); mGfxRgbaBuffer[i] = NULL; } if (mpWorkingBuffer != NULL) { free(mpWorkingBuffer); } return MFALSE; } MBOOL FeaturePipeGpuNode:: threadUninit() { FUNCTION_LOG_START; if (mpGpuWarp != NULL) { mpGpuWarp->WarpReset(); mpGpuWarp->destroyInstance(mpGpuWarp); } #ifdef _CPUWARP free(mpCpuWarpInputBuffer); free(mpCpuWarpOutputBuffer); #endif for (MUINT8 i = 0; i < GPU_NODE_BUFFER_NUM; i++) { LOG_DBG("Freeing GPU Node output GraphicBuffer"); mGfxRgbaBuffer[i]->unlock(); mGfxRgbaBuffer[i] = NULL; } if (mpWorkingBuffer != NULL) { free(mpWorkingBuffer); } FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeGpuNode:: onStart() { FUNCTION_LOG_START; FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeGpuNode:: onStop() { FUNCTION_LOG_START; MBOOL ret = syncWithThread(); // wait for jobs done FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeGpuNode:: onNotify(MUINT32 const datamsg, MUINT32 const ext1, MUINT32 const ext2) { FUNCTION_LOG_START; LOG_DBG("datamsg(0x%x), ext1(0x%x), ext2(0x%x)", datamsg, ext1, ext2); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeGpuNode:: onPostBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { //FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); Mutex::Autolock lock(mLock); MUINT32 numReadyJobs = MIN(mqJobFullImg.size(),mqJobWarpMap.size()); FeaturePipeNodeImgReqJob_s job; job.dataType = (NSCamNode::NodeDataTypes) data; job.imgReq = *(ImgRequest*) buf; job.mFrameNo = ext; switch (data) { case P2A_TO_GPU: case SWITCHER_TO_GPU: mqJobFullImg.push(job); break; case VFBSW_TO_GPU: case EISSW_TO_GPU: mqJobWarpMap.push(job); break; default: LOG_AST(0, "Wrong data (%d)!", data); } MUINT32 newReadyJobs = MIN(mqJobFullImg.size(),mqJobWarpMap.size()); if (newReadyJobs > numReadyJobs) triggerLoop(); //FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeGpuNode:: threadLoopUpdate() { Mutex::Autolock autoLock(mUninitMtx); FUNCTION_LOG_START; MRESULT mret; struct WarpImageExtInfo warp_info; GpuTuning gpu_tuning; warp_info.pTuningPara = &gpu_tuning; CPTLog(Event_FeaturePipe_GPUThread, CPTFlagStart); FeaturePipeNodeImgReqJob_s jobWarpMap; FeaturePipeNodeImgReqJob_s jobFullImg; { Mutex::Autolock lock(mLock); /* Get warp job */ jobWarpMap = mqJobWarpMap.front(); mqJobWarpMap.pop(); /* Get full image job */ jobFullImg = mqJobFullImg.front(); mqJobFullImg.pop(); } MUINT32 frameNo = jobWarpMap.mFrameNo; LOG_AST(frameNo == jobFullImg.mFrameNo, "Frame number does not match", 0); CAM_TRACE_FMT_BEGIN("GPUThread:%d", frameNo); /* Calculate GPU input/output width and height */ mInputImageWidth = jobFullImg.imgReq.mBuffer->getImgSize().w; mInputImageHeight = jobFullImg.imgReq.mBuffer->getImgSize().h; if (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { reinterpret_cast<FeaturePipeEisNode*>(mpFeaturePipeObj->mpEisSwNode)->GetEisPlusTargetSize(mOutputImageWidth,mOutputImageHeight); LOG_DBG("FPipe_G:FNO(%u,%u),Eis(%u,%u,%u,%u)",frameNo,jobFullImg.mFrameNo,mInputImageWidth,mInputImageHeight,mOutputImageWidth,mOutputImageHeight); } else { mOutputImageWidth = mInputImageWidth; mOutputImageHeight = mInputImageHeight; } /* Copy full image into Graphic buffer */ #ifndef _CPUWARP CPTLog(Event_FeaturePipe_GPU_Memcpy, CPTFlagStart); CAM_TRACE_FMT_BEGIN("GPUMemcpy:%d", frameNo); char* gfxYuvBuf; char* gfxRgbaBuf; #ifdef _WORKAROUND_GPU_FLASH mGfxYuvBuffer->lock(GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_SW_READ_OFTEN, (void**)(&gfxYuvBuf)); //***************************src YV12********************************// DpBlitStream dpBlit; unsigned int src_addr_list[3] = {0, 0, 0}; unsigned int src_size_list[3] = {0, 0, 0}; int plane_num = 3; src_addr_list[0] = (unsigned int)jobFullImg.imgReq.mBuffer->getBufVA(0); src_addr_list[1] = (unsigned int)jobFullImg.imgReq.mBuffer->getBufVA(1); src_addr_list[2] = (unsigned int)jobFullImg.imgReq.mBuffer->getBufVA(2); src_size_list[0] = jobFullImg.imgReq.mBuffer->getBufSizeInBytes(0); src_size_list[1] = jobFullImg.imgReq.mBuffer->getBufSizeInBytes(1); src_size_list[2] = jobFullImg.imgReq.mBuffer->getBufSizeInBytes(2); dpBlit.setSrcBuffer((void **)src_addr_list, src_size_list, plane_num); dpBlit.setSrcConfig(jobFullImg.imgReq.mBuffer->getImgSize().w, jobFullImg.imgReq.mBuffer->getImgSize().h, FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_WIDTH / 2, DP_COLOR_YV12); //***************************dst RGBA8888****************************// unsigned int dst_addr_list[3] = {0, 0, 0}; unsigned int dst_size_list[3] = {0, 0, 0}; plane_num = 1; dst_addr_list[0] = (unsigned int)gfxYuvBuf; dst_size_list[0] = FULL_IMAGE_MAX_WIDTH * jobFullImg.imgReq.mBuffer->getImgSize().h * 4; dpBlit.setDstBuffer((void **)dst_addr_list, dst_size_list, plane_num); dpBlit.setDstConfig(jobFullImg.imgReq.mBuffer->getImgSize().w, jobFullImg.imgReq.mBuffer->getImgSize().h, FULL_IMAGE_MAX_WIDTH * 4, 0, DP_COLOR_RGBA8888); dpBlit.setRotate(0); // set & add pipe to stream if (dpBlit.invalidate()) //trigger HW { LOG_ERR("[convertRGBA8888toYV12] FDstream invalidate failed"); return false; } mGfxYuvBuffer->unlock(); #endif //_WORKAROUND_GPU_FLASH CAM_TRACE_FMT_END(); CPTLog(Event_FeaturePipe_GPU_Memcpy, CPTFlagEnd); #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpgpu", EnableOption, "0"); if (EnableOption[0] == '1' || EnableOption[0] == '3') #endif { char szFileName[100]; ::sprintf(szFileName, "/sdcard/gfxi_%dx%d_%04d.yuv", FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, frameNo); LOG_DBG("DUMP gfxi:%s",szFileName); saveBufToFile(szFileName, (MUINT8*) gfxYuvBuf, FULL_IMAGE_MAX_WIDTH * FULL_IMAGE_MAX_HEIGHT * 3 / 2); } #else memcpy(mpCpuWarpInputBuffer, (void*) jobFullImg.imgReq.mBuffer->getBufVA(0), mInputImageWidth * mInputImageHeight * 3 / 2); { char szFileName[100]; ::sprintf(szFileName, "/sdcard/gfxi_%dx%d_%04d.yuv", mInputImageWidth, mInputImageHeight, frameNo); saveBufToFile(szFileName, (MUINT8*) mpCpuWarpInputBuffer, mInputImageWidth * mInputImageHeight * 4); } #endif /* Set per frame process info */ warp_info.ClipWidth = mOutputImageWidth; warp_info.ClipHeight = mOutputImageHeight; warp_info.Width = mInputImageWidth; warp_info.Height = mInputImageHeight; warp_info.WarpMapSize[0][0] = const_cast<IImageBuffer*>(jobWarpMap.imgReq.mBuffer)->getImgSize().w / 4; warp_info.WarpMapSize[0][1] = const_cast<IImageBuffer*>(jobWarpMap.imgReq.mBuffer)->getImgSize().h / 2; warp_info.WarpMapAddr[0][0] = (MUINT32*) const_cast<IImageBuffer*>(jobWarpMap.imgReq.mBuffer)->getBufVA(0); warp_info.WarpMapAddr[0][1] = (MUINT32*) (const_cast<IImageBuffer*>(jobWarpMap.imgReq.mBuffer)->getBufVA(0) + const_cast<IImageBuffer*>(jobWarpMap.imgReq.mBuffer)->getBufSizeInBytes(0) / 2); #ifdef _CPUWARP warp_info.SrcGraphicBuffer = (void*) mpCpuWarpInputBuffer; warp_info.DstGraphicBuffer = (void*) mpCpuWarpOutputBuffer; #else #ifndef _WORKAROUND_GPU_FLASH if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->getGraphicBuffer((jobFullImg.dataType == SWITCHER_TO_GPU)? P2A_TO_SWITCHER: jobFullImg.dataType, const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer), (sp<GraphicBuffer>**) &(warp_info.SrcGraphicBuffer)) ) { LOG_ERR("Failed to get GB from ImageBuffer(%x)", const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer)); return MFALSE; } #else warp_info.SrcGraphicBuffer = (void*)&mGfxYuvBuffer; #endif //_WORKAROUND_GPU_FLASH ImgRequest fullImgReq; if(!pBufHandler->dequeBuffer(GPU_TO_MDP, &fullImgReq)) { LOG_AST(false, "dequeBuffer fail. Out of GPU_TO_MDP buffer", 0); return MFALSE; } if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->getGraphicBuffer(GPU_TO_MDP, const_cast<IImageBuffer*>(fullImgReq.mBuffer), (sp<GraphicBuffer>**) &(warp_info.DstGraphicBuffer)) ) { LOG_ERR("Failed to get GB from ImageBuffer(%x)", const_cast<IImageBuffer*>(fullImgReq.mBuffer)); return MFALSE; } if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->resizeBuffer(GPU_TO_MDP, &fullImgReq.mBuffer, mOutputImageWidth, mOutputImageHeight) ) { LOG_ERR("EIS Resize full image buffer failed"); return MFALSE; } #endif //_CPUWARP mret = mpGpuWarp->WarpFeatureCtrl(WARP_FEATURE_ADD_IMAGE, &warp_info, NULL); if (mret != S_WARP_OK) { LOG_ERR("MTKWarp WARP_FEATURE_ADD_IMAGE failed! (%d)", mret); } /* GPU Processing */ LOG_DBG("WarpMain: feature(0x%08x),input(%d,%d),output(%d,%d),warp map(%d,%d),addr(0x%x,0x%x)",warp_info.Features,warp_info.Width,warp_info.Height, warp_info.ClipWidth, warp_info.ClipHeight, warp_info.WarpMapSize[0][0], warp_info.WarpMapSize[0][1], warp_info.WarpMapAddr[0][0], warp_info.WarpMapAddr[0][1]); CPTLog(Event_FeaturePipe_GPU_Warp, CPTFlagStart); CAM_TRACE_FMT_BEGIN("GPUWarp:%d", frameNo); (*((sp<GraphicBuffer>*) warp_info.DstGraphicBuffer))->unlock(); mret = mpGpuWarp->WarpMain(); (*((sp<GraphicBuffer>*) warp_info.DstGraphicBuffer))->lock(GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_SW_READ_OFTEN, (void**)(&gfxRgbaBuf)); CAM_TRACE_FMT_END(); CPTLog(Event_FeaturePipe_GPU_Warp, CPTFlagEnd); if (mret != S_WARP_OK) { LOG_ERR("MTKWarp WarpMain failed! (%d)", mret); } #ifndef _DEBUG_DUMP property_get("camera.featurepipe.dumpgpu", EnableOption, "0"); if (EnableOption[0] == '1') #endif { (*((sp<GraphicBuffer>*) warp_info.DstGraphicBuffer))->lock(GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_SW_READ_OFTEN, (void**)(&gfxRgbaBuf)); char szFileName[100]; ::sprintf(szFileName, "/sdcard/gfxo_%dx%d_%04d.rgb", FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, frameNo); saveBufToFile(szFileName, (MUINT8*) gfxRgbaBuf, FULL_IMAGE_MAX_WIDTH * FULL_IMAGE_MAX_HEIGHT * 4); (*((sp<GraphicBuffer>*) warp_info.DstGraphicBuffer))->unlock(); } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { /* Return buffer to previous node */ LOG_DBG("Returning VFB node warp map buffer %d", jobWarpMap.mFrameNo); handleReturnBuffer(VFBSW_TO_GPU, (MUINTPTR) &jobWarpMap.imgReq, jobWarpMap.mFrameNo); } else if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { ImgRequest fullImgReq; char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpgpu", EnableOption, "0"); if(EnableOption[0] == '2' || EnableOption[0] == '3') { (*((sp<GraphicBuffer>*) warp_info.DstGraphicBuffer))->lock(GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_SW_READ_OFTEN, (void**)(&gfxRgbaBuf)); if(!pBufHandler->dequeBuffer(8001, &fullImgReq)) { LOG_ERR("Out of EIS gfxo buffer"); return MFALSE; } LOG_DBG("EIS Resize full image buffer to %dx%d", mOutputImageWidth, mOutputImageHeight); if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->resizeBuffer(8001, &fullImgReq.mBuffer, mOutputImageWidth, mOutputImageHeight) ) { LOG_ERR("EIS Resize full image buffer failed"); return MFALSE; } char szFileName[100]; //::sprintf(szFileName, "/sdcard/gfxo_%dx%d_%04d.rgb", FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, frameNo); //saveBufToFile(szFileName, (MUINT8*) gfxRgbaBuf, FULL_IMAGE_MAX_WIDTH * FULL_IMAGE_MAX_HEIGHT * 4); convertRGBA8888toYV12((MINTPTR)gfxRgbaBuf, mOutputImageWidth, mOutputImageHeight, const_cast<IImageBuffer*>(fullImgReq.mBuffer)); ::sprintf(szFileName, "/sdcard/gfxo_%dx%d_%04d.yuv", mOutputImageWidth, mOutputImageHeight, frameNo); LOG_DBG("DUMP+EIS gfxo:%s",szFileName); const_cast<IImageBuffer*>(fullImgReq.mBuffer)->syncCache(eCACHECTRL_INVALID); const_cast<IImageBuffer*>(fullImgReq.mBuffer)->saveToFile(szFileName); pBufHandler->enqueBuffer(8001,fullImgReq.mBuffer); (*((sp<GraphicBuffer>*) warp_info.DstGraphicBuffer))->unlock(); } /* Return buffer to previous node */ LOG_DBG("Returning EIS node warp map buffer %d", jobWarpMap.mFrameNo); handleReturnBuffer(EISSW_TO_GPU, (MUINTPTR) &jobWarpMap.imgReq, jobWarpMap.mFrameNo); } #ifndef _CPUWARP //mGfxRgbaBuffer->unlock(); #endif LOG_DBG("Returning P2A node full image buffer %d", jobFullImg.mFrameNo); handleReturnBuffer(jobFullImg.dataType, (MUINTPTR) &jobFullImg.imgReq, jobFullImg.mFrameNo); if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) || FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { /* Post buffer to next node */ LOG_DBG("Posting GPU->MDP node GB of frame %d", frameNo); handlePostBuffer(GPU_TO_MDP, (MUINTPTR) &fullImgReq, frameNo); } CPTLog(Event_FeaturePipe_GPUThread, CPTFlagEnd); CAM_TRACE_FMT_END(); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeGpuNode:: onReturnBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { //FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); LOG_DBG("Recycling GPU GB node buffer %d", ext); pBufHandler->enqueBuffer(data, ((ImgRequest*)buf)->mBuffer); //FUNCTION_LOG_END; return MTRUE; } MVOID FeaturePipeGpuNode:: onDumpBuffer(const char* usr, MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { } /****************************************************************************** * ******************************************************************************/ #undef LOG_VRB #undef LOG_DBG #undef LOG_DBG #undef LOG_WRN #undef LOG_ERR #undef LOG_AST #define LOG_VRB(fmt, arg...) CAM_LOGV("[MDP:%s] " fmt, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGD("[MDP:%s] " fmt, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGI("[MDP:%s] " fmt, __func__, ##arg) #define LOG_WRN(fmt, arg...) CAM_LOGW("[MDP:%s] " fmt, __func__, ##arg) #define LOG_ERR(fmt, arg...) CAM_LOGE("[MDP:%s] " fmt, __func__, ##arg) #define LOG_AST(cond, fmt, arg...) do{ if(!cond) CAM_LOGA("[MDP:%s] " fmt, __func__, ##arg); } while(0) FeaturePipeMdpNode* FeaturePipeMdpNode::createInstance(MUINT32 featureOnMask, FeaturePipe *pFeaturePipeObj) { return new FeaturePipeMdpNode("FeaturePipeMdpNode", SingleTrigger, SCHED_POLICY, SCHED_PRIORITY, featureOnMask, pFeaturePipeObj); } MVOID FeaturePipeMdpNode::destroyInstance() { delete this; } FeaturePipeMdpNode::FeaturePipeMdpNode( const char* name, eThreadNodeType type, int policy, int priority, MUINT32 featureOnMask, FeaturePipe *pFeaturePipeObj) : FeaturePipeNode(name, type, policy, priority, featureOnMask, 0, pFeaturePipeObj), mImageWidth(0), mImageHeight(0) { if ((FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) || (FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask))) { addDataSupport(ENDPOINT_SRC, GPU_TO_MDP); } if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_DST, MDP_TO_SWITCHER); } if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { addDataSupport(ENDPOINT_SRC, P2A_TO_MDP_QPARAMS); } } MBOOL FeaturePipeMdpNode::onInit() { FUNCTION_LOG_START; /* Allocate buffer for next node */ if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { pBufHandler = getBufferHandler(MDP_TO_SWITCHER); if (pBufHandler == NULL) { LOG_ERR("ICamBufHandler failed!"); goto _Exit; } LOG_DBG("Allocate full image buffer %dx%d", FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT); AllocInfo allocinfo(FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, eImgFmt_YV12, eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN | eBUFFER_USAGE_SW_WRITE_RARELY); for (MUINT8 i = 0; i < MDP_NODE_BUFFER_NUM; i++) { if( !pBufHandler->requestBuffer(MDP_TO_SWITCHER, allocinfo) ) return MFALSE; } } if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { mpStream = new DpIspStream(DpIspStream::ISP_ZSD_STREAM); if(mpStream == NULL) { LOG_ERR("New DpIspStream failed"); goto _Exit; } char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpmdp", EnableOption, "0"); if(EnableOption[0] == '1' || EnableOption[0] == '3') { pBufHandler = getBufferHandler(8001); if (pBufHandler == NULL) { LOG_ERR("EIS mdpi pBufHandler failed!"); goto _Exit; } LOG_DBG("EIS mdpi buffer(%dx%d)", FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT); AllocInfo allocinfo(FULL_IMAGE_MAX_WIDTH, FULL_IMAGE_MAX_HEIGHT, eImgFmt_YV12, eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN | eBUFFER_USAGE_SW_WRITE_RARELY); if( !pBufHandler->requestBuffer(8001, allocinfo) ) { LOG_ERR("EIS mdpi buffer fail"); return MFALSE; } } } sem_init(&mModuleSem, 0, 0); FUNCTION_LOG_END; return true; _Exit: return false; } MBOOL FeaturePipeMdpNode:: onUninit() { Mutex::Autolock autoLock(mUninitMtx); FUNCTION_LOG_START; if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { delete mpStream; } sem_destroy(&mModuleSem); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeMdpNode:: onStart() { FUNCTION_LOG_START; FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeMdpNode:: onStop() { FUNCTION_LOG_START; MBOOL ret = syncWithThread(); // wait for jobs done FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeMdpNode:: onNotify(MUINT32 const datamsg, MUINT32 const ext1, MUINT32 const ext2) { FUNCTION_LOG_START; LOG_DBG("datamsg(0x%x), ext1(0x%x), ext2(0x%x)", datamsg, ext1, ext2); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeMdpNode:: dequeWrapper(QParams& rParams, MINT64 i8TimeoutNs) { FUNCTION_LOG_START; MBOOL ret = MTRUE; sem_wait(&mModuleSem); rParams = mqPostProcQParams.front(); mqPostProcQParams.pop(); FUNCTION_LOG_END; return ret; } MBOOL FeaturePipeMdpNode:: onPostBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { //FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); Mutex::Autolock lock(mLock); MUINT32 numReadyJobs = MIN(mqFullImgJob.size(),mqQParamsJob.size()); FeaturePipeNodeImgReqJob_s job; job.imgReq = *(ImgRequest*) buf; job.mFrameNo = ext; switch (data) { case P2A_TO_MDP_QPARAMS: mqQParamsJob.push(*(reinterpret_cast<QParams*>(buf))); break; case GPU_TO_MDP: mqFullImgJob.push(job); break; default: LOG_AST(0, "Wrong data (%d)!", data); } if (!FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask) && FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { //Must wait for QParams when EIS-only MUINT32 newReadyJobs = MIN(mqFullImgJob.size(),mqQParamsJob.size()); if (newReadyJobs > numReadyJobs) triggerLoop(); } else{ triggerLoop(); } //FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeMdpNode:: threadLoopUpdate() { Mutex::Autolock autoLock(mUninitMtx); FUNCTION_LOG_START; MRESULT mret; /* Get job */ FeaturePipeNodeImgReqJob_s jobFullImg; { Mutex::Autolock lock(mLock); jobFullImg = mqFullImgJob.front(); mqFullImgJob.pop(); } MUINT32 frameNo = jobFullImg.mFrameNo; CAM_TRACE_FMT_BEGIN("MDPThread:%d", frameNo); ImgRequest fullImgReq; if (FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { IImageBuffer *pImageBuffer = const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer); /* Prepare buffer for next node */ if(!pBufHandler->dequeBuffer(MDP_TO_SWITCHER, &fullImgReq)) { LOG_AST(false, "Out of MDP_TO_SWITCHER buffer", 0); return MFALSE; } if ((fullImgReq.mBuffer->getImgSize().w != pImageBuffer->getImgSize().w) || (fullImgReq.mBuffer->getImgSize().h != pImageBuffer->getImgSize().h)) { LOG_DBG("Resize full image buffer to %dx%d", pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h); if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->resizeBuffer(MDP_TO_SWITCHER, &fullImgReq.mBuffer, pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h) ) { LOG_ERR("Resize full image buffer failed"); return MFALSE; } } /* MDP format convertion from RGBA8888 to YV12 */ convertRGBA8888(pImageBuffer, const_cast<IImageBuffer*>(fullImgReq.mBuffer)); #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpgpu", EnableOption, "0"); if (EnableOption[0] == '1') #endif { char szFileName[100]; ::sprintf(szFileName, "/sdcard/mdpo_%dx%d_%04d.yuv", pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h, frameNo); const_cast<IImageBuffer*>(fullImgReq.mBuffer)->saveToFile(szFileName); } } else if(FEATURE_MASK_IS_EIS_ENABLED(mFeatureOnMask)) { QParams OutQParams; { Mutex::Autolock lock(mLock); /*Get output QParams*/ OutQParams = mqQParamsJob.front(); mqQParamsJob.pop(); } IImageBuffer *pImageBuffer = const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer); char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpmdp", EnableOption, "0"); if(EnableOption[0] == '1' || EnableOption[0] == '3') { ImgRequest fullImgReq; if(!pBufHandler->dequeBuffer(8001, &fullImgReq)) { LOG_ERR("Out of EIS mdpi buffer"); return MFALSE; } LOG_DBG("EIS Resize full image buffer to %dx%d",pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h); if( !reinterpret_cast<FeaturePipeBufHandler*>(pBufHandler)->resizeBuffer(8001, &fullImgReq.mBuffer,pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h)) { LOG_ERR("EIS Resize full image buffer failed"); return MFALSE; } char szFileName[100]; convertRGBA8888toYV12(pImageBuffer->getBufVA(0), pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h, const_cast<IImageBuffer*>(fullImgReq.mBuffer)); ::sprintf(szFileName, "/sdcard/mdpi_%dx%d_%04d.yuv", pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h, frameNo); LOG_DBG("DUMP+EIS mdpi:%s",szFileName); const_cast<IImageBuffer*>(fullImgReq.mBuffer)->syncCache(eCACHECTRL_INVALID); const_cast<IImageBuffer*>(fullImgReq.mBuffer)->saveToFile(szFileName); pBufHandler->enqueBuffer(8001,fullImgReq.mBuffer); } /* Copy result to PostProc output buffer */ if(mpStream->setSrcConfig(DP_COLOR_RGBA8888, pImageBuffer->getImgSize().w, pImageBuffer->getImgSize().h, FULL_IMAGE_MAX_WIDTH * 4, false) < 0) { LOG_ERR("DpIspStream->setSrcConfig failed"); return MFALSE; } MUINT32 va[3] = {(MUINT32) pImageBuffer->getBufVA(0),0,0}; MUINT32 mva[3] = {(MUINT32) pImageBuffer->getBufPA(0),0,0}; MUINT32 size[3] = {FULL_IMAGE_MAX_WIDTH * pImageBuffer->getImgSize().h * 4,0,0}; if (mpStream->queueSrcBuffer((void**)va, mva, size, 1) < 0) { LOG_ERR("DpIspStream->queueSrcBuffer failed"); return MFALSE; } if(mpStream->setSrcCrop(0,0,0,0,pImageBuffer->getImgSize().w,pImageBuffer->getImgSize().h) < 0) { LOG_ERR("DpIspStream->setSrcCrop failed"); return MFALSE; } for(int i=0; i < OutQParams.mvOut.size(); i++) { DpColorFormat dp_fmt; switch( NSCam::EImageFormat fmt = (NSCam::EImageFormat) OutQParams.mvOut[i].mBuffer->getImgFormat() ) { #define FMT_SUPPORT( fmt, dpfmt ) \ case fmt: \ dp_fmt = dpfmt; \ break; FMT_SUPPORT(eImgFmt_YUY2 , DP_COLOR_YUYV) FMT_SUPPORT(eImgFmt_UYVY , DP_COLOR_UYVY) FMT_SUPPORT(eImgFmt_YVYU , DP_COLOR_YVYU) FMT_SUPPORT(eImgFmt_VYUY , DP_COLOR_VYUY) FMT_SUPPORT(eImgFmt_NV16 , DP_COLOR_NV16) FMT_SUPPORT(eImgFmt_NV61 , DP_COLOR_NV61) FMT_SUPPORT(eImgFmt_NV21 , DP_COLOR_NV21) FMT_SUPPORT(eImgFmt_NV12 , DP_COLOR_NV12) FMT_SUPPORT(eImgFmt_YV16 , DP_COLOR_YV16) FMT_SUPPORT(eImgFmt_I422 , DP_COLOR_I422) FMT_SUPPORT(eImgFmt_YV12 , DP_COLOR_YV12) FMT_SUPPORT(eImgFmt_I420 , DP_COLOR_I420) FMT_SUPPORT(eImgFmt_Y800 , DP_COLOR_GREY) FMT_SUPPORT(eImgFmt_RGB565 , DP_COLOR_RGB565) FMT_SUPPORT(eImgFmt_RGB888 , DP_COLOR_RGB888) FMT_SUPPORT(eImgFmt_ARGB888, DP_COLOR_ARGB8888) // not supported default: LOG_ERR(" fmt(0x%x) not support in DP", fmt); return MFALSE; break; #undef FMT_SUPPORT } //LOG_DBG("mvOut:idx(%d),SZ(%u,%u),stride(%u,%u)",i,OutQParams.mvOut[i].mBuffer->getImgSize().w, // OutQParams.mvOut[i].mBuffer->getImgSize().h, // OutQParams.mvOut[i].mBuffer->getBufStridesInBytes(0), // OutQParams.mvOut[i].mBuffer->getBufStridesInBytes(1)); if(mpStream->setDstConfig(i, //port OutQParams.mvOut[i].mBuffer->getImgSize().w, OutQParams.mvOut[i].mBuffer->getImgSize().h, OutQParams.mvOut[i].mBuffer->getBufStridesInBytes(0), OutQParams.mvOut[i].mBuffer->getBufStridesInBytes(1), dp_fmt, DP_PROFILE_FULL_BT601, eInterlace_None, //default NULL, //default false) < 0) { LOG_ERR("DpIspStream->setDstConfig failed"); return MFALSE; } MUINT32 va[3] = {0,0,0}; MUINT32 size[3] = {0,0,0}; MUINT32 pa[3] = {0,0,0}; for(int j=0; j < OutQParams.mvOut[i].mBuffer->getPlaneCount(); j++) { va[j] = OutQParams.mvOut[i].mBuffer->getBufVA(j); pa[j] = OutQParams.mvOut[i].mBuffer->getBufPA(j); size[j] = OutQParams.mvOut[i].mBuffer->getBufSizeInBytes(j); } if(mpStream->queueDstBuffer(i, //port (void**)va, pa, size, OutQParams.mvOut[i].mBuffer->getPlaneCount()) < 0) { LOG_ERR("queueDstBuffer failed"); return MFALSE; } } if(mpStream->startStream() < 0) { LOG_ERR("startStream failed"); return MFALSE; } if(mpStream->dequeueSrcBuffer() < 0) { LOG_ERR("dequeueSrcBuffer failed"); return MFALSE; } for(int i=0; i < OutQParams.mvOut.size(); i++) { MUINT32 va[3] = {0,0,0}; if(mpStream->dequeueDstBuffer(i,(void**)va) < 0) { LOG_ERR("dequeueDstBuffer failed"); return MFALSE; } } if(mpStream->stopStream() < 0) { LOG_ERR("stopStream failed"); return MFALSE; } if(mpStream->dequeueFrameEnd() < 0) { LOG_ERR("dequeueFrameEnd failed"); return MFALSE; } // FLUSH //for(int i=0; i < OutQParams.mvOut.size(); i++) //{ // OutQParams.mvOut[i].mBuffer->syncCache(eCACHECTRL_INVALID); //} // dump { char debugFlag[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpmdp", debugFlag, "0"); if(debugFlag[0] == '2' || debugFlag[0] == '3') { for(int i=0; i < OutQParams.mvOut.size(); i++) { char szFileName[100]; ::sprintf(szFileName, "/sdcard/mdpo_%dx%d_%04d.yuv",OutQParams.mvOut[i].mBuffer->getImgSize().w,OutQParams.mvOut[i].mBuffer->getImgSize().h,frameNo); LOG_DBG("MDP+EIS mdpo:%s",szFileName); OutQParams.mvOut[i].mBuffer->saveToFile(szFileName); } } } OutQParams.mDequeSuccess = MTRUE; if(OutQParams.mpfnCallback != NULL) { LOG_DBG("Callback of frame %d", getMagicNo(OutQParams)); mpFeaturePipeObj->performCallback(OutQParams); } else { Mutex::Autolock lock(mLock); mqPostProcQParams.push(OutQParams); sem_post(&mModuleSem); } } LOG_DBG("Returning GPU node GB %d", jobFullImg.mFrameNo); handleReturnBuffer(GPU_TO_MDP, (MUINTPTR) &jobFullImg.imgReq, jobFullImg.mFrameNo); if(FEATURE_MASK_IS_VFB_ENABLED(mFeatureOnMask)) { /* Post buffer to next node */ LOG_DBG("Posting MDP->SWITCHER node full image of frame %d", frameNo); handlePostBuffer(MDP_TO_SWITCHER, (MUINTPTR) &fullImgReq, frameNo); } CAM_TRACE_FMT_END(); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeMdpNode:: onReturnBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { //FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); LOG_DBG("Recycling MDP full image node buffer %d", ext); pBufHandler->enqueBuffer(data, ((ImgRequest*)buf)->mBuffer); //FUNCTION_LOG_END; return MTRUE; } MVOID FeaturePipeMdpNode:: onDumpBuffer(const char* usr, MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { } MINT32 FeaturePipeMdpNode:: convertRGBA8888(IImageBuffer* srcIImageBuffer, IImageBuffer* dstIImageBuffer) { bool ret = true; FUNCTION_LOG_START; //***************************src RGBA8888****************************// unsigned int src_addr_list[3] = {0, 0, 0}; unsigned int src_mva_addr_list[3] = {0, 0, 0}; unsigned int src_size_list[3] = {0, 0, 0}; int plane_num = 1; src_addr_list[0] = (unsigned int)srcIImageBuffer->getBufVA(0); src_mva_addr_list[0] = (unsigned int)srcIImageBuffer->getBufPA(0); src_size_list[0] = FULL_IMAGE_MAX_WIDTH * srcIImageBuffer->getImgSize().h * 4; mDpBlit.setSrcBuffer((void **)src_addr_list, (void **)src_mva_addr_list, src_size_list, plane_num); mDpBlit.setSrcConfig(srcIImageBuffer->getImgSize().w, srcIImageBuffer->getImgSize().h, FULL_IMAGE_MAX_WIDTH * 4, 0, DP_COLOR_RGBA8888, DP_PROFILE_FULL_BT601, eInterlace_None, 0, DP_SECURE_NONE, false); //***************************dst YV12********************************// unsigned int dst_addr_list[3] = {0, 0, 0}; unsigned int dst_mva_addr_list[3] = {0, 0, 0}; unsigned int dst_size_list[3] = {0, 0, 0}; plane_num = 3; dst_addr_list[0] = (unsigned int)dstIImageBuffer->getBufVA(0); dst_addr_list[1] = (unsigned int)dstIImageBuffer->getBufVA(1); dst_addr_list[2] = (unsigned int)dstIImageBuffer->getBufVA(2); dst_mva_addr_list[0] = (unsigned int)dstIImageBuffer->getBufPA(0); dst_mva_addr_list[1] = (unsigned int)dstIImageBuffer->getBufPA(1); dst_mva_addr_list[2] = (unsigned int)dstIImageBuffer->getBufPA(2); dst_size_list[0] = dstIImageBuffer->getBufSizeInBytes(0); dst_size_list[1] = dstIImageBuffer->getBufSizeInBytes(1); dst_size_list[2] = dstIImageBuffer->getBufSizeInBytes(2); mDpBlit.setDstBuffer((void**)dst_addr_list, (void**)dst_mva_addr_list, dst_size_list, plane_num); mDpBlit.setDstConfig(dstIImageBuffer->getImgSize().w, dstIImageBuffer->getImgSize().h, dstIImageBuffer->getBufStridesInBytes(0), dstIImageBuffer->getBufStridesInBytes(1), DP_COLOR_YV12, DP_PROFILE_FULL_BT601, eInterlace_None, 0, DP_SECURE_NONE, false); mDpBlit.setRotate(0); // set & add pipe to stream if (mDpBlit.invalidate()) //trigger HW { LOG_ERR("[convertRGBA8888toYV12] FDstream invalidate failed"); return false; } FUNCTION_LOG_END; return ret; } /****************************************************************************** * ******************************************************************************/ #undef LOG_VRB #undef LOG_DBG #undef LOG_DBG #undef LOG_WRN #undef LOG_ERR #undef LOG_AST #define LOG_VRB(fmt, arg...) CAM_LOGV("[%d:P2B:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGD("[%d:P2B:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_DBG(fmt, arg...) CAM_LOGI("[%d:P2B:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_WRN(fmt, arg...) CAM_LOGW("[%d:P2B:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_ERR(fmt, arg...) CAM_LOGE("[%d:P2B:%s] " fmt, mOpenedSensorIndex, __func__, ##arg) #define LOG_AST(cond, fmt, arg...) do{ if(!cond) CAM_LOGA("[%d:P2B:%s] " fmt, mOpenedSensorIndex, __func__, ##arg); } while(0) FeaturePipeP2bNode* FeaturePipeP2bNode::createInstance(MUINT32 featureOnMask, MUINT32 mOpenedSensorIndex, FeaturePipe *pFeaturePipeObj) { LOG_AST(FEATURE_MASK_IS_VFB_ENABLED(featureOnMask), "Create P2B node while vFB is off", 0); return new FeaturePipeP2bNode("FeaturePipeP2bNode", SingleTrigger, SCHED_POLICY, SCHED_PRIORITY, featureOnMask, mOpenedSensorIndex, pFeaturePipeObj); } MVOID FeaturePipeP2bNode::destroyInstance() { delete this; } FeaturePipeP2bNode::FeaturePipeP2bNode( const char* name, eThreadNodeType type, int policy, int priority, MUINT32 featureOnMask, MUINT32 mOpenedSensorIndex, FeaturePipe *pFeaturePipeObj ) : FeaturePipeNode(name, type, policy, priority, featureOnMask, mOpenedSensorIndex, pFeaturePipeObj) { addDataSupport(ENDPOINT_SRC, P2A_TO_P2B); addDataSupport(ENDPOINT_SRC, VFBSW_TO_P2B_DSIMG); addDataSupport(ENDPOINT_SRC, VFBSW_TO_P2B_ALPCL); addDataSupport(ENDPOINT_SRC, VFBSW_TO_P2B_ALPNR); addDataSupport(ENDPOINT_SRC, VFBSW_TO_P2B_PCA); addDataSupport(ENDPOINT_SRC, SWITCHER_TO_P2B); } MBOOL FeaturePipeP2bNode::onInit() { FUNCTION_LOG_START; MRESULT mret; /* Create IFeatureStream */ mpIFeatureStream = NSCam::NSIoPipe::NSPostProc::IFeatureStream::createInstance("FeaturePipe_VfbP2B", EFeatureStreamTag_vFB_FB, mOpenedSensorIndex); if (mpIFeatureStream == NULL) { LOG_ERR("IFeatureStream create instance failed!"); goto _Exit; } mpIFeatureStream->init(); mp3AHal = NS3A::IHal3A::createInstance(NS3A::IHal3A::E_Camera_1, mOpenedSensorIndex, "FeaturePipe_VfbP2B"); if (!mp3AHal) { LOG_ERR("IHal3A::createInstance failed!"); goto _Exit; } sem_init(&mModuleSem, 0, 0); FUNCTION_LOG_END; return true; _Exit: if (mpIFeatureStream != NULL) { mpIFeatureStream->destroyInstance("FeaturePipe_VfbP2B"); } if (mp3AHal != NULL) { mp3AHal->destroyInstance("FeaturePipe_VfbP2B"); } return false; } MBOOL FeaturePipeP2bNode:: onUninit() { Mutex::Autolock autoLock(mUninitMtx); FUNCTION_LOG_START; mpIFeatureStream->uninit(); mpIFeatureStream->destroyInstance("FeaturePipe_VfbP2B"); mp3AHal->destroyInstance("FeaturePipe_VfbP2B"); sem_destroy(&mModuleSem); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2bNode:: onStart() { FUNCTION_LOG_START; FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2bNode:: onStop() { FUNCTION_LOG_START; MBOOL ret = syncWithThread(); // wait for jobs done FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2bNode:: onNotify(MUINT32 const datamsg, MUINT32 const ext1, MUINT32 const ext2) { FUNCTION_LOG_START; LOG_DBG("datamsg(0x%x), ext1(0x%x), ext2(0x%x)", datamsg, ext1, ext2); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2bNode:: dequeWrapper(QParams& rParams, MINT64 i8TimeoutNs) { FUNCTION_LOG_START; MBOOL ret = MTRUE; sem_wait(&mModuleSem); Mutex::Autolock lock(mLock); rParams = qCallerQParams.front(); qCallerQParams.pop(); FUNCTION_LOG_END; return ret; } MVOID FeaturePipeP2bNode:: p2bCbFunc(QParams& rParams) { CPTLog(Event_FeaturePipe_P2B_FeatureStream, CPTFlagEnd); CAM_TRACE_FMT_BEGIN("P2BCb:%d", getMagicNo(rParams)); FeaturePipeP2bNode* pP2BNodeObj = (FeaturePipeP2bNode*)(rParams.mpCookie); pP2BNodeObj->handleP2Done(rParams); Mutex::Autolock lock(pP2BNodeObj->mLock); MBOOL dequeSuccess = rParams.mDequeSuccess; rParams = pP2BNodeObj->mqCallbackQParams.front(); pP2BNodeObj->mqCallbackQParams.pop(); rParams.mDequeSuccess = dequeSuccess; #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpp2b", EnableOption, "0"); if (EnableOption[0] == '1') #endif { for (int i=0; i < rParams.mvOut.size(); i++) { char szFileName[100]; ::sprintf(szFileName, "/sdcard/p2bo_%dx%d_%04d.yuv", rParams.mvOut[i].mBuffer->getImgSize().w, rParams.mvOut[i].mBuffer->getImgSize().h, getMagicNo(rParams)); rParams.mvOut[i].mBuffer->saveToFile(szFileName); } } pP2BNodeObj->mpFeaturePipeObj->performCallback(rParams); CAM_TRACE_FMT_END(); } MBOOL FeaturePipeP2bNode:: handleP2Done(QParams& rParams) { LOG_DBG("Callback of frame %d", getMagicNo(rParams)); for(MUINT32 i = 0; i < rParams.mvIn.size(); i++) { ImgRequest imgReq(rParams.mvIn[i].mBuffer); NSCamNode::NodeDataTypes dType; switch (rParams.mvIn[i].mPortID.index) { case NSImageio::NSIspio::EPortIndex_VIPI: dType = SWITCHER_TO_P2B; break; case NSImageio::NSIspio::EPortIndex_IMGI: dType = VFBSW_TO_P2B_DSIMG; break; case NSImageio::NSIspio::EPortIndex_UFDI: dType = VFBSW_TO_P2B_ALPNR; break; case NSImageio::NSIspio::EPortIndex_LCEI: dType = VFBSW_TO_P2B_ALPCL; break; default: LOG_AST(0, "Wrong port (%d)!", rParams.mvIn[i].mPortID.index); } handleReturnBuffer(dType, (MUINTPTR) &imgReq, getMagicNo(rParams)); } return MTRUE; } MBOOL FeaturePipeP2bNode:: onPostBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { #define MIN(a,b) (((a) < (b))? (a): (b)) //FUNCTION_LOG_START; LOG_DBG("data(%d), buf(0x%x), ext(0x%x)", data, buf, ext); Mutex::Autolock lock(mLock); MUINT32 numReadyJobs = MIN(MIN(mqFullImgJob.size(),mqDsImgJob.size()),mqQParamsJob.size()); FeaturePipeNodeImgReqJob_s job; job.dataType = (NSCamNode::NodeDataTypes) data; job.imgReq = *(ImgRequest*) buf; job.mFrameNo = ext; switch (data) { case P2A_TO_P2B: mqQParamsJob.push(*(reinterpret_cast<QParams*>(buf))); break; case VFBSW_TO_P2B_DSIMG: mqDsImgJob.push(job); break; case VFBSW_TO_P2B_ALPCL: mqAlphaCLJob.push(job); break; case VFBSW_TO_P2B_ALPNR: mqAlphaNRJob.push(job); break; case VFBSW_TO_P2B_PCA: mqPCAJob.push(job); break; case SWITCHER_TO_P2B: mqFullImgJob.push(job); break; default: LOG_AST(0, "Wrong data (%d)!", data); } MUINT32 newReadyJobs = MIN(MIN(mqFullImgJob.size(),mqDsImgJob.size()),mqQParamsJob.size()); if (newReadyJobs > numReadyJobs) triggerLoop(); //FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2bNode:: threadLoopUpdate() { Mutex::Autolock autoLock(mUninitMtx); static const NSCam::NSIoPipe::PortID VIPI( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_VIPI, 0); static const NSCam::NSIoPipe::PortID IMGI( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_IMGI, 0); static const NSCam::NSIoPipe::PortID UFDI( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_UFDI, 0); static const NSCam::NSIoPipe::PortID LCEI( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_LCEI, 0); FUNCTION_LOG_START; MRESULT mret; CPTLog(Event_FeaturePipe_P2BThread, CPTFlagStart); QParams OutQParams; FeaturePipeNodeImgReqJob_s jobFullImg; FeaturePipeNodeImgReqJob_s jobDsImg; FeaturePipeNodeImgReqJob_s jobAlphaCL; FeaturePipeNodeImgReqJob_s jobAlphaNR; FeaturePipeNodeImgReqJob_s jobPCA; { /* All jobs have to be de-queued in one place!! */ Mutex::Autolock lock(mLock); if(!(mqQParamsJob.size() && mqFullImgJob.size() && mqDsImgJob.size() && mqAlphaNRJob.size() && mqAlphaCLJob.size() && mqPCAJob.size())){ LOG_ERR("One or more of job queues are empty\n"); return false; } /* Get output QParams */ OutQParams = mqQParamsJob.front(); mqQParamsJob.pop(); /* Get full image */ jobFullImg = mqFullImgJob.front(); mqFullImgJob.pop(); jobDsImg = mqDsImgJob.front(); mqDsImgJob.pop(); jobAlphaCL = mqAlphaCLJob.front(); mqAlphaCLJob.pop(); jobAlphaNR = mqAlphaNRJob.front(); mqAlphaNRJob.pop(); jobPCA = mqPCAJob.front(); mqPCAJob.pop(); } LOG_AST(jobFullImg.mFrameNo == getMagicNo(OutQParams), "Frame number does not match", 0); LOG_AST(jobDsImg.mFrameNo == getMagicNo(OutQParams), "Frame number does not match", 0); LOG_AST(jobAlphaCL.mFrameNo == getMagicNo(OutQParams), "Frame number does not match", 0); LOG_AST(jobAlphaNR.mFrameNo == getMagicNo(OutQParams), "Frame number does not match", 0); LOG_AST(jobPCA.mFrameNo == getMagicNo(OutQParams), "Frame number does not match", 0); CAM_TRACE_FMT_BEGIN("P2BThread:%d", getMagicNo(OutQParams)); QParams mQParams; mQParams.mvIn.clear(); mQParams.mvIn.reserve(4); mQParams.mvOut.clear(); mQParams.mvOut.reserve(OutQParams.mvOut.size()); mQParams.mFrameNo = getMagicNo(OutQParams); if (OutQParams.mvMagicNo.size()) mQParams.mvMagicNo.push_back(OutQParams.mvMagicNo[0]); mQParams.mpPrivaData = OutQParams.mpPrivaData; if (OutQParams.mvPrivaData.size()) mQParams.mvPrivaData.push_back(OutQParams.mvPrivaData[0]); /* PASS2 Processing */ NSCam::NSIoPipe::NSPostProc::Input minput; /* VIPI */ minput.mPortID = VIPI; minput.mBuffer = const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer); minput.mCropRect.p_integral.x = 0; minput.mCropRect.p_integral.y = 0; minput.mCropRect.p_fractional.x = 0; minput.mCropRect.p_fractional.y = 0; minput.mCropRect.s.w = const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer)->getImgSize().w; minput.mCropRect.s.h = const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer)->getImgSize().h; mQParams.mvIn.push_back(minput); { #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpp2b", EnableOption, "0"); if (EnableOption[0] == '1') #endif { char szFileName[100]; ::sprintf(szFileName, "/sdcard/p2bi_%dx%d_%04d.yuv", const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer)->getImgSize().w, const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer)->getImgSize().h, getMagicNo(OutQParams)); const_cast<IImageBuffer*>(jobFullImg.imgReq.mBuffer)->saveToFile(szFileName); } } /* IMGI */ LOG_DBG("Received VFB->P2B ds req(%x) mbuffer(%x)", &jobDsImg.imgReq, jobDsImg.imgReq.mBuffer); minput.mPortID = IMGI; minput.mBuffer = const_cast<IImageBuffer*>(jobDsImg.imgReq.mBuffer); minput.mCropRect.p_integral.x = 0; minput.mCropRect.p_integral.y = 0; minput.mCropRect.p_fractional.x = 0; minput.mCropRect.p_fractional.y = 0; minput.mCropRect.s.w = const_cast<IImageBuffer*>(jobDsImg.imgReq.mBuffer)->getImgSize().w; minput.mCropRect.s.h = const_cast<IImageBuffer*>(jobDsImg.imgReq.mBuffer)->getImgSize().h; mQParams.mvIn.push_back(minput); { #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpp2b", EnableOption, "0"); if (EnableOption[0] == '1') #endif { char szFileName[100]; ::sprintf(szFileName, "/sdcard/p2bi_%dx%d_%04d.yuv", const_cast<IImageBuffer*>(jobDsImg.imgReq.mBuffer)->getImgSize().w, const_cast<IImageBuffer*>(jobDsImg.imgReq.mBuffer)->getImgSize().h, getMagicNo(OutQParams)); const_cast<IImageBuffer*>(jobDsImg.imgReq.mBuffer)->saveToFile(szFileName); } } /* LCEI */ minput.mPortID = LCEI; minput.mBuffer = const_cast<IImageBuffer*>(jobAlphaCL.imgReq.mBuffer); minput.mCropRect.p_integral.x = 0; minput.mCropRect.p_integral.y = 0; minput.mCropRect.p_fractional.x = 0; minput.mCropRect.p_fractional.y = 0; minput.mCropRect.s.w = const_cast<IImageBuffer*>(jobAlphaCL.imgReq.mBuffer)->getImgSize().w; minput.mCropRect.s.h = const_cast<IImageBuffer*>(jobAlphaCL.imgReq.mBuffer)->getImgSize().h; mQParams.mvIn.push_back(minput); /* UFDI */ //reinterpret_cast<FeaturePipeVfbNode*>(mpFeaturePipeObj->mpVfbSwNode)->setLCE(const_cast<IImageBuffer*>(jobAlphaNR.imgReq.mBuffer)); minput.mPortID = UFDI; minput.mBuffer = const_cast<IImageBuffer*>(jobAlphaNR.imgReq.mBuffer); minput.mCropRect.p_integral.x = 0; minput.mCropRect.p_integral.y = 0; minput.mCropRect.p_fractional.x = 0; minput.mCropRect.p_fractional.y = 0; minput.mCropRect.s.w = const_cast<IImageBuffer*>(jobAlphaNR.imgReq.mBuffer)->getImgSize().w; minput.mCropRect.s.h = const_cast<IImageBuffer*>(jobAlphaNR.imgReq.mBuffer)->getImgSize().h; mQParams.mvIn.push_back(minput); /* PCA */ #ifdef MTK_CAM_VIDEO_FACEBEAUTY_SUPPORT reinterpret_cast<FeaturePipeVfbNode*>(mpFeaturePipeObj->mpVfbSwNode)->setPCA(const_cast<IImageBuffer*>(jobPCA.imgReq.mBuffer)); #endif for (int i=0; i < mQParams.mvIn.size(); i++) { LOG_DBG("[P2B sets mvIn (%d)] imgfmt(%d),w(%d),h(%d),type(%d),index(%d),inout(%d),mem( va(0x%x)/pa(0x%x)/size(0x%x) ),p2pxlid(%d),magicnum(%d)",i, mQParams.mvIn[i].mBuffer->getImgFormat(),mQParams.mvIn[i].mBuffer->getImgSize().w,mQParams.mvIn[i].mBuffer->getImgSize().h, mQParams.mvIn[i].mPortID.type,mQParams.mvIn[i].mPortID.index,mQParams.mvIn[i].mPortID.inout, mQParams.mvIn[i].mBuffer->getBufVA(0),mQParams.mvIn[i].mBuffer->getBufPA(0), mQParams.mvIn[i].mBuffer->getBufSizeInBytes(0),mQParams.mvIn[i].mExtraParams.p2pxlID,getMagicNo(mQParams)); } /* Output */ for (int i=0; i < OutQParams.mvOut.size(); i++) { LOG_DBG("[P2B gets mvOut (%d)] imgfmt(%d),w(%d),h(%d),type(%d),index(%d),inout(%d),mem( va(0x%x)/pa(0x%x)/size(0x%x) ),p2pxlid(%d),magicnum(%d)",i, OutQParams.mvOut[i].mBuffer->getImgFormat(),OutQParams.mvOut[i].mBuffer->getImgSize().w,OutQParams.mvOut[i].mBuffer->getImgSize().h, OutQParams.mvOut[i].mPortID.type,OutQParams.mvOut[i].mPortID.index,OutQParams.mvOut[i].mPortID.inout, OutQParams.mvOut[i].mBuffer->getBufVA(0),OutQParams.mvOut[i].mBuffer->getBufPA(0), OutQParams.mvOut[i].mBuffer->getBufSizeInBytes(0),OutQParams.mvOut[i].mExtraParams.p2pxlID,getMagicNo(OutQParams)); mQParams.mvOut.push_back(OutQParams.mvOut[i]); } for (int i=0; i < OutQParams.mvCropRsInfo.size(); i++) { MCrpRsInfo crop; crop.mGroupID = i + 1; if (i == 0) { /* Scale up IMGI to match VIPI */ crop.mCropRect.s.w = jobDsImg.imgReq.mBuffer->getImgSize().w; crop.mCropRect.s.h = jobDsImg.imgReq.mBuffer->getImgSize().h; } else { crop.mCropRect.s.w = jobFullImg.imgReq.mBuffer->getImgSize().w; crop.mCropRect.s.h = jobFullImg.imgReq.mBuffer->getImgSize().h; } crop.mCropRect.p_integral.x = 0; crop.mCropRect.p_integral.y = 0; crop.mCropRect.p_fractional.x = 0; crop.mCropRect.p_fractional.y = 0; crop.mResizeDst.w = jobFullImg.imgReq.mBuffer->getImgSize().w; crop.mResizeDst.h = jobFullImg.imgReq.mBuffer->getImgSize().h; LOG_DBG("[P2B sets mCropRsInfo] groupid(%d),crop w(%d),h(%d),p_int(%d,%d),p_fra(%d,%d), resize w(%d),h(%d)", crop.mGroupID,crop.mCropRect.s.w,crop.mCropRect.s.h,crop.mCropRect.p_integral.x,crop.mCropRect.p_integral.y, crop.mCropRect.p_fractional.x,crop.mCropRect.p_fractional.y,crop.mResizeDst.w,crop.mResizeDst.h); mQParams.mvCropRsInfo.push_back(crop); } #ifndef _WORKAROUND_P2B /* Invoke ISP tuning to load PCA and LCE */ NS3A::ParamIspProfile_T _3A_profile( NS3A::EIspProfile_VFB_PostProc, getMagicNo(mQParams), MFALSE, NS3A::ParamIspProfile_T::EParamValidate_P2Only ); mp3AHal->setIspProfile(_3A_profile); /* Enque */ CPTLog(Event_FeaturePipe_P2B_FeatureStream, CPTFlagStart); if (OutQParams.mpfnCallback != NULL) { Mutex::Autolock lock(mLock); mqCallbackQParams.push(OutQParams); mQParams.mpCookie = this; mQParams.mpfnCallback = p2bCbFunc; } LOG_DBG("IFeatureStream enque (frame %d)", getMagicNo(mQParams)); CAM_TRACE_FMT_BEGIN("P2BFStrm:%d", getMagicNo(mQParams)); mpIFeatureStream->enque(mQParams); CAM_TRACE_FMT_END(); if (OutQParams.mpfnCallback == NULL) { /* Deque */ QParams outParams; mret = mpIFeatureStream->deque(outParams, -1); if (!mret) { LOG_ERR("IFeatureStream deque failed! (frame %d)", getMagicNo(mQParams)); return MFALSE; } LOG_DBG("IFeatureStream deque succeeds! (frame %d)", getMagicNo(outParams)); OutQParams.mDequeSuccess = outParams.mDequeSuccess; CPTLog(Event_FeaturePipe_P2B_FeatureStream, CPTFlagEnd); #ifndef _DEBUG_DUMP char EnableOption[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camera.featurepipe.dumpp2b", EnableOption, "0"); if (EnableOption[0] == '1') #endif { for (int i=0; i < OutQParams.mvOut.size(); i++) { char szFileName[100]; ::sprintf(szFileName, "/sdcard/p2bo_%dx%d_%04d.yuv", OutQParams.mvOut[i].mBuffer->getImgSize().w, OutQParams.mvOut[i].mBuffer->getImgSize().h, getMagicNo(OutQParams)); OutQParams.mvOut[i].mBuffer->saveToFile(szFileName); } } } #else DpBlitStream dpBlit; MUINT8* dstbufadr = (MUINT8*) mQParams.mvOut[0].mBuffer->getBufVA(0); //***************************src YV12****************************// unsigned int src_addr_list[3] = {0, 0, 0}; unsigned int src_size_list[3] = {0, 0, 0}; int plane_num = 3; src_addr_list[0] = (unsigned int) mQParams.mvIn[0].mBuffer->getBufVA(0), src_addr_list[1] = (unsigned int) mQParams.mvIn[0].mBuffer->getBufVA(1), src_addr_list[2] = (unsigned int) mQParams.mvIn[0].mBuffer->getBufVA(2), src_size_list[0] = mQParams.mvIn[0].mBuffer->getBufSizeInBytes(0); src_size_list[1] = mQParams.mvIn[0].mBuffer->getBufSizeInBytes(1); src_size_list[2] = mQParams.mvIn[0].mBuffer->getBufSizeInBytes(2); dpBlit.setSrcBuffer((void **)src_addr_list, src_size_list, plane_num); dpBlit.setSrcConfig(mQParams.mvIn[0].mBuffer->getImgSize().w, mQParams.mvIn[0].mBuffer->getImgSize().h, DP_COLOR_YV12); //***************************dst YV12********************************// int dst_ysize = mQParams.mvOut[0].mBuffer->getImgSize().w * mQParams.mvOut[0].mBuffer->getImgSize().h; int dst_uvsize; dst_uvsize = dst_ysize / 4; unsigned int dst_addr_list[3] = {0, 0, 0}; unsigned int dst_size_list[3] = {0, 0, 0}; plane_num = 3; dst_addr_list[0] = (unsigned int) mQParams.mvOut[0].mBuffer->getBufVA(0); dst_addr_list[1] = (unsigned int) mQParams.mvOut[0].mBuffer->getBufVA(1); dst_addr_list[2] = (unsigned int) mQParams.mvOut[0].mBuffer->getBufVA(2); dst_size_list[0] = mQParams.mvOut[0].mBuffer->getBufSizeInBytes(0); dst_size_list[1] = mQParams.mvOut[0].mBuffer->getBufSizeInBytes(1); dst_size_list[2] = mQParams.mvOut[0].mBuffer->getBufSizeInBytes(2); dpBlit.setDstBuffer((void**)dst_addr_list, dst_size_list, plane_num); dpBlit.setDstConfig(mQParams.mvOut[0].mBuffer->getImgSize().w, mQParams.mvOut[0].mBuffer->getImgSize().h, DP_COLOR_YV12); dpBlit.setRotate(0); // set & add pipe to stream if (dpBlit.invalidate()) //trigger HW { LOG_ERR("FDstream invalidate failed"); return MFALSE; } //saveBufToFile("fdi.yuv", dstbufadr, dst_ysize + dst_uvsize * 2); #endif if (OutQParams.mpfnCallback == NULL) { Mutex::Autolock lock(mLock); qCallerQParams.push(OutQParams); sem_post(&mModuleSem); } handleReturnBuffer(VFBSW_TO_P2B_PCA, (MUINTPTR) &jobPCA.imgReq, jobPCA.mFrameNo); CPTLog(Event_FeaturePipe_P2BThread, CPTFlagEnd); CAM_TRACE_FMT_END(); FUNCTION_LOG_END; return MTRUE; } MBOOL FeaturePipeP2bNode:: onReturnBuffer(MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { //FUNCTION_LOG_START; //FUNCTION_LOG_END; return MTRUE; } MVOID FeaturePipeP2bNode:: onDumpBuffer(const char* usr, MUINT32 const data, MUINTPTR const buf, MUINT32 const ext) { }
bd29f06b1178581a9241f3e8e0423b6a93b2ef60
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_2/processor39/15/U
79669700d0a99f6a05fa2b92a7f711d20270bda7
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
20,939
U
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "15"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 392 ( (0.35068 -0.00172033 1.67084e-22) (0.358766 -0.00168662 7.53196e-23) (0.366701 -0.00165362 -4.19321e-23) (0.352019 -0.00515804 -6.28432e-22) (0.360079 -0.00505712 2.96927e-22) (0.367988 -0.00495832 1.14835e-21) (0.354689 -0.00857805 4.53702e-22) (0.362697 -0.00841042 -2.97569e-22) (0.370556 -0.00824628 9.06407e-22) (0.358675 -0.0119687 -1.426e-21) (0.366605 -0.0117352 7.68196e-22) (0.374388 -0.0115065 -2.77334e-21) (0.363954 -0.0153187 2.96067e-22) (0.371781 -0.0150203 3.0091e-22) (0.379464 -0.0147281 2.20597e-22) (0.370494 -0.0186167 3.65704e-21) (0.378194 -0.018255 -2.41729e-21) (0.385753 -0.0179007 7.61558e-22) (0.37826 -0.0218522 -7.1818e-21) (0.385809 -0.0214287 4.93114e-21) (0.393222 -0.0210139 -4.78558e-21) (0.387207 -0.0250147 -4.17824e-21) (0.394583 -0.0245316 1.50642e-21) (0.401826 -0.0240582 -7.82586e-23) (0.397284 -0.0280947 -6.48278e-21) (0.404465 -0.027554 -2.5613e-22) (0.411519 -0.0270242 -1.64401e-21) (0.408436 -0.0310829 -2.00946e-21) (0.415403 -0.0304872 5.79742e-21) (0.422247 -0.0299034 3.71931e-22) (0.420602 -0.0339708 2.67543e-21) (0.427335 -0.0333229 5.68926e-22) (0.433952 -0.0326877 2.81386e-21) (0.433715 -0.0367508 -1.36271e-21) (0.440198 -0.0360535 -1.27179e-22) (0.446571 -0.0353698 -2.21423e-22) (0.447708 -0.0394158 5.57148e-21) (0.453924 -0.0386722 -9.5939e-21) (0.460038 -0.0379429 1.18063e-20) (0.466051 -0.0372283 -8.42958e-21) (0.462505 -0.0419597 -7.64423e-22) (0.468441 -0.041173 9.08353e-21) (0.474282 -0.0404013 -1.38256e-20) (0.48003 -0.0396449 5.95969e-21) (0.478033 -0.044377 3.98051e-21) (0.483676 -0.0435506 -3.46082e-21) (0.489232 -0.0427398 3.12834e-21) (0.494703 -0.0419447 -3.30529e-21) (0.499554 -0.0458008 -3.28763e-21) (0.504815 -0.0449541 9.92218e-22) (0.509998 -0.0441237 -5.02317e-21) (0.515996 -0.0479199 9.02965e-21) (0.520954 -0.0470408 -8.75907e-21) (0.525841 -0.0461783 6.98249e-21) (0.532927 -0.0499054 -2.16552e-20) (0.537573 -0.0489974 8.56599e-21) (0.542158 -0.0481062 -2.55911e-21) (0.550267 -0.0517556 9.65587e-21) (0.554598 -0.0508222 -6.7071e-21) (0.558875 -0.0499056 -6.25873e-22) (0.56794 -0.0534689 1.52513e-20) (0.571952 -0.0525135 -2.92515e-21) (0.575919 -0.051575 -1.73592e-21) (0.58587 -0.0550427 -6.11849e-21) (0.589561 -0.0540691 3.52324e-21) (0.593216 -0.053112 -1.62886e-20) (0.596834 -0.0521723 6.68415e-21) (0.607353 -0.0554921 5.11047e-21) (0.610696 -0.0545198 -8.16507e-21) (0.61401 -0.0535645 -7.18888e-21) (0.625258 -0.0568075 9.21729e-21) (0.628289 -0.0558219 -1.21238e-20) (0.6313 -0.054853 2.00258e-21) (0.643207 -0.0580185 -1.38742e-20) (0.64593 -0.0570218 1.08943e-20) (0.648641 -0.0560415 -2.04661e-21) (0.676571 -0.059821 0) (0.678786 -0.0588244 0) (0.681001 -0.0578424 0) (0.728248 -0.0616993 0) (0.729678 -0.0607147 0) (0.731127 -0.0597426 0) (0.780144 -0.0627926 -1.78217e-11) (0.780806 -0.0618391 1.78217e-11) (0.781506 -0.0608951 0) (0.831233 -0.0630736 -1.79381e-11) (0.83117 -0.062171 1.79381e-11) (0.83116 -0.0612739 0) (0.880582 -0.0625996 0) (0.879857 -0.0617646 0) (0.8792 -0.0609309 0) (0.927383 -0.0614544 0) (0.926076 -0.0607004 0) (0.924849 -0.0599431 0) (0.970972 -0.0597338 0) (0.969178 -0.0590706 0) (0.967469 -0.0583993 0) (1.01085 -0.0575438 -1.83703e-11) (1.00867 -0.056977 1.83703e-11) (1.00658 -0.0563973 0) (1.04669 -0.0549947 -1.84601e-11) (1.04422 -0.0545258 1.84601e-11) (1.04184 -0.0540396 3.75748e-29) (1.07833 -0.0521943 1.92795e-28) (1.07567 -0.0518212 6.66352e-28) (1.0731 -0.0514268 -3.75748e-29) (1.10576 -0.0492431 0) (1.10299 -0.0489606 0) (1.10031 -0.0486534 0) (1.1291 -0.0462297 0) (1.12631 -0.0460304 0) (1.12359 -0.0458036 0) (1.14858 -0.0432284 -1.87109e-11) (1.14582 -0.0431033 1.87109e-11) (1.14313 -0.0429486 0) (1.16452 -0.0402979 -1.87447e-11) (1.16184 -0.0402373 1.87447e-11) (1.15922 -0.0401456 0) (1.17727 -0.037481 1.95258e-28) (1.17471 -0.0374752 0) (1.1722 -0.0374373 3.83537e-29) (1.18723 -0.0348061 -1.95258e-28) (1.18481 -0.0348457 0) (1.18242 -0.0348528 -3.83537e-29) (1.19479 -0.0322891 0) (1.19252 -0.0323656 0) (1.19027 -0.0324094 0) (1.20033 -0.0299354 0) (1.1982 -0.0300411 0) (1.1961 -0.0301144 0) (1.2042 -0.0277426 0) (1.20222 -0.0278709 -3.90568e-28) (1.20026 -0.0279673 0) (1.20672 -0.0257025 0) (1.20488 -0.025848 3.90568e-28) (1.20305 -0.0259621 0) (1.20817 -0.0238037 0) (1.20645 -0.0239616 0) (1.20474 -0.024089 1.07967e-27) (1.20879 -0.0220326 0) (1.20718 -0.0221992 0) (1.20558 -0.022336 -1.07967e-27) (1.20878 -0.0203753 0) (1.20727 -0.0205472 0) (1.20577 -0.0206904 0) (1.20831 -0.0188182 0) (1.20688 -0.0189926 0) (1.20546 -0.0191395 0) (1.2075 -0.0173483 0) (1.20615 -0.017523 -2.88996e-28) (1.2048 -0.0176713 1.07409e-27) (1.20647 -0.0159542 0) (1.20519 -0.016127 2.88996e-28) (1.2039 -0.0162748 -1.07409e-27) (1.2053 -0.0146258 0) (1.20408 -0.0147948 0) (1.20285 -0.0149402 0) (1.20406 -0.013354 0) (1.20289 -0.0135176 0) (1.2017 -0.013659 0) (1.2028 -0.0121314 0) (1.20167 -0.012288 -3.83537e-28) (1.20053 -0.0124238 0) (1.20156 -0.0109512 0) (1.20047 -0.0110993 3.83537e-28) (1.19936 -0.0112283 0) (1.20037 -0.00980791 0) (1.19931 -0.00994617 -1.70425e-11) (1.19823 -0.0100669 -1.67279e-11) (1.19926 -0.00869642 0) (1.19822 -0.00882361 1.70425e-11) (1.19717 -0.008935 1.67279e-11) (1.19823 -0.00761239 0) (1.19721 -0.00772738 2.84426e-28) (1.19619 -0.00782831 0) (1.19731 -0.00655187 0) (1.19631 -0.00665364 -2.84426e-28) (1.19531 -0.00674314 0) (1.1965 -0.00551125 0) (1.19553 -0.0055989 0) (1.19453 -0.00567611 0) (1.19582 -0.00448715 0) (1.19486 -0.00455992 0) (1.19388 -0.00462411 0) (1.19527 -0.00347637 0) (1.19432 -0.00353364 0) (1.19335 -0.0035842 0) (1.19486 -0.00247586 0) (1.19391 -0.00251712 0) (1.19295 -0.00255358 0) (1.19458 -0.0014826 0) (1.19363 -0.0015075 -3.7857e-28) (1.19268 -0.00152952 0) (1.19444 -0.00049371 0) (1.1935 -0.000502035 3.82636e-28) (1.19254 -0.000509398 0) (0.676571 0.0598231 0) (0.728249 0.0617013 0) (0.780145 0.0627944 8.54657e-28) (0.831233 0.0630753 -3.5367e-28) (0.880583 0.0626012 -1.88935e-28) (0.927383 0.0614559 1.88935e-28) (0.970972 0.0597351 0) (1.01085 0.0575451 1.83703e-11) (1.04669 0.0549959 1.84601e-11) (1.07833 0.0521954 -1.92794e-28) (1.10576 0.0492441 1.77911e-11) (1.1291 0.0462306 -1.77911e-11) (1.14858 0.0432292 2.52989e-28) (1.16452 0.0402986 -1.01504e-27) (1.17727 0.0374816 0) (1.18723 0.0348067 0) (1.19479 0.0322897 0) (1.20033 0.0299359 0) (1.2042 0.027743 -1.78506e-11) (1.20672 0.0257029 1.78506e-11) (1.20817 0.023804 0) (1.20879 0.0220329 0) (1.20878 0.0203756 0) (1.20831 0.0188184 0) (1.2075 0.0173485 1.7618e-11) (1.20647 0.0159545 -1.7618e-11) (1.2053 0.014626 0) (1.20406 0.0133542 0) (1.2028 0.0121315 0) (1.20156 0.0109514 0) (1.20037 0.00980802 1.73558e-11) (1.19925 0.00869652 -1.73558e-11) (1.19823 0.00761248 -3.52176e-28) (1.19731 0.00655194 3.52176e-28) (1.1965 0.00551131 0) (1.19582 0.00448719 0) (1.19527 0.00347641 0) (1.19485 0.00247588 0) (1.19458 0.00148262 0) (1.19443 0.000493715 0) (0.678786 0.0588265 0) (0.729679 0.0607167 0) (0.780807 0.061841 -8.54657e-28) (0.83117 0.0621727 3.5367e-28) (0.879857 0.0617662 0) (0.926077 0.0607019 0) (0.969178 0.059072 0) (1.00867 0.0569783 -1.83703e-11) (1.04422 0.0545269 -3.55943e-11) (1.07567 0.0518223 1.71342e-11) (1.10299 0.0489615 1.72724e-11) (1.12631 0.0460312 -1.72724e-11) (1.14582 0.0431041 -2.52989e-28) (1.16184 0.040238 1.01504e-27) (1.17471 0.0374758 -1.74228e-11) (1.18481 0.0348463 1.74228e-11) (1.19252 0.0323661 1.74392e-11) (1.1982 0.0300416 -1.74392e-11) (1.20222 0.0278714 -1.74238e-11) (1.20488 0.0258484 1.74238e-11) (1.20645 0.023962 0) (1.20718 0.0221995 0) (1.20727 0.0205475 0) (1.20688 0.0189929 0) (1.20615 0.0175232 0) (1.20519 0.0161272 0) (1.20408 0.014795 0) (1.20289 0.0135178 0) (1.20167 0.0122881 3.83536e-28) (1.20046 0.0110995 -3.83536e-28) (1.19931 0.00994627 0) (1.19822 0.0088237 0) (1.19721 0.00772745 0) (1.19631 0.0066537 0) (1.19553 0.00559895 0) (1.19486 0.00455996 0) (1.19432 0.00353367 0) (1.19391 0.00251714 0) (1.19363 0.00150752 3.78569e-28) (1.1935 0.00050204 -3.82636e-28) (0.681001 0.0578446 0) (0.731128 0.0597446 0) (0.781506 0.060897 0) (0.831161 0.0612757 0) (0.8792 0.0609325 0) (0.924849 0.0599446 0) (0.967469 0.0584006 0) (1.00658 0.0563985 0) (1.04184 0.0540407 -1.66154e-11) (1.0731 0.0514278 1.66154e-11) (1.10031 0.0486543 0) (1.12359 0.0458044 0) (1.14313 0.0429494 0) (1.15922 0.0401463 0) (1.1722 0.0374379 -1.69599e-11) (1.18242 0.0348533 1.69599e-11) (1.19027 0.0324098 1.69979e-11) (1.1961 0.0301148 -1.69979e-11) (1.20026 0.0279677 0) (1.20305 0.0259625 0) (1.20474 0.0240893 1.69853e-11) (1.20558 0.0223363 -1.69853e-11) (1.20577 0.0206907 0) (1.20546 0.0191398 0) (1.2048 0.0176715 1.07408e-27) (1.2039 0.016275 -1.07408e-27) (1.20285 0.0149404 0) (1.2017 0.0136591 0) (1.20053 0.0124239 0) (1.19936 0.0112284 0) (1.19823 0.010067 -1.0633e-27) (1.19717 0.00893507 1.0633e-27) (1.19619 0.00782837 -1.66795e-11) (1.19531 0.00674319 1.66795e-11) (1.19453 0.00567616 0) (1.19388 0.00462415 0) (1.19335 0.00358423 1.05605e-27) (1.19295 0.0025536 -1.05605e-27) (1.19268 0.00152953 -1.65999e-11) (1.19254 0.000509402 1.67782e-11) (0.643208 0.0580207 1.38866e-20) (0.645931 0.0570241 -1.04994e-20) (0.648641 0.0560438 2.05815e-21) (0.625258 0.0568097 -8.98504e-21) (0.62829 0.0558242 1.20744e-20) (0.631301 0.0548553 -1.80516e-21) (0.607354 0.0554944 -5.07966e-21) (0.610696 0.0545221 8.05213e-21) (0.61401 0.0535669 7.21443e-21) (0.585871 0.0550451 6.15572e-21) (0.589562 0.0540714 -4.03321e-21) (0.593217 0.0531144 1.58923e-20) (0.596835 0.0521747 -6.91524e-21) (0.567941 0.0534713 -1.54008e-20) (0.571953 0.0525159 3.58359e-21) (0.57592 0.0515774 2.50218e-21) (0.550268 0.051758 -9.49978e-21) (0.554599 0.0508246 6.33082e-21) (0.558876 0.0499081 1.03542e-21) (0.532928 0.0499079 2.1485e-20) (0.537574 0.0489999 -9.54122e-21) (0.542159 0.0481087 1.4757e-21) (0.515997 0.0479225 -9.3248e-21) (0.520955 0.0470434 8.69806e-21) (0.525842 0.0461809 -7.34534e-21) (0.499555 0.0458034 3.32394e-21) (0.504816 0.0449567 8.881e-22) (0.509998 0.0441263 5.48143e-21) (0.478035 0.0443796 -3.05035e-21) (0.483677 0.0435533 4.79379e-21) (0.489233 0.0427424 -2.82168e-21) (0.494704 0.0419474 4.63274e-21) (0.462507 0.0419623 7.29429e-23) (0.468442 0.0411756 -1.06691e-20) (0.474283 0.040404 1.2386e-20) (0.480031 0.0396476 -7.857e-21) (0.447709 0.0394185 -6.26718e-21) (0.453925 0.0386749 1.09041e-20) (0.460038 0.0379456 -1.15436e-20) (0.466052 0.0372311 9.02178e-21) (0.433716 0.0367535 1.14727e-21) (0.440199 0.0360562 -2.78276e-22) (0.446572 0.0353725 -4.25768e-22) (0.420603 0.0339736 -8.94647e-22) (0.427336 0.0333257 3.6093e-22) (0.433953 0.0326906 -1.15358e-21) (0.408437 0.0310856 6.88591e-22) (0.415403 0.03049 -7.69377e-21) (0.422248 0.0299063 -8.64822e-23) (0.397285 0.0280975 7.18031e-21) (0.404466 0.0275569 1.09748e-21) (0.41152 0.0270272 9.07649e-22) (0.387207 0.0250176 3.71214e-21) (0.394583 0.0245344 -1.63219e-21) (0.401827 0.0240611 -1.55137e-22) (0.378261 0.021855 7.41166e-21) (0.38581 0.0214316 -4.94649e-21) (0.393222 0.0210169 4.69071e-21) (0.370495 0.0186196 -3.88688e-21) (0.378195 0.0182579 2.66982e-21) (0.385754 0.0179036 -1.46695e-21) (0.363954 0.0153216 -8.24793e-22) (0.371781 0.0150233 -8.0732e-22) (0.379464 0.0147311 7.01678e-22) (0.358675 0.0119717 1.74913e-21) (0.366605 0.0117382 -6.97303e-22) (0.374388 0.0115095 2.48537e-21) (0.354689 0.00858098 -2.33416e-22) (0.362697 0.00841342 6.40594e-22) (0.370556 0.00824933 -9.86907e-22) (0.352019 0.00516097 5.21699e-22) (0.360079 0.00506013 -5.4871e-22) (0.367988 0.00496137 -1.27479e-21) (0.35068 0.00172327 -8.96019e-23) (0.358766 0.00168963 1.80245e-23) (0.366701 0.00165668 7.5122e-23) ) ; boundaryField { inlet { type uniformFixedValue; uniformValue constant (1 0 0); value nonuniform 0(); } outlet { type pressureInletOutletVelocity; value nonuniform 0(); } cylinder { type fixedValue; value nonuniform 0(); } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary39to38 { type processor; value nonuniform List<vector> 132 ( (0.34244 -0.00175474 2.62628e-22) (0.343806 -0.00526101 8.62205e-22) (0.34653 -0.00874909 -3.64011e-22) (0.350596 -0.012207 -1.35449e-21) (0.35598 -0.0156231 2.94527e-21) (0.362651 -0.0189858 6.09963e-22) (0.370571 -0.0222841 -8.80596e-21) (0.379696 -0.0255075 -1.34511e-22) (0.389973 -0.028646 -9.3185e-21) (0.401345 -0.0316902 2.72539e-21) (0.413751 -0.0346313 1.94845e-21) (0.427122 -0.0374614 -3.98964e-22) (0.441388 -0.0401734 -1.68517e-21) (0.456474 -0.0427609 -3.40044e-21) (0.472303 -0.0452184 6.09833e-22) (0.494214 -0.0466634 -9.59577e-21) (0.494214 -0.0466634 -9.59577e-21) (0.510969 -0.0488151 1.07831e-20) (0.528218 -0.0508296 -9.16352e-21) (0.545882 -0.0527052 8.01217e-21) (0.563883 -0.0544402 1.32826e-20) (0.582143 -0.0560321 -2.17799e-20) (0.603983 -0.0564807 -7.25216e-21) (0.603983 -0.0564807 -7.25216e-21) (0.622207 -0.057809 1.82179e-21) (0.640474 -0.0590305 -4.72431e-21) (0.674358 -0.0608311 0) (0.72684 -0.0626949 0) (0.779522 -0.0637538 0) (0.831354 -0.0639799 0) (0.88138 -0.0634336 -4.04914e-29) (0.928772 -0.0622022 4.04914e-29) (0.972856 -0.0603857 0) (1.01313 -0.0580944 0) (1.04925 -0.0554427 -4.12214e-29) (1.08108 -0.0525424 4.12214e-29) (1.10861 -0.049497 0) (1.13196 -0.0463976 0) (1.1514 -0.04332 0) (1.16725 -0.0403235 0) (1.17988 -0.037451 4.15733e-29) (1.18969 -0.0347303 -4.15733e-29) (1.1971 -0.0321765 -1.16641e-27) (1.20248 -0.0297939 1.16641e-27) (1.2062 -0.027579 0) (1.20858 -0.0255226 0) (1.20991 -0.0236122 0) (1.21041 -0.0218337 0) (1.2103 -0.0201723 0) (1.20973 -0.0186138 0) (1.20885 -0.0171451 1.14295e-27) (1.20775 -0.0157543 -1.14295e-27) (1.20652 -0.0144311 0) (1.20523 -0.0131664 0) (1.20393 -0.0119524 0) (1.20265 -0.0107825 0) (1.20143 -0.00965079 0) (1.20028 -0.00855222 0) (1.19923 -0.00748229 0) (1.19829 -0.00643693 0) (1.19747 -0.00541238 0) (1.19677 -0.00440516 0) (1.19621 -0.00341192 0) (1.19578 -0.00242945 0) (1.1955 -0.00145461 0) (1.19536 -0.000484353 0) (0.674358 0.0608332 0) (0.726841 0.0626969 0) (0.779523 0.0637556 0) (0.831355 0.0639816 0) (0.88138 0.0634352 0) (0.928772 0.0622037 0) (0.972857 0.0603871 0) (1.01313 0.0580957 0) (1.04925 0.0554439 4.12214e-29) (1.08108 0.0525435 -4.12214e-29) (1.1086 0.049498 1.16492e-27) (1.13196 0.0463985 -1.16492e-27) (1.1514 0.0433209 0) (1.16725 0.0403243 0) (1.17988 0.0374517 0) (1.18969 0.034731 0) (1.1971 0.0321771 0) (1.20248 0.0297945 0) (1.2062 0.0275795 -1.82845e-11) (1.20858 0.025523 1.82845e-11) (1.2099 0.0236126 0) (1.21041 0.021834 0) (1.2103 0.0201726 0) (1.20973 0.018614 0) (1.20885 0.0171453 3.59618e-11) (1.20775 0.0157545 -3.59618e-11) (1.20652 0.0144313 0) (1.20523 0.0131666 0) (1.20393 0.0119526 -1.04876e-27) (1.20265 0.0107826 1.04876e-27) (1.20143 0.00965091 1.76672e-11) (1.20028 0.00855233 -1.76672e-11) (1.19923 0.00748238 0) (1.19829 0.006437 0) (1.19747 0.00541245 -1.11378e-27) (1.19677 0.00440521 1.11378e-27) (1.19621 0.00341196 0) (1.19578 0.00242948 0) (1.1955 0.00145463 -1.03063e-27) (1.19536 0.000484359 1.0417e-27) (0.640475 0.0590327 4.73718e-21) (0.622208 0.0578112 -1.60157e-21) (0.603984 0.056483 7.02167e-21) (0.603984 0.056483 7.02167e-21) (0.582144 0.0560344 2.09553e-20) (0.563884 0.0544426 -1.25283e-20) (0.545884 0.0527076 -8.30794e-21) (0.528219 0.0508321 8.58076e-21) (0.51097 0.0488176 -1.15918e-20) (0.494215 0.0466659 1.06538e-20) (0.494215 0.0466659 1.06538e-20) (0.472304 0.0452209 1.35789e-21) (0.456475 0.0427634 1.18023e-21) (0.441389 0.040176 2.90192e-21) (0.427123 0.0374641 1.04864e-21) (0.413752 0.034634 -2.44652e-21) (0.401346 0.0316929 -2.60489e-21) (0.389974 0.0286487 9.10908e-21) (0.379697 0.0255103 -6.97736e-23) (0.370572 0.0222869 9.13011e-21) (0.362652 0.0189886 -4.08021e-22) (0.35598 0.0156259 -3.83208e-21) (0.350596 0.0122099 1.54681e-21) (0.34653 0.00875193 6.04518e-22) (0.343806 0.00526386 -9.54439e-22) (0.34244 0.0017576 -1.16971e-22) ) ; } procBoundary39to40 { type processor; value nonuniform List<vector> 132 ( (0.374488 -0.00162133 1.65555e-22) (0.375751 -0.00486165 6.99988e-22) (0.378269 -0.00808568 8.85199e-22) (0.382027 -0.0112827 -3.30436e-21) (0.387005 -0.0144422 -4.38172e-21) (0.393174 -0.0175539 -1.96853e-21) (0.4005 -0.0206079 7.38631e-22) (0.40894 -0.0235948 2.74869e-21) (0.418448 -0.0265056 -4.47077e-21) (0.428973 -0.0293319 4.15287e-23) (0.440456 -0.0320657 7.47387e-21) (0.452837 -0.0347 -4.14561e-21) (0.452837 -0.0347 -4.14561e-21) (0.471966 -0.0365288 -3.0088e-21) (0.485686 -0.0389042 5.79737e-21) (0.500088 -0.041166 -5.08213e-21) (0.515103 -0.04331 -1.83088e-21) (0.530659 -0.045333 6.8244e-21) (0.546682 -0.0472323 -6.56004e-21) (0.5631 -0.0490065 -1.41115e-21) (0.579841 -0.0506539 -2.4599e-21) (0.579841 -0.0506539 -2.4599e-21) (0.600415 -0.0512503 4.84956e-21) (0.617295 -0.0526269 -7.89325e-21) (0.63429 -0.0539015 -7.56157e-21) (0.651338 -0.0550782 1.75956e-20) (0.683214 -0.056876 0) (0.732593 -0.0587842 0) (0.78224 -0.059962 0) (0.831201 -0.0603844 0) (0.878606 -0.0601006 6.10222e-28) (0.923695 -0.059185 -6.10222e-28) (0.965842 -0.0577225 0) (1.00457 -0.0558078 0) (1.03955 -0.0535393 0) (1.0706 -0.0510145 0) (1.0977 -0.048325 0) (1.12094 -0.0455529 0) (1.1405 -0.0427679 0) (1.15666 -0.0400264 0) (1.16973 -0.0373708 -6.42016e-28) (1.18008 -0.0348306 6.42016e-28) (1.18806 -0.0324237 0) (1.19403 -0.0301583 0) (1.19831 -0.0280347 3.71926e-28) (1.20123 -0.0260478 -3.71926e-28) (1.20304 -0.0241886 -2.77875e-28) (1.20399 -0.0224459 2.77875e-28) (1.20427 -0.0208075 0) (1.20404 -0.0192613 0) (1.20346 -0.0177955 0) (1.20262 -0.0163996 0) (1.20162 -0.0150638 0) (1.20052 -0.0137799 0) (1.19938 -0.0125406 0) (1.19825 -0.0113396 0) (1.19715 -0.0101715 -2.74855e-28) (1.19611 -0.00903176 2.74855e-28) (1.19515 -0.00791622 -2.74206e-28) (1.19429 -0.00682127 2.74206e-28) (1.19353 -0.00574364 0) (1.19289 -0.00468034 0) (1.19237 -0.00362855 2.73309e-28) (1.19198 -0.00258558 -2.73309e-28) (1.19171 -0.00154886 3.65569e-28) (1.19158 -0.000515867 -3.69495e-28) (0.683215 0.0568782 0) (0.732593 0.0587862 0) (0.78224 0.0599638 0) (0.831201 0.0603861 0) (0.878606 0.0601022 -6.1022e-28) (0.923695 0.0591864 6.1022e-28) (0.965842 0.0577238 0) (1.00457 0.0558089 0) (1.03955 0.0535403 0) (1.0706 0.0510154 0) (1.0977 0.0483259 1.62832e-11) (1.12094 0.0455537 -1.62832e-11) (1.1405 0.0427686 0) (1.15666 0.040027 0) (1.16973 0.0373713 6.42013e-28) (1.18008 0.0348311 -6.42013e-28) (1.18806 0.0324242 1.6566e-11) (1.19403 0.0301587 -1.6566e-11) (1.19831 0.028035 -3.71925e-28) (1.20123 0.0260481 3.71925e-28) (1.20304 0.0241888 1.65927e-11) (1.20399 0.0224461 -1.65927e-11) (1.20426 0.0208077 0) (1.20404 0.0192615 0) (1.20346 0.0177957 1.65407e-11) (1.20262 0.0163997 -1.65407e-11) (1.20162 0.0150639 0) (1.20052 0.01378 0) (1.19938 0.0125407 0) (1.19825 0.0113397 0) (1.19715 0.0101716 2.74855e-28) (1.19611 0.00903183 -2.74855e-28) (1.19515 0.00791627 -1.63736e-11) (1.19429 0.00682131 1.63736e-11) (1.19353 0.00574368 0) (1.19289 0.00468037 0) (1.19237 0.00362857 -2.73308e-28) (1.19198 0.0025856 2.73308e-28) (1.19171 0.00154887 -1.63086e-11) (1.19158 0.00051587 1.64837e-11) (0.651339 0.0550805 -1.75845e-20) (0.63429 0.0539038 7.79903e-21) (0.617295 0.0526292 7.82728e-21) (0.600416 0.0512527 -5.21865e-21) (0.579842 0.0506563 2.20703e-21) (0.579842 0.0506563 2.20703e-21) (0.563101 0.049009 2.02573e-21) (0.546683 0.0472349 5.97727e-21) (0.53066 0.0453356 -7.5262e-21) (0.515104 0.0433127 3.58409e-21) (0.500089 0.0411687 5.05882e-21) (0.485686 0.038907 -6.39832e-21) (0.471966 0.0365315 2.74435e-21) (0.452838 0.0347028 4.6873e-21) (0.452838 0.0347028 4.6873e-21) (0.440457 0.0320686 -7.86712e-21) (0.428973 0.0293348 -8.44268e-22) (0.418449 0.0265086 5.19238e-21) (0.40894 0.0235978 -3.39076e-21) (0.4005 0.0206109 8.46852e-24) (0.393175 0.0175569 2.03017e-21) (0.387006 0.0144452 3.7236e-21) (0.382028 0.0112858 3.47183e-21) (0.378269 0.00808876 -7.39536e-22) (0.375751 0.00486474 -6.76857e-22) (0.374488 0.00162443 -7.83819e-23) ) ; } } // ************************************************************************* //
ebca6c58bd1c31d4abf5575d1e9e2a00ab15cdd7
b029d4bbe5b67365ac2b66f3d854b8c49141905f
/Parcial II/Parcial 2 - 2018-3/Problema 2/Genero.h
9bf901533f30c69ae140125f51cec536c881bd83
[]
no_license
chjesus/Estructura-de-Datos
5ea4e0f5d2ecb3a3013d6b9cd437c747fdf50ebf
e8b865b442e8a5b7f03da4de0d0f7a7ddcebbbd0
refs/heads/master
2020-03-28T20:07:28.211502
2018-12-01T04:10:33
2018-12-01T04:10:33
149,041,372
5
0
null
null
null
null
UTF-8
C++
false
false
1,371
h
Genero.h
#ifndef GENERO_H #define GENERO_H #include "ListaDinSimple.h" #include "Canciones.h" using namespace std; class Genero{ char genero[30]; ListDinSimple<Canciones> *lista; public: Genero(){} Genero(char *gen){ strcpy(this->genero,gen); lista = new ListDinSimple<Canciones>(); } int agregarCancion(Canciones x); int eliminarCancion(Canciones &x); int buscarCancion(Canciones &x); void vaciarListaCanciones(); void invertListaCanciones(); void imprimir(bool band=true); char *getGenero(){return genero;} void setGenero(char *gen) {strcpy(this->genero,gen);} bool operator<(const Genero& datos){ return strcmpi(this->genero,datos.genero)<0; } bool operator==(const Genero& datos){ return strcmpi(this->genero,datos.genero)==0; } friend ostream& operator<<(ostream& os, const Genero& datos){ os<<"Genero: "<<datos.genero; return os; } }; int Genero::agregarCancion(Canciones x){ return lista->agregar(x); } int Genero::eliminarCancion(Canciones &x){ return lista->eliminar(x); } int Genero::buscarCancion(Canciones &x){ return lista->buscar(x); } void Genero::vaciarListaCanciones(){ lista->Vaciar(); } void Genero::invertListaCanciones(){ lista->invert(); } void Genero::imprimir(bool band){ cout<<endl<<"Genero: "<<genero<<endl; if(band){ cout<<"Canciones: "<<endl; lista->imprimir(); } } #endif
085ffec35480d972c6245cb29eed0acaf26013f6
64cb3c5443ba6fbf79343916dc8ac5dc920d48fb
/34. Find First and Last Position of Element in Sorted Array.cpp
0239880b9a9af09ea8461ad614758c3427d3f034
[]
no_license
JianHangChen/LeetCode
ec905e903049de4021ecd83de9b8cfeb6e900114
0183704dcf7208e274d5eea6e41e4caad7ed6954
refs/heads/master
2022-08-16T12:12:13.142517
2022-07-24T05:36:55
2022-07-24T05:36:55
170,805,203
2
1
null
2019-06-08T03:16:17
2019-02-15T05:09:32
Python
UTF-8
C++
false
false
7,202
cpp
34. Find First and Last Position of Element in Sorted Array.cpp
//!!!! sol2.1 new template class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { if(nums.size() == 0) return {-1, -1};// !!! check int l = 0, r = nums.size() - 1; vector<int> res; while(l < r - 1){ int mid = l + (r - l) / 2; if(nums[mid] == target){ r = mid; } else if(nums[mid] < target){ l = mid; } else{ r = mid; } } if(nums[l] == target) res.push_back(l); else if(nums[r] == target) res.push_back(r); else return {-1, -1}; r = nums.size() - 1; while(l < r - 1){ int mid = l + (r - l) / 2; if(nums[mid] == target){ l = mid; } else if(nums[mid] < target){ l = mid; } else{ r = mid; } } if(nums[r] == target) res.push_back(r); else res.push_back(l); return res; } }; // sol2, my upper lower bound not using default funciton class Solution{ public: vector<int> searchRange(vector<int>& nums, int target){ int n = nums.size(); vector<int> res = {-1, -1}; int left = 0, right = n, mid; while(left < right){ mid = left + (right - left) / 2; if( nums[mid] < target){ left = mid + 1; } else{ right = mid; } } if( left >= n || nums[left] != target) return res; res[0] = left; right = n; while(left < right){ mid = left + (right - left) / 2; if(nums[mid] <= target) left = mid + 1; else right = mid; } res[1] = left - 1; return res; } }; //!!!! sol1, my upper, lower bound , O(logn), O(1) #include <stdc++.h> #include <algorithm> class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int n = nums.size(); auto lb = lower_bound(nums.begin(), nums.end(), target); if(lb == nums.end() || *lb != target) return {-1, -1}; //!!! carefull about if we can find the target auto ub = upper_bound(nums.begin(), nums.end(), target); return {lb - nums.begin(), ub - nums.begin() - 1}; } }; class Solution: # test case: [], [1,2], [1] 1 # sol1, 2 binary search, write from ans # def searchRange(self, nums: List[int], target: int) -> List[int]: # if nums == []: # return [-1, -1] # low = 0 # high = len(nums) - 1 # while low + 1 < high: # mid = low + (high - low) // 2 # if nums[mid] >= target: # high = mid # else: # low = mid + 1 # if nums[low] == target: # start = low # elif nums[high] == target: # start = high # else: # return [-1, -1] # low = start # high = len(nums) # while low < high: # mid = low + (high - low) // 2 # if nums[mid] > target: # high = mid # else: # low = mid + 1 # end = low - 1 # return [start, end] # sol 1.1, from ans, iteratively 2 binary search # def searchRange(self, nums: List[int], target: int) -> List[int]: # def search(isleft): # low = 0 # high = len(nums) # while low < high: # mid = low + (high - low) // 2 # # left not done: find the first appearance # # left done: find the idx after last appearance # if nums[mid] > target or (isleft and nums[mid] == target): # high = mid # else: # low = mid + 1 # return low # left_idx = search(isleft = True) # if left_idx >= len(nums) or nums[left_idx] != target: # return [-1, -1] # return [left_idx, search(isleft = False) - 1] # sol1.2, best two binary search !!! # from sol2 of https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/14707/9-11-lines-O(log-n) def searchRange(self, nums: List[int], target: int) -> List[int]: def insert_idx(n): # get the idx if insert n to nums low = 0 high = len(nums) while low < high: mid = low + (high - low) // 2 if nums[mid] < n: low = mid + 1 else: high = mid return low left = insert_idx(target) return [left, insert_idx(target+1) - 1] if target in nums[left:left+1] else [-1, -1] # here if target in nums[left:left+1], even if nums == [], we can say target not in nums # is not the same as nums[left] == target # sol2, my, brute force, linear scan O(n) # start = end = -1 # for i in range(len(nums)): # if nums[i] == target: # if start == -1: # start = end = i # else: # end = i # return [start, end] # # sol2.1, from the ans, better linear scan # for i in range(len(nums)): # if nums[i] == target: # start = i # break # else: # return [-1, -1] # for i in range(len(nums)-1, -1, -1): # if nums[i] == target: # end = i # break # return [start, end] # sol3, divide and conquer by recursion #from https://leetcode.com/explore/learn/card/binary-search/135/template-iii/944/discuss/14707/9-11-lines-O(log-n) # def searchRange(self, nums: List[int], target: int) -> List[int]: # def search(low, high): # mid = low + (high - low) // 2 # if nums[low] == nums[high] == target: # return [low, high] # if nums[low] <= target <= nums[high]: # left = search(low, mid) # right = search(mid+1, high) # return max(left , right) if -1 in (left+right) else [ left[0], right[1] ] # else: # return [-1, -1] # return [-1, -1] if len(nums) == 0 else search(0, len(nums) - 1) # sol4, use python library # from sol3 of https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/14707/9-11-lines-O(log-n) # def searchRange(self, nums: List[int], target: int) -> List[int]: # low = bisect.bisect_left(nums, target) # return [low, bisect.bisect(nums, target) - 1] if target in nums[low:low+1] else [-1, -1]
eeaecb1c830856dc8d26ff17b547ce11366781a4
674330d2c23115e7d4f364a6636fe3147a445840
/my_scpi_dll/handle_multi_cmd.h
6bc5fd70693e4c5377d28a646336854500849ef0
[]
no_license
NumbLucas/scpi-parser
58cf9bd25a34eebdf267d4379b5230e487d323e5
708c5260c8f8c2e9becc216d478ff138741456a2
refs/heads/master
2020-11-25T15:12:04.718304
2019-12-21T02:32:53
2019-12-21T02:32:53
228,733,914
0
0
null
null
null
null
UTF-8
C++
false
false
270
h
handle_multi_cmd.h
#include <string> #include <vector> using namespace std; int handleMultiCmd(char *); void splitStr(const string& str, const char& separator, vector<string>& rst); void splitCmdAndParm(const string& str,string& cmd, string& param); void removeHeadTailSpace(string& str);
35b418cef57bbcada99acde2e82efd23f3da67de
66330f7a1ff0b8447b4245474ab4de48727fd1c5
/libs/blueprint/include/nil/crypto3/zk/components/algebra/curves/weierstrass/element_g1.hpp
12c445c854a00e0f8b3c0a2da2e312d91b9501ee
[ "MIT" ]
permissive
everscalecodes/knapsack-snark
fd3cc6155125ae6ff0fc56aa979f84ba6a8c49c7
633515a13906407338a81b9874d964869ddec624
refs/heads/main
2023-07-18T06:05:22.319230
2021-08-31T16:10:16
2021-08-31T16:10:16
447,180,824
0
1
MIT
2022-01-12T10:53:21
2022-01-12T10:53:20
null
UTF-8
C++
false
false
13,219
hpp
element_g1.hpp
//---------------------------------------------------------------------------// // Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation> // Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation> // // MIT 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. //---------------------------------------------------------------------------// // @file Declaration of interfaces for G1 components. // // The components verify curve arithmetic in G1 = E(F) where E/F: y^2 = x^3 + A * X + B // is an elliptic curve over F in short Weierstrass form. //---------------------------------------------------------------------------// #ifndef CRYPTO3_ZK_BLUEPRINT_WEIERSTRASS_G1_COMPONENT_HPP #define CRYPTO3_ZK_BLUEPRINT_WEIERSTRASS_G1_COMPONENT_HPP #include <nil/crypto3/zk/components/component.hpp> #include <nil/crypto3/zk/components/algebra/fields/element_fp.hpp> #include <nil/crypto3/zk/components/blueprint_variable.hpp> namespace nil { namespace crypto3 { namespace zk { namespace components { /** * Component that represents a G1 element. */ template<typename CurveType> class element_g1 : public component<typename CurveType::scalar_field_type> { using underlying_field_type = typename CurveType::scalar_field_type; using underlying_element_type = element_fp<underlying_field_type>; public: underlying_element_type X; underlying_element_type Y; blueprint_linear_combination_vector<underlying_field_type> all_vars; element_g1(blueprint<underlying_field_type> &bp) : component<underlying_field_type>(bp) { blueprint_variable<underlying_field_type> X_var, Y_var; X_var.allocate(bp); Y_var.allocate(bp); X = underlying_element_type(X_var); Y = underlying_element_type(Y_var); all_vars.emplace_back(X); all_vars.emplace_back(Y); } element_g1(blueprint<underlying_field_type> &bp, const typename CurveType::pairing::pair_curve_type::g1_type::value_type &P) : component<underlying_field_type>(bp) { typename CurveType::pairing::pair_curve_type::g1_type::value_type Pcopy = P.to_affine(); X.assign(bp, Pcopy.X); Y.assign(bp, Pcopy.Y); X.evaluate(bp); Y.evaluate(bp); all_vars.emplace_back(X); all_vars.emplace_back(Y); } void generate_r1cs_witness( const typename CurveType::pairing::pair_curve_type::g1_type::value_type &el) { typename CurveType::pairing::pair_curve_type::g1_type::value_type el_normalized = el.to_affine(); this->bp.lc_val(X) = el_normalized.X; this->bp.lc_val(Y) = el_normalized.Y; } // (See a comment in r1cs_ppzksnark_verifier_component.hpp about why // we mark this function noinline.) TODO: remove later static std::size_t __attribute__((noinline)) size_in_bits() { return 2 * underlying_field_type::modulus_bits; } static std::size_t num_variables() { return 2; } }; /** * Component that creates constraints for the validity of a G1 element. */ template<typename CurveType> class element_g1_is_well_formed : public component<typename CurveType::scalar_field_type> { using underlying_field_type = typename CurveType::scalar_field_type; public: element_g1<CurveType> P; blueprint_variable<underlying_field_type> P_X_squared; blueprint_variable<underlying_field_type> P_Y_squared; element_g1_is_well_formed(blueprint<underlying_field_type> &bp, const element_g1<CurveType> &P) : component<underlying_field_type>(bp), P(P) { P_X_squared.allocate(bp); P_Y_squared.allocate(bp); } void generate_r1cs_constraints() { this->bp.add_r1cs_constraint( snark::r1cs_constraint<underlying_field_type>({P.X}, {P.X}, {P_X_squared})); this->bp.add_r1cs_constraint( snark::r1cs_constraint<underlying_field_type>({P.Y}, {P.Y}, {P_Y_squared})); this->bp.add_r1cs_constraint(snark::r1cs_constraint<underlying_field_type>( {P.X}, {P_X_squared, blueprint_variable<underlying_field_type>(0) * CurveType::pairing::pair_curve_type::a}, {P_Y_squared, blueprint_variable<underlying_field_type>(0) * (-CurveType::pairing::pair_curve_type::b)})); } void generate_r1cs_witness() { this->bp.val(P_X_squared) = this->bp.lc_val(P.X).squared(); this->bp.val(P_Y_squared) = this->bp.lc_val(P.Y).squared(); } }; /** * Component that creates constraints for G1 addition. */ template<typename CurveType> class element_g1_add : public component<typename CurveType::scalar_field_type> { using underlying_field_type = typename CurveType::scalar_field_type; public: blueprint_variable<underlying_field_type> lambda; blueprint_variable<underlying_field_type> inv; element_g1<CurveType> A; element_g1<CurveType> B; element_g1<CurveType> C; element_g1_add(blueprint<underlying_field_type> &bp, const element_g1<CurveType> &A, const element_g1<CurveType> &B, const element_g1<CurveType> &C) : component<underlying_field_type>(bp), A(A), B(B), C(C) { /* lambda = (B.y - A.y)/(B.x - A.x) C.x = lambda^2 - A.x - B.x C.y = lambda(A.x - C.x) - A.y Special cases: doubling: if B.y = A.y and B.x = A.x then lambda is unbound and C = (lambda^2, lambda^3) addition of negative point: if B.y = -A.y and B.x = A.x then no lambda can satisfy the first equation unless B.y - A.y = 0. But then this reduces to doubling. So we need to check that A.x - B.x != 0, which can be done by enforcing I * (B.x - A.x) = 1 */ lambda.allocate(bp); inv.allocate(bp); } void generate_r1cs_constraints() { this->bp.add_r1cs_constraint(snark::r1cs_constraint<underlying_field_type>( {lambda}, {B.X, A.X * (-1)}, {B.Y, A.Y * (-1)})); this->bp.add_r1cs_constraint( snark::r1cs_constraint<underlying_field_type>({lambda}, {lambda}, {C.X, A.X, B.X})); this->bp.add_r1cs_constraint( snark::r1cs_constraint<underlying_field_type>({lambda}, {A.X, C.X * (-1)}, {C.Y, A.Y})); this->bp.add_r1cs_constraint(snark::r1cs_constraint<underlying_field_type>( {inv}, {B.X, A.X * (-1)}, {blueprint_variable<underlying_field_type>(0)})); } void generate_r1cs_witness() { this->bp.val(inv) = (this->bp.lc_val(B.X) - this->bp.lc_val(A.X)).inversed(); this->bp.val(lambda) = (this->bp.lc_val(B.Y) - this->bp.lc_val(A.Y)) * this->bp.val(inv); this->bp.lc_val(C.X) = this->bp.val(lambda).squared() - this->bp.lc_val(A.X) - this->bp.lc_val(B.X); this->bp.lc_val(C.Y) = this->bp.val(lambda) * (this->bp.lc_val(A.X) - this->bp.lc_val(C.X)) - this->bp.lc_val(A.Y); } }; /** * Component that creates constraints for G1 doubling. */ template<typename CurveType> class element_g1_doubled : public component<typename CurveType::scalar_field_type> { using underlying_field_type = typename CurveType::scalar_field_type; public: blueprint_variable<underlying_field_type> Xsquared; blueprint_variable<underlying_field_type> lambda; element_g1<CurveType> A; element_g1<CurveType> B; element_g1_doubled(blueprint<underlying_field_type> &bp, const element_g1<CurveType> &A, const element_g1<CurveType> &B) : component<underlying_field_type>(bp), A(A), B(B) { Xsquared.allocate(bp); lambda.allocate(bp); } void generate_r1cs_constraints() { this->bp.add_r1cs_constraint( snark::r1cs_constraint<underlying_field_type>({A.X}, {A.X}, {Xsquared})); this->bp.add_r1cs_constraint(snark::r1cs_constraint<underlying_field_type>( {lambda * 2}, {A.Y}, {Xsquared * 3, blueprint_variable<underlying_field_type>(0x00) * CurveType::pairing::pair_curve_type::a})); this->bp.add_r1cs_constraint( snark::r1cs_constraint<underlying_field_type>({lambda}, {lambda}, {B.X, A.X * 2})); this->bp.add_r1cs_constraint( snark::r1cs_constraint<underlying_field_type>({lambda}, {A.X, B.X * (-1)}, {B.Y, A.Y})); } void generate_r1cs_witness() { this->bp.val(Xsquared) = this->bp.lc_val(A.X).squared(); this->bp.val(lambda) = (typename underlying_field_type::value_type(0x03) * this->bp.val(Xsquared) + CurveType::pairing::pair_curve_type::a) * (typename underlying_field_type::value_type(0x02) * this->bp.lc_val(A.Y)).inversed(); this->bp.lc_val(B.X) = this->bp.val(lambda).squared() - typename underlying_field_type::value_type(0x02) * this->bp.lc_val(A.X); this->bp.lc_val(B.Y) = this->bp.val(lambda) * (this->bp.lc_val(A.X) - this->bp.lc_val(B.X)) - this->bp.lc_val(A.Y); } }; } // namespace components } // namespace zk } // namespace crypto3 } // namespace nil #endif // CRYPTO3_ZK_BLUEPRINT_WEIERSTRASS_G1_COMPONENT_HPP
097c3fd7f70f08fc5feec8698d46b266e8a0c074
3879d1ca43c573c209f962182cd1e7f7fe978fbf
/leetcode/1275. Find Winner on a Tic Tac Toe Game/1275.cpp
5bbbfc2e9184c66afb167469ef01c49901cbe0d3
[]
no_license
DoctorLai/ACM
34a5600a5adf22660c5d81b2d8b7a358be537ecf
aefa170f74c55c1230eb6f352770512b1e3f469e
refs/heads/master
2023-09-01T02:13:01.604508
2023-08-31T15:42:07
2023-08-31T15:42:07
146,173,024
62
18
null
2020-10-11T13:19:57
2018-08-26T11:00:36
C++
UTF-8
C++
false
false
1,491
cpp
1275.cpp
// https://helloacm.com/algorithm-to-find-the-winner-on-a-tic-tac-toe-game/ // https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/ // EASY, BRUTEFORCE, GAME class Solution { public: string tictactoe(vector<vector<int>>& moves) { char board[3][3] = {}; //std::fill(&board[0][0], &board[0][0] + sizeof(board), ' '); string result; int i = 0; for (const auto &n: moves) { board[n[0]][n[1]] = ((i ++) % 2 == 0) ? 'A' : 'B'; if (win(board, result)) { return result; } } return i == 9 ? "Draw" : "Pending"; } private: bool win(char board[3][3], string &result) { for (int i = 0; i < 3; ++ i) { if ((board[i][0] != 0) && (board[i][0] == board[i][1]) && (board[i][1] == board[i][2])) { result = board[i][0]; return true; } if ((board[0][i] != 0) && (board[0][i] == board[1][i]) && (board[1][i] == board[2][i])) { result = board[0][i]; return true; } } if ((board[1][1] != 0) && (board[0][0] == board[1][1]) && (board[1][1] == board[2][2])) { result = board[1][1]; return true; } if ((board[1][1] != 0) && (board[0][2] == board[1][1]) && (board[1][1] == board[2][0])) { result = board[1][1]; return true; } return false; } };
45b3a61d832fc71a58ba0f6a8266165c49cff807
8d539ced39960119c418907075b631cec18ca399
/ProjectEuler/148-PE12-HighlyDivisibleTriangularNumber.cpp
251c82588087daba956dbec1160531abd2f88a9d
[ "MIT" ]
permissive
lucastarche/aotd
d27eed7414c11ce1a0a18c2459b800e9cdf91eef
e501a1f27fc48508d24eac461308aaa2e56a23cf
refs/heads/master
2023-07-19T03:56:06.845259
2021-09-12T12:14:56
2021-09-12T12:14:56
294,989,043
3
1
null
2020-12-16T13:58:42
2020-09-12T17:06:06
C++
UTF-8
C++
false
false
1,021
cpp
148-PE12-HighlyDivisibleTriangularNumber.cpp
//PE 12: Highly Divisible Triangular Number //Problem: Find the smallest triangular number (Tn = 1 + 2 + ... + n) with more than 500 divisors. //Solution: We can represent Tn as n * (n + 1) / 2. //Then we precalculate the amount of divisors of every integer up to a certain point (100000 in this case), //and we can get the amount of divisors of the triangular numbers in constant time. //Runtime: O(n log n) //Note: Thanks to Arkhist for helping me prove the bound :D #include "EulerUtils.hpp" long long solve() { vector<long long> sieve = divisor_sieve(100000LL); long long curr = 1LL; while (curr < 100000LL) { long long divisors = 0LL; if (curr % 2 == 0) { divisors = sieve[curr / 2] * sieve[curr + 1]; } else { divisors = sieve[curr] * sieve[(curr + 1) / 2]; } if (divisors > 500LL) return (curr * (curr + 1)) / 2; curr++; } return -1; //This should never happen } int main() { cout << solve() << '\n'; }
1bc87d1a45a5da67b0b3ae6ac8974b942f7c7055
82c55fcfa9f3b7bd5d845cd961cbcfea8fd29bcd
/src/base/unix_task_runner.cc
422947fd84ae2d76370053ce4f86053dcd031b02
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
LineageOS/android_external_perfetto
18fe7db30911cd164c6a95f418d5534945f8a911
37e41206db9bc9c8f86b09d88436b0e9a7b3f5d3
refs/heads/lineage-18.1
2022-10-24T23:28:16.450303
2021-06-08T13:18:57
2021-06-08T13:18:57
144,285,906
3
17
Apache-2.0
2022-10-02T20:13:21
2018-08-10T12:54:13
C++
UTF-8
C++
false
false
6,573
cc
unix_task_runner.cc
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/base/build_config.h" #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include "perfetto/ext/base/unix_task_runner.h" #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <limits> #include "perfetto/ext/base/watchdog.h" namespace perfetto { namespace base { UnixTaskRunner::UnixTaskRunner() { AddFileDescriptorWatch(event_.fd(), [] { // Not reached -- see PostFileDescriptorWatches(). PERFETTO_DFATAL("Should be unreachable."); }); } UnixTaskRunner::~UnixTaskRunner() = default; void UnixTaskRunner::WakeUp() { event_.Notify(); } void UnixTaskRunner::Run() { PERFETTO_DCHECK_THREAD(thread_checker_); created_thread_id_ = GetThreadId(); quit_ = false; for (;;) { int poll_timeout_ms; { std::lock_guard<std::mutex> lock(lock_); if (quit_) return; poll_timeout_ms = GetDelayMsToNextTaskLocked(); UpdateWatchTasksLocked(); } int ret = PERFETTO_EINTR(poll( &poll_fds_[0], static_cast<nfds_t>(poll_fds_.size()), poll_timeout_ms)); PERFETTO_CHECK(ret >= 0); // To avoid starvation we always interleave all types of tasks -- immediate, // delayed and file descriptor watches. PostFileDescriptorWatches(); RunImmediateAndDelayedTask(); } } void UnixTaskRunner::Quit() { std::lock_guard<std::mutex> lock(lock_); quit_ = true; WakeUp(); } bool UnixTaskRunner::QuitCalled() { std::lock_guard<std::mutex> lock(lock_); return quit_; } bool UnixTaskRunner::IsIdleForTesting() { std::lock_guard<std::mutex> lock(lock_); return immediate_tasks_.empty(); } void UnixTaskRunner::UpdateWatchTasksLocked() { PERFETTO_DCHECK_THREAD(thread_checker_); if (!watch_tasks_changed_) return; watch_tasks_changed_ = false; poll_fds_.clear(); for (auto& it : watch_tasks_) { it.second.poll_fd_index = poll_fds_.size(); poll_fds_.push_back({it.first, POLLIN | POLLHUP, 0}); } } void UnixTaskRunner::RunImmediateAndDelayedTask() { // If locking overhead becomes an issue, add a separate work queue. std::function<void()> immediate_task; std::function<void()> delayed_task; TimeMillis now = GetWallTimeMs(); { std::lock_guard<std::mutex> lock(lock_); if (!immediate_tasks_.empty()) { immediate_task = std::move(immediate_tasks_.front()); immediate_tasks_.pop_front(); } if (!delayed_tasks_.empty()) { auto it = delayed_tasks_.begin(); if (now >= it->first) { delayed_task = std::move(it->second); delayed_tasks_.erase(it); } } } errno = 0; if (immediate_task) RunTaskWithWatchdogGuard(immediate_task); errno = 0; if (delayed_task) RunTaskWithWatchdogGuard(delayed_task); } void UnixTaskRunner::PostFileDescriptorWatches() { PERFETTO_DCHECK_THREAD(thread_checker_); for (size_t i = 0; i < poll_fds_.size(); i++) { if (!(poll_fds_[i].revents & (POLLIN | POLLHUP))) continue; poll_fds_[i].revents = 0; // The wake-up event is handled inline to avoid an infinite recursion of // posted tasks. if (poll_fds_[i].fd == event_.fd()) { event_.Clear(); continue; } // Binding to |this| is safe since we are the only object executing the // task. PostTask(std::bind(&UnixTaskRunner::RunFileDescriptorWatch, this, poll_fds_[i].fd)); // Make the fd negative while a posted task is pending. This makes poll(2) // ignore the fd. PERFETTO_DCHECK(poll_fds_[i].fd >= 0); poll_fds_[i].fd = -poll_fds_[i].fd; } } void UnixTaskRunner::RunFileDescriptorWatch(int fd) { std::function<void()> task; { std::lock_guard<std::mutex> lock(lock_); auto it = watch_tasks_.find(fd); if (it == watch_tasks_.end()) return; // Make poll(2) pay attention to the fd again. Since another thread may have // updated this watch we need to refresh the set first. UpdateWatchTasksLocked(); size_t fd_index = it->second.poll_fd_index; PERFETTO_DCHECK(fd_index < poll_fds_.size()); PERFETTO_DCHECK(::abs(poll_fds_[fd_index].fd) == fd); poll_fds_[fd_index].fd = fd; task = it->second.callback; } errno = 0; RunTaskWithWatchdogGuard(task); } int UnixTaskRunner::GetDelayMsToNextTaskLocked() const { PERFETTO_DCHECK_THREAD(thread_checker_); if (!immediate_tasks_.empty()) return 0; if (!delayed_tasks_.empty()) { TimeMillis diff = delayed_tasks_.begin()->first - GetWallTimeMs(); return std::max(0, static_cast<int>(diff.count())); } return -1; } void UnixTaskRunner::PostTask(std::function<void()> task) { bool was_empty; { std::lock_guard<std::mutex> lock(lock_); was_empty = immediate_tasks_.empty(); immediate_tasks_.push_back(std::move(task)); } if (was_empty) WakeUp(); } void UnixTaskRunner::PostDelayedTask(std::function<void()> task, uint32_t delay_ms) { TimeMillis runtime = GetWallTimeMs() + TimeMillis(delay_ms); { std::lock_guard<std::mutex> lock(lock_); delayed_tasks_.insert(std::make_pair(runtime, std::move(task))); } WakeUp(); } void UnixTaskRunner::AddFileDescriptorWatch(int fd, std::function<void()> task) { PERFETTO_DCHECK(fd >= 0); { std::lock_guard<std::mutex> lock(lock_); PERFETTO_DCHECK(!watch_tasks_.count(fd)); watch_tasks_[fd] = {std::move(task), SIZE_MAX}; watch_tasks_changed_ = true; } WakeUp(); } void UnixTaskRunner::RemoveFileDescriptorWatch(int fd) { PERFETTO_DCHECK(fd >= 0); { std::lock_guard<std::mutex> lock(lock_); PERFETTO_DCHECK(watch_tasks_.count(fd)); watch_tasks_.erase(fd); watch_tasks_changed_ = true; } // No need to schedule a wake-up for this. } bool UnixTaskRunner::RunsTasksOnCurrentThread() const { return GetThreadId() == created_thread_id_; } } // namespace base } // namespace perfetto #endif // !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
7b6c32b3a194aad6ef9def76d956f9391101fddd
4512a24742a8e860b6a482dcb57201ebc782e81c
/Hmwk/HelloWorld/main.cpp
3a246a15b2dab2451bc59f6a2f0c171e0bb36813
[]
no_license
yehaolan/CSC-5
1e99c85a342700cb80749d59ba5d8298fa0c1a48
a24da1ae8e2de9a6690870fb85274c579dc4486d
refs/heads/master
2021-05-29T04:24:41.417318
2015-02-12T16:57:07
2015-02-12T16:57:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
409
cpp
main.cpp
/* * File: main.cpp * Author: Haolan Ye(Benjamin) * Created on January 7, 2015, 7:28 AM * Purpose: set up homework */ //System Libraries #include <iostream> using namespace std; //User Libraries //Global Constants //Function Prototypes //Execution begins here int main(int argc, char** argv) { //Output Hello World cout << "Hello World!" << endl; //Exit stage right! return 0; }
51b386ed2ef88c475f58419ada8c03a560a18187
618734c07c3cd262c67bd54d7f10e70c32545ad7
/Source/SphereCollider.hpp
1114cfd4fbc075068003d51cc676ea94328cd550
[]
no_license
Caspila/GUInity
c9e97ed2e0ad4c9c9a9afb3b036cdef2ac4ad204
0fe75e767fd0913ebb00f76afd3d181caa215efd
refs/heads/master
2021-01-22T07:32:47.297635
2015-07-13T07:46:38
2015-07-13T07:46:38
28,250,903
2
3
null
null
null
null
UTF-8
C++
false
false
1,612
hpp
SphereCollider.hpp
#pragma once #include "Collider.hpp" /** SphereCollider uses a sphere as the volume collider. Can either be real physics simulated or trigger only. */ class SphereCollider : public Collider #ifdef GUINITY_DEBUG , public StaticCounter<SphereCollider> #endif { private: /** The radius of the Sphere */ float radius; public: /** Default Constructor*/ SphereCollider(); /** Deserialization Constructor*/ SphereCollider(float radius, PxVec3 center); /** Default Destructor*/ virtual ~SphereCollider(); /** radius Getter @return radius of the sphere */ float getRadius() const; /** radius Setter @param [in] newRadius the radius of the sphere */ void setRadius(float newRadius); /** Init component override. Create a new Sphere Shape in the PhysX scene. */ virtual void init(); /** Clones current component (Prototype Design Pattern) @return shared_ptr to cloned SphereCollider Component */ virtual shared_ptr<Component> clone() override; /** Looks for a MeshComponent and gets the extent for the collider */ virtual void recalculateBounds() override; /** @defgroup serialization_functions Serialization Functions * Serialization Region * @{ */ #pragma region Serialization Functions /** Creates a description for the Component*/ virtual shared_ptr<ComponentDescription> getComponentDescription() override; /** Deserializes a description to a Component */ virtual void deserialize(shared_ptr<ComponentDescription> desc) override; #pragma endregion /** @} */ // end of serialization_functions };
7b129f7acff7214e8e6f9fb85775be4a0e4d7cde
2359c13c2b34b91518cceb23dc340dcfdbe4018c
/Source/FirstProjcet/MyGameMode.cpp
26333547511a42b2cfd67653443636181a45924b
[]
no_license
3Hoo/G_UnrealEngine_FirstC--BasedGameProject
d87a0252e34aa4254ad7fe70cb347cf59643851c
905e6224ca30785d359d44683d16a1fe878953e6
refs/heads/master
2023-09-03T00:09:12.041009
2021-11-18T07:26:27
2021-11-18T07:26:27
429,303,761
0
0
null
null
null
null
UTF-8
C++
false
false
365
cpp
MyGameMode.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "MyGameMode.h" #include "Main.h" #include "MainPlayerController.h" bool AMyGameMode::GetIsFirst() { UE_LOG(LogTemp, Warning, TEXT("GetIsFirst()")); return bIsFirst; } void AMyGameMode::SetIsFirst(bool B) { UE_LOG(LogTemp, Warning, TEXT("SetIsFirst()")); bIsFirst = B; }
4304945352942aa6096588eed7e7ac91e2866cb8
0d22d93a5876608c173d550c75808c7208f99072
/Physics.cpp
fbb0742980d27b732958d5888233688d71e57d3e
[]
no_license
Percevase/Rampage
b43a8503add12983dffd325f9269eea16a17f4e0
df31dda55e7ea0bf900777b0fd510c678f17b31d
refs/heads/master
2020-03-14T08:58:36.334412
2018-05-04T20:35:44
2018-05-04T20:35:44
131,536,318
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
Physics.cpp
#include <ctime> #include <cmath> #include "Physics.h" using namespace std; using namespace nsGamePhysics; double nsGamePhysics::freeFallEquation(const double &speed0) { const double t0 = time(NULL); double t = difftime(t0, time(NULL)); return (-0.5) * g * pow(t, 2) + speed0 * t; }
51fc161d70c00775b7c370a02decf2d861ca9112
ba86aa615a1455fd79ac3732b77d07f935a04ae3
/c++程序/MP.cpp
8010703672667d878a3b8ac6488b32297a0a3c40
[]
no_license
300I/jjj
ce0c64bd3a535e593ec38f8b498b77e5ec71e334
942c708fc5994ae75cf96e254dac00ba00b94e88
refs/heads/master
2020-07-10T01:20:30.600985
2019-09-16T12:50:09
2019-09-16T12:50:09
204,130,261
1
0
null
null
null
null
UTF-8
C++
false
false
362
cpp
MP.cpp
#include<iostream> #include<cstdio> #include<iomanip> #include<cstring> #include<cmath> using namespace std; const int n=10; int a[n+1]; int main() { for(int i=1;i<=n;i++)cin>>a[i]; for(int i=1;i<=n-1;++i) for(int j=1;j<=n-i;++j) if(a[j]<a[j+1])swap(a[j],a[j+1]); for(int i=1;i<=n;++i)cout<<" "<<a[i]; cout<<endl; return 0; }//i
6acb19b93b3d9f1e428ce2846d60d130b49a9b2a
6b1b0a8aa3db4558327e3e07abc4e72faab35634
/inc/ralloc.hpp
4798c7264e429aca0a3f635f28b0f553cd260e4f
[]
no_license
nmosier/zc
70952dbad5c1699a99d0d327332e34345e4f1381
42605341dec6a88343269557aaac6d1fa21b8e24
refs/heads/master
2020-11-27T14:26:07.553541
2020-02-10T12:45:11
2020-02-10T12:45:11
229,485,843
0
0
null
null
null
null
UTF-8
C++
false
false
6,729
hpp
ralloc.hpp
#ifndef __RALLOC_HPP #define __RALLOC_HPP #include <unordered_map> #include <unordered_set> #include <list> #include <ostream> #include <iterator> #include "asm.hpp" namespace zc::z80 { struct RallocInterval; } namespace std { } namespace zc::z80 { /** * Check whether iterator comes before another iterator. */ bool before(Instructions::const_iterator lhs, Instructions::const_iterator rhs, Instructions::const_iterator end); /** * Interval as used in representing a variable lifetime or when a register is free. */ struct RallocInterval { Instructions::iterator begin; Instructions::iterator end; int length() const { return std::distance(begin, end); } bool operator<(const RallocInterval& other) const; bool in(const RallocInterval& other) const; /* NOTE: Checks for exclusive intersection, i.e. overlap without containment. */ bool intersects(const RallocInterval& other) const; void Merge(const RallocInterval& with) { Merge(with, *this); } void Merge(const RallocInterval& with, RallocInterval& out) const; void Dump(std::ostream& os, Instructions::iterator instrs_begin) const { os << "[" << std::distance(instrs_begin, begin) << "," << std::distance(instrs_begin, end) << "]"; } RallocInterval(Instructions::iterator begin, Instructions::iterator end): begin(begin), end(end) {} RallocInterval() {} }; #if 0 class RallocIntervals { public: typedef std::multiset<RallocInterval>::iterator iterator; typedef std::multiset<RallocInterval>::const_iterator const_iterator; iterator begin() { return intervals_.begin(); } const_iterator begin() const { return intervals_.begin(); } iterator end() { return intervals_.end(); } const_iterator end() const { return intervals_.end(); } private: std::multiset<RallocInterval> intervals_; }; typedef std::multiset<RallocInterval> RallocIntervals; #else typedef std::list<RallocInterval> RallocIntervals; #endif class NestedRallocIntervals { public: bool try_add(const RallocInterval& interval); protected: RallocIntervals intervals_; }; enum class AllocKind {ALLOC_NONE, ALLOC_REG, ALLOC_STACK, ALLOC_FRAME}; std::ostream& operator<<(std::ostream& os, AllocKind kind); /** * Variable info for the register allocator. */ struct VariableRallocInfo { const VariableValue *var; const Value *allocated_val = nullptr; Instructions::iterator gen; /*!< where the variable is assigned (i.e. generated) */ std::list<Instructions::iterator> uses; /*!< the instructions in which the variable is used */ RallocInterval interval; AllocKind alloc_kind = AllocKind::ALLOC_NONE; void AssignVal(const Value *val); bool requires_reg() const; bool is_stack_spillable() const; void StackSpill(Instructions& instrs); void FrameSpill(StackFrame& frame); /** * Check if variable is joinable with next variable. * @return variable to join; nullptr if no join was possible. */ const VariableValue *joinable(); void Dump(std::ostream& os, Instructions::iterator instrs_begin) const; VariableRallocInfo(const VariableValue *var, Instructions::iterator gen): var(var), gen(gen), interval(gen, gen) {} VariableRallocInfo(const VariableValue *var, Instructions::iterator gen, const RallocInterval& interval): var(var), gen(gen), interval(interval) {} /** * Priority number when scheduling allocations. Higher number means higher priority. * Positive values for those that require registers; negative values for those that don't.xs */ double priority() const { double base = (uses.size() + 1) / (interval.length() + 1); if (requires_reg()) { return base; } else { return -1/base; } } }; /** * Register free intervals. */ struct RegisterFreeIntervals { RallocIntervals intervals; RallocIntervals::iterator superinterval(const RallocInterval& subinterval); void remove_interval(const RallocInterval& interval); void Dump(std::ostream& os, Instructions::iterator instrs_begin) const; RegisterFreeIntervals(const RallocIntervals& intervals): intervals(intervals) {} }; /** * Block register allocator. */ class RegisterAllocator { public: Block *block() const { return block_; } void ComputeIntervals(); void RunAllocation(); void Dump(std::ostream& os) const; RegisterAllocator(Block *block, StackFrame& stack_frame): block_(block), stack_frame_(stack_frame) {} static void Ralloc(FunctionImpl& impl, StackFrame& stack_frame); static void Ralloc(CgenEnv& env); protected: Block *block_; /*!< block containing instructions. */ StackFrame& stack_frame_; /*!< stack frame for spilling locals. */ typedef std::unordered_map<int, VariableRallocInfo> Vars; Vars vars_; /*!< map from variable ID to register allocation information */ typedef std::unordered_map<const ByteRegister *, RegisterFreeIntervals> Regs; Regs regs_; NestedRallocIntervals stack_spills_; /*!< intervals on which vars are stack-spilled */ AllocKind AllocateVar(const VariableValue *var); /** * Try to allocate register to variable. * @param var variable to allocate to * @return whether allocation was successful */ bool TryRegAllocVar(const VariableValue *var); /** * Get registers that can be assigned to given variable. * @tparam output iterator to byte register * @param var variable * @param out output list of registers */ void GetAssignableRegs(const VariableValue *var, std::unordered_set<const Register *>& out) const; /** * Try to assign register to variable. * @param varinfo variable info * @return whether a register was assigned */ bool TryAssignReg(VariableRallocInfo& varinfo); /** * Join variables. * @param first first variable to appear. The second variable will be joined into this one. * @param second second variable to appear. After joining, this one disappears. */ void JoinVar(const VariableValue *first, const VariableValue *second); void JoinVars(); static void RallocBlock(Block *block, StackFrame& stack_frame); }; } #endif
3ce4e8c4c64c7e017933701495387b96306e6e56
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/EventFilter/CSCRawToDigi/src/CSCTMBTrailer.cc
187a8f8d95aa62b73960fd251eb1fd61edc8bf44
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
2,368
cc
CSCTMBTrailer.cc
#include "EventFilter/CSCRawToDigi/interface/CSCTMBTrailer.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <iostream> #include <cassert> CSCTMBTrailer::CSCTMBTrailer(int wordCount, int firmwareVersion) : theFirmwareVersion(firmwareVersion) { //FIXME do firmware version theData[0] = 0x6e0c; // all the necessary lines from this thing first wordCount += 5; // see if we need thePadding to make a multiple of 4 thePadding = 0; if (wordCount % 4 == 2) { theData[1] = 0x2AAA; theData[2] = 0x5555; thePadding = 2; wordCount += thePadding; } // the next four words start with 11011, or a D for (int i = 1; i < 5; ++i) { theData[i + thePadding] = 0xD800; } theData[de0fOffset()] = 0xde0f; // word count excludes the trailer theData[4 + thePadding] |= wordCount; } CSCTMBTrailer::CSCTMBTrailer(const uint16_t* buf, unsigned short int firmwareVersion) : theFirmwareVersion(firmwareVersion) { // take a little too much, maybe memcpy(theData, buf, 14); switch (firmwareVersion) { case 2006: // if there's padding, there'll be a de0f in the 6th word. // If not, you'll be in CFEB-land, where they won't be de0f. thePadding = (theData[5] == 0xde0f ? 2 : 0); break; case 2007: ///in 2007 format de0f line moved // =VB= check for 1st word to be 0xDE0F, then check 3rd // to handle freaky cases of double 0xDE0F signatures in trailer thePadding = (theData[1] == 0xde0f ? 0 : (theData[3] == 0xde0f ? 2 : 0)); // thePadding = (theData[3] == 0xde0f ? 2 : 0); break; default: edm::LogError("CSCTMBTrailer|CSCRawToDigi") << "failed to contruct: firmware version is bad/not defined!"; } } unsigned int CSCTMBTrailer::crc22() const { return (theData[crcOffset()] & 0x07ff) + ((theData[crcOffset() + 1] & 0x07ff) << 11); } void CSCTMBTrailer::setCRC(int crc) { theData[crcOffset()] |= (crc & 0x07ff); theData[crcOffset() + 1] |= ((crc >> 11) & 0x07ff); } int CSCTMBTrailer::wordCount() const { return theData[4 + thePadding] & 0x7ff; } void CSCTMBTrailer::selfTest() { CSCTMBTrailer trailer(104, 2006); unsigned int crc = 0xb00b1; trailer.setCRC(crc); assert(trailer.crc22() == 0xb00b1); CSCTMBTrailer trailer2(104, 2007); crc = 0xb00b1; trailer2.setCRC(crc); assert(trailer2.crc22() == 0xb00b1); }
40274bd30271fd66da2b8d42b351cd721f631586
d9756b2d68edd109f1ea0a7535f1865769f4994a
/src/streamrenderwin.h
d29a73143bd6ce9b5fae7345fe9f5519537f5bca
[]
no_license
somaproject/streams
509362c9d88d608e429de225b785937a34984e87
9fed8ddb3b519a00fd8761a2382e11023ccf5186
refs/heads/master
2021-01-11T11:16:27.971865
2009-11-30T02:51:33
2009-11-30T02:51:33
100,223
1
0
null
null
null
null
UTF-8
C++
false
false
2,423
h
streamrenderwin.h
#ifndef STREAMRENDERWIN_H #define STREAMRENDERWIN_H #include <iostream> #include <cstdlib> #include <cmath> #include <assert.h> #include <stdlib.h> #include <gtkmm.h> #define GL_GLEXT_PROTOTYPES #include <gtkglmm.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glext.h> #include "glconfig.h" #include "glspikes.h" #include <elements/property.h> #include "viscontrol.h" #include <cairogltext/glstring.h> enum ViewTypes {OVERWRITE, STRIPCHART, MANUAL}; class StreamRenderWin : public Gtk::GL::DrawingArea { /* StreamRenderWin has a viewT1 and a viewT2 which define the time window we are looking at in streamtimes. However, we are actually always plotting openGL starting with 0. */ public: explicit StreamRenderWin(pVisControl_t pvc); virtual ~StreamRenderWin(); // Invalidate whole window. void inv(); // Update window synchronously (fast). void update() { get_window()->process_updates(false); } elements::Property<bool> trackLive; void invalidate(); void invalidate2(); void setCurrentTime(streamtime_t time); void setViewType(ViewTypes val); protected: // signal handlers: virtual void on_realize(); virtual bool on_configure_event(GdkEventConfigure* event); virtual bool on_expose_event(GdkEventExpose* event); virtual bool on_map_event(GdkEventAny* event); virtual bool on_unmap_event(GdkEventAny* event); virtual bool on_visibility_notify_event(GdkEventVisibility* event); virtual bool on_button_press_event(GdkEventButton* event); virtual bool on_button_release_event(GdkEventButton* event); bool on_motion_notify_event(GdkEventMotion* event); bool on_scroll_event(GdkEventScroll* event); void updateViewingWindow(bool reset); void setZoom(float zoomval, float tcenter); void renderTimeTicks(float T1, float T2); void setSelectionRegion(float t1, float t2); void renderCurrentTimeCursor(); bool invalidateCallback(); // primary data source // state variables int lastX_; int decayRange_; int cutoffPos_; float viewT1_, viewT2_, viewX1_, viewX2_; float selT1_, selT2_; float zoomLevel_; int s1fact_; ViewTypes viewType_; pVisControl_t pVisControl_; float currentTime_; // font-associated crap GLuint fontListBase_; int fontHeight_; GLString timeGLstring_; }; #endif //STREAMRENDERWIN_H
11d460f95ea45c8fcbfeb750283993f82ccebd06
c0864b9e6ed699d173c268ee1ad50f59e61c69f1
/bus.cpp
3b522604d4e3a81913d9fec935729ea208527b35
[]
no_license
palelile/AsistenciaBus
e3718f7447e06670663d476840244e77d8dd7d01
341ab7b4dfd7ae0bf399379101f1f94ac8d7ebc2
refs/heads/master
2021-10-09T12:48:47.906322
2013-04-15T21:40:29
2013-04-15T21:40:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,521
cpp
bus.cpp
#include "bus.h" #include "ui_bus.h" Bus::Bus(QWidget *parent) : QMainWindow(parent), ui(new Ui::Bus) { QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8")); ui->setupUi(this); connect(ui->toolBox, SIGNAL(currentChanged(int)), this, SLOT(cambioDePagina(int))); connect(ui->bot_imp_txt, SIGNAL(pressed()), this, SLOT(importar_Sige()) ); cargarOpciones(); this->showMaximized(); ui->toolBox->setCurrentIndex(0); ui->asistenciaRut->setFocus(); db_local = new dbLocal(); } Bus::~Bus() { guardarOpciones(); delete ui; } /******************************************************************************* * Funciones administrativas ******************************************************************************/ // Intercambio de áreas de trabajo void Bus::cambioDePagina(int pagina){ switch (pagina) { case 0: // Agregar asistencia ui->asistenciaRut->setFocus(); break; case 1: ui->rutasRutaNueva->setFocus(); break; case 2: ui->autorizarIngresarRut->setFocus(); break; case 3: { ui->reporteFin->setDate(QDate::currentDate()); ui->reporteInicio->setDate(QDate::currentDate()); } break; case 4: { ui->progressBar->setVisible(false); ui->syncButton->setFocus(); } break; default: break; } } /******************************************************************************* * Página 0: Agregar asistencia ******************************************************************************/ // Valida si el rut es candidato para la asistencia, si es así, lo ingresa a la // DB. bool Bus::agregarAsistencia() { QString rut = ui->asistenciaRut->text(); limpiarAsistencia(); bool estado = false; if ( ! db_local->validarRut( rut ) ) { mensajeAsistencia(1, ""); // Rut no existe en registro return estado; } if ( ! db_local->validarAutorizacion( rut ) ) { mensajeAsistencia(2, db_local->infoRut( rut )); // Alumno no autorizado a viajar return estado; } if ( esViajeManana( ) ){ estado = db_local->almacenarRegistro(rut, 1); mensajeAsistencia(3, db_local->infoRut( rut )); } else { estado = db_local->almacenarRegistro(rut, 2); mensajeAsistencia(4, db_local->infoRut( rut )); } return estado; } // Limpia la ventana de asistencia. void Bus::limpiarAsistencia() { ui->asistenciaRut->setText(""); ui->asistenciaRut->setFocus(); } // Mensaje de información de error por ventana void Bus::mensajeAsistencia(int opcion, QString alumno) { QString mensaje = ""; switch (opcion) { case 1: mensaje = "RUT no pertenece a ningún alumno"; break; case 2: mensaje = alumno + "<br />no ha sido autorizado a viajar."; break; case 3: mensaje = alumno + "<br />ha iniciado el día."; break; case 4: mensaje = alumno + "<br />ha finalizado el día."; break; default: mensaje = "Error sin definir."; break; } ui->asistenciaInfo->setText(mensaje); ui->asistenciaInfo->setStyleSheet("font-size : 26px; background-color : #BC3A00; color : #FFFFFF;"); } /******************************************************************************* * Página 1: Agregar ruta ******************************************************************************/ // Agrega una nueva ruta al listado de rutas void Bus::agregarRuta() { if ( ui->rutasRutaNueva->text().compare("") != 0 ){ db_local->agregarRutaEnDb(ui->rutasRuta->count(), ui->rutasRutaNueva->text()); ui->rutasRuta->addItem( ui->rutasRutaNueva->text() ); ui->autorizarRuta->addItem( ui->rutasRutaNueva->text() ); } ui->rutasRutaNueva->setText(NULL); } /******************************************************************************* * Página 2: Autorizar usuarios en ruta ******************************************************************************/ void Bus::autorizar() { int mensaje = db_local->autorizarRut( ui->autorizarIngresarRut->text(), ui->autorizarRuta->currentIndex() ); mensajeErrorAutorizar(mensaje, db_local->infoRut( ui->autorizarIngresarRut->text() )); limpiarAutorizacion(); } void Bus::desautorizar() { int mensaje = db_local->desAutorizarRut( ui->autorizarRemoverRut->text() ); mensajeErrorAutorizar(mensaje, db_local->infoRut( ui->autorizarRemoverRut->text() )); limpiarDesAutorizacion(); } // Mensaje de información de error por ventana void Bus::mensajeErrorAutorizar(int opcion, QString alumno) { QString mensaje = ""; switch (opcion) { case 1: mensaje = "RUT no pertenece a ningún alumno"; break; case 2: mensaje = alumno + ",<br /> ya autorizado a viajar, se ha asignado la nueva ruta."; break; case 3: mensaje = alumno + ",<br /> no posee autorización previa."; break; default: mensaje = "Error sin definir."; break; } ui->autorizarInfo->setText(mensaje); ui->autorizarInfo->setStyleSheet("font-size : 26px; background-color : #BC3A00; color : #FFFFFF;"); } void Bus::limpiarAutorizacion(){ ui->autorizarIngresarRut->setText(NULL); ui->autorizarIngresarRut->setFocus(); } void Bus::limpiarDesAutorizacion(){ ui->autorizarRemoverRut->setText(NULL); ui->autorizarRemoverRut->setFocus(); } /******************************************************************************* * Página 3: Reportes ******************************************************************************/ void Bus::poblarTabla() { int indice = ui->reporteOpcion->currentIndex(); QStringList labels; int nAlumnos = 0; int columnas = 0; QList<QString*> alumnos = db_local->generarReporte( &nAlumnos, indice, &columnas, ui->reporteInicio->date(), ui->reporteFin->date() ); switch (indice){ case 0: // Asistencia por ruta «mañana» labels << "Fecha" << "Ruta" << "Asistencia mañana"; break; case 1: // Asistencia por ruta «tarde» labels << "Fecha" << "Ruta" << "Asistencia tarde"; break; case 2: // Asistencia por alumno «mañana» labels << "Curso" << "Nombre" << "Apellido Paterno" << "Apellido Materno" << "Asistencia mañana"; break; case 3: // Asistencia por alumno «tarde» labels << "Curso" << "Nombre" << "Apellido Paterno" << "Apellido Materno" << "Asistencia tarde"; break; case 4: // Inasistencia del dia «mañana» labels << "Ruta" << "Curso" << "Alumnos"; break; case 5: // Inasistencia del dia «tarde» labels << "Ruta" << "Curso" << "Alumnos"; break; } ui->tablaReporte->setColumnCount(columnas); ui->tablaReporte->setHorizontalHeaderLabels(labels); ui->tablaReporte->verticalHeader()->hide(); ui->tablaReporte->setShowGrid(false); for (int i=0; ui->tablaReporte->rowCount() > 0; i++) ui->tablaReporte->removeRow(0); for (int i=0; i< nAlumnos; i++){ int row = ui->tablaReporte->rowCount(); ui->tablaReporte->insertRow( row ); for (int j=0; j< columnas;j++) ui->tablaReporte->setItem(row, j, new QTableWidgetItem(alumnos[i][j], 0)); } ui->tablaReporte->horizontalHeader()->setResizeMode(QHeaderView::Stretch); } void Bus::GuardarReporte() { int tipo_reporte = ui->reporteOpcion->currentIndex(); QString documento_cadena; QTextStream documento_html(&documento_cadena); documento_html.setCodec("UTF-8"); QTableWidget * tabla = ui->tablaReporte; const int cantidad_filas = tabla->model()->rowCount(); const int cantidad_columnas = tabla->model()->columnCount(); documento_html << "<html>\n"; documento_html << "<head>\n"; documento_html << "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n"; documento_html << "<style type=\"text/css\">*{font-size: 9px;}table{margin: 5px;}td { padding: 3px; text-align: right;}th { padding: 5px; text-align: center;}</style>"; documento_html << "</head>\n"; documento_html << "<body>\n<center>"; switch ( tipo_reporte ) { case 0: documento_html << QString("<h1>Reporte de asistencia por ruta «mañana»</h1>"); break; case 1: documento_html << QString("<h1>Reporte de asistencia por ruta «tarde»</h1>"); break; case 2: documento_html << QString("<h1>Reporte de asistencia por alumno «mañana»</h1>"); break; case 3: documento_html << QString("<h1>Reporte de asistencia por alumno «tarde»</h1>"); break; case 4: documento_html << QString("<h1>Reporte de inasistencias «mañana»</h1>"); break; case 5: documento_html << QString("<h1>Reporte de inasistencias «tarde»</h1>"); break; } documento_html << QString("<p>Fecha inicio: %1<br />").arg(ui->reporteInicio->date().toString("dd.MM.yyyy")); documento_html << QString("Fecha fin: %1<br />").arg(ui->reporteFin->date().toString("dd.MM.yyyy")); documento_html<< "<table style=\"padding:5px;\">\n"; // headers documento_html << "<tr>"; for (int columna = 0; columna < cantidad_columnas; columna++) if (!tabla->isColumnHidden(columna)) documento_html << QString("<th>%1</th>").arg(tabla->model()->headerData(columna, Qt::Horizontal).toString()); documento_html << "</tr>\n"; // data table for (int fila = 0; fila < cantidad_filas; fila++) { documento_html << "<tr>"; for (int columna = 0; columna < cantidad_columnas; columna++) { if (!tabla->isColumnHidden(columna)) { QString data = tabla->model()->data(tabla->model()->index(fila, columna)).toString().simplified(); documento_html << QString("<td>%1</td>").arg((!data.isEmpty()) ? data : QString("&nbsp;")); } } documento_html << "</tr>\n"; } QTextDocument *documento = new QTextDocument(); documento->setHtml(documento_cadena); QPrinter printer; QString s = QFileDialog::getSaveFileName( this, "Elija el archivo donde se guardará el documento", "", "Archivo PDF (*.pdf)" ); if (s.isEmpty()) return; printer.setOutputFileName( s ); printer.setPageSize(QPrinter::Letter); printer.setPaperSize(QPrinter::Letter); printer.setFullPage( false ); printer.setPageMargins(20,20,20,20,QPrinter::Millimeter); printer.setOutputFormat( QPrinter::PdfFormat ); documento->print(&printer); delete documento; } void Bus::ImprimirReporte() { int tipo = ui->reporteOpcion->currentIndex(); QString strStream; QTextStream documento_html(&strStream); documento_html.setCodec("UTF-8"); QTableWidget * tabla = ui->tablaReporte; const int rowCount = tabla->model()->rowCount(); const int columnCount = tabla->model()->columnCount(); documento_html << "<html>\n"; documento_html << "<head>\n"; documento_html << "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n"; documento_html << "<style type=\"text/css\">*{font-size: 9px;}table{margin: 5px;}td { padding: 3px; text-align: right;}th { padding: 5px; text-align: center;}</style>"; documento_html<< "</head>\n"; documento_html<< "<body>\n"; switch ( tipo ) { case 0: documento_html << QString("<h1>Reporte de asistencia por ruta «mañana»</h1>"); break; case 1: documento_html << QString("<h1>Reporte de asistencia por ruta «tarde»</h1>"); break; case 2: documento_html << QString("<h1>Reporte de asistencia por alumno «mañana»</h1>"); break; case 3: documento_html << QString("<h1>Reporte de asistencia por alumno «tarde»</h1>"); break; case 4: documento_html << QString("<h1>Reporte de inasistencias «mañana»</h1>"); break; case 5: documento_html << QString("<h1>Reporte de inasistencias «tarde»</h1>"); break; } documento_html << QString("<p>Fecha inicio: %1<br />").arg(ui->reporteInicio->date().toString("dd.MM.yyyy")); documento_html << QString("<p>Fecha fin: %1<br />").arg(ui->reporteFin->date().toString("dd.MM.yyyy")); documento_html<< "<table style=\"padding:5px;\">\n"; // headers documento_html << "<tr>"; for (int column = 0; column < columnCount; column++) if (!tabla->isColumnHidden(column)) documento_html << QString("<th>%1</th>").arg(tabla->model()->headerData(column, Qt::Horizontal).toString()); documento_html << "</tr>\n"; // data table for (int row = 0; row < rowCount; row++) { documento_html << "<tr>"; for (int column = 0; column < columnCount; column++) { if (!tabla->isColumnHidden(column)) { QString data = tabla->model()->data(tabla->model()->index(row, column)).toString().simplified(); documento_html << QString("<td>%1</td>").arg((!data.isEmpty()) ? data : QString("&nbsp;")); } } documento_html << "</tr>\n"; } documento_html << "</table>\n" << "</body>\n" << "</html>\n"; QTextDocument *document = new QTextDocument(); document->setHtml(strStream); QPrinter printer; printer.setPageSize(QPrinter::Letter); printer.setPaperSize(QPrinter::Letter); printer.setPageMargins(20,20,20,20,QPrinter::Millimeter); QPrintDialog *dialog = new QPrintDialog(&printer, NULL); if (dialog->exec() == QDialog::Accepted) { document->print(&printer); } delete document; } /******************************************************************************* * Funciones de importación y sincronización de datos ******************************************************************************/ void Bus::sincronizarDBs() { dbSync sync; sync.sincronizarDB(); } void Bus::importar_Sige() { QString archivo = QFileDialog::getOpenFileName( this, "Abrir archivo", QDir::currentPath(), "Archivo TXT de SIGE (*.txt)" ); if( archivo.isNull() ) return; else { csv_lector csv; csv.leer_archivo_db( archivo, db_local ); } } /******************************************************************************* * Permanencia de opciones ******************************************************************************/ // Guarda las opciones del programa de forma permanente void Bus::guardarOpciones() { QSettings opciones(QSettings::IniFormat, QSettings::UserScope, "Ashtaroth", "AsistenciaBus"); QStringList rutas; int fin = ui->rutasRuta->count(); for(int index = 0; index < fin; index++) rutas.append( ui->rutasRuta->itemText(index) ); opciones.setValue("rutas", rutas); QString archivo = opciones.fileName(); opciones.beginGroup("DB"); opciones.setValue("Direccion", ui->syncDireccion->text()); opciones.setValue("Puerto", ui->syncPuerto->text()); opciones.setValue("DB", ui->syncDb->text()); opciones.setValue("Usuario", ui->syncUsuario->text()); opciones.setValue("Password", ui->syncPassword->text()); opciones.endGroup(); } // Carga las opciones del programa void Bus::cargarOpciones(){ QSettings opciones(QSettings::IniFormat, QSettings::UserScope, "Ashtaroth", "AsistenciaBus"); ui->rutasRuta->addItems( opciones.value("rutas").toStringList() ); ui->autorizarRuta->addItems( opciones.value("rutas").toStringList() ); opciones.beginGroup("DB"); ui->syncDireccion->setText( opciones.value("Direccion").toString() ); ui->syncPuerto->setText( opciones.value("Puerto").toString() ); ui->syncDb->setText( opciones.value("DB").toString() ); ui->syncUsuario->setText( opciones.value("Usuario").toString() ); ui->syncPassword->setText( opciones.value("Password").toString() ); opciones.endGroup(); } /******************************************************************************* * Funciones de asistencia ******************************************************************************/ // Indica si es un viaje de mañana o tarde usando como referencia la hora del sistema bool Bus::esViajeManana( ) { QTime hora_mediodia; hora_mediodia.setHMS(12, 00, 00, 00); if ( QTime::currentTime() < hora_mediodia ) return true; return false; }
c30480a43d33f62e2bdfaba19b15e5cf7e3ff5cb
7346bdce9499f829df6a012a3a0ae1812fce1439
/SpreadsheetsWithUnreal/Source/SpreadsheetsWithUnreal/Private/SpreadsheetsHttp.cpp
9bf77fbf5a1a94558235c23f64a201998e02275b
[ "MIT" ]
permissive
jenspetter/SpreadsheetsWithUnreal
4119f6a08bdfdd3f5165676c0e48b0106005b3d5
9c6c0fcce46811ec541fd1aca52353995778dd18
refs/heads/main
2023-05-14T21:44:17.019206
2021-06-06T09:59:49
2021-06-06T09:59:49
319,257,158
0
0
null
null
null
null
UTF-8
C++
false
false
4,265
cpp
SpreadsheetsHttp.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "SpreadsheetsHttp.h" #include "Http.h" #include "HttpModule.h" #include "Interfaces/IPluginManager.h" #include "SpreadsheetsWithUnrealBPLibrary.h" void FSpreadsheetsHttp::SendRequest(const FSpreadsheetCrendentials Credentials, const FString Url, const TEnumAsByte<ERequestType> HttpRequestType, const TEnumAsByte<EReadWriteType> SpreadsheetRequestType, const FString Body) { const FString tokenUrl = SetupTokenRequest(Credentials); TSharedRef<IHttpRequest> tokenRequest = FHttpModule::Get().CreateRequest(); FHttpRequestCompleteDelegate& tokenDelegate = tokenRequest->OnProcessRequestComplete(); tokenDelegate.BindLambda([&, Url, HttpRequestType, SpreadsheetRequestType, Body](FHttpRequestPtr request, FHttpResponsePtr response, bool success) { TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject()); const TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(*response->GetContentAsString()); if (FJsonSerializer::Deserialize(JsonReader, JsonObject) && JsonObject.IsValid()) { const FString accessToken = JsonObject->GetStringField("access_token"); const FString extendedUrl = Url + accessToken; TSharedRef<IHttpRequest> Request = FHttpModule::Get().CreateRequest(); FHttpRequestCompleteDelegate& del = Request->OnProcessRequestComplete(); switch (SpreadsheetRequestType) { case EReadWriteType::ReadCell: del.BindStatic(&USpreadsheetReadWrite::OnRequestReadCellFinished); break; case EReadWriteType::ReadRange: del.BindStatic(&USpreadsheetReadWrite::OnRequestReadRangeFinished); break; case EReadWriteType::WriteToCell: del.BindStatic(&USpreadsheetReadWrite::OnRequestWriteToCellFinished); break; case EReadWriteType::WriteToRange: del.BindStatic(&USpreadsheetReadWrite::OnRequestWriteToRangeFinished); break; case EReadWriteType::AppendToTable: //Setting content type header purely for appending since that is treated as as a //streamed http request Request->SetHeader("Content-Type", "application/json"); del.BindStatic(&USpreadsheetReadWrite::OnRequestAppendToTableFinished); break; case EReadWriteType::ClearCell: del.BindStatic(&USpreadsheetReadWrite::OnRequestClearCellFinished); break; case EReadWriteType::ClearRange: del.BindStatic(&USpreadsheetReadWrite::OnRequestClearRangeFinished); break; case EReadWriteType::Export: del.BindStatic(&USpreadsheetReadWrite::OnRequestExportFinished); break; } Request->SetURL(extendedUrl); switch (HttpRequestType) { case ERequestType::Get: Request->SetVerb("GET"); break; case ERequestType::Put: Request->SetVerb("PUT"); Request->SetContentAsString(Body); break; case ERequestType::Post: Request->SetVerb("POST"); Request->SetContentAsString(Body); break; } Request->ProcessRequest(); } }); tokenRequest->SetURL(tokenUrl); tokenRequest->SetVerb("POST"); tokenRequest->ProcessRequest(); } FString FSpreadsheetsHttp::SetupTokenRequest(const FSpreadsheetCrendentials Credentials) { ///Get file path and load into string const FString filePath = FPaths::ProjectContentDir() + FString("/") + Credentials.PathToOAuthCredentialsFile; FString fileData = ""; FFileHelper::LoadFileToString(fileData, *filePath); FString clientId; FString clientSecret; const FString refreshToken = Credentials.RefreshToken; TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject()); const TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(fileData); // Deserialize content of loaded file if (FJsonSerializer::Deserialize(JsonReader, JsonObject) && JsonObject.IsValid()) { const TSharedPtr<FJsonObject> PersonObject = JsonObject->GetObjectField("web"); // Assigning properties clientId = PersonObject->GetStringField("client_id"); clientSecret = PersonObject->GetStringField("client_secret"); } // Construct Url const FString url = "https://accounts.google.com/o/oauth2/token?client_id=" + clientId + FString("&client_secret=") + clientSecret + FString("&refresh_token=") + refreshToken + FString("&grant_type=refresh_token"); return FString(url); }
a520d2cdff9390c24fa5d716385d9964fe55f9dc
1be562353c54fe742b0b18337e5801fcbbcd576e
/ComputerAssisted Instruction/Functions.cpp
8ed7f1ebdd7d099f6565234e669e2f2d82155ed1
[]
no_license
aahmedramy1/Computer-Assisted-Instruction
cfb28dcae0d75638ed915d5fe204b2ce81ba0955
efff1ab0e99a47a1036ba178a276c66a09545a6d
refs/heads/main
2023-01-10T01:46:04.629051
2020-10-30T15:36:23
2020-10-30T15:36:23
308,672,366
0
0
null
null
null
null
UTF-8
C++
false
false
4,934
cpp
Functions.cpp
// // Functions.cpp // Computer-Assisted Instruction // // Created by Ahmed Ramy on 3/27/20. // Copyright © 2020 Ahmed Ramy. All rights reserved. // #include <iostream> #include <time.h> #include <iomanip> #include "Functions.hpp" using namespace std; int randomNumber(int level) { long srand(time(0)); switch (level) { case 1: return (rand() % 10 ); break; case 2: return (rand() % 100); break; case 3: return (rand() % 1000); break; default: return (rand() % 10 ); break; } } bool round(int first, int second, int problem) // takes in two random number and start a round { int correctAnswer; switch (problem) { case 1: correctAnswer = first + second; break; case 2: correctAnswer = first - second; break; case 3: correctAnswer = multiply(first, second); break; case 4: correctAnswer = first / second; break; default: correctAnswer = first + second; break; } int userAnswer; switch (problem) { case 1: cout << "How much is " << first << " plus " << second << "?"; break; case 2: cout << "How much is " << first << " minus " << second << "?"; break; case 3: cout << "How much is " << first << " time " << second << "?"; break; case 4: cout << "How much is " << first << "divided" << second << "?"; break; default: cout << "How much is " << first << " time " << second << "?"; break; } cin >> userAnswer; return feedback(userAnswer, correctAnswer); } int multiply(int first, int second) // takes in two numbers and multiplies them { return first * second; } bool feedback(int userAnswer, int correctAnswer) { if(userAnswer == correctAnswer) { long srand(time(0)); int correct = (rand() % 4) + 1; switch (correct) { case 1: cout << "Very good!" << endl; break; case 2: cout << "Excellent!" << endl; break; case 3: cout << "Nice work!" << endl; break; case 4: cout << "Keep up the good work" << endl; break; default: cout << "The program should never reach this stage" << endl; break; } return true; } else { long srand(time(0)); int wrong = (rand() % 4) + 1; switch (wrong) { case 1: cout << "No. Please try again." << endl; break; case 2: cout << "Wrong. Try once more" << endl; break; case 3: cout << "Don't give up!" << endl; break; case 4: cout << "No. Keep trying." << endl; break; default: cout << "The program should never reach this stage" << endl; break; } return false; } } void finalResult(double correct, double wrong, double attempts) /* Takes number of correct, wrong answers and returns a feedback to the user */ { cout << setprecision(2) << fixed; double percentage = static_cast<double>(correct / attempts) * 100 ; if (percentage >= 75 ) { scoreBoard(correct, wrong, attempts); cout << "\nCongratulations, you are ready to go to the next level!" << endl; } else { scoreBoard(correct, wrong, attempts); cout << "\nPlease ask your teacher for extra help." << endl; } } void scoreBoard(double correct, double wrong, double attempts) // Show the user The score board { cout << setw(10) << "\n\n\t" << correct << "/" << attempts << endl; cout << "\t" << setprecision(2) << static_cast<double>((correct / attempts) * 100) << "%" << endl; } void restart(double &correct, double &wrong, bool &answer) { correct = 0; wrong = 0; answer = true; } void adjustScore(double &correct, double &wrong, bool answer) { if ( answer == true) { correct += 1; } else { wrong += 1; } } int chooseDifficulty() { int level; cout << "Enter a difficulty level: \n" << "1.Easy\n" << "2.Medium\n" << "3.Hard"; cin >> level; return level; } int chooseProblem() { int arithmeticProblem; cout << "Choose an arithmetic problem to study\n" << "1.Addition\n" << "2.Subtraction\n" << "3.Multiplication\n" << "4.Division"; cin >> arithmeticProblem; return arithmeticProblem; }
39720e9de23dd8470e1a605ba973275971fadd08
ffa2014a838b6c34ca6a79c975c280d17616b3d2
/Graphs/flows/mincost__maximum_bipartite matching.cpp
3a58ad73b49a71c7ac841fbcbb9f994184e2dcd4
[]
no_license
TarunSinghania/Prewritten-code
ada2b9d71b3bd452b5b0583e38c6c1d656529a18
fcb3b951fdf82fa88abeeb7133564515232bfff0
refs/heads/master
2020-12-31T08:46:57.394606
2020-12-26T17:47:52
2020-12-26T17:47:52
238,958,293
2
0
null
null
null
null
UTF-8
C++
false
false
1,716
cpp
mincost__maximum_bipartite matching.cpp
#include <bits/stdc++.h> using namespace std; #define fr(i,a,b) for(int i=a;i<b;i++) #define pb push_back #define speed ios::sync_with_stdio(false), cin.tie(0) , cout.tie(0) #define fillm(m,r,c,k) fr(i,0,r)fr(j,0,c)m[i][j]=k; #define prm(m,r,c) fr(i,0,r){fr(j,0,c){cout<<m[i][j]<<" "; }cout<<endl;} #define pr(a,n)fr(i,0,n)cout<<a[i]<<",";cout<<endl; #define endl '\n' #define MOD 1000000007 #define INF 1000000000 #define prv(v) for(auto x: v)cout<<x<<" ";cout<<endl; #define MAX 400005 #define all(x) x.begin(),x.end() #define mkp make_pair #define ll long long #define f first #define s second int cost[205][410]; void mincost_maxmatching(int n,int m){ vector<int> u (n+1), v (m+1), p (m+1), way (m+1); for (int i=1; i<=n; ++i) { p[0] = i; int j0 = 0; vector<int> minv (m+1, INF); vector<char> used (m+1, false); do { used[j0] = true; int i0 = p[j0], delta = INF, j1; for (int j=1; j<=m; ++j) if (!used[j]) { int cur = cost[i0][j]-u[i0]-v[j]; if (cur < minv[j]) minv[j] = cur, way[j] = j0; if (minv[j] < delta) delta = minv[j], j1 = j; } for (int j=0; j<=m; ++j) if (used[j]) u[p[j]] += delta, v[j] -= delta; else minv[j] -= delta; j0 = j1; } while (p[j0] != 0); do { int j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0); } //who is matched were ? int ans[n+1]; fr(i,1,m+1){ ans[p[i]] = i; } //pr(ans,n+1); //total cost cout<<-v[0]<<endl; } int main(){ speed; int t;cin>>t; while(t--){ int n; cin>>n; int tm[n+1]; fr(i,1,n+1){ cin>>tm[i]; } int m = 2*n+2; fr(i,1,n+1){ fr(j,1,m+1) { cost[i][j] = abs(tm[i]-j); } } mincost_maxmatching(n,m); } return 0; }
5c4eff6c996d2722c7586ab1880ad3b860a3c910
65ab52bbdaffd39544a6cffe2a4f296e5cf2186c
/App.h
0258139dfe4b55566ddd3c5e39bcdadee3e9a716
[]
no_license
Naiztu/proveedora
f589ae20f4acc4a43900c2d6826a134df19abd87
356802be837b562a813171753e2374c1ce098474
refs/heads/main
2023-05-08T22:52:18.223144
2021-06-04T13:05:27
2021-06-04T13:05:27
366,752,747
0
0
null
null
null
null
UTF-8
C++
false
false
16,116
h
App.h
#ifndef APP_H #define APP_H // // // Proyecto Proveedora main // // José Ángel Rico Mendieta // // A01707404 // // 27/05/2021 // // Clase App, tendra todas las funcionalidades para que el programa // sea ejecutada desde el main // // #include "Personal.h" #include "Proveedor.h" #include "Cliente.h" #include "Cajero.h" #include "Producto.h" #include "Subproducto.h" #include "Ticket.h" #include "Factura.h" #include <vector> #include <iostream> using namespace std; class App{ private: vector<Personal*> personal; vector<Producto*> productos; vector<Ticket*> tickets; vector<Factura*> facturas; int numInt=1000; int menu(); void generarEjemplos(); void agregaPersonal(int); void verPersonal(string); void listaPersonal(string); void listaProductos(); void listaTickets(); void listaFacturas(); void venta(int); void agregaProdcuto(); string tipoPer(int); bool validaOpcion(int, int, int); vector<Subproducto> listaSubproductos(); public: App(){} ~App(); void start(); }; App::~App(){ for (Personal *aux : personal) { delete aux; } for (Producto *aux : productos) { delete aux; } for (Ticket *aux : tickets) { delete aux; } for (Factura *aux : facturas) { delete aux; } } /** * star() * * Método que inicializa la ejecución * del programa * @param * @return */ void App::start(){ generarEjemplos(); int op = 0, op2 = 0, op3 = 0; do{ op = menu(); bool ban = true; if ((op>=1)&&(op<=3)){ while (ban){ cout << "\n*******************************************"; cout << "\n Personal:\n"; cout << "*******************************************\n"; cout << "1. Cliente \n"; cout << "2. Proveedor \n"; cout << "3. Cajero \n"; cout << "*******************************************\n"; cout << "\nOpción: "; cin>>op2; ban = validaOpcion(op2,1,3); } } ban = true; cout << "\n*******************************************"; switch(op){ case 1: cout << "\n* Agregar " << tipoPer(op2); cout << "\n*******************************************\n"; agregaPersonal(op2); break; case 2: cout << "\n* Ver " << tipoPer(op2); cout << "\n*******************************************\n"; verPersonal(tipoPer(op2)); break; case 3: cout << "\n* Lista " << tipoPer(op2); cout << "\n*******************************************\n"; listaPersonal(tipoPer(op2)); break; case 4: while (ban){ cout << "\n* Venta:\n"; cout << "*******************************************\n"; cout << "1. Sin Factura\n"; cout << "2. Con Factura \n"; cout << "*******************************************\n"; cout << "\nOpción: "; cin>>op3; ban = validaOpcion(op3,1,2); } venta(op3); break; case 5: cout << "\n* Agregar Producto"; cout << "\n*******************************************\n"; agregaProdcuto(); break; case 6: cout << "\n* Lista Productos"; cout << "\n*******************************************\n"; listaProductos(); break; case 7: cout << "\n* Lista Tickets"; cout << "\n*******************************************\n"; listaTickets(); break; case 8: cout << "\n* Lista Facturas"; cout << "\n*******************************************\n"; listaFacturas(); break; default: cout << "\n* ¡¡¡Adios!!! *"; cout << "\n*******************************************\n"; } }while(op!=9); } /** * agregaProducto() * * Método que agrega un producto al registro. * @param * @return */ void App::agregaProdcuto(){ string nombre; int id; double precio; bool ban = true; cout <<"\nNombre: "; cin >> nombre; cout <<"\nPrecio: $"; cin >> precio; while (ban){ cout << "\nId del Proveedor: "; cin>>id; for (Personal *i : personal){ if ((i->getId()==id)&&(i->getTipo()=="Proveedor")){ productos.push_back(new Producto(productos.size()+numInt, nombre, precio, (Proveedor*)i)); cout << "\n ¡¡¡AGREGADO CON EXITO!!!\n"; ban = false; } } if(ban){ cout << "\n ¡¡¡Introduce una opción valida!!! \n"; } } } /** * venta() * * Método que agrega un ticket sin factura o con factura * @param int op Si es 1, es venta sin factura. Si es 2, * es venta co factura. * @return */ void App::venta(int op){ int idC, id; bool ban=true; switch (op){ case 1: while(ban){ cout << "Id Cajero: "; cin >> idC; for(Personal *i : personal){ if ((i->getTipo()=="Cajero")&&(i->getId()==idC)){ tickets.push_back(new Ticket(tickets.size()+numInt, "03/06/2021", (Cajero*) i, listaSubproductos())); cout << tickets[tickets.size()-1]->printTicket(); cout << "\nNombre\tCantidad\tPrecio\tSubtotal"; for(Subproducto k : tickets[tickets.size()-1]->getLista()){ cout<<k.printSubproducto(); } ban = false; break; } } if(ban){ cout << "\n ¡¡¡Introduce una opción valida!!! \n"; } } break; default: while(ban){ cout << "Id Cajero: "; cin >> idC; for(Personal *i : personal){ if ((i->getTipo()=="Cajero")&&(i->getId()==idC)){ cout << "Id Cliente: "; cin >> id; for(Personal *j : personal){ if ((j->getTipo()=="Cliente")&&(j->getId()==id)){ facturas.push_back(new Factura(facturas.size()+numInt,Ticket(tickets.size()+numInt, "03/06/2021", (Cajero*) i, listaSubproductos()), (Cliente*)j)); cout << facturas[facturas.size()-1]->printFactura(); cout << "\nNombre\tCantidad\tPrecio\tSubtotal"; for(Subproducto k : facturas[facturas.size()-1]->getTicket().getLista()){ cout<<k.printSubproducto(); } ban = false; break; } } } } if(ban){ cout << "\n ¡¡¡Introduce una opción valida!!! \n"; } } break; } cout<<"\n"; } /** * validaOpcion() * * Metodo que valida la opcion escogida este dentro * del rango asignado * @param int op opcion a evaluar * int inf limite inferio * int sup limite superior * @return bool que indicara si ya se cumple la condición */ bool App::validaOpcion(int op,int inf, int sup){ bool ban = true; if ((op>=inf)&&(op<=sup)){ ban = false; }else{ cout << "\n ¡¡¡Introduce una opción valida!!! \n"; } return ban; } /** * tipoPer() * * Método que devuelve el personas escogido * marcado en numero a string * @param int num numero relacion con el tipo * de personal * @return string tipo de personal */ string App::tipoPer(int num){ switch (num){ case 1: return "Cliente"; break; case 2: return "Proveedor"; break; case 3: return "Cajero"; break; default: break; } } /** * menu() * * Método que presenta el menu para despues evaluar * la opción escogida, el cin>>op solo debe ser tecleado * con numero enteros * @param * @return int op opcion elegida por el usuario */ int App::menu(){ bool ban = true; int op=0; while (ban){ cout << "\n*******************************************"; cout << "\n MENU:\n"; cout << "*******************************************\n"; cout << "1. Agregar Personal \n"; cout << "2. Ver Personal \n"; cout << "3. Lista Personal \n"; cout << "4. Hacer Venta (con/sin factura)\n"; cout << "5. Agregar Producto\n"; cout << "6. Lista Productos\n"; cout << "7. Lista Tickets \n"; cout << "8. Lista Facturas \n"; cout << "9. Salir \n"; cout << "*******************************************\n"; cout << "\nOpción: "; cin>>op; ban = validaOpcion(op,1,9); } return op; } /** * generarEjemplos() * * Genera ejemplos predeterminados como * base para el programa. * @param * @return */ void App::generarEjemplos(){ personal.push_back(new Cajero(personal.size()+numInt, "Andy", "andy@gmail.com", "av. yucatan #56", "9991255323", 18.3)); personal.push_back(new Cajero(personal.size()+numInt, "Fermin", "fer@gmail.com", "av. queretaro #434", "422868357", 18.5)); personal.push_back(new Proveedor(personal.size()+numInt, "Yose", "yose@gmail.com", "av. ejidal #124", "4611255323", "Cuplasa")); personal.push_back(new Proveedor(personal.size()+numInt, "Lucero", "lucy@gmail.com", "av. Lopes #863", "4615673432", "Gorila")); personal.push_back(new Cliente(personal.size()+numInt, "Sam", "sam@gmail.com", "av. Tecnologico #76", "422967578", "3S4A5M7")); personal.push_back(new Cliente(personal.size()+numInt, "Lili", "lili@gmail.com", "av. alemania #812", "461737783", "L9I4L3I9")); personal.push_back(new Cliente(personal.size()+numInt, "Carlos", "carlitos@hotmail.com", "av. mexico #346", "462461542", "C8A2RL5O6S")); personal.push_back(new Cliente(personal.size()+numInt, "Juan", "juanin@gmail.com", "av. japon #861", "422346781", "J8U9A6N")); personal.push_back(new Cliente(personal.size()+numInt, "Diego", "diegin@gmail.com", "av. celaya #413", "461523563", "D1I2E3G4O")); productos.push_back(new Producto(productos.size()+numInt, "Cubeta", 21.20, (Proveedor*)personal[2])); productos.push_back(new Producto(productos.size()+numInt, "Sarten", 130.10, (Proveedor*)personal[3])); vector<Subproducto> sub; sub.push_back(Subproducto(2, *productos[0])); sub.push_back(Subproducto(3, *productos[1])); tickets.push_back(new Ticket(tickets.size()+numInt, "03/06/2021", (Cajero*) personal[0], sub)); vector<Subproducto> sub2; sub2.push_back(Subproducto(5, *productos[1])); sub2.push_back(Subproducto(2, *productos[0])); tickets.push_back(new Ticket(tickets.size()+numInt, "03/06/2021", (Cajero*) personal[1], sub2)); facturas.push_back(new Factura(facturas.size()+numInt, Ticket(tickets.size()+numInt, "03/06/2021", (Cajero*) personal[1], sub2), (Cliente*)personal[4])); facturas.push_back(new Factura(facturas.size()+numInt, Ticket(tickets.size()+numInt, "03/06/2021", (Cajero*) personal[0], sub), (Cliente*)personal[4])); } /** * listaFacturas() * * Método que presenta todos los facturas * registrados. * @param * @return */ void App::listaFacturas(){ cout << "\nID\tCajero\tTotal"; for(Factura *i : facturas){ cout << i->printListaFactura(); } cout << "\n"; } /** * listaTickets() * * Método que presenta todos los tickets * registrados. * @param * @return */ void App::listaTickets(){ cout << "\nID\tFecha\t\tCajero\tTotal"; for(Ticket *i : tickets){ cout << i->printListaTicket(); } cout << "\n"; } /** * listaProducto() * * Método que presenta todos los productos * registrados. * @param * @return */ void App::listaProductos(){ cout << "\nID\tNombre\tPrecio\tProveedor"; for(Producto *i : productos){ cout << i->printProducto(); } cout << "\n"; } /** * listaSubproducto() * * Método que ejecuta un loop de registro de * subproductos para un ticket. * @param * @return vector<Subproducto> lista de * subproducto. */ vector<Subproducto> App::listaSubproductos(){ vector<Subproducto> subproducto; int id, cant; string op ="n"; bool ban = true; do{ while (ban){ cout << "\nId del Producto: "; cin>>id; for (Producto *i : productos){ if (i->getId()==id){ cout << "Cantidad: "; cin>>cant; subproducto.push_back(Subproducto(cant, *i)); ban = false; } } if(ban){ cout << "\n ¡¡¡Introduce una opción valida!!! \n"; } } cout << "Agregar otro producto(s/n): "; cin >> op; ban=true; }while(op=="s"); return subproducto; } /** * verPersonal(string) * * Busca por medio del ID al personal * que le pertenesca * @param string tipo las opciones del * parametro son: "Proveedor", "Cliente" o "Cajero" * @return */ void App::verPersonal(string tipo){ int id; bool ban = true; cout << "\nID: "; cin >> id; for(Personal *i : personal){ if ((i->getTipo()==tipo)&&(i->getId()==id)){ cout << i->printPersonal(); ban = false; break; } } if (ban){ cout << "\n ¡¡¡NO ENCONTRADO!!!\n"; } cout << "\n"; } /** * listaPersonal(string) * * En lista todos los personales del tipo * requerido al que pertenecen * @param string tipo las opciones del * parametro son: "Proveedor", "Cliente" o "Cajero" * @return */ void App::listaPersonal(string tipo){ cout << "\nID\tNombre"; for(Personal *i : personal){ if (i->getTipo()==tipo){ cout << i->printListaPersonal(); } } cout << "\n"; } /** * verPersonal(string) * * Agrega un personal en el ambito * en que se requiera * @param int op tipo las opciones del * parametro son: 1 para Proveedor, * 2 para Cliente o 3 para Cajero. * @return */ void App::agregaPersonal(int op){ string nombre, correo, direccion, RFC, empresa, numeroTel; double salario; cout << "\nNombre: "; cin >> nombre; cout << "\nCorreo: "; cin >> correo; cout << "\nDirección: "; cin >> direccion; cout << "\nTelefono: "; cin >> numeroTel; switch(op){ case 1: cout << "\nRFC: "; cin >> RFC; personal.push_back(new Cliente(personal.size()+numInt, nombre, correo, direccion, numeroTel, RFC)); break; case 2: cout << "\nEmpresa: "; cin >> empresa; personal.push_back(new Proveedor(personal.size()+numInt, nombre, correo, direccion, numeroTel, empresa)); break; case 3: cout << "\nSalario p/Hr: "; cin >> salario; personal.push_back(new Cajero(personal.size()+numInt, nombre, correo, direccion, numeroTel, salario)); break; } cout << "\n\n ID ASIGNADO: "<<personal.size()+numInt-1<<"\n"; cout << "\n ¡¡¡AGREGADO CON EXITO!!!\n"; } #endif
a9e1b72aa4f9aacd8348345c7f0be24df0bdb7ac
88bd5acc20e1446147d3a5fb22a51ab74b76037b
/OculusCam/Rendering/OculusRenderer.cpp
05ee8f520d9e13cbf3b7abfb31b901266d9f4f5d
[]
no_license
ethanli83/OculusCam
55b961479eea859a901165a42d0e2b581d5bb9c5
b6d03c9af625c86db714f5a78421ac1c057dd02c
refs/heads/master
2021-01-10T18:39:02.093606
2014-04-26T15:23:08
2014-04-26T15:23:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,163
cpp
OculusRenderer.cpp
// // Created by Ethan Li on 26/04/2014. // Copyright (c) 2014 Ethan.Li. All rights reserved. // #include <type_ptr.hpp> #include <matrix_transform.hpp> #include "OculusRenderer.h" const glm::vec3 UpVec(0.0f, 1.0f, 0.0f); const glm::vec3 ForwardVec(0.0f, 0.0f, -1.0f); const float YawInitial = 3.141592f; static const GLfloat ScreenQuadVertex[] = { 0.0f, 1.0f, 0.0f, 1.0f, // BL x 1.0f, 0.0f, 1.0f, 0.0f, // TR | 0.0f, 0.0f, 0.0f, 0.0f, // TL x-x 0.0f, 1.0f, 0.0f, 1.0f, // BL x-x 1.0f, 1.0f, 1.0f, 1.0f, // BR | 1.0f, 0.0f, 1.0f, 0.0f // TR x }; OculusRenderer::OculusRenderer(): eyePosition(0.0f, 1.6f, -5.0f), eyeYaw(YawInitial), eyePitch(0), eyeRoll(0), stereoConfig(), leftCam(2), rightCam(0) { clearColour.a = 0.0f; } OculusRenderer::~OculusRenderer() { glDeleteVertexArrays(1, &oculusProgramVAO); glDeleteProgram(oculusProgram); glDeleteBuffers(1, &screenRenderingBuffer); glDeleteFramebuffers(1, &renderTargetBuffer); glDeleteTextures(1, &renderResultTexture); glDeleteTextures(1, &leftEyeCamTex); glDeleteTextures(1, &rightEyeCamTex); RemoveHandlerFromDevices(); ptrSensor.Clear(); ptrHmd.Clear(); ptrDeviceManager.Clear(); } void OculusRenderer::init() { BaseRenderer::init(); const char *detectionMessage; ptrDeviceManager = *DeviceManager::Create(); ptrDeviceManager->SetMessageHandler(this); // Release Sensor/HMD in case this is a retry. ptrSensor.Clear(); ptrHmd.Clear(); ptrHmd = *ptrDeviceManager->EnumerateDevices<HMDDevice>().CreateDevice(); if (ptrHmd) { ptrSensor = *ptrHmd->GetSensor(); // This will initialize hmdInfo with information about configured IPD, // screen size and other variables needed for correct projection. // We pass HMD DisplayDeviceName into the renderer to select the // correct monitor in full-screen mode. if (ptrHmd->GetDeviceInfo(&hmdInfo)) stereoConfig.SetHMDInfo(hmdInfo); } else { // If we didn't detect an HMD, try to create the sensor directly. // This is useful for debugging sensor interaction; it is not needed in // a shipping app. ptrSensor = *ptrDeviceManager->EnumerateDevices<SensorDevice>().CreateDevice(); } // If there was a problem detecting the Rift, display appropriate message. if (!ptrHmd && !ptrSensor) detectionMessage = "Oculus Rift not detected."; else if (!ptrHmd) detectionMessage = "Oculus Sensor detected; HMD Display not detected."; else if (!ptrSensor) detectionMessage = "Oculus HMD Display detected; Sensor not detected."; else if (hmdInfo.DisplayDeviceName[0] == '\0') detectionMessage = "Oculus Sensor detected; HMD display EDID not detected."; else detectionMessage = 0; if (detectionMessage) { throwError(detectionMessage); } if (hmdInfo.HResolution > 0) { winWidth = hmdInfo.HResolution; winHeight = hmdInfo.VResolution; } if (ptrSensor) { // We need to attach sensor to SensorFusion object for it to receive // body frame messages and update orientation. sensorFusion.GetOrientation() // is used in OnIdle() to orient the view. sensorFusion.AttachToSensor(ptrSensor); sensorFusion.SetDelegateMessageHandler(this); sensorFusion.SetPredictionEnabled(true); } glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glEnable(GL_CULL_FACE); glFrontFace(GL_CW); glDepthFunc(GL_LEQUAL); setupRenderProgram(); setupRenderTargetBuffer(); leftCam.startCapture(); rightCam.startCapture(); } void OculusRenderer::preRender(ViewPort vp) { BaseRenderer::preRender(vp); } void OculusRenderer::render(Scene scene, Camera camera, double time) { switch (stereoConfig.GetStereoMode()) { case Stereo_None: BaseRenderer::render(scene, camera, time); break; case Stereo_LeftRight_Multipass: renderStereo(scene, camera, time, stereoConfig.GetEyeRenderParams(StereoEye_Left)); renderStereo(scene, camera, time, stereoConfig.GetEyeRenderParams(StereoEye_Right)); break; } } void OculusRenderer::postRender() { BaseRenderer::postRender(); } void OculusRenderer::renderStereo(Scene scene, Camera camera, double time, StereoEyeParams const params) { glBindFramebuffer(GL_FRAMEBUFFER, renderTargetBuffer); updateOculusCamera(camera, params); ViewPort vp(params.VP.x, params.VP.y, params.VP.w, params.VP.h); BaseRenderer::preRender(vp); BaseRenderer::render(scene, oculusCamera, time); renderScreen(time, params); } void OculusRenderer::renderScreen(double time, StereoEyeParams const params) { glBindFramebuffer(GL_FRAMEBUFFER, 0); ViewPort vp(params.VP.x, params.VP.y, params.VP.w, params.VP.h); BaseRenderer::preRender(vp); glUseProgram(oculusProgram); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindVertexArray(oculusProgramVAO); float w = float(params.VP.w) / float(winWidth), h = float(params.VP.h) / float(winHeight), x = float(params.VP.x) / float(winWidth), y = float(params.VP.y) / float(winHeight); float aspect = float(params.VP.w) / float(params.VP.h); DistortionConfig distortion = *params.pDistortion; float offsetX = params.Eye == StereoEye_Left ? distortion.XCenterOffset : -distortion.XCenterOffset; glm::vec2 lensCenter = glm::vec2(x + (w + offsetX * 0.5f) * 0.5f, y + h * 0.5f); glUniform2f(lensCenterLoc, lensCenter[0], lensCenter[1]); glm::vec2 screenCenter = glm::vec2(x + w * 0.5f, y + h * 0.5f); glUniform2f(screenCenterLoc, screenCenter[0], screenCenter[1]); float scaleFactor = 1.0f / (distortion.Scale * 0.76f); glUniform2f(scaleLoc, w / 2.0f * scaleFactor, h / 2.0f * scaleFactor * aspect); glUniform2f(scaleInLoc, 2.0f / w, 2.0f / h); glUniform4f(hmdWarpParamLoc, distortion.K[0], distortion.K[1], distortion.K[2], distortion.K[3]); glUniform4f(chromAbParamLoc, distortion.ChromaticAberration[0], distortion.ChromaticAberration[1], distortion.ChromaticAberration[2], distortion.ChromaticAberration[3]); glm::mat4 texMatrix( glm::vec4(w, 0, 0, 0), glm::vec4(0, h, 0, 0), glm::vec4(0, 0, 0, 0), glm::vec4(x, y, 0, 1) ); glUniformMatrix4fv(posMatrixLoc, 1, GL_FALSE, glm::value_ptr(posMatrix)); glUniformMatrix4fv(texMatrixLoc, 1, GL_FALSE, glm::value_ptr(texMatrix)); if (params.Eye == StereoEye_Left) { loadCamImageToTex(leftCam, leftEyeCamTex); glBindTexture(GL_TEXTURE_2D, leftEyeCamTex); } else { loadCamImageToTex(rightCam, rightEyeCamTex); glBindTexture(GL_TEXTURE_2D, rightEyeCamTex); } glDrawArrays(GL_TRIANGLES, 0, 6); glBindTexture(GL_TEXTURE_2D, renderResultTexture); glDrawArrays(GL_TRIANGLES, 0, 6); glBindTexture(GL_TEXTURE_2D, 0); } void OculusRenderer::updateOculusCamera(Camera camera, StereoEyeParams const params) { if (ptrSensor) { Quatf hmdOrient = sensorFusion.GetOrientation(); float yaw = 0.0f; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wint-conversion" #pragma ide diagnostic ignored "ImplicitIntegerAndEnumConversion" hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&yaw, &eyePitch, &eyeRoll); #pragma clang diagnostic pop eyeYaw += (yaw - lastEyeYaw); lastEyeYaw = yaw; } if (!ptrSensor) { const float maxPitch = ((3.1415f / 2) * 0.98f); if (eyePitch > maxPitch) eyePitch = maxPitch; if (eyePitch < -maxPitch) eyePitch = -maxPitch; } glm::mat4 ypyMatrix = glm::rotate(glm::mat4(1.0f), eyeYaw, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::rotate(glm::mat4(1.0f), eyePitch, glm::vec3(1.0f, 0.0f, 0.0f)) * glm::rotate(glm::mat4(1.0f), eyeRoll, glm::vec3(0.0f, 0.0f, 1.0f)); glm::vec3 up = ypyMatrix * UpVec; glm::vec3 forward = ypyMatrix * ForwardVec; // Minimal head modelling. float headBaseToEyeHeight = 0.15f; // Vertical height of eye from base of head float headBaseToEyeProtrusion = 0.09f; // Distance forward of eye from base of head glm::vec3 eyeCenterInHeadFrame(0.0f, headBaseToEyeHeight, -headBaseToEyeProtrusion); glm::vec3 rotatedEyeCenter = ypyMatrix * eyeCenterInHeadFrame; glm::vec3 shiftedEyePosition = eyePosition + rotatedEyeCenter; shiftedEyePosition[1] -= eyeCenterInHeadFrame[1]; // Bring the head back down to original height oculusCamera.viewMatrix = glm::lookAt(shiftedEyePosition, shiftedEyePosition + forward, up) * camera.viewMatrix; oculusCamera.projectMatrix = castMatrix(params.Projection); } void OculusRenderer::setupRenderProgram() { oculusProgram = glCreateProgram(); GLuint vs = loadShader("resources/shaders/oculus.vs.glsl", GL_VERTEX_SHADER); GLuint fs = loadShader("resources/shaders/oculus.fs.glsl", GL_FRAGMENT_SHADER); glAttachShader(oculusProgram, vs); glAttachShader(oculusProgram, fs); glLinkProgram(oculusProgram); glDeleteShader(vs); glDeleteShader(fs); glGenVertexArrays(1, &oculusProgramVAO); glBindVertexArray(oculusProgramVAO); glGenBuffers(1, &screenRenderingBuffer); glBindBuffer(GL_ARRAY_BUFFER, screenRenderingBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(ScreenQuadVertex), ScreenQuadVertex, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, screenRenderingBuffer); positionLoc = glGetAttribLocation(oculusProgram, "position"); glEnableVertexAttribArray((GLuint)positionLoc); glVertexAttribPointer((GLuint)positionLoc, 2, GL_FLOAT, false, sizeof(GLfloat) * 4, NULL); texCoordLoc = glGetAttribLocation(oculusProgram, "texCoord"); glEnableVertexAttribArray((GLuint)texCoordLoc); glVertexAttribPointer((GLuint)texCoordLoc, 2, GL_FLOAT, false, sizeof(GLfloat) * 4, (GLvoid const *) (sizeof(GLfloat) * 2)); posMatrixLoc = glGetUniformLocation(oculusProgram, "posMatrix"); texMatrixLoc = glGetUniformLocation(oculusProgram, "texMatrix"); lensCenterLoc = glGetUniformLocation(oculusProgram, "LensCenter"); screenCenterLoc = glGetUniformLocation(oculusProgram, "ScreenCenter"); scaleLoc = glGetUniformLocation(oculusProgram, "Scale"); scaleInLoc = glGetUniformLocation(oculusProgram, "ScaleIn"); hmdWarpParamLoc = glGetUniformLocation(oculusProgram, "HmdWarpParam"); chromAbParamLoc = glGetUniformLocation(oculusProgram, "ChromAbParam"); glGenTextures(1, &leftEyeCamTex); glGenTextures(1, &rightEyeCamTex); } void OculusRenderer::setupRenderTargetBuffer() { // set up the texture as a storage of the rendering result glGenFramebuffers(1, &renderTargetBuffer); glBindFramebuffer(GL_FRAMEBUFFER, renderTargetBuffer); glGenTextures(1, &renderResultTexture); glBindTexture(GL_TEXTURE_2D, renderResultTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, winWidth, winHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, renderResultTexture, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { throwError("GL_FRAMEBUFFER_COMPLETE"); return; } glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); } void OculusRenderer::loadCamImageToTex(WebCam cam, GLuint texture) { cv::Mat frame; cam.capture.read(frame); flip(frame, frame, 0); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, cam.width * 2, cam.height / 2, 0, GL_BGR, GL_UNSIGNED_BYTE, frame.ptr()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); }
238a4a0467542b4573693784dfe9c9fb5087a103
7a0fd4dbc026b21813169d8ec505fabf31603b11
/Gammiriovanie.cpp
8b027db56fc8066922a433808e8bcd6b3b149d36
[]
no_license
sapvelich0906/Homework1
eb7ea5765616d9b6a9624f18ebff6095b9efb670
3b78592297064a4eb9dede6e48ff570d42f265a4
refs/heads/master
2020-01-23T21:57:44.950692
2016-11-25T04:03:36
2016-11-25T04:03:36
74,724,465
0
0
null
null
null
null
UTF-8
C++
false
false
2,312
cpp
Gammiriovanie.cpp
// Gammiriovanie.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <math.h> #include<time.h> #include <iostream> using namespace std; int per2_10(int a) { int a1=0, k=1; while (a > 0) { a1 = a1 + k * (a % 2); a = int(a / 2); k *= 10; } return a1; } int per10_2(int a) { int a1 = 0, k = 0; while (a > 0) { a1 = a1 + int((a % 10)*pow(2, k)); k++; a = int(a / 10); } return a1; } int uni(int a, int b) { return 256*a+b; } int del_1(int a) { return int(a / 256); } int del_2(int a) { return (a % 256); } int gamm_8(int a, int b) { int c = 0, k=1; a = per2_10(a); b = per2_10(b); for (int i = 0; i < 8; i++) { c += (((a % 10) + (b % 10)) % 2) * k; a = int(a / 10); b = int(b / 10); k *= 10; } return per10_2(c); } int gamm_16(int a, int b) { return uni(gamm_8(del_1(a), del_1(b)), gamm_8(del_2(a), del_2(b))); } int sdvigp(int a) { return (a >> 2) | ((a % 4)<<14); } int sdvigl(int a) { return ((a % 16384) << 2) | ((a-(a % 16384))>> 14); } int ascii_cod(unsigned char a) { int c; c = a; return c; } unsigned char ascii_sym(int a) { char c; c = a; return c; } int main() { setlocale(LC_ALL, "rus"); char text[255], sht[255], desht[255]; int *p; int l,k; srand(time(NULL)); cin.getline(text, 255); l = int(strlen(text) / 2) + (strlen(text) % 2); p = (int *)malloc(l * sizeof(int)); for (int i = 0; i < l; i++) { p[i] = rand() % 65535; cout << p[i] << " "; } cout << endl; for (int i = 0; i < l; i++) { sht[2 * i] = ascii_sym(del_1(sdvigp(gamm_16(uni(ascii_cod(text[2 * i]), ascii_cod(text[2 * i + 1])), p[i])))); sht[2 * i + 1] = ascii_sym(del_2(sdvigp(gamm_16(uni(ascii_cod(text[2 * i]), ascii_cod(text[2 * i + 1])), p[i])))); } for (int i = 0; i < 2*l; i++) cout << sht[i]; cout << endl; for (int i = 0; i < l; i++) { desht[2 * i] = ascii_sym(del_1(gamm_16(sdvigl(uni(ascii_cod(sht[2 * i]), ascii_cod(sht[2 * i + 1]))), p[i]))); desht[2 * i + 1] = ascii_sym(del_2(gamm_16(sdvigl(uni(ascii_cod(sht[2 * i]), ascii_cod(sht[2 * i + 1]))), p[i]))); } for (int i = 0;i < 2*l; i++) cout << desht[i]; cout << endl; return 0; }
2e94b48be4ba671c7ddcc0c45fec903d9f0f0cac
8a0458d96da032528319422f5ced046621efc3da
/networktables/include/networktables2/util/EOFException.h
4a8ccd16cd756f62a34269d1159334cbd362682e
[ "MIT" ]
permissive
warrenlp/2015VisionCode
c44a1bba9f4432553a2900f16b13b16b6c9453ec
38a46724e2fbdc57baeeb7bf196327a106437f11
refs/heads/master
2021-01-18T02:19:24.809552
2015-12-30T02:10:05
2015-12-30T02:10:05
46,771,955
1
1
null
2015-12-30T02:10:05
2015-11-24T06:31:57
C++
UTF-8
C++
false
false
605
h
EOFException.h
/* * EOFException.h * * Created on: Oct 1, 2012 * Author: Mitchell Wills */ #ifndef EOFEXCEPTION_H_ #define EOFEXCEPTION_H_ #include "networktables2/util/IOException.h" /** * Indicates that an EOF was encountered during an I/O operation, * and therefore the operation could not be completed. */ class EOFException : public IOException{ public: /** * Creates an EOFException. */ EOFException(); virtual ~EOFException() throw (); /** * Implements {@link IOException}::isEOF() */ virtual bool isEOF(); }; #endif /* EOFEXCEPTION_H_ */
6ecda3b6e71f3390c0ac155fe26797ddeb93fea1
87c94d04f7b34e04df6456450a2a4ef09f2d81a4
/Doggo/src/usb_serial.cpp
dd534aab0b706ced2e07a24cffa74c3186ba5a53
[ "MIT" ]
permissive
jamestiotio/SUTDoggo
7d1f7deb3fd29947bfa136ac84ec8e8632d6be2a
f8aa493acd06046a9a0fc580687bc6445463ded8
refs/heads/master
2023-04-08T07:47:30.120342
2021-06-02T14:58:41
2021-06-02T14:58:41
237,259,172
5
1
MIT
2023-04-03T23:45:10
2020-01-30T16:51:24
C
UTF-8
C++
false
false
5,160
cpp
usb_serial.cpp
#include "usb_serial.h" #include "ChRt.h" #include "Arduino.h" #include "globals.h" #include "config.h" #include "jump.h" #include "backflip.h" #include "position_control.h" THD_WORKING_AREA(waUSBSerialThread, 2048); THD_FUNCTION(USBSerialThread, arg) { (void)arg; int MAX_COMMAND_LENGTH = 32; char cmd[MAX_COMMAND_LENGTH + 1]; int pos = 0; while(true) { while(Serial.available()) { char c = Serial.read(); if (c == ';' || c == '\n') { cmd[pos] = '\0'; InterpretCommand(cmd); pos = 0; } else { cmd[pos++] = c; } } chThdSleepMicroseconds(1000000/USB_SERIAL_FREQ); } } void InterpretCommand(char* cmd) { char c; float f; // Note: Putting a space in front of %c allows you type commands like: // f 2.0; l 0.01; h 0.08 int num_parsed = sscanf(cmd, " %c %f", &c, &f); if (num_parsed < 1) { Serial.println("Invalid command"); return; } switch(c) { // Change gait frequency case 'f': Serial << "Set freq. to: " << f << "\n"; state_gait_params[state].freq = f; break; // Change stride length case 'l': Serial << "Set stride len to: " << f << "\n"; state_gait_params[state].step_length = f; break; // Change stride differential case 's': Serial << "Set step difference len to: " << f << "\n"; state_gait_params[state].step_diff = f; break; // Change stance height case 'h': Serial << "Set stance ht. to: " << f << "\n"; state_gait_params[state].stance_height = f; break; // Change gait up amplitude case 'u': Serial << "Set up amp. to: " << f << "\n"; state_gait_params[state].up_amp = f; break; // Change gait down amplitude case 'd': Serial << "Set down amp. to: " << f << "\n"; state_gait_params[state].down_amp = f; break; // Change gait flight percent case 'p': Serial << "Set flt. perc. to: " << f << "\n"; state_gait_params[state].flight_percent = f; break; // Change leg gains case 'g': { // Have to create a new scope here in order to declare variables float kp_t, kd_t, kp_g, kd_g; int res = sscanf(cmd, "g %f %f %f %f", &kp_t, &kd_t, &kp_g, &kd_g); if (res == 4) { Serial << "Set gains to: " << kp_t << " " << kd_t << " " << kp_g << " " << kd_g << "\n"; gait_gains.kp_theta = kp_t; gait_gains.kd_theta = kd_t; gait_gains.kp_gamma = kp_g; gait_gains.kd_gamma = kd_g; } else { Serial.println("Invalid gain format."); } } break; // Toggle debug printing case 'D': enable_debug = !enable_debug; Serial << "Debug printing: " << enable_debug << "\n"; break; // Switch into STOP state case 'S': state = STOP; Serial.println("STOP"); break; // Switch into DANCE state case 'E': TransitionToDance(); break; // Switch into BOUND state case 'B': TransitionToBound(); break; // Switch into TROT state case 'T': TransitionToTrot(); break; // Swith into TURN_TROT case 'Y': TransitionToTurnTrot(); break; // Switch into WALK state case 'W': TransitionToWalk(); break; // Switch into WALK state case 'P': TransitionToPronk(); break; // Switch into JUMP state case 'J': StartJump(millis()/1000.0f); Serial.println("JUMP"); break; case 'H': TransitionToHop(); break; case 'F': StartFlip(millis()/1000.0f); break; case 'R': state = RESET; Serial.println("RESET"); break; // // Switch into TEST state // TODO: Make new character for test mode case '1': state = TEST; Serial.println("(1)TEST"); break; default: Serial.println("Unknown command"); } } void PrintGaitCommands() { Serial.println("Available gait commands:"); Serial.println("(f)req"); Serial.println("step (l)ength"); Serial.println("stance (h)eight"); Serial.println("(d)own amplitude"); Serial.println("(u)p amplitude"); Serial.println("flight (p)roportion"); Serial.println("(s)tep difference"); } void PrintStates() { Serial.println("STATES: Danc(E), (W)alk, (T)rot, (B)ound, (P)ronk, (S)top, (J)ump, (Y)TurnTrot"); Serial.println("Toggle (D)ebug"); }
0da65a341937dcbab0602948de2d92db4cbb9bb9
29e9a31e0039fcb18ffea8b96b7918a15d5b2e7a
/Hw5/Document.cpp
5827fffdbee2b973f2569f25d1246a149b6c6bcf
[]
no_license
tommyduncan/POSD-homework
c6c3ab3438ed7f099213fcbc468d88c0f53feaf3
1e28a869b0b6249021f8a6c38e24ec8e115e2182
refs/heads/master
2021-05-02T18:45:47.867112
2017-01-04T13:29:25
2017-01-04T13:29:25
69,227,347
0
1
null
null
null
null
UTF-8
C++
false
false
588
cpp
Document.cpp
#include "Document.h" string Document::openDocument(const string name){ if(!canOpenDocument(name)) throw std::string("file is not existed."); openFile(name); return readFile(); } /* Class "MyDocument" which is the subclass of "Document" */ void MyDocument::openFile(const string name){ fin.open(name, ios::in); } bool MyDocument::canOpenDocument(const string name){ fin.open(name, ios::in); if(!fin) return false; fin.close(); return true; } string MyDocument::readFile(){ fin.getline(line,sizeof(line)); return line; }
33ac31ebbbd7b840efc38067b90825ecbe00ce0c
b669094d27d471ab82bd25220ee22fc0867465cb
/lib/core/src/togo/core/math/vector/1_type.hpp
dee8c773d6495e62afabc5f0437b41001456e831
[ "MIT" ]
permissive
komiga/togo
9f26af22f3cc4dc535d30d886deb294ebf717ba9
7a366fc02e87c8480f008aa110516e4b04f8d73b
refs/heads/master
2021-01-23T21:18:15.402108
2020-11-07T06:35:14
2020-11-07T06:35:14
21,193,515
27
1
null
null
null
null
UTF-8
C++
false
false
2,981
hpp
1_type.hpp
#line 2 "togo/core/math/vector/1_type.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief 1-dimensional vector. @ingroup lib_core_types @ingroup lib_core_math @ingroup lib_core_math_vector @ingroup lib_core_math_vector_1d @defgroup lib_core_math_vector_1d 1-dimensional vector @ingroup lib_core_math @ingroup lib_core_math_vector @details */ #pragma once #include <togo/core/config.hpp> #include <togo/core/error/assert.hpp> #include <togo/core/utility/types.hpp> #include <togo/core/utility/traits.hpp> #include <togo/core/math/types.hpp> #include <togo/core/math/traits.hpp> namespace togo { namespace math { // Forward declarations /** @cond INTERNAL */ template<class T> struct TVec1; template<class T> struct TVec2; template<class T> struct TVec3; template<class T> struct TVec4; TOGO_DECLARE_TYPE_IS_VECTOR(TVec1); /** @endcond */ /** @addtogroup lib_core_math_vector_1d @{ */ /// Generic 1-dimensional vector. template<class T> struct TVec1 { static_assert(is_arithmetic<T>::value, ""); /// Type of @c *this. using type = TVec1<T>; /// Type of components. using value_type = T; /// Size/length type. using size_type = unsigned; struct operations; /** @name Fields */ /// @{ value_type x; ///< X value. /// @} /** @name Constructors */ /// @{ /// Construct zeroed. TVec1() : x{T(0)} {} /// Construct uninitialized. explicit TVec1(no_init_tag) {} /// Construct to value. explicit TVec1(value_type const& c1) : x{c1} {} /// Construct to value. template<class U> explicit TVec1(U const& c1) : x{T(c1)} {} /// Construct to vector. TVec1(type const& v) = default; /// Construct to vector. template<class U> TVec1(TVec1<U> const& v) : x{T(v.x)} {} /// Construct to slice of higher-dimension vector. template<class U> explicit TVec1(TVec2<U> const& v) : x{T(v.x)} {} /// Construct to slice of higher-dimension vector. template<class U> explicit TVec1(TVec3<U> const& v) : x{T(v.x)} {} /// Construct to slice of higher-dimension vector. template<class U> explicit TVec1(TVec4<U> const& v) : x{T(v.x)} {} /// @} /** @name Properties */ /// @{ /// Number of components. static constexpr size_type size() { return size_type(1); } /// Value at index. value_type& operator[](size_type const& i) { (void)i; TOGO_DEBUG_ASSERTE(i < size()); return this->x; } /// Value at index. value_type const& operator[](size_type const& i) const { (void)i; TOGO_DEBUG_ASSERTE(i < size()); return this->x; } /// @} /** @name Assignment operators */ /// @{ /// Assign to value. template<class U> type& operator=(U const& s) { this->x = T(s); return *this; } /// Assign to vector. type& operator=(type const& v) = default; /// Assign to vector. template<class U> type& operator=(TVec1<U> const& v) { this->x = T(v.x); return *this; } /// @} }; /** @} */ // end of doc-group lib_core_math_vector_1d } // namespace math } // namespace togo
7033ad84b21666ee2ba726523013da17fa183b2d
95a631b48aa2975a34d673d6c2900fe66c7442f9
/src/diar/segment.h
93261a54a25aa541f48b75e14531eeecc2fc8179
[]
no_license
cyu0913/CRSS-SpkrDiar
243f650778fe5c684c9c551bd82db4a24c946e8f
8a1d6be0ca4ae3854c5214dbdeec2e389795ed2a
refs/heads/master
2021-06-16T13:00:36.053452
2017-05-12T18:05:14
2017-05-12T18:05:14
55,802,632
9
4
null
null
null
null
UTF-8
C++
false
false
2,777
h
segment.h
#ifndef KALDI_SRC_DIAR_SEGMENTS_H_ #define KALDI_SRC_DIAR_SEGMENTS_H_ #include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <map> #include "util/common-utils.h" #include "matrix/matrix-lib.h" #include "hmm/posterior.h" #include "gmm/am-diag-gmm.h" #include "ivector/ivector-extractor.h" #include "ivector/plda.h" #include "diar-utils.h" namespace kaldi{ class Segment { public: Segment(); Segment(const int32 start, const int32 end); Segment(const std::string label, const int32 start, const int32 end); std::string Label(); // return cluster label int32 StartIdx(); // return start frame index of segment int32 EndIdx(); // return last frame index of segment int32 Size(); // return the frame length of the segment int32 SizeAfterMask(); // return the frame length of the segment after masking Vector<double> Ivector(); // return i-vector SpMatrix<double> IvectorCovar(); // return the i-vector uncertainty (covariance) Vector<BaseFloat> Mask(); // return the mask void SetLabel(std::string label); void SetIvector(Vector<double>& ivec); void SetIvector(Vector<double>& ivec, SpMatrix<double>& ivec_covar); void SetIvector(const Matrix<BaseFloat>& feats, const Posterior& posteriors, const IvectorExtractor& extractor); private: std::string label_; Vector<BaseFloat> mask_; // frame selection ., int32 start_; int32 end_; int32 size_; int32 size_after_mask_; Vector<double> ivector_; SpMatrix<double> ivector_covar_; }; // Segments are collection of segment, and the operations on those segments. class SegmentCollection { public: SegmentCollection(); SegmentCollection(const std::string uttid); SegmentCollection(const Vector<BaseFloat>& frame_labels, const std::string uttid); int32 Size() const; std::string UttID(); //void ToLabels(Vector<BaseFloat>&); void WriteToRTTM(const std::string& rttm_outputdir); Segment* KthSegment(int32 k); SegmentCollection GetSpeechSegments(); SegmentCollection GetLargeSegments(int32 min_seg_len); /* void ExtractIvectors(const Matrix<BaseFloat>& feats, const Posterior& posterior, const IvectorExtractor& extractor); void GetSegmentIvector(const Matrix<BaseFloat>& segFeats, const Posterior& segPosterior, const IvectorExtractor& extractor, Segment& seg); void NormalizeIvectors(); */ void Append(Segment* seg); void Read(const std::string& segments_rxfilename); void Write(const std::string& segments_dirname); /* void ReadIvectors(const std::string& ivector_rxfilename); void WriteIvectors(const std::string& ivector_wxfilename); */ private: std::vector<Segment*> segment_list_; std::string uttid_; std::vector< Vector<double> > ivector_list_; }; } #endif
96e470040bce4231c5545ed7bfb61aabe2ec5bbe
fae5dd24fa7c3736e1cacb80ec5a3de87c66e3e8
/2016-17년 겨울방학/study15/study15/2839.cpp
6a799ba686c95583a3ce3063e8e162ee89553136
[]
no_license
syshim77/FirstTouch
a83fd0e8d8879d8d7305eb020fa19ab1fcbb68d1
3dfaa3bb23e2b37676997598b7970709d0557bd1
refs/heads/master
2020-04-27T20:28:36.858279
2019-03-09T06:55:23
2019-03-09T06:55:23
174,659,434
0
0
null
null
null
null
UTF-8
C++
false
false
314
cpp
2839.cpp
#include <iostream> using namespace std; int main() { int sugar; int cnt = 0; cin >> sugar; cnt = sugar / 5; if ((sugar % 5) % 3 == 0) cnt += (sugar % 5) / 3; else { if (sugar % 3 == 0) cnt = sugar / 3; else { cout << "-1" << endl; return 0; } } cout << cnt << endl; return 0; }
ed0cb8bd8b65b730841cace92e3d71d7dc9cb338
90d39aa2f36783b89a17e0687980b1139b6c71ce
/HackerRank/101MAR/3.cpp
2e91eb3978a517ec1e903716341f796c9c3caece
[]
no_license
nims11/coding
634983b21ad98694ef9badf56ec8dfc950f33539
390d64aff1f0149e740629c64e1d00cd5fb59042
refs/heads/master
2021-03-22T08:15:29.770903
2018-05-28T23:27:37
2018-05-28T23:27:37
247,346,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,378
cpp
3.cpp
/* Nimesh Ghelani (nims11) */ #include <bits/stdc++.h> #define in_T int t;for(scanf("%d",&t);t--;) #define in_I(a) scanf("%d",&a) #define in_F(a) scanf("%lf",&a) #define in_L(a) scanf("%lld",&a) #define in_S(a) scanf("%s",a) #define newline printf("\n") #define BE(a) a.begin(), a.end() using namespace std; const int mod = 1000000007; int fact[100010], inv[100010]; int POW(long long r, long long n) { int ans = 1; while(n>0) { if(n&1) ans = (ans*r)%mod; n >>= 1; r = (r*r)%mod; } return ans; } long long C(int n, int r){ // cout<<n<<" "<<r<<endl; if(r < 0)return 0; long long ret = fact[n]; ret = (ret * inv[n-r])%mod; ret = (ret * inv[r])%mod; return ret; } long long cat(int m, int n){ long long ret = C(m+n, m) - C(m+n, m-1); ret %= mod; if(ret < 0)ret += mod; // cout<<m<<" "<<n<<" "<<ret<<endl; return ret; } int main() { fact[0] = 1; for(int i = 1;i<=100000;i++) fact[i] = (fact[i-1]*1LL*i)%mod; for(int i = 0;i<=100000;i++) inv[i] = POW(fact[i], mod-2); in_T{ int N; in_I(N); if(N%2 == 1){ printf("0\n"); continue; } int res = 0; for(int m = 0, n = N-1; n > m; n--, m++){ res = (res + cat(m, n))%mod; } printf("%d\n", res); } }
fe4f3b3c8e00885938bb7572d9a54bf3a58bcb91
a2ee7bdda1ec77faf3f68b158da3523de425987e
/tp-entrega-01/cliente1942/src/MainCliente.cpp
8f7e49a7e8b830555d4caa95fea219ca046f4925
[]
no_license
MauroToscano/Taller-de-Programacion-I-Grupo-8
e495cbc27b76533619e0fc36c9826fe8a51e1645
1b5e6c6e3eda8eb1c11ab905fa75e75a571234a5
refs/heads/master
2022-07-20T04:00:08.267771
2020-02-25T23:44:10
2020-02-25T23:44:10
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
10,476
cpp
MainCliente.cpp
#include "MainCliente.h" MainCliente::MainCliente(){ dirXML.assign(""); conex = 0; len = 0; conectado = false; // aca deberia de obtener el ip, port y cargar los mensajes en el map ip = ""; port = -1; // si usan el principal comentar inicializar() parserx = new ParserXml(); } MainCliente::~MainCliente(){ delete this->parserx; } void MainCliente::parsearArchivoXml(int argc, char* argv[]){ getParserXml()->cargarXmlCliente(argc,argv); int res = getParserXml()->validarXmlArchivoCliente(); if (res < 0){ printf("\nERROR: Error semantico\n"); Log::getInstance()->error("ERROR: Error semantico."); getParserXml()->cargarXmlCliente(0,argv); } //else{ //luego de la carga crea los datos a partir del XML ClienteXml * clienteXml = getParserXml()->createDataClienteXml(); printf("\nOK\n"); //se cargan los datos desde el cliente //copia la ip this->ip.assign(clienteXml->getConexionXmlCopy()->getIp()); //copia el puerto int puerto = clienteXml->getConexionXmlCopy()->getPuerto(); char cadena[10]; sprintf(cadena,"%d",puerto); this->port.assign(cadena); std::cout<< port<<std::endl; //carga un listado, //que luego viajara al cliente //aca ya se puede cargar el mapa cargarIDMensajes(clienteXml); // luego de usarlo se debe borrar delete clienteXml; // } } ParserXml * MainCliente::getParserXml(){ return this->parserx; } bool MainCliente::esUnNumero(string s){ for(int i=0;i<s.length();i++) if(!isdigit(s[i])) return false; return true; } int MainCliente::chequearConexion(int len){ if (len == 0){ printf("\n No llego el mensaje, se desconecto el servidor\n"); conectado=false; system("PAUSE"); return -1; } else if (len < 0){ conectado=false; int error = WSAGetLastError(); if(error == WSAENOTCONN || error == WSAECONNRESET) printf("\n Se a desconectado inesperadamente el servidor\n"); else if (error == WSAENETDOWN) printf("\nRed caida\n"); else printf("\nError en conexion con el servidor\n"); system("PAUSE"); return -1; } return 0; } int MainCliente::inicializar(){ //Inicializamos WSAStartup(MAKEWORD(2,2),&wsa); //resolvemos el nombre de dominio localhost, esto se resolverá a 127.0.0.1 host=gethostbyname(ip.c_str()); //creamos el socket sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (sock==-1) { Log::getInstance()->error(" al crear el socket."); printf("Error al crear el socket"); return -1; } setsockopt (sock, IPPROTO_TCP, SO_REUSEADDR | SOCK_STREAM, (char*)&c, sizeof(int)); //Definimos la dirección a conectar que hemos recibido desde el gethostbyname //y decimos que el puerto al que deberá conectar es el 9999 con el protocolo ipv4 direc.sin_family=AF_INET; direc.sin_port=htons(atoi(port.c_str())); direc.sin_addr = *((struct in_addr *)host->h_addr); memset(direc.sin_zero,0,8); return 0; } int MainCliente::optConectar(){ inicializar(); if(conectado==true){ Log::getInstance()->warn(" el cliente ya se encuentra conectado."); printf("ya se encuentra conectado \n"); //WARN? } else{ //Intentamos establecer la conexión conex=connect(sock,(sockaddr *)&direc, sizeof(sockaddr)); if (conex==-1) //si no se ha podido conectar porque no se ha encontrado el host o no está el puerto abierto { Log::getInstance()->error(" no se ha podido conectar."); printf("No se ha podido conectar\n"); printf("%i", conex); return -1; } else{ int len2 =2; char bufferEntrada[1024]; len2=recv(sock,bufferEntrada,1023,0); if(len2 == 18){ // Si el server no envia respuesta es que la conexion ha sido satisfactoria Log::getInstance()->info("El cliente se ha conectado correctamente."); conectado = true; } else if (len2 > 0){ // El server envia un mensaje al superar la cantidad de clientes bufferEntrada[len2] =0; Log::getInstance()->error(bufferEntrada); printf("Respuesta servidor:> %s\n",bufferEntrada); shutdown(sock,2); closesocket(sock); } else{ // Es un error chequearConexion(len2); } } } return 0; } int MainCliente::optDesconectar(){ shutdown(sock,2); closesocket(sock); conectado=false; // WSACleanup(); return 0; } int MainCliente::optSalir(){ mapMensajes.clear(); // chequear si se liberan los string // liberar la memoria de los mensajes optDesconectar(); return 0; } // auxiliar de carga de mensajes que deberia hacerse desde el xml int MainCliente::cargarIDMensajes(ClienteXml * clienteXml){ int idx = 0; MensajeXml ** listaMsjs = clienteXml->getListaMensajes(); int totMsjs = clienteXml->getCanMsjs(); while (idx < totMsjs){ //se crea una copia MensajeXml * pMensj = new MensajeXml(*listaMsjs[idx]); mapMensajes.insert ( std::pair<int,MensajeXml*>(pMensj->getId(),pMensj)); idx++; } //hasta aca return 0; } int MainCliente::optEnviar(){ if(conectado==false){ //!conectado Log::getInstance()->info(" debe conectarse para enviar/recibir mensajes."); printf("debe conectarse para enviar/recibir mensajes. \n"); system("PAUSE"); return -1; } char bufferEntrada[1024]; int id=-1,enc=0, len2 =2; int encRecibido = 0; printf("Para salir escriba 0 \n"); // se deberian de cargar los mensajes desde el XML //TODO se cambia esto y se realiza en forma temprana, es decir a penas parsea //pues esto se realiza luego de parsear que carga la lista de mensajes del cliente //cargarIDMensajes(); while(enc!=1){ printf("Ingrese el ID del mensaje: "); string numstring; cin>>numstring; // scanf("%d",&id); if(!esUnNumero(numstring)){ cout<<"recuerde los valores tienen que ser numericos"<<endl; system("PAUSE"); return -1; } id=atoi(numstring.c_str()); if(id==0) return 0; std::map<int,MensajeXml*>::iterator it; it=mapMensajes.find(id); if(it==mapMensajes.end()){ printf("Mensaje no encontrado\n"); enc=0; }else{ //---------------- //se envia de a uno los mensajes, por eso no hace falta un dato para la cantidad //total de mensajes (ahora trivila canMjs=1) MensajeXml* pMsj = it->second; char * buffEnvio = new char[pMsj->getSizeBytes()]; Protocolo::codificar(*pMsj,buffEnvio); int sizeBytesTotalLista = pMsj->getSizeBytes(); //---------------- if(chequearConexion(send(sock,buffEnvio,sizeBytesTotalLista,0))<0) //enviar el texto que se ha introducido return -1; Log::getInstance()->debug(it->second->getValor()); std::cout<< "Enviando:> ID:" << it->first << " => " << it->second->getValor(); enc=1; // usar el socket y enviar el mensaje //recibir un mensaje if(chequearConexion(len2=recv(sock,bufferEntrada,1023,0))<0) return -1; bufferEntrada[len2] =0; Log::getInstance()->debug(bufferEntrada); printf(" || respuesta servidor:> %s\n",bufferEntrada); } } system("PAUSE"); return 0; } int MainCliente::contarCiclo(void* sciclo){ ciclar_t* ciclos=(ciclar_t*)sciclo; SDL_Delay(ciclos->tiempo); ciclos->terminarCiclar=true; return 0; } int MainCliente::optCiclar(){ if(conectado==false){ //!conectado Log::getInstance()->info(" debe conectarse para enviar/recibir mensajes."); printf(" debe conectarse para enviar/recibir mensajes.\n"); system("PAUSE"); return -1; } int tiempo=0; char bufferEntrada[1024]; int len2 = -1; ciclar_t ciclos; ciclos.terminarCiclar=false; printf("por cuanto tiempo desea ciclar(ms):"); string numstring; cin>>numstring; // scanf("%d",&id); if(!esUnNumero(numstring)){ cout<<"recuerde los valores tienen que ser numericos"<<endl; system("PAUSE"); return -1; } ciclos.tiempo=atoi(numstring.c_str()); //scanf("%d",&(ciclos.tiempo)); SDL_Thread* hiloCiclar=SDL_CreateThread(MainCliente::contarCiclo, "contarCiclo", (void*)&ciclos); std::map<int,MensajeXml*>::iterator it = mapMensajes.begin(); while(ciclos.terminarCiclar==false){ if(it==mapMensajes.end()) it=mapMensajes.begin(); std::cout<< "Enviando:> ID:" << it->first << " => " << it->second; //----------------- //se envia de a uno los mensajes, por eso no hace falta un dato para la cantidad //total de mensajes (ahora trivila canMjs=1) MensajeXml* pMsj = it->second; char * buffEnvio = new char[pMsj->getSizeBytes()]; Protocolo::codificar(*pMsj,buffEnvio); int sizeBytesTotalLista = it->second->getSizeBytes(); //----------------- if(chequearConexion(send(sock,buffEnvio,sizeBytesTotalLista,0))<0) return -1; if(chequearConexion(len2=recv(sock,bufferEntrada,1023,0))<0) return -1; bufferEntrada[len2] =0; printf(" || respuesta servidor:> %s\n",bufferEntrada); it++; } SDL_WaitThread(hiloCiclar, NULL); system("PAUSE"); return 0; } int MainCliente::optErronea(){ printf("\n No existe la opcion marcada\n"); system("PAUSE"); return 0; } /** * muestra el menu y direcciona a las opciones * */ int MainCliente::cargarMenuMsj(){ std::map<int,MensajeXml*>::iterator it = mapMensajes.begin(); std::cout<<""<<std::endl; for (it=mapMensajes.begin(); it!=mapMensajes.end(); ++it) std::cout<< "\t ID:" << it->first << " => " << it->second->getValor() << std::endl; return 0; } int MainCliente::menu(){ int opt = 0; while (opt != OPT_SALIR){ system("CLS"); if(conectado) std::cout<<"\t se encuentra: CONECTADO" <<std::endl; else std::cout<<"\t se encuentra: DESCONECTADO" <<std::endl; printf("\n<1> CONECTAR"); printf("\n<2> DESCONECTAR"); printf("\n<3> SALIR"); printf("\n<4> ENVIAR"); cargarMenuMsj(); printf("\n<5> CICLAR"); printf("\n"); string numstring; cin>>numstring; // scanf("%d",&id); if(!esUnNumero(numstring)){ cout<<"recuerde los valores tienen que ser numericos"<<endl; system("PAUSE"); }else{ opt=atoi(numstring.c_str()); //scanf("%d",&opt); switch (opt) { case OPT_CONECTAR:{ optConectar(); } break; case OPT_DESCONECTAR:{ optDesconectar(); } break; case OPT_SALIR:{ optSalir(); } break; case OPT_ENVIAR:{ optEnviar(); } break; case OPT_CICLAR:{ optCiclar(); } break; default: optErronea(); break; } } } return 0; }
591d5e4c628bee6c59e44e3af5391003b8743db1
d14bc4c582954e78a5462627fc335fb7e045601a
/src/CornrowsX.cpp
8f23a606a8067073c16307c57fee6935613eda8d
[ "MIT" ]
permissive
flyingLowSounds/Southpole
8a49d0036ceb1009279dd9b88af928cba91d51a8
511d1d5bd667c2725ad8261d8d0b84075a05eab7
refs/heads/v2
2023-08-19T11:55:33.302274
2021-10-02T15:04:31
2021-10-02T15:04:31
412,817,135
0
2
NOASSERTION
2021-10-02T14:59:37
2021-10-02T14:18:18
C++
UTF-8
C++
false
false
21,381
cpp
CornrowsX.cpp
// // CornrowsX Mutable Instruments Braids // copied from VCV Audible Instruments // // #include <string.h> #include "CornrowsSettings.h" #include "Southpole.hpp" #include "braids/macro_oscillator.h" #include "braids/signature_waveshaper.h" #include "braids/vco_jitter_source.h" #include "braids/envelope.h" #include "braids/quantizer.h" #include "braids/quantizer_scales.h" struct CornrowsX : Module { enum ParamIds { FINE_PARAM, COARSE_PARAM, FM_PARAM, TIMBRE_PARAM, MODULATION_PARAM, COLOR_PARAM, SHAPE_PARAM, PITCH_RANGE_PARAM, PITCH_OCTAVE_PARAM, TRIG_DELAY_PARAM, ATT_PARAM, DEC_PARAM, AD_TIMBRE_PARAM, AD_MODULATION_PARAM, AD_COLOR_PARAM, RATE_PARAM, BITS_PARAM, SCALE_PARAM, ROOT_PARAM, NUM_PARAMS }; enum InputIds { TRIG_INPUT, PITCH_INPUT, FM_INPUT, TIMBRE_INPUT, COLOR_INPUT, NUM_INPUTS }; enum OutputIds { OUT_OUTPUT, NUM_OUTPUTS }; braids::MacroOscillator osc; braids::SettingsData settings; braids::VcoJitterSource jitter_source; braids::SignatureWaveshaper ws; braids::Envelope envelope; braids::Quantizer quantizer; uint8_t current_scale = 0xff; bool trigger_detected_flag; bool trigger_flag; uint16_t trigger_delay; uint16_t gain_lp; int16_t previous_pitch = 0; dsp::SampleRateConverter<1> src; dsp::DoubleRingBuffer<dsp::Frame<1>, 256> outputBuffer; bool lastTrig = false; bool lowCpu = false; bool paques = false; const uint16_t bit_reduction_masks[7] = { 0xc000, 0xe000, 0xf000, 0xf800, 0xff00, 0xfff0, 0xffff}; const uint16_t decimation_factors[7] = {24, 12, 6, 4, 3, 2, 1}; // only for display braids::SettingsData last_settings; braids::Setting last_setting_changed; uint32_t disp_timeout = 0; CornrowsX() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS); memset(&osc, 0, sizeof(osc)); osc.Init(); memset(&quantizer, 0, sizeof(quantizer)); quantizer.Init(); memset(&envelope, 0, sizeof(envelope)); envelope.Init(); memset(&jitter_source, 0, sizeof(jitter_source)); jitter_source.Init(); memset(&ws, 0, sizeof(ws)); ws.Init(0x0000); memset(&settings, 0, sizeof(settings)); configParam(CornrowsX::SHAPE_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::TRIG_DELAY_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::ATT_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::DEC_PARAM, 0.0, 1.0, 0.5, ""); configParam(CornrowsX::FINE_PARAM, -1.0, 1.0, 0.0, ""); configParam(CornrowsX::COARSE_PARAM, -2.0, 2.0, 0.0, ""); configParam(CornrowsX::PITCH_OCTAVE_PARAM, 0.0, 1.0, 0.5, ""); configParam(CornrowsX::ROOT_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::SCALE_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::PITCH_RANGE_PARAM, 0.0, 1.0, 0., ""); configParam(CornrowsX::FM_PARAM, -1.0, 1.0, 0.0, ""); configParam(CornrowsX::AD_MODULATION_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::MODULATION_PARAM, -1.0, 1.0, 0.0, ""); configParam(CornrowsX::TIMBRE_PARAM, 0.0, 1.0, 0.5, ""); configParam(CornrowsX::AD_TIMBRE_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::COLOR_PARAM, 0.0, 1.0, 0.5, ""); configParam(CornrowsX::AD_COLOR_PARAM, 0.0, 1.0, 0.0, ""); configParam(CornrowsX::BITS_PARAM, 0.0, 1.0, 1.0, ""); configParam(CornrowsX::RATE_PARAM, 0.0, 1.0, 1.0, ""); } void process(const ProcessArgs &args) override; void setShape(int shape); json_t *dataToJson() override { json_t *rootJ = json_object(); json_t *settingsJ = json_array(); uint8_t *settingsArray = &settings.shape; for (int i = 0; i < 20; i++) { json_t *settingJ = json_integer(settingsArray[i]); json_array_insert_new(settingsJ, i, settingJ); } json_object_set_new(rootJ, "settings", settingsJ); json_t *lowCpuJ = json_boolean(lowCpu); json_object_set_new(rootJ, "lowCpu", lowCpuJ); return rootJ; } void dataFromJson(json_t *rootJ) override { json_t *settingsJ = json_object_get(rootJ, "settings"); if (settingsJ) { uint8_t *settingsArray = &settings.shape; for (int i = 0; i < 20; i++) { json_t *settingJ = json_array_get(settingsJ, i); if (settingJ) settingsArray[i] = json_integer_value(settingJ); } } json_t *lowCpuJ = json_object_get(rootJ, "lowCpu"); if (lowCpuJ) { lowCpu = json_boolean_value(lowCpuJ); } } }; void CornrowsX::process(const ProcessArgs &args) { settings.quantizer_scale = params[SCALE_PARAM].getValue() * 48.; //sizeof(quantization_values); settings.quantizer_root = params[ROOT_PARAM].getValue() * 11.; settings.pitch_range = params[PITCH_RANGE_PARAM].getValue() * 4.; settings.pitch_octave = params[PITCH_OCTAVE_PARAM].getValue() * 4.; settings.trig_delay = params[TRIG_DELAY_PARAM].getValue() * 6.; settings.sample_rate = params[RATE_PARAM].getValue() * 6.; settings.resolution = params[BITS_PARAM].getValue() * 6.; settings.ad_attack = params[ATT_PARAM].getValue() * 15.; settings.ad_decay = params[DEC_PARAM].getValue() * 15.; settings.ad_timbre = params[AD_TIMBRE_PARAM].getValue() * 15.; settings.ad_fm = params[AD_MODULATION_PARAM].getValue() * 15.; settings.ad_color = params[AD_COLOR_PARAM].getValue() * 15.; // Display - return to SHAPE after 2s if (last_setting_changed != braids::SETTING_OSCILLATOR_SHAPE) { disp_timeout++; } if (disp_timeout > 1.0 * args.sampleRate) { last_setting_changed = braids::SETTING_OSCILLATOR_SHAPE; disp_timeout = 0; } uint8_t *last_settingsArray = &last_settings.shape; uint8_t *settingsArray = &settings.shape; for (int i = 0; i < 20; i++) { if (settingsArray[i] != last_settingsArray[i]) { last_settingsArray[i] = settingsArray[i]; last_setting_changed = static_cast<braids::Setting>(i); disp_timeout = 0; } } // Trigger bool trig = inputs[TRIG_INPUT].getVoltage() >= 1.0; if (!lastTrig && trig) { trigger_detected_flag = trig; } lastTrig = trig; if (trigger_detected_flag) { trigger_delay = settings.trig_delay ? (1 << settings.trig_delay) : 0; ++trigger_delay; trigger_detected_flag = false; } if (trigger_delay) { --trigger_delay; if (trigger_delay == 0) { trigger_flag = true; } } // Quantizer if (current_scale != settings.quantizer_scale) { current_scale = settings.quantizer_scale; quantizer.Configure(braids::scales[current_scale]); } // Render frames if (outputBuffer.empty()) { envelope.Update(settings.ad_attack * 8, settings.ad_decay * 8); uint32_t ad_value = envelope.Render(); float fm = params[FM_PARAM].getValue() * inputs[FM_INPUT].getVoltage(); // Set shape if (paques) { osc.set_shape(braids::MACRO_OSC_SHAPE_QUESTION_MARK); } else { int shape = roundf(params[SHAPE_PARAM].getValue() * braids::MACRO_OSC_SHAPE_LAST_ACCESSIBLE_FROM_META); if (settings.meta_modulation) { shape += roundf(fm / 10.0 * braids::MACRO_OSC_SHAPE_LAST_ACCESSIBLE_FROM_META); } settings.shape = clamp(shape, 0, braids::MACRO_OSC_SHAPE_LAST_ACCESSIBLE_FROM_META); // Setup oscillator from settings osc.set_shape((braids::MacroOscillatorShape)settings.shape); } // Set timbre/modulation float timbre = params[TIMBRE_PARAM].getValue() + params[MODULATION_PARAM].getValue() * inputs[TIMBRE_INPUT].getVoltage() / 5.0; float modulation = params[COLOR_PARAM].getValue() + inputs[COLOR_INPUT].getVoltage() / 5.0; timbre += ad_value / 65535. * settings.ad_timbre / 16.; modulation += ad_value / 65535. * settings.ad_color / 16.; int16_t param1 = rescale(clamp(timbre, 0.0, 1.0), 0.0, 1.0, 0, INT16_MAX); int16_t param2 = rescale(clamp(modulation, 0.0, 1.0), 0.0, 1.0, 0, INT16_MAX); osc.set_parameters(param1, param2); // Set pitch float pitchV = inputs[PITCH_INPUT].getVoltage() + params[COARSE_PARAM].getValue() + params[FINE_PARAM].getValue() / 12.0; if (!settings.meta_modulation) pitchV += fm; if (lowCpu) pitchV += log2f(96000.0 / args.sampleRate); int32_t pitch = (pitchV * 12.0 + 60) * 128; // pitch_range if (settings.pitch_range == braids::PITCH_RANGE_EXTERNAL || settings.pitch_range == braids::PITCH_RANGE_LFO) { // no change - calibration not implemented } else if (settings.pitch_range == braids::PITCH_RANGE_FREE) { pitch = pitch - 1638; } else if (settings.pitch_range == braids::PITCH_RANGE_440) { pitch = 69 << 7; } else { // PITCH_RANGE_EXTENDED pitch -= 60 << 7; pitch = (pitch - 1638) * 9 >> 1; pitch += 60 << 7; } pitch = quantizer.Process(pitch, (60 + settings.quantizer_root) << 7); // Check if the pitch has changed to cause an auto-retrigger int32_t pitch_delta = pitch - previous_pitch; if (settings.auto_trig && (pitch_delta >= 0x40 || -pitch_delta >= 0x40)) { trigger_detected_flag = true; } previous_pitch = pitch; pitch += jitter_source.Render(settings.vco_drift); pitch += ad_value * settings.ad_fm >> 7; pitch = clamp(int(pitch), 0, 16383); if (settings.vco_flatten) { pitch = braids::Interpolate88(braids::lut_vco_detune, pitch << 2); } // pitch_transposition() int32_t t = settings.pitch_range == braids::PITCH_RANGE_LFO ? -(36 << 7) : 0; t += (static_cast<int32_t>(settings.pitch_octave) - 2) * 12 * 128; osc.set_pitch(pitch + t); //osc.set_pitch(pitch); if (trigger_flag) { osc.Strike(); envelope.Trigger(braids::ENV_SEGMENT_ATTACK); trigger_flag = false; } // TODO: add a sync input buffer (must be sample rate converted) uint8_t sync_buffer[24] = {}; int16_t render_buffer[24]; osc.Render(sync_buffer, render_buffer, 24); // Signature waveshaping, decimation (not yet supported), and bit reduction (not yet supported) int16_t sample = 0; size_t decimation_factor = decimation_factors[settings.sample_rate]; uint16_t bit_mask = bit_reduction_masks[settings.resolution]; int32_t gain = settings.ad_vca > 0 ? ad_value : 65535; uint16_t signature = settings.signature * settings.signature * 4095; for (size_t i = 0; i < 24; i++) { //const int16_t bit_mask = 0xffff; if ((i % decimation_factor) == 0) { sample = render_buffer[i] & bit_mask; } sample = sample * gain_lp >> 16; gain_lp += (gain - gain_lp) >> 4; int16_t warped = ws.Transform(sample); render_buffer[i] = stmlib::Mix(sample, warped, signature); } if (lowCpu) { for (int i = 0; i < 24; i++) { dsp::Frame<1> f; f.samples[0] = render_buffer[i] / 32768.0; outputBuffer.push(f); } } else { // Sample rate convert dsp::Frame<1> in[24]; for (int i = 0; i < 24; i++) { in[i].samples[0] = render_buffer[i] / 32768.0; } src.setRates(96000, args.sampleRate); int inLen = 24; int outLen = outputBuffer.capacity(); src.process(in, &inLen, outputBuffer.endData(), &outLen); outputBuffer.endIncr(outLen); } } // Output if (!outputBuffer.empty()) { dsp::Frame<1> f = outputBuffer.shift(); outputs[OUT_OUTPUT].setVoltage(5.0 * f.samples[0]); } } struct CornrowsXDisplay : TransparentWidget { CornrowsX *module; std::shared_ptr<Font> font; CornrowsXDisplay() { font = APP->window->loadFont(asset::plugin(pluginInstance, "res/hdad-segment14-1.002/Segment14.ttf")); } void draw(const DrawArgs &args) override { int shape = module ? module->settings.shape : 0; const char *text = ""; // Background NVGcolor backgroundColor = nvgRGB(0x30, 0x10, 0x10); NVGcolor borderColor = nvgRGB(0xd0, 0xd0, 0xd0); nvgBeginPath(args.vg); nvgRoundedRect(args.vg, 0.0, 0.0, box.size.x, box.size.y, 5.0); nvgFillColor(args.vg, backgroundColor); nvgFill(args.vg); nvgStrokeWidth(args.vg, 1.5); nvgStrokeColor(args.vg, borderColor); nvgStroke(args.vg); nvgFontSize(args.vg, 20.); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.); Vec textPos = Vec(5, 28); NVGcolor textColor = nvgRGB(0xff, 0x00, 0x00); nvgFillColor(args.vg, nvgTransRGBA(textColor, 16)); nvgText(args.vg, textPos.x, textPos.y, "~~~~", NULL); nvgFillColor(args.vg, textColor); //blink if (module && module->disp_timeout & 0x1000) return; if (module && module->last_setting_changed == braids::SETTING_OSCILLATOR_SHAPE) { shape = module->settings.shape; if (module->paques) { text = " 49"; } else { text = algo_values[shape]; } } if (module && module->last_setting_changed == braids::SETTING_META_MODULATION) { text = "META"; } if (module && module->last_setting_changed == braids::SETTING_RESOLUTION) { shape = module->settings.resolution; text = bits_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_SAMPLE_RATE) { shape = module->settings.sample_rate; text = rates_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_TRIG_SOURCE) { text = "AUTO"; } if (module && module->last_setting_changed == braids::SETTING_TRIG_DELAY) { shape = module->settings.trig_delay; text = trig_delay_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_AD_ATTACK) { shape = module->settings.ad_attack; text = zero_to_fifteen_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_AD_DECAY) { shape = module->settings.ad_decay; text = zero_to_fifteen_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_AD_FM) { shape = module->settings.ad_fm; text = zero_to_fifteen_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_AD_TIMBRE) { shape = module->settings.ad_timbre; text = zero_to_fifteen_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_AD_COLOR) { shape = module->settings.ad_color; text = zero_to_fifteen_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_AD_VCA) { text = "\\VCA"; } if (module && module->last_setting_changed == braids::SETTING_PITCH_RANGE) { shape = module->settings.pitch_range; text = pitch_range_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_PITCH_OCTAVE) { shape = module->settings.pitch_octave; text = octave_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_QUANTIZER_SCALE) { shape = module->settings.quantizer_scale; text = quantization_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_QUANTIZER_ROOT) { shape = module->settings.quantizer_root; text = note_values[shape]; } if (module && module->last_setting_changed == braids::SETTING_VCO_FLATTEN) { text = "FLAT"; } if (module && module->last_setting_changed == braids::SETTING_VCO_DRIFT) { text = "DRFT"; } if (module && module->last_setting_changed == braids::SETTING_SIGNATURE) { text = "SIGN"; } nvgText(args.vg, textPos.x, textPos.y, text, NULL); } }; struct CornrowsXWidget : ModuleWidget { CornrowsXWidget(CornrowsX *module) { setModule(module); box.size = Vec(8 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT); { SvgPanel *panel = new SvgPanel(); panel->setBackground(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Cornrows.svg"))); panel->box.size = box.size; addChild(panel); } { CornrowsXDisplay *display = new CornrowsXDisplay(); display->box.pos = Vec(8, 32); display->box.size = Vec(80., 34.); display->module = module; addChild(display); } const float x1 = 4.; const float xh = 30.; const float x2 = x1 + xh; const float x3 = x1 + 2 * xh; const float x4 = x1 + 3 * xh; // const float x5 = x1+4*xh; // const float x6 = x1+5*xh; const float y1 = 115; const float yh = 36.; addParam(createParam<sp_Encoder>(Vec(x3 - 5, 68), module, CornrowsX::SHAPE_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 - 1 * yh), module, CornrowsX::TRIG_INPUT)); addParam(createParam<sp_Trimpot>(Vec(x2, y1 - 1 * yh), module, CornrowsX::TRIG_DELAY_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x1, y1 + 0 * yh), module, CornrowsX::ATT_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 0 * yh), module, CornrowsX::DEC_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + yh), module, CornrowsX::PITCH_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + yh), module, CornrowsX::FINE_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x3, y1 + yh), module, CornrowsX::COARSE_PARAM)); addParam(createParam<sp_Trimpot>(Vec(x4, y1 + yh), module, CornrowsX::PITCH_OCTAVE_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x1, y1 + 2 * yh), module, CornrowsX::ROOT_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 2 * yh), module, CornrowsX::SCALE_PARAM)); addParam(createParam<sp_Trimpot>(Vec(x4, y1 + 2 * yh), module, CornrowsX::PITCH_RANGE_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 3 * yh), module, CornrowsX::FM_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x3, y1 + 3 * yh), module, CornrowsX::FM_PARAM)); addParam(createParam<sp_Trimpot>(Vec(x4, y1 + 3 * yh), module, CornrowsX::AD_MODULATION_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 4 * yh), module, CornrowsX::TIMBRE_INPUT)); addParam(createParam<sp_Trimpot>(Vec(x2, y1 + 4 * yh), module, CornrowsX::MODULATION_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x3, y1 + 4 * yh), module, CornrowsX::TIMBRE_PARAM)); addParam(createParam<sp_Trimpot>(Vec(x4, y1 + 4 * yh), module, CornrowsX::AD_TIMBRE_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 5 * yh), module, CornrowsX::COLOR_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x3, y1 + 5 * yh), module, CornrowsX::COLOR_PARAM)); addParam(createParam<sp_Trimpot>(Vec(x4, y1 + 5 * yh), module, CornrowsX::AD_COLOR_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x1, y1 + 5.75 * yh), module, CornrowsX::BITS_PARAM)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 5.75 * yh), module, CornrowsX::RATE_PARAM)); addOutput(createOutput<sp_Port>(Vec(x4, y1 + 5.75 * yh), module, CornrowsX::OUT_OUTPUT)); } void appendContextMenu(Menu *menu) override { CornrowsX *braids = dynamic_cast<CornrowsX *>(module); assert(braids); struct CornrowsXSettingItem : MenuItem { CornrowsX *braids; uint8_t *setting = NULL; uint8_t offValue = 0; uint8_t onValue = 1; void onAction(const event::Action &e) override { // Toggle setting *setting = (*setting == onValue) ? offValue : onValue; } void step() override { rightText = (*setting == onValue) ? "✔" : ""; MenuItem::step(); } }; struct CornrowsXLowCpuItem : MenuItem { CornrowsX *braids; void onAction(const event::Action &e) override { braids->lowCpu = !braids->lowCpu; } void step() override { rightText = (braids->lowCpu) ? "✔" : ""; MenuItem::step(); } }; struct CornrowsXPaquesItem : MenuItem { CornrowsX *braids; void onAction(const event::Action &e) override { braids->paques = !braids->paques; } void step() override { rightText = (braids->paques) ? "✔" : ""; MenuItem::step(); } }; menu->addChild(construct<MenuLabel>()); menu->addChild(construct<MenuLabel>(&MenuLabel::text, "Options")); menu->addChild(construct<CornrowsXSettingItem>(&MenuItem::text, "META", &CornrowsXSettingItem::setting, &braids->settings.meta_modulation)); menu->addChild(construct<CornrowsXSettingItem>(&MenuItem::text, "AUTO", &CornrowsXSettingItem::setting, &braids->settings.auto_trig)); menu->addChild(construct<CornrowsXSettingItem>(&MenuItem::text, "|\\VCA", &CornrowsXSettingItem::setting, &braids->settings.ad_vca)); menu->addChild(construct<CornrowsXSettingItem>(&MenuItem::text, "FLAT", &CornrowsXSettingItem::setting, &braids->settings.vco_flatten, &CornrowsXSettingItem::onValue, 4)); menu->addChild(construct<CornrowsXSettingItem>(&MenuItem::text, "DRFT", &CornrowsXSettingItem::setting, &braids->settings.vco_drift, &CornrowsXSettingItem::onValue, 4)); menu->addChild(construct<CornrowsXSettingItem>(&MenuItem::text, "SIGN", &CornrowsXSettingItem::setting, &braids->settings.signature, &CornrowsXSettingItem::onValue, 4)); menu->addChild(construct<CornrowsXLowCpuItem>(&MenuItem::text, "Low CPU", &CornrowsXLowCpuItem::braids, braids)); menu->addChild(construct<CornrowsXPaquesItem>(&MenuItem::text, "Paques", &CornrowsXPaquesItem::braids, braids)); } }; Model *modelCornrowsX = createModel<CornrowsX, CornrowsXWidget>("CornrowsX");
0314ab76270485b6adb684c7b36b9fec4a2f21e3
e4ed9407640709a207a2ed51c31d7c3ebd347927
/example/reducer.cpp
55bfabb8b79939f935e0503b0135f5e5211bb1ab
[]
no_license
ra1u/tubez
34618f85c2bd1670ed7b38dd559891f0249193c4
29da96653f261968afcc0ffdf00020dd9adb9c3d
refs/heads/master
2021-05-06T14:23:33.926225
2017-09-24T11:06:39
2017-12-10T14:39:01
113,358,393
13
0
null
null
null
null
UTF-8
C++
false
false
728
cpp
reducer.cpp
#include "../src/tubez.hpp" #include "main_common.hpp" static auto sum() { return tubez::reducer(uint64_t(0), [](uint64_t &a, const uint64_t b) -> void { a += b; }); } static auto sum2(){ return tubez::reducer(uint64_t(0), [](uint64_t& a,const uint64_t val){ a += val; }); } auto reducer_tube(uint64_t N) { auto t = tubez::iter(uint64_t(0), [](auto a) { return a + 1; }) | tubez::take_while([N](auto n) { return n < N; }) | sum(); return run_push(t); } uint64_t reducer_for(uint64_t N) { uint64_t r = 0; for (uint64_t i = 0; i < N; ++i) { r += i; } return r; } int main(int argc, char **argv) { return main_perf_helper(argc, argv, reducer_tube, reducer_for); }
8d028eaaa8fabcd9466eea8b6e429d5324a1df9e
e571f8dbe2e3459c82ae50cecfb9405ae7c8acce
/src/onnx/parse_softmax.cpp
635871339af7e3dc7230440cafcc07d16f6d3b96
[ "MIT" ]
permissive
barathum000/AMDMIGraphX
423b7f9fb8d959c7b4117ec286e44ba66ba044bf
fb39e5e4ae4170f6fb4a366315a6cd53008dfccc
refs/heads/master
2023-09-05T16:12:28.778972
2021-11-09T13:25:59
2021-11-09T13:25:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,198
cpp
parse_softmax.cpp
#include <migraphx/onnx/op_parser.hpp> #include <migraphx/ranges.hpp> #include <migraphx/make_op.hpp> #include <migraphx/onnx/checks.hpp> #include <migraphx/instruction.hpp> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { namespace onnx { struct parse_softmax : op_parser<parse_softmax> { std::vector<op_desc> operators() const { return {{"Softmax", "softmax"}, {"LogSoftmax", "logsoftmax"}}; } instruction_ref parse(const op_desc& opd, const onnx_parser& parser, const onnx_parser::node_info& info, const std::vector<instruction_ref>& args) const { // default axis value is -1 for opset 13 int64_t axis = -1; // axis value is 1 for previous opset versions if(parser.opset_version < 13) { axis = 1; } if(contains(info.attributes, "axis")) { axis = parser.parse_value(info.attributes.at("axis")).at<int>(); } return info.add_instruction(make_op(opd.op_name, {{"axis", axis}}), args); } }; } // namespace onnx } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx
573d3f38d87976a82423e75582ed4bcc3acc9e77
7bb3f6028fe9ba1b04e005ed9dc20eabb30e5dda
/NumberSet.cpp
e8bcacffaa510ac8204d07efabbc5822db0bc2b8
[]
no_license
HWeldon/VectorProject
3197f2d3468ce2e6934b966673df79f623974892
b5d2cd5601ff40b1835f496a7a90068b627bb5ed
refs/heads/master
2021-01-19T13:33:30.475422
2015-03-03T08:11:04
2015-03-03T08:11:04
31,528,414
0
0
null
null
null
null
UTF-8
C++
false
false
1,857
cpp
NumberSet.cpp
#include <iostream> #include <algorithm> #include <vector> #include "NumberSet.h" using namespace std; NumberSet :: NumberSet() { } void NumberSet :: add(int A) { // Check to see if user input is already in the set // warn user if found if (find(v_set.begin(), v_set.end(), A) != v_set.end()) { cout << endl; cout << "Number already in set."; cout << endl; } // If user input is not already in set, add the // input to the vector else { v_set.push_back(A); } } void NumberSet :: remove(int A) { // If set contains user number, remove it from set. if (find(v_set.begin(), v_set.end(), A) != v_set.end()) { vector<int>::iterator position = find(v_set.begin(), v_set.end(), A); if (position != v_set.end()) { v_set.erase(position); } } // If user number is not in set, warn user else { cout << endl; cout << "Number not in set."; cout << endl; } } void NumberSet :: clear() { // If set is not empty, clear it if(!v_set.empty()) { v_set.clear(); cout << "The set is now empty."; cout << endl; cout << endl; } // if set is already empty, warn user else { cout << "Set already empty."; cout << endl; cout << endl; } } int NumberSet :: size() { // If set is empty, return 0 for size if(v_set.empty()) { cout << "The size of the set is: 0"; cout << endl; cout << endl; } // If set contains values, return size of the set else { cout << "The size of the set is: " << v_set.size(); cout << endl; cout << endl; } } void NumberSet :: output() { cout << "The set is: "; for (vector<int>::const_iterator i = v_set.begin(); i != v_set.end(); ++i) { cout << *i << ' '; } cout << endl; cout << endl; }
317523ded73800c557ba8e3d50fa01947ba660d5
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Walkyrie Dx9/Valkyrie/Moteur/Polygonlist.cpp
77df4ac2151cd66a414d0861fa042b33d8bb9bdd
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
ISO-8859-1
C++
false
false
16,082
cpp
Polygonlist.cpp
#include "Polygonlist.h" // ************************ Classe CPolygonContainer ************************* // Cette classe, qui représente un noeud de la liste, permet de contenir un // polygone, ou une adresse vers un polygone si la liste est une copie d'une // autre liste. // Constructeur de la classe E_PolygonContainer. CPolygonContainer::CPolygonContainer() { p_Polygon = NULL; p_Next = NULL; p_IsCopy = false; } // Destructeur de la classe E_PolygonContainer. CPolygonContainer::~CPolygonContainer() { // On nettoie la ressource, à condition que celle-ci soit locale. if ( p_Polygon != NULL && p_IsCopy == false ) { delete p_Polygon; p_Polygon = NULL; } } // Obtient le polygone, ou l'adresse du polygone. CPolygon* CPolygonContainer::GetPolygon() { return p_Polygon; } // Définit le polygone, ou l'adresse du polygone. void CPolygonContainer::SetPolygon( CPolygon* Polygon, bool IsCopy ) { p_Polygon = Polygon; p_IsCopy = IsCopy; } // Obtient le pointeur vers le noeud suivant. CPolygonContainer* CPolygonContainer::GetNext() { return p_Next; } // Définit le pointeur vers le noeud suivant. void CPolygonContainer::SetNext( CPolygonContainer* Next ) { p_Next = Next; } // ************************** Classe CPolygonList **************************** // Cette classe est une liste de polygones, utilisée par exemple pour la // détection des collisions. Elle permet un accès simplifié aux données // spaciales représentant un objet, et mets à disposition des outils comme la // création d'une boîte de collisions pour l'objet. // Constructeur de la classe E_PolygonList. CPolygonList::CPolygonList() { p_First = NULL; p_Current = NULL; p_FirstBox = NULL; p_CurrentBox = NULL; p_PolygonCount = 0; } // Destructeur de la classe E_PolygonList. CPolygonList::~CPolygonList() { // On appelle la fonction de nettoyage de la liste. ReleaseList(); } // Cette fonction permet l'ajout d'un polygone dans la liste. bool CPolygonList::AddPolygon( CPolygon* Polygon, bool IsCopy ) { // On commence par tester si l'objet est valide. if ( Polygon == NULL ) { // Si ce n'est pas le cas, on retourne une erreur. return false; } // Ensuite, on crée un nouveau conteneur. CPolygonContainer* p_New = new CPolygonContainer(); // Puis, on teste si le conteneur a été correctement alloué en mémoire. if ( p_New == NULL ) { // Si ce n'est pas le cas, on retourne une erreur. return false; } // On alloue ensuite le pointeur vers le polygone dans le conteneur. p_New->SetPolygon( Polygon, IsCopy ); // On teste si le premier conteneur de la liste d'objets a déjà été crée. if ( p_First == NULL ) { // Si ce n'est pas le cas, on définit le nouveau conteneur comme // premier conteneur de la liste d'objets, et on définit le pointeur // courant sur le premier conteneur de la liste. p_First = p_New; p_Current = p_First; } else { // Si le premier conteneur est défini, on ajoute le nouveau conteneur à // la fin de la liste. On commence par définir le pointeur courant sur // le premier conteneur. p_Current = p_First; // Puis, on passe toute la liste d'objets, jusqu'à pointer sur le // dernier objet de la liste. while ( p_Current->GetNext() != NULL ) { // On passe à l'objet suivant. p_Current = p_Current->GetNext(); } // Maintenant, on sait que p_Current contient le dernier objet de la // liste. On définit le pointeur vers le prochain conteneur sur le // nouveau conteneur que l'on a crée. p_Current->SetNext( p_New ); } // On additionne le compteur interne de polygones. p_PolygonCount++; // Pour finir, on retourne un message de réussite. return true; } // Cette fonction permet l'ajout d'un polygone dans la liste. bool CPolygonList::AddPolygon( D3DXVECTOR3 Vertex1, D3DXVECTOR3 Vertex2, D3DXVECTOR3 Vertex3 ) { // On crée un nouveau polygone. CPolygon* Polygon = new CPolygon( Vertex1, Vertex2, Vertex3 ); // Puis, on teste si le polygone a bien été crée en mémoire. if ( Polygon == NULL ) { return false; } // Pour finir, on tente d'ajouter le polygone à la liste, et on retourne // la réponse. return AddPolygon( Polygon, false ); } // Cette fonction permet de créer une liste depuis un objet. bool CPolygonList::CreateListFromMesh( LPD3DXMESH Mesh ) { // On teste d'abord si l'objet est valide. if ( Mesh == NULL ) { return false; } D3DXVECTOR3 Vertex[3]; D3DXVECTOR3 CurVertex; WORD* p_Indices; D3DXVECTOR3* p_Vertices; // Puis, on obtient le nombre de faces et d'index contenus dans l'objet. DWORD NbVertices = Mesh->GetNumVertices(); DWORD NbFaces = Mesh->GetNumFaces(); // On verrouille ensuite le buffer d'index, ... if ( FAILED( Mesh->LockIndexBuffer( D3DLOCK_READONLY, (void**)&p_Indices ) ) ) { // Si le verrouillage échoue, on retourne une erreur. return false; } // ... ainsi que le buffer de sommets. if ( FAILED( Mesh->LockVertexBuffer( D3DLOCK_READONLY, (void**)&p_Vertices ) ) ) { // Si le verrouillage échoue, on retourne une erreur. return false; } // On extrait ensuite les données nécessaires à l'initialisation. for ( DWORD i = 0; i < NbFaces; i++ ) { // On copie les données du polygone. for ( DWORD j = 0; j < 3; j++ ) { CurVertex = (float*)&p_Vertices[p_Indices[3*i+j]]; Vertex[j] = CurVertex; } // Puis, on tente d'ajouter le polygone dans la liste. if ( AddPolygon( Vertex[0], Vertex[1], Vertex[2] ) == false ) { // Si l'ajout échoue, on déverrouille les buffers, et on retourne // une erreur. Mesh->UnlockVertexBuffer(); Mesh->UnlockIndexBuffer(); return false; } } // Puis, on déverrouille les buffers, ... Mesh->UnlockVertexBuffer(); Mesh->UnlockIndexBuffer(); // ... et on retourne le message de réussite. return true; } // Cette fonction teste si un polygone existe déjà dans la liste. bool CPolygonList::Exist( CPolygon* Polygon ) { p_Current = p_First; // On passe toute la liste en revue. while ( p_Current != NULL ) { // Puis, on teste si le polygone existe déjà dans la liste. if ( p_Current->GetPolygon() == Polygon ) { // Si c'est le cas, on retourne une réponse positive. return true; } // Sinon, on passe au prochain polygone. p_Current = p_Current->GetNext(); } // Si aucun polygone n'est trouvé, on retourne une réponse négative. return false; } // Cette fonction permet de créer une boîte de collisions pour l'objet. void CPolygonList::CreateBoundingBox() { D3DXVECTOR3 Max = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); D3DXVECTOR3 Min = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); p_Current = p_First; // On passe toute la liste des polygones en revue. while ( p_Current != NULL ) { // Puis, on extrait chaque sommet. for ( int i = 0; i < 3; i++ ) { D3DXVECTOR3 v = p_Current->GetPolygon()->GetVertex( i ); // Pour chaque sommet, on recherche si la valeur courante est // plus grande ou plus petite que les valeurs maximales et // minimales déjà trouvées. Si c'est le cas, on met à jour les // valeurs. Max = CMaths::GetMaxValue( Max, v ); Min = CMaths::GetMinValue( Min, v ); } // Puis, on passe au polygone suivant. p_Current = p_Current->GetNext(); } // Enfin, on inscrit les valeurs trouvées dans la boîte de collisions. p_BoundingBox.SetMax( Max ); p_BoundingBox.SetMin( Min ); CreateListBoundingBox (Min,Max); } // Obtient la boîte de collisions de l'objet. CBoundingBox& CPolygonList::GetBoundingBox() { return p_BoundingBox; } // Cette fonction permet de créer une sphère de collisions pour l'objet. void CPolygonList::CreateBoundingSphere() { D3DXVECTOR3 Max = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); D3DXVECTOR3 Min = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); p_Current = p_First; // On passe toute la liste des polygones en revue. while ( p_Current != NULL ) { // Puis, on extrait chaque sommet. for ( int i = 0; i < 3; i++ ) { D3DXVECTOR3 v = p_Current->GetPolygon()->GetVertex( i ); // Pour chaque sommet, on recherche si la valeur courante est // plus grande ou plus petite que les valeurs maximales et // minimales déjà trouvées. Si c'est le cas, on met à jour les // valeurs. Max = CMaths::GetMaxValue( Max, v ); Min = CMaths::GetMinValue( Min, v ); } // Puis, on passe au polygone suivant. p_Current = p_Current->GetNext(); } D3DXMATRIXA16 matIdentity; D3DXMatrixIdentity( &matIdentity ); p_BoundingSphere.SetSphere(matIdentity,Min,Max); } // Obtient la sphère de collisions de l'objet. CBoundingSphere& CPolygonList::GetBoundingSphere() { return p_BoundingSphere; } // Obtient le nombre de polygones de l'objet. int CPolygonList::GetCount() { return p_PolygonCount; } // Obtient le premier conteneur de polygone de la liste. CPolygonContainer* CPolygonList::GetFirst() { return p_First; } // Obtient le premier conteneur de polygone de la liste. CPolygonContainer* CPolygonList::GetFirstBox() { return p_FirstBox; } // Cette fonction permet de libérer les ressources de la liste. void CPolygonList::ReleaseList() { p_Current = p_First; // On détruit toute la liste d'objets. while ( p_Current != NULL ) { CPolygonContainer* p_Tmp = p_Current->GetNext(); delete p_Current; p_Current = p_Tmp; } p_First = NULL; p_Current = NULL; p_CurrentBox = p_FirstBox; // On détruit toute la liste d'objets. while ( p_CurrentBox != NULL ) { CPolygonContainer* p_Tmp = p_CurrentBox->GetNext(); delete p_CurrentBox; p_CurrentBox = p_Tmp; } p_FirstBox = NULL; p_CurrentBox = NULL; } void CPolygonList::RenduPolygonList() { } bool CPolygonList::CreateListBoundingBox (D3DXVECTOR3 BoxMin,D3DXVECTOR3 BoxMax) { //face 1 CPolygon* Polygon = new CPolygon( BoxMin, D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z), D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z) ); if(!AddPolygonBox(Polygon,false)) return false; Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z), D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z), D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z) ); if(!AddPolygonBox(Polygon,false)) return false; //face 2 Polygon = new CPolygon( D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z), D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z), D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z) ); if(!AddPolygonBox(Polygon,false)) return false; Polygon = new CPolygon( D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z), D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z), BoxMax); if(!AddPolygonBox(Polygon,false)) return false; //face 3 Polygon = new CPolygon( D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z), D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z), BoxMax); if(!AddPolygonBox(Polygon,false)) return false; Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z), D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z), BoxMax); if(!AddPolygonBox(Polygon,false)) return false; //face 4 Polygon = new CPolygon( BoxMin, D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z), D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z)); if(!AddPolygonBox(Polygon,false)) return false; Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z), D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z), D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z)); if(!AddPolygonBox(Polygon,false)) return false; //face 5 Polygon = new CPolygon( BoxMin, D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z), D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z)); if(!AddPolygonBox(Polygon,false)) return false; Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMin.y,BoxMax.z), D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMax.z), D3DXVECTOR3(BoxMax.x,BoxMin.y,BoxMin.z)); if(!AddPolygonBox(Polygon,false)) return false; //face 6 Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMin.z), D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z), D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z)); if(!AddPolygonBox(Polygon,false)) return false; Polygon = new CPolygon( D3DXVECTOR3(BoxMin.x,BoxMax.y,BoxMax.z), D3DXVECTOR3(BoxMax.x,BoxMax.y,BoxMin.z), BoxMax); if(!AddPolygonBox(Polygon,false)) return false; return true; } // Cette fonction permet l'ajout d'un polygone dans la liste. bool CPolygonList::AddPolygonBox( CPolygon* Polygon, bool IsCopy ) { // On commence par tester si l'objet est valide. if ( Polygon == NULL ) { // Si ce n'est pas le cas, on retourne une erreur. return false; } // Ensuite, on crée un nouveau conteneur. CPolygonContainer* p_New = new CPolygonContainer(); // Puis, on teste si le conteneur a été correctement alloué en mémoire. if ( p_New == NULL ) { // Si ce n'est pas le cas, on retourne une erreur. return false; } // On alloue ensuite le pointeur vers le polygone dans le conteneur. p_New->SetPolygon( Polygon, IsCopy ); // On teste si le premier conteneur de la liste d'objets a déjà été crée. if ( p_FirstBox == NULL ) { // Si ce n'est pas le cas, on définit le nouveau conteneur comme // premier conteneur de la liste d'objets, et on définit le pointeur // courant sur le premier conteneur de la liste. p_FirstBox = p_New; p_CurrentBox = p_FirstBox; } else { // Si le premier conteneur est défini, on ajoute le nouveau conteneur à // la fin de la liste. On commence par définir le pointeur courant sur // le premier conteneur. p_CurrentBox = p_FirstBox; // Puis, on passe toute la liste d'objets, jusqu'à pointer sur le // dernier objet de la liste. while ( p_CurrentBox->GetNext() != NULL ) { // On passe à l'objet suivant. p_CurrentBox = p_CurrentBox->GetNext(); } // Maintenant, on sait que p_Current contient le dernier objet de la // liste. On définit le pointeur vers le prochain conteneur sur le // nouveau conteneur que l'on a crée. p_CurrentBox->SetNext( p_New ); } // Pour finir, on retourne un message de réussite. return true; } // Cette fonction permet l'ajout d'un polygone dans la liste. bool CPolygonList::AddPolygonBox( D3DXVECTOR3 Vertex1, D3DXVECTOR3 Vertex2, D3DXVECTOR3 Vertex3 ) { // On crée un nouveau polygone. CPolygon* Polygon = new CPolygon( Vertex1, Vertex2, Vertex3 ); // Puis, on teste si le polygone a bien été crée en mémoire. if ( Polygon == NULL ) { return false; } // Pour finir, on tente d'ajouter le polygone à la liste, et on retourne // la réponse. return AddPolygonBox( Polygon, false ); }
93ae4201e10ac0da6981043ebf359c66ad8cec39
4fcc010579218a20d2ff59bcb9f2c688a354c05b
/MeKaSlug/State_LeonaDeb.cpp
c62d7a95ac97d693a285b144c8b78b99503f3931
[]
no_license
hki2345/MetalSlug
ef6bdc646800d2f14e242cd7370e44cb6d18145c
ecf3c220e78452288abab5e5b4eee86d93b27343
refs/heads/master
2020-03-30T03:30:22.479081
2019-04-01T10:40:11
2019-04-01T10:40:11
150,691,841
0
0
null
null
null
null
UHC
C++
false
false
3,265
cpp
State_LeonaDeb.cpp
#include "stdafx.h" #include "State_LeonaDeb.h" #include "ResourceManager.h" #include "Player_Leona.h" #include "Enemy_Walker.h" #include "Enemy_Bomb.h" #include "Enemy_Sarubian.h" #include "Enemy_MachineGun.h" #include "Enemy_Cannon.h" #include "Enemy_Tank.h" #include "Enemy_Bradley.h" #include "Item_Heavy.h" #include "One_Stage1.h" #include "One_Effect.h" #include "PlayerMgr.h" #include "Core.h" State_LeonaDeb::State_LeonaDeb() { } State_LeonaDeb::~State_LeonaDeb() { } void State_LeonaDeb::StateStart() { PlayerMgr::MainPlayer(m_p_Player); PlayerMgr::character(PlayerMgr::Play_Character::Leona); } void State_LeonaDeb::StateUpdate() { if (KEYMANAGER.KEY_DOWN("Value_Debug")) { CORE.Value_Debug_Switch(); } if (KEYMANAGER.KEY_DOWN("Obj_Debug")) { CORE.Obj_Debug_Switch(); } if (KEYMANAGER.KEY_PRESS("CamerUp")) { MoveCamera(Vector2f::Up * CAMERA_SPD * DELTATIME); } if (KEYMANAGER.KEY_PRESS("CamerDown")) { MoveCamera(Vector2f::Down * CAMERA_SPD * DELTATIME); } if (KEYMANAGER.KEY_PRESS("CamerLeft")) { MoveCamera(Vector2f::Left * CAMERA_SPD * DELTATIME); } if (KEYMANAGER.KEY_PRESS("CamerRight")) { MoveCamera(Vector2f::Right * CAMERA_SPD * DELTATIME); } if (KEYMANAGER.KEY_DOWN("Debug")) { CORE.ActingStateChanger(L"Game"); } } void State_LeonaDeb::Setting_Image() { StateOfOne_Create<One_Stage1>(); m_p_Player = StateOfOne_Create<Player_Leona>(); /* One_Effect* Test = StateOfOne_Create<One_Effect>(); Test->Start(One_Effect::Effect_Type::BULLET, { 500, 300 });*/ /*for (size_t i = 0; i < 5; i++) { StateOfOne_Create<Enemy_Walker>(); StateOfOne_Create<Enemy_Bomb>(); StateOfOne_Create<Enemy_MachineGun>(); StateOfOne_Create<Enemy_Cannon>(); StateOfOne_Create<Enemy_Sarubian>(); StateOfOne_Create<Enemy_Tank>(); StateOfOne_Create<Enemy_Bradley>(); }*/ StateOfOne_Create<Item_Heavy>(); m_Wchar_Map = L"Stage1_Collider.bmp"; } void State_LeonaDeb::Setting_Collider() { COLLIDERMANAGER.Link(Name(), L"Player", L"Enemy"); COLLIDERMANAGER.Link(Name(), L"Player", L"Item"); COLLIDERMANAGER.Link(Name(), L"Player", L"Weapon"); COLLIDERMANAGER.Link(Name(), L"Enemy", L"Weapon"); } void State_LeonaDeb::All_SetUp() { CameraPos({0, 200}); Setting_Image(); Setting_Collider(); } void State_LeonaDeb::Value_DebugRender() { // 특정 포맷의 문자열을 소스 문자열로 복사해준다. WCHAR Str[100] = { 0, }; static float Frame = 0; Frame++; // DeltaTime : 1 = 1 : x; swprintf_s(Str, L"FPS: %3.2f", 1 / TIMEMANAGER.DeltaTime()); TEXT_OUT(100, 20, Str); swprintf_s(Str, L"Mouse Pos: %d, %d", CORE.GetMousePos().X, CORE.GetMousePos().Y); TEXT_OUT(100, 40, Str); swprintf_s(Str, L"Player Pos: %f, %f", m_p_Player->pos().X, m_p_Player->pos().Y); TEXT_OUT(100, 60, Str); swprintf_s(Str, L"Player To Mouse Dis: %f", MathManager::Inst().Distance(CORE.GetMousePos(), m_p_Player->pos())); TEXT_OUT(100, 80, Str); swprintf_s(Str, L"Player To Mouse Radian: %f", MathManager::Inst().Degree(CORE.GetMousePos(), m_p_Player->pos())); TEXT_OUT(100, 100, Str); Positionf DirPos = MathManager::Inst().PntToPnt_Dir(CORE.GetMousePos(), m_p_Player->pos()); swprintf_s(Str, L"Player To Mouse Dir: %f %f", DirPos.X, DirPos.Y); TEXT_OUT(100, 120, Str); }
6460af2d5268c4de8d97813b397a4bde2f933e9d
e8244e5a28d8a2b01d938a6eb00e4d71583a9047
/TempSensorTest/TempSensorTest.ino
5dfe1eaf183b78f26536903eda0f1a53a2025041
[]
no_license
carlosgj/Temperature-Monitor
e6fd0f0fdd266556ecea8e083ebbe13eec64e645
12303c2d9d6a5787ab30c5e769e783c2e1ed3664
refs/heads/master
2022-01-21T18:50:50.143196
2021-12-23T06:17:51
2021-12-23T06:17:51
160,013,142
0
0
null
null
null
null
UTF-8
C++
false
false
926
ino
TempSensorTest.ino
#include <OneWire.h> OneWire myWire(11); #define SERIAL_ENABLE uint8_t addr[8]; void setup() { Serial.begin(115200); while (!Serial) { } for(uint8_t i=0; i<8; i++){ addr[i] = 0; } myWire.reset_search(); myWire.search(addr); Serial.print("Found address: "); for(uint8_t i=0; i<8; i++){ Serial.print(addr[i], HEX); } Serial.println(); //Write config register myWire.reset(); myWire.select(addr); } void loop() { myWire.reset(); myWire.select(addr); myWire.write(0x44); delay(1000); myWire.reset(); myWire.select(addr); myWire.write(0xbe); uint8_t result[9]; for(uint8_t i=0; i<9; i++){ result[i] = myWire.read(); } Serial.print("Got: "); for(uint8_t i=0; i<9; i++){ Serial.print(result[i], HEX); Serial.print(" "); } Serial.println(); int16_t temp; temp = *((int16_t *)result); Serial.print("Temp: "); Serial.println(temp, HEX); }
e0df05d77bec341ed4b7361541ec596d36b4c444
d81d794c77d759e0e14f9bd787fe2cfa82764e8d
/eYRC-AB#6338_Code/Arduino/task-4-main/rgb_test.ino
ad032b8a23cab52e75a3ca65072c2570e1d4c911
[]
no_license
ArshGoyal25/Eyantra
8f70efaf2698e92b27d02bad6f1afb5b376efffa
d2938d42ff3f3467d91513d3ba3ea101e382130c
refs/heads/main
2023-03-27T09:53:43.310642
2021-03-28T08:00:22
2021-03-28T08:00:22
352,268,774
0
0
null
null
null
null
UTF-8
C++
false
false
1,845
ino
rgb_test.ino
/* * Team Id: #6338 * Author List: Arnav Agarwal, Arsh Gayal, Sujith K * Filename: rgb_test.ino * Theme: Ant Bot * Functions: rgb, setColor * Global Variables: All global variables are declared in the header file line.h */ /* * Function Name: rgb * Input: a character * Output: none * Logic: This function is used to glow the correct colour of the RGB LED. * We are doing so by the checking the ASCII value of the character sent by the Raspberry Pi through the serial port. * Example Call: rgb(R) */ void rgb(char n) { if(n=='R') { setColor(0, 255, 255); // RGB LED will glow red in colour for one second and then turn off. delay(1000); setColor(255,255,255); } else if (n=='B') { setColor(255, 0, 255); // RGB LED will glow blue in colour for one second and then turn off. delay(1000); setColor(255,255,255); } else if (n=='G') { setColor(255, 255, 0); // RGB LED will glow green in colour for one second and then turn off. delay(1000); setColor(255,255,255); } else if (n=='Y') { setColor(0,255,0); // RGB LED will glow yellow in colour for one second and then turn off. delay(1000); setColor(255,255,255); } } /* * Function Name:setColor * Input: redValue, greenValue, blueValue. These parameters are the analog values used to turn on the LED with the correct colour. * Output: none * Logic: This function is used to set the analog values of the red, green and blue analog pins that have been declared. * We are doing this using the basic analogWrite function which is present in the IDE. * Example Call: setColor(0,255,255) */ void setColor(int redValue, int greenValue, int blueValue) { analogWrite(redPin, redValue); analogWrite(greenPin, greenValue); analogWrite(bluePin, blueValue); }
89fca634ba2febdcd9855ea1ec0d755b1948dbcb
904c714fb778276ec4a75c9987099bfea8eafe3a
/day04/day04_1.cpp
2d0111ac1407e61e8645e030a228c1cb8af16ff3
[]
no_license
chriswpark00/C_Algorithm
c77ce9386e902dad88409ed34c030aa9ce3501be
fce5ecc5859f84563018450c911c2e537c6835fa
refs/heads/master
2022-11-13T21:18:38.172486
2020-07-11T14:24:27
2020-07-11T14:24:27
273,645,941
0
0
null
2020-06-30T05:05:52
2020-06-20T05:39:54
C++
UHC
C++
false
false
562
cpp
day04_1.cpp
/* 모듈화 프로그래밍. 헤더파일 분리 - 함수와 구조체를 분리 */ #include "day04_01_header.h" /* 인원수 입력받고 이름 과 성적을 입력받고 출력: 이름: -- 점 */ int main() { int n = 0; S *s; printf("인원수: "); scanf("%d", &n); s = (S *) calloc(n, sizeof(S)); for(int i = 0; i < n; i++){ printf("이름: "); scanf("%s", s[i].name); //%s는 &없이 입력받음 printf("점수: "); scanf("%d", &s[i].score); } show(s, n); return 0; }
625aa8b101a2a3ef65fb09bee3ce1c5560d0eb37
69b4f7c49f18fc193f49275a2d32ffbcbe70471d
/Codeforces/E. Blood Cousins.cpp
f238e943a63f7a693fa7573d1c25cdabe27327a9
[]
no_license
TD2106/Competitive-Programming
05f322a14f1e7a1d62633b713f1416ab0c547b3b
2905c9d5f36909330fc3637f5461aaba8928a154
refs/heads/master
2020-04-03T12:59:49.790124
2019-09-21T14:51:08
2019-09-21T14:51:08
155,270,877
0
0
null
null
null
null
UTF-8
C++
false
false
1,580
cpp
E. Blood Cousins.cpp
#include <bits/stdc++.h> #define bug(x) cout << #x << " = " << x << endl #define fr(x) freopen(x,"r",stdin) #define fw(x) freopen(x,"w",stdout) #define F first #define S second #define mp make_pair using namespace std; typedef long long int ll; typedef pair<int,int> pii; typedef vector<int> vi; int parent[100005][20]={0},level[100005]={0},n,q,dfsOrder[200005],idx=0,Ti,t,u,v; pii euler[100005],levelIndex[200005]; vi root; vector<vi> child; void dfs(int x){ level[x]=level[parent[x][0]]+1; dfsOrder[++idx]=x; euler[x].F=idx; for(int t:child[x]) dfs(t); dfsOrder[++idx]=x; euler[x].S=idx; } int walk(int s,int p){ for(int i=0;i<=19;i++){ if(p&(1<<i)) s=parent[s][i]; } return s; } int main(){ ios_base::sync_with_stdio(0); cin>>n; child.resize(n+1); for(int i=1;i<=n;i++){ cin>>parent[i][0]; if(!parent[i][0]){ root.push_back(i); } child[parent[i][0]].push_back(i); } for(int t:root) dfs(t); for(int i=1;i<=19;i++){ for(int j=1;j<=n;j++){ parent[j][i]=parent[parent[j][i-1]][i-1]; } } for(int i=1;i<=2*n;i++) levelIndex[i]={level[dfsOrder[i]],i}; sort(levelIndex+1,levelIndex+1+2*n); cin>>q; while(q--){ cin>>u>>v; t=walk(u,v); if(t==0) cout<<0<<endl; else{ Ti=lower_bound(levelIndex+1,levelIndex+1+2*n,mp(level[u],euler[t].S))-lower_bound(levelIndex+1,levelIndex+1+2*n,mp(level[u],euler[t].F)); Ti/=2; cout<<Ti-1<<endl; } } return 0; }
65582fab6e442366d056aebe86b3a9d65e3e5657
8f0c19443475e22472e9b6b78eeb14d58523b0d9
/keithley1/keithley1/keithley1Dlg.cpp
3d5c0f3d7a5d8131f138632b81b70cfc870986ce
[]
no_license
asdfhhh/visualstudio-projects-ihep
a27993d9ae568b9ec53ab8998ef54c65565ff655
8e1d936f7db31c3f3b8c182dc2f327c54d471d13
refs/heads/master
2021-01-10T14:10:46.650519
2019-08-12T02:57:32
2019-08-12T02:57:32
46,844,293
0
0
null
null
null
null
GB18030
C++
false
false
17,879
cpp
keithley1Dlg.cpp
// keithley1Dlg.cpp : 实现文件 // #include "stdafx.h" #include "keithley1.h" #include "keithley1Dlg.h" #include "DlgProxy.h" #include "IEEE-C.H" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // Ckeithley1Dlg 对话框 IMPLEMENT_DYNAMIC(Ckeithley1Dlg, CDialog); Ckeithley1Dlg::Ckeithley1Dlg(CWnd* pParent /*=NULL*/) : CDialog(Ckeithley1Dlg::IDD, pParent) , ZRC_flag(false) { m_str_read = _T("Welcome to the soft of silicon measurement!"); StrFileName="data.txt"; ZRC_flag=false; m_waittime=4; m_maxvoltage=11; m_stepvoltage=4; operation_flag=false; m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_pAutoProxy = NULL; } Ckeithley1Dlg::~Ckeithley1Dlg() { // 如果该对话框有自动化代理,则 // 将此代理指向该对话框的后向指针设置为 NULL,以便 // 此代理知道该对话框已被删除。 if (m_pAutoProxy != NULL) m_pAutoProxy->m_pDialog = NULL; } void Ckeithley1Dlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT2,StrFileName); DDX_CBIndex(pDX, IDC_COMBO1, m_waittime); DDX_CBIndex(pDX, IDC_COMBO2, m_maxvoltage); DDX_CBIndex(pDX, IDC_COMBO3, m_stepvoltage); } BEGIN_MESSAGE_MAP(Ckeithley1Dlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_CLOSE() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDOK, &Ckeithley1Dlg::OnBnClickedOk) ON_BN_CLICKED(IDC_BUTTON1, &Ckeithley1Dlg::OnBnClickedButton1) ON_BN_CLICKED(IDCANCEL, &Ckeithley1Dlg::OnBnClickedCancel) ON_BN_CLICKED(IDC_BUTTON2, &Ckeithley1Dlg::OnBnClickedButton2) ON_EN_CHANGE(IDC_EDIT2, &Ckeithley1Dlg::OnEnChangeEdit2) ON_CBN_SELCHANGE(IDC_COMBO1, &Ckeithley1Dlg::OnCbnSelchangeCombo1) ON_LBN_SELCHANGE(IDC_LIST1, &Ckeithley1Dlg::OnLbnSelchangeList1) //ON_BN_CLICKED(IDC_WARM, &Ckeithley1Dlg::OnBnClickedWarm) ON_CBN_SELCHANGE(IDC_COMBO2, &Ckeithley1Dlg::OnCbnSelchangeCombo2) ON_BN_CLICKED(IDC_HELP, &Ckeithley1Dlg::OnBnClickedAbout) ON_BN_CLICKED(IDC_CHECK1, &Ckeithley1Dlg::OnBnClickedCheck1) END_MESSAGE_MAP() // Ckeithley1Dlg 消息处理程序 BOOL Ckeithley1Dlg::OnInitDialog() { CDialog::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 pCtrl = (CListBox *)GetDlgItem( IDC_LIST1 ) ; pCtrl->AddString(m_str_read); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void Ckeithley1Dlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void Ckeithley1Dlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标显示。 // HCURSOR Ckeithley1Dlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } // 当用户关闭 UI 时, // 如果控制器仍保持着它的某个对象,则自动化服务器不应退出。这些 // 消息处理程序确保如下情形: 如果代理仍在使用, // 则将隐藏 UI;但是在关闭对话框时, // 对话框仍然会保留在那里。 void Ckeithley1Dlg::OnClose() { if (CanExit()) CDialog::OnClose(); } void Ckeithley1Dlg::OnOK() { if (CanExit()) CDialog::OnOK(); } void Ckeithley1Dlg::OnCancel() { if (CanExit()) CDialog::OnCancel(); } BOOL Ckeithley1Dlg::CanExit() { // 如果代理对象仍保留在那里,则自动化 // 控制器仍会保持此应用程序。 // 使对话框保留在那里,但将其 UI 隐藏起来。 if (m_pAutoProxy != NULL) { ShowWindow(SW_HIDE); return FALSE; } return TRUE; } void Ckeithley1Dlg::OnBnClickedOk() { // TODO: Add your control notification handler code here //OnOK(); int m_gpib=0; char wrtbuf[100]="*RST"; char rdbuf[100]; long int status; unsigned long len; UpdateData(); ieee488_boardselect (m_gpib); if(ieee488_board_present()) { //Open and initialize the GPIB interface card ieee488_initialize (m_gpib, 0); } else { AfxMessageBox(_T("Invalid GPIB interface card.")); return; } operation_flag=true; ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Reset all bits of the following event registers to 0: strcpy(wrtbuf,"*CLS"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } //Select current function strcpy(wrtbuf,"FUNC 'CURR'"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } if(ZRC_flag) { //Enable zero check strcpy(wrtbuf,"SYST:ZCH ON"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Select cunrrent range 200nA strcpy(wrtbuf,"CURR:RANG:AUTO ON"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Trigger reading to be used as zero correction strcpy(wrtbuf,"INIT"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Turn zero correct off strcpy(wrtbuf,"SYST:ZCOR:STAT OFF"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Use last reading taken as zero corret value strcpy(wrtbuf,"SYST:ZCOR:ACQ"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Perform zero correction strcpy(wrtbuf,"SYST:ZCOR ON"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Disable zero check strcpy(wrtbuf,"SYST:ZCH OFF"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } } //Select source range strcpy(wrtbuf,"SOUR:VOLT:RANGE 500"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Set current limit 2mA strcpy(wrtbuf,"SOUR:VOLT:ILIM 2.5e-3"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Inital voltage set 0V strcpy(wrtbuf,"SOUR:VOLT 0"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Set voltage into data strcpy(wrtbuf,"FORM:ELEM READ"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Read the IDN strcpy(wrtbuf,"*IDN?"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Read the response string from the instrument with specific address ieee488_enter (rdbuf, 100, &len, 22, &status); m_str_read = rdbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in reading the response string from the GPIB instrument.")); return; } } //自定义消息 #define WM_UPDATEPOS WM_USER + 1000 //线程数据结构 typedef struct ThreadData { Ckeithley1Dlg* pDlg; int nIndex; int tmp_maxvoltage; int tmp_stepvoltage; int tmp_waittime; }THREADDATA; //工作线程 FILE* gnu_plot_pipe; UINT WorkThreadProc(LPVOID lParam) { THREADDATA* pData = (THREADDATA*)lParam; char wrtbuf[100]="*CLS"; char rdbuf[100]; char*pend; unsigned int data; char tmp_data[100]; gnu_plot_pipe= NULL; char *gnu_plot_filename= (char*)malloc(1000); //create the file if(!pData->pDlg->f_out.Open(pData->pDlg->StrFileName,CFile::modeCreate|CFile::modeReadWrite,NULL)) { AfxMessageBox(_T("Can not open the file! (HD is full?)")); } pData->pDlg->f_out.Close(); // open the pipe strcpy( gnu_plot_filename, "pgnuplot"); if((gnu_plot_pipe=_popen( gnu_plot_filename, "w"))==NULL) { AfxMessageBox(_T("Can not open the Online monitor!")); }; free( gnu_plot_filename); long int status; unsigned long len; double i_test; int wtime,mV,sV; CString tmp_str_read; mV=(pData->tmp_maxvoltage+1)*10; sV=pData->tmp_stepvoltage+1; wtime=(pData->tmp_waittime+1)*1000; //Select source range /*sprintf(wrtbuf,"SOUR:VOLT:RANGE 500"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } */ //Reset all bits of the following event registers to 0: ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } //************************** Voltage ON //************************** strcpy(wrtbuf,"SOUR:VOLT:STAT ON"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } //Change voltage for(int v_set=0;v_set<mV;v_set=v_set+sV) { sprintf(wrtbuf,"SOUR:VOLT %d",v_set); ieee488_send(22, wrtbuf, strlen(wrtbuf), &status); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } //reading /*strcpy(wrtbuf,"READ?"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); }*/ Sleep(wtime); //reading strcpy(wrtbuf,"READ?"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } //Read the response string from the instrument with specific address ieee488_enter (rdbuf, 100, &len, 22, &status); if (status) { AfxMessageBox(_T("Error in reading the response string from the GPIB instrument.")); } //i_test=atof(rdbuf); sprintf(tmp_data,"%d",v_set); pData->pDlg->f_out.Open(pData->pDlg->StrFileName,CFile::modeReadWrite,NULL); pData->pDlg->f_out.SeekToEnd(); pData->pDlg->f_out.Write(tmp_data,::strlen(tmp_data)); pData->pDlg->f_out.Write("\t",1); pData->pDlg->f_out.Write(rdbuf,::strlen(rdbuf)); pData->pDlg->f_out.Write("\r\n",2); pData->pDlg->f_out.Close(); CString tmp_name=_T("plot '")+pData->pDlg->StrFileName+_T("' with lp\n"); char *aux_string=(char*)tmp_name.GetBuffer(0); long len = wcslen (tmp_name); //the length of "salut" wcstombs (aux_string,tmp_name,len); //conversion to char * aux_string[len] = '\0'; //don't forget to put the caracter of terminated string //int strLength = tmp_name.GetLength() + 1; //memset(aux_string,0, sizeof(bool) * 100); //strncpy(aux_string, tmp_name,strLength); //sprintf(aux_string,"plot 'data.txt' with lp\n"); if(fwrite( aux_string, 1, strlen( aux_string), gnu_plot_pipe)!= strlen( aux_string)) { AfxMessageBox(_T("Can not open the Online monitor!")); }; fflush( gnu_plot_pipe); } strcpy(wrtbuf,"SOUR:VOLT:STAT OFF"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } AfxMessageBox(_T("Mesurement complete!")); if(gnu_plot_pipe)_pclose( gnu_plot_pipe); delete pData; return 0; } void Ckeithley1Dlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here UpdateData(); THREADDATA* pData = new THREADDATA; pData->nIndex = 1; pData->pDlg = this; pData->tmp_maxvoltage=m_maxvoltage; pData->tmp_stepvoltage=m_stepvoltage; pData->tmp_waittime=m_waittime; //启动工作线程 this->m_ThreadOne=AfxBeginThread(WorkThreadProc,pData); } void Ckeithley1Dlg::OnBnClickedCancel() { // TODO: Add your control notification handler code here char wrtbuf[100]="*RST"; long int status; if(operation_flag) { //Inital voltage set 0V strcpy(wrtbuf,"SOUR:VOLT 0"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //************************** Voltage OFF //************************** strcpy(wrtbuf,"SOUR:VOLT:STAT OFF"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } } //Reset all bits of the following event registers to 0: strcpy(wrtbuf,"*CLS"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } if(gnu_plot_pipe)_pclose( gnu_plot_pipe); OnCancel(); } void Ckeithley1Dlg::OnBnClickedButton2() { // TODO: Add your control notification handler code here //终止线程 if(this->m_ThreadOne) TerminateThread(this->m_ThreadOne->m_hThread,NULL); char wrtbuf[100]="*RST"; long int status; //************************** Voltage OFF //************************** strcpy(wrtbuf,"SOUR:VOLT:STAT OFF"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); return; } //Reset all bits of the following event registers to 0: strcpy(wrtbuf,"*CLS"); ieee488_send (22, wrtbuf, strlen(wrtbuf), &status); m_str_read = wrtbuf; pCtrl->AddString(m_str_read); if (status) { AfxMessageBox(_T("Error in writing the string command to the GPIB instrument.")); } if(gnu_plot_pipe)_pclose( gnu_plot_pipe); } void Ckeithley1Dlg::OnEnChangeEdit2() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here } void Ckeithley1Dlg::OnCbnSelchangeCombo1() { // TODO: Add your control notification handler code here } void Ckeithley1Dlg::OnLbnSelchangeList1() { // TODO: Add your control notification handler code here } void Ckeithley1Dlg::OnCbnSelchangeCombo2() { // TODO: Add your control notification handler code here } void Ckeithley1Dlg::OnBnClickedAbout() { CAboutDlg AboutDlg; AboutDlg.DoModal(); // TODO: Add your control notification handler code here } void Ckeithley1Dlg::OnBnClickedCheck1() { // TODO: Add your control notification handler code here ZRC_flag=!ZRC_flag; }
d92e6d5d208e39063186ea0b55fdd447da426a8c
d28312bf87d6f4e4aa2a921d54c00ff5384eb508
/test2.cpp
ab965e2c50e785cf9c629d2b5bd02b399352a312
[]
no_license
abhayjain09/repo2
10c3e03159a3691128f7d48bd467cb6fd4d7ab81
8064fe71b111e8a2aff51f0b1a02bd7e8e25aaf6
refs/heads/master
2020-05-04T21:28:19.996322
2019-04-04T10:18:08
2019-04-04T10:18:08
179,477,415
0
0
null
null
null
null
UTF-8
C++
false
false
25
cpp
test2.cpp
Abhay wants to meet MSD.
6667a19ac02053df015c6152ceac64cff655d3b2
ec07a78ff899c8fd24e9a41e5305e41643756cdd
/abc161_b.cpp
2cc5cd0089445c37c268029e20c12ab9108fe341
[]
no_license
jasonhuh/AtCoder-Solutions
90a72692f6b08126dbb869f70ca70829c2840863
ff0abe29215a3fb5b3e2229583878e6c7b1b564d
refs/heads/master
2022-12-22T16:42:28.190905
2020-10-05T13:39:52
2020-10-05T13:39:52
286,298,448
0
0
null
null
null
null
UTF-8
C++
false
false
677
cpp
abc161_b.cpp
#include <bits/stdc++.h> using namespace std; #define reps(i,s,n) for(int (i) = (s); (i) < (n); (i)++) #define rep(i,n) reps(i,0,n) typedef long long ll; typedef vector<int> vi; ll mod = 1e9+7; string solve() { int n, m, a; cin >> n >> m; vi nums; rep(i, n) { cin >> a; nums.push_back(a); } sort(nums.rbegin(), nums.rend()); int sum = accumulate(nums.begin(), nums.end(), 0); rep(i, m) { if (nums[i] / static_cast<double>(sum) < 1 / static_cast<double>(4 * m)) { return "No"; } } return "Yes"; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout << solve() << endl; }
e5f1046f946f04ce6a1d7b9c861f84464b116bce
f1a2325795dcd90f940e45a3535ac3a0cb765616
/development/TelecomServices/Monitoring/MON_Region.h
2f638ac775dd827e0091f02c80e3eb1f33ab7dab
[]
no_license
MoonStart/Frame
45c15d1e6febd7eb390b74b891bc5c40646db5de
e3a3574e5c243d9282778382509858514585ae03
refs/heads/master
2021-01-01T19:09:58.670794
2015-12-02T07:52:55
2015-12-02T07:52:55
31,520,344
0
0
null
null
null
null
UTF-8
C++
false
false
727
h
MON_Region.h
//Copyright(c) Tellabs Transport Group. All rights reserved #ifndef MON_REGION_H #define MON_REGION_H #include <TelCommon/TEL_BbRegionBase.h> #include "MON_Object.h" //This class is a MON_Object container. This is a //generic region. //##ModelId=3C0FE66E03B7 class MON_Region : public TEL_BbRegionBase { public: //Constructor. //##ModelId=3C0FE66E03C2 MON_Region(const FC_BbKey theKey); //Virtual destructor. //##ModelId=3C0FE66E03CD virtual ~MON_Region(void); //##ModelId=3C0FE66E03E0 virtual void Reset(void); //##ModelId=3C7170D9033F MON_Object& operator[] ( bbindex_t theIndex ) const { return static_cast<MON_Object&>( ElementAt(theIndex)); } }; #endif /* MON_REGION_H */
05a1197757492242aa032c206527ce4a9a389412
232bdf11e6d48d54876842f76e9e28d622590e83
/source/view/quploadfilewidget.cpp
ca109ee69e1ca48cf2b5be438f7890545a510815
[ "Apache-2.0" ]
permissive
c6supper/json_serialize_deserialize_qt
22a1c24a4d967a2ca9a8e9c8e6485f4ee581c62a
c70e89056900835221309f7c54dcca2e9fefe498
refs/heads/master
2023-05-27T06:13:39.867301
2021-06-15T01:47:49
2021-06-15T01:47:49
377,003,767
0
0
null
null
null
null
UTF-8
C++
false
false
6,184
cpp
quploadfilewidget.cpp
#include "quploadfilewidget.h" #include "qgenericcommand.h" #include "quploadprofilemodel.h" #include "qrservermessagebox.h" #include "qrserverstrtable.h" #include "quploadstatus.h" using namespace QRserver; QUploadFileWidget::QUploadFileWidget(QWidget *parent, const QString &tagName) : QRserverContainerWidget(parent) { setObjectName("QUploadFileWidget"); setTagName(tagName); setFixedSize(parent->width(), parent->height() - TAB_ROW_HEIGHT); m_tableWidget = new QUploadFileTableWidget(this); m_tableWidget->setHorizontalHeaderLabels(QStringList() << "" << TRANSLATE_STR_RSERVER_UPLOAD_NAME << TRANSLATE_STR_RSERVER_UPLOAD_TYPE << TRANSLATE_STR_RSERVER_UPLOAD_DATE << TRANSLATE_STR_RSERVER_UPLOAD_TYPEVALUE << TRANSLATE_STR_RSERVER_UPLOAD_FULLPATH << TRANSLATE_STR_RSERVER_UPLOAD_JOBID << TRANSLATE_STR_RSERVER_UPLOAD_LOCATION); m_tableWidget->setShowGrid(false); m_tableWidget->setFilterKeyColumn( QUploadFileTableWidget::ColumnIndexDisplayName); m_tableWidget->setColumnHidden(QUploadFileTableWidget::ColumnIndexFileType, true); m_tableWidget->setColumnHidden(QUploadFileTableWidget::ColumnIndexPathName, true); m_tableWidget->setColumnHidden(QUploadFileTableWidget::ColumnIndexJobId, true); m_tableWidget->setColumnHidden(QUploadFileTableWidget::ColumnIndexLocation, true); connect(m_tableWidget, SIGNAL(invalidRowChecked()), this, SLOT(onInvalidRowChecked())); m_filterPattern = new QBaseLineEdit(this); m_filterPattern->setObjectName("UploadFileFilterPattern"); m_filterPattern->setPlaceholderText(":Name"); m_filterPattern->setTitle("Filter"); connect(m_filterPattern, SIGNAL(textChanged(const QString &)), m_tableWidget, SLOT(onFilterPatternChanged(const QString &))); m_pBtnRefresh = new QPushButton(this); m_pBtnRefresh->setObjectName("UploadFileBtnRefresh"); m_pBtnRefresh->setText(TRANSLATE_STR_RSERVER_BTN_REFRESH); connect(m_pBtnRefresh, SIGNAL(clicked(bool)), SLOT(onGetFileList())); QHBoxLayout *bottomLayout = new QHBoxLayout(this); bottomLayout->setContentsMargins(8, 2, 5, 8); bottomLayout->setSpacing(8); bottomLayout->addWidget(m_filterPattern); bottomLayout->addWidget(m_pBtnRefresh); bottomLayout->addStretch(); m_bottomWidget = new QWidget(this); m_bottomWidget->setLayout(bottomLayout); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_tableWidget); layout->addWidget(m_bottomWidget); layout->addStretch(); } QUploadFileWidget::~QUploadFileWidget() { } void QUploadFileWidget::setColumnFilterPattern(const int column, const QString &pattern) { m_tableWidget->onColumnFilterPatternChanged(column, pattern); } void QUploadFileWidget::allocBackProgress() { } void QUploadFileWidget::onInvalidRowChecked() { QRserverMessageBox::Show(this, TRANSLATE_STR_RSERVER_WARNING, TRANSLATE_STR_RSERVER_UPLOAD_FILENAME_LENGTH_TOOLONG.arg( QUploadFileTableWidget::FileNameLengthLimitation), QMessageBox::Ok); } void QUploadFileWidget::onGetFileList() { m_tableWidget->clear(); QGenericCommand genericCommand(this, QUploadFileModel::CommandGetFileList); QVariant statusVar = issueCommand(genericCommand.toVariant(), QUploadFileModel::GetFileListTimeout, ""); if (!statusVar.isNull()) { QUploadStatus status(statusVar); switch (status.commandStatus()) { case QAbstractStatus::Succeed: break; default: QString message = QString("%1").arg( TRANSLATE_STR_RSERVER_UPLOAD_LOADFILES_FAILED.arg(status.commandStatus())); QRserverMessageBox::Show(this, TRANSLATE_STR_RSERVER_WARNING, message, QMessageBox::Ok); break; } } } const QVariantList QUploadFileWidget::fileModelList() const { return m_tableWidget->getCheckedItems(); } void QUploadFileWidget::setFileModelList(const QVariantList &fileModelList) { m_tableWidget->clear(); m_tableWidget->addItems(fileModelList); } QStringList QUploadFileWidget::getColumnValueList(const int column) const { return m_tableWidget->getColumnValueList(column); } void QUploadFileWidget::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); m_tableWidget->setSize(rect().width(), rect().height() - m_bottomWidget->height() - 5); m_tableWidget->setColumnWidth(0, (int)(width() * 0.05)); m_tableWidget->setColumnWidth(1, (int)(width() * 0.35)); m_tableWidget->setColumnWidth(2, (int)(width() * 0.28)); m_tableWidget->setColumnWidth(3, (int)(width() * 0.32 + 1)); m_tableWidget->setMaxVisibleRows(m_tableWidget->height() / 30 - 1); } void QUploadFileWidget::translate(const QFont &font) { m_tableWidget->setHorizontalHeaderLabels(QStringList() << "" << TRANSLATE_STR_RSERVER_UPLOAD_NAME << TRANSLATE_STR_RSERVER_UPLOAD_TYPE << TRANSLATE_STR_RSERVER_UPLOAD_DATE << TRANSLATE_STR_RSERVER_UPLOAD_TYPEVALUE << TRANSLATE_STR_RSERVER_UPLOAD_FULLPATH << TRANSLATE_STR_RSERVER_UPLOAD_JOBID << TRANSLATE_STR_RSERVER_UPLOAD_LOCATION); m_pBtnRefresh->setText(TRANSLATE_STR_RSERVER_BTN_REFRESH); // m_tableWidget->setFont(font); m_filterPattern->setFont(font); m_pBtnRefresh->setFont(font); } void QUploadFileWidget::showEvent(QShowEvent *event) { QUploadFileModel *fileModel = qobject_cast<QUploadFileModel *>(model()); if (!getBackProgress()->isActive() && fileModel->fileModelList().size() == 0) { QTimer::singleShot(0, this, SLOT(onGetFileList())); } QWidget::showEvent(event); }
3ed907d0914673e7f10b2ae448cf24a40f318f98
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/tiia/include/tencentcloud/tiia/v20190529/model/AttributesForBody.h
281358e65dd4b6f875982cd62bb8e4e269734408
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
6,295
h
AttributesForBody.h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_TIIA_V20190529_MODEL_ATTRIBUTESFORBODY_H_ #define TENCENTCLOUD_TIIA_V20190529_MODEL_ATTRIBUTESFORBODY_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/tiia/v20190529/model/ImageRect.h> #include <tencentcloud/tiia/v20190529/model/BodyAttributes.h> namespace TencentCloud { namespace Tiia { namespace V20190529 { namespace Model { /** * 属性检测到的人体 */ class AttributesForBody : public AbstractModel { public: AttributesForBody(); ~AttributesForBody() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取人体框。当不开启人体检测时,内部参数默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * @return Rect 人体框。当不开启人体检测时,内部参数默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * */ ImageRect GetRect() const; /** * 设置人体框。当不开启人体检测时,内部参数默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * @param _rect 人体框。当不开启人体检测时,内部参数默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetRect(const ImageRect& _rect); /** * 判断参数 Rect 是否已赋值 * @return Rect 是否已赋值 * */ bool RectHasBeenSet() const; /** * 获取人体检测置信度。取值0-1之间,当不开启人体检测开关时默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * @return DetectConfidence 人体检测置信度。取值0-1之间,当不开启人体检测开关时默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * */ double GetDetectConfidence() const; /** * 设置人体检测置信度。取值0-1之间,当不开启人体检测开关时默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * @param _detectConfidence 人体检测置信度。取值0-1之间,当不开启人体检测开关时默认为0。 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetDetectConfidence(const double& _detectConfidence); /** * 判断参数 DetectConfidence 是否已赋值 * @return DetectConfidence 是否已赋值 * */ bool DetectConfidenceHasBeenSet() const; /** * 获取属性信息。 注意:此字段可能返回 null,表示取不到有效值。 * @return Attributes 属性信息。 注意:此字段可能返回 null,表示取不到有效值。 * */ std::vector<BodyAttributes> GetAttributes() const; /** * 设置属性信息。 注意:此字段可能返回 null,表示取不到有效值。 * @param _attributes 属性信息。 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetAttributes(const std::vector<BodyAttributes>& _attributes); /** * 判断参数 Attributes 是否已赋值 * @return Attributes 是否已赋值 * */ bool AttributesHasBeenSet() const; private: /** * 人体框。当不开启人体检测时,内部参数默认为0。 注意:此字段可能返回 null,表示取不到有效值。 */ ImageRect m_rect; bool m_rectHasBeenSet; /** * 人体检测置信度。取值0-1之间,当不开启人体检测开关时默认为0。 注意:此字段可能返回 null,表示取不到有效值。 */ double m_detectConfidence; bool m_detectConfidenceHasBeenSet; /** * 属性信息。 注意:此字段可能返回 null,表示取不到有效值。 */ std::vector<BodyAttributes> m_attributes; bool m_attributesHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_TIIA_V20190529_MODEL_ATTRIBUTESFORBODY_H_
e08a07382edef9486cf1ed4222a1acfa990c01bc
5cdb4b5af1a62e018186ab834f72ad1bf3e8db13
/jni/nitroFrame/Render/DAOInsert.h
89e7945ea41d50ae3668dc458a4b690fe14c477c
[]
no_license
Opheliasong/ndkProj
2e13a115fbbfa0ccfe90752c7dcf4cf73b37fd0f
b3ef64e7381e92ef73732a3c12746e75aa58e070
refs/heads/master
2023-04-24T16:58:21.936501
2021-05-13T04:27:53
2021-05-13T04:27:53
366,552,445
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
h
DAOInsert.h
/* * DAOInsert.h * * Created on: 2012. 10. 23. * Author: Ophelia */ #ifndef DAOINSERT_H_ #define DAOINSERT_H_ //#include "../NitroFrame.h" #include "TextureAtlas.h" #include "ScreenplayStore.h" #include "TextureRawPacket.h" #include "npRenderTypedef.h" class npInsertDAO{ protected: class ScreenplayPacket{ public: screenplayTag tag; int screenplayID; ScreenplayPacket& operator=(const ScreenplayPacket& rightSide){ this->screenplayID = rightSide.screenplayID; this->tag = rightSide.tag; return *this; } }; public: npInsertDAO(); ~npInsertDAO(); void SendRawSourceByModule(const RawDataPacket& rawSource); private: void ParsingRawSource(const RawDataPacket& rawSource, UVPacket& outputUvPacket, ScreenplayPacket& screenOutputPacket); void CalcUVArrayByRawSource(const RawDataPacket& rawSource, UVPacket& UVoutputPacket); void InsertUVPacket(UVPacket& UvPacketsUvPackets,int UvKeys); // void InsertScreenplayPackets(ScreenplayPacket& screenplayPacket); int GetFramewIndex(); }; #endif /* DAOINSERT_H_ */
b1382f19a97fea306546a63338f1421864d08d33
26c3e3c441c021dd0138afef886ef802b451fced
/xt_session_server/XTRtsp.h
1301e63361816a189d628461d6d1dc1267276751
[]
no_license
chxj1980/firstproject
1b25543db4e4b3d1ba636a03d2f3d9d8c8fef69f
effadd90087a0894a84e5a90924935c6d492eada
refs/heads/master
2021-09-15T20:24:09.870832
2018-06-10T11:17:18
2018-06-10T11:17:18
null
0
0
null
null
null
null
GB18030
C++
false
false
1,909
h
XTRtsp.h
#ifdef _USE_XT_RTSP_SESSION_SERVER #ifdef _OS_WINDOWS #pragma once #endif #ifndef _XTRTSP_H__ #define _XTRTSP_H__ #include <string> #include "h_xtsessionserver.h" using namespace std; class XTRtsp { private: XTRtsp(void); ~XTRtsp(void); static XTRtsp self; public: static XTRtsp* instance(){return &self;} // 初始化 int init(const string& ip, unsigned short listen_port, unsigned int max_session, xt_print_cb func); int set_rtsp_heartbit_time(const unsigned int check_timer_interval,const unsigned int time_out_interval); // 反初始化 int uninit(); // 建立转发 static int SESSIONSERVER_STDCALL add_send_proc(void *hsession, int srcno, //srcno int trackid, //track id const char *pstrRAddr, //IP unsigned short nRPort, //port bool multiplex, //multiplex unsigned int multiplexID); //multiplexID // 删除转发 static int SESSIONSERVER_STDCALL del_send_proc(void *hsession, int srcno, //srcno int trackid, //track id const char *pstrRAddr, //IP unsigned short nRPort, //port bool multiplex, //multiplex unsigned int multiplexID); //multiplexID static int SESSIONSERVER_STDCALL rtsp_play_cb_func(void *hSession, int sessionno, int trackid, double npt, float scale, uint32_t *rtp_pkt_seq, uint32_t *rtp_pkt_timestamp); static int SESSIONSERVER_STDCALL rtsp_pause_cb_func(void *hSession, int sessionno, int trackid); // 增加/删除源 int add_src(int srcno); int del_src(int srcno); // 设置SDP int set_sdp(int srcno, const char *sdp, int len); // 设置发送端口 int set_snd_port(int srcno, int trackid, unsigned short port, bool demux,unsigned int demuxid); int set_play_cb(rtsp_play_cb func); int set_pause_cb(rtsp_pause_cb func); }; #endif //#ifndef _XTRTSP_H__ #endif //_USE_XT_RTSP_SESSION_SERVER
59457e2257631c4466fc98e76be2364ed42f2812
cc16d9f71b69e10b35a16e4693a13eb9f5e09da9
/lib/Threads/SystemSlaveThreadFactory.h
7e9e1c623aff1c77347e93be84636657e1be001a
[]
no_license
dadarek/HTTP-Server
5b15b5e2a205e6d8b9a31e70c7302617238a0b28
179e96d0e99d20e953b97824588ce24a246149d6
refs/heads/master
2021-01-02T09:08:17.184727
2012-05-03T19:44:24
2012-05-03T19:44:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
358
h
SystemSlaveThreadFactory.h
#ifndef SYSTEM_SLAVE_THREAD_FACTORY #define SYSTEM_SLAVE_THREAD_FACTORY #include "SlaveThreadFactory.h" class ThreadApi; class SystemSlaveThreadFactory : public SlaveThreadFactory { private: ThreadApi& api_; public: SystemSlaveThreadFactory( ThreadApi& api ); virtual ~SystemSlaveThreadFactory(); SlaveThread* create(); }; #endif
3ab1d9d5a315f8b5b11fa94d1d6e2f0fc3a5810d
62510fa67d0ca78082109a861b6948206252c885
/hihope_neptune-oh_hid/00_src/v0.1/foundation/multimedia/camera_lite/frameworks/camera_device.cpp
f0a12632f8a63822a6cae5fb9909104161b036f3
[ "Apache-2.0" ]
permissive
dawmlight/vendor_oh_fun
a869e7efb761e54a62f509b25921e019e237219b
bc9fb50920f06cd4c27399f60076f5793043c77d
refs/heads/master
2023-08-05T09:25:33.485332
2021-09-10T10:57:48
2021-09-10T10:57:48
406,236,565
1
0
null
null
null
null
UTF-8
C++
false
false
19,694
cpp
camera_device.cpp
/* * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * 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 "camera_device.h" #include "codec_interface.h" #include "hal_display.h" #include "media_log.h" #include "meta_data.h" #include "securec.h" #include <string> #include <thread> using namespace OHOS; using namespace OHOS::Media; using namespace std; const int32_t KEY_IS_SYNC_FRAME = 1; // "is-sync-frame" const int32_t KEY_TIME_US = 2; // "timeUs" namespace OHOS { namespace Media { inline PicSize Convert2CodecSize(int32_t width, int32_t height) { struct SizeMap { PicSize res_; int32_t width_; int32_t height_; }; static SizeMap sizeMap[] = {{Resolution_CIF, 352, 288}, {Resolution_360P, 640, 360}, {Resolution_D1_PAL, 720, 576}, {Resolution_D1_NTSC, 720, 480}, {Resolution_720P, 1280, 720}, {Resolution_1080P, 1920, 1080}}; for (uint32_t i = 0; i < sizeof(sizeMap) / sizeof(SizeMap); i++) { if (sizeMap[i].width_ == width && sizeMap[i].height_ == height) { return sizeMap[i].res_; } } return Resolution_INVALID; } static int32_t SetVencSource(CODEC_HANDLETYPE codecHdl, uint32_t deviceId) { Param param = {.key = KEY_DEVICE_ID, .val = (void *)&deviceId, .size = sizeof(uint32_t)}; int32_t ret = CodecSetParameter(codecHdl, &param, 1); if (ret != 0) { MEDIA_ERR_LOG("Set enc source failed.(ret=%d)", ret); return ret; } return MEDIA_OK; } static int32_t CameraCreateVideoEnc(FrameConfig &fc, HalVideoProcessorAttr *attr, uint32_t srcDev, CODEC_HANDLETYPE *codecHdl) { const char *name = "codec.video.hardware.encoder"; const uint32_t maxParamNum = 10; uint32_t paramIndex = 0; Param param[maxParamNum]; CodecType domainKind = VIDEO_ENCODER; param[paramIndex].key = KEY_CODEC_TYPE; param[paramIndex].val = &domainKind; param[paramIndex].size = sizeof(CodecType); paramIndex++; AvCodecMime codecMime = MEDIA_MIMETYPE_VIDEO_HEVC; param[paramIndex].key = KEY_MIMETYPE; param[paramIndex].val = &codecMime; param[paramIndex].size = sizeof(AvCodecMime); paramIndex++; VenCodeRcMode rcMode = VENCOD_RC_CBR; param[paramIndex].key = KEY_VIDEO_RC_MODE; param[paramIndex].val = &rcMode; param[paramIndex].size = sizeof(VenCodeRcMode); paramIndex++; VenCodeGopMode gopMode = VENCOD_GOPMODE_NORMALP; param[paramIndex].key = KEY_VIDEO_GOP_MODE; param[paramIndex].val = &gopMode; param[paramIndex].size = sizeof(VenCodeGopMode); paramIndex++; Profile profile = HEVC_MAIN_PROFILE; param[paramIndex].key = KEY_VIDEO_PROFILE; param[paramIndex].val = &profile; param[paramIndex].size = sizeof(Profile); paramIndex++; PicSize picSize = Convert2CodecSize(attr->width, attr->height); MEDIA_DEBUG_LOG("picSize=%d", picSize); param[paramIndex].key = KEY_VIDEO_PIC_SIZE; param[paramIndex].val = &picSize; param[paramIndex].size = sizeof(PicSize); paramIndex++; uint32_t frameRate = attr->fps; MEDIA_DEBUG_LOG("frameRate=%u", frameRate); param[paramIndex].key = KEY_VIDEO_FRAME_RATE; param[paramIndex].val = &frameRate; param[paramIndex].size = sizeof(uint32_t); paramIndex++; int32_t ret = CodecCreate(name, param, paramIndex, codecHdl); if (ret != 0) { MEDIA_ERR_LOG("Create video encoder failed."); return HAL_MEDIA_ERR; } ret = SetVencSource(*codecHdl, srcDev); if (ret != 0) { CodecDestroy(codecHdl); return HAL_MEDIA_ERR; } return HAL_MEDIA_OK; } static int32_t CameraCreateJpegEnc(FrameConfig &fc, uint32_t srcDev, HalVideoProcessorAttr *attr, CODEC_HANDLETYPE *codecHdl) { const char *videoEncName = "codec.jpeg.hardware.encoder"; const uint32_t maxParamNum = 5; Param param[maxParamNum]; uint32_t paramIndex = 0; CodecType domainKind = VIDEO_ENCODER; param[paramIndex].key = KEY_CODEC_TYPE; param[paramIndex].val = &domainKind; param[paramIndex].size = sizeof(CodecType); paramIndex++; AvCodecMime codecMime = MEDIA_MIMETYPE_IMAGE_JPEG; param[paramIndex].key = KEY_MIMETYPE; param[paramIndex].val = &codecMime; param[paramIndex].size = sizeof(AvCodecMime); paramIndex++; PicSize picSize = Convert2CodecSize(attr->width, attr->height); param[paramIndex].key = KEY_VIDEO_PIC_SIZE; param[paramIndex].val = &picSize; param[paramIndex].size = sizeof(PicSize); paramIndex++; int32_t ret = CodecCreate(videoEncName, param, paramIndex, codecHdl); if (ret != 0) { return HAL_MEDIA_ERR; } int32_t qfactor = -1; fc.GetParameter(PARAM_KEY_IMAGE_ENCODE_QFACTOR, qfactor); if (qfactor != -1) { MEDIA_DEBUG_LOG("qfactor=%d", qfactor); Param jpegParam = { .key = KEY_IMAGE_Q_FACTOR, .val = &qfactor, .size = sizeof(qfactor) }; ret = CodecSetParameter(*codecHdl, &jpegParam, 1); if (ret != 0) { MEDIA_ERR_LOG("CodecSetParameter set jpeg qfactor failed.(ret=%u)", ret); } } ret = SetVencSource(*codecHdl, srcDev); if (ret != 0) { MEDIA_ERR_LOG("Set video encoder source failed."); CodecDestroy(*codecHdl); return HAL_MEDIA_ERR; } return HAL_MEDIA_OK; } static int32_t CopyCodecOutput(void *dst, uint32_t *size, OutputInfo *buffer) { char *dstBuf = reinterpret_cast<char *>(dst); for (uint32_t i = 0; i < buffer->bufferCnt; i++) { uint32_t packSize = buffer->buffers[i].length - buffer->buffers[i].offset; errno_t ret = memcpy_s(dstBuf, *size, buffer->buffers[i].addr + buffer->buffers[i].offset, packSize); if (ret != EOK) { return HAL_MEDIA_ERR; } *size -= packSize; dstBuf += packSize; } return MEDIA_OK; } static int32_t FindAvailProcessorIdx(Surface &surface, vector<HalVideoProcessorAttr> &attrs) { for (uint32_t i = 0; i < attrs.size(); i++) { if (attrs[i].width == surface.GetWidth() && attrs[i].height == surface.GetHeight()) { return i; } } return -1; } int RecordAssistant::OnVencBufferAvailble(UINTPTR hComponent, UINTPTR dataIn, OutputInfo *buffer) { CODEC_HANDLETYPE hdl = reinterpret_cast<CODEC_HANDLETYPE>(hComponent); RecordAssistant *assistant = reinterpret_cast<RecordAssistant *>(dataIn); list<Surface *> *surfaceList = nullptr; for (uint32_t idx = 0; idx < assistant->vencHdls_.size(); idx++) { if (assistant->vencHdls_[idx] == hdl) { surfaceList = &(assistant->vencSurfaces_[idx]); break; } } if (surfaceList == nullptr || surfaceList->empty()) { MEDIA_ERR_LOG("Encoder handle is illegal."); return -1; } int32_t ret = -1; for (auto &surface : *surfaceList) { SurfaceBuffer *surfaceBuf = surface->RequestBuffer(); if (surfaceBuf == nullptr) { MEDIA_ERR_LOG("No available buffer in surface."); break; } uint32_t size = surface->GetSize(); void *buf = surfaceBuf->GetVirAddr(); if (buf == nullptr) { MEDIA_ERR_LOG("Invalid buffer address."); break; } ret = CopyCodecOutput(buf, &size, buffer); if (ret != HAL_MEDIA_OK) { MEDIA_ERR_LOG("No available buffer in surface."); surface->CancelBuffer(surfaceBuf); break; } surfaceBuf->SetInt32(KEY_IS_SYNC_FRAME, (((buffer->flag & STREAM_FLAG_KEYFRAME) == 0) ? 0 : 1)); surfaceBuf->SetInt64(KEY_TIME_US, buffer->timeStamp); surfaceBuf->SetSize(surface->GetSize() - size); if (surface->FlushBuffer(surfaceBuf) != 0) { MEDIA_ERR_LOG("Flush surface failed."); surface->CancelBuffer(surfaceBuf); ret = -1; break; } } if (CodecQueueOutput(hdl, buffer, 0, -1) != 0) { MEDIA_ERR_LOG("Codec queue output failed."); } return ret; } CodecCallback RecordAssistant::recordCodecCb_ = {nullptr, nullptr, RecordAssistant::OnVencBufferAvailble}; int32_t RecordAssistant::SetFrameConfig(FrameConfig &fc, vector<HalProcessorHdl> &hdls, vector<HalVideoProcessorAttr> &attrs) { fc_ = &fc; auto surfaceList = fc.GetSurfaces(); if (surfaceList.size() != 1) { MEDIA_ERR_LOG("Only support one surface in frame config now."); return MEDIA_ERR; } for (auto &surface : surfaceList) { CODEC_HANDLETYPE codecHdl = nullptr; int32_t ProcessorIdx = FindAvailProcessorIdx(*surface, attrs); if (ProcessorIdx < 0) { MEDIA_ERR_LOG("No suitble procesor for recording."); return MEDIA_ERR; } uint32_t deviceId = HalGetProcessorDeviceId(hdls[ProcessorIdx]); int32_t encIdx = VideoEncIsExist(&attrs[deviceId]); if (encIdx >= 0) { vencSurfaces_[encIdx].emplace_back(surface); continue; } int32_t ret = CameraCreateVideoEnc(fc, &attrs[ProcessorIdx], deviceId, &codecHdl); if (ret != MEDIA_OK) { MEDIA_ERR_LOG("Cannot create suitble video encoder."); return MEDIA_ERR; } ret = CodecSetCallback(codecHdl, &recordCodecCb_, reinterpret_cast<UINTPTR>(this)); if (ret != 0) { MEDIA_ERR_LOG("Set codec callback failed.(ret=%d)", ret); CodecDestroy(codecHdl); return MEDIA_ERR; } vencHdls_.emplace_back(codecHdl); list<Surface *> conList({surface}); vencSurfaces_.emplace_back(conList); vencAttr_.emplace_back(&attrs[deviceId]); } state_ = LOOP_READY; return MEDIA_OK; } int32_t RecordAssistant::Start() { if (state_ != LOOP_READY) { return MEDIA_ERR; } int32_t ret = HAL_MEDIA_OK; int32_t i; for (i = 0; static_cast<uint32_t>(i) < vencHdls_.size(); i++) { ret = CodecStart(vencHdls_[i]); if (ret != HAL_MEDIA_OK) { MEDIA_ERR_LOG("Video encoder start failed."); ret = MEDIA_ERR; break; } } if (ret == MEDIA_ERR) { /* rollback */ for (; i >= 0; i--) { CodecStop(vencHdls_[i]); } return MEDIA_ERR; } state_ = LOOP_LOOPING; MEDIA_DEBUG_LOG("Start camera recording succeed."); return MEDIA_OK; } int32_t RecordAssistant::Stop() { if (state_ != LOOP_LOOPING) { return MEDIA_ERR; } for (uint32_t i = 0; i < vencHdls_.size(); i++) { CodecStop(vencHdls_[i]); CodecDestroy(vencHdls_[i]); } vencHdls_.clear(); vencAttr_.clear(); vencSurfaces_.clear(); state_ = LOOP_STOP; return MEDIA_OK; } int32_t RecordAssistant::VideoEncIsExist(HalVideoProcessorAttr *attr) { for (uint32_t i = 0; i < vencAttr_.size(); i++) { if (vencAttr_[i] == attr) { return i; } } return -1; } static void GetSurfaceRect(Surface *surface, HalVideoOutputAttr *attr) { attr->regionPositionX = std::stoi(surface->GetUserData("region_position_x")); attr->regionPositionY = std::stoi(surface->GetUserData("region_position_y")); attr->regionWidth = std::stoi(surface->GetUserData("region_width")); attr->regionHeight = std::stoi(surface->GetUserData("region_height")); } int32_t PreviewAssistant::SetFrameConfig(FrameConfig &fc, vector<HalProcessorHdl> &hdls, vector<HalVideoProcessorAttr> &attrs) { fc_ = &fc; auto surfaceList = fc.GetSurfaces(); if (surfaceList.size() != 1) { MEDIA_ERR_LOG("Only support one surface in frame config now."); return MEDIA_ERR; } auto surface = surfaceList.front(); int32_t ProcessorIdx = FindAvailProcessorIdx(*surface, attrs); if (ProcessorIdx < 0) { MEDIA_ERR_LOG("No suitble procesor for preview."); return MEDIA_ERR; } uint32_t deviceId = HalGetProcessorDeviceId(hdls[ProcessorIdx]); HalVideoOutputAttr attr; GetSurfaceRect(surface, &attr); int32_t ret = HalCreateCameraVideoOutput(deviceId, &attr); if (ret != 0) { MEDIA_ERR_LOG("Create preview video output failed."); return MEDIA_ERR; } return MEDIA_OK; } int32_t PreviewAssistant::Start() { // enable vo return MEDIA_OK; } int32_t PreviewAssistant::Stop() { HalDestroyCameraVideoOutput(); return MEDIA_OK; } int32_t CaptureAssistant::SetFrameConfig(FrameConfig &fc, vector<HalProcessorHdl> &hdls, vector<HalVideoProcessorAttr> &attrs) { auto surfaceList = fc.GetSurfaces(); if (surfaceList.size() != 1) { MEDIA_ERR_LOG("Only support one surface in frame config now."); return MEDIA_ERR; } if (surfaceList.empty()) { MEDIA_ERR_LOG("Frame config with empty surface list."); return MEDIA_ERR; } if (surfaceList.size() > 1) { MEDIA_WARNING_LOG("Capture only fullfill the first surface in frame config."); } Surface *surface = surfaceList.front(); int32_t idx = FindAvailProcessorIdx(*surface, attrs); if (idx < 0) { MEDIA_ERR_LOG("No suitble procesor for venc."); return MEDIA_ERR; } uint32_t deviceId = HalGetProcessorDeviceId(hdls[idx]); int32_t ret = CameraCreateJpegEnc(fc, deviceId, &attrs[idx], &vencHdl_); if (ret != HAL_MEDIA_OK) { MEDIA_ERR_LOG("Create capture venc failed."); return MEDIA_ERR; } capSurface_ = surface; state_ = LOOP_READY; return MEDIA_OK; } /* Block method, waiting for capture completed */ int32_t CaptureAssistant::Start() { state_ = LOOP_LOOPING; int32_t ret = CodecStart(vencHdl_); if (ret != 0) { MEDIA_ERR_LOG("Start capture encoder failed.(ret=%d)", ret); return MEDIA_ERR; } MEDIA_DEBUG_LOG("surface = %p", capSurface_); SurfaceBuffer *surfaceBuf = capSurface_->RequestBuffer(); if (surfaceBuf == nullptr) { MEDIA_ERR_LOG("No available buffer in surface."); return -1; } OutputInfo outInfo; ret = CodecDequeueOutput(vencHdl_, 0, nullptr, &outInfo); if (ret != 0) { capSurface_->CancelBuffer(surfaceBuf); MEDIA_ERR_LOG("Dequeue capture frame failed.(ret=%d)", ret); return MEDIA_ERR; } uint32_t size = capSurface_->GetSize(); void *buf = surfaceBuf->GetVirAddr(); if (buf == nullptr) { MEDIA_ERR_LOG("Invalid buffer address."); return -1; } ret = CopyCodecOutput(buf, &size, &outInfo); if (ret != HAL_MEDIA_OK) { MEDIA_ERR_LOG("No available buffer in capSurface_."); capSurface_->CancelBuffer(surfaceBuf); return -1; } surfaceBuf->SetSize(capSurface_->GetSize() - size); if (capSurface_->FlushBuffer(surfaceBuf) != 0) { MEDIA_ERR_LOG("Flush surface buffer failed."); capSurface_->CancelBuffer(surfaceBuf); return -1; } CodecQueueOutput(vencHdl_, &outInfo, 0, -1); // 0:no timeout -1:no fd CodecStop(vencHdl_); CodecDestroy(vencHdl_); state_ = LOOP_STOP; return MEDIA_OK; } int32_t CaptureAssistant::Stop() { MEDIA_DEBUG_LOG("No support method."); return MEDIA_OK; } CameraDevice::CameraDevice() {} CameraDevice::~CameraDevice() {} int32_t CameraDevice::Initialize(CameraAbility &ability) { /* Need to be Refactored when delete config file */ int32_t ret = HalCreateVideoProcessor(nullptr); if (ret != HAL_MEDIA_OK) { MEDIA_ERR_LOG("Init camera device failed.(ret=%d)", ret); return MEDIA_ERR; } HalVideoProcessorAttr attrs[HAL_MAX_VPSS_NUM]; HalProcessorHdl hdls[HAL_MAX_VPSS_NUM]; int32_t size; list<CameraPicSize> range; HalCameraGetProcessorAttr(hdls, attrs, &size); for (int i = 0; i < size; i++) { prcessorAttrs_.emplace_back(attrs[i]); prcessorHdls_.emplace_back(hdls[i]); CameraPicSize tmpSize = {.width = attrs[i].width, .height = attrs[i].height}; range.emplace_back(tmpSize); } ability.SetParameterRange(PARAM_KEY_SIZE, range); ret = CodecInit(); if (ret != 0) { MEDIA_ERR_LOG("Codec module init failed.(ret=%d)", ret); return MEDIA_ERR; } MEDIA_DEBUG_LOG("Codec module init succeed."); captureAssistant_.state_ = LOOP_READY; previewAssistant_.state_ = LOOP_READY; recordAssistant_.state_ = LOOP_READY; return MEDIA_OK; } int32_t CameraDevice::UnInitialize() { HalDestroyVideoProcessor(); return MEDIA_OK; } int32_t CameraDevice::TriggerLoopingCapture(FrameConfig &fc) { MEDIA_DEBUG_LOG("Camera device start looping capture."); DeviceAssistant *assistant = nullptr; int fcType = fc.GetFrameConfigType(); switch (fcType) { case FRAME_CONFIG_RECORD: assistant = &recordAssistant_; break; case FRAME_CONFIG_PREVIEW: assistant = &previewAssistant_; break; case FRAME_CONFIG_CAPTURE: assistant = &captureAssistant_; break; default: break; } if (assistant == nullptr) { MEDIA_ERR_LOG("Invalid frame config type.(type=%d)", fcType); return MEDIA_ERR; } if (assistant->state_ == LOOP_IDLE || assistant->state_ == LOOP_LOOPING || assistant->state_ == LOOP_ERROR) { MEDIA_ERR_LOG("Device state is %d, cannot start looping capture.", assistant->state_); return MEDIA_ERR; } int ret = assistant->SetFrameConfig(fc, prcessorHdls_, prcessorAttrs_); if (ret != MEDIA_OK) { MEDIA_ERR_LOG("Check and set frame config failed.(ret=%d)", ret); return MEDIA_ERR; } ret = assistant->Start(); if (ret != MEDIA_OK) { MEDIA_ERR_LOG("Start looping capture failed.(ret=%d)", ret); return MEDIA_ERR; } return MEDIA_OK; } void CameraDevice::StopLoopingCapture() { previewAssistant_.Stop(); recordAssistant_.Stop(); } int32_t CameraDevice::TriggerSingleCapture(FrameConfig &fc) { return TriggerLoopingCapture(fc); } int32_t CameraDevice::SetCameraConfig(CameraConfig &config) { cc_ = &config; return MEDIA_OK; } } // namespace Media } // namespace OHOS
c0fabda9d504a19d6837553101029897cd1359ed
48b0f9a92320b5b94ba9e441cb7a5c7cee6a0132
/MarsRover/Microcontroller/Minibot-Microcontroller/MergedSystem/IMU.ino
4f70fa3e2ca5a115f2a10465379d32b9379082cf
[ "MIT" ]
permissive
jpadillak/Concordia_Capstone2013-14
318735c49b9efc861ceed049afd8cbeb19869374
0fcdec6b757a2e3b32eeda37824c7351e288f674
refs/heads/master
2021-01-10T20:20:41.363996
2014-03-31T15:20:40
2014-03-31T15:20:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,735
ino
IMU.ino
void read_sensors() { Read_Gyro(); // Read gyroscope Read_Accel(); // Read accelerometer Read_Magn(); // Read magnetometer } // Read every sensor and record a time stamp // Init DCM with unfiltered orientation // TODO re-init global vars? void reset_sensor_fusion() { float temp1[3]; float temp2[3]; float xAxis[] = {1.0f, 0.0f, 0.0f}; read_sensors(); timestamp = millis(); // GET PITCH // Using y-z-plane-component/x-component of gravity vector pitch = -atan2(accel[0], sqrt(accel[1] * accel[1] + accel[2] * accel[2])); // GET ROLL // Compensate pitch of gravity vector Vector_Cross_Product(temp1, accel, xAxis); Vector_Cross_Product(temp2, xAxis, temp1); // Normally using x-z-plane-component/y-component of compensated gravity vector // roll = atan2(temp2[1], sqrt(temp2[0] * temp2[0] + temp2[2] * temp2[2])); // Since we compensated for pitch, x-z-plane-component equals z-component: roll = atan2(temp2[1], temp2[2]); // GET YAW Compass_Heading(); yaw = MAG_Heading; // Init rotation matrix init_rotation_matrix(DCM_Matrix, yaw, pitch, roll); } // Apply calibration to raw sensor readings void compensate_sensor_errors() { // Compensate accelerometer error accel[0] = (accel[0] - ACCEL_X_OFFSET) * ACCEL_X_SCALE; accel[1] = (accel[1] - ACCEL_Y_OFFSET) * ACCEL_Y_SCALE; accel[2] = (accel[2] - ACCEL_Z_OFFSET) * ACCEL_Z_SCALE; // Compensate magnetometer error #if CALIBRATION__MAGN_USE_EXTENDED == true for (int i = 0; i < 3; i++) magnetom_tmp[i] = magnetom[i] - magn_ellipsoid_center[i]; Matrix_Vector_Multiply(magn_ellipsoid_transform, magnetom_tmp, magnetom); #else magnetom[0] = (magnetom[0] - MAGN_X_OFFSET) * MAGN_X_SCALE; magnetom[1] = (magnetom[1] - MAGN_Y_OFFSET) * MAGN_Y_SCALE; magnetom[2] = (magnetom[2] - MAGN_Z_OFFSET) * MAGN_Z_SCALE; #endif // Compensate gyroscope error gyro[0] -= GYRO_AVERAGE_OFFSET_X; gyro[1] -= GYRO_AVERAGE_OFFSET_Y; gyro[2] -= GYRO_AVERAGE_OFFSET_Z; } // Reset calibration session if reset_calibration_session_flag is set void check_reset_calibration_session() { // Raw sensor values have to be read already, but no error compensation applied // Reset this calibration session? if (!reset_calibration_session_flag) return; // Reset acc and mag calibration variables for (int i = 0; i < 3; i++) { accel_min[i] = accel_max[i] = accel[i]; magnetom_min[i] = magnetom_max[i] = magnetom[i]; } // Reset gyro calibration variables gyro_num_samples = 0; // Reset gyro calibration averaging gyro_average[0] = gyro_average[1] = gyro_average[2] = 0.0f; reset_calibration_session_flag = false; } void turn_output_stream_on() { output_stream_on = true; digitalWrite(STATUS_LED_PIN, HIGH); } void turn_output_stream_off() { output_stream_on = false; digitalWrite(STATUS_LED_PIN, LOW); } // Blocks until another byte is available on serial port char readChar() { while (Serial.available() < 1) { } // Block return Serial.read(); } void Init_IMU() { // Init status LED pinMode (STATUS_LED_PIN, OUTPUT); digitalWrite(STATUS_LED_PIN, LOW); // Init sensors delay(50); // Give sensors enough time to start I2C_Init(); Accel_Init(); Magn_Init(); Gyro_Init(); Servo_Init(); // Read sensors, init DCM algorithm delay(20); // Give sensors enough time to collect data reset_sensor_fusion(); // Init output #if (OUTPUT__HAS_RN_BLUETOOTH == true) || (OUTPUT__STARTUP_STREAM_ON == false) turn_output_stream_off(); #else turn_output_stream_on(); #endif } // Main loop void Loop_IMU() { // Read incoming control messages if (Serial.available() >= 2) { if (Serial.read() == '#') // Start of new control message { int command = Serial.read(); // Commands if (command == 'f') // request one output _f_rame output_single_on = true; else if (command == 's') // _s_ynch request { // Read ID byte id[2]; id[0] = readChar(); id[1] = readChar(); // Reply with synch message Serial.print("#SYNCH"); Serial.write(id, 2); Serial.println(); } else if (command == 'o') // Set _o_utput mode { char output_param = readChar(); if (output_param == 'n') // Calibrate _n_ext sensor { curr_calibration_sensor = (curr_calibration_sensor + 1) % 3; reset_calibration_session_flag = true; } else if (output_param == 't') // Output angles as _t_ext { output_mode = OUTPUT__MODE_ANGLES; output_format = OUTPUT__FORMAT_TEXT; } else if (output_param == 'b') // Output angles in _b_inary format { output_mode = OUTPUT__MODE_ANGLES; output_format = OUTPUT__FORMAT_BINARY; } else if (output_param == 'c') // Go to _c_alibration mode { output_mode = OUTPUT__MODE_CALIBRATE_SENSORS; reset_calibration_session_flag = true; } else if (output_param == 's') // Output _s_ensor values { char values_param = readChar(); char format_param = readChar(); if (values_param == 'r') // Output _r_aw sensor values output_mode = OUTPUT__MODE_SENSORS_RAW; else if (values_param == 'c') // Output _c_alibrated sensor values output_mode = OUTPUT__MODE_SENSORS_CALIB; else if (values_param == 'b') // Output _b_oth sensor values (raw and calibrated) output_mode = OUTPUT__MODE_SENSORS_BOTH; if (format_param == 't') // Output values as _t_text output_format = OUTPUT__FORMAT_TEXT; else if (format_param == 'b') // Output values in _b_inary format output_format = OUTPUT__FORMAT_BINARY; } else if (output_param == '0') // Disable continuous streaming output { turn_output_stream_off(); reset_calibration_session_flag = true; } else if (output_param == '1') // Enable continuous streaming output { reset_calibration_session_flag = true; turn_output_stream_on(); } else if (output_param == 'e') // _e_rror output settings { char error_param = readChar(); if (error_param == '0') output_errors = false; else if (error_param == '1') output_errors = true; else if (error_param == 'c') // get error count { Serial.print("#AMG-ERR:"); Serial.print(num_accel_errors); Serial.print(","); Serial.print(num_magn_errors); Serial.print(","); Serial.println(num_gyro_errors); } } } #if OUTPUT__HAS_RN_BLUETOOTH == true // Read messages from bluetooth module // For this to work, the connect/disconnect message prefix of the module has to be set to "#". else if (command == 'C') // Bluetooth "#CONNECT" message (does the same as "#o1") turn_output_stream_on(); else if (command == 'D') // Bluetooth "#DISCONNECT" message (does the same as "#o0") turn_output_stream_off(); #endif // OUTPUT__HAS_RN_BLUETOOTH == true } else { } // Skip character } // Time to read the sensors again? if((millis() - timestamp) >= OUTPUT__DATA_INTERVAL) { timestamp_old = timestamp; timestamp = millis(); if (timestamp > timestamp_old) G_Dt = (float) (timestamp - timestamp_old) / 1000.0f; // Real time of loop run. We use this on the DCM algorithm (gyro integration time) else G_Dt = 0; // Update sensor readings read_sensors(); if (output_mode == OUTPUT__MODE_CALIBRATE_SENSORS) // We're in calibration mode { check_reset_calibration_session(); // Check if this session needs a reset if (output_stream_on || output_single_on) output_calibration(curr_calibration_sensor); } else if (output_mode == OUTPUT__MODE_ANGLES) // Output angles { // Apply sensor calibration compensate_sensor_errors(); // Run DCM algorithm Compass_Heading(); // Calculate magnetic heading Matrix_update(); Normalize(); Drift_correction(); Euler_angles(); if (output_stream_on || output_single_on) output_angles(); } else // Output sensor values { if (output_stream_on || output_single_on) output_sensors(); } //Update_Servos(); output_single_on = false; #if DEBUG__PRINT_LOOP_TIME == true Serial.print("loop time (ms) = "); Serial.println(millis() - timestamp); #endif } #if DEBUG__PRINT_LOOP_TIME == true else { Serial.println("waiting..."); } #endif }
6c1526c4d68642a5d953a9a9ad94eebefe12610c
2473fa1f15f7ee116b008e3ba9faef1af65230e1
/fuse_optimizers/test/test_variable_stamp_index.cpp
5003d3646f0fef5e9396d85d8de8d9392949d225
[ "BSD-3-Clause" ]
permissive
locusrobotics/fuse
c08ab905fb9368ec310812fe49e93bc180b8be21
6814698a3a850ec37bf0535240e0c0eb5dd64bdf
refs/heads/devel
2023-08-17T04:03:38.390980
2023-08-16T22:07:48
2023-08-16T22:07:48
139,344,157
524
91
NOASSERTION
2023-08-16T22:07:49
2018-07-01T16:21:44
C++
UTF-8
C++
false
false
11,986
cpp
test_variable_stamp_index.cpp
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <fuse_core/constraint.h> #include <fuse_core/transaction.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <fuse_core/variable.h> #include <fuse_optimizers/variable_stamp_index.h> #include <fuse_variables/stamped.h> #include <ros/time.h> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <gtest/gtest.h> #include <algorithm> #include <iterator> #include <stdexcept> #include <string> #include <vector> /** * @brief Create a simple stamped Variable for testing */ class StampedVariable : public fuse_core::Variable, public fuse_variables::Stamped { public: FUSE_VARIABLE_DEFINITIONS(StampedVariable); explicit StampedVariable(const ros::Time& stamp = ros::Time(0, 0)) : fuse_core::Variable(fuse_core::uuid::generate()), fuse_variables::Stamped(stamp), data_{} { } size_t size() const override { return 1; } const double* data() const override { return &data_; } double* data() override { return &data_; } void print(std::ostream& /*stream = std::cout*/) const override { } private: double data_; // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Variable>(*this); archive & boost::serialization::base_object<fuse_variables::Stamped>(*this); archive & data_; } }; BOOST_CLASS_EXPORT(StampedVariable); /** * @brief Create a simple unstamped Variable for testing */ class UnstampedVariable : public fuse_core::Variable { public: FUSE_VARIABLE_DEFINITIONS(UnstampedVariable); UnstampedVariable() : fuse_core::Variable(fuse_core::uuid::generate()), data_{} { } size_t size() const override { return 1; } const double* data() const override { return &data_; } double* data() override { return &data_; } void print(std::ostream& /*stream = std::cout*/) const override { } private: double data_; // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Variable>(*this); archive & data_; } }; BOOST_CLASS_EXPORT(UnstampedVariable); /** * @brief Create a simple Constraint for testing */ class GenericConstraint : public fuse_core::Constraint { public: FUSE_CONSTRAINT_DEFINITIONS(GenericConstraint); GenericConstraint() = default; GenericConstraint(const std::string& source, std::initializer_list<fuse_core::UUID> variable_uuids) : Constraint(source, variable_uuids) { } explicit GenericConstraint(const std::string& source, const fuse_core::UUID& variable1) : fuse_core::Constraint(source, {variable1}) { } GenericConstraint( const std::string& source, const fuse_core::UUID& variable1, const fuse_core::UUID& variable2) : fuse_core::Constraint(source, {variable1, variable2}) { } GenericConstraint( const std::string& source, const fuse_core::UUID& variable1, const fuse_core::UUID& variable2, const fuse_core::UUID& variable3) : fuse_core::Constraint(source, {variable1, variable2, variable3}) { } void print(std::ostream& /*stream = std::cout*/) const override { } ceres::CostFunction* costFunction() const override { return nullptr; } private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Constraint>(*this); } }; BOOST_CLASS_EXPORT(GenericConstraint); TEST(VariableStampIndex, Size) { // Create an empty index auto index = fuse_optimizers::VariableStampIndex(); EXPECT_TRUE(index.empty()); EXPECT_EQ(0u, index.size()); // Add some variables/constraints to the index auto x1 = UnstampedVariable::make_shared(); auto transaction1 = fuse_core::Transaction(); transaction1.addVariable(x1); index.addNewTransaction(transaction1); EXPECT_FALSE(index.empty()); EXPECT_EQ(1u, index.size()); // Remove the same variables auto transaction2 = fuse_core::Transaction(); transaction2.removeVariable(x1->uuid()); index.addNewTransaction(transaction2); EXPECT_TRUE(index.empty()); EXPECT_EQ(0u, index.size()); } TEST(VariableStampIndex, CurrentStamp) { // Create an empty index auto index = fuse_optimizers::VariableStampIndex(); // Verify the current stamp is 0 EXPECT_EQ(ros::Time(0, 0), index.currentStamp()); // Add an unstamped variable auto x1 = UnstampedVariable::make_shared(); auto transaction1 = fuse_core::Transaction(); transaction1.addVariable(x1); index.addNewTransaction(transaction1); // Verify the current stamp is still 0 EXPECT_EQ(ros::Time(0, 0), index.currentStamp()); // Add a stamped variable auto x2 = StampedVariable::make_shared(ros::Time(1, 0)); auto transaction2 = fuse_core::Transaction(); transaction2.addVariable(x2); index.addNewTransaction(transaction2); // Verify the current stamp is now Time(1, 0) EXPECT_EQ(ros::Time(1, 0), index.currentStamp()); } TEST(VariableStampIndex, Query) { // Create an empty index auto index = fuse_optimizers::VariableStampIndex(); // Add some variables and constraints auto x1 = StampedVariable::make_shared(ros::Time(1, 0)); auto x2 = StampedVariable::make_shared(ros::Time(2, 0)); auto x3 = StampedVariable::make_shared(ros::Time(3, 0)); auto l1 = UnstampedVariable::make_shared(); auto l2 = UnstampedVariable::make_shared(); auto c1 = GenericConstraint::make_shared("test", x1->uuid(), x2->uuid()); auto c2 = GenericConstraint::make_shared("test", x2->uuid(), x3->uuid()); auto c3 = GenericConstraint::make_shared("test", x1->uuid(), l1->uuid()); auto c4 = GenericConstraint::make_shared("test", x2->uuid(), l1->uuid()); auto c5 = GenericConstraint::make_shared("test", x3->uuid(), l2->uuid()); auto transaction = fuse_core::Transaction(); transaction.addVariable(x1); transaction.addVariable(x2); transaction.addVariable(x3); transaction.addVariable(l1); transaction.addVariable(l2); transaction.addConstraint(c1); transaction.addConstraint(c2); transaction.addConstraint(c3); transaction.addConstraint(c4); transaction.addConstraint(c5); index.addNewTransaction(transaction); auto expected1 = std::vector<fuse_core::UUID>{}; auto actual1 = std::vector<fuse_core::UUID>(); index.query(ros::Time(1, 500000), std::back_inserter(actual1)); EXPECT_EQ(expected1, actual1); auto expected2 = std::vector<fuse_core::UUID>{x1->uuid(), l1->uuid()}; std::sort(expected2.begin(), expected2.end()); auto actual2 = std::vector<fuse_core::UUID>(); index.query(ros::Time(2, 500000), std::back_inserter(actual2)); std::sort(actual2.begin(), actual2.end()); EXPECT_EQ(expected2, actual2); } TEST(VariableStampIndex, MarginalTransaction) { // Create an empty index auto index = fuse_optimizers::VariableStampIndex(); // Add some variables and constraints auto x1 = StampedVariable::make_shared(ros::Time(1, 0)); auto x2 = StampedVariable::make_shared(ros::Time(2, 0)); auto x3 = StampedVariable::make_shared(ros::Time(3, 0)); auto l1 = UnstampedVariable::make_shared(); auto l2 = UnstampedVariable::make_shared(); auto c1 = GenericConstraint::make_shared("test", x1->uuid(), x2->uuid()); auto c2 = GenericConstraint::make_shared("test", x2->uuid(), x3->uuid()); auto c3 = GenericConstraint::make_shared("test", x1->uuid(), l1->uuid()); auto c4 = GenericConstraint::make_shared("test", x2->uuid(), l1->uuid()); auto c5 = GenericConstraint::make_shared("test", x3->uuid(), l2->uuid()); auto transaction = fuse_core::Transaction(); transaction.addVariable(x1); transaction.addVariable(x2); transaction.addVariable(x3); transaction.addVariable(l1); transaction.addVariable(l2); transaction.addConstraint(c1); transaction.addConstraint(c2); transaction.addConstraint(c3); transaction.addConstraint(c4); transaction.addConstraint(c5); index.addNewTransaction(transaction); // Now create a fake marginal transaction. The constraint connections should *not* change the unstamped variable // timestamps auto marginal = fuse_core::Transaction(); marginal.removeVariable(x1->uuid()); marginal.removeConstraint(c1->uuid()); marginal.removeConstraint(c3->uuid()); auto m1 = GenericConstraint::make_shared("test", x3->uuid(), l1->uuid()); marginal.addConstraint(m1); index.addMarginalTransaction(marginal); // The x1 variable should be removed EXPECT_EQ(4u, index.size()); // And the marginal constraint x3->l1 should not affect future queries auto expected = std::vector<fuse_core::UUID>{l1->uuid()}; std::sort(expected.begin(), expected.end()); auto actual = std::vector<fuse_core::UUID>(); index.query(ros::Time(2, 500000), std::back_inserter(actual)); std::sort(actual.begin(), actual.end()); EXPECT_EQ(expected, actual); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
a7d3fd9dd8321e2f443838f9d091addc158fc62b
c3cd9698a481eccf47b7c00d7447d339d3da4af9
/cpp11/main.cpp
ce890e35f21701cf48cd3987a570adeafa8bc1df
[]
no_license
willwsxu/cppPerf
b89f44c2705ff53514027b58bb482900d6f62672
fcf37bc7b7ff7678feba001696e5abde099955b2
refs/heads/master
2021-01-09T06:02:42.511366
2020-04-23T01:07:48
2020-04-23T01:07:48
80,876,503
0
0
null
2020-04-23T01:07:50
2017-02-03T22:55:49
C++
UTF-8
C++
false
false
8,348
cpp
main.cpp
#include <iostream> #include <vector> #include <deque> #include <list> #include <random> #include <set> #include <iterator> #include <string> #include "ConsoleLogger.h" #include "dynBuffer.h" #include "DynMsg.h" #include "matrix2D.h" #include "myalgo.h" using namespace std; typedef Matrix2D<int, vector> MatrixVii; typedef Matrix2D<int, vector>::ColIterator vii_col_iter; #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "..\catch.hpp" TEST_CASE("DynBuffer", "BUF") { CDynBuffer<Console,char> buf; buf.AppendData("Hello"); REQUIRE(buf.GetBufferLen() == 5); } TEST_CASE("DynMsg", "DMSG") { SECTION("basic") { CDynMsg<Console, char> buf; buf.AppendData("Hello"); REQUIRE(buf.GetBufferLen() == 5); } SECTION("copy") { CDynMsg<Console, char> buf; buf.AddMsg("Hello!", 6); CDynMsg<Console, char> buf2 = buf; CHECK(buf.GetBufferLen() == 10); CHECK(buf2.GetBufferLen() == 10); REQUIRE(buf2.GetNumMsgs() == 1); } } #include <thread> #include <mutex> thread_local unsigned int rage = 1; std::mutex cout_mutex; void increase_rage(const std::string& thread_name) { ++rage; // modifying outside a lock is okay; this is a thread-local variable std::lock_guard<std::mutex> lock(cout_mutex); std::cout << "Rage counter for " << thread_name << ": " << rage << '\n'; } void threadtest() { std::thread a(increase_rage, "a"), b(increase_rage, "b"); { std::lock_guard<std::mutex> lock(cout_mutex); std::cout << "Rage counter for main: " << rage << '\n'; } a.join(); b.join(); { std::lock_guard<std::mutex> lock(cout_mutex); std::cout << "After Rage counter for main: " << rage << '\n'; // rage is not changed in the main thread } } TEST_CASE("Thread local", "THREAD") { threadtest(); } TEST_CASE("Matrix", "[MATRIX1]") { MatrixVii vii; vii.emplace_back(vector<int>{2, 4, 6}); vii.emplace_back(vector<int>{1, 7, 7}); vii.emplace_back(vector<int>{1, 3, 7}); auto it = vii.begin(1); ++it; --it; it += 1; it -= 1; auto z=it + 1; auto y=it - 1; auto end = vii.end(1); auto size = end - it; vii_col_iter zz = z; zz = z; CHECK(count(vii.begin(1), end, 1) == 0); CHECK(count(vii.begin(1), end, 3)==1); CHECK(count_if(vii.begin(1), end, [](auto i) {return i % 2 == 0; }) == 1); CHECK(find_if(vii.begin(1), end, [](auto i) {return i % 2 == 0; }) != end); CHECK(is_sorted(vii.begin(1), vii.end(1)) == false); reverse(vii.begin(1), end); CHECK(*vii.begin(1) == 3); auto x= lower_bound(vii.begin(2), vii.end(2), 6); REQUIRE(*x == 6); } /* todo: iterator fails in stable_sort TEST_CASE("Matrix 2", "[MATRIX]") { MatrixVii vii; vii.emplace_back(vector<int>{2, 4, 6}); vii.emplace_back(vector<int>{1, 3, 7}); stable_sort(vii.begin(1), vii.end(1)); CHECK(vii[0][1] == 3); WXU::shuffle(vii.begin(1), vii.end(1)); stable_sort(vii.begin(1), vii.end(1)); CHECK(vii[1][1] == 4); CHECK(is_sorted(vii.begin(1), vii.end(1)) == true); } */ #include "courseSchedule.h" TEST_CASE("Course Schedule conflict", "SCHED") { std::vector<Schedule> schedule; const char*str[] = { "CS101", "W", "1730", "2030","CS242", "T", "1000", "1130","CS242", "T", "1230", "1430","CS242", "R", "1000", "1130","CS281", "T", "1300", "1430", "CS281", "R", "1300", "1430","CS282", "M", "1300", "1430","CS282", "W", "1300", "1430","CS201", "T", "1600", "1730","CS201", "R", "1600", "1730" }; auto count = sizeof(str) / sizeof(char*); std::copy(cstring_iterator<Schedule>(count, str, 4), cstring_iterator<Schedule>(), back_inserter(schedule)); CHECK(schedule.size() == 10); sort(begin(schedule), end(schedule)); copy(begin(schedule), end(schedule), ostream_iterator<Schedule>(cout, "\n")); auto conflict = adjacent_find(begin(schedule), end(schedule)); if (conflict != end(schedule)) { cout << "CONFLICT:" << endl; cout << *conflict << endl; cout << *(conflict + 1) << endl; } std::transform(begin(schedule), end(schedule) - 1, begin(schedule) + 1, begin(schedule), [](const auto& lhs, const auto& rhs)->const auto& { if (lhs == rhs) { cout << "CONFLICT:" << endl; cout << lhs << endl; cout << rhs << endl; } return lhs; }); copy(begin(schedule), end(schedule), ostream_iterator<Schedule>(cout, "\n")); } #include "movector.h" TEST_CASE("Small class Custom", "CUST") { string s("Irina"); Cust c1("Joe", "Fix",42); // 2 mallocs (2cr) Cust c2(s, "Fix", 42); // 2 mallocs (1cp + 1cr) Cust c3(move(s), "z"); // 1 mallocs (1mv + 1cr) Cust c4{ "Jill" }; Cust c5{ c4 }; Cust c6 = "Jill"; VIP v{ "Boss" }; VIP v2{ v }; Cust c7{ v }; } #include "eraseRemove.h" TEST_CASE("remove erase idiom", "[NEW]") { vector<int> v{ 1,2,3,4,5 }; erase_remove(v, 3); CHECK(v == vector<int>{1, 2, 4, 5}); deque<int> d{ 1,2,3,4,5 }; erase_remove(d, 3); CHECK(d == deque<int>{1, 2, 4, 5}); string st{ "12345" }; // string and set have same template signature, how to distinguish? erase_remove(st, '3'); CHECK(st == "1245"); list<int> l{ 1,2,3,4,5 }; erase_remove(l, 3); CHECK(l == list<int>{1, 2, 4, 5}); set<int> s{ 1,2,3,4,5 }; erase_remove(s, 3); CHECK(s == set<int>{1, 2, 4, 5}); } TEST_CASE("remove erase idiom with predicate", "[NEW]") { auto even = [](int i) { return i % 2 == 0; }; vector<int> v{ 1,2,3,4,5 }; erase_remove_if(v, even); CHECK(v == vector<int>{1, 3, 5}); deque<int> d{ 1,2,3,4,5 }; erase_remove_if2(d, even); CHECK(d == deque<int>{1, 3, 5}); string st{ "12345" }; // string and set have same template signature, how to distinguish? erase_remove_if(st, [](char i) { return (i-'0') % 2 == 0; }); CHECK(st == "135"); list<int> l{ 1,2,3,4,5 }; erase_remove_if(l, even); CHECK(l == list<int>{1, 3, 5}); set<int> s{ 1,2,3,4,5 }; erase_remove_if(s, even); CHECK(s == set<int>{1, 3, 5}); } class Base1 { private: int b1=0; public: int mf1() { return 1; } }; class Base2 { private: int b2 = 0; public: int mf2() { return 2; } }; class MultiInheritance : public Base1, public Base2 { private: int d = 0; public: int mf3() { return 3; } }; int test(MultiInheritance& obj, int (MultiInheritance::*mf)()) { printf("derived %p\n", mf); return (obj.*mf)(); } int test2(Base2& obj, int (Base2::*mf)()) { printf("Base2 %p\n", mf); return (obj.*mf)(); } TEST_CASE("member fun test multi inheritance pointer offset", "[NEW]") { MultiInheritance obj; Base1*pB1 = &obj; Base2*pB2=&obj; // pB1 address +4 MultiInheritance*pD = &obj; // same as pB1 address CHECK((Base1*)pB2 - pB1 == 1); CHECK((Base1*)pD - pB1 == 0); // pmf_b==pmf_a, c++ template complete guide ed 1 state adjust is different, but no longer in vs2015 compiler int (MultiInheritance::*pmf_a)() = &MultiInheritance::mf2; // adjustment of +4 recorded int (Base2::*pmf_b)() = (int (Base2::*)())pmf_a; // adjustment changed to 0 CHECK(test(obj, &MultiInheritance::mf1) == 1); CHECK(test(obj, &MultiInheritance::mf2) == 2); CHECK(test(obj, &MultiInheritance::mf3) == 3); CHECK(test(obj, &Base2::mf2) == 2); CHECK(test2(obj, &MultiInheritance::mf2) == 2); } #include "str.h" TEST_CASE("test construction", "[NEW]") { Str s1("test "); CHECK(s1.state == Str::STRING_MOVE_CTOR); string x("test2 "); Str s2(x); CHECK(s2.state == Str::STRING_CTOR); Str s2a(move(x)); CHECK(s2a.state == Str::STRING_MOVE_CTOR); Str s2b(string("test2b ")); CHECK(s2b.state == Str::STRING_MOVE_CTOR); Str s3(Str("test3 ")); // elision, one constructor call CHECK(s3.state == Str::STRING_MOVE_CTOR); Str s9 = string("test9 "); CHECK(s9.state == Str::STRING_MOVE_CTOR); Str s10 = "test10 "; // up to 2 conversions, const char * -> string -> Str CHECK(s10.state == Str::STRING_MOVE_CTOR); Str s4(s1); CHECK(s4.state == Str::COPY_CTOR); Str s4a(move(s1)); CHECK(s4a.state == Str::MOVE_CTOR); copy_elision(make_str("test5 ")); // elision, one constructor call copy_elision(Str("test5a ")); Str s6(make_str("test6 ")); CHECK(s6.state == Str::STRING_MOVE_CTOR); Str s7 = s6; CHECK(s7.state == Str::COPY_CTOR); Str s8 = move(s6); CHECK(s8.state == Str::MOVE_CTOR); s9 = move(s10); // move assignment s8 = s7; // copy assignment Str2 s20 = string("test20 "); // up to 2 conversions, string -> Str -> Str2 //Str2 s20 = "test20 "; can't compile } #include "mathlib_largeInt.h" TEST_CASE("large power", "[NEW]") { CHECK(Power_Large::compute(12345, 12345, 12)== 291259765625); }
6248aa436460535b1ec299db6392807df4efce79
0761707f0b1f038c1ee7ee6f96e419a108a61acc
/[kuangbin带你飞]专题十一 网络流/POJ1459.cpp
6204d35ce3cb7f74c2cea7fa7864408fbb6812c9
[ "MIT" ]
permissive
HardLearning/ACM_Solution
c27cc8ef655a50e799073ae3b41a1d825a7802d5
2495211017db828876d49910461f404ae0476261
refs/heads/master
2021-05-09T02:47:17.443012
2018-04-13T09:35:34
2018-04-13T09:35:34
119,221,299
2
1
null
null
null
null
UTF-8
C++
false
false
2,644
cpp
POJ1459.cpp
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <queue> using namespace std; const int INF = 1e9; const int maxn = 100+10; struct Edge{ int from,to,cap,flow; }; struct Dinic{ int m,s,t; vector<Edge>edges; vector<int>G[maxn]; bool vis[maxn]; int d[maxn]; int cur[maxn]; #define pb push_back void init(int n){ s = 0; t = n+1; edges.clear(); for (int i=s; i<=t; i++) G[i].clear(); } void addEdge(int from, int to, int cap){ edges.pb((Edge){from,to,cap,0}); edges.pb((Edge){to,from,0,0}); m = edges.size(); G[from].pb(m-2); G[to].pb(m-1); } bool BFS(){ queue<int>que; que.push(s); memset(vis,0,sizeof(vis)); vis[s] = 1; d[s] = 0; int u; while (!que.empty()){ u = que.front(); que.pop(); for (int i=0; i<G[u].size(); i++) { Edge& e = edges[G[u][i]]; if (!vis[e.to] && e.cap>e.flow){ vis[e.to] = 1; d[e.to] = d[u] + 1; que.push(e.to); } } } return vis[t]; } int DFS(int x, int a){ if (x==t || a==0) return a; int flow = 0, f; for (int& i=cur[x]; i<G[x].size(); i++){ Edge& e = edges[G[x][i]]; if (d[e.to]==d[x]+1 && (f=DFS(e.to,min(a,e.cap-e.flow)))>0 ){ flow += f; a -= f; e.flow += f; edges[G[x][i]^1].flow -= f; if (a==0) break; } } return flow; } int Maxflow(){ int flow = 0; while (BFS()){ memset(cur,0,sizeof(cur)); flow += DFS(s,INF); } return flow; } }dinic; int n,np,nc,m; int main(){ while (scanf("%d%d%d%d",&n,&np,&nc,&m)==4){ dinic.init(n); int u,v,z; char c; while (m--){ c = '!'; while (c!='(') c = getchar(); scanf("%d,%d)%d",&u,&v,&z); u++; v++; dinic.addEdge(u,v,z); } while (np--){ c = '!'; while (c!='(') c = getchar(); scanf("%d)%d",&u,&z); u++; dinic.addEdge(dinic.s,u,z); } while (nc--){ c = '!'; while (c!='(') c = getchar(); scanf("%d)%d",&u,&z); u++; dinic.addEdge(u,dinic.t,z); } printf("%d\n",dinic.Maxflow()); } return 0; }
b13f0f42019f3395bfc3c376320f03e804bc2b35
356a3ced7502c34b510bcd786f565bdf2a4c9492
/ACM-ICPC/hdu 4266.cpp
ae20ea75411c1df9ea31f8ce9fd0889380f75f59
[]
no_license
philokey/Algorithm-Problems
bb1872b50a0d9ef4bc27fd40e5775ffb872eb858
774d515661647748372a1a1b6850063e04d37c03
refs/heads/master
2020-12-24T14:09:50.828232
2015-06-30T13:29:54
2015-06-30T13:29:54
38,310,200
0
0
null
null
null
null
UTF-8
C++
false
false
5,459
cpp
hdu 4266.cpp
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <iostream> #include <queue> #define FI first #define SE second using namespace std; const double EPS = 1e-8; const int MAXN = 1005; const double INF = 1e50; inline double sqr(double x){return x*x;} inline int dcmp(double x) { if(fabs(x)<EPS) return 0; return x<0?-1:1; } struct Point3{ double x,y,z; Point3(){} Point3(double a,double b,double c):x(a),y(b),z(c){} Point3 operator+(const Point3 &a)const { return Point3(x+a.x,y+a.y,z+a.z); } Point3 operator-(const Point3 &a)const { return Point3(x-a.x,y-a.y,z-a.z); } Point3 operator/(double a)const { return Point3(x/a,y/a,z/a); } Point3 operator*(const Point3 &a)const { return Point3(y*a.z-z*a.y,z*a.x-x*a.z,x*a.y-y*a.x); } double operator^(const Point3 &a)const { return x*a.x+y*a.y+z*a.z; } double len(){return sqrt(x*x+y*y+z*z);} void input(){scanf("%lf%lf%lf",&x,&y,&z);} void output(){printf("%lf %lf% lf\n",x,y,z);} }; struct ConvexPolygon3D{ struct Face{ int a,b,c; //表示一个面上三个点的编号 bool flag; //是否属于凸包的面 }; int n; Point3 pt[MAXN]; int tri_num; Face face[8*MAXN]; int g[MAXN][MAXN];//凸包表面的三角形 double vlen(const Point3 &p) { return sqrt(sqr(p.x)+sqr(p.y)+sqr(p.z)); } double tri_area(Point3 a,Point3 b,Point3 c) { return vlen((a-c)*(b-c))/2; } double volume6(Point3 a,Point3 b,Point3 c,Point3 d)//四面体有向体积的六倍 { return ((b-a)*(c-a)^(d-a))/6; } double dlcmp(Point3 &p,Face &f)//判断点是否在面内,正:点在面同向 { Point3 m = pt[f.b]-pt[f.a]; Point3 n = pt[f.c]-pt[f.a]; Point3 t = p-pt[f.a]; return (m*n)^t; } void deal(int a,int b,int p) { int f = g[a][b]; Face add; if(face[f].flag) { if(dlcmp(pt[p],face[f])>EPS) dfs(p,f); else { add.a = b,add.b = a,add.c = p; add.flag = 1; g[p][b]=g[a][p]=g[b][a]=tri_num; face[tri_num++] = add; } } } void dfs(int p,int now) { face[now].flag = 0; deal(face[now].b,face[now].a,p); deal(face[now].c,face[now].b,p); deal(face[now].a,face[now].c,p); } bool same(int s,int t) { Point3 &a = pt[face[s].a]; Point3 &b = pt[face[s].b]; Point3 &c = pt[face[s].c]; bool res=fabs(volume6(a,b,c,pt[face[t].a]))<EPS&& fabs(volume6(a,b,c,pt[face[t].b]))<EPS&& fabs(volume6(a,b,c,pt[face[t].c]))<EPS; return res; } void solve() { int tmp; Face add; bool flag; tri_num = 0; if(n<4) return ; //先找到一个四面体 flag = true; for(int i = 1; i < n; i++)//第一个和第二个点不重合 { if(vlen(pt[0]-pt[i])>EPS) { swap(pt[1],pt[i]); flag = false; break; } } if(flag) return; flag = true; for(int i = 2; i < n; i++)//三点不共线 if(vlen((pt[0]-pt[1])*(pt[1]-pt[i]))>EPS) { swap(pt[2],pt[i]); flag = false; break; } if(flag) return; flag = true; for(int i = 3; i < n;i++)//四点不共面 if(fabs((pt[0]-pt[1])*(pt[1]-pt[2])^(pt[0]-pt[i]))>EPS) { swap(pt[3],pt[i]); flag = false; break; } if(flag) return; for(int i = 0; i < 4; i++) { add.a = (i+1)%4; add.b = (i+2)%4; add.c = (i+3)%4; add.flag = true; if(dlcmp(pt[i],add)>EPS) swap(add.b,add.c); g[add.a][add.b]=g[add.b][add.c]=g[add.c][add.a]=tri_num; face[tri_num++] = add; } for(int i = 4; i < n; i++) for(int j = 0; j < tri_num; j++) if(face[j].flag&&dlcmp(pt[i],face[j])>EPS) { dfs(i,j); break; } tmp = tri_num; for(int i = tri_num=0; i < tmp; i++) if(face[i].flag) face[tri_num++] = face[i]; } double area() { double res=0; if(n==3) { return tri_area(pt[0],pt[1],pt[2]); } else for(int i = 0; i < tri_num; i++) res+=tri_area(pt[face[i].a],pt[face[i].b],pt[face[i].c]); return res; } double volume() { double res; Point3 tmp(0,0,0); for(int i = 0; i < tri_num; i++) res+=volume6(tmp,pt[face[i].a],pt[face[i].b],pt[face[i].c]); return fabs(res); } Point3 get_center()//重心 { Point3 res(0,0,0),o(0,0,0),p; double sum,vol; sum = 0; for(int i = 0; i < tri_num; i++) { vol=volume6(o,pt[face[i].a],pt[face[i].b],pt[face[i].c]); sum+=vol; p = (pt[face[i].a]+pt[face[i].b]+pt[face[i].c])/4; p.x*=vol,p.y*=vol,p.z*=vol; res=res+p; } res=res/sum; return res; } int polygon_num() { int res=0; bool flag; for(int i = 0; i < tri_num; i++) { flag = 1; for(int j = 0; j < i; j++) if(same(i,j)) { flag = 0; break; } res+=flag; } return res; } double dis_p_f(Point3 p,Point3 a,Point3 b,Point3 c) { Point3 vec=(b-a)*(c-a); Point3 t = a-p; double tmp=(vec^t)/(vec.len()*t.len()); return fabs(t.len()*tmp); } double min_dis(Point3 p) { double ret = INF; for(int i = 0; i < tri_num; i++) { ret = min(ret,dis_p_f(p,pt[face[i].a],pt[face[i].b],pt[face[i].c])); } return ret; } }; int main() { //freopen("/home/qitaishui/code/in.txt","r",stdin); int n,m; ConvexPolygon3D p; Point3 pt; //cout<<":\n"; while(scanf("%d",&n)&&n) { //cout<<n<<endl; p.n = n; for(int i = 0; i < n;i++) p.pt[i].input(); p.solve(); scanf("%d",&m); for(int i = 0; i<m; i++) { double ans = INF; pt.input(); printf("%.4f\n",p.min_dis(pt)); } } return 0; }
9d07f0aefc6a95637138091a7d8676691d34ab92
2fb6e3860be751132d26502325a0c4559a794217
/cpac/chef/chficrm.cpp
39d2a7e3425c31522c1d429b9414851f7e2763cd
[ "MIT" ]
permissive
00mjk/Allcodes_codeWar
8af56bf4c74cbdef577fc34d991d6ec88d24c67f
0dfc3367ecc1df58f502f20ff3d732c49c62f140
refs/heads/master
2023-04-18T11:23:41.844829
2021-05-09T13:32:40
2021-05-09T13:32:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
chficrm.cpp
#include<bits/stdc++.h> using namespace std; #define abhinav ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); #define endl "\n" #define ll long long int int main() { abhinav; int t; cin>>t; while(t--) { int n,i; cin>>n; int change=0, val; string all="YES"; for(i=0;i<n;i++) { cin>>val; val-=5; if(val>change) all="NO"; else{ change+=5; change-=val; } } if(i==n) cout<<all<<endl; else cout<<all<<endl; } return 0; }
d40298a5ffb5d8d2f863e96987190df547be22ae
1db694c43ba7044acf28e4883d0d35213bad3311
/Cchart/Plot/Extended/ContourLinePlot/ContourLinePlot.h
93dd3ea6e7883322b9a9361a6acae106a67d2332
[]
no_license
shanrenshushu/monitor
0e6af131f41a211006dfd7a88a0f4c41edeb9661
7982228bc9d8e9c06ba343cb47c91cfd114a2f96
refs/heads/master
2021-06-23T12:09:47.493441
2020-10-22T08:31:11
2020-10-22T08:31:11
130,328,989
0
2
null
null
null
null
UTF-8
C++
false
false
1,566
h
ContourLinePlot.h
/*============================================================================*/ /* */ /* C O P Y R I G H T */ /* */ /* (C) Copyright 2011 by */ /* Yang Guojun */ /* All Rights Reserved */ /* */ /* The author assumes no responsibility for the use or reliability of */ /* his software. */ /* */ /*============================================================================*/ /* ############################################################################################################################## */ #ifndef __COUNTOURLINEPLOT_H_122333444455555__ #define __COUNTOURLINEPLOT_H_122333444455555__ // class CListContour; class CContourLinePlot { public: CContourLinePlot(); virtual ~CContourLinePlot(); protected: CListContour* m_pListContour; public: CListContour* GetContour() { return m_pListContour; } void SetFieldFcn(double (*_pFieldFcn) (double, double));//{m_listContour.SetFieldFcn(_pFieldFcn);} void SetPlotRange(double pRange[4]); }; #endif
f529623e2abf1279cdc03103967fc6d441115dfa
c5ad8aa67e8f0490e2aa050c92413282b33eb541
/Item.h
882e61d1490579b8303531e396e7eba57e48ae00
[]
no_license
JeffLuoo/CC3K
2cf2c62782dbbc75022bb1d4e16d385cc42d481f
84f383cfbeeb7f2bb3a3d5a8cae687805b0c3da8
refs/heads/master
2020-03-24T15:31:07.858241
2018-07-29T20:40:29
2018-07-29T20:40:29
142,792,641
0
0
null
null
null
null
UTF-8
C++
false
false
225
h
Item.h
#ifndef _ITEM_H #define _ITEM_H #include "GameObject.h" #include <string> #include <iostream> class Item : public GameObject { private: public: Item(); // 'P' or 'G' potion or gold ~Item(); }; #endif
f4a16781e5a531ef012248ac870eff5d818f43a2
5b6f7818038c2c05e16fe7222703af54ac6cac25
/ACSE5/ACSE5-CW/CSRMatrix.h
f202d7868f299f1a8a6f558107304757efb98301
[]
no_license
acse-jsy-2020/IC-ACSE
792a21774a714893433903d48b5248c3bcbd24e0
7b9f356e7c29470652bd0bb31a7150a28477cd93
refs/heads/master
2023-01-09T12:22:37.119402
2020-11-03T06:22:43
2020-11-03T06:22:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,411
h
CSRMatrix.h
#ifndef CSRMatrix_h #define CSRMatrix_h #include "Matrix.h" template <class T> class CSRMatrix: public Matrix<T> { public: // Explicitly using the C++11 nullptr here int *row_position = nullptr; int *col_index = nullptr; // How many non-zero entries we have in the matrix int nnzs=-1; // constructor where we want to preallocate ourselves CSRMatrix(int rows, int cols, int nnzs, bool preallocate); // constructor where we already have allocated memory outside CSRMatrix(int rows, int cols, int nnzs, T *values_ptr, int *row_position, int *col_index); // destructor ~CSRMatrix(); // deep copy constructor CSRMatrix(const CSRMatrix<T> & A); // copy assignment CSRMatrix<T> & operator=(const CSRMatrix<T> &v); // Move constructor CSRMatrix(CSRMatrix<T> && A); // Move assignment CSRMatrix<T> & operator=(CSRMatrix<T> && A); // Print out the values in our matrix virtual void printMatrix(); // Perform some operations with our matrix void matMatMult(CSRMatrix<T>& mat_right, CSRMatrix<T>& output); // Perform some operations with our matrix void matVecMult(double *input, double *output); template <class U> friend CSRMatrix<U> operator~(const CSRMatrix<U> & A); // Private variables - there is no need for other classes // to know about these variables private: }; #endif /* CSRMatrix_h */
a515c1b492b076b452d82619e6196fb939daf254
7a44204672c44e103aad47f3afd18952fbd9afd0
/src/SupportClasses/FIR_RingBuffer.h
755adebcc92c767cc2007ba18ff20fa17bcd6e77
[ "MIT" ]
permissive
AuditoryBiophysicsLab/EarLab
202acdb79489ea903c20e45239a9a3ba820caeba
bc5ccc39076ee0419078e9ff5147e98f28fac3c9
refs/heads/master
2020-04-15T20:45:36.062819
2019-07-10T11:54:27
2019-07-10T11:54:27
27,502,131
3
1
null
2017-06-28T01:53:57
2014-12-03T18:47:42
C++
UTF-8
C++
false
false
375
h
FIR_RingBuffer.h
#ifndef __FIR_RING_BUFFER_H_INCLUDED #define __FIR_RING_BUFFER_H_INCLUDED class FIR_RingBuffer { public: FIR_RingBuffer(int BufferLength); ~FIR_RingBuffer(); void AddSample(float NewSample); float &operator[](unsigned int index); float &operator[](int index); private: unsigned int StartIndex, EndIndex, BufferLength; float *Buffer; }; #endif
c85bd79327d0e69ed36c472e0fb60cd8940c050e
0f4c8d1c6235facbee0614d20a17e97b0caec71b
/Group_the_People_Given_the_Group_Size_They_Belong_To.cpp
ff82afbef2fd9c178423d87b87054a0e7d607e43
[]
no_license
JerryTheUser/Leetcode
4875151e17093bbdd315f5e0f2a2184f51eea2ec
b06cbd09113f9d606f50a8c58fd28ad7a80b3414
refs/heads/master
2021-06-20T03:20:29.181276
2020-12-19T13:03:30
2020-12-19T13:03:30
141,655,430
1
0
null
null
null
null
UTF-8
C++
false
false
845
cpp
Group_the_People_Given_the_Group_Size_They_Belong_To.cpp
#include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<vector<int>> groupThePeople(vector<int>& groupSizes) { vector<vector<int>> ret; unordered_map<int, vector<int>> table; for(int i=0 ; i<groupSizes.size() ; ++i){ table[groupSizes[i]].push_back(i); if(table[groupSizes[i]].size() == groupSizes[i]){ ret.push_back(table[groupSizes[i]]); table[groupSizes[i]].clear(); } } return ret; } }; int main(){ Solution sol; vector<int> input {3,3,3,3,3,1,3}; vector<vector<int>> result = sol.groupThePeople(input); for(auto&& i : result){ for(auto&& j : i){ cout << j << ' '; } cout << '\n'; } return 0; }
bcae8b1baae8ddef94070fc610993fbfd338c730
681c697d7b8d757c5f83b71e052636b75d498c03
/EventRegister.cpp
a331b4826f63d042abaaf88b80ac38df22b069d8
[]
no_license
OpenGL-Scene-Graph/Mocha-focused-on-geographical-map-displays
28d346e5f3effd1b3e92bf33ca8436ff5b6b2df7
15860ead100c9d175da7c400d0881d0d4ab7fdc5
refs/heads/master
2020-09-23T10:02:42.163493
2013-01-24T04:46:19
2013-01-24T04:46:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,401
cpp
EventRegister.cpp
#include <EventRegister.h> namespace Mocha { /***************************************/ CEventRegister::CEventRegister() /***************************************/ { ClearEventMask(); ClearSelectionMask(); } /***************************************/ CEventRegister::~CEventRegister() /***************************************/ { } /***************************************/ void CEventRegister::ClearEventMask() /***************************************/ { EventMask(0); } /***************************************/ void CEventRegister::ClearSelectionMask() /***************************************/ { SelectionMask(0); } /***************************************/ int CEventRegister::EventMask() /***************************************/ { return(_eventMask); } /***************************************/ void CEventRegister::EventMask(int mask) /***************************************/ { _eventMask = mask; } /***************************************/ bool CEventRegister::IsRegistered(MochaEventType eventToCatch) /***************************************/ { return(eventToCatch == (EventMask() & eventToCatch)); } /***************************************/ bool CEventRegister::IsRegisteredForSelection(MochaEventType eventToCatch) /***************************************/ { return(eventToCatch == (SelectionMask() & eventToCatch)); } /***************************************/ int CEventRegister::SelectionMask() /***************************************/ { return(_SelectionMask); } /***************************************/ void CEventRegister::SelectionMask(int mask) /***************************************/ { _SelectionMask = mask; } /***************************************/ void CEventRegister::Register(MochaEventType eventToCatch, bool onlyOnSelection) /***************************************/ { EventMask(EventMask() | eventToCatch); if(onlyOnSelection) SelectionMask(SelectionMask() | eventToCatch); else SelectionMask(SelectionMask() & ~(eventToCatch)); } /***************************************/ void CEventRegister::Unregister(MochaEventType eventToDisable) /***************************************/ { EventMask(EventMask() & (~(eventToDisable))); SelectionMask(SelectionMask() & (~(eventToDisable))); } }
3e8e0fae3182144ee28bdf6df286bcf47c05ed65
a1928b1382d8ced1b6e70e42c5b6bc977b7fb487
/allocore/allocore/math/al_Spherical.hpp
2671fa4695cce1c968fc495c3e66e774f5bdc6a4
[ "BSD-3-Clause" ]
permissive
AlloSphere-Research-Group/AlloSystem
59391f5b1be5e07f3d263875f80b9fe884d420a6
d559231048e91c51f7f8adf6b1e2ba5a6385bb1e
refs/heads/devel
2023-09-04T10:55:05.177183
2022-02-13T08:36:34
2022-02-13T08:36:34
3,911,722
52
24
null
2016-12-16T05:58:35
2012-04-02T21:16:12
C++
UTF-8
C++
false
false
8,403
hpp
al_Spherical.hpp
#ifndef INCLUDE_AL_SPHERICAL_HPP #define INCLUDE_AL_SPHERICAL_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the University of California nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File description: A collection of classes related to spherical geometry File author(s): Lance Putnam, 2011, putnam.lance@gmail.com */ #include "allocore/math/al_Complex.hpp" #include "allocore/math/al_Functions.hpp" #include "allocore/math/al_Vec.hpp" namespace al{ template <class T> class SphereCoord; typedef SphereCoord<float> SphereCoordf; ///< float SphereCoord typedef SphereCoord<double> SphereCoordd; ///< double SphereCoord /// Convert spherical to Cartesian coordinates in-place /// @param[in,out] r2x radius to x coordinate /// @param[in,out] t2y theta (angle on xy plane), in [-pi, pi], to z coordinate /// @param[in,out] p2z phi (angle from z axis), in [0, pi], to y coordinate template<class T> void sphericalToCart(T& r2x, T& t2y, T& p2z); /// Convert spherical to Cartesian coordinates in-place template<class T> void sphericalToCart(T * vec3); /// Convert Cartesian to spherical coordinates in-place /// @param[in,out] x2r x coordinate to radius /// @param[in,out] y2t y coordinate to theta (angle on xy plane), in [-pi, pi] /// @param[in,out] z2p z coordinate to phi (angle from z axis), in [0, pi] template<class T> void cartToSpherical(T& x2r, T& y2t, T& z2p); /// Convert Cartesian to spherical coordinates in-place template<class T> void cartToSpherical(T * vec3); /// Stereographic projection from an n-sphere to an n-1 dimensional hyperplane /// \tparam N dimensions of sphere /// \tparam T element type /// @param[in] v unit n-vector describing point on n-sphere /// \returns vector describing projected coordinate on n-1 hyperplane template <int N, class T> Vec<N-1,T> sterProj(const Vec<N,T>& v); /// Spherical coordinate in terms of two complex numbers /// The first component, theta, is the angle on the x-y plane and the second /// component, phi, is the angle from the +z axis. The magnitude of theta /// should always be 1, while the magnitude of phi is the radius. /// /// @ingroup allocore template <class T> class SphereCoord { public: typedef Complex<T> C; C t; ///< Theta component, longitudinal angle (angle from +x towards +y) C p; ///< Phi component, latitudinal angle (angle from +z axis) /// SphereCoord(const C& theta =C(1,0), const C& phi =C(1,0)) : t(theta), p(phi){} /// @param[in] v Cartesian position template <class U> SphereCoord(const Vec<3,U>& v){ fromCart(v); } /// Get negation in Cartesian space SphereCoord operator - () const { return SphereCoord(t, -p); } SphereCoord& operator *=(T v){ p*=v; return *this; } SphereCoord operator * (T v) const { return SphereCoord(t, p*v); } /// Get radius T radius() const { return p.mag(); } /// Returns Cartesian coordinate Vec<3,T> toCart() const{ return Vec<3,T>(t.r*p.i, t.i*p.i, p.r); } /// Set from two angles, in radians, and radius /// @param[in] theta longitudinal angle (angle from +x towards +y) /// @param[in] phi latitudinal angle (angle from +z axis) /// @param[in] radius radius SphereCoord& fromAngle(const T& theta, const T& phi, const T& radius =T(1)){ t.fromPolar(theta); p.fromPolar(radius, phi); return *this; } /// Set from Cartesian coordinate template <class U> SphereCoord& fromCart(const Vec<3,U>& v){ t.set(v[0], v[1]); T tmag = t.mag(); p.set(v[2], tmag); tmag != 0 ? t*=(1./tmag) : t.set(1,0); return *this; } }; /// Spherical harmonic evaluator using cached coefficients /// Spherical harmonics are solutions to Laplace's differential equation on the /// surface of a 2-sphere. The solutions are complex functions parameterized by /// two integers, l and m, and two angles defining an orientation in space. /// The l number determines the number of nodal lines (circles with zero /// magnitude) and m determines the number of latitudinal nodal lines /// (geodesics intersecting the z axis). When |m| = l, the harmonics are "beach /// ball"-like (sectoral) and when m = 0, the harmonics are "target"-like /// (zonal). Other values of m produce a checkerboard pattern (tesseral). /// Th Condon-Shortley phase factor of (-1)^m is included. /// /// @ingroup allocore template <int L_MAX=16> class SphericalHarmonic{ public: SphericalHarmonic(){ createLUT(); } /// Evaluate spherical harmonic /// @param[in] l number of nodal lines /// @param[in] m number of latitudinal nodal lines, |m| <= l /// @param[in] ctheta unit magnitude complex number describing longitudinal angle in [0, 2pi] /// @param[in] cphi unit magnitude complex number describing latitudinal angle in [0, pi] template <class T> Complex<T> operator()(int l, int m, const Complex<T>& ctheta, const Complex<T>& cphi) const { return coef(l,m) * al::legendreP(l, al::abs(m), cphi.r, cphi.i) * expim(m, ctheta); } template <class T> static Complex<T> expim(int m, const Complex<T>& ctheta){ Complex<T> res = al::powN(ctheta, al::abs(m)); if(m < 0) res.i = -res.i; return res; } /// Get normalization coefficient static double coef(int l, int m){ return l<=L_MAX ? coefTab(l,m) : coefCalc(l,m); } /// Get normalization coefficient (tabulated) static const double& coefTab(int l, int m){ return LUT(l,m); } /// Get normalization coefficient (calculated) static double coefCalc(int l, int m){ int M = al::abs(m); double res = ::sqrt((2*l + 1) / M_4PI) * al::factorialSqrt(l-M) / al::factorialSqrt(l+M); return (m<0 && al::odd(M)) ? -res : res; } private: // this holds precomputed coefficients for each basis static double& LUT(int l, int m){ static double t[L_MAX+1][L_MAX*2+1]; return t[l][m+L_MAX]; } static void createLUT(){ static bool make=true; if(make){ make=false; for(int l=0; l<=L_MAX; ++l){ for(int m=-L_MAX; m<=L_MAX; ++m){ double c=0; // m must be in [-l,l] if(al::abs(m) <= l) c = coefCalc(l,m); LUT(l, m) = c; } } } } }; /// Spherical harmonic function static SphericalHarmonic<> spharm; // Implementation //------------------------------------------------------------------------------ template <class T> void sphericalToCart(T& r, T& t, T& p){ T rsinp = r * sin(p); T rcosp = r * cos(p); r = rsinp * cos(t); t = rsinp * sin(t); p = rcosp; } template <class T> inline void sphericalToCart(T * vec3){ sphericalToCart(vec3[0], vec3[1], vec3[2]); } template <class T> void cartToSpherical(T& x, T& y, T& z){ T r = sqrt(x*x + y*y + z*z); T t = atan2(y, x); z = acos(z/r); y = t; x = r; } template <class T> inline void cartToSpherical(T * vec3){ cartToSpherical(vec3[0], vec3[1], vec3[2]); } template <int N, class T> inline Vec<N-1,T> sterProj(const Vec<N,T>& v){ return sub<N-1>(v) * (T(1)/v[N-1]); } } // ::al #endif
fcecc85f910905535bf8a8ba101e8842256c28c4
603af95665a7432245bc4ced8a00cdc7b009876e
/Menu.h
f23ac1ff418002e78355d1fa6f669994fe4a2a93
[]
no_license
npbtien1100/DoAn_CTDL
591b77d219239539c1db74dc02ce27251cadd0ae
618073f4b1db45e05e45bf1c2492a434a8bf305a
refs/heads/master
2020-09-06T00:42:40.445715
2019-11-07T15:29:17
2019-11-07T15:29:17
220,261,740
0
0
null
2019-11-07T15:26:11
2019-11-07T14:56:56
C++
WINDOWS-1252
C++
false
false
346
h
Menu.h
// // Menu.h // Matrix1 // // Created by Admin on 11/1/19. // Copyright © 2019 tvt3. All rights reserved. // #ifndef Menu_h #define Menu_h #include<iostream> #include"Matrix.h" #include<vector> #include"Vector.h" #include"TEST.h" #include<Windows.h> using namespace std; int ChooseMenu(); void Menu(); #endif /* Menu_h */
c2b1799b849098e36905fccca125cb8ca37b29c3
dacf17dcc45b8d8a4a8aa9301582ae5e16ea7036
/psdaq/psdaq/eb/EbLfClient.cc
d440ced0108c4223750e9010772f9cd75cd434b0
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
elliottslaughter/lcls2
779a2ec542508f058f1a7e32e29ba429903f1da5
faecf0387c1fd3a41cf29cb66de702b7b651a60d
refs/heads/master
2021-06-11T11:26:09.157609
2018-10-16T21:57:53
2018-10-16T21:58:08
113,411,348
0
0
null
2017-12-07T06:21:26
2017-12-07T06:21:26
null
UTF-8
C++
false
false
3,328
cc
EbLfClient.cc
#include "EbLfClient.hh" #include "EbLfLink.hh" #include "Endpoint.hh" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> // For sleep()... #include <assert.h> #include <chrono> using namespace Pds; using namespace Pds::Fabrics; using namespace Pds::Eb; using ms_t = std::chrono::milliseconds; EbLfClient::EbLfClient() { } EbLfClient::~EbLfClient() { } int EbLfClient::connect(const char* peer, const char* port, unsigned tmo, EbLfLink** link) { const uint64_t flags = 0; const size_t txSize = 0; const size_t rxSize = 0; Fabric* fab = new Fabric(peer, port, flags, txSize, rxSize); if (!fab || !fab->up()) { fprintf(stderr, "%s: Failed to create Fabric for %s:%s: %s\n", __PRETTY_FUNCTION__, peer, port, fab ? fab->error() : "No memory"); return fab ? fab->error_num() : -FI_ENOMEM; } //void* data = fab; // Something since data can't be NULL //printf("EbLfClient is using LibFabric version '%s', fabric '%s', '%s' provider version %08x\n", // fi_tostr(data, FI_TYPE_VERSION), fab->name(), fab->provider(), fab->version()); CompletionQueue* txcq = new CompletionQueue(fab); if (!txcq) { fprintf(stderr, "%s: Failed to create TX completion queue: %s\n", __PRETTY_FUNCTION__, "No memory"); return -FI_ENOMEM; } printf("Waiting for EbLfServer %s:%s\n", peer, port); Endpoint* ep = nullptr; bool tmoEnabled = tmo != 0; int timeout = tmoEnabled ? tmo : -1; // mS auto t0(std::chrono::steady_clock::now()); auto t1(t0); uint64_t dT = 0; while (true) { CompletionQueue* rxcq = nullptr; ep = new Endpoint(fab, txcq, rxcq); if (!ep || (ep->state() != EP_UP)) { fprintf(stderr, "%s: Failed to initialize Endpoint: %s\n", __PRETTY_FUNCTION__, ep ? ep->error() : "No memory"); return ep ? ep->error_num() : -FI_ENOMEM; } if (ep->connect(timeout, FI_TRANSMIT | FI_SELECTIVE_COMPLETION, 0)) break; if (ep->error_num() == -FI_ENODATA) break; // connect() timed out t1 = std::chrono::steady_clock::now(); dT = std::chrono::duration_cast<ms_t>(t1 - t0).count(); if (tmoEnabled && (dT > tmo)) break; delete ep; // Can't try to connect on an EP a 2nd time usleep(100000); } if ((ep->error_num() != FI_SUCCESS) || (tmoEnabled && (dT > tmo))) { int rc = ep->error_num(); fprintf(stderr, "%s: Error connecting to %s:%s: %s\n", __PRETTY_FUNCTION__, peer, port, (rc == FI_SUCCESS) ? ep->error() : "Timed out"); delete ep; return (rc != FI_SUCCESS) ? rc : -FI_ETIMEDOUT; } printf("txDepth = %zd\n", fab->info()->tx_attr->size); *link = new EbLfLink(ep); if (!*link) { fprintf(stderr, "%s: Failed to find memory for link\n", __PRETTY_FUNCTION__); return ENOMEM; } return 0; } int EbLfClient::shutdown(EbLfLink* link) { if (link) { Endpoint* ep = link->endpoint(); delete link; if (ep) { CompletionQueue* txcq = ep->txcq(); Fabric* fab = ep->fabric(); delete ep; if (txcq) delete txcq; if (fab) delete fab; } } return 0; }
ed90c7cfe71c638c56c9e3ff008539780e20e459
bed05496e526a2716d6aa2ca7904c1b89c9058f3
/SPOJ/fibonaccisum.cpp
bff9b71faa53b4bd7743d17cc0858f58daac6d85
[]
no_license
dushyant7917/Competitive-Programming
2e5b6141e87f42bb5dbb61db3b6bcb383c559c16
d25bbb12235bdaf42435342e4865b5b0b6b37a31
refs/heads/master
2020-06-28T12:05:58.959849
2019-08-02T12:24:15
2019-08-02T12:24:15
200,230,019
0
0
null
null
null
null
UTF-8
C++
false
false
1,084
cpp
fibonaccisum.cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef double dbl; #define fr(x,a,b) for(ll x=a;x<b;x++) #define PB push_back #define MP make_pair #define mod 1000000007 #define gmax LLONG_MAX #define gmin LLONG_MIN #define INF 2e9 #define N 1000000001 #define MAX(a,b,c) max(max(a,b),c) #define MIN(a,b,c) min(min(a,b),c) void multiply(ll f[2][2],ll m[2][2]){ ll c[2][2]; fr(i,0,2){ fr(j,0,2){ c[i][j]=0; fr(k,0,2) c[i][j]=((c[i][j]%mod)+((f[i][k]*m[k][j])%mod))%mod; } } fr(i,0,2){ fr(j,0,2) f[i][j]=c[i][j]; } } void power(ll f[2][2],ll n){ if(n==0 || n==1) return; ll m[2][2]={{1,1},{1,0}}; power(f,n/2); multiply(f,f); if(n%2!=0) multiply(f,m); } ll fib(ll n){ ll f[2][2]={{1,1},{1,0}}; if(n==0) return 0; power(f,n-1); return f[0][0]; } int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll t; cin>>t; ll n,m,ans; while(t--){ cin>>n>>m; ans=(fib(m+2)-1)-(fib(n+1)-1); if(ans<0) cout<<ans+mod<<"\n"; else cout<<ans<<"\n"; } return 0; }
db7a71009e77f34857e99852bc677e95226ccc70
c4dd387d1a2339c2910370671d4ec04246c402d2
/SmartPoint/SmartPoint/MainCharacter.h
84be5726a4b702366faf4c0f17cec864252a8c45
[]
no_license
liuqiangNetease/SmartPoint
341c33a83502b27ffc464219352b1ba87d7caf4c
74b981e1c56992b83ec9f6c25fc144d3c468a12c
refs/heads/master
2020-03-18T18:55:10.988885
2018-10-26T08:10:38
2018-10-26T08:10:38
135,122,607
0
0
null
null
null
null
UTF-8
C++
false
false
930
h
MainCharacter.h
// // MainCharacter.h // SmartPoint // // Created by liuqiang on 2018/9/12. // Copyright © 2018年 liuqiang. All rights reserved. // #ifndef MainCharacter_h #define MainCharacter_h #include <iostream> #include <memory> #include <vector> #include "FollowObject.h" class MainCharacter { public: MainCharacter() { printf("MainCharacter()\n"); } ~MainCharacter() { printf("~MainCharactor() \n"); } void SetFollow(FollowObjectWeakPtr object) { m_ptrFollow = object;} void Update() { if(m_ptrFollow.expired() == false) { FollowObjectPtr follow = m_ptrFollow.lock(); follow->GetPosition(); } else { printf("weakpoint expired!\n"); } } FollowObjectWeakPtr m_ptrFollow; }; typedef std::shared_ptr<MainCharacter> MainCharacterPtr; #endif /* MainCharacter_h */
1a1d4248e9c151f71c7f3bb765d9a17c31f53b8b
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/Simulation/G4SimCnv/G4SimTPCnv/test/TrackRecordCnv_p1_test.cxx
349dbe6a1fadfdd1885eed0a1d69dd87d5756620
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
1,788
cxx
TrackRecordCnv_p1_test.cxx
/* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ /** * @file G4SimTPCnv/test/TrackRecordCnv_p1_test.cxx * @author scott snyder <snyder@bnl.gov> * @date Dec, 2019 * @brief Tests for TrackRecordCnv_p1. */ #undef NDEBUG #include "G4SimTPCnv/TrackRecordCnv_p1.h" #include "G4SimTPCnv/TrackRecord_p1.h" #include "TrackRecord/TrackRecord.h" #include "TestTools/leakcheck.h" #include "GaudiKernel/MsgStream.h" #include <cassert> #include <iostream> void compare (const CLHEP::Hep3Vector& p1, const CLHEP::Hep3Vector& p2) { assert ( p1.x() == p2.x() ); assert ( p1.y() == p2.y() ); assert ( p1.z() == p2.z() ); } void compare (const TrackRecord& p1, const TrackRecord& p2) { assert ( p1.GetPDGCode() == p2.GetPDGCode() ); assert ( p1.GetEnergy() == p2.GetEnergy() ); assert ( p1.GetTime() == p2.GetTime() ); assert ( p1.GetBarCode() == p2.GetBarCode() ); assert ( p1.GetVolName() == p2.GetVolName() ); compare ( p1.GetPosition(), p2.GetPosition() ); compare ( p1.GetMomentum(), p2.GetMomentum() ); } void testit (const TrackRecord& trans1) { MsgStream log (0, "test"); TrackRecordCnv_p1 cnv; TrackRecord_p1 pers; cnv.transToPers (&trans1, &pers, log); TrackRecord trans2; cnv.persToTrans (&pers, &trans2, log); compare (trans1, trans2); } void test1() { std::cout << "test1\n"; Athena_test::Leakcheck check; TrackRecord trans1 (123, 124.5, CLHEP::Hep3Vector (10.5, 11.5, 12.5), CLHEP::Hep3Vector (20.5, 21.5, 22.5), 125.5, 126, "vol"); testit (trans1); } int main() { std::cout << "G4SimTPCnv/TrackRecordCnv_p1_test\n"; test1(); return 0; }
31ad5ae23d133d6bcd9422c6a56db75498126a80
3bca6aed70e802f4ab5410e29ab522456ec5360f
/source/include/ExPROM/EEPROM_Header.cpp
17234694d01f02c7e58a5c4c071aa3a22c34662b
[]
no_license
mat-cab/ESP8266-Daikin-Remote
f2837b9bb1b0901c9d1fca605d2e1fa775591d4e
efe8189b4a429d7fff5bfab573a21741c595352e
refs/heads/master
2022-04-26T17:25:26.491659
2022-04-23T02:00:33
2022-04-23T02:13:53
96,718,863
1
0
null
null
null
null
UTF-8
C++
false
false
1,297
cpp
EEPROM_Header.cpp
#include "EEPROM_Header.h" EEPROM_Header::EEPROM_Header() { this->reset(); } void EEPROM_Header::reset() { // Reset the indexes this->resetActionIndex(); this->resetMeasurementIndex(); } void EEPROM_Header::resetActionIndex() { this->setActionIndex(0); } void EEPROM_Header::resetMeasurementIndex() { this->measurementIndexStart = 0; this->measurementIndexEnd = 0; } void EEPROM_Header::resetMeasurementIndexEnd() { this->measurementIndexEnd = 0; } uint16_t EEPROM_Header::getActionIndex() const { return (this->actionIndex); } uint16_t EEPROM_Header::getMeasurementIndexStart() const { return (this->measurementIndexStart); } uint16_t EEPROM_Header::getMeasurementIndexEnd() const { return (this->measurementIndexEnd); } void EEPROM_Header::setActionIndex(uint16_t newIndex) { this->actionIndex = newIndex; } void EEPROM_Header::resetMeasurementIndexStart(uint16_t newStart) { this->measurementIndexStart = newStart; } uint16_t EEPROM_Header::increaseActionIndex(uint8_t increase) { return (this->actionIndex += increase); } uint16_t EEPROM_Header::increaseMeasurementIndexEnd() { return (this->measurementIndexEnd += 1); } uint16_t EEPROM_Header::increaseMeasurementIndexStart(uint16_t increase) { return (this->measurementIndexStart += increase); }
bf079449975e5ecca590315d0a376e860db9e7e8
5e76744b541add1c8c0b1d3b5f071733d75ede74
/opsin_image.cc
d7305f4eefcee00433e99b5a219d0495b114030b
[ "Apache-2.0" ]
permissive
TiKevin83/pik
2ea3dfb5e097e95cc57714066b0fe838236cd572
56e644f3b7530ea9faeaa32f315329cc98604c2b
refs/heads/master
2020-03-20T05:35:58.132378
2018-07-11T13:08:30
2018-07-11T13:08:30
137,219,978
0
0
Apache-2.0
2018-07-11T13:08:32
2018-06-13T13:33:02
C++
UTF-8
C++
false
false
3,865
cc
opsin_image.cc
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "opsin_image.h" #include <stddef.h> #include <array> #undef PROFILER_ENABLED #define PROFILER_ENABLED 1 #include "approx_cube_root.h" #include "compiler_specific.h" #include "gamma_correct.h" #include "profiler.h" namespace pik { namespace { PIK_INLINE float SimpleGamma(float v) { return ApproxCubeRoot(v); } void LinearXybTransform(float r, float g, float b, float* PIK_RESTRICT valx, float* PIK_RESTRICT valy, float* PIK_RESTRICT valz) { *valx = (kScaleR * r - kScaleG * g) * 0.5f; *valy = (kScaleR * r + kScaleG * g) * 0.5f; *valz = b; } void LinearToXyb(const float rgb[3], float* PIK_RESTRICT valx, float* PIK_RESTRICT valy, float* PIK_RESTRICT valz) { float mixed[3]; OpsinAbsorbance(rgb, mixed); mixed[0] = SimpleGamma(mixed[0]); mixed[1] = SimpleGamma(mixed[1]); mixed[2] = SimpleGamma(mixed[2]); LinearXybTransform(mixed[0], mixed[1], mixed[2], valx, valy, valz); } } // namespace void RgbToXyb(uint8_t r, uint8_t g, uint8_t b, float* PIK_RESTRICT valx, float* PIK_RESTRICT valy, float* PIK_RESTRICT valz) { // TODO(janwas): replace with polynomial to enable vectorization. const float* lut = Srgb8ToLinearTable(); const float rgb[3] = {lut[r], lut[g], lut[b]}; LinearToXyb(rgb, valx, valy, valz); } Image3F OpsinDynamicsImage(const Image3B& srgb) { PROFILER_FUNC; // This is different from butteraugli::OpsinDynamicsImage() in the sense that // it does not contain a sensitivity multiplier based on the blurred image. const size_t xsize = srgb.xsize(); const size_t ysize = srgb.ysize(); Image3F opsin(xsize, ysize); for (size_t iy = 0; iy < ysize; iy++) { const uint8_t* PIK_RESTRICT row_srgb0 = srgb.ConstPlaneRow(0, iy); const uint8_t* PIK_RESTRICT row_srgb1 = srgb.ConstPlaneRow(1, iy); const uint8_t* PIK_RESTRICT row_srgb2 = srgb.ConstPlaneRow(2, iy); float* PIK_RESTRICT row_xyb0 = opsin.PlaneRow(0, iy); float* PIK_RESTRICT row_xyb1 = opsin.PlaneRow(1, iy); float* PIK_RESTRICT row_xyb2 = opsin.PlaneRow(2, iy); for (size_t ix = 0; ix < xsize; ix++) { RgbToXyb(row_srgb0[ix], row_srgb1[ix], row_srgb2[ix], &row_xyb0[ix], &row_xyb1[ix], &row_xyb2[ix]); } } return opsin; } Image3F OpsinDynamicsImage(const Image3F& linear) { PROFILER_FUNC; // This is different from butteraugli::OpsinDynamicsImage() in the sense that // it does not contain a sensitivity multiplier based on the blurred image. const size_t xsize = linear.xsize(); const size_t ysize = linear.ysize(); Image3F opsin(xsize, ysize); for (size_t iy = 0; iy < ysize; iy++) { const float* PIK_RESTRICT row_in0 = linear.ConstPlaneRow(0, iy); const float* PIK_RESTRICT row_in1 = linear.ConstPlaneRow(1, iy); const float* PIK_RESTRICT row_in2 = linear.ConstPlaneRow(2, iy); float* PIK_RESTRICT row_xyb0 = opsin.PlaneRow(0, iy); float* PIK_RESTRICT row_xyb1 = opsin.PlaneRow(1, iy); float* PIK_RESTRICT row_xyb2 = opsin.PlaneRow(2, iy); for (size_t ix = 0; ix < xsize; ix++) { const float rgb[3] = {row_in0[ix], row_in1[ix], row_in2[ix]}; LinearToXyb(rgb, &row_xyb0[ix], &row_xyb1[ix], &row_xyb2[ix]); } } return opsin; } } // namespace pik
c3b376cd2c7dd548a320362fae3128522b0fbd07
b643c0422cc9b5da1c86232928575289473765a1
/c++/dp/maxTurbulenceSize.cc
834ca32b5e49ded4f0b83e77e5b1082ce44591c0
[]
no_license
sjc2870/LeetCode
c63b93db422f680a3d3c3ee138769444e1b64a84
752ff83a69ad233651e3c73ae9864a8bcc4a8a9a
refs/heads/master
2023-05-13T07:30:41.945834
2023-05-04T09:00:57
2023-05-04T09:01:58
274,354,613
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
cc
maxTurbulenceSize.cc
#include <vector> #include <string.h> #include <stdio.h> #include <algorithm> using namespace std; /* 算法思想:用一个数组dp来存放当前连续湍流子数组的长度 * dp[i]的默认值为1或者2 * 当计算dp[i]时,我们已知道dp[i-1]的值,如果当前序列可以与上一个数字组成湍流数组,则取一个较大值 * 否则就为默认值 */ class Solution { public: int maxTurbulenceSize(vector<int>& arr) { int len = arr.size(); if(len == 1) return 1; /* vector<int> dp(len,0); */ int *dp = new int[len]; memset(dp,0,len*sizeof(int)); dp[0] = 1; dp[1] = (arr[0]==arr[1] ? 1 : 2); for(int i = 2; i < len; ++i) { dp[i] = (arr[i-1] != arr[i] ? 2 : 1); if((arr[i-2] < arr[i-1] && arr[i-1] > arr[i]) || (arr[i-2] > arr[i-1] && arr[i-1] < arr[i])) { dp[i] = std::max(dp[i], dp[i-1]+1); } } int ret = 1; for(int i = 0; i < len; ++i) { if(dp[i] > ret) { ret = dp[i]; } } /* return *(std::max_element(dp.begin(),dp.end())); */ return ret; } };
7e926b102e1a91368e69ed690ed5a682a0b0e95c
8db57a3f0db771c2924bc10455361c142680d36f
/Workout/test/test.ino
26b469d1a284b155c6cc8651f12e570061cbc8c6
[]
no_license
nawavit0/arduino-code
d658df9fb896ae5afb5de3c7e9a58342d3c6af9e
a73452cb519208a7e835946c6d489f4d91facf77
refs/heads/master
2020-04-09T05:05:17.209273
2018-12-02T14:24:19
2018-12-02T14:24:19
160,050,612
0
0
null
null
null
null
UTF-8
C++
false
false
317
ino
test.ino
#define RX 1 #define TX 3 #include "SoftwareSerial.h" SoftwareSerial myESP(RX,TX); void setup() { Serial.begin(9600); myESP.begin(9600); } void loop() { if (Serial.available()) { myESP.write("Tª4100500000MC9--"); while(myESP.available() > 0) { Serial.println(myESP.read()); } } }
2e114549beba91b5217c14ef76ff5c502af027ba
f8ca5b99e780f390081b8afd285239326ba589e8
/src/libsalt/Link.cpp
25a09af4acb247add687ead237d1e9ee0e03bb7f
[ "Apache-2.0" ]
permissive
ksh1006/traffic-simulator
4ef36ffbc217d3517fdf051f87572d8620d326c3
a0f05c6b75d91d6405cbcb60a5d6fadb731f6785
refs/heads/master
2023-01-14T07:38:15.837212
2020-11-16T01:36:41
2020-11-16T01:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,331
cpp
Link.cpp
/****************************************************************************/ // C++ libsalt.link API implementation /****************************************************************************/ #include <algorithm> #include <json/json.h> #include <Object/NetworkManager.h> #include <utils/ParserSALT.h> #include <libsalt/LibsaltDefs.h> #include "Link.h" #include "utils/config.h" #include "Simulation.h" namespace libsalt { // =========================================================================== // Getter Implementation // =========================================================================== std::vector<LibsaltLink> Link::getLinkList() { std::vector<LibsaltLink> links; std::vector<SALT::Link*> rs = Simulation::getNetworkManager()->getLinkList(); for (SALT::Link* r : rs) { LibsaltLink link = LibsaltLink(r); links.push_back(link); } return links; } std::vector<LibsaltLink> Link::getValidLinkList() { std::vector<LibsaltLink> links; const auto rs = Simulation::getNetworkManager()->getValidLinkList(); for (auto r: rs){ LibsaltLink link = LibsaltLink(r); links.push_back(link); } return links; } LibsaltLink Link::getLink(const std::string& linkID) { std::vector<LibsaltLink> links = getLinkList(); LibsaltLink link = std::find(links.begin(), links.end(), linkID).operator*(); return link; } std::vector<LibsaltLane> Link::getLaneList(const std::string& linkID) { std::vector<LibsaltLane> lanes; int numLane = Simulation::getNetworkManager()->findLinkByID(linkID)->getNumLane(); for (int i = 0; i < numLane; i++) { LibsaltLane lane = LibsaltLane(linkID, i); lanes.push_back(lane); } return lanes; } int Link::getLength(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getLength(); } int Link::getNumLane(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getNumLane(); } int Link::getNumSection(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getNumSection(); } float Link::getSpeedLimit(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getMySpeedLimit(); } float Link::getSumPassed(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getSumPassingCount(); } float Link::getAverageWaitingQLength(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getAverageWaitingQLength(); } float Link::getAverageWaitingTime(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getAverageWaitingTime(); } float Link::getAverageDensity(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getAverageDensity(); } float Link::getAverageSpeed(const std::string& linkID) { SALT::Link* link = Simulation::getNetworkManager()->findLinkByID(linkID); int section = getNumSection(linkID); int lane = getNumLane(linkID); float sumSpeed = 0.0; float avgSpeed = 0.0; int numCounts = 0; for (int i = 0; i < section; i++) { for (int j = 0; j < lane; j++) { SALT::CellInterface* cell = link->getCellByIndex(i, j); float cellSpeed = cell->getAverageSpeed(); if (cellSpeed != 0) { sumSpeed += cellSpeed; numCounts++; } } } // avgSpeed = sumSpeed / numCells; if (numCounts != 0) { avgSpeed = sumSpeed / numCounts; } return avgSpeed; } float Link::getAverageVehicleSpeed(const std::string& linkID) { SALT::Link* link = Simulation::getNetworkManager()->findLinkByID(linkID); int section = getNumSection(linkID); int lane = getNumLane(linkID); float sumSpeed = 0.0; float avgSpeed = 0.0; int numCounts = 0; for (int i = 0; i < section; i++) { for (int j = 0; j < lane; j++) { SALT::CellInterface* cell = link->getCellByIndex(i, j); float cellSpeed = cell->getAverageVehicleSpeed(); if (cellSpeed != 0) { sumSpeed += cellSpeed; numCounts++; } } } // avgSpeed = sumSpeed / numCells; if (numCounts != 0) { avgSpeed = sumSpeed / numCounts; } // if (avgSpeed > 100.0) { // std::cout << "linkID=" << linkID << ", avgSpeed=" << avgSpeed << ", counts=" << numCounts << std::endl; // } return avgSpeed; } float Link::getSumTravelLength(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getSumTravelLength(); } float Link::getSumTravelTime(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getSumTravelTime(); } std::tuple<float, float, float> Link::computeWaitingVehicleInfo(const string &linkID, int currentStep, int lastSwitchingTime) { return Simulation::getNetworkManager()->findLinkByID(linkID)->computeVehWait(currentStep, lastSwitchingTime); } float Link::getAverageVehicleWaitingTime(const string &linkID, int currentStep, int lastSwitchingTime) { return get<1>(computeWaitingVehicleInfo(linkID, currentStep, lastSwitchingTime)); } float Link::getAverageVehicleWaitingQLength(const string &linkID, int currentStep, int lastSwitchingTime) { return get<2>(computeWaitingVehicleInfo(linkID, currentStep, lastSwitchingTime)); } float Link::getNumWaitingVehicle(const string &linkID, int currentStep, int lastSwitchingTime) { return get<0>(computeWaitingVehicleInfo(linkID, currentStep, lastSwitchingTime)); } LibsaltCell Link::getCellByIndex(const std::string& linkID, int section, int lane) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getCellByIndex(section, lane); } std::string Link::getTrafficSignalState(const std::string& linkID, const std::string& nextLinkID) { SALT::Link* nextLink = Simulation::getNetworkManager()->findLinkByID(nextLinkID); SALT::TrafficSignalState state = Simulation::getNetworkManager()->findLinkByID(linkID)->getTrafficSignalState(nextLink); std::string s; if (state == SALT::TrafficSignalState::GREEN) { s = "G"; } else if (state == SALT::TrafficSignalState::WEAK_GREEN) { s = "g"; } else if (state == SALT::TrafficSignalState::RED) { s = "r"; } else { // YELLOW s = "y"; } return s; } LibsaltConnection Link::getAnyConnectionTo(const std::string& linkID, const std::string& nextLinkID) { SALT::Link* nextLink = Simulation::getNetworkManager()->findLinkByID(nextLinkID); SALT::Connection* c = Simulation::getNetworkManager()->findLinkByID(linkID)->getAnyConnectionTo(nextLink); LibsaltConnection conn = LibsaltConnection(c); return conn; } LibsaltConnection Link::getConnectionTo(const std::string& linkID, const std::string& nextLinkID, int fromLane) { SALT::Link* nextLink = Simulation::getNetworkManager()->findLinkByID(nextLinkID); SALT::Connection* c = Simulation::getNetworkManager()->findLinkByID(linkID)->getConnectionTo(nextLink, fromLane); LibsaltConnection conn = LibsaltConnection(c); return conn; } bool Link::canReach(const std::string& linkID, const std::string& nextLinkID) { SALT::Link* nextLink = Simulation::getNetworkManager()->findLinkByID(nextLinkID); return Simulation::getNetworkManager()->findLinkByID(linkID)->canReach(nextLink); } LibsaltNode Link::getFromNode(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getFromNode(); } LibsaltNode Link::getToNode(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getToNode(); } std::string Link::getSpreadType(const std::string& linkID) { SALT::SpreadType type = Simulation::getNetworkManager()->findLinkByID(linkID)->getSpreadType(); std::string s; if (type == SALT::SpreadType::CENTER) { s = "CENTER"; } else { s = "RIGHT"; } return s; } bool Link::isExceptionalLink(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->isExceptionalLink(); } bool Link::isOutFlowLink(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->isOutFlowLink(); } const::string Link::getShape(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getShape(); } LibsaltPosition Link::getDirection(const std::string& linkID) { LibsaltPosition p; SALT::Vector2D direction = Simulation::getNetworkManager()->findLinkByID(linkID)->getDirection(); p.x = direction.x; p.y = direction.y; return p; } int Link::getLeftPocket(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getMyLeftPocket(); } int Link::getRightPocket(const std::string& linkID) { return Simulation::getNetworkManager()->findLinkByID(linkID)->getMyRightPocket(); } // =========================================================================== // Setter Implementation // =========================================================================== } // end of namespace libsalt /****************************************************************************/
f4630c6ed83feca3c55a3db514190f09fdac70cc
39dafc6053082f1b24decda6cb67caa1a65b8463
/JNIBridgeGenerator/src/main/cpp/com/tecnyse/integration/defines.h
b2e2db7a58e403cae110551492cc3d62c1b5ca63
[ "Apache-2.0" ]
permissive
geertcl/JNIBridgeGenerator
86f853a99ab67ea0e62497dabfdbf74a2cdf59c1
453693a5ed1d6ecb4c5d6bdf9a7e5171aeec31f5
refs/heads/master
2021-04-12T04:28:01.166898
2015-06-05T09:25:46
2015-06-05T09:25:46
35,766,743
1
0
null
null
null
null
UTF-8
C++
false
false
1,335
h
defines.h
/* * Copyright 2015 Geert Claeys * * 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. */ #ifndef DEFINES_H #define DEFINES_H //#define MONITOR_JNI_CALLS #define CHECKERROR(p) com::tecnyse::integration::JNIBridge::checkError(p) #if defined(_WIN32) || defined(WIN32) || defined(_WIN64) || defined(WIN64) #define WINDOWS #endif #ifdef MONITOR_JNI_CALLS #include <ctime> #include <iostream> static clock_t logging_timer_clock; #define TIMED_CALL(call, description) \ logging_timer_clock = clock(); \ call; \ logging_timer_clock = clock() - logging_timer_clock; \ printf("Execution of '%s' took took %f milliseconds \n", description, ((float)logging_timer_clock)/CLOCKS_PER_SEC*1000); \ fflush(stdout) #else #define TIMED_CALL(call, f) call #endif #endif
543a4af39084a10ff8f5bbbc541c7d8d4e968f38
6229b84c47856cc48ff6307448e10b9ac12bde45
/Contest/MEX Foundation Contest/D.cpp
1b93028baaabb6952019db6fb055f11bac25cb1d
[]
no_license
ltf0501/NoName
d7498adfbc3b37ebc4408ee9480b2746e250784b
ee2f9d303892cbb3a1d47c89dda47f86dd41a986
refs/heads/master
2021-06-29T23:02:15.509131
2020-11-06T06:48:13
2020-11-06T06:48:13
187,497,633
4
1
null
null
null
null
UTF-8
C++
false
false
4,744
cpp
D.cpp
#include <bits/stdc++.h> using namespace std; constexpr int kN = 120010, kBlk = 256, kBs = 2 * (kN / kBlk + 5); struct Block { int l, r, mn, mx, has_left_mn, has_right_mx; bool complete, dirty; vector<int> vals, vals_sorted; }; void RebuildBlock(Block &blk, bool resort = true) { static int pref_mn[kBlk], suff_mx[kBlk]; blk.has_left_mn = INT_MAX; blk.has_right_mx = INT_MIN; blk.complete = false; int r = int(blk.vals.size()); pref_mn[0] = blk.vals[0]; suff_mx[r - 1] = blk.vals[r - 1]; for (int i = 1; i < r; i++) pref_mn[i] = min(pref_mn[i - 1], blk.vals[i]); for (int i = r - 2; i >= 0; i--) suff_mx[i] = max(suff_mx[i + 1], blk.vals[i]); blk.mn = pref_mn[r - 1]; blk.mx = suff_mx[0]; for (int i = 1; i < r; i++) { if (pref_mn[i - 1] < blk.vals[i]) { blk.has_left_mn = min(blk.has_left_mn, blk.vals[i]); } } for (int i = 0; i < r - 1; i++) { if (blk.vals[i] < suff_mx[i + 1]) { blk.has_right_mx = max(blk.has_right_mx, blk.vals[i]); } } for (int i = 1; i < r - 1; i++) { if (pref_mn[i - 1] < blk.vals[i] && blk.vals[i] < suff_mx[i + 1]) { blk.complete = true; break; } } if (resort) { blk.vals_sorted.clear(); } } bool BlockHasRange(Block &blk, int l, int r) { if (blk.vals_sorted.empty()) { blk.vals_sorted = blk.vals; sort(blk.vals_sorted.begin(), blk.vals_sorted.end()); } return upper_bound(blk.vals_sorted.begin(), blk.vals_sorted.end(), r) != lower_bound(blk.vals_sorted.begin(), blk.vals_sorted.end(), l); } bool QueryAns(vector<Block> &blks) { static int pref_mn[kBs], suff_mx[kBs]; int bs = int(blks.size()); pref_mn[0] = blks[0].mn; suff_mx[bs - 1] = blks[bs - 1].mx; for (int i = 0; i < bs; i++) { if (blks[i].complete) return true; } for (int i = 1; i < bs; i++) pref_mn[i] = min(pref_mn[i - 1], blks[i].mn); for (int i = bs - 2; i >= 0; i--) suff_mx[i] = max(suff_mx[i + 1], blks[i].mx); for (int i = 1; i < bs; i++) { if (pref_mn[i - 1] < blks[i].has_right_mx) return true; } for (int i = 0; i < bs - 1; i++) { if (blks[i].has_left_mn < suff_mx[i + 1]) return true; } for (int i = 1; i < bs - 1; i++) { if (blks[i].dirty && pref_mn[i - 1] < suff_mx[i + 1]) { blks[i].dirty = false; if (BlockHasRange(blks[i], pref_mn[i - 1], suff_mx[i + 1])) return true; } } return false; } void SplitAt(vector<Block> &blks, int p) { int bs = int(blks.size()); for (int i = 0; i < bs; i++) { if (blks[i].l <= p && p <= blks[i].r) { if (blks[i].l == p) return; Block new_blk{}; new_blk.l = p; new_blk.r = blks[i].r; new_blk.vals = vector<int>(blks[i].vals.begin() + (p - blks[i].l), blks[i].vals.end()); new_blk.dirty = blks[i].dirty; RebuildBlock(new_blk); blks.insert(blks.begin() + i + 1, std::move(new_blk)); blks[i].r = p - 1; blks[i].vals.erase(blks[i].vals.begin() + (p - blks[i].l), blks[i].vals.end()); RebuildBlock(blks[i]); return; } } } void Merge(vector<Block> &blks) { for (int i = 0; i < int(blks.size()) - 1; i++) { if (blks[i].vals.size() + blks[i + 1].vals.size() <= kBlk) { blks[i].r = blks[i + 1].r; blks[i].dirty |= blks[i + 1].dirty; blks[i].vals.insert(blks[i].vals.end(), blks[i + 1].vals.begin(), blks[i + 1].vals.end()); RebuildBlock(blks[i], blks[i].vals_sorted.empty() || blks[i + 1].vals_sorted.empty()); vector<int> sorted(blks[i].vals_sorted.size() + blks[i + 1].vals_sorted.size()); merge(blks[i].vals_sorted.begin(), blks[i].vals_sorted.end(), blks[i + 1].vals_sorted.begin(), blks[i + 1].vals_sorted.end(), sorted.begin()); blks[i].vals_sorted = std::move(sorted); blks.erase(blks.begin() + i + 1); } } } void SwapRange(vector<Block> &blks, int l, int m, int r) { SplitAt(blks, l); SplitAt(blks, m); SplitAt(blks, r + 1); int bs = int(blks.size()); int lb = bs, mb = bs, rb = bs; for (int i = 0; i < bs; i++) { if (blks[i].l == l) lb = i; if (blks[i].l == m) mb = i; if (blks[i].l == r + 1) rb = i; } for (int i = lb; i < rb; i++) blks[i].dirty = true; rotate(blks.begin() + lb, blks.begin() + mb, blks.begin() + rb); int sum = 1; for (int i = 0; i < bs; i++) { blks[i].l = sum; blks[i].r = (sum += int(blks[i].vals.size())) - 1; } Merge(blks); } int main() { int n; cin >> n; vector<Block> blks(n / kBlk + 1); for (auto &b : blks) b.l = INT_MAX, b.dirty = true; for (int i = 1; i <= n; i++) { int h; cin >> h; int b = i / kBlk; blks[b].l = min(blks[b].l, i); blks[b].r = max(blks[b].r, i); blks[b].vals.push_back(h); } for (int i = 0; i < int(blks.size()); i++) { RebuildBlock(blks[i]); } int q; cin >> q; while (q--) { int l, r, k; cin >> l >> r >> k; if (k && k != r - l + 1) SwapRange(blks, l, r + 1 - k, r); cout << (QueryAns(blks) ? "YES" : "NO") << '\n'; } }
9dedfce0cbc176ee93574f77a8446c03fd0fe4ca
9de7a07060e89bc9c9d57cf62abd77e19b596861
/Plugins/org.mitk.gui.qt.diffusionimaging.controls/src/internal/QmitkControlVisualizationPropertiesView.cpp
dba1c61daf8b47bbf5be7ae163f779df8cca374d
[]
no_license
MIC-DKFZ/MITK-Diffusion
c2f07bcb14dca635b918cc847b9dc5007f5b748c
32d7d08ab99b40625e0673628acaa39a75be2ff8
refs/heads/master
2023-07-08T21:08:39.592144
2023-06-27T10:12:35
2023-06-27T10:12:35
195,387,051
53
14
null
null
null
null
UTF-8
C++
false
false
46,190
cpp
QmitkControlVisualizationPropertiesView.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkControlVisualizationPropertiesView.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkResliceMethodProperty.h" #include "mitkRenderingManager.h" #include "mitkImageCast.h" #include "mitkShImage.h" #include "mitkPlanarFigure.h" #include "mitkFiberBundle.h" #include "QmitkDataStorageComboBox.h" #include "mitkPlanarFigureInteractor.h" #include <mitkOdfImage.h> #include <mitkTensorImage.h> #include <mitkImage.h> #include <mitkDiffusionPropertyHelper.h> #include "usModuleRegistry.h" #include <mitkPeakImage.h> #include <mitkBaseRenderer.h> #include "mitkPlaneGeometry.h" #include <QmitkRenderWindow.h> #include <itkFlipPeaksFilter.h> #include <mitkImageToItk.h> #include <mitkWorkbenchUtil.h> #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" #include "itkRGBAPixel.h" #include <itkTractDensityImageFilter.h> #include "qwidgetaction.h" #include "qcolordialog.h" #include <QRgb> #include <itkMultiThreaderBase.h> #include <mitkClippingProperty.h> #include <ciso646> #define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a))) const std::string QmitkControlVisualizationPropertiesView::VIEW_ID = "org.mitk.views.controlvisualizationpropertiesview"; using namespace berry; QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView() : QmitkAbstractView(), m_Controls(nullptr), m_CurrentSelection(nullptr), m_IconTexOFF(new QIcon(":/QmitkDiffusionImaging/texIntOFFIcon.png")), m_IconTexON(new QIcon(":/QmitkDiffusionImaging/texIntONIcon.png")), m_IconGlyOFF_T(new QIcon(":/QmitkDiffusionImaging/glyphsoff_T.png")), m_IconGlyON_T(new QIcon(":/QmitkDiffusionImaging/glyphson_T.png")), m_IconGlyOFF_C(new QIcon(":/QmitkDiffusionImaging/glyphsoff_C.png")), m_IconGlyON_C(new QIcon(":/QmitkDiffusionImaging/glyphson_C.png")), m_IconGlyOFF_S(new QIcon(":/QmitkDiffusionImaging/glyphsoff_S.png")), m_IconGlyON_S(new QIcon(":/QmitkDiffusionImaging/glyphson_S.png")), m_GlyIsOn_T(false), m_GlyIsOn_C(false), m_GlyIsOn_S(false), m_CurrentThickSlicesMode(1), m_CurrentThickSlicesNum(0), m_CurrentPickingNode(nullptr), m_ColorPropertyObserverTag(0), m_OpacityPropertyObserverTag(0) { m_MyMenu = nullptr; auto numThread = itk::MultiThreaderBase::GetGlobalMaximumNumberOfThreads(); itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(numThread); } QmitkControlVisualizationPropertiesView::~QmitkControlVisualizationPropertiesView() { } void QmitkControlVisualizationPropertiesView::SetTs(int currentThickSlicesMode, int num, std::string render_window) { if (auto renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategy::OPEN)) { mitk::BaseRenderer::Pointer renderer = renderWindowPart->GetQmitkRenderWindow(QString(render_window.c_str()))->GetRenderer(); renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices.num", mitk::IntProperty::New(num)); if(num>0) { renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices", mitk::ResliceMethodProperty::New(currentThickSlicesMode)); renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices.showarea", mitk::BoolProperty::New(true)); } else { renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices", mitk::ResliceMethodProperty::New(0)); renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices.showarea", mitk::BoolProperty::New(false)); } renderer->SendUpdateSlice(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::OnThickSlicesModeSelected( QAction* action ) { m_CurrentThickSlicesMode = action->data().toInt(); switch( m_CurrentThickSlicesMode ) { case 0: return; case 1: this->m_Controls->m_TSMenu->setText("MIP"); break; case 2: this->m_Controls->m_TSMenu->setText("SUM"); break; case 3: this->m_Controls->m_TSMenu->setText("WEIGH"); break; default: return; } SetTs(m_CurrentThickSlicesMode, m_CurrentThickSlicesNum, "axial"); SetTs(m_CurrentThickSlicesMode, m_CurrentThickSlicesNum, "sagittal"); SetTs(m_CurrentThickSlicesMode, m_CurrentThickSlicesNum, "coronal"); } void QmitkControlVisualizationPropertiesView::OnTSNumChanged( int num ) { m_CurrentThickSlicesNum = num; SetTs(m_CurrentThickSlicesMode, m_CurrentThickSlicesNum, "axial"); SetTs(m_CurrentThickSlicesMode, m_CurrentThickSlicesNum, "sagittal"); SetTs(m_CurrentThickSlicesMode, m_CurrentThickSlicesNum, "coronal"); m_TSLabel->setText(QString::number( num*2 + 1 )); } void QmitkControlVisualizationPropertiesView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkControlVisualizationPropertiesViewControls; m_Controls->setupUi(parent); this->CreateConnections(); // hide warning (ODFs in rotated planes) m_Controls->m_lblRotatedPlanesWarning->hide(); m_MyMenu = new QMenu(parent); m_Controls->m_TSMenu->setMenu( m_MyMenu ); QIcon iconFiberFade(":/QmitkDiffusionImaging/MapperEfx2D.png"); m_Controls->m_FiberFading2D->setIcon(iconFiberFade); m_Controls->m_NormalizationFrame->setVisible(false); m_Controls->m_Crosshair->setVisible(false); mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); if (renderWindow) { m_SliceChangeListener.RenderWindowPartActivated(renderWindow); connect(&m_SliceChangeListener, SIGNAL(SliceChanged()), this, SLOT(OnSliceChanged())); } connect(m_Controls->m_SetColor1, SIGNAL(clicked()), this, SLOT(SetColor())); connect(m_Controls->m_SetColor2, SIGNAL(clicked()), this, SLOT(SetColor())); } } void QmitkControlVisualizationPropertiesView::SetColor() { for (auto node : m_SelectedNodes) { QColor c = QColorDialog::getColor(); if (c.isValid()) { float rgb[3]; rgb[0] = static_cast<float>(c.redF()); rgb[1] = static_cast<float>(c.greenF()); rgb[2] = static_cast<float>(c.blueF()); node->SetColor(rgb); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkControlVisualizationPropertiesView::SetFocus() { m_Controls->m_TSMenu->setFocus(); } void QmitkControlVisualizationPropertiesView::SliceRotation(const itk::EventObject&) { // test if plane rotated if( m_GlyIsOn_T || m_GlyIsOn_C || m_GlyIsOn_S ) { if( this->IsPlaneRotated() ) { // show label m_Controls->m_lblRotatedPlanesWarning->show(); } else { //hide label m_Controls->m_lblRotatedPlanesWarning->hide(); } } } void QmitkControlVisualizationPropertiesView::NodeRemoved(const mitk::DataNode* /*node*/) { } #include <mitkMessage.h> void QmitkControlVisualizationPropertiesView::CreateConnections() { if ( m_Controls ) { connect( static_cast<QObject*>(m_Controls->m_VisibleOdfsON_T), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_T()) ); connect( static_cast<QObject*>(m_Controls->m_VisibleOdfsON_S), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_S()) ); connect( static_cast<QObject*>(m_Controls->m_VisibleOdfsON_C), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_C()) ); connect( static_cast<QObject*>(m_Controls->m_ShowMaxNumber), SIGNAL(editingFinished()), this, SLOT(ShowMaxNumberChanged()) ); connect( static_cast<QObject*>(m_Controls->m_NormalizationDropdown), SIGNAL(currentIndexChanged(int)), this, SLOT(NormalizationDropdownChanged(int)) ); connect( static_cast<QObject*>(m_Controls->m_ScalingFactor), SIGNAL(valueChanged(double)), this, SLOT(ScalingFactorChanged(double)) ); connect( static_cast<QObject*>(m_Controls->m_AdditionalScaling), SIGNAL(currentIndexChanged(int)), this, SLOT(AdditionalScaling(int)) ); connect(static_cast<QObject*>(m_Controls->m_ResetColoring), SIGNAL(clicked()), static_cast<QObject*>(this), SLOT(ResetColoring())); connect(static_cast<QObject*>(m_Controls->m_ResetColoring2), SIGNAL(clicked()), static_cast<QObject*>(this), SLOT(ResetColoring())); connect(static_cast<QObject*>(m_Controls->m_FiberFading2D), SIGNAL(clicked()), static_cast<QObject*>(this), SLOT( Fiber2DfadingEFX() ) ); connect(static_cast<QObject*>(m_Controls->m_FiberClippingBox), SIGNAL(editingFinished()), static_cast<QObject*>(this), SLOT( FiberSlicingThickness2D() ) ); connect(static_cast<QObject*>(m_Controls->m_Crosshair), SIGNAL(clicked()), static_cast<QObject*>(this), SLOT(SetInteractor())); connect(static_cast<QObject*>(m_Controls->m_LineWidth), SIGNAL(editingFinished()), static_cast<QObject*>(this), SLOT(LineWidthChanged())); connect(static_cast<QObject*>(m_Controls->m_TubeWidth), SIGNAL(editingFinished()), static_cast<QObject*>(this), SLOT(TubeRadiusChanged())); connect(static_cast<QObject*>(m_Controls->m_RibbonWidth), SIGNAL(editingFinished()), static_cast<QObject*>(this), SLOT(RibbonWidthChanged())); connect( static_cast<QObject*>(m_Controls->m_OdfColorBox), SIGNAL(currentIndexChanged(int)), static_cast<QObject*>(this), SLOT(OnColourisationModeChanged() ) ); connect(static_cast<QObject*>(m_Controls->m_Clip0), SIGNAL(toggled(bool)), static_cast<QObject*>(this), SLOT(Toggle3DClipping(bool))); connect(static_cast<QObject*>(m_Controls->m_Clip1), SIGNAL(toggled(bool)), static_cast<QObject*>(this), SLOT(Toggle3DClipping(bool))); connect(static_cast<QObject*>(m_Controls->m_Clip2), SIGNAL(toggled(bool)), static_cast<QObject*>(this), SLOT(Toggle3DClipping(bool))); connect(static_cast<QObject*>(m_Controls->m_Clip3), SIGNAL(toggled(bool)), static_cast<QObject*>(this), SLOT(Toggle3DClipping(bool))); connect(static_cast<QObject*>(m_Controls->m_FlipClipBox), SIGNAL(stateChanged(int)), static_cast<QObject*>(this), SLOT(Toggle3DClipping())); connect(static_cast<QObject*>(m_Controls->m_Enable3dPeaks), SIGNAL(stateChanged(int)), static_cast<QObject*>(this), SLOT(Toggle3DPeaks())); connect(static_cast<QObject*>(m_Controls->m_FlipPeaksButton), SIGNAL(clicked()), static_cast<QObject*>(this), SLOT(FlipPeaks())); m_Controls->m_BundleControlsFrame->setVisible(false); m_Controls->m_ImageControlsFrame->setVisible(false); m_Controls->m_PeakImageFrame->setVisible(false); m_Controls->m_lblRotatedPlanesWarning->setVisible(false); m_Controls->m_3DClippingBox->setVisible(false); } } // set diffusion image channel to b0 volume void QmitkControlVisualizationPropertiesView::NodeAdded(const mitk::DataNode *node) { mitk::DataNode* notConst = const_cast<mitk::DataNode*>(node); bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast<mitk::Image *>(node->GetData())) ); if (isDiffusionImage) { mitk::Image::Pointer dimg = dynamic_cast<mitk::Image*>(notConst->GetData()); // if there is no b0 image in the dataset, the GetB0Indices() returns a vector of size 0 // and hence we cannot set the Property directly to .front() int displayChannelPropertyValue = 0; mitk::DiffusionPropertyHelper::BValueMapType map = mitk::DiffusionPropertyHelper::GetBValueMap(dimg); if( map[0].size() > 0) { displayChannelPropertyValue = map[0].front(); } notConst->SetIntProperty("DisplayChannel", displayChannelPropertyValue ); } } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkControlVisualizationPropertiesView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer>& nodes) { m_Controls->m_BundleControlsFrame->setVisible(false); m_Controls->m_ImageControlsFrame->setVisible(false); m_Controls->m_PeakImageFrame->setVisible(false); m_Controls->m_3DClippingBox->setVisible(false); m_Controls->m_FlipClipBox->setVisible(false); m_Controls->m_Enable3dPeaks->setVisible(false); // if (nodes.size()>1) // only do stuff if one node is selected // return; m_Controls->m_NumberGlyphsFrame->setVisible(false); m_Controls->m_GlyphFrame->setVisible(false); m_Controls->m_TSMenu->setVisible(false); m_SelectedNodes.clear(); int numOdfImages = 0; for (mitk::DataNode::Pointer node: nodes) { if(node.IsNull()) continue; mitk::BaseData* nodeData = node->GetData(); if(nodeData == nullptr) continue; if (dynamic_cast<mitk::PeakImage*>(nodeData)) { m_Controls->m_PeakImageFrame->setVisible(true); if (m_Color.IsNotNull()) m_Color->RemoveObserver(m_ColorPropertyObserverTag); itk::ReceptorMemberCommand<QmitkControlVisualizationPropertiesView>::Pointer command = itk::ReceptorMemberCommand<QmitkControlVisualizationPropertiesView>::New(); command->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SetCustomColor ); m_Color = dynamic_cast<mitk::ColorProperty*>(node->GetProperty("color", nullptr)); if (m_Color.IsNotNull()) m_ColorPropertyObserverTag = m_Color->AddObserver( itk::ModifiedEvent(), command ); int ClippingPlaneId = -1; node->GetPropertyValue("3DClippingPlaneId",ClippingPlaneId); switch(ClippingPlaneId) { case 0: m_Controls->m_Clip0->setChecked(1); break; case 1: m_Controls->m_Clip1->setChecked(1); break; case 2: m_Controls->m_Clip2->setChecked(1); break; case 3: m_Controls->m_Clip3->setChecked(1); break; default : m_Controls->m_Clip0->setChecked(1); } m_Controls->m_Enable3dPeaks->setVisible(true); m_Controls->m_3DClippingBox->setVisible(true); } else if (dynamic_cast<mitk::FiberBundle*>(nodeData)) { int ClippingPlaneId = -1; node->GetPropertyValue("3DClippingPlaneId",ClippingPlaneId); switch(ClippingPlaneId) { case 0: m_Controls->m_Clip0->setChecked(1); break; case 1: m_Controls->m_Clip1->setChecked(1); break; case 2: m_Controls->m_Clip2->setChecked(1); break; case 3: m_Controls->m_Clip3->setChecked(1); break; default : m_Controls->m_Clip0->setChecked(1); } // handle fiber property observers if (m_Color.IsNotNull()) m_Color->RemoveObserver(m_ColorPropertyObserverTag); itk::ReceptorMemberCommand<QmitkControlVisualizationPropertiesView>::Pointer command = itk::ReceptorMemberCommand<QmitkControlVisualizationPropertiesView>::New(); command->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SetCustomColor ); m_Color = dynamic_cast<mitk::ColorProperty*>(node->GetProperty("color", nullptr)); if (m_Color.IsNotNull()) m_ColorPropertyObserverTag = m_Color->AddObserver( itk::ModifiedEvent(), command ); m_Controls->m_FlipClipBox->setVisible(true); m_Controls->m_3DClippingBox->setVisible(true); m_Controls->m_BundleControlsFrame->setVisible(true); if(m_CurrentPickingNode != 0 && node.GetPointer() != m_CurrentPickingNode) { m_Controls->m_Crosshair->setEnabled(false); } else { m_Controls->m_Crosshair->setEnabled(true); } int width; node->GetIntProperty("shape.linewidth", width); m_Controls->m_LineWidth->setValue(width); float radius; node->GetFloatProperty("shape.tuberadius", radius); m_Controls->m_TubeWidth->setValue(radius); float range; node->GetFloatProperty("Fiber2DSliceThickness",range); mitk::FiberBundle::Pointer fib = dynamic_cast<mitk::FiberBundle*>(node->GetData()); mitk::BaseGeometry::Pointer geo = fib->GetGeometry(); mitk::ScalarType max = geo->GetExtentInMM(0); max = std::max(max, geo->GetExtentInMM(1)); max = std::max(max, geo->GetExtentInMM(2)); m_Controls->m_FiberClippingBox->setMaximum(max); m_Controls->m_FiberClippingBox->setValue(range); } else if(dynamic_cast<mitk::OdfImage*>(nodeData) || dynamic_cast<mitk::TensorImage*>(nodeData) || dynamic_cast<mitk::ShImage*>(nodeData)) { m_Controls->m_ImageControlsFrame->setVisible(true); m_Controls->m_NumberGlyphsFrame->setVisible(true); m_Controls->m_GlyphFrame->setVisible(true); m_Controls->m_NormalizationFrame->setVisible(true); if(m_NodeUsedForOdfVisualization.IsNotNull()) { m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", false); } m_NodeUsedForOdfVisualization = node; m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); if (dynamic_cast<mitk::TensorImage*>(nodeData)) { m_Controls->m_NormalizationDropdown->setVisible(false); m_Controls->m_NormalizationLabel->setVisible(false); } else { m_Controls->m_NormalizationDropdown->setVisible(true); m_Controls->m_NormalizationLabel->setVisible(true); } int val; node->GetIntProperty("ShowMaxNumber", val); m_Controls->m_ShowMaxNumber->setValue(val); m_Controls->m_NormalizationDropdown->setCurrentIndex(dynamic_cast<mitk::EnumerationProperty*>(node->GetProperty("Normalization"))->GetValueAsId()); float fval; node->GetFloatProperty("Scaling",fval); m_Controls->m_ScalingFactor->setValue(fval); m_Controls->m_AdditionalScaling->setCurrentIndex(dynamic_cast<mitk::EnumerationProperty*>(node->GetProperty("ScaleBy"))->GetValueAsId()); bool switchTensorViewValue = false; node->GetBoolProperty( "DiffusionCore.Rendering.OdfVtkMapper.SwitchTensorView", switchTensorViewValue ); bool colourisationModeBit = false; node->GetBoolProperty("DiffusionCore.Rendering.OdfVtkMapper.ColourisationModeBit", colourisationModeBit ); m_Controls->m_OdfColorBox->setCurrentIndex(colourisationModeBit); numOdfImages++; } else if(dynamic_cast<mitk::PlanarFigure*>(nodeData)) { PlanarFigureFocus(); } else if( dynamic_cast<mitk::Image*>(nodeData) ) { m_Controls->m_ImageControlsFrame->setVisible(true); m_Controls->m_TSMenu->setVisible(true); } m_SelectedNodes.push_back(node); } if( nodes.empty() ) { return; } mitk::DataNode::Pointer node = nodes.at(0); if( node.IsNull() ) { return; } QMenu *myMenu = m_MyMenu; myMenu->clear(); QActionGroup* thickSlicesActionGroup = new QActionGroup(myMenu); thickSlicesActionGroup->setExclusive(true); int currentTSMode = 0; { mitk::ResliceMethodProperty::Pointer m = dynamic_cast<mitk::ResliceMethodProperty*>(node->GetProperty( "reslice.thickslices" )); if( m.IsNotNull() ) currentTSMode = m->GetValueAsId(); } int maxTS = 30; for (auto node: nodes) { mitk::Image* image = dynamic_cast<mitk::Image*>(node->GetData()); if (image) { int size = std::max(image->GetDimension(0), std::max(image->GetDimension(1), image->GetDimension(2))); if (size>maxTS) { maxTS=size; } } } maxTS /= 2; int currentNum = 0; { mitk::IntProperty::Pointer m = dynamic_cast<mitk::IntProperty*>(node->GetProperty( "reslice.thickslices.num" )); if( m.IsNotNull() ) { currentNum = m->GetValue(); if(currentNum < 0) { currentNum = 0; } if(currentNum > maxTS) { currentNum = maxTS; } } } if(currentTSMode==0) { currentNum=0; } QSlider *m_TSSlider = new QSlider(myMenu); m_TSSlider->setMinimum(0); m_TSSlider->setMaximum(maxTS-1); m_TSSlider->setValue(currentNum); m_TSSlider->setOrientation(Qt::Horizontal); connect( m_TSSlider, SIGNAL( valueChanged(int) ), this, SLOT( OnTSNumChanged(int) ) ); QHBoxLayout* _TSLayout = new QHBoxLayout; _TSLayout->setContentsMargins(4,4,4,4); _TSLayout->addWidget(m_TSSlider); _TSLayout->addWidget(m_TSLabel=new QLabel(QString::number(currentNum*2+1),myMenu)); QWidget* _TSWidget = new QWidget; _TSWidget->setLayout(_TSLayout); QActionGroup* thickSliceModeActionGroup = new QActionGroup(myMenu); thickSliceModeActionGroup->setExclusive(true); QWidgetAction *m_TSSliderAction = new QWidgetAction(myMenu); m_TSSliderAction->setDefaultWidget(_TSWidget); myMenu->addAction(m_TSSliderAction); QAction* mipThickSlicesAction = new QAction(myMenu); mipThickSlicesAction->setActionGroup(thickSliceModeActionGroup); mipThickSlicesAction->setText("MIP (max. intensity proj.)"); mipThickSlicesAction->setCheckable(true); mipThickSlicesAction->setChecked(m_CurrentThickSlicesMode==1); mipThickSlicesAction->setData(1); myMenu->addAction( mipThickSlicesAction ); QAction* sumThickSlicesAction = new QAction(myMenu); sumThickSlicesAction->setActionGroup(thickSliceModeActionGroup); sumThickSlicesAction->setText("SUM (sum intensity proj.)"); sumThickSlicesAction->setCheckable(true); sumThickSlicesAction->setChecked(m_CurrentThickSlicesMode==2); sumThickSlicesAction->setData(2); myMenu->addAction( sumThickSlicesAction ); QAction* weightedThickSlicesAction = new QAction(myMenu); weightedThickSlicesAction->setActionGroup(thickSliceModeActionGroup); weightedThickSlicesAction->setText("WEIGHTED (gaussian proj.)"); weightedThickSlicesAction->setCheckable(true); weightedThickSlicesAction->setChecked(m_CurrentThickSlicesMode==3); weightedThickSlicesAction->setData(3); myMenu->addAction( weightedThickSlicesAction ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); connect( thickSliceModeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(OnThickSlicesModeSelected(QAction*)) ); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_S() { m_GlyIsOn_S = m_Controls->m_VisibleOdfsON_S->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is nullptr"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::Visible() { mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); if (renderWindow) { m_SliceChangeListener.RenderWindowPartActivated(renderWindow); connect(&m_SliceChangeListener, SIGNAL(SliceChanged()), this, SLOT(OnSliceChanged())); } } void QmitkControlVisualizationPropertiesView::Hidden() { } void QmitkControlVisualizationPropertiesView::Activated() { mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); if (renderWindow) { m_SliceChangeListener.RenderWindowPartActivated(renderWindow); connect(&m_SliceChangeListener, SIGNAL(SliceChanged()), this, SLOT(OnSliceChanged())); } } void QmitkControlVisualizationPropertiesView::Deactivated() { } void QmitkControlVisualizationPropertiesView::FlipPeaks() { for (auto node : m_SelectedNodes) { if (dynamic_cast<mitk::PeakImage*>(node->GetData())==nullptr) continue; std::string name = node->GetName(); mitk::Image::Pointer image = dynamic_cast<mitk::PeakImage*>(node->GetData()); typedef mitk::ImageToItk< mitk::PeakImage::ItkPeakImageType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(image); caster->Update(); mitk::PeakImage::ItkPeakImageType::Pointer itkImg = caster->GetOutput(); itk::FlipPeaksFilter< float >::Pointer flipper = itk::FlipPeaksFilter< float >::New(); flipper->SetInput(itkImg); flipper->SetFlipX(m_Controls->m_FlipPeaksX->isChecked()); flipper->SetFlipY(m_Controls->m_FlipPeaksY->isChecked()); flipper->SetFlipZ(m_Controls->m_FlipPeaksZ->isChecked()); flipper->Update(); mitk::Image::Pointer resultImage = dynamic_cast<mitk::Image*>(mitk::PeakImage::New().GetPointer()); mitk::CastToMitkImage(flipper->GetOutput(), resultImage); resultImage->SetVolume(flipper->GetOutput()->GetBufferPointer()); node->SetData(resultImage); node->SetName(name); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::Toggle3DPeaks() { for (auto node : m_SelectedNodes) { if (dynamic_cast<mitk::PeakImage*>(node->GetData())==nullptr) continue; bool enabled = false; node->GetBoolProperty("Enable3DPeaks", enabled); node->SetBoolProperty( "Enable3DPeaks", !enabled ); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::Toggle3DClipping(bool enabled) { for (auto node : m_SelectedNodes) { if (!enabled || node.IsNull() || (dynamic_cast<mitk::FiberBundle*>(node->GetData())==nullptr && dynamic_cast<mitk::PeakImage*>(node->GetData())==nullptr)) continue; node->SetBoolProperty( "3DClippingPlaneFlip", m_Controls->m_FlipClipBox->isChecked() ); if (m_Controls->m_Clip0->isChecked()) { node->SetIntProperty( "3DClippingPlaneId", 0 ); Set3DClippingPlane(true, node, ""); } else if (m_Controls->m_Clip1->isChecked()) { node->SetIntProperty( "3DClippingPlaneId", 1 ); Set3DClippingPlane(false, node, "axial"); } else if (m_Controls->m_Clip2->isChecked()) { node->SetIntProperty( "3DClippingPlaneId", 2 ); Set3DClippingPlane(false, node, "sagittal"); } else if (m_Controls->m_Clip3->isChecked()) { node->SetIntProperty( "3DClippingPlaneId", 3 ); Set3DClippingPlane(false, node, "coronal"); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::OnSliceChanged() { mitk::DataStorage::SetOfObjects::ConstPointer nodes = this->GetDataStorage()->GetAll(); for (unsigned int i=0; i<nodes->Size(); ++i) { mitk::DataNode::Pointer node = nodes->GetElement(i); int plane_id = -1; node->GetIntProperty("3DClippingPlaneId", plane_id); if (plane_id==1) Set3DClippingPlane(false, node, "axial"); else if (plane_id==2) Set3DClippingPlane(false, node, "sagittal"); else if (plane_id==3) Set3DClippingPlane(false, node, "coronal"); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::Set3DClippingPlane(bool disable, mitk::DataNode* node, std::string plane) { mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); if (renderWindow && node && (dynamic_cast<mitk::FiberBundle*>(node->GetData()) || dynamic_cast<mitk::PeakImage*>(node->GetData()))) { mitk::Vector3D planeNormal; planeNormal.Fill(0.0); mitk::Point3D planeOrigin; planeOrigin.Fill(0.0); if (!disable) { mitk::SliceNavigationController* slicer = renderWindow->GetQmitkRenderWindow(QString(plane.c_str()))->GetSliceNavigationController(); mitk::PlaneGeometry::ConstPointer planeGeo = slicer->GetCurrentPlaneGeometry(); planeOrigin = this->GetRenderWindowPart()->GetSelectedPosition(); planeNormal = planeGeo->GetNormal(); } node->SetProperty( "3DClipping", mitk::ClippingProperty::New( planeOrigin, planeNormal ) ); if (dynamic_cast<mitk::FiberBundle*>(node->GetData())) dynamic_cast<mitk::FiberBundle*>(node->GetData())->RequestUpdate(); else mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_T() { m_GlyIsOn_T = m_Controls->m_VisibleOdfsON_T->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is nullptr"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_C() { m_GlyIsOn_C = m_Controls->m_VisibleOdfsON_C->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is nullptr"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } bool QmitkControlVisualizationPropertiesView::IsPlaneRotated() { mitk::Image* currentImage = dynamic_cast<mitk::Image* >( m_NodeUsedForOdfVisualization->GetData() ); if( currentImage == nullptr ) { MITK_ERROR << " Casting problems. Returning false"; return false; } mitk::Vector3D imageNormal0 = currentImage->GetSlicedGeometry()->GetAxisVector(0); mitk::Vector3D imageNormal1 = currentImage->GetSlicedGeometry()->GetAxisVector(1); mitk::Vector3D imageNormal2 = currentImage->GetSlicedGeometry()->GetAxisVector(2); imageNormal0.Normalize(); imageNormal1.Normalize(); imageNormal2.Normalize(); auto renderWindowPart = this->GetRenderWindowPart(); double eps = 0.000001; // for all 2D renderwindows of the render window part check alignment { mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast<const mitk::PlaneGeometry*> ( renderWindowPart->GetQmitkRenderWindow("axial")->GetRenderer()->GetCurrentWorldPlaneGeometry() ); if (displayPlane.IsNull()) { return false; } mitk::Vector3D normal = displayPlane->GetNormal(); normal.Normalize(); int test = 0; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal0.GetVnlVector()))-1) > eps ) { test++; } if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal1.GetVnlVector()))-1) > eps ) { test++; } if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal2.GetVnlVector()))-1) > eps ) { test++; } if (test==3) { return true; } } { mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast<const mitk::PlaneGeometry*> ( renderWindowPart->GetQmitkRenderWindow("sagittal")->GetRenderer()->GetCurrentWorldPlaneGeometry() ); if (displayPlane.IsNull()) { return false; } mitk::Vector3D normal = displayPlane->GetNormal(); normal.Normalize(); int test = 0; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal0.GetVnlVector()))-1) > eps ) { test++; } if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal1.GetVnlVector()))-1) > eps ) { test++; } if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal2.GetVnlVector()))-1) > eps ) { test++; } if (test==3) { return true; } } { mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast<const mitk::PlaneGeometry*> ( renderWindowPart->GetQmitkRenderWindow("coronal")->GetRenderer()->GetCurrentWorldPlaneGeometry() ); if (displayPlane.IsNull()) { return false; } mitk::Vector3D normal = displayPlane->GetNormal(); normal.Normalize(); int test = 0; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal0.GetVnlVector()))-1) > eps ) { test++; } if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal1.GetVnlVector()))-1) > eps ) { test++; } if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal2.GetVnlVector()))-1) > eps ) { test++; } if (test==3) { return true; } } return false; } void QmitkControlVisualizationPropertiesView::ShowMaxNumberChanged() { int maxNr = m_Controls->m_ShowMaxNumber->value(); if ( maxNr < 1 ) { m_Controls->m_ShowMaxNumber->setValue( 1 ); maxNr = 1; } for (auto node : m_SelectedNodes) { if ( dynamic_cast<mitk::OdfImage*>(node->GetData()) || dynamic_cast<mitk::TensorImage*>(node->GetData()) || dynamic_cast<mitk::ShImage*>(node->GetData()) ) { node->SetIntProperty("ShowMaxNumber", maxNr); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::NormalizationDropdownChanged(int normDropdown) { typedef mitk::OdfNormalizationMethodProperty PropType; PropType::Pointer normMeth = PropType::New(); switch(normDropdown) { case 0: normMeth->SetNormalizationToMinMax(); break; case 1: normMeth->SetNormalizationToMax(); break; case 2: normMeth->SetNormalizationToNone(); break; case 3: normMeth->SetNormalizationToGlobalMax(); break; default: normMeth->SetNormalizationToMinMax(); } for (auto node : m_SelectedNodes) { if ( dynamic_cast<mitk::OdfImage*>(node->GetData()) || dynamic_cast<mitk::TensorImage*>(node->GetData()) || dynamic_cast<mitk::ShImage*>(node->GetData()) ) { node->SetProperty("Normalization", normMeth.GetPointer()); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::ScalingFactorChanged(double scalingFactor) { for (auto node : m_SelectedNodes) { if ( dynamic_cast<mitk::OdfImage*>(node->GetData()) || dynamic_cast<mitk::TensorImage*>(node->GetData()) || dynamic_cast<mitk::ShImage*>(node->GetData()) ) { node->SetFloatProperty("Scaling", scalingFactor); } } if (auto renderWindowPart = this->GetRenderWindowPart()) { renderWindowPart->RequestUpdate(); } } void QmitkControlVisualizationPropertiesView::AdditionalScaling(int additionalScaling) { typedef mitk::OdfScaleByProperty PropType; PropType::Pointer scaleBy = PropType::New(); switch(additionalScaling) { case 0: scaleBy->SetScaleByNothing(); break; case 1: scaleBy->SetScaleByGFA(); //m_Controls->params_frame->setVisible(true); break; default: scaleBy->SetScaleByNothing(); } for (auto node : m_SelectedNodes) { if ( dynamic_cast<mitk::OdfImage*>(node->GetData()) || dynamic_cast<mitk::TensorImage*>(node->GetData()) || dynamic_cast<mitk::ShImage*>(node->GetData()) ) { node->SetProperty("ScaleBy", scaleBy.GetPointer()); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::Fiber2DfadingEFX() { for (auto node : m_SelectedNodes) { if (node && dynamic_cast<mitk::FiberBundle*>(node->GetData()) ) { bool currentMode; node->GetBoolProperty("Fiber2DfadeEFX", currentMode); node->SetProperty("Fiber2DfadeEFX", mitk::BoolProperty::New(!currentMode)); dynamic_cast<mitk::FiberBundle*>(node->GetData())->RequestUpdate2D(); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::FiberSlicingThickness2D() { for (auto node : m_SelectedNodes) { if (node && dynamic_cast<mitk::FiberBundle*>(node->GetData())) { float fibThickness = m_Controls->m_FiberClippingBox->value(); float currentThickness = 0; node->GetFloatProperty("Fiber2DSliceThickness", currentThickness); if ( fabs(fibThickness-currentThickness) < 0.001 ) continue; node->SetProperty("Fiber2DSliceThickness", mitk::FloatProperty::New(fibThickness)); dynamic_cast<mitk::FiberBundle*>(node->GetData())->RequestUpdate2D(); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::SetCustomColor(const itk::EventObject& /*e*/) { for (auto node : m_SelectedNodes) { if(node && dynamic_cast<mitk::FiberBundle*>(node->GetData())) { float color[3]; node->GetColor(color); mitk::FiberBundle::Pointer fib = dynamic_cast<mitk::FiberBundle*>(node->GetData()); fib->SetFiberColors(color[0]*255, color[1]*255, color[2]*255); } else if (node && dynamic_cast<mitk::PeakImage*>(node->GetData())) { float color[3]; node->GetColor(color); mitk::PeakImage::Pointer img = dynamic_cast<mitk::PeakImage*>(node->GetData()); img->SetCustomColor(color[0]*255, color[1]*255, color[2]*255); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::ResetColoring() { for (auto node : m_SelectedNodes) { if(node && dynamic_cast<mitk::FiberBundle*>(node->GetData())) { mitk::FiberBundle::Pointer fib = dynamic_cast<mitk::FiberBundle*>(node->GetData()); fib->ColorFibersByOrientation(); } else if(node && dynamic_cast<mitk::PeakImage*>(node->GetData())) { mitk::PeakImage::Pointer fib = dynamic_cast<mitk::PeakImage*>(node->GetData()); fib->ColorByOrientation(); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::PlanarFigureFocus() { for (auto node : m_SelectedNodes) { if(node) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast<mitk::PlanarFigure*> (node->GetData()); if (_PlanarFigure && _PlanarFigure->GetPlaneGeometry()) { QmitkRenderWindow* selectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; auto renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategy::OPEN); QmitkRenderWindow* axialRenderWindow = renderWindowPart->GetQmitkRenderWindow("axial"); if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, axialRenderWindow->GetRenderer())) { selectedRenderWindow = axialRenderWindow; } QmitkRenderWindow* sagittalRenderWindow = renderWindowPart->GetQmitkRenderWindow("sagittal"); if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, sagittalRenderWindow->GetRenderer())) { selectedRenderWindow = sagittalRenderWindow; } QmitkRenderWindow* coronalRenderWindow = renderWindowPart->GetQmitkRenderWindow("coronal"); if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, coronalRenderWindow->GetRenderer())) { selectedRenderWindow = coronalRenderWindow; } QmitkRenderWindow* _3DRenderWindow = renderWindowPart->GetQmitkRenderWindow("3d"); if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, _3DRenderWindow->GetRenderer())) { selectedRenderWindow = _3DRenderWindow; } const mitk::PlaneGeometry* _PlaneGeometry = _PlanarFigure->GetPlaneGeometry(); mitk::VnlVector normal = _PlaneGeometry->GetNormalVnl(); mitk::PlaneGeometry::ConstPointer worldGeometry1 = axialRenderWindow->GetRenderer()->GetCurrentWorldPlaneGeometry(); mitk::PlaneGeometry::ConstPointer _Plane1 = dynamic_cast<const mitk::PlaneGeometry*>( worldGeometry1.GetPointer() ); mitk::VnlVector normal1 = _Plane1->GetNormalVnl(); mitk::PlaneGeometry::ConstPointer worldGeometry2 = sagittalRenderWindow->GetRenderer()->GetCurrentWorldPlaneGeometry(); mitk::PlaneGeometry::ConstPointer _Plane2 = dynamic_cast<const mitk::PlaneGeometry*>( worldGeometry2.GetPointer() ); mitk::VnlVector normal2 = _Plane2->GetNormalVnl(); mitk::PlaneGeometry::ConstPointer worldGeometry3 = coronalRenderWindow->GetRenderer()->GetCurrentWorldPlaneGeometry(); mitk::PlaneGeometry::ConstPointer _Plane3 = dynamic_cast<const mitk::PlaneGeometry*>( worldGeometry3.GetPointer() ); mitk::VnlVector normal3 = _Plane3->GetNormalVnl(); normal[0] = fabs(normal[0]); normal[1] = fabs(normal[1]); normal[2] = fabs(normal[2]); normal1[0] = fabs(normal1[0]); normal1[1] = fabs(normal1[1]); normal1[2] = fabs(normal1[2]); normal2[0] = fabs(normal2[0]); normal2[1] = fabs(normal2[1]); normal2[2] = fabs(normal2[2]); normal3[0] = fabs(normal3[0]); normal3[1] = fabs(normal3[1]); normal3[2] = fabs(normal3[2]); double ang1 = angle(normal, normal1); double ang2 = angle(normal, normal2); double ang3 = angle(normal, normal3); if(ang1 < ang2 && ang1 < ang3) { selectedRenderWindow = axialRenderWindow; } else { if(ang2 < ang3) { selectedRenderWindow = sagittalRenderWindow; } else { selectedRenderWindow = coronalRenderWindow; } } // make node visible if (selectedRenderWindow) { const mitk::Point3D& centerP = _PlaneGeometry->GetOrigin(); selectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); } } // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast<mitk::PlanarFigureInteractor*>(node->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "MitkPlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( node ); } node->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true)); } } } void QmitkControlVisualizationPropertiesView::SetInteractor() { // BUG 19179 // typedef std::vector<mitk::DataNode*> Container; // Container _NodeSet = this->GetDataManagerSelection(); // mitk::DataNode* node = 0; // mitk::FiberBundle* bundle = 0; // mitk::FiberBundleInteractor::Pointer bundleInteractor = 0; // // finally add all nodes to the model // for(Container::const_iterator it=_NodeSet.begin(); it!=_NodeSet.end() // ; it++) // { // node = const_cast<mitk::DataNode*>(*it); // bundle = dynamic_cast<mitk::FiberBundle*>(node->GetData()); // if(bundle) // { // bundleInteractor = dynamic_cast<mitk::FiberBundleInteractor*>(node->GetInteractor()); // if(bundleInteractor.IsNotNull()) // mitk::GlobalInteraction::GetInstance()->RemoveInteractor(bundleInteractor); // if(!m_Controls->m_Crosshair->isChecked()) // { // m_Controls->m_Crosshair->setChecked(false); // this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::ArrowCursor); // m_CurrentPickingNode = 0; // } // else // { // m_Controls->m_Crosshair->setChecked(true); // bundleInteractor = mitk::FiberBundleInteractor::New("FiberBundleInteractor", node); // mitk::GlobalInteraction::GetInstance()->AddInteractor(bundleInteractor); // this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::CrossCursor); // m_CurrentPickingNode = node; // } // } // } } void QmitkControlVisualizationPropertiesView::TubeRadiusChanged() { for (auto node : m_SelectedNodes) { if(node && dynamic_cast<mitk::FiberBundle*>(node->GetData())) { float newRadius = m_Controls->m_TubeWidth->value(); node->SetFloatProperty("shape.tuberadius", newRadius); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::RibbonWidthChanged() { for (auto node : m_SelectedNodes) { if(node && dynamic_cast<mitk::FiberBundle*>(node->GetData())) { float newWidth = m_Controls->m_RibbonWidth->value(); node->SetFloatProperty("shape.ribbonwidth", newWidth); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::LineWidthChanged() { for (auto node : m_SelectedNodes) { if(node && dynamic_cast<mitk::PeakImage*>(node->GetData())) { auto newWidth = m_Controls->m_LineWidth->value(); float currentWidth = 0; node->SetFloatProperty("shape.linewidth", currentWidth); if (currentWidth==newWidth) continue; node->SetFloatProperty("shape.linewidth", newWidth); } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::Welcome() { berry::PlatformUI::GetWorkbench()->GetIntroManager() ->ShowIntro(GetSite()->GetWorkbenchWindow(), false); } void QmitkControlVisualizationPropertiesView::OnColourisationModeChanged() { for (auto node : m_SelectedNodes) { if( node && m_NodeUsedForOdfVisualization.IsNotNull() ) { node->SetProperty( "DiffusionCore.Rendering.OdfVtkMapper.ColourisationModeBit", mitk::BoolProperty::New( m_Controls->m_OdfColorBox->currentIndex() ) ); } else { MITK_DEBUG << "QmitkControlVisualizationPropertiesView::OnColourisationModeChanged() was called but m_NodeUsedForOdfVisualization was Null."; } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); }
1f851b2a034b60537a734eb4cdf447ef97dc55ad
393d9799bf6ad23cc5918cd79e9653da7bfc7e86
/Source/GameMain/MainMenuState.cpp
47ac7d503a4cc052c43e5ea811b9e1b034777ad9
[]
no_license
guydunton/asteroids-redux
c8a6d8c34c74491debaad04ad696691cfa2201c6
8df333cedb7798b9abcfc995e76ecd339fa2832a
refs/heads/master
2020-03-22T05:57:16.454810
2019-02-17T08:30:20
2019-02-17T08:30:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,711
cpp
MainMenuState.cpp
//----------------------------------------------------------- // File: MainMenuState.cpp //----------------------------------------------------------- #include "MainMenuState.h" #include "../Graphics/GraphicsDeviceManager.h" #include "GameStateManager.h" #include "GameLogic.h" #include "LevelStartState.h" #include "ControlScreenState.h" #include "Game.h" #include "Globals.h" MainMenuState::MainMenuState(const Content& content, GameStateManager* parent) : GameState(parent), titleFont(content.Graphics()), subFont1(content.Graphics()), menu(content, MakeMenuItems(content.Graphics()), 100), background(content.Textures(), "transparent") { } void MainMenuState::Enter() { // Set the level of the game parent->GetGameLogic().StartIdleMode(); } void MainMenuState::Update(float dt, const KeyboardState& keyboardState) { menu.Update(keyboardState); parent->GetGameLogic().Update(dt); } void MainMenuState::Exit() {} void MainMenuState::Render() { // Render the game parent->GetGameLogic().Render(false, false); background.Draw(Vector2(0, 0), 0.6f); menu.Render(); Vector2 size = titleFont.GetTextSize("Asteroids Redux"); Vector2 textPos((WINDOW_WIDTH / 2) - (size.x / 2), (WINDOW_HEIGHT / 2) - (size.y / 2) - (WINDOW_HEIGHT / 4)); titleFont.DrawString("Asteroids Redux", textPos); // draw the menu controls to the screen size = subFont1.GetTextSize("Menu Navigation: Up/Down and Enter"); textPos = Vector2(WINDOW_WIDTH - size.x - 7, WINDOW_HEIGHT - size.y - 7); subFont1.DrawString("Menu Navigation: Up/Down and Enter", textPos); } void MainMenuState::SelectStartGame() { // Reset and start the game. Update is to run collision detection once to hide // asteroid spawn errors parent->GetGameLogic().Reset(); parent->GetGameLogic().Update(0.016f); parent->SetState<LevelStartState>(); } void MainMenuState::SelectControls() { // Show the control for the game parent->SetState<ControlScreenState>(); } void MainMenuState::SelectExit() const { parent->GetGameLogic().GetParent().Close(); } std::shared_ptr<std::vector<MenuItem>> MainMenuState::MakeMenuItems(const GraphicsDeviceManager& graphics) { auto newItems = std::make_shared<std::vector<MenuItem>>(); // Add the menu items newItems->push_back(MenuItem( graphics, [this]() { SelectExit(); }, Vector2(WINDOW_WIDTH / 2, (WINDOW_HEIGHT / 2) + 30), "Exit Game", WHITE)); newItems->push_back(MenuItem( graphics, [this]() { SelectControls(); }, Vector2(WINDOW_WIDTH / 2, (WINDOW_HEIGHT / 2)), "Controls", WHITE)); newItems->push_back(MenuItem( graphics, [this]() { SelectStartGame(); }, Vector2(WINDOW_WIDTH / 2, (WINDOW_HEIGHT / 2) - 30), "Start Game", WHITE)); return newItems; }
f70fb6023ce646a77eda93da7ecfa7a9c243ec5b
128a9f1b0a15b39cc5ecb0505255bcad4e4ac216
/RetoUF4/RetoUF4/Generator.h
dcc040e97cd3b0e8b75f9a4c55df656b726cd444
[]
no_license
GitRomera/primeroUF4AccesoADAtos
19ac2984e6e79fd698b7e07f8299417922dc42e1
c67bfde1f848268d27999c26b7322a060991bb5f
refs/heads/master
2020-03-20T02:12:30.827213
2018-06-12T17:08:11
2018-06-12T17:08:11
137,103,637
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
h
Generator.h
#pragma once #include <string> struct Question { int order; int amountOfAnswers; std::string text; }; struct Answer { int order; int relatedQuestion; int points; std::string text; }; struct AnswerPoints { int pointsGained; int relatedQuestion; }; class Generator { public: Generator(); ~Generator(); void loadDialog(std::string xml); int getQuestionsAmount() { return questionsAmount; }; std::string getQuestiontext(int question) { return allQuestions[question].text; }; int getAnswersAmountOfQuestion(int question) { return allQuestions[question].amountOfAnswers; }; std::string getAnswersTextOfQuestion(int question, int answer); int getWinnedPointsOfQuestion(int question) { return pointsForQuestion[question].pointsGained; }; void setAnswerPointsOfQuestion(int question, int answer); int getTotalPoints() { return totalpoints; }; private: int questionsAmount; Question *allQuestions; int globalAnswersAmount; Answer *allAnswers; int totalpoints; AnswerPoints *pointsForQuestion; };
17a4f1641b6aebb2f7c8632ba1af98411230a848
6f54a292bb4b7251210766096742c24a6a4633a1
/picoquicfirst/picoquicclientxia.cpp
479e530e7853d8d962bfc7b307a870fddefcc2b1
[ "MIT" ]
permissive
XIA-Project/picoquic
df9ee1332b1457d4d15261727ca0390ed2037ae8
947fb56d9f8a73ce96507de2fb51121bb4d76051
refs/heads/master
2022-05-07T06:18:57.627651
2020-06-18T06:02:59
2020-06-18T06:02:59
170,539,329
0
2
MIT
2020-06-18T06:03:02
2019-02-13T16:20:47
C
UTF-8
C++
false
false
13,706
cpp
picoquicclientxia.cpp
#include "localconfig.hpp" // XIA support #include "xiaapi.hpp" #include "dagaddr.hpp" // C++ includes #include <iostream> // C includes #include <string.h> // memset #include <stdio.h> #include <pthread.h> extern "C" { #include "picoquic.h" // picoquic_create, states, err, pkt types, contexts //#include "picoquic_internal.h" #include "picosocks.h" // picoquic_select and server socks functions #include "util.h" }; #define CONFFILE "local.conf" #define THEIR_ADDR "THEIR_ADDR" // The THEIR_ADDR entry in config file #define CLIENT_AID "CLIENT_AID" // The CLIENT_AID entry in config file #define TICKET_STORE "TICKET_STORE" #define IFNAME "IFNAME" #define CONTROL_PORT "8295" #define CONTROL_IP "10.0.1.131" // If there were multiple streams, we would track progress for them here struct callback_context_t { int connected; int stream_open; int received_so_far; uint64_t last_interaction_time; }; //picoquic_stream_data_cb_fn int client_callback(picoquic_cnx_t* cnx, uint64_t stream_id, uint8_t*bytes, size_t length, picoquic_call_back_event_t event, void *callback_context) { printf("Client callback\n"); struct callback_context_t *context = (struct callback_context_t*)callback_context; context->last_interaction_time = picoquic_current_time(); switch(event) { case picoquic_callback_ready: printf("Callback: ready\n"); break; case picoquic_callback_almost_ready: printf("Callback: almost_ready\n"); break; case picoquic_callback_close: printf("Callback: close\n"); case picoquic_callback_application_close: printf("Callback: application close\n"); case picoquic_callback_stateless_reset: printf("Callback: stateless reset\n"); context->stream_open = 0; return 0; case picoquic_callback_stream_reset: printf("Callback: stream reset\n"); case picoquic_callback_stop_sending: printf("Callback: stop_sending\n"); picoquic_reset_stream(cnx, stream_id, 0); context->stream_open = 0; return 0; case picoquic_callback_stream_gap: printf("Callback: stream gap\n"); picoquic_reset_stream(cnx, stream_id, PICOQUIC_TRANSPORT_PROTOCOL_VIOLATION); context->stream_open = 0; return 0; case picoquic_callback_stream_data: printf("Callback: no event\n"); if(length > 0) { char data[256]; memcpy(data, (char*)bytes, length); data[length] = 0; printf("Server sent: %s\n", data); context->received_so_far += length; } break; case picoquic_callback_stream_fin: printf("Callback: stream finished\n"); if(length > 0) { char data[256]; memcpy(data, (char*)bytes, length); data[length] = 0; printf("Server sent: %s\n", data); context->received_so_far += length; } context->stream_open = 0; printf("Reception completed after %d bytes.\n", context->received_so_far); printf("Resetting the stream after it finished.\n"); picoquic_reset_stream(cnx, stream_id, 0); /* // Closing connection immediately printf("Closing connection after stream ended\n"); picoquic_close(cnx, 0); */ break; default: printf("ERROR: unknown callback event %d\n", event); }; return 0; } void start_stream(picoquic_cnx_t* connection, struct callback_context_t* context) { printf("Starting a stream\n"); uint64_t stream_id = 0; char data[] = "Hello world!"; context->stream_open = 1; context->connected = 1; // Queue up a "Hello world!" to be sent to the server printf("Sending %ld bytes of data on stream\n", sizeof(data)); if(picoquic_add_to_stream(connection, stream_id, // Any arbitrary stream ID client picks (uint8_t*)data, sizeof(data), // data to be sent 1)) { // finished; would be 0 if interacting more with server printf("ERROR: sending hello on stream\n"); } } int main() { // cleanup state int state = 0; int retval = -1; FILE* logfile = NULL; // Event loop parameters int64_t delay_max = 10000000; sockaddr_x packet_from; sockaddr_x packet_to; unsigned long if_index_to = 0; uint8_t buffer[1536]; int bytes_recv; int64_t delta_t = 0; //int notified_ready = 0; int established = 0; unsigned char received_ecn; uint64_t current_time; int zero_rtt_available = 0; // Flag set to 1 if 0RTT is available // Outgoing packet buffer uint8_t send_buffer[1536]; size_t send_length = 0; // read local config //server // sockaddr_x server_address; // std::string serverdagstr = SERVER_ADDR + " " + SERVER_AID; // Graph serverdag(serverdagstr); // serverdag.fill_sockaddr(&server_address); // int server_addrlen = sizeof(sockaddr_x); // LocalConfig conf; conf.control_addr = CONTROL_IP; conf.control_port = CONTROL_PORT; addr_info_t myaddr; addr_info_t serveraddr; std::string ticket_store_filename; if(conf.configure(CONTROL_PORT, CONTROL_IP, myaddr, serveraddr) < 0) { goto client_done; } // Server address - keeping that fixed // auto server_addr = conf.get_their_addr(); // auto server_aid = conf.get_server_aid(); // int server_addrlen; // auto conf = LocalConfig::get_instance(CONFFILE); // auto server_addr = conf.get(THEIR_ADDR); // auto server_aid = conf.get(SERVER_AID); // auto client_aid = conf.get(CLIENT_AID); // std::string client_ifname = conf.get(IFNAME); ticket_store_filename = TICKET_STORE; //conf.get_ticket_store(); // // QUIC client picoquic_quic_t *client; // Callback context struct callback_context_t callback_context; memset(&callback_context, 0, sizeof(struct callback_context_t)); // // A socket to talk to server on // //sockfd = socket(server_address.ss_family, SOCK_DGRAM, IPPROTO_UDP); // // bind to socket and fill my addr // sockfd = picoquic_xia_open_server_socket(client_aid.c_str(), mydag, client_ifname); // if(sockfd == INVALID_SOCKET) { // goto client_done; // } // std::cout << "CLIENTADDR: " << mydag->dag_string().c_str() << std::endl; // mydag->fill_sockaddr(&my_address); // my_addrlen = sizeof(sockaddr_x); // printf("Created socket to talk to server\n"); state = 1; // socket created // Create QUIC context for client current_time = picoquic_current_time(); callback_context.last_interaction_time = current_time; client = picoquic_create( 8, // number of connections NULL, // cert_file_name NULL, // key_file_name NULL, // cert_root_file_name "hq-17", // Appl. Layer Protocol Nogotiation NULL, // Stream data callback NULL, // Stream data context NULL, // connection ID callback NULL, // connection ID callback context NULL, // reset_seed current_time, // current time NULL, // p_simulated_time ticket_store_filename.c_str(), // ticket_file_name NULL, // ticket_encryption_key 0 // ticket encryption key length ); if(client == NULL) { printf("ERROR: creating client\n"); goto client_done; } printf("Created QUIC context\n"); state = 2; // picoquic context created for client // Open a log file for writing logfile = fopen("client.log", "w"); if(logfile == NULL) { printf("ERROR opening log file\n"); goto client_done; } PICOQUIC_SET_LOG(client, logfile); state = 3; // logfile needs to be closed // We didn't provide a root cert, so set verifier to null picoquic_set_null_verifier(client); // Create a connection in QUIC picoquic_cnx_t *connection; connection = picoquic_create_cnx( client, // QUIC context picoquic_null_connection_id, // initial connection ID picoquic_null_connection_id, // remote_connection ID (struct sockaddr*) &serveraddr.addr, // Address to current_time, // start time 0, // preferred version "localhost", // Server name identifier "hq-17", // ALPN 1 // client mode, set to 1, if on client side ); if(connection == NULL) { printf("ERROR: creating client connection in QUIC\n"); goto client_done; } printf("Created QUIC connection instance\n"); state = 4; // Set a callback for the client connection // TODO: Can we just set the callback in picoquic_create? picoquic_set_callback(connection, client_callback, &callback_context); // Now connect to the server if(picoquic_start_client_cnx(connection)) { printf("ERROR: connecting to server\n"); goto client_done; } printf("Started connection to server\n"); // If 0RTT is available, start a stream if(picoquic_is_0rtt_available(connection)) { start_stream(connection, &callback_context); zero_rtt_available = 1; } printf("Zero RTT available: %d\n", zero_rtt_available); pthread_mutex_lock(&conf.lock); // Send a packet to get the connection establishment started if(picoquic_prepare_packet(connection, current_time, send_buffer, sizeof(send_buffer), &send_length, (struct sockaddr_storage*)&serveraddr.addr, &serveraddr.addrlen, (struct sockaddr_storage*)&myaddr.addr, &myaddr.addrlen)) { printf("ERROR: preparing a QUIC packet to send\n"); pthread_mutex_unlock(&conf.lock); goto client_done; } printf("Prepared packet of size %zu\n", send_length); myaddr.dag->fill_sockaddr(&myaddr.addr); int bytes_sent; if(send_length > 0) { bytes_sent = picoquic_xia_sendmsg(myaddr.sockfd, send_buffer, (int) send_length, &serveraddr.addr, &myaddr.addr, conf); if(bytes_sent < 0) { printf("ERROR: sending packet to server\n"); goto client_done; } printf("Sent %d byte packet to server: %s) from me: %s\n", bytes_sent, serveraddr.dag->dag_string().c_str(), myaddr.dag->dag_string().c_str()); } pthread_mutex_unlock(&conf.lock); // Wait for incoming packets while(picoquic_get_cnx_state(connection) != picoquic_state_disconnected) { delay_max = 10000000; // Wait until data or timeout bytes_recv = picoquic_xia_select(myaddr.sockfd, &packet_from, &packet_to, buffer, sizeof(buffer), delta_t, &current_time); // Exit on error if(bytes_recv < 0) { printf("ERROR: receiving packet after select\n"); goto client_done; } // Get the connection state picoquic_state_enum cnx_state = picoquic_get_cnx_state(connection); printf("Connection state: %d\n", cnx_state); // We have a packet to process if(bytes_recv > 0) { printf("Got %d byte packet\n", bytes_recv); // TODO: it seems this function always returns 0 if(picoquic_incoming_packet(client, buffer, (size_t)bytes_recv, (struct sockaddr*)&packet_from, (struct sockaddr*)&packet_to, if_index_to, received_ecn, current_time)) { printf("ERROR: processing incoming packet\n"); delta_t = 0; } delta_t = 0; } // Timed out. Check if connection established or stream ended if(bytes_recv == 0) { if(cnx_state == picoquic_state_ready || cnx_state == picoquic_state_client_ready_start) { // The connection is ready. Start a stream. if(!established) { printf("Connected! ver: %x, I-CID: %llx\n", picoquic_supported_versions[ connection->version_index].version, (unsigned long long)picoquic_val64_connection_id( picoquic_get_logging_cnxid(connection))); if(!zero_rtt_available) { printf("zero rtt was not available, starting stream\n"); start_stream(connection, &callback_context); } established = 1; } } // If the stream has been closed, we close the connection if(callback_context.connected && !callback_context.stream_open) { printf("The stream was not open, close connection\n"); picoquic_close(connection, 0); connection = NULL; break; } // Waited too long. Close connection if(current_time > callback_context.last_interaction_time && current_time - callback_context.last_interaction_time > 60000000ull) { printf("No progress for 60 seconds. Closing\n"); picoquic_close(connection, 0); connection = NULL; break; //goto client_done; } } // We get here whether there was a packet or a timeout send_length = PICOQUIC_MAX_PACKET_SIZE; while(send_length > 0) { //sleep(5); // add a delay make sure the configuration updates // Send out all packets waiting to go pthread_mutex_lock(&conf.lock); if(picoquic_prepare_packet(connection, current_time, send_buffer, sizeof(send_buffer), &send_length, NULL, NULL, NULL, NULL)) { printf("ERROR sending QUIC packet\n"); pthread_mutex_unlock(&conf.lock); goto client_done; } if(send_length > 0) { printf("Sending packet of size %ld\n", send_length); bytes_sent = picoquic_xia_sendmsg(myaddr.sockfd, send_buffer, (int) send_length, &serveraddr.addr, &myaddr.addr, conf); //printf("Sending a packet of size %d\n", (int)send_length); if(bytes_sent <= 0) { printf("ERROR sending packet to server\n"); } printf("Sent %d byte packet to server: %s) from me: %s\n", bytes_sent, serveraddr.dag->dag_string().c_str(), myaddr.dag->dag_string().c_str()); } pthread_mutex_unlock(&conf.lock); } // How long before we timeout waiting for more packets delta_t = picoquic_get_next_wake_delay(client, current_time, delay_max); } // Save tickets from server, so we can join quickly next time if(picoquic_save_tickets(client->p_first_ticket, current_time, ticket_store_filename.c_str()) != 0) { printf("ERROR saving session tickets\n"); } // Everything went well, so return success retval = 0; client_done: switch(state) { case 4: if(connection) { picoquic_close(connection, 0); // 0 = reason code } case 3: fclose(logfile); // fallthrough case 2: picoquic_free(client); // fallthrough case 1: // TODO: Need to unregister this socket and AID at router close(myaddr.sockfd); }; return retval; }
34cfe9827a93fa2d0cac6501f81a8a65bb6da84d
faabc45380c3860e3447dc6622f32cfc69f60398
/1027C.cpp
080e086636e744e640cd31cc963d52b5bcd28bdd
[]
no_license
salmandotexe/Codeforces
ce2cd4e087911cc4703c1e2a0b2d964fbea3a7b8
fb71cda1a63751fb1ba78dca80e01903bdc4529e
refs/heads/master
2021-04-15T04:45:08.212196
2021-01-08T17:43:20
2021-01-08T17:43:20
126,494,526
2
0
null
null
null
null
UTF-8
C++
false
false
19
cpp
1027C.cpp
//WA on Test 4 //
f66a118c1aa06a08920b395fe4cc5c3598df5647
77ab48a43cfc334904d1d9b059b1a94adfee89b6
/phase.h
e7cdb523b0a862a3003d887075b5236a04522acd
[]
no_license
wakaba-c/GraduationPresentation
51bb296344054411d82d31079dbddd3549593cc6
0105b580154c026b794c35a698a8c0e9da3ac055
refs/heads/master
2023-02-21T20:54:15.829624
2021-01-25T15:15:06
2021-01-25T15:15:06
303,548,547
0
5
null
2021-01-22T06:09:47
2020-10-13T00:47:54
C++
SHIFT_JIS
C++
false
false
1,805
h
phase.h
//============================================================================= // // フェーズ数表示処理 [phase.h] // Author : masayasu wakita // //============================================================================= #ifndef _PHASE_H_ #define _PHASE_H_ //============================================================================= // インクルードファイル //============================================================================= #include "main.h" #include "scene2D.h" //============================================================================= // マクロ定義 //============================================================================= #define MAX_DAYNUMBER 2 // 数字の桁数 //============================================================================= // 前方宣言 //============================================================================= class CNumber; //============================================================================= // クラス定義 //============================================================================= class CPhase : public CScene2D { public: CPhase(PRIORITY obj); // コンストラクタ ~CPhase(); // デストラクタ HRESULT Init(void); // 初期化処理 void Uninit(void); // 開放処理 void Update(void); // 更新処理 void Draw(void); // 描画処理 static CPhase *Create(void); // クリエイト処理 static HRESULT Load(void); // ロード処理 void SetNumber(int nValue); // 数字の設定 void AddNumber(int nValue); // 数字の加算 int GetNumber(void){ return m_nNumber; } // 数字の取得 private: CNumber *m_apNumber[MAX_DAYNUMBER]; // 数字のポインタ int m_nNumber; // 数字 }; #endif
fba5f1710a5e95060e5f9b08b8244be3246ef1a9
651576d3efdc0852fadc27df033388857b7e58f9
/teamwork(1)/change_password.h
13447c81d0adcdbaeed974b72f3897615be5bdeb
[]
no_license
wsx676/919106840138
d8dc959561c211fce796fa65b13f4c8e0f716c4f
28d7f93abe825ff1d965e7ab4d79a185d869ef32
refs/heads/master
2022-12-20T18:04:25.738676
2020-09-26T11:00:42
2020-09-26T11:00:42
294,738,259
0
0
null
null
null
null
UTF-8
C++
false
false
474
h
change_password.h
#ifndef CHANGE_PASSWORD_H #define CHANGE_PASSWORD_H #include <QWidget> namespace Ui { class change_password; } class change_password : public QWidget { Q_OBJECT public: explicit change_password(QWidget *parent = nullptr); ~change_password(); signals: void Mysignal(); private slots: void on_queding_clicked(); void on_fanhui_clicked(); private: Ui::change_password *ui; }; #endif // CHANGE_PASSWORD_H
9def16696c29aa03e3d0ef4f79f1854771d4d429
5279fdde651ecb50ee7e178a6351156437b7f069
/BAPSPresenter/BAPSPresenterMainReactions_database.cpp
febc5fe62aa90e9a02926e75c043a6d0ae73ce0b
[ "BSD-3-Clause" ]
permissive
UniversityRadioYork/BAPS2
587bb8ed6864e719eca406e31d2c2eda38d0e36a
af80b66cdd7a980cf34714bef7b5260167714ca5
refs/heads/master
2022-03-07T16:35:51.735951
2019-05-26T19:19:19
2019-05-26T19:19:19
80,321,106
4
1
BSD-3-Clause
2019-05-26T19:19:20
2017-01-29T00:45:05
C
UTF-8
C++
false
false
2,935
cpp
BAPSPresenterMainReactions_database.cpp
#include "stdafx.h" #include "BAPSPresenterMain.h" using namespace BAPSPresenter; /** Just pass all the data through to the child form (if present) **/ void BAPSPresenterMain::addLibraryResult(u32int index, int dirtyStatus, System::String^ result) { if (recordLibrarySearch != nullptr) { MethodInvokerObjObjStr^ mi = gcnew MethodInvokerObjObjStr(recordLibrarySearch, &RecordLibrarySearch::add); array<System::Object^>^ dd = gcnew array<System::Object^>(3) {(int)index, dirtyStatus, result}; recordLibrarySearch->Invoke(mi,dd); } } void BAPSPresenterMain::setLibraryResultCount(int count) { if (recordLibrarySearch != nullptr) { MethodInvokerObj^ mi = gcnew MethodInvokerObj(recordLibrarySearch, &RecordLibrarySearch::setResultCount); array<System::Object^>^ dd = gcnew array<System::Object^>(1) {count}; recordLibrarySearch->Invoke(mi,dd); } } void BAPSPresenterMain::notifyLibraryError(int errorcode, System::String^ description) { if (recordLibrarySearch != nullptr) { MethodInvokerObjStr^ mi = gcnew MethodInvokerObjStr(recordLibrarySearch, &RecordLibrarySearch::handleError); array<System::Object^>^ dd = gcnew array<System::Object^>(2) {errorcode, description}; recordLibrarySearch->Invoke(mi,dd); } } void BAPSPresenterMain::addShowResult(u32int showid, System::String^ description) { if (loadShowDialog != nullptr) { MethodInvokerObjStr^ mi = gcnew MethodInvokerObjStr(loadShowDialog, &LoadShowDialog::addShow); array<System::Object^>^ dd = gcnew array<System::Object^>(2) {(int)showid, description}; loadShowDialog->Invoke(mi,dd); } } void BAPSPresenterMain::setShowResultCount(int count) { if (loadShowDialog != nullptr) { MethodInvokerObj^ mi = gcnew MethodInvokerObj(loadShowDialog, &LoadShowDialog::setShowResultCount); array<System::Object^>^ dd = gcnew array<System::Object^>(1) {count}; loadShowDialog->Invoke(mi,dd); } } void BAPSPresenterMain::addListingResult(u32int listingid, u32int channel, System::String^ description) { if (loadShowDialog != nullptr) { MethodInvokerObjObjStr^ mi = gcnew MethodInvokerObjObjStr(loadShowDialog, &LoadShowDialog::addListing); array<System::Object^>^ dd = gcnew array<System::Object^>(3) {(int)listingid, (int)channel, description}; loadShowDialog->Invoke(mi,dd); } } void BAPSPresenterMain::setListingResultCount(int count) { if (loadShowDialog != nullptr) { MethodInvokerObj^ mi = gcnew MethodInvokerObj(loadShowDialog, &LoadShowDialog::setListingResultCount); array<System::Object^>^ dd = gcnew array<System::Object^>(1) {count}; loadShowDialog->Invoke(mi,dd); } } void BAPSPresenterMain::notifyLoadShowError(int errorCode, System::String^ message) { if (loadShowDialog != nullptr) { MethodInvokerObjStr^ mi = gcnew MethodInvokerObjStr(loadShowDialog, &LoadShowDialog::notifyError); array<System::Object^>^ dd = gcnew array<System::Object^>(2) {errorCode, message}; loadShowDialog->Invoke(mi,dd); } }
d02d712d7bf77fbcb8c7de6cd4ed7d26fd70a47d
0fb4a3b4dcbbb5a618ffb255044882025922582f
/src/Frame.hpp
400e4b50f2ed092cedd996e39936c075ddc86a07
[ "Apache-2.0" ]
permissive
otaGran/ios-minicap
678bfb6f96adb95fd17550c1e42831346e4e6a13
bcd654fb35b756120803ac3f6e6566ee603cf286
refs/heads/master
2023-01-24T15:24:54.044094
2019-06-11T07:14:57
2019-06-11T07:14:57
191,316,200
1
0
NOASSERTION
2023-01-11T01:16:37
2019-06-11T07:20:42
C++
UTF-8
C++
false
false
383
hpp
Frame.hpp
// // Created by pavlov on 16/11/16. // #ifndef IOS_MINICAP_FRAME_HPP #define IOS_MINICAP_FRAME_HPP #include <cstdlib> enum Format { FORMAT_BGRA_8888 = 0x01, FORMAT_UNKNOWN = 0x00, }; struct Frame { void const* data; Format format; uint32_t width; uint32_t height; uint32_t bytesPerRow; size_t size; }; #endif //IOS_MINICAP_FRAME_HPP
36282cbb49c4755a6c53914e0cab4cb81d921f08
8cfed62f9103b8a5c41a01ca60144f99896b275d
/bspline_isti.cpp
59bbf6147ee9c33f15b5faffde288e37c457b601
[]
no_license
liiniix/CG
f402fa30ff3d80dbbfbb5c284cf711332e0773e1
cbeb73c4328f2e0f72d3f74f0ddccea95a5e168b
refs/heads/master
2022-12-26T14:23:37.886500
2020-09-28T05:47:46
2020-09-28T05:47:46
234,679,077
0
0
null
null
null
null
UTF-8
C++
false
false
6,258
cpp
bspline_isti.cpp
#if 0 Skip to content Using University of Dhaka Mail with screen readers Meet New meeting My meetingsNew Hangouts 2 of 4 Program for drawing rainbow colored B-splines Inbox x Ishtiaque Zahid <ruko97@gmail.com> Attachments 12:54 PM (1 hour ago) to Haider Attachments area #endif // 0 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <GL/glut.h> #define TARGET 0 typedef struct { float x; float y; } poi; //2D point or vector typedef struct { float R; float G; float B; } color; // Color static int Ym = 960, Xm = 1280; //static poi P[6] = { {-620, 450}, {-530, -400}, // {-150, 400}, {0, -460}, // {450, 420}, {630, -260} }; // 6 vertex static poi P[7][6]; // For 7 colors, 6 points for each color static color rainbow[7] = { {0.7, 0, 1.0 }, { 0.2, 0.0, 1.0 }, { 0.6, 0.6, 1.0 }, {0, 1, 0}, { 1, 1, 0 }, { 1, 0.6, 0}, {1, 0, 0} }; static poi Ch[6] = { {-1.5, 1.7}, {-1.5, -1},{1.5, 1.7}, {1.5, -1}, {1.5, 1.7}, {1.5, -1.7} }; static void initValues() { P[0][0] = { -620, 450 }, P[0][1] = { -530, -400 }, P[0][2] = { -150, 400 }, P[0][3] = { 0, -400 }, P[0][4] = { 450, 400 }, P[0][5] = { 630, -400 }; for (int i = 1; i < 7; i++) { for (int j = 0; j < 6; j++) { P[i][j].x = P[i - 1][j].x + 6; P[i][j].y = P[i - 1][j].y + 6; } } } static void reShape(int width, int height) { //const float ar = (float)width/(float)height; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-Xm / 2, Xm / 2 - 1, Ym / 2 - 1, -Ym / 2, -1, 1); //640x480 glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } // Draws border along the curve of target color static void drawBorder(int target) { for (int i = 0; i < 6; i++) { glPointSize(5); glBegin(GL_POINTS); glColor3f(0, 1, 1); glVertex2i((int)P[target][i % 6].x, (int)P[target][i % 6].y); glVertex2i((int)P[target][(i + 1) % 6].x, (int)P[target][(i + 1) % 6].y); glVertex2i((int)P[target][(i + 2) % 6].x, (int)P[target][(i + 2) % 6].y); glVertex2i((int)P[target][(i + 3) % 6].x, (int)P[target][(i + 3) % 6].y); glEnd(); glPointSize(1); glBegin(GL_LINES); glColor3f(1, 1, 1); glVertex2i((int)P[target][i % 6].x, (int)P[target][i % 6].y); glVertex2i((int)P[target][(i + 1) % 6].x, (int)P[target][(i + 1) % 6].y); glVertex2i((int)P[target][(i + 1) % 6].x, (int)P[target][(i + 1) % 6].y); glVertex2i((int)P[target][(i + 2) % 6].x, (int)P[target][(i + 2) % 6].y); glVertex2i((int)P[target][(i + 2) % 6].x, (int)P[target][(i + 2) % 6].y); glVertex2i((int)P[target][(i + 3) % 6].x, (int)P[target][(i + 3) % 6].y); glEnd(); } } static void drawSpline(int color) { float t; poi Po; for (int i = 0; i < 6; i++) { glPointSize(1); glColor3f(rainbow[color].R, rainbow[color].G, rainbow[color].B); glBegin(GL_POINTS); for (t = 0; t < 1.0; t += 0.0005) { Po.x = ((1 - t) * (1 - t) * (1 - t) * P[color][(i) % 6].x + (3 * t * t * t - 6 * t * t + 4) * P[color][(i + 1) % 6].x + (-3 * t * t * t + 3 * t * t + 3 * t + 1) * P[color][(i + 2) % 6].x + t * t * t * P[color][(i + 3) % 6].x) / 6; Po.y = ((1 - t) * (1 - t) * (1 - t) * P[color][(i) % 6].y + (3 * t * t * t - 6 * t * t + 4) * P[color][(i + 1) % 6].y + (-3 * t * t * t + 3 * t * t + 3 * t + 1) * P[color][(i + 2) % 6].y + t * t * t * P[color][(i + 3) % 6].y) / 6; glVertex2i((int)Po.x, (int)Po.y); } glEnd(); glColor3f(1, 1, 1); } } static void drawSplines() { for (int c = 0; c < 7; c++) { drawSpline(c); } } // Points are bounced if the points having target color meet the corner of the screen static void bouncePoints(int target) { for (int i = 0; i < 6; i++) { for (int c = 0; c < 7; c++) { P[c][i].x += Ch[i].x; } if (P[target][i].x > (Xm/2 - 1) || P[target][i].x < (-Xm/2)) Ch[i].x *= -1; for (int c = 0; c < 7; c++) { P[c][i].y += Ch[i].y; } if (P[target][i].y > (Ym/2 - 1) || P[target][i].y < (-Ym/2)) Ch[i].y *= -1; } } static void display(void) { for (;;) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); //drawBorder(TARGET); drawSplines(); glPopMatrix(); //glFlush(); glutSwapBuffers(); bouncePoints(TARGET); } } static void idle(void) { glutPostRedisplay(); } static void myinit(void) { glClearColor(0, 0, 0, 1); glEnable(GL_COLOR_MATERIAL); } static int nearPoi(poi a, poi b) { float d; d = sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); if (d < 5.0) return 1; else return 0; } static void OnMouseClick(int button, int state, int X, int Y) { poi Pt; int i, k = -1; Pt.x = X - Xm / 2; Pt.y = Y - Ym / 2; if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { //store the x,y value where the click happened puts("Left button clicked"); for (i = 0; i < 4; i++) { if (nearPoi(P[TARGET][(i) % 4], Pt)) { k = i; break; } } printf("i = %d, x = %d and y = %d\n", k, X - Xm / 2, Y - Ym / 2); } if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { //store the x,y value where the click happened puts("Right button clicked"); } glutPostRedisplay(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitWindowSize(Xm, Ym); glutInitWindowPosition(10, 10); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutCreateWindow("Spline Curve"); glutReshapeFunc(reShape); glutDisplayFunc(display); glutMouseFunc(OnMouseClick); glutIdleFunc(idle); myinit(); initValues(); glutMainLoop(); return EXIT_SUCCESS; }
90116cb37cf96bddd432ccc482623b2e07198bbc
6f17641edd2f55f4ebc2352231d91276f7158ca7
/exercise-02.cpp
9001a0fcf2f4eb1c9787b5cea4ad6a8d1dfa28b4
[]
no_license
nadhifalR/strukdat-02
a213911261e3a22041ccaf56a5c24cc83001da1d
0a381eeeff3eb509f70c55f42773097080eb064f
refs/heads/master
2020-04-27T07:01:20.049196
2019-03-06T10:39:26
2019-03-06T10:39:26
174,124,764
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
exercise-02.cpp
/* * Author : Nadhifal * NPM : 140810180048 * Deskripsi : * Tahun : 2019 */ #include <iostream> #include <string.h> using namespace std; struct Theater{ int room; char seat[3]; char movieTitle[30]; }; main(){ Theater theater; theater.room=7; strcpy(theater.seat, "J9"); strcpy(theater.movieTitle, "Adit & Jarwo"); cout<<theater.room<<endl; cout<<theater.seat<<endl; cout<<theater.movieTitle<<endl; }
d38567172854deb351a286b0eb1c37078d113893
79e9131a98cee0ffe42774479f5ace379a577738
/src/Exception.cpp
8b9206061bedb5ff1827a269bd91b52112530474
[]
no_license
tangyibo/libcppes
cd7272589fb16500b6471b3fb2d93ffa8c43001b
b9e529bc6baf89ce13e972c36f20797bd2c85aca
refs/heads/master
2020-03-27T19:47:08.255116
2018-09-03T09:02:22
2018-09-03T09:02:22
147,011,174
3
1
null
null
null
null
UTF-8
C++
false
false
2,152
cpp
Exception.cpp
// Copyright tang. All rights reserved. // https://github.com/tangyibo/libcppes // // Use of this source code is governed by a BSD-style license // // Author: tang (inrgihc@126.com) // Data : 2018/8/2 // Location: beijing , china ///////////////////////////////////////////////////////////// #include "Exception.h" #include <cxxabi.h> #include <execinfo.h> #include <stdlib.h> #include <stdio.h> #include <sstream> namespace cppes { using namespace std; Exception::Exception( const char *file,const int line,const char* msg) : _message(msg) { fillStackTrace(file,line); } Exception::Exception( const char *file,const int line,const string& msg) : _message(msg) { fillStackTrace(file,line); } Exception::~Exception() throw () { _message.clear(); _stack.clear(); } const char* Exception::what() const throw () { return _message.c_str(); } const char* Exception::stackTrace() const throw () { return _stack.c_str(); } void Exception::fillStackTrace( const char *file,const int line) { const int len = 200; void* buffer[len]; int nptrs = ::backtrace(buffer, len); char** strings = ::backtrace_symbols(buffer, nptrs); std::stringstream stream; stream << "Exception in file[" << file << ":" << line << ":\n"; _stack.append(stream.str()); if (strings) { for (int i = 0; i < nptrs; ++i) { std::stringstream ss; ss << "\n >>>[" << i << "] "; _stack.append(ss.str()); _stack.append(demangle(strings[i])); } free(strings); } } string Exception::demangle(const char* symbol) { size_t size; int status; char temp[128]; char* demangled; if (1 == sscanf(symbol, "%*[^(]%*[^_]%127[^)+]", temp)) { if (NULL != (demangled = abi::__cxa_demangle(temp, NULL, &size, &status))) { string result(demangled); free(demangled); return result; } } if (1 == sscanf(symbol, "%127s", temp)) { return temp; } return symbol; } } // end namespace
0008ebdd9879db2bfc3698d65cac29ed0aacaae7
cb21eebdc39d3bcc46e72bd1f1e2a420df12e2b7
/project-02/mainrun.cpp
2d9a1ba6962ee16d3de343efe708f543fd86f1a3
[]
no_license
trigggggy/tie-02206-basic-course-on-programming_s2017
b2ff56d41c1d4672d6b8d873bd489c8d5e3bb277
c6649cfc92ae7d8174668e3057810d2b3653dfae
refs/heads/master
2021-02-11T08:48:46.922005
2020-03-02T21:03:56
2020-03-02T21:03:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,372
cpp
mainrun.cpp
//hung.nguyen@student.tut.fi - student id: 272585 //sanghun.2.lee@student.tut.fi - student id: 272571 #include <iostream> #include "market.hh" #include "mainrun.hh" #include "splitter.hh" void mainRun(market m){ while(1){ string line; cout<<"product search> "; getline(cin,line); if(line == "quit" ){ break; }else if(line == "chains"){ m.getChains(); }else{ vector<string> vec = split(line,' '); if(vec.at(0) == "cheapest"){ if(vec.size() != 2){ cout<<"Error: require 1 parameter after \"cheapest\"."<<endl; }else{ m.getCheapest(vec.at(1)); } }else if(vec.at(0) =="stores"){ if(vec.size() != 2){ cout<<"Error: require 1 parameter after \"stores\"."<<endl; }else{ m.getChainStores(vec.at(1)); } }else if(vec.at(0) == "selection") { if(vec.size() != 3){ cout<<"Error: require 2 parameters after \"selection\"."<<endl; }else{ m.getStoreProducts(vec.at(1),vec.at(2)); } }else{ cout<<"Error: unknown command."<<endl; } } } }