blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
9b4c0274d6a2516abc2d18b9e79aadf84d0d0594
db3b085d00c89ed16bd9e78e132c4558848e6866
/659_Split_Array_into_Consecutive_Subsequences.cpp
99b30ca09ead495f89395e758950eca1e04ddb2d
[]
no_license
zkxshg/Test_of_LeetCode
23e4bcd814499c26940659614607f0782c764b09
8a3c2d43ed0b5815c5fb2d2bb4d59e586aae9dba
refs/heads/master
2023-08-22T16:08:04.801856
2023-08-09T22:43:56
2023-08-09T22:43:56
230,379,638
1
0
null
null
null
null
UTF-8
C++
false
false
1,812
cpp
// https://leetcode.com/problems/split-array-into-consecutive-subsequences/ // RLE + Heap + DP class Solution { public: bool isPossible(vector<int>& nums) { int n = nums.size(); // RLE coding vector<pair<int, int> > RLE; RLE.push_back({nums[0], 1}); for (int i = 1; i < n; i++) { if (nums[i] == RLE.back().first) RLE.back().second++; else RLE.push_back({nums[i], 1}); } // for (auto& p : RLE) cout << p.first << ":" << p.second << ","; cout << endl; n = RLE.size(); vector<int> pre; for (int i = 0; i < RLE[0].second; i++) pre.push_back(1); for (int i = 1; i < n; i++) { vector<int> tem; int suc = RLE[i].first, cou = RLE[i].second; // Non-consecutive if (suc - RLE[i - 1].first > 1) { if (!pre.empty() && pre[0] < 3) return false; pre.clear(); for (int j = 0; j < cou; j++) pre.push_back(1); continue; } // Consecutive if (cou <= pre.size()) { int m = pre.size(), pos = 0; for (int j = 0; j < cou; j++) tem.push_back(pre[j] + 1); if (cou < pre.size() && pre[cou] < 3) return false; } else { for (int j = 0; j < cou - pre.size(); j++) tem.push_back(1); for (int j : pre) tem.push_back(j + 1); } pre = tem; // for (int i : pre) cout << i << ","; cout << endl; } if (!pre.empty() && pre[0] < 3) return false; return true; } };
[ "zkxshg@126.com" ]
zkxshg@126.com
54944cb21349501cb6fd10c966902c5a7f615feb
2593fd19ae08e43c2891774bdf46a2aa28649e05
/src/gui/f_gui_enums.hpp
146c35ea011a0d7f6a86174379c0f9d9e39dd6e7
[ "MIT" ]
permissive
Frozen-Team/3FEngine
58fbf6a92e741dd24bd23e4128e49a0eb62d0326
f0b7002a1e5912b8f49377570b226b22eec662cf
refs/heads/master
2020-12-28T23:46:42.938043
2015-11-25T23:02:57
2015-11-25T23:02:57
43,645,038
2
2
null
null
null
null
UTF-8
C++
false
false
820
hpp
#ifndef _3FENGINE_SRC_GUI_F_GUI_ENUMS_HPP_ #define _3FENGINE_SRC_GUI_F_GUI_ENUMS_HPP_ #include <utils/f_flags.hpp> namespace fengine { namespace fgui { enum WindowFlag { kWindowFullscreen = 0x00000001, kWindowOpenGl = 0x00000002, kWindowShown = 0x00000004, kWindowHidden = 0x00000008, kWindowBordless = 0x00000010, kWindowResizeble = 0x00000020, kWindowMinimized = 0x00000040, kWindowMaximized = 0x00000080, kWindowInputGrabbed = 0x00000100, kWindowInputFocus = 0x00000200, kWindowMouseFocus = 0x00000400, kWindowFullDesktop = (kWindowFullscreen | 0x00001000), kWindowFOREIGN = 0x00000800, kWindowAllowHighDpi = 0x00002000, kWindowMouseCapture = 0x00004000 }; F_DECLARE_FLAGS_ENUM(WindowFlag, WindowFlags) } } #endif // _3FENGINE_SRC_GUI_F_GUI_ENUMS_HPP_
[ "maxymhammer@yandex.ru" ]
maxymhammer@yandex.ru
1c29ce90dba5abca9fbc48ee9347194733917c67
660f25caf939daf0de0cbdb28c40f493b9894c25
/Coursework option 18 year2term2/Assignment.h
084c643492dea011faff72b562259e5f42cec4cc
[]
no_license
keptt/Uni
0bb270632a8dd3e980632397d21b87ce11093fa5
20555abb5ccb68160c2ce147978dc297ce3dea97
refs/heads/master
2020-04-09T04:41:42.263994
2019-06-16T10:43:55
2019-06-16T10:43:55
160,032,523
0
0
null
null
null
null
UTF-8
C++
false
false
1,709
h
#pragma once #include <string> #include <iostream> enum eStatus : short { inprogress = 0, done }; enum ePriority :short { low = 1, medium, high, urgent }; class Assignment { protected: std::string m_name; size_t m_id; eStatus m_status; std::string m_start_date; std::string m_deadline; std::string m_description; ePriority m_priority; public: Assignment(); Assignment(std::string name, size_t id, short status, std::string start_date, std::string deadline, std::string description, short priority); std::string get_name() const; std::string get_deadline(); size_t get_id() const; std::string get_start_date() const; eStatus get_status() const; ePriority get_priority() const; void set_name(std::string name); void set_description(std::string description); void set_start_date(std::string start_date); void set_deadline(std::string deadline); void set_id(size_t id); void set_status(eStatus status); void set_priority(ePriority priority); ///virtual std::ostream &print_out(std::ostream &out) const = 0; ///virtual std::ostream &enter_info(std::ostream &in) const = 0; virtual void output_obj(std::ostream &out) const = 0; virtual void input_obj(std::istream &in) = 0; ///friend std::ofstream &operator<<(std::ofstream &fout, const Assignment *obj); ///friend std::ifstream &operator>>(std::ifstream &fin, Assignment *obj); friend std::ostream &operator<<(std::ostream &out, const Assignment *obj); friend std::istream &operator>>(std::istream &in, Assignment *obj); virtual ~Assignment() = default;/// }; //std::ifstream in("FILENAME.smth"); //std::string s; //char buffer[100]; // //while (in) //{ // in.read(buffer, 100); // s.append(buffer, in.gcount()); // //}
[ "blackoutxray@gmail.com" ]
blackoutxray@gmail.com
1b3a1bc7e3ba1c72aed1764b674fa2ea0d4fae7a
27a9208e100540c0f019a7b7dc39129796fef651
/SpaceSim/NodeGraph/GraphNodeDefinition.h
174a89f7f8dc625620980b367acd0b9ea6078274
[]
no_license
NightCreature/SpaceSim
09cd94a5382c92a5cc5385c5e533daa8bbd8b649
bda51a4454ebb0dbc2f8c9605073f0c3d7f7e2c7
refs/heads/master
2023-05-26T07:16:43.045731
2022-07-27T03:00:19
2022-07-27T03:00:19
20,378,638
3
1
null
2022-07-27T03:00:20
2014-06-01T14:14:26
C++
UTF-8
C++
false
false
580
h
#pragma once #include "Core/tinyxml2.h" #include "GraphNodePin.h" #include <vector> namespace NodeGraph { class NodeDefinition { public: NodeDefinition() = default; ~NodeDefinition() = default; void Deserialise(const tinyxml2::XMLElement& nodeDefinition); HASH_ELEMENT_DEFINITION(NodeDefinition) private: std::vector<PinDefinition> m_inputPins; std::vector<PinDefinition> m_outputPins; size_t m_id = 0; //this is the node name needed to encode the connections in a grpah size_t m_nodeDefinition = 0; //links to actual node implementation }; }
[ "paulkruitz@gmail.com" ]
paulkruitz@gmail.com
0081213e568db2df2fe0f4b94b8d6169b3883580
5042d0ed03720d4308e8c8fad1ebfc59a28fecca
/ctvshowwidget.cpp
d08451ee8b83f424176fd6e40c24f00707e546c1
[]
no_license
birkeh/qtKodiAdmin
66995625752bc79f588ce6d7c3495a02472bae84
e50bdbd7089ab0c844324d480ca661c30fcd8f2b
refs/heads/master
2023-04-07T11:52:23.118613
2023-03-28T08:17:35
2023-03-28T08:17:35
71,261,863
0
0
null
null
null
null
UTF-8
C++
false
false
4,980
cpp
#include "ctvshowwidget.h" #include "ui_ctvshowwidget.h" #include "cimage.h" #include "cvideoviewitemdelegate.h" #include "ccheckboxitemdelegate.h" #include "common.h" cTVShowWidget::cTVShowWidget(QWidget *parent) : QWidget(parent), ui(new Ui::cTVShowWidget), m_lpTVShowModel(0), m_lpImageList(0) { initUI(); } cTVShowWidget::~cTVShowWidget() { DELETE(m_lpTVShowModel); DELETE(m_lpCastModel); DELETE(m_lpDirectorModel); DELETE(m_lpWriterModel); DELETE(m_lpCountryModel); DELETE(m_lpGenreModel); DELETE(m_lpStudioModel); // DELETE(m_lpVideoStreamModel); // DELETE(m_lpAudioStreamModel); // DELETE(m_lpSubtitleStreamModel); delete ui; } void cTVShowWidget::initUI() { ui->setupUi(this); ui->m_lpBanner->setMinimumSize(BANNER_WIDTH, BANNER_HEIGHT); ui->m_lpFanart->setMinimumSize(FANART_WIDTH, FANART_HEIGHT); ui->m_lpPoster->setMinimumSize(POSTER_WIDTH, POSTER_HEIGHT); ui->m_lpThumb->setMinimumSize(THUMB_WIDTH, THUMB_HEIGHT); ui->m_lpInformationTab->setCurrentIndex(0); m_lpTVShowModel = new QStandardItemModel(0, 1); QStringList headerLabels = QStringList() << tr("TV Show"); m_lpTVShowModel->setHorizontalHeaderLabels(headerLabels); ui->m_lpTVShowView->setModel(m_lpTVShowModel); ui->m_lpTVShowView->setItemDelegate(new cVideoViewItemDelegate()); m_lpCastModel = new QStandardItemModel(0, 2); headerLabels = QStringList() << tr("Name") << tr("Role"); m_lpCastModel->setHorizontalHeaderLabels(headerLabels); ui->m_lpCastView->setModel(m_lpCastModel); m_lpDirectorModel = new QStandardItemModel(0, 1); headerLabels = QStringList() << tr("Name"); m_lpDirectorModel->setHorizontalHeaderLabels(headerLabels); ui->m_lpDirectorView->setModel(m_lpDirectorModel); m_lpWriterModel = new QStandardItemModel(0, 1); headerLabels = QStringList() << tr("Name"); m_lpWriterModel->setHorizontalHeaderLabels(headerLabels); ui->m_lpWriterView->setModel(m_lpWriterModel); m_lpCountryModel = new QStandardItemModel(0, 1); headerLabels = QStringList() << tr("Name"); m_lpCountryModel->setHorizontalHeaderLabels(headerLabels); ui->m_lpCountryView->setModel(m_lpCountryModel); ui->m_lpCountryView->setItemDelegate(new cCheckBoxItemDelegate()); m_lpGenreModel = new QStandardItemModel(0, 1); headerLabels = QStringList() << tr("Name"); m_lpGenreModel->setHorizontalHeaderLabels(headerLabels); ui->m_lpGenreView->setModel(m_lpGenreModel); ui->m_lpGenreView->setItemDelegate(new cCheckBoxItemDelegate()); m_lpStudioModel = new QStandardItemModel(0, 1); headerLabels = QStringList() << tr("Name"); m_lpStudioModel->setHorizontalHeaderLabels(headerLabels); ui->m_lpStudioView->setModel(m_lpStudioModel); ui->m_lpStudioView->setItemDelegate(new cCheckBoxItemDelegate()); // m_lpVideoStreamModel = new QStandardItemModel(0, 4); // ui->m_lpVideoStreamView->setModel(m_lpVideoStreamModel); // m_lpAudioStreamModel = new QStandardItemModel(0, 4); // ui->m_lpAudioStreamView->setModel(m_lpAudioStreamModel); // m_lpSubtitleStreamModel = new QStandardItemModel(0, 1); // ui->m_lpSubtitleStreamView->setModel(m_lpSubtitleStreamModel); ui->m_lpCountryView->setWrapping(true); ui->m_lpGenreView->setWrapping(true); ui->m_lpStudioView->setWrapping(true); QList<int> sizes; sizes << 500 << 1000; ui->m_lpSplitter->setSizes(sizes); // QItemSelectionModel* selectionModel = ui->m_lpVideoView->selectionModel(); // connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(videoSelectionChanged(QItemSelection,QItemSelection))); // selectionModel = ui->m_lpCastView->selectionModel(); // connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(castSelectionChanged(QItemSelection,QItemSelection))); // selectionModel = ui->m_lpDirectorView->selectionModel(); // connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(directorSelectionChanged(QItemSelection,QItemSelection))); // selectionModel = ui->m_lpWriterView->selectionModel(); // connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(writerSelectionChanged(QItemSelection,QItemSelection))); } void cTVShowWidget::setLibrary(cKodiVideoLibrary* lpVideoLibrary, cImageList* lpImageList) { m_lpVideoLibrary = lpVideoLibrary; m_lpImageList = lpImageList; showList(); } void cTVShowWidget::showList() { m_lpTVShowModel->clear(); m_lpVideoLibrary->fillTVShowList(m_lpTVShowModel); ui->m_lpTVShowView->resizeColumnToContents(0); ui->m_lpTVShowView->selectionModel()->setCurrentIndex(m_lpTVShowModel->index(0, 0), QItemSelectionModel::Select | QItemSelectionModel::Current); m_lpCountryModel->clear(); m_lpVideoLibrary->fillCountriesList(m_lpCountryModel); m_lpGenreModel->clear(); m_lpVideoLibrary->fillGenresList(m_lpGenreModel); m_lpStudioModel->clear(); m_lpVideoLibrary->fillStudiosList(m_lpStudioModel); ui->m_lpSet->clear(); m_lpVideoLibrary->fillSetsList(ui->m_lpSet); }
[ "Herwig.Birke@windesign.at" ]
Herwig.Birke@windesign.at
1e3e0048195b0fb94c72293fe456484d23af0ebc
929ecaa278928c053faf9097c6a2d1ff41b5128b
/Box2D/Dynamics/Joints/b2MouseJoint.h
4266b3f3cf5b975a142663ee47ab5342cadee98a
[]
no_license
Patchnote-v2/Baker-Street-Heroes
fb178ed14d895436f4855323a173b7137bd37dc2
ebdd68c7864379bf69e07cf8b9afaacbaf8b7b4e
refs/heads/master
2021-11-24T12:32:26.136781
2017-11-04T03:29:04
2017-11-04T03:29:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,902
h
/* * Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_MOUSE_JOINT_H #define B2_MOUSE_JOINT_H #include "../Box2D/Dynamics/Joints/b2Joint.h" /// Mouse joint definition. This requires a world target point, /// tuning parameters, and the time step. struct b2MouseJointDef : public b2JointDef { b2MouseJointDef() { type = e_mouseJoint; target.Set(0.0f, 0.0f); maxForce = 0.0f; frequencyHz = 5.0f; dampingRatio = 0.7f; } /// The initial world target point. This is assumed /// to coincide with the body anchor initially. b2Vec2 target; /// The maximum constraint force that can be exerted /// to move the candidate body. Usually you will express /// as some multiple of the weight (multiplier * mass * gravity). float32 maxForce; /// The response speed. float32 frequencyHz; /// The damping ratio. 0 = no damping, 1 = critical damping. float32 dampingRatio; }; /// A mouse joint is used to make a point on a body track a /// specified world point. This a soft constraint with a maximum /// force. This allows the constraint to stretch and without /// applying huge forces. /// NOTE: this joint is not documented in the manual because it was /// developed to be used in the testbed. If you want to learn how to /// use the mouse joint, look at the testbed. class b2MouseJoint : public b2Joint { public: /// Implements b2Joint. b2Vec2 GetAnchorA() const override; /// Implements b2Joint. b2Vec2 GetAnchorB() const override; /// Implements b2Joint. b2Vec2 GetReactionForce(float32 inv_dt) const override; /// Implements b2Joint. float32 GetReactionTorque(float32 inv_dt) const override; /// Use this to update the target point. void SetTarget(const b2Vec2& target); const b2Vec2& GetTarget() const; /// Set/get the maximum force in Newtons. void SetMaxForce(float32 force); float32 GetMaxForce() const; /// Set/get the frequency in Hertz. void SetFrequency(float32 hz); float32 GetFrequency() const; /// Set/get the damping ratio (dimensionless). void SetDampingRatio(float32 ratio); float32 GetDampingRatio() const; /// The mouse joint does not support dumping. void Dump() override { b2Log("Mouse joint dumping is not supported.\n"); } /// Implement b2Joint::ShiftOrigin void ShiftOrigin(const b2Vec2& newOrigin) override; protected: friend class b2Joint; b2MouseJoint(const b2MouseJointDef* def); void InitVelocityConstraints(const b2SolverData& data) override; void SolveVelocityConstraints(const b2SolverData& data) override; bool SolvePositionConstraints(const b2SolverData& data) override; b2Vec2 m_localAnchorB; b2Vec2 m_targetA; float32 m_frequencyHz; float32 m_dampingRatio; float32 m_beta; // Solver shared b2Vec2 m_impulse; float32 m_maxForce; float32 m_gamma; // Solver temp int32 m_indexA; int32 m_indexB; b2Vec2 m_rB; b2Vec2 m_localCenterB; float32 m_invMassB; float32 m_invIB; b2Mat22 m_mass; b2Vec2 m_C; }; #endif
[ "horizonistic@gmail.com" ]
horizonistic@gmail.com
d294f08fcd1e858197b7e927bda6fb66848b68a6
90c260851952b7638e569a43ccd81d29a49dcad9
/logic_program/main.cpp
8681c4c02c3b8ee9c2a726bfdac8581a7c818947
[]
no_license
andreyf/cpp_tutorials
70def7304f0eb72423f00dcef5a8fe4d206b0818
654107eb38178877a25e3ae81c5ac169f56d52e2
refs/heads/master
2021-01-18T06:01:05.425561
2018-01-15T05:40:41
2018-01-15T05:40:41
68,437,967
2
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
#include <iostream> using namespace std; int main() { bool pravda = true, lozh = false; if(pravda && lozh) cout << "Правда && ложь" << endl;// строка не выводится if(pravda || lozh) cout << "Правда || ложь" << endl; if(!pravda) cout << "Отрицание (Правда)" << endl; // эта строка также не появится ... if(!lozh) cout << "Отрицание (ложь)" << endl; //... а эта появится return 0; }
[ "andreyfomin82@gmail.com" ]
andreyfomin82@gmail.com
ac5b28e06dbb69c92e8bbb9450954ee36756f366
0fffb5e463c1dea1b10f81bab28e0de8d1d9fde9
/Navier-Stokes_Solver_on_GPU/main.cpp
f7be3b00b9308e166e56fc760ef26aef0ecf3de5
[]
no_license
wojciechpawlak/Navier-Stokes_Solver_on_GPU
51ba36b0446495cd296d7a54e42dd0864cad078b
05325550e2d3967f4240b77c6215372b6d60d310
refs/heads/master
2020-06-04T23:38:27.700772
2012-12-08T22:56:42
2012-12-08T22:56:42
4,445,159
3
0
null
null
null
null
UTF-8
C++
false
false
70,616
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include <CL/cl.h> #include "alloc.h" #include "utils.h" #include "utils_opencl.h" #include "datadef.h" #include "init.h" #include "boundary.h" #include "uvp.h" #include "visual.h" #include "surface.h" // #define OPENCL_DEVICE 0 // Workgroup sizes #define BLOCK_SIZE_2D_X 16 #define BLOCK_SIZE_2D_Y 16 #define BLOCK_SIZE1D 256 // Problem options #define DCAV // used as benchmark problem (simplest) // Parts of simulations #define GPU #define CPU #define VERIFY //#define PRINT //#define LOG //#define VISUAL #define STATS // Parts of GPU execution #define ON_GPU_P0 #define ON_CPU_1_RELAX #define ON_CPU_1_RES #define ON_GPU_2_COPY #define ON_CPU_2_RELAX //#define ON_GPU_2_RES // commented - no residual computation // Time calculation #define TIME_WITH_MEM //#define TIME_WITHOUT_MEM // NVIDIA - normal vs. pinned //#define NORMAL #define PINNED #define NAIVE //#define SHARED // Name of source file with OpenCL kernels #ifdef NAIVE const char sourceFile[] = "kernels_naive.cl"; #endif #ifdef SHARED const char sourceFile[] = "kernels_shared.cl"; #endif const char buildOptions[] = "-cl-nv-verbose " // "-cl-nv-maxrregcount=256 " "-cl-single-precision-constant " "-cl-denorms-are-zero " "-cl-strict-aliasing " "-cl-mad-enable " "-cl-no-signed-zeros " "-cl-fast-relaxed-math " ; #ifdef NORMAL cl_mem_flags memoryRWFlags = CL_MEM_READ_WRITE; cl_mem_flags memoryRFlags = CL_MEM_READ_ONLY; cl_mem_flags memoryWFlags = CL_MEM_WRITE_ONLY; #endif #ifdef PINNED cl_mem_flags memoryRWFlags = CL_MEM_READ_WRITE|CL_MEM_ALLOC_HOST_PTR; cl_mem_flags memoryRFlags = CL_MEM_READ_ONLY|CL_MEM_ALLOC_HOST_PTR; cl_mem_flags memoryWFlags = CL_MEM_WRITE_ONLY|CL_MEM_ALLOC_HOST_PTR; #endif //#define SYNC cl_bool blocking_map = CL_FALSE; //#ifdef NAIVE //const char statsFile[] = "naive.csv"; //#endif // //#ifdef SHARED //const char statsFile[] = "shared.csv"; //#endif int main(int argc, char *argv[]) { #ifdef LOG FILE* log_file_cpu; log_file_cpu = fopen("logCPU.txt", "w"); FILE* log_file_gpu; log_file_gpu = fopen("logGPU.txt", "w"); #endif /* * Navier-Stokes Solver Initialization (both for CPU and GPU implementations) */ char problem[30]; char infile[30], outfile[30]; REAL xlength, ylength; int imax, jmax; REAL delx, dely; REAL t_end, delt, tau; REAL del_trace, del_inj, del_streak, del_vec; char vecfile[30], tracefile[30], streakfile[30]; int N; REAL pos1x, pos2x, pos1y, pos2y; int itermax; REAL eps, omg, gamma; int p_bound; REAL Re, Pr, beta, GX, GY, UI, VI, TI; int wW, wE, wN, wS; int itersor=0, write; REAL t; REAL res; REAL **U, **V, **P, **PSI, **ZETA, **RHS, **F, **G, **TEMP, **HEAT; int **FLAG; int ppc, ifull=0, isurf=0, ibound=0; struct particleline *Particlelines; int init_case, cycle; /* READ the parameters of the problem. */ /* Stop if problem type or inputfile are not defined */ /*----------------------------------------------------*/ if (READ_PARAMETER(argv[1],problem, &xlength, &ylength, &imax, &jmax, &delx, &dely, &t_end, &delt, &tau, &del_trace, &del_inj, &del_streak, &del_vec, vecfile,tracefile,streakfile, infile, outfile, &N, &pos1x, &pos1y, &pos2x, &pos2y, &itermax,&eps,&omg,&gamma,&p_bound, &Re, &Pr, &beta, &GX, &GY, &UI, &VI, &TI, &wW, &wE, &wN, &wS) != 0 ) { return(1); } imax = argc > 3 ? atoi(argv[3]) : imax; jmax = argc > 4 ? atoi(argv[4]) : jmax; int BLOCK_SIZE_2D_1 = argc > 5 ? atoi(argv[5]) : BLOCK_SIZE_2D_X; int BLOCK_SIZE_2D_2 = argc > 6 ? atoi(argv[6]) : BLOCK_SIZE_2D_Y; int BLOCK_SIZE_1D = BLOCK_SIZE_2D_1 * BLOCK_SIZE_2D_2; const char *statsFile = argc > 7 ? argv[7] : "naive.csv"; /* Allocate memory for the arrays */ /*--------------------------------*/ U = RMATRIX(0, imax+1, 0, jmax+1); V = RMATRIX(0, imax+1, 0, jmax+1); F = RMATRIX(0, imax+1, 0, jmax+1); G = RMATRIX(0, imax+1, 0, jmax+1); P = RMATRIX(0, imax+1, 0, jmax+1); TEMP = RMATRIX(0, imax+1, 0, jmax+1); PSI = RMATRIX(0, imax, 0, jmax); ZETA = RMATRIX(1, imax-1, 1, jmax-1); HEAT = RMATRIX(0, imax, 0, jmax); RHS = RMATRIX(0, imax+1, 0, jmax+1); FLAG = IMATRIX(0, imax+1, 0, jmax+1); ppc = 4; REAL rdx2, rdy2; rdx2 = 1./delx/delx; rdy2 = 1./dely/dely; /* Read initial values from file "infile" */ /*----------------------------------------*/ init_case = READ_bin(U, V, P, TEMP, FLAG, imax, jmax, infile); if (init_case > 0) { /* Error while reading "infile" */ return(1); } if (init_case < 0) { /* Set initial values if */ /* "infile" is not specified */ INIT_UVP(problem, U, V, P, TEMP, imax, jmax, UI, VI, TI); INIT_FLAG(problem, FLAG, imax, jmax, delx, dely, &ibound); } #ifdef VISUAL /* Initialize particles for streaklines or particle tracing */ /*----------------------------------------------------------*/ //if (strcmp(streakfile, "none") || strcmp(tracefile, "none")) { // Particlelines = SET_PARTICLES(N, pos1x, pos1y, pos2x, pos2y); //} /* Initialize particles for free boundary problems */ /*-------------------------------------------------*/ //if (!strcmp(problem, "drop") || !strcmp(problem, "dam")) { // Particlelines = INIT_PARTICLES(&N, imax, jmax, delx, dely, // ppc, problem, U, V); //} #endif /* Set initial values for boundary conditions */ /* and specific boundary conditions, depending on "problem" */ /*----------------------------------------------------------*/ SETBCOND(U, V, P, TEMP, FLAG, imax, jmax, wW, wE, wN, wS); SETSPECBCOND(problem, U, V, P, TEMP, imax, jmax, UI, VI); #ifdef GPU /* * OpenCL Initialization */ cl_int status; //----------------------------------------------------- // Discover and initialize the platforms //----------------------------------------------------- cl_uint numPlatforms = 0; cl_platform_id *platforms = NULL; // Retrieve the number of platforms status = clGetPlatformIDs(0, NULL, &numPlatforms); if (status != CL_SUCCESS) { printf("clGetPlatformIDs failed: %s\n", cluErrorString(status)); exit(-1); } // Make sure some platforms were found if (numPlatforms == 0) { printf("No platforms detected.\n"); exit(-1); } // Allocate enough space for each platform platforms = (cl_platform_id*) malloc(numPlatforms * sizeof(cl_platform_id)); if (platforms == NULL) { perror("malloc failed"); exit(-1); } // Fill in platforms status = clGetPlatformIDs(numPlatforms, platforms, NULL); if (status != CL_SUCCESS) { printf("clGetPlatformIDs failed: %s\n", cluErrorString(status)); exit(-1); } // Print basic information about each platform //printPlatforms(platforms, numPlatforms, status); // uncommment for platform information //----------------------------------------------------- // Discover and initialize the devices //----------------------------------------------------- cl_uint numDevices = 0; cl_device_id *devices = NULL; // Retrive the number of devices present status = clGetDeviceIDs(platforms[OPENCL_DEVICE], CL_DEVICE_TYPE_ALL, //TODO CL_DEVICE_TYPE_ALL for all types 0, NULL, &numDevices); if (status != CL_SUCCESS) { printf("clGetDeviceIDs failed: %s\n", cluErrorString(status)); exit(-1); } // Make sure some devices were found if (numDevices == 0) { printf("No devices detected.\n"); exit(-1); } // Allocate enough space for each device devices = (cl_device_id*)malloc(numDevices * sizeof(cl_device_id)); if(devices == NULL) { perror("malloc failed"); exit(-1); } // Fill in devices status = clGetDeviceIDs(platforms[OPENCL_DEVICE], CL_DEVICE_TYPE_ALL, // CL_DEVICE_TYPE_ALL numDevices, devices, NULL); if(status != CL_SUCCESS) { printf("clGetDeviceIDs failed: %s\n", cluErrorString(status)); exit(-1); } // Print basic information about each device // printDevices(devices, numDevices, status); // uncomment to get device information // getDeviceInfo(devices, numDevices); // uncomment for detailed device information //----------------------------------------------------- // Create a context //----------------------------------------------------- cl_context context = NULL; // Create a context and associate it with the devices context = clCreateContext(NULL, numDevices, devices, NULL, NULL, &status); if (status != CL_SUCCESS || context == NULL) { printf("clCreateContext failed: %s\n", cluErrorString(status)); exit(-1); } //----------------------------------------------------- // Create a command queue //----------------------------------------------------- cl_command_queue cmdQueue = NULL; // Create a command queue and associate it with the device to execute on cmdQueue = clCreateCommandQueue(context, devices[0], 0, &status); if (status != CL_SUCCESS || cmdQueue == NULL) { printf("clCreateCommandQueue failed: %s\n", cluErrorString(status)); exit(-1); } //----------------------------------------------------- // Create device buffers //----------------------------------------------------- // Check limitations of first available device char buf[100]; printf("Device selected:\n"); printf("Device %u: \n", 0); status = clGetDeviceInfo(devices[0], CL_DEVICE_VENDOR, sizeof(buf), buf, NULL); printf("\tDevice: %s\n", buf); status = clGetDeviceInfo(devices[0], CL_DEVICE_NAME, sizeof(buf), buf, NULL); printf("\tName: %s\n", buf); size_t buf2 = 0; status = clGetDeviceInfo(devices[0], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &buf2, NULL); printf("\tMax Work Group Size: %u threads\n\n", buf2); if (status != CL_SUCCESS) { printf("clGetDeviceInfo failed: %s\n", cluErrorString(status)); exit(-1); } int MAX_THREADS_PR_WORKGROUP = buf2; int THREADS_PR_WORKGROUP = argc > 2 ? nextPow2(atoi(argv[2])) : MAX_THREADS_PR_WORKGROUP; printf("Threads per work group = %d.\n\n", THREADS_PR_WORKGROUP); // Compute the number of workgroups for 1D and 2D worksizes int NUM_WORKGROUPS_2D = (getGlobalSize(BLOCK_SIZE_2D_1, imax) * getGlobalSize(BLOCK_SIZE_2D_2, jmax)) / (BLOCK_SIZE_2D_1*BLOCK_SIZE_2D_2); int NUM_WORKGROUPS_1D = (getGlobalSize(BLOCK_SIZE_2D_1, imax) * getGlobalSize(BLOCK_SIZE_2D_2, jmax)) / BLOCK_SIZE_1D; printf("Work groups allocated for 2D block size (%d, %d , 1) = %d\n", BLOCK_SIZE_2D_1, BLOCK_SIZE_2D_2, NUM_WORKGROUPS_2D); printf("Work groups allocated for 1D block size (%d, 1, 1) = %d\n\n", BLOCK_SIZE_1D, NUM_WORKGROUPS_1D); ////////////////////////////////////////////////////////////////////////// // Computer the number of elements in grids used const int elements = (imax+2) * (jmax+2); // size of grid + ghost cells on boundaries // Compute the size of the data size_t datasize = sizeof(REAL)*elements; size_t datasize_int = sizeof(int)*elements; size_t datasize_reduc = sizeof(REAL)*NUM_WORKGROUPS_1D; //----------------------------------------------------- // Allocate memory for host buffers for GPU execution //----------------------------------------------------- int *FLAG_h; REAL *U_h, *V_h, *TEMP_h, *TEMP_new_h, *F_h, *G_h, *RHS_h, *P_h, *p0_result_h; #ifdef ON_GPU_2_RES REAL *res_result_h; #endif #ifdef NORMAL FLAG_h = (int *) malloc(datasize_int); U_h = (REAL *) malloc(datasize); V_h = (REAL *) malloc(datasize); TEMP_h = (REAL *) malloc(datasize); F_h = (REAL *) malloc(datasize); G_h = (REAL *) malloc(datasize); RHS_h = (REAL *) malloc(datasize); P_h = (REAL *) malloc(datasize); p0_result_h = (REAL *) malloc(NUM_WORKGROUPS_1D*sizeof(REAL)); #ifdef ON_GPU_2_RES res_result_h = (REAL *) malloc(NUM_WORKGROUPS_1D*sizeof(REAL)); #endif //TODO initialize them separately // Copy initial contents for host buffers from original arrays copy_array_int_2d_to_1d(FLAG, FLAG_h, imax+2, jmax+2); copy_array_real_2d_to_1d(U, U_h, imax+2, jmax+2); copy_array_real_2d_to_1d(V, V_h, imax+2, jmax+2); copy_array_real_2d_to_1d(TEMP, TEMP_h, imax+2, jmax+2); copy_array_real_2d_to_1d(P, P_h, imax+2, jmax+2); #endif // does not need to copy values to F_h, G_h, RHS_h, because they are raw REAL **PSI_h, **ZETA_h, **HEAT_h; PSI_h = RMATRIX(0, imax, 0, jmax); ZETA_h = RMATRIX(1, imax-1, 1, jmax-1); HEAT_h = RMATRIX(0, imax, 0, jmax); copy_array_real(PSI, PSI_h, imax+1, jmax+1); copy_array_real(ZETA, ZETA_h, imax-1, jmax-1); copy_array_real(HEAT, HEAT_h, imax+1, jmax+1); ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------- // Allocate memory for data on device //----------------------------------------------------- // Input and Output arrays on the device cl_mem U_d; cl_mem V_d; cl_mem FLAG_d; cl_mem TEMP_d; cl_mem TEMP_new_d; cl_mem F_d; cl_mem G_d; cl_mem RHS_d; cl_mem P_d; cl_mem p0_result_d; #ifdef ON_GPU_2_RES cl_mem res_result_d; #endif #ifdef ON_GPU_2_RES_NAIVE cl_mem res_d; #endif // Create a buffer object (U_d) U_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || U_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (V_d) V_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || V_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (FLAG_d) FLAG_d = clCreateBuffer(context, memoryRFlags, datasize_int, NULL, &status); if (status != CL_SUCCESS || FLAG_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (TEMP_d) TEMP_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || TEMP_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (TEMP_new_d) TEMP_new_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || TEMP_new_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (F_d) F_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || F_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (G_d) G_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || G_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (RHS_d) RHS_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || RHS_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (P_d) P_d = clCreateBuffer(context, memoryRWFlags, datasize, NULL, &status); if (status != CL_SUCCESS || P_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object for vector of partial results // for initial pressure value computation p0_result_d = clCreateBuffer(context, memoryWFlags, datasize_reduc, NULL, &status); if (status != CL_SUCCESS || p0_result_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef ON_GPU_2_RES_NAIVE // Create a buffer object for scalar value for residual computation res_d = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(REAL), NULL, &status); if (status != CL_SUCCESS || res_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #endif #ifdef ON_GPU_2_RES // Create a buffer object for vector of partial results // for residual computation res_result_d = clCreateBuffer(context, CL_MEM_WRITE_ONLY, datasize_reduc, NULL, &status); if (status != CL_SUCCESS || res_result_d == NULL) { printf("clCreateBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #endif #ifdef PINNED // Map standard pointer to reference the pinned host memory // input and output buffers with standard pointers U_h = (REAL *)clEnqueueMapBuffer(cmdQueue, U_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || U_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } V_h = (REAL *)clEnqueueMapBuffer(cmdQueue, V_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || V_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } FLAG_h = (int *)clEnqueueMapBuffer(cmdQueue, FLAG_d, blocking_map, CL_MAP_READ, 0, datasize_int, 0, NULL, NULL, &status); if (status != CL_SUCCESS || FLAG_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } TEMP_h = (REAL *)clEnqueueMapBuffer(cmdQueue, TEMP_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || TEMP_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } TEMP_new_h = (REAL *)clEnqueueMapBuffer(cmdQueue, TEMP_new_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || TEMP_new_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } F_h = (REAL *)clEnqueueMapBuffer(cmdQueue, F_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || F_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (G_d) G_h = (REAL *)clEnqueueMapBuffer(cmdQueue, G_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || G_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (RHS_d) RHS_h = (REAL *)clEnqueueMapBuffer(cmdQueue, RHS_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || RHS_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object (P_d) P_h = (REAL *)clEnqueueMapBuffer(cmdQueue, P_d, blocking_map, CL_MAP_READ|CL_MAP_WRITE, 0, datasize, 0, NULL, NULL, &status); if (status != CL_SUCCESS || P_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Create a buffer object for vector of partial results // for initial pressure value computation p0_result_h = (REAL *)clEnqueueMapBuffer(cmdQueue, p0_result_d, blocking_map, CL_MAP_WRITE, 0, datasize_reduc, 0, NULL, NULL, &status); if (status != CL_SUCCESS || p0_result_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef ON_GPU_2_RES_NAIVE // Create a buffer object for scalar value for residual computation res_h = (REAL *)clEnqueueMapBuffer(cmdQueue, res_d, blocking_map, CL_MAP_WRITE, 0, sizeof(REAL), 0, NULL, NULL, &status); if (status != CL_SUCCESS || res_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #endif #ifdef ON_GPU_2_RES // Create a buffer object for vector of partial results // for residual computation res_result_h = (REAL *)clEnqueueMapBuffer(cmdQueue, res_result_d, blocking_map, CL_MAP_WRITE, 0, datasize_reduc, 0, NULL, NULL, &status); if (status != CL_SUCCESS || res_result_h == NULL) { printf("clEnqueueMapBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #endif copy_array_int_2d_to_1d(FLAG, FLAG_h, imax+2, jmax+2); copy_array_real_2d_to_1d(U, U_h, imax+2, jmax+2); copy_array_real_2d_to_1d(V, V_h, imax+2, jmax+2); copy_array_real_2d_to_1d(TEMP, TEMP_h, imax+2, jmax+2); copy_array_real_2d_to_1d(P, P_h, imax+2, jmax+2); #endif ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------- // Create and compile the program //----------------------------------------------------- cl_program program; char *programSource; // Read in the source code of the program programSource = READ_kernelSource(sourceFile); // Create a program program = clCreateProgramWithSource(context, 1, (const char**)&programSource, NULL, &status); if (status != CL_SUCCESS) { printf("clCreateProgramWithSource failed: %s\n", cluErrorString(status)); exit(-1); } // Build (compile & link) the program for the devices status = clBuildProgram(program, numDevices, devices, buildOptions, NULL, NULL); char *buildOptions; size_t buildOptionsSize; clGetProgramBuildInfo(program, devices[0], CL_PROGRAM_BUILD_OPTIONS, 0, NULL, &buildOptionsSize); buildOptions = (char*)malloc(buildOptionsSize); if (buildOptions == NULL) { perror("malloc"); exit(-1); } clGetProgramBuildInfo(program, devices[0], CL_PROGRAM_BUILD_OPTIONS, buildOptionsSize, buildOptions, NULL); buildOptions[buildOptionsSize-1] = '\0'; printf("Device %u Build Options:\n%s\n", 0, buildOptions); free(buildOptions); char *buildLog; size_t buildLogSize; clGetProgramBuildInfo(program, devices[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &buildLogSize); buildLog = (char*)malloc(buildLogSize); if (buildLog == NULL) { perror("malloc"); exit(-1); } clGetProgramBuildInfo(program, devices[0], CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, NULL); buildLog[buildLogSize-1] = '\0'; printf("Device %u Build Log:\n%s\n", 0, buildLog); free(buildLog); // Print build errors if any if (status != CL_SUCCESS) { printf("Program failed to build.\n"); cl_build_status buildStatus; for (unsigned int i = 0; i < numDevices; i++) { clGetProgramBuildInfo(program, devices[i], CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &buildStatus, NULL); if (buildStatus == CL_SUCCESS) { continue; } char *buildLog; size_t buildLogSize; clGetProgramBuildInfo(program, devices[i], CL_PROGRAM_BUILD_LOG, 0, NULL, &buildLogSize); buildLog = (char*)malloc(buildLogSize); if (buildLog == NULL) { perror("malloc"); exit(-1); } clGetProgramBuildInfo(program, devices[i], CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, NULL); buildLog[buildLogSize-1] = '\0'; printf("Device %u Build Log:\n%s\n", i, buildLog); free(buildLog); } exit(0); } else { printf("No kernel build errors\n\n"); } ////////////////////////////////////////////////////////////////////////// /* * GPU Execution */ // Create timers double timer_gpu; clock_t start_gpu, stop_gpu; //----------------------------------------------------- // Create the kernel //----------------------------------------------------- cl_kernel TEMP_kernel = NULL; cl_kernel FG_kernel = NULL; cl_kernel RHS_kernel = NULL; cl_kernel POISSON_p0_kernel = NULL; cl_kernel POISSON_1_relaxation_kernel = NULL; cl_kernel POISSON_1_comp_res_kernel = NULL; cl_kernel POISSON_2_copy_boundary_kernel = NULL; cl_kernel POISSON_2_relaxation_kernel = NULL; cl_kernel POISSON_2_comp_res_kernel = NULL; cl_kernel ADAP_UV_kernel = NULL; cl_kernel SETBCOND_outer_kernel = NULL; cl_kernel SETBCOND_inner_kernel = NULL; cl_kernel SETSPECBCOND_kernel = NULL; // Create a kernel for computation of temperature TEMP TEMP_kernel = clCreateKernel(program, "COMP_TEMP_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of velocity vectors F, G FG_kernel = clCreateKernel(program, "COMP_FG_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of right-hand side for pressure equation RHS RHS_kernel = clCreateKernel(program, "COMP_RHS_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of initial pressure values for pressure P POISSON_p0_kernel = clCreateKernel(program, "POISSON_p0_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for relaxation for pressure P (method 2) POISSON_1_relaxation_kernel = clCreateKernel(program, "POISSON_1_relaxation_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of norm of residual for pressure P (method 1) POISSON_1_comp_res_kernel = clCreateKernel(program, "POISSON_1_comp_res_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for copying values a boundary cells for pressure P (method 2) POISSON_2_copy_boundary_kernel = clCreateKernel(program, "POISSON_2_copy_boundary_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for relaxation for pressure P (method 2) POISSON_2_relaxation_kernel = clCreateKernel(program, "POISSON_2_relaxation_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of norm of residual for pressure P (method 2) POISSON_2_comp_res_kernel = clCreateKernel(program, "POISSON_2_comp_res_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of new velocity filed U, V ADAP_UV_kernel = clCreateKernel(program, "ADAP_UV_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of new velocity filed U, V SETBCOND_outer_kernel = clCreateKernel(program, "SETBCOND_outer_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of new velocity filed U, V SETBCOND_inner_kernel = clCreateKernel(program, "SETBCOND_inner_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } // Create a kernel for computation of new velocity filed U, V SETSPECBCOND_kernel = clCreateKernel(program, "SETSPECBCOND_kernel", &status); if (status != CL_SUCCESS) { printf("clCreateKernel failed: %s\n", cluErrorString(status)); exit(-1); } //----------------------------------------------------- // Configure the work-item structure //----------------------------------------------------- // Define an index space (global work size) of work items for execution. // A workgroup size (local work size) is not required, but can be used. size_t localWorkSize[] = {BLOCK_SIZE_2D_1, BLOCK_SIZE_2D_2}; size_t globalWorkSize[] = {getGlobalSize(BLOCK_SIZE_2D_1, imax), getGlobalSize(BLOCK_SIZE_2D_2, jmax)}; //size_t localWorkSize1d[] = {BLOCK_SIZE * BLOCK_SIZE}; size_t localWorkSize1d[] = {BLOCK_SIZE_1D}; size_t globalWorkSize1d[] = {getGlobalSize(BLOCK_SIZE_1D, imax) * getGlobalSize(BLOCK_SIZE_1D, jmax)}; printf("Local Work Size 2D: (%d, %d, 1)\n", localWorkSize[0], localWorkSize[1]); printf("Global Work Size 2D: (%d, %d, 1)\n", globalWorkSize[0], globalWorkSize[1]); printf("Local Work Size 1D: (%d, 1, 1)\n", localWorkSize1d[0]); printf("Global Work Size 1D: (%d, 1, 1)\n\n", globalWorkSize1d[0]); ////////////////////////////////////////////////////////////////////////// printf("GPU execution - start\n"); start_gpu = clock(); //----------------------------------------------------- // Write host data to device buffers //----------------------------------------------------- status = clEnqueueWriteBuffer(cmdQueue, FLAG_d, blocking_map, 0, datasize_int, FLAG_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, U_d, blocking_map, 0, datasize, U_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, V_d, blocking_map, 0, datasize, V_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, TEMP_d, blocking_map, 0, datasize, TEMP_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, TEMP_new_d, blocking_map, 0, datasize, TEMP_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, F_d, blocking_map, 0, datasize, F_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, G_d, blocking_map, 0, datasize, G_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, RHS_d, blocking_map, 0, datasize, RHS_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, P_d, blocking_map, 0, datasize, P_h, 0, NULL, NULL); status |= clEnqueueWriteBuffer(cmdQueue, p0_result_d, blocking_map, 0, datasize_reduc, p0_result_h, 0, NULL, NULL); #ifdef ON_GPU_2_RES status |= clEnqueueWriteBuffer(cmdQueue, res_result_d, blocking_map, 0, sizeof(REAL), res_result_h, 0, NULL, NULL); #endif #ifdef ON_GPU_2_RES_NAIVE status |= clEnqueueWriteBuffer(cmdQueue, res_result_d, blocking_map, 0, datasize_reduc,, res_result_h, 0, NULL, NULL); #endif if (status != CL_SUCCESS) { printf("clEnqueueWriteBuffer failed: %s\n", cluErrorString(status)); exit(-1); } ////////////////////////////////////////////////////////////////////////// /* * Main time loop */ for (t=0.0, cycle=0; t < t_end; t+=delt, cycle++) { COMP_delt_1d(&delt, t, imax, jmax, delx, dely, U_h, V_h, Re, Pr, tau, &write, del_trace, del_inj, del_streak, del_vec); #ifndef DCAV //TODO make it work for other problems than dcav /* Determine fluid cells for free boundary problems */ /* and set boundary values at free surface */ /*--------------------------------------------------*/ //if (!strcmp(problem, "drop") || !strcmp(problem, "dam") || // !strcmp(problem, "molding") || !strcmp(problem, "wave")) { // //TODO change FLAG // MARK_CELLS(FLAG, imax, jmax, delx, dely, &ifull, &isurf, // N, Particlelines); // //TODO change U,V,P // SET_UVP_SURFACE(U, V, P, FLAG, GX, GY, // imax, jmax, Re, delx, dely, delt); //} else { // ifull = imax*jmax-ibound; //} #else ifull = imax*jmax-ibound; #endif //--------------------------------------------------------------- // Set arguments for kernels and enqueue them for execution //--------------------------------------------------------------- cl_event event; /* Compute new temperature */ /*-------------------------*/ int padding = 1; int localWidth = localWorkSize[0] + 2*padding; int localHeight = localWorkSize[1] + 2*padding; // Associate the input and output buffers with the TEMP_kernel status = clSetKernelArg(TEMP_kernel, 0, sizeof(cl_mem), &U_d); status |= clSetKernelArg(TEMP_kernel, 1, sizeof(cl_mem), &V_d); status |= clSetKernelArg(TEMP_kernel, 2, sizeof(cl_mem), &TEMP_d); status |= clSetKernelArg(TEMP_kernel, 3, sizeof(cl_mem), &TEMP_new_d); status |= clSetKernelArg(TEMP_kernel, 4, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(TEMP_kernel, 5, sizeof(int), &imax); status |= clSetKernelArg(TEMP_kernel, 6, sizeof(int), &jmax); status |= clSetKernelArg(TEMP_kernel, 7, sizeof(REAL), &delt); status |= clSetKernelArg(TEMP_kernel, 8, sizeof(REAL), &delx); status |= clSetKernelArg(TEMP_kernel, 9, sizeof(REAL), &dely); status |= clSetKernelArg(TEMP_kernel, 10, sizeof(REAL), &gamma); status |= clSetKernelArg(TEMP_kernel, 11, sizeof(REAL), &Re); status |= clSetKernelArg(TEMP_kernel, 12, sizeof(REAL), &Pr); #ifdef SHARED status |= clSetKernelArg(TEMP_kernel, 13, sizeof(REAL)*localWorkSize[0]*localWorkSize[1], NULL); status |= clSetKernelArg(TEMP_kernel, 14, sizeof(int), &localWidth); status |= clSetKernelArg(TEMP_kernel, 15, sizeof(int), &localHeight); #endif if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the TEMP_kernel kernel status = clEnqueueNDRangeKernel(cmdQueue, TEMP_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } //clWaitForEvents(1, &event); // Old temperature array is not useful anymore #ifdef PINNED *TEMP_h = *TEMP_new_h; #endif /* Compute tentative velocity field (F, G) */ /*----------------------------------------*/ // Associate the input and output buffers with the FG_kernel status = clSetKernelArg(FG_kernel, 0, sizeof(cl_mem), &U_d); status |= clSetKernelArg(FG_kernel, 1, sizeof(cl_mem), &V_d); status |= clSetKernelArg(FG_kernel, 2, sizeof(cl_mem), &TEMP_d); status |= clSetKernelArg(FG_kernel, 3, sizeof(cl_mem), &F_d); status |= clSetKernelArg(FG_kernel, 4, sizeof(cl_mem), &G_d); status |= clSetKernelArg(FG_kernel, 5, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(FG_kernel, 6, sizeof(int), &imax); status |= clSetKernelArg(FG_kernel, 7, sizeof(int), &jmax); status |= clSetKernelArg(FG_kernel, 8, sizeof(REAL), &delt); status |= clSetKernelArg(FG_kernel, 9, sizeof(REAL), &delx); status |= clSetKernelArg(FG_kernel, 10, sizeof(REAL), &dely); status |= clSetKernelArg(FG_kernel, 11, sizeof(REAL), &GX); status |= clSetKernelArg(FG_kernel, 12, sizeof(REAL), &GY); status |= clSetKernelArg(FG_kernel, 13, sizeof(REAL), &gamma); status |= clSetKernelArg(FG_kernel, 14, sizeof(REAL), &Re); status |= clSetKernelArg(FG_kernel, 15, sizeof(REAL), &beta); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the FG_kernel status = clEnqueueNDRangeKernel(cmdQueue, FG_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif /* Compute right hand side for pressure equation */ /*-----------------------------------------------*/ // Associate the input and output buffers with the RHS_kernel status = clSetKernelArg(RHS_kernel, 0, sizeof(cl_mem), &F_d); status |= clSetKernelArg(RHS_kernel, 1, sizeof(cl_mem), &G_d); status |= clSetKernelArg(RHS_kernel, 2, sizeof(cl_mem), &RHS_d); status |= clSetKernelArg(RHS_kernel, 3, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(RHS_kernel, 4, sizeof(int), &imax); status |= clSetKernelArg(RHS_kernel, 5, sizeof(int), &jmax); status |= clSetKernelArg(RHS_kernel, 6, sizeof(REAL), &delt); status |= clSetKernelArg(RHS_kernel, 7, sizeof(REAL), &delx); status |= clSetKernelArg(RHS_kernel, 8, sizeof(REAL), &dely); #ifdef SHARED status |= clSetKernelArg(RHS_kernel, 9, sizeof(REAL)*localWorkSize[0]*localWorkSize[1], NULL); status |= clSetKernelArg(RHS_kernel, 10, sizeof(REAL)*localWorkSize[0]*localWorkSize[1], NULL); #endif if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the RHS_kernel kernel status = clEnqueueNDRangeKernel(cmdQueue, RHS_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif //TODO because of CPU versions of Relaxation and Comp Res kernels status = clEnqueueReadBuffer(cmdQueue, RHS_d, blocking_map, 0, datasize, RHS_h, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); exit(-1); } /* Solve the pressure equation by successive over relaxation */ /*-----------------------------------------------------------*/ int iter = 0; if (ifull > 0) { int iimax = imax + 2; int jjmax = jmax + 2; REAL p0 = 0.0; #ifdef ON_CPU_P0 for (int i = 1; i <= iimax-2; i++) { for (int j = 1; j <= jjmax-2; j++) { if (FLAG_h[i*jjmax + j] & C_F) { p0 += P_h[i*jjmax + j]*P_h[i*jjmax + j]; } } } #endif #ifdef ON_GPU_P0 // Associate the input and output buffers with the POISSON_p0_kernel status = clSetKernelArg(POISSON_p0_kernel, 0, sizeof(cl_mem), &P_d); status |= clSetKernelArg(POISSON_p0_kernel, 1, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(POISSON_p0_kernel, 2, sizeof(int), &imax); status |= clSetKernelArg(POISSON_p0_kernel, 3, sizeof(int), &jmax); status |= clSetKernelArg(POISSON_p0_kernel, 4, sizeof(cl_mem), &p0_result_d); status |= clSetKernelArg(POISSON_p0_kernel, 5, sizeof(REAL)*localWorkSize1d[0], NULL); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the POISSON_p0_kernel kernel status = clEnqueueNDRangeKernel(cmdQueue, POISSON_p0_kernel, 1, NULL, globalWorkSize1d, localWorkSize1d, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif // Read the partial results from reduction kernel status = clEnqueueReadBuffer(cmdQueue, p0_result_d, blocking_map, 0, NUM_WORKGROUPS_1D*sizeof(REAL), p0_result_h, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); exit(-1); } // Compute the initial pressure value p0 for (int group_id = 0; group_id < NUM_WORKGROUPS_1D; group_id++) { p0 += p0_result_h[group_id]; } #endif p0 = sqrt(p0/ifull); if (p0 < 0.0001) p0 = 1.0; REAL beta_2; beta_2 = -omg/(2.0*(rdx2+rdy2)); /* SOR-iteration */ /*---------------*/ for (iter = 1; iter <= itermax; iter++) { res = 0.0; if (p_bound == 1) { #ifdef ON_CPU_1_RELAX REAL beta_mod; for (int i = 1; i <= iimax-1; i++) { for (int j = 1; j <= jjmax-1; j++) { /* five point star for interior fluid cells */ if (FLAG_h[i*jmax + j] == 0x001f) { P_h[i*jmax + j] = (1.-omg)*P_h[i*jmax + j] - beta_2*((P_h[(i+1)*jmax + j]+P_h[(i-1)*jmax + j])*rdx2 + (P_h[i*jmax + j+1]+P_h[i*jmax + j-1])*rdy2 - RHS_h[i*jmax + j]); } /* modified star near boundary */ else if ((FLAG_h[i*jmax + j] & C_F) && (FLAG_h[i*jmax + j] < 0x0100)) { beta_mod = -omg/((eps_E+eps_W)*rdx2+(eps_N+eps_S)*rdy2); P_h[i*jmax + j] = (1.-omg)*P_h[i*jmax + j] - beta_mod*( (eps_E*P_h[(i+1)*jmax + j]+eps_W*P_h[(i-1)*jmax + j])*rdx2 + (eps_N*P_h[i*jmax + j+1]+eps_S*P_h[i*jmax + j-1])*rdy2 - RHS_h[i*jmax + j]); } } } #endif #ifdef ON_GPU_1_RELAX //TODO time dependencies /* relaxation for fluid cells */ /*----------------------------*/ // Associate the input and output buffers with the POISSON_1_relaxation_kernel //status = clSetKernelArg(POISSON_1_relaxation_kernel, 0, sizeof(cl_mem), &P_d); //status |= clSetKernelArg(POISSON_1_relaxation_kernel, 1, sizeof(cl_mem), &RHS_d); //status |= clSetKernelArg(POISSON_1_relaxation_kernel, 2, sizeof(cl_mem), &FLAG_d); //status |= clSetKernelArg(POISSON_1_relaxation_kernel, 3, sizeof(int), &imax); //status |= clSetKernelArg(POISSON_1_relaxation_kernel, 4, sizeof(int), &jmax); //status |= clSetKernelArg(POISSON_1_relaxation_kernel, 5, sizeof(REAL), &delx); //status |= clSetKernelArg(POISSON_1_relaxation_kernel, 6, sizeof(REAL), &dely); //status |= clSetKernelArg(POISSON_1_relaxation_kernel, 7, sizeof(REAL), &omg); //if (status != CL_SUCCESS) { // printf("clSetKernelArg failed: %s\n", cluErrorString(status)); // exit(-1); //} // //// Execute the POISSON_1_relaxation_kernel //status = clEnqueueNDRangeKernel(cmdQueue, POISSON_1_relaxation_kernel, 2, // NULL, globalWorkSize, localWorkSize, 0, NULL, &event); //if(status != CL_SUCCESS) { // printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); // exit(-1); //} ////clWaitForEvents(1, &event); #endif #ifdef ON_CPU_1_RES /* computation of residual */ /*-------------------------*/ //REAL add; //res = 0.0; //for (int i = 1; i <= iimax-2; i++) { // for (int j = 1; j <= jjmax-2; j++) { // /* only fluid cells */ // if ((FLAG_h[i*jjmax + j] & C_F) && (FLAG_h[i*jjmax + j] < 0x0100)) { // add = ( eps_E_h*(P_h[(i+1)*jjmax + j]-P_h[i*jjmax + j]) - // eps_W_h*(P_h[i*jjmax + j]-P_h[(i-1)*jjmax + j])) * rdx2 // + ( eps_N_h*(P_h[i*jjmax + j+1]-P_h[i*jjmax + j]) - // eps_S_h*(P_h[i*jjmax + j]-P_h[i*jjmax + j-1])) * rdy2 // - RHS_h[i*jjmax + j]; // res += add * add; // } // } //} //res = sqrt(res/ifull)/p0; ///* convergence? */ //if (res < eps) { // break; //} #endif #ifdef ON_GPU_1_RES //TODO because of dependencies above //status = clEnqueueWriteBuffer(cmdQueue, P_d, CL_FALSE, 0, // datasize, P_h, 0, NULL, NULL); //if (status != CL_SUCCESS) { // printf("clEnqueueWriteBuffer failed: %s\n", cluErrorString(status)); // exit(-1); //} //// Associate the input and output buffers with the POISSON_1_comp_res_kernel //status = clSetKernelArg(POISSON_1_comp_res_kernel, 0, sizeof(cl_mem), &P_d); //status |= clSetKernelArg(POISSON_1_comp_res_kernel, 1, sizeof(cl_mem), &RHS_d); //status |= clSetKernelArg(POISSON_1_comp_res_kernel, 2, sizeof(cl_mem), &FLAG_d); //status |= clSetKernelArg(POISSON_1_comp_res_kernel, 3, sizeof(int), &imax); //status |= clSetKernelArg(POISSON_1_comp_res_kernel, 4, sizeof(int), &jmax); //status |= clSetKernelArg(POISSON_1_comp_res_kernel, 5, sizeof(REAL), &delx); //status |= clSetKernelArg(POISSON_1_comp_res_kernel, 6, sizeof(REAL), &dely); //status |= clSetKernelArg(POISSON_1_comp_res_kernel, 7, sizeof(REAL), &res); //if (status != CL_SUCCESS) { // printf("clSetKernelArg failed: %s\n", cluErrorString(status)); // exit(-1); //} //// Execute the POISSON_1_comp_res_kernel //status = clEnqueueNDRangeKernel(cmdQueue, POISSON_1_comp_res_kernel, 2, // NULL, globalWorkSize, localWorkSize, 0, NULL, &event); //if(status != CL_SUCCESS) { // printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); // exit(-1); //} ////clWaitForEvents(1, &event); //res = sqrt(res/ifull)/p0; ///* convergence? */ //if (res < eps) { // break; //} #endif } else if (p_bound == 2) { #ifdef ON_CPU_2_COPY //TODO because of time dependencies above //status = clEnqueueReadBuffer(cmdQueue, P_d, CL_FALSE, 0, // datasize, P_h, 0, NULL, NULL); //if (status != CL_SUCCESS) { // printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); // exit(-1); //} /* copy values at external boundary */ /*----------------------------------*/ for (int i = 1; i <= iimax-2; i++) { P_h[i*jjmax] = P_h[i*jjmax + 1]; P_h[i*jjmax + (jjmax-1)] = P_h[i*jjmax + (jjmax-2)]; } for (int j = 1; j <= jjmax-2; j++) { P_h[j] = P_h[jjmax + j]; P_h[(iimax-1)*jjmax + j] = P_h[(iimax-2)*jjmax + j]; } /* and at interior boundary cells */ /*--------------------------------*/ for (int i = 1; i <= iimax-2; i++) { for (int j = 1; j <= jjmax-2; j++) { if (FLAG_h[i*jjmax + j] >= B_N && FLAG_h[i*jjmax + j] <= B_SO) { switch (FLAG_h[i*jjmax + j]) { case B_N: { P_h[i*jjmax + j] = P_h[i*jjmax + j+1]; break; } case B_O: { P_h[i*jjmax + j] = P_h[(i+1)*jjmax + j]; break; } case B_S: { P_h[i*jjmax + j] = P_h[i*jjmax + j-1]; break; } case B_W: { P_h[i*jjmax + j] = P_h[(i-1)*jjmax + j]; break; } case B_NO: { P_h[i*jjmax + j] = 0.5*(P_h[i*jjmax + j+1]+P_h[(i+1)*jjmax + j]); break; } case B_SO: { P_h[i*jjmax + j] = 0.5*(P_h[i*jjmax + j-1]+P_h[(i+1)*jjmax + j]); break; } case B_SW: { P_h[i*jjmax + j] = 0.5*(P_h[i*jjmax + j-1]+P_h[(i-1)*jjmax + j]); break; } case B_NW: { P_h[i*jjmax + j] = 0.5*(P_h[i*jjmax + j+1]+P_h[(i-1)*jjmax + j]); break; } default: break; } } } } status = clEnqueueWriteBuffer(cmdQueue, P_d, blocking_map, 0, datasize, P_h, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueWriteBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #endif #ifdef ON_GPU_2_COPY /* copy values at external and interior boundary cells */ /*------------------------------------------------------*/ // Associate the input and output buffers with the POISSON_p0_kernel status = clSetKernelArg(POISSON_2_copy_boundary_kernel, 0, sizeof(cl_mem), &P_d); status |= clSetKernelArg(POISSON_2_copy_boundary_kernel, 1, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(POISSON_2_copy_boundary_kernel, 2, sizeof(int), &imax); status |= clSetKernelArg(POISSON_2_copy_boundary_kernel, 3, sizeof(int), &jmax); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the POISSON_2_copy_boundary_kernel status = clEnqueueNDRangeKernel(cmdQueue, POISSON_2_copy_boundary_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif #endif #ifdef ON_CPU_2_RELAX status |= clEnqueueReadBuffer(cmdQueue, P_d, CL_TRUE, 0, datasize, P_h, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); exit(-1); } /* relaxation for fluid cells */ /*----------------------------*/ for (int i = 1; i <= iimax-2; i++) { for (int j = 1; j <= jjmax-2; j++) { if ((FLAG_h[i*jjmax + j] & C_F) && (FLAG_h[i*jjmax + j] < 0x0100)) { P_h[i*jjmax + j] = (1.-omg)*P_h[i*jjmax + j] - beta_2*((P_h[(i+1)*jjmax + j]+P_h[(i-1)*jjmax + j])*rdx2 + (P_h[i*jjmax + j+1]+P_h[i*jjmax + j-1])*rdy2 - RHS_h[i*jjmax + j]); } } } status = clEnqueueWriteBuffer(cmdQueue, P_d, blocking_map, 0, datasize, P_h, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueWriteBuffer failed: %s\n", cluErrorString(status)); exit(-1); } #endif #ifdef ON_GPU_2_RELAX // Associate the input and output buffers with the POISSON_2_relaxation_kernel status = clSetKernelArg(POISSON_2_relaxation_kernel, 0, sizeof(cl_mem), &P_d); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 1, sizeof(cl_mem), &RHS_d); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 2, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 3, sizeof(int), &imax); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 4, sizeof(int), &jmax); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 5, sizeof(REAL), &rdx2); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 6, sizeof(REAL), &rdy2); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 7, sizeof(REAL), &beta_2); status |= clSetKernelArg(POISSON_2_relaxation_kernel, 8, sizeof(REAL), &omg); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the POISSON_2_relaxation_kernel status = clEnqueueNDRangeKernel(cmdQueue, POISSON_2_relaxation_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif //status |= clEnqueueReadBuffer(cmdQueue, P_d, CL_FALSE, 0, // datasize, P_h, 0, NULL, NULL); //if (status != CL_SUCCESS) { // printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); // exit(-1); //} //print_1darray_to_file(P_h, imax+2, jmax+2, "P_h_after.txt"); #endif #ifdef ON_CPU_2_RES REAL add; res = 0.0; for (int i = 1; i <= iimax-2; i++) { for (int j = 1; j <= jjmax-2; j++) { if ((FLAG_h[i*jjmax + j] & C_F) && (FLAG_h[i*jjmax + j] < 0x0100)) { add = (P_h[(i+1)*jjmax + j]-2*P_h[i*jjmax + j]+P_h[(i-1)*jjmax + j])*rdx2 + (P_h[i*jjmax + j+1]-2*P_h[i*jjmax + j]+P_h[i*jjmax + j-1])*rdy2 - RHS_h[i*jjmax + j]; res += add * add; } } } res = sqrt(res/ifull)/p0; // convergence? if (res < eps) { break; } #endif #ifdef ON_GPU_2_RES_NAIVE // Associate the input and output buffers with the POISSON_2_comp_res_naive_kernel status = clSetKernelArg(POISSON_2_comp_res_kernel, 0, sizeof(cl_mem), &P_d); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 1, sizeof(cl_mem), &RHS_d); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 2, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 3, sizeof(int), &imax); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 4, sizeof(int), &jmax); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 5, sizeof(REAL), &rdx2); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 6, sizeof(REAL), &rdy2); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 7, sizeof(cl_mem), &res_d); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the POISSON_2_comp_res_kernel status = clEnqueueNDRangeKernel(cmdQueue, POISSON_2_comp_res_kernel, 1, NULL, globalWorkSize1d, localWorkSize1d, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif // Read the final result from reduction kernel status = clEnqueueReadBuffer(cmdQueue, res_d, blocking_map, 0, sizeof(REAL), &res, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); exit(-1); } res = sqrt(res/ifull)/p0; // convergence? if (res < eps) { break; } #endif #ifdef ON_GPU_2_RES /* computation of residual */ /*-------------------------*/ // Associate the input and output buffers with the POISSON_2_comp_res_kernel status = clSetKernelArg(POISSON_2_comp_res_kernel, 0, sizeof(cl_mem), &P_d); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 1, sizeof(cl_mem), &RHS_d); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 2, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 3, sizeof(int), &imax); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 4, sizeof(int), &jmax); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 5, sizeof(REAL), &rdx2); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 6, sizeof(REAL), &rdy2); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 7, sizeof(cl_mem), &res_result_d); status |= clSetKernelArg(POISSON_2_comp_res_kernel, 8, sizeof(REAL)*localWorkSize1d[0], NULL); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the POISSON_2_comp_res_kernel status = clEnqueueNDRangeKernel(cmdQueue, POISSON_2_comp_res_kernel, 1, NULL, globalWorkSize1d, localWorkSize1d, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif // Read the partial results from reduction kernel status = clEnqueueReadBuffer(cmdQueue, res_result_d, blocking_map, 0, NUM_WORKGROUPS_1D*sizeof(REAL), res_result_h, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); exit(-1); } res = 0.0; // Compute residual from partial results for (int group_id = 0; group_id < NUM_WORKGROUPS_1D; group_id++) { res += res_result_h[group_id]; } res = sqrt(res/ifull)/p0; // convergence? if (res < eps) { break; } #endif } } } // End of SOR iteration #ifdef PRINT printf("t_end= %1.5g, t= %1.3e, delt= %1.1e, iterations %3d, res: %e, F-cells: %d, S-cells: %d, B-cells: %d\n", t_end, t+delt, delt, iter, res, ifull, isurf, ibound); #endif /* Compute the new velocity field */ /*--------------------------------*/ // Associate the input and output buffers with the ADAP_UV_kernel status = clSetKernelArg(ADAP_UV_kernel, 0, sizeof(cl_mem), &U_d); status |= clSetKernelArg(ADAP_UV_kernel, 1, sizeof(cl_mem), &V_d); status |= clSetKernelArg(ADAP_UV_kernel, 2, sizeof(cl_mem), &F_d); status |= clSetKernelArg(ADAP_UV_kernel, 3, sizeof(cl_mem), &G_d); status |= clSetKernelArg(ADAP_UV_kernel, 4, sizeof(cl_mem), &P_d); status |= clSetKernelArg(ADAP_UV_kernel, 5, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(ADAP_UV_kernel, 6, sizeof(int), &imax); status |= clSetKernelArg(ADAP_UV_kernel, 7, sizeof(int), &jmax); status |= clSetKernelArg(ADAP_UV_kernel, 8, sizeof(REAL), &delt); status |= clSetKernelArg(ADAP_UV_kernel, 9, sizeof(REAL), &delx); status |= clSetKernelArg(ADAP_UV_kernel, 10, sizeof(REAL), &dely); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the ADAP_UV_kernel status = clEnqueueNDRangeKernel(cmdQueue, ADAP_UV_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif /* Set boundary conditions */ /*-------------------------*/ // Associate the input and output buffers with the SETBCOND_outer_kernel status = clSetKernelArg(SETBCOND_outer_kernel, 0, sizeof(cl_mem), &U_d); status |= clSetKernelArg(SETBCOND_outer_kernel, 1, sizeof(cl_mem), &V_d); status |= clSetKernelArg(SETBCOND_outer_kernel, 2, sizeof(cl_mem), &P_d); status |= clSetKernelArg(SETBCOND_outer_kernel, 3, sizeof(cl_mem), &TEMP_new_d); status |= clSetKernelArg(SETBCOND_outer_kernel, 4, sizeof(int), &imax); status |= clSetKernelArg(SETBCOND_outer_kernel, 5, sizeof(int), &jmax); status |= clSetKernelArg(SETBCOND_outer_kernel, 6, sizeof(int), &wW); status |= clSetKernelArg(SETBCOND_outer_kernel, 7, sizeof(int), &wE); status |= clSetKernelArg(SETBCOND_outer_kernel, 8, sizeof(int), &wN); status |= clSetKernelArg(SETBCOND_outer_kernel, 9, sizeof(int), &wS); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the SETBCOND_outer_kernel status = clEnqueueNDRangeKernel(cmdQueue, SETBCOND_outer_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif // Associate the input and output buffers with the SETBCOND_inner_kernel status = clSetKernelArg(SETBCOND_inner_kernel, 0, sizeof(cl_mem), &U_d); status |= clSetKernelArg(SETBCOND_inner_kernel, 1, sizeof(cl_mem), &V_d); status |= clSetKernelArg(SETBCOND_inner_kernel, 2, sizeof(cl_mem), &TEMP_d); status |= clSetKernelArg(SETBCOND_inner_kernel, 3, sizeof(cl_mem), &FLAG_d); status |= clSetKernelArg(SETBCOND_inner_kernel, 4, sizeof(int), &imax); status |= clSetKernelArg(SETBCOND_inner_kernel, 5, sizeof(int), &jmax); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the SETBCOND_inner_kernel status = clEnqueueNDRangeKernel(cmdQueue, SETBCOND_inner_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif /* Set special boundary conditions */ /* Overwrite preset default values */ /*---------------------------------*/ // Associate the input and output buffers with the SETSPECBCOND_kernel //status = clSetKernelArg(SETSPECBCOND_kernel, 0, sizeof(cl_mem), &problem); status |= clSetKernelArg(SETSPECBCOND_kernel, 0, sizeof(cl_mem), &U_d); status |= clSetKernelArg(SETSPECBCOND_kernel, 1, sizeof(cl_mem), &V_d); status |= clSetKernelArg(SETSPECBCOND_kernel, 2, sizeof(cl_mem), &P_d); status |= clSetKernelArg(SETSPECBCOND_kernel, 3, sizeof(cl_mem), &TEMP_d); status |= clSetKernelArg(SETSPECBCOND_kernel, 4, sizeof(int), &imax); status |= clSetKernelArg(SETSPECBCOND_kernel, 5, sizeof(int), &jmax); status |= clSetKernelArg(SETSPECBCOND_kernel, 6, sizeof(REAL), &UI); status |= clSetKernelArg(SETSPECBCOND_kernel, 7, sizeof(REAL), &VI); if (status != CL_SUCCESS) { printf("clSetKernelArg failed: %s\n", cluErrorString(status)); exit(-1); } // Execute the SETSPECBCOND_kernel status = clEnqueueNDRangeKernel(cmdQueue, SETSPECBCOND_kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &event); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed: %s\n", cluErrorString(status)); exit(-1); } #ifdef SYNC clWaitForEvents(1, &event); #endif #ifndef DCAV //TODO other problems than dcav //if (!strcmp(problem, "drop") || !strcmp(problem, "dam") || // !strcmp(problem, "molding") || !strcmp(problem, "wave")) { // SET_UVP_SURFACE(U_h, V_h, P_h, FLAG_h, GX, GY, imax, jmax, Re, delx, dely, delt); //} #endif #ifdef VISUAL //TODO Data Visualisation /* Write data for visualization */ /*------------------------------*/ //if ((write & 8) && strcmp(vecfile, "none")) { // COMPPSIZETA(U_h, V_h, PSI_h, ZETA_h, FLAG_h, imax, jmax, delx, dely); // COMP_HEAT(U_h, V_h, TEMP_h, HEAT_h, FLAG_h, Re, Pr, imax, jmax, delx, dely); // OUTPUTVEC_txt(U_h, V_h, P_h, TEMP_h, PSI_h, ZETA_h, HEAT_h, FLAG_h, xlength, ylength, // imax, jmax, vecfile); //} //if ((write & 8) && strcmp(outfile, "none")) { // WRITE_txt(U_h, V_h, P_h, TEMP_h, FLAG_h, imax, jmax, outfile); //} //if (strcmp(tracefile, "none")) { // PARTICLE_TRACING(tracefile, t, imax, jmax, delx, dely, delt, // U_h, V_h, FLAG_h, N, Particlelines, write); //} //if (strcmp(streakfile, "none")) { // STREAKLINES(streakfile, write, imax, jmax, delx, dely, delt, t, // U_h, V_h, FLAG_h, N, Particlelines); //} #endif } /* * End of main time loop */ ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------- // Read the output buffers back to the host //----------------------------------------------------- // Read the OpenCL output buffer (U_d) to the host output array (U_h) status = clEnqueueReadBuffer(cmdQueue, U_d, CL_TRUE, 0, datasize, U_h, 0, NULL, NULL); // Read the OpenCL output buffer (V_d) to the host output array (V_h) status |= clEnqueueReadBuffer(cmdQueue, V_d, CL_TRUE, 0, datasize, V_h, 0, NULL, NULL); // Read the OpenCL output buffer (TEMP_new_d) to the host output array (TEMP_h) status |= clEnqueueReadBuffer(cmdQueue, TEMP_new_d, CL_TRUE, 0, datasize, TEMP_h, 0, NULL, NULL); // Read the OpenCL output buffer (F_d) to the host output array (F_h) status |= clEnqueueReadBuffer(cmdQueue, F_d, CL_TRUE, 0, datasize, F_h, 0, NULL, NULL); // Read the OpenCL output buffer (G_d) to the host output array (G_h) status |= clEnqueueReadBuffer(cmdQueue, G_d, CL_TRUE, 0, datasize, G_h, 0, NULL, NULL); // Read the OpenCL output buffer (RHS_d) to the host output array (RHS_h) status |= clEnqueueReadBuffer(cmdQueue, RHS_d, CL_TRUE, 0, datasize, RHS_h, 0, NULL, NULL); // Read the OpenCL output buffer (P_d) to the host output array (P_h) status |= clEnqueueReadBuffer(cmdQueue, P_d, CL_TRUE, 0, datasize, P_h, 0, NULL, NULL); if (status != CL_SUCCESS) { printf("clEnqueueReadBuffer failed: %s\n", cluErrorString(status)); exit(-1); } stop_gpu = clock(); printf("GPU execution - finish\n\n"); timer_gpu = (double) (stop_gpu - start_gpu) / CLOCKS_PER_SEC; ////////////////////////////////////////////////////////////////////////// #ifdef VISUAL //TODO input for GPU //if (strcmp(vecfile,"none")) //{ // COMPPSIZETA(U, V, PSI, ZETA, FLAG, imax, jmax, delx, dely); // COMP_HEAT(U, V, TEMP, HEAT, FLAG, Re, Pr, imax, jmax, delx, dely); // OUTPUTVEC_txt(U, V, P, TEMP, PSI, ZETA, HEAT, FLAG, xlength, ylength, // imax, jmax, vecfile); //} //if (strcmp(outfile,"none")) { // WRITE_txt(U, V, P, TEMP, FLAG, imax, jmax, outfile); //} #endif #ifdef PRINT print_1darray_to_file(U_h, imax+2, jmax+2, "U_h.txt"); print_1darray_to_file(V_h, imax+2, jmax+2, "V_h.txt"); print_1darray_to_file(TEMP_h, imax+2, jmax+2, "TEMP_h.txt"); print_1darray_to_file(F_h, imax+2, jmax+2, "F_h.txt"); print_1darray_to_file(G_h, imax+2, jmax+2, "G_h.txt"); print_1darray_to_file(RHS_h, imax+2, jmax+2, "RHS_h.txt"); print_1darray_to_file(P_h, imax+2, jmax+2, "P_h.txt"); //print_1darray_to_file(PSI_h, imax+1, jmax+1, "PSI_h.txt"); //print_1darray_to_file(ZETA_h, imax, jmax, "ZETA_h.txt"); //print_1darray_to_file(HEAT_h, imax+1, jmax+1, "HEAT_h.txt"); print_1darray_int_to_file(FLAG_h, imax+2, jmax+2, "FLAG_h.txt"); #endif #endif ////////////////////////////////////////////////////////////////////////// #ifdef CPU /* * CPU Execution */ // Create timers double timer_cpu; clock_t start_cpu, stop_cpu; printf("CPU execution - start\n"); start_cpu = clock(); res = 0.0; /* * Main time loop */ for (t=0.0, cycle=0; t < t_end; t+=delt, cycle++) { COMP_delt(&delt, t, imax, jmax, delx, dely, U, V, Re, Pr, tau, &write, del_trace, del_inj, del_streak, del_vec); //TODO other problems than dcav /* Determine fluid cells for free boundary problems */ /* and set boundary values at free surface */ /*--------------------------------------------------*/ //if (!strcmp(problem, "drop") || !strcmp(problem, "dam") || // !strcmp(problem, "molding") || !strcmp(problem, "wave")) { // MARK_CELLS(FLAG, imax, jmax, delx, dely, &ifull, &isurf, // N, Particlelines); // SET_UVP_SURFACE(U, V, P, FLAG, GX, GY, // imax, jmax, Re, delx, dely, delt); //} else { ifull = imax*jmax-ibound; //} /* Compute new temperature */ /*-------------------------*/ COMP_TEMP(U, V, TEMP, FLAG, imax, jmax, delt, delx, dely, gamma, Re, Pr); /* Compute tentative velocity field (F, G) */ /*----------------------------------------*/ COMP_FG(U, V, TEMP, F, G, FLAG, imax, jmax, delt, delx, dely, GX, GY, gamma, Re, beta); /* Compute right hand side for pressure equation */ /*-----------------------------------------------*/ COMP_RHS(F, G, RHS, FLAG, imax, jmax, delt, delx, dely); /* Solve the pressure equation by successive over relaxation */ /*-----------------------------------------------------------*/ if (ifull > 0) { itersor = POISSON(P, RHS, FLAG, imax, jmax, delx, dely, eps, itermax, omg, &res, ifull, p_bound); } #ifdef PRINT printf("t_end= %1.5g, t= %1.3e, delt= %1.1e, iterations %3d, res: %e, F-cells: %d, S-cells: %d, B-cells: %d\n", t_end, t+delt, delt, itersor, res, ifull, isurf, ibound); #endif /* Compute the new velocity field */ /*--------------------------------*/ ADAP_UV(U, V, F, G, P, FLAG, imax, jmax, delt, delx, dely); /* Set boundary conditions */ /*-------------------------*/ SETBCOND(U, V, P, TEMP, FLAG, imax, jmax, wW, wE, wN, wS); /* Set special boundary conditions */ /* Overwrite preset default values */ /*---------------------------------*/ SETSPECBCOND(problem, U, V, P, TEMP, imax, jmax, UI, VI); //TODO other problems than dcav // if (!strcmp(problem, "drop") || !strcmp(problem, "dam") || // !strcmp(problem, "molding") || !strcmp(problem, "wave")) { // SET_UVP_SURFACE(U, V, P, FLAG, GX, GY, imax, jmax, Re, delx, dely, delt); // } #ifdef VISUAL //TODO Data Visualisation // /* Write data for visualization */ // /*------------------------------*/ // if ((write & 8) && strcmp(vecfile, "none")) { // COMPPSIZETA(U, V, PSI, ZETA, FLAG, imax, jmax, delx, dely); // COMP_HEAT(U, V, TEMP, HEAT, FLAG, Re, Pr, imax, jmax, delx, dely); // OUTPUTVEC_txt(U, V, P, TEMP, PSI, ZETA, HEAT, FLAG, xlength, ylength, // imax, jmax, vecfile); // } // if ((write & 8) && strcmp(outfile, "none")) { // WRITE_txt(U, V, P, TEMP, FLAG, imax, jmax, outfile); // } // if (strcmp(tracefile, "none")) { // PARTICLE_TRACING(tracefile, t, imax, jmax, delx, dely, delt, // U, V, FLAG, N, Particlelines, write); // } // if (strcmp(streakfile, "none")) { // STREAKLINES(streakfile, write, imax, jmax, delx, dely, delt, t, // U, V, FLAG, N, Particlelines); // } #endif } /* * End of main time loop */ stop_cpu = clock(); printf("CPU execution - finish\n\n"); timer_cpu = (double) (stop_cpu - start_cpu) / CLOCKS_PER_SEC; ////////////////////////////////////////////////////////////////////////// #ifdef VISUAL //if (strcmp(vecfile, "none")) //{ // COMPPSIZETA(U, V, PSI, ZETA, FLAG, imax, jmax, delx, dely); // COMP_HEAT(U, V, TEMP, HEAT, FLAG, Re, Pr, imax, jmax, delx, dely); // OUTPUTVEC_txt(U, V, P, TEMP, PSI, ZETA, HEAT, FLAG, xlength, ylength, // imax, jmax, vecfile); //} //if (strcmp(outfile, "none")) { // WRITE_txt(U, V, P, TEMP, FLAG, imax, jmax, outfile); //} #endif #ifdef PRINT print_array_to_file(U, imax+2, jmax+2, "U.txt"); print_array_to_file(V, imax+2, jmax+2, "V.txt"); print_array_to_file(TEMP, imax+2, jmax+2, "TEMP.txt"); print_array_to_file(F, imax+2, jmax+2, "F.txt"); print_array_to_file(G, imax+2, jmax+2, "G.txt"); print_array_to_file(RHS, imax+2, jmax+2, "RHS.txt"); print_array_to_file(P, imax+2, jmax+2, "P.txt"); //print_array_to_file(PSI, imax+1, jmax+1, "PSI.txt"); //print_array_to_file(ZETA, imax, jmax, "ZETA.txt"); //print_array_to_file(HEAT, imax+1, jmax+1, "HEAT.txt"); print_array_int_to_file(FLAG, imax+2, jmax+2, "FLAG.txt"); #endif #endif /*--------------------------------------------------------------------------------*/ #ifdef VERIFY /* * Verification */ printf("U: "); if (compare_array(U, U_h, imax+2, jmax+2)) { printf("PASSED\n"); } else { printf("FAILED\n"); } printf("V: "); if (compare_array(V, V_h, imax+2, jmax+2)) { printf("PASSED\n"); } else { printf("FAILED\n"); } printf("TEMP: "); if (compare_array(TEMP, TEMP_h, imax+2, jmax+2)) { printf("PASSED\n"); } else { printf("FAILED\n"); } printf("F: "); if (compare_array(F, F_h, imax+2, jmax+2)) { printf("PASSED\n"); } else { printf("FAILED\n"); } printf("G: "); if (compare_array(G, G_h, imax+2, jmax+2)) { printf("PASSED\n"); } else { printf("FAILED\n"); } printf("RHS: "); if (compare_array(RHS, RHS_h, imax+2, jmax+2)) { printf("PASSED\n"); } else { printf("FAILED\n"); } printf("P: "); if (compare_array(P, P_h, imax+2, jmax+2)) { printf("PASSED\n"); } else { printf("FAILED\n"); } // Print timings REAL speedup = timer_cpu/timer_gpu; printf("\n"); printf(" GPU time : %.4f seconds\n", timer_gpu); printf(" CPU time : %.4f seconds\n", timer_cpu); printf(" Speedup %.2fx\n\n", speedup); #endif ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------- // Save execution statistics //----------------------------------------------------- #ifdef STATS FILE *fp; fp=fopen(statsFile, "a"); fprintf(fp, "%d,%d,%d,%d,%d,%d,", globalWorkSize[0], globalWorkSize[1], localWorkSize[0], localWorkSize[1], cycle, itermax); fprintf(fp, "%.4f,%.4f,%.4f,", t_end, timer_cpu, timer_gpu); fprintf(fp, "%.2f\n", speedup); fclose(fp); #endif ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------- // Release resources //----------------------------------------------------- #ifdef GPU // Free OpenCL resources clReleaseMemObject(FLAG_d); clReleaseMemObject(U_d); clReleaseMemObject(V_d); clReleaseMemObject(TEMP_d); clReleaseMemObject(TEMP_new_d); clReleaseMemObject(F_d); clReleaseMemObject(G_d); clReleaseMemObject(P_d); clReleaseMemObject(p0_result_d); #ifdef ON_GPU_2_RES clReleaseMemObject(res_result_d); #endif #ifdef ON_GPU_2_RES_NAIVE clReleaseMemObject(res_d); #endif clReleaseKernel(FG_kernel); clReleaseKernel(TEMP_kernel); clReleaseProgram(program); clReleaseCommandQueue(cmdQueue); clReleaseContext(context); // Free host resources #ifdef NORMAL free(FLAG_h); free(U_h); free(V_h); free(TEMP_h); free(F_h); free(G_h); free(RHS_h); free(P_h); free(p0_result_h); #ifdef ON_GPU_2_RES free(res_result_h); #endif #endif FREE_RMATRIX(PSI_h, 0, imax, 0, jmax); FREE_RMATRIX(ZETA_h, 1, imax-1, 1, jmax-1); FREE_RMATRIX(HEAT_h, 0, imax, 0, jmax); free(platforms); free(devices); #endif FREE_RMATRIX(U, 0, imax+1, 0, jmax+1); FREE_RMATRIX(V, 0, imax+1, 0, jmax+1); FREE_RMATRIX(F, 0, imax+1, 0, jmax+1); FREE_RMATRIX(G, 0, imax+1, 0, jmax+1); FREE_RMATRIX(P, 0, imax+1, 0, jmax+1); FREE_RMATRIX(TEMP, 0, imax+1, 0, jmax+1); FREE_RMATRIX(PSI, 0, imax, 0, jmax); FREE_RMATRIX(ZETA, 1, imax-1, 1, jmax-1); FREE_RMATRIX(HEAT, 0, imax, 0, jmax); FREE_RMATRIX(RHS, 0, imax+1, 0, jmax+1); FREE_IMATRIX(FLAG, 0, imax+1, 0, jmax+1); #ifdef LOG fclose(log_file_cpu); fclose(log_file_gpu); #endif printf("End of program\n"); return(0); }
[ "wojciechpawlak@gmail.com" ]
wojciechpawlak@gmail.com
fd5ec5dc31fd873928bb499c7ef58b84aa9b5305
3c84dfff979b964d20819131e0b4a72dbb794f3d
/uni/honours/plabx/include/api/UiInputHandler.h
1ac54bb20369e08fc6844b88c9bcddbeefdf6892
[]
no_license
pserwylo/archived
47fed785c9353c57c7932d1d6b4d3687af701d3c
55f65374fd8005dae54dddd5049d344bea00aead
refs/heads/master
2023-06-22T08:32:52.037257
2023-06-08T06:24:00
2023-06-08T06:24:00
9,230,462
0
0
null
null
null
null
UTF-8
C++
false
false
867
h
/* * UiInputHandler.h * * Created on: 11/05/2009 * Author: pete */ #ifndef UIINPUTHANDLER_H_ #define UIINPUTHANDLER_H_ #include <osg/Vec3> #include <osg/Array> #include <sigc++/sigc++.h> class UiApplication; class UiOutput; class UiInputHandler { public: UiInputHandler(); virtual ~UiInputHandler(); /* * The following functions return pointers to the signals required for you * to connect to in order to receive high level input events. * They live from * Usage: * inputHandler->pointSelectedSignal()->connect(sigc::mem_func(object, &Class::function)); */ sigc::signal<void, osg::Vec3>* getPointSelectedSignal(); sigc::signal<void, osg::Vec3Array*>* getPolygonDrawnSignal(); protected: sigc::signal<void, osg::Vec3> pointSelectedSignal; sigc::signal<void, osg::Vec3Array*> polygonDrawnSignal; }; #endif /* UIINPUTHANDLER_H_ */
[ "peter@ivt.com.au" ]
peter@ivt.com.au
9ecf71be94ef22cf809145de9580290636bf3034
35b16f16d0e8f9ae9e51798159cfd5aa1d33d54a
/include/ft/base/market_data.h
cbf63a690710e6850a3dfa298001eb2f760e1cea
[ "MIT" ]
permissive
QuanterStudio/ft
050a7e02aa4477f4bc125147cf370d2118f1e19b
14aaafe26eb9752c8dc83ef8c9daf50b13ed9617
refs/heads/master
2023-04-23T18:36:32.092729
2021-05-12T12:35:50
2021-05-12T12:35:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,322
h
// Copyright [2020-2021] <Copyright Kevin, kevin.lau.gd@gmail.com> #ifndef FT_INCLUDE_FT_BASE_MARKET_DATA_H_ #define FT_INCLUDE_FT_BASE_MARKET_DATA_H_ #include <cstdint> #include "ft/component/pubsub/serializable.h" #include "ft/utils/datetime.h" namespace ft { constexpr int kMaxMarketLevel = 10; enum class MarketDataSource : uint8_t { kCTP = 1, kXTP = 2, }; struct TickData : public pubsub::Serializable<TickData> { MarketDataSource source; datetime::Datetime datetime; uint32_t ticker_id; double last_price = 0; double open_price = 0; double highest_price = 0; double lowest_price = 0; double pre_close_price = 0; double upper_limit_price = 0; double lower_limit_price = 0; uint64_t volume = 0; uint64_t turnover = 0; uint64_t open_interest = 0; double ask[kMaxMarketLevel]{0}; double bid[kMaxMarketLevel]{0}; int ask_volume[kMaxMarketLevel]{0}; int bid_volume[kMaxMarketLevel]{0}; struct { double iopv; } etf; SERIALIZABLE_FIELDS(source, datetime, ticker_id, last_price, open_price, highest_price, lowest_price, pre_close_price, upper_limit_price, lower_limit_price, volume, turnover, open_interest, ask, bid, ask_volume, bid_volume, etf.iopv); }; } // namespace ft #endif // FT_INCLUDE_FT_BASE_MARKET_DATA_H_
[ "kevin.lau.gd@gmail.com" ]
kevin.lau.gd@gmail.com
969db73d4c4c7e8c3951463e73d9041a043abd0a
3790aefc92f31c1abbe5594d4ea020e15cb12aae
/tizen-sdk/platforms/tizen2.1/rootstraps/tizen-emulator-2.1.native/usr/include/osp/FWebJsonJsonString.h
7c9bf2ab29123f6626f8e09dc94cfaac066fbe78
[]
no_license
abhijitrd/CppSharpTizen
e9871793c27acbb8ae0f599f2013ea56c7b2fca4
92e42a36cc3c5f2b1636061e82025feec4edda0d
refs/heads/master
2021-01-16T22:04:57.789905
2014-07-05T11:39:32
2014-07-05T11:39:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,132
h
// // Open Service Platform // Copyright (c) 2012 Samsung Electronics 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. // /** * @file FWebJsonJsonString.h * @brief This is the header file for the %JsonString class. * * This header file contains the declarations of the %JsonString class. * This class represents the JSON value of type string. */ #ifndef _FWEB_JSON_JSON_STRING_H_ #define _FWEB_JSON_JSON_STRING_H_ #include <FBaseString.h> #include <FWebJsonIJsonValue.h> namespace Tizen { namespace Web { namespace Json { class _JsonStringImpl; }}} // Tizen::Web::Json namespace Tizen { namespace Web { namespace Json { /** * @class JsonString * @brief This class represents the JSON value of type string. * * @since 2.0 * * @final This class is not intended for extension. * * The %JsonString class represents the JSON value of type string. * * For more information on the class features, see <a href="../org.tizen.native.appprogramming/html/guide/web/json_namespace.htm">JSON Guide</a>. * */ class _OSP_EXPORT_ JsonString : public IJsonValue , public Tizen::Base::String { public: /** * Initializes this instance of %JsonString with the specified parameter. * * @since 2.0 * * @param[in] pValue A pointer to an array of UTF-8 characters */ JsonString(const char* pValue); /** * Initializes this instance of %JsonString with the specified parameter. * * @since 2.0 * * @param[in] value A reference to Tizen::Base::String */ JsonString(const Tizen::Base::String& value); /** * Initializes this instance of %JsonString with the specified Unicode string. * * @since 2.0 * * @param[in] pValue A pointer to an array of Unicode characters */ JsonString(const wchar_t* pValue); /** * Copying of objects using this copy constructor is allowed. * * @since 2.0 * * @param[in] rhs An instance of %JsonString */ JsonString(const Tizen::Web::Json::JsonString& rhs); /** * This destructor overrides Tizen::Base::Object::~Object(). * * @since 2.0 */ virtual ~JsonString(void); /** * Gets the type of the JSON string. * * @since 2.0 * * @return The type of the JSON string */ JsonType GetType(void) const; /** * Copying of objects using this copy assignment operator is allowed. * * @since 2.0 * * @param[in] rhs A reference to the %JsonString instance to copy */ JsonString& operator =(const Tizen::Web::Json::JsonString& rhs); private: _JsonStringImpl* __pJsonStringImpl; friend class _JsonStringImpl; }; // JsonString }}} // Tizen::Web::Json #endif // _FWEB_JSON_JSON_STRING_H_
[ "brighttwinsoftware@gmail.com" ]
brighttwinsoftware@gmail.com
fe89977d1c5cc5dcdb8eb45687dddc6d9aa0ae66
aa979a30ce6d384989d6d40ce4a2ba2536b41a3f
/csl100/2013CS50302_assign4/q1_num.cpp
5f00647c90016af325be243b10e573f4761b8641
[ "Apache-2.0" ]
permissive
y-gupta/learn-with-me
0ed99df8e122a6f01608083266bb63fa314bd12f
2be141b118256750cbbb974099da6b423ff4ca8a
refs/heads/master
2021-05-28T13:49:55.603693
2014-11-17T19:07:16
2014-11-17T19:07:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
561
cpp
/* * @author Yash Gupta (cs5130302) * @desc lab4-Q2 determining type of number */ #include <iostream> using namespace std; int isprime(long n){//checks if a number is prime if(n==1) return 0; for(int i=2;i<=n/2;i++) { if(n%i==0) return 0; } return 1; } int main() { long n; cout<<"Enter the number:"; cin>>n; cout<<n<<" is "; if(n%2==0){//if n is divisible by 2 cout<<"even"; if(n==2)//2 is the only prime and even! cout<<" and prime"; }else{ cout<<"odd"; if(isprime(n)){ cout<<" and prime"; } } cout<<endl; return 0; }
[ "yashg2@gmail.com" ]
yashg2@gmail.com
8a12cb600ace338324c28775ea9479c41b6e6b2c
53f3f38eac3ed44f23f8f58d34aa8bd89555eaef
/src/msvc/include/AutoGemmKernelSources/zgemm_Col_NT_B1_ML048_NX048_KX01_src.cpp
4fa92f33550de4f105f61b17a0b7177e53aea569
[ "Apache-2.0" ]
permissive
gajgeospatial/clBLAS-1.10
16039ddfad67b6c26a00767f33911e7c6fe374dc
2f5f1347e814e23b93262cd6fa92ec1d228963ac
refs/heads/master
2022-06-27T09:08:34.399452
2020-05-12T16:50:46
2020-05-12T16:50:46
263,172,549
0
0
null
null
null
null
UTF-8
C++
false
false
8,524
cpp
/******************************************************************************* * This file was auto-generated using the AutoGemm.py python script. * DO NOT modify this file! Instead, make changes to scripts in * clBLAS/src/library/blas/AutoGemm/ then re-generate files * (otherwise local changes will be lost after re-generation). ******************************************************************************/ #ifndef KERNEL_ZGEMM_COL_NT_B1_ML048_NX048_KX01_SRC_H #define KERNEL_ZGEMM_COL_NT_B1_ML048_NX048_KX01_SRC_H const unsigned int zgemm_Col_NT_B1_ML048_NX048_KX01_workGroupNumRows = 16; const unsigned int zgemm_Col_NT_B1_ML048_NX048_KX01_workGroupNumCols = 16; const unsigned int zgemm_Col_NT_B1_ML048_NX048_KX01_microTileNumRows = 3; const unsigned int zgemm_Col_NT_B1_ML048_NX048_KX01_microTileNumCols = 3; const unsigned int zgemm_Col_NT_B1_ML048_NX048_KX01_unroll = 1; const char * const zgemm_Col_NT_B1_ML048_NX048_KX01_src ="\n" "/* zgemm_Col_NT_B1_ML048_NX048_KX01 */\n" "\n" "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" "\n" "/* kernel parameters */\n" "#define WG_NUM_ROWS 16\n" "#define WG_NUM_COLS 16\n" "#define MICRO_TILE_NUM_ROWS 3\n" "#define MICRO_TILE_NUM_COLS 3\n" "#define MACRO_TILE_NUM_ROWS 48\n" "#define MACRO_TILE_NUM_COLS 48\n" "#define NUM_UNROLL_ITER 1\n" "\n" "#define LOCAL_ROW_PAD 0\n" "#define LOCAL_COL_PAD 0\n" "\n" "/* global memory indices */\n" "#define GET_GLOBAL_INDEX_A(ROW,COL) ((COL)*lda+(ROW))\n" "#define GET_GLOBAL_INDEX_B(ROW,COL) ((ROW)*ldb+(COL))\n" "#define GET_GLOBAL_INDEX_C(ROW,COL) ((COL)*ldc+(ROW))\n" "\n" "/* local memory indices */\n" "#define GET_LOCAL_INDEX_A(ROW,COL) ((ROW) + (COL)*((MACRO_TILE_NUM_ROWS)+(LOCAL_COL_PAD)) )\n" "#define GET_LOCAL_INDEX_B(ROW,COL) ((COL) + (ROW)*((MACRO_TILE_NUM_COLS)+(LOCAL_ROW_PAD)) )\n" "\n" "/* data types */\n" "#define DATA_TYPE_STR double2\n" "#define TYPE_MAD(MULA,MULB,DST) \\\n" " DST.s0 = mad( MULA.s0, MULB.s0, DST.s0 ); \\\n" " DST.s0 = mad( -MULA.s1, MULB.s1, DST.s0 ); \\\n" " DST.s1 = mad( MULA.s0, MULB.s1, DST.s1 ); \\\n" " DST.s1 = mad( MULA.s1, MULB.s0, DST.s1 );\n" "#define TYPE_MAD_WRITE( DST, ALPHA, REG, BETA ) \\\n" " /* (1) */ \\\n" " type_mad_tmp = REG.s0; \\\n" " REG.s0 *= ALPHA.s0; \\\n" " REG.s0 = mad( -ALPHA.s1, REG.s1, REG.s0 ); \\\n" " REG.s1 *= ALPHA.s0; \\\n" " REG.s1 = mad( ALPHA.s1, type_mad_tmp, REG.s1 ); \\\n" " /* (2) */ \\\n" " REG.s0 = mad( BETA.s0, DST.s0, REG.s0 ); \\\n" " REG.s0 = mad( -BETA.s1, DST.s1, REG.s0 ); \\\n" " REG.s1 = mad( BETA.s1, DST.s0, REG.s1 ); \\\n" " REG.s1 = mad( BETA.s0, DST.s1, REG.s1 ); \\\n" " /* (3) */ \\\n" " DST = REG;\n" "\n" "/* 3x3 micro-tile */\n" "#define MICRO_TILE \\\n" " rA[0] = localA[offA + 0*WG_NUM_ROWS]; \\\n" " rA[1] = localA[offA + 1*WG_NUM_ROWS]; \\\n" " rA[2] = localA[offA + 2*WG_NUM_ROWS]; \\\n" " rB[0] = localB[offB + 0*WG_NUM_COLS]; \\\n" " rB[1] = localB[offB + 1*WG_NUM_COLS]; \\\n" " rB[2] = localB[offB + 2*WG_NUM_COLS]; \\\n" " offA += (MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD); \\\n" " offB += (MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD); \\\n" " TYPE_MAD(rA[0],rB[0],rC[0][0]); \\\n" " TYPE_MAD(rA[0],rB[1],rC[0][1]); \\\n" " TYPE_MAD(rA[0],rB[2],rC[0][2]); \\\n" " TYPE_MAD(rA[1],rB[0],rC[1][0]); \\\n" " TYPE_MAD(rA[1],rB[1],rC[1][1]); \\\n" " TYPE_MAD(rA[1],rB[2],rC[1][2]); \\\n" " TYPE_MAD(rA[2],rB[0],rC[2][0]); \\\n" " TYPE_MAD(rA[2],rB[1],rC[2][1]); \\\n" " TYPE_MAD(rA[2],rB[2],rC[2][2]); \\\n" " mem_fence(CLK_LOCAL_MEM_FENCE);\n" "\n" "__attribute__((reqd_work_group_size(WG_NUM_COLS,WG_NUM_ROWS,1)))\n" "__kernel void zgemm_Col_NT_B1_ML048_NX048_KX01(\n" " __global DATA_TYPE_STR const * restrict A,\n" " __global DATA_TYPE_STR const * restrict B,\n" " __global DATA_TYPE_STR * C,\n" " DATA_TYPE_STR const alpha,\n" " DATA_TYPE_STR const beta,\n" " uint const M,\n" " uint const N,\n" " uint const K,\n" " uint const lda,\n" " uint const ldb,\n" " uint const ldc,\n" " uint const offsetA,\n" " uint const offsetB,\n" " uint const offsetC\n" ") {\n" "\n" " /* apply offsets */\n" " A += offsetA;\n" " B += offsetB;\n" " C += offsetC;\n" "\n" " /* allocate registers */\n" " DATA_TYPE_STR rC[MICRO_TILE_NUM_ROWS][MICRO_TILE_NUM_COLS] = { {0} };\n" " DATA_TYPE_STR rA[MICRO_TILE_NUM_ROWS];\n" " DATA_TYPE_STR rB[MICRO_TILE_NUM_COLS];\n" "\n" " /* allocate local memory */\n" " __local DATA_TYPE_STR localA[NUM_UNROLL_ITER*(MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD)];\n" " __local DATA_TYPE_STR localB[NUM_UNROLL_ITER*(MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD)];\n" "\n" " /* work item indices */\n" " uint groupRow = M / 48; // last row\n" " uint groupCol = get_group_id(1);\n" " uint localRow = get_local_id(0);\n" " uint localCol = get_local_id(1);\n" " uint localSerial = localRow + localCol*WG_NUM_ROWS;\n" "\n" " /* global indices being loaded */\n" "#define globalARow(LID) (groupRow*MACRO_TILE_NUM_ROWS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%MACRO_TILE_NUM_ROWS)\n" "#define globalACol(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/MACRO_TILE_NUM_ROWS)\n" "#define globalBRow(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/MACRO_TILE_NUM_COLS)\n" "#define globalBCol(LID) (groupCol*MACRO_TILE_NUM_COLS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%MACRO_TILE_NUM_COLS)\n" "\n" " /* loop over k */\n" " uint block_k = K / NUM_UNROLL_ITER;\n" " do {\n" "\n" " /* local indices being written */\n" "#define localARow (localSerial % MACRO_TILE_NUM_ROWS)\n" "#define localACol (localSerial / MACRO_TILE_NUM_ROWS)\n" "#define localAStride (WG_NUM_ROWS*WG_NUM_COLS)\n" "#define localBRow ( localSerial / MACRO_TILE_NUM_COLS )\n" "#define localBCol ( localSerial % MACRO_TILE_NUM_COLS )\n" "#define localBStride (WG_NUM_ROWS*WG_NUM_COLS)\n" " __local DATA_TYPE_STR *lA = localA + GET_LOCAL_INDEX_A(localARow, localACol);\n" " __local DATA_TYPE_STR *lB = localB + GET_LOCAL_INDEX_B(localBRow, localBCol);\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "\n" " /* load global -> local */\n" " if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_ROWS*MICRO_TILE_NUM_ROWS*NUM_UNROLL_ITER) ) {\n" " lA[ 0*localAStride ] = ( globalARow(0) >= M) ? (double2)(0.0, 0.0) : A[ GET_GLOBAL_INDEX_A( globalARow(0), globalACol(0) ) ];\n" " }\n" " if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_COLS*MICRO_TILE_NUM_COLS*NUM_UNROLL_ITER) ) {\n" " lB[ 0*localBStride ] = B[ GET_GLOBAL_INDEX_B( globalBRow(0), globalBCol(0) ) ];\n" " }\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" " uint offA = localRow;\n" " uint offB = localCol;\n" "\n" " /* do mads */\n" " MICRO_TILE\n" "\n" " /* shift to next k block */\n" " A += lda*NUM_UNROLL_ITER;\n" " B += ldb*NUM_UNROLL_ITER;\n" "\n" " } while (--block_k > 0);\n" "\n" "\n" " /* which global Cij index */\n" " uint globalCRow = groupRow * MACRO_TILE_NUM_ROWS + localRow;\n" " uint globalCCol = groupCol * MACRO_TILE_NUM_COLS + localCol;\n" "\n" " /* write global Cij */\n" " double type_mad_tmp;\n" " if (globalCRow+0*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[0][0], beta )}\n" " if (globalCRow+0*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[0][1], beta )}\n" " if (globalCRow+0*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[0][2], beta )}\n" " if (globalCRow+1*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[1][0], beta )}\n" " if (globalCRow+1*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[1][1], beta )}\n" " if (globalCRow+1*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[1][2], beta )}\n" " if (globalCRow+2*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[2][0], beta )}\n" " if (globalCRow+2*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[2][1], beta )}\n" " if (globalCRow+2*WG_NUM_ROWS < M){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[2][2], beta )}\n" "\n" "}\n" ""; #else #endif
[ "glen.johnson@gaj-geospatial.com" ]
glen.johnson@gaj-geospatial.com
0f6af89bf5495101006d2fce158a094dccf6224b
e1d6417b995823e507a1e53ff81504e4bc795c8f
/gbk/client/Client/Game/Network/PacketHandler/GCExchangeSynchConfirmIIHandler.cpp
6550d9b623a8ef9deae7b74c21461b101049b426
[]
no_license
cjmxp/pap_full
f05d9e3f9390c2820a1e51d9ad4b38fe044e05a6
1963a8a7bda5156a772ccb3c3e35219a644a1566
refs/heads/master
2020-12-02T22:50:41.786682
2013-11-15T08:02:30
2013-11-15T08:02:30
null
0
0
null
null
null
null
GB18030
C++
false
false
801
cpp
/* 接到服务器通知,显示确定按钮 */ #include "stdafx.h" #include "GCExchangeSynchConfirmII.h" #include "..\..\Procedure\GameProcedure.h" #include "..\..\DataPool\GMDataPool.h" #include "..\..\Event\GMEventSystem.h" #include "GIException.h" uint GCExchangeSynchConfirmIIHandler::Execute( GCExchangeSynchConfirmII* pPacket, Player* pPlayer ) { __ENTER_FUNCTION if(CGameProcedure::GetActiveProcedure() == (CGameProcedure*)CGameProcedure::s_pProcMain) {//初始化双方交易盒,打开界面 BYTE IsEnable = pPacket->GetIsEnable(); if(IsEnable) { CDataPool::GetMe()->MyExBox_SetConfirm(TRUE); } else { CDataPool::GetMe()->MyExBox_SetConfirm(FALSE); } //刷新界面 } return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
[ "viticm@126.com" ]
viticm@126.com
c03962b88113b57780ea277b517199346ab1064f
2bc835b044f306fca1affd1c61b8650b06751756
/setup/ieak5/brandll/rsop.h
a508e0e6c66514431e910d98195a71adadce8725
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_inetcore
bbb2354d95a51a75ce2dfd67b18cfb6b21c94939
75f614d008bfce1ea71e4a727205f46b0de8e1c3
refs/heads/master
2023-04-04T02:55:25.139618
2021-04-14T05:25:01
2021-04-14T05:25:01
357,780,123
1
0
null
null
null
null
UTF-8
C++
false
false
6,610
h
// Interface for RSoPUpdate class #ifndef __IEAK_BRANDING_RSOP_H__ #define __IEAK_BRANDING_RSOP_H__ #include <userenv.h> #include <setupapi.h> #include "wbemcli.h" #include <ras.h> #include "reghash.h" #include "SComPtr.h" // defines #define MAX_GUID_LENGTH 40 typedef struct _ADMFILEINFO { WCHAR * pwszFile; // Adm file path WCHAR * pwszGPO; // Gpo that the adm file is in FILETIME ftWrite; // Last write time of Adm file struct _ADMFILEINFO * pNext; // Singly linked list pointer } ADMFILEINFO; /////////////////////////////////////////////////////////////////////////////// // Flags for GetWBEMObject #define OPENRSOPOBJ_OPENEXISTING 0x00000000 #define OPENRSOPOBJ_NEVERCREATE 0x00000001 #define OPENRSOPOBJ_ALWAYSCREATE 0x00000010 /////////////////////////////////////////////////////////////////////////////// class CRSoPGPO { public: CRSoPGPO(ComPtr<IWbemServices> pWbemServices, LPCTSTR szINSFile, BOOL fPlanningMode); virtual ~CRSoPGPO(); // operations public: HRESULT LogPolicyInstance(LPWSTR wszGPO, LPWSTR wszSOM, DWORD dwPrecedence ); private: // Text file functions BOOL GetInsString(LPCTSTR szSection, LPCTSTR szKey, LPTSTR szValue, DWORD dwValueLen, BOOL &bEnabled); BOOL GetInsBool(LPCTSTR szSection, LPCTSTR szKey, BOOL bDefault, BOOL *pbEnabled = NULL); UINT GetInsInt(LPCTSTR szSection, LPCTSTR szKey, INT nDefault, BOOL *pbEnabled = NULL); BOOL GetINFStringField(PINFCONTEXT pinfContext, LPCTSTR szFileName, LPCTSTR szSection, DWORD dwFieldIndex, LPCTSTR szFieldSearchText, LPTSTR szBuffer, DWORD dwBufferLen, BOOL &bFindNextLine); HRESULT StoreStringArrayFromIniFile(LPCTSTR szSection, LPCTSTR szKeyFormat, ULONG nArrayInitialSize, ULONG nArrayIncSize, LPCTSTR szFile, BSTR bstrPropName, ComPtr<IWbemClassObject> pWbemObj); // Property putting & getting HRESULT PutWbemInstanceProperty(BSTR bstrPropName, _variant_t vtPropValue); HRESULT PutWbemInstancePropertyEx(BSTR bstrPropName, _variant_t vtPropValue, ComPtr<IWbemClassObject> pWbemClass); HRESULT PutWbemInstance(ComPtr<IWbemClassObject> pWbemObj, BSTR bstrClassName, BSTR *pbstrObjPath); // Object creation, deletion, retrieval HRESULT CreateAssociation(BSTR bstrAssocClass, BSTR bstrProp2Name, BSTR bstrProp2ObjPath); HRESULT CreateRSOPObject(BSTR bstrClass, IWbemClassObject **ppResultObj, BOOL bTopObj = FALSE ); // -------------------- Methods which write data to WMI // Precedence Mode HRESULT StorePrecedenceModeData(); // Browser UI settings HRESULT StoreDisplayedText(); HRESULT StoreBitmapData(); // toolbar buttons HRESULT StoreToolbarButtons(BSTR **ppaTBBtnObjPaths, long &nTBBtnCount); HRESULT CreateToolbarButtonObjects(BSTR **ppaTBBtnObjPaths, long &nTBBtnCount); // Connection settings HRESULT StoreConnectionSettings(BSTR *bstrConnSettingsObjPath, BSTR **ppaDUSObjects, long &nDUSCount, BSTR **ppaDUCObjects, long &nDUCCount, BSTR **ppaWSObjects, long &nWSCount); HRESULT StoreAutoBrowserConfigSettings(ComPtr<IWbemClassObject> pCSObj); HRESULT StoreProxySettings(ComPtr<IWbemClassObject> pCSObj); HRESULT ProcessAdvancedConnSettings(ComPtr<IWbemClassObject> pCSObj, BSTR **ppaDUSObjects, long &nDUSCount, BSTR **ppaDUCObjects, long &nDUCCount, BSTR **ppaWSObjects, long &nWSCount); HRESULT ProcessRasCS(PCWSTR pszNameW, PBYTE *ppBlob, LPRASDEVINFOW prdiW, UINT cDevices, ComPtr<IWbemClassObject> pCSObj, BSTR *pbstrConnDialUpSettingsObjPath); HRESULT ProcessRasCredentialsCS(PCWSTR pszNameW, PBYTE *ppBlob, ComPtr<IWbemClassObject> pCSObj, BSTR *pbstrConnDialUpCredObjPath); HRESULT ProcessWininetCS(PCWSTR pszNameW, PBYTE *ppBlob, ComPtr<IWbemClassObject> pCSObj, BSTR *pbstrConnWinINetSettingsObjPath); // URL settings HRESULT StoreCustomURLs(); // favorites & links HRESULT StoreFavoritesAndLinks(BSTR **ppaFavObjPaths, long &nFavCount, BSTR **ppaLinkObjPaths, long &nLinkCount); HRESULT CreateFavoriteObjects(BSTR **ppaFavObjPaths, long &nFavCount); HRESULT CreateLinkObjects(BSTR **ppaLinkObjPaths, long &nLinkCount); // channels & categories HRESULT StoreChannelsAndCategories(BSTR **ppaCatObjPaths, long &nCatCount, BSTR **ppaChnObjPaths, long &nChnCount); HRESULT CreateCategoryObjects(BSTR **ppaCatObjPaths, long &nCatCount); HRESULT CreateChannelObjects(BSTR **ppaChnObjPaths, long &nChnCount); // Security settings HRESULT StoreSecZonesAndContentRatings(); HRESULT StoreZoneSettings(LPCTSTR szRSOPZoneFile); HRESULT StorePrivacySettings(LPCTSTR szRSOPZoneFile); HRESULT StoreRatingsSettings(LPCTSTR szRSOPRatingsFile); HRESULT StoreAuthenticodeSettings(); HRESULT StoreCertificates(); // Program settings HRESULT StoreProgramSettings(BSTR *pbstrProgramSettingsObjPath); // Advanced settings HRESULT StoreADMSettings(LPWSTR wszGPO, LPWSTR wszSOM); BOOL LogRegistryRsopData(REGHASHTABLE *pHashTable, LPWSTR wszGPOID, LPWSTR wszSOMID); BOOL LogAdmRsopData(ADMFILEINFO *pAdmFileCache); // attributes private: // Keep copies of RSOP_PolicySetting key info to use as foreign keys in other // classes DWORD m_dwPrecedence; _bstr_t m_bstrID; BOOL m_fPlanningMode; // implementation private: ComPtr<IWbemServices> m_pWbemServices; TCHAR m_szINSFile[MAX_PATH]; // MOF class-specific info ComPtr<IWbemClassObject> m_pIEAKPSObj; BSTR m_bstrIEAKPSObjPath; }; /////////////////////////////////////////////////////////////////////////////// class CRSoPUpdate { public: CRSoPUpdate(ComPtr<IWbemServices> pWbemServices, LPCTSTR szCustomDir); virtual ~CRSoPUpdate(); // operations public: HRESULT Log(DWORD dwFlags, HANDLE hToken, HKEY hKeyRoot, PGROUP_POLICY_OBJECT pDeletedGPOList, PGROUP_POLICY_OBJECT pChangedGPOList, ASYNCCOMPLETIONHANDLE pHandle); HRESULT Plan(DWORD dwFlags, WCHAR *wszSite, PRSOP_TARGET pComputerTarget, PRSOP_TARGET pUserTarget); // attributes // implementation private: HRESULT DeleteIEAKDataFromNamespace(); HRESULT DeleteObjects(BSTR bstrClass); ComPtr<IWbemServices> m_pWbemServices; TCHAR m_szCustomDir[MAX_PATH]; }; #endif //__IEAK_BRANDING_RSOP_H__
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
410ea5edc91ac40297dbd779f50f78af9d81b51e
a0be71e84272af17e3f9c71b182f782c35a56974
/Fem/Gui/TaskFemConstraintFixed.cpp
ab6b65324a8e2b0b04d7c7fb0663c3363f04af6c
[]
no_license
PrLayton/SeriousFractal
52e545de2879f7260778bb41ac49266b34cec4b2
ce3b4e98d0c38fecf44d6e0715ce2dae582c94b2
refs/heads/master
2021-01-17T19:26:33.265924
2016-07-22T14:13:23
2016-07-22T14:13:23
60,533,401
3
0
null
null
null
null
UTF-8
C++
false
false
8,480
cpp
/*************************************************************************** * Copyright (c) 2013 Jan Rheinländer <jrheinlaender@users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <QRegExp> # include <QTextStream> # include <QMessageBox> # include <Precision.hxx> # include <TopoDS.hxx> # include <BRepAdaptor_Surface.hxx> # include <Geom_Plane.hxx> # include <gp_Pln.hxx> # include <gp_Ax1.hxx> # include <BRepAdaptor_Curve.hxx> # include <Geom_Line.hxx> # include <gp_Lin.hxx> #endif #include "ui_TaskFemConstraintFixed.h" #include "TaskFemConstraintFixed.h" #include <App/Application.h> #include <App/Document.h> #include <App/PropertyGeo.h> #include <Gui/Application.h> #include <Gui/Document.h> #include <Gui/BitmapFactory.h> #include <Gui/ViewProvider.h> #include <Gui/WaitCursor.h> #include <Gui/Selection.h> #include <Gui/Command.h> #include <Mod/Fem/App/FemConstraintFixed.h> #include <Mod/Part/App/PartFeature.h> #include <Base/Console.h> using namespace FemGui; using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintFixed */ TaskFemConstraintFixed::TaskFemConstraintFixed(ViewProviderFemConstraintFixed *ConstraintView,QWidget *parent) : TaskFemConstraint(ConstraintView, parent, "Fem_ConstraintFixed") { // we need a separate container widget to add all controls to proxy = new QWidget(this); ui = new Ui_TaskFemConstraintFixed(); ui->setupUi(proxy); QMetaObject::connectSlotsByName(this); // Create a context menu for the listview of the references QAction* action = new QAction(tr("Delete"), ui->listReferences); action->connect(action, SIGNAL(triggered()), this, SLOT(onReferenceDeleted())); ui->listReferences->addAction(action); ui->listReferences->setContextMenuPolicy(Qt::ActionsContextMenu); connect(ui->buttonReference, SIGNAL(pressed()), this, SLOT(onButtonReference())); this->groupLayout()->addWidget(proxy); // Temporarily prevent unnecessary feature recomputes ui->listReferences->blockSignals(true); ui->buttonReference->blockSignals(true); // Get the feature data Fem::ConstraintFixed* pcConstraint = static_cast<Fem::ConstraintFixed*>(ConstraintView->getObject()); std::vector<App::DocumentObject*> Objects = pcConstraint->References.getValues(); std::vector<std::string> SubElements = pcConstraint->References.getSubValues(); // Fill data into dialog elements ui->listReferences->clear(); for (std::size_t i = 0; i < Objects.size(); i++) ui->listReferences->addItem(makeRefText(Objects[i], SubElements[i])); if (Objects.size() > 0) ui->listReferences->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); ui->listReferences->blockSignals(false); ui->buttonReference->blockSignals(false); // Selection mode can be always on since there is nothing else in the UI onButtonReference(true); } void TaskFemConstraintFixed::onSelectionChanged(const Gui::SelectionChanges& msg) { if (msg.Type == Gui::SelectionChanges::AddSelection) { // Don't allow selection in other document if (strcmp(msg.pDocName, ConstraintView->getObject()->getDocument()->getName()) != 0) return; if (!msg.pSubName || msg.pSubName[0] == '\0') return; std::string subName(msg.pSubName); if (selectionMode == selnone) return; std::vector<std::string> references(1,subName); Fem::ConstraintFixed* pcConstraint = static_cast<Fem::ConstraintFixed*>(ConstraintView->getObject()); App::DocumentObject* obj = ConstraintView->getObject()->getDocument()->getObject(msg.pObjectName); Part::Feature* feat = static_cast<Part::Feature*>(obj); TopoDS_Shape ref = feat->Shape.getShape().getSubShape(subName.c_str()); if (selectionMode == selref) { std::vector<App::DocumentObject*> Objects = pcConstraint->References.getValues(); std::vector<std::string> SubElements = pcConstraint->References.getSubValues(); // Ensure we don't have mixed reference types if (SubElements.size() > 0) { if (subName.substr(0,4) != SubElements.front().substr(0,4)) { QMessageBox::warning(this, tr("Selection error"), tr("Mixed shape types are not possible. Use a second constraint instead")); return; } } else { if ((subName.substr(0,4) != "Face") && (subName.substr(0,4) != "Edge") && (subName.substr(0,6) != "Vertex")) { QMessageBox::warning(this, tr("Selection error"), tr("Only faces, edges and vertices can be picked")); return; } } // Avoid duplicates std::size_t pos = 0; for (; pos < Objects.size(); pos++) if (obj == Objects[pos]) break; if (pos != Objects.size()) if (subName == SubElements[pos]) return; // add the new reference Objects.push_back(obj); SubElements.push_back(subName); pcConstraint->References.setValues(Objects,SubElements); ui->listReferences->addItem(makeRefText(obj, subName)); } Gui::Selection().clearSelection(); } } void TaskFemConstraintFixed::onReferenceDeleted() { int row = ui->listReferences->currentIndex().row(); TaskFemConstraint::onReferenceDeleted(row); ui->listReferences->model()->removeRow(row); ui->listReferences->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } const std::string TaskFemConstraintFixed::getReferences() const { int rows = ui->listReferences->model()->rowCount(); std::vector<std::string> items; for (int r = 0; r < rows; r++) items.push_back(ui->listReferences->item(r)->text().toStdString()); return TaskFemConstraint::getReferences(items); } TaskFemConstraintFixed::~TaskFemConstraintFixed() { delete ui; } void TaskFemConstraintFixed::changeEvent(QEvent *e) { TaskBox::changeEvent(e); if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(proxy); } } //************************************************************************** //************************************************************************** // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintFixed::TaskDlgFemConstraintFixed(ViewProviderFemConstraintFixed *ConstraintView) { this->ConstraintView = ConstraintView; assert(ConstraintView); this->parameter = new TaskFemConstraintFixed(ConstraintView);; Content.push_back(parameter); } //==== calls from the TaskView =============================================================== bool TaskDlgFemConstraintFixed::accept() { return TaskDlgFemConstraint::accept(); } #include "moc_TaskFemConstraintFixed.cpp"
[ "gogokoko3@hotmail.fr" ]
gogokoko3@hotmail.fr
cf5382c4fce2065f5416f4f6f1626a35daab9d07
9f03c9326aa725f49ed8583fae7be175699450d7
/ConsoleApplication9/square.h
51b7310c873ac3a1cac32747ed5d44c3a43361ec
[]
no_license
krishanj20/OOP-Chess
b80a6a9a817838f6404b0c076c2f935f1ee16ddc
a608c9a9cce14c0287b7373403db263a904a930a
refs/heads/master
2020-06-01T22:10:38.364260
2019-06-10T16:16:09
2019-06-10T16:16:09
190,945,206
1
0
null
null
null
null
UTF-8
C++
false
false
600
h
#pragma once #include "piece.h" //This class is for each square of the board. //It contains a pointer to the piece on the quare, and is a nullptr if there is no piece. class square { private: piece * pieceOnSquare; //pointer to piece on the square. void if no piece is present. public: //Default constructor square(); //Parameterised constuctor square(piece *); //Default destuctor ~square(); //Piece setter void setPieceOnSquare(piece *piece); //Piece getter piece* getPieceOnSquare(); //A getter and setter are being used //this allows access to protected/private variables };
[ "krishanjethwa@msn.com" ]
krishanjethwa@msn.com
5cf17e3eeb111185a926a9339452a6033524d9ab
3299c43394dae4558d9468a26efa3fdba0bd0709
/Algoritmo_de_ordenacao_shell_sort/Algoritmo_de_ordenacao_shell_sort/stdafx.cpp
f060e96d3232e3616d760125913225f4ca6f2ec9
[]
no_license
GuibsonKrause/Algoritmo_de_ordenacao_shell_sort
bd58ed2acea13a4a4221ddc5d71fcf4f39c260e4
6f3ac33847a4bc0695bc1c88e077e2be29b80d1f
refs/heads/master
2021-07-17T17:17:15.247326
2017-10-24T16:09:33
2017-10-24T16:09:33
108,151,774
0
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
// stdafx.cpp : source file that includes just the standard includes // Algoritmo_de_ordenacao_shell_sort.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "oliveira.guibson@hotmail.com" ]
oliveira.guibson@hotmail.com
1e2ae969c4b4d078822166a550e5b7e334462d7f
a411a55762de11dc2c9d913ff33d2f1477ac02cf
/lte/gateway/c/core/oai/tasks/nas5g/src/M5GPDUSessionReleaseReject.cpp
81c0fecd0b1eb615db4165b6feafef2d2b46acfc
[ "BSD-3-Clause" ]
permissive
magma/magma
0dc48c1513d9968bd05fb7589f302c192b7c0f94
0e1d895dfe625681229e181fbc2dbad83e13c5cb
refs/heads/master
2023-09-04T09:31:56.140395
2023-08-29T13:54:49
2023-08-29T13:54:49
170,803,235
1,219
525
NOASSERTION
2023-09-07T17:45:42
2019-02-15T04:46:24
C++
UTF-8
C++
false
false
3,123
cpp
/* Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. 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 <sstream> #ifdef __cplusplus extern "C" { #endif #include "lte/gateway/c/core/oai/common/log.h" #ifdef __cplusplus } #endif #include "lte/gateway/c/core/oai/tasks/nas5g/include/M5GPDUSessionReleaseReject.hpp" #include "lte/gateway/c/core/oai/tasks/nas5g/include/M5GCommonDefs.h" namespace magma5g { PDUSessionReleaseRejectMsg::PDUSessionReleaseRejectMsg(){}; PDUSessionReleaseRejectMsg::~PDUSessionReleaseRejectMsg(){}; // Decode PDUSessionReleaseReject Message and its IEs int PDUSessionReleaseRejectMsg::DecodePDUSessionReleaseRejectMsg( PDUSessionReleaseRejectMsg* pdu_session_release_reject, uint8_t* buffer, uint32_t len) { // Not yet implemented, will be supported POST MVC return 0; } // Encode PDUSessionReleaseReject Message and its IEs int PDUSessionReleaseRejectMsg::EncodePDUSessionReleaseRejectMsg( PDUSessionReleaseRejectMsg* pdu_session_release_reject, uint8_t* buffer, uint32_t len) { uint32_t encoded = 0; int encoded_result = 0; CHECK_PDU_POINTER_AND_LENGTH_DECODER(buffer, PDU_SESSION_RELEASE_REJECT_MIN_LEN, len); if ((encoded_result = pdu_session_release_reject->extended_protocol_discriminator .EncodeExtendedProtocolDiscriminatorMsg( &pdu_session_release_reject->extended_protocol_discriminator, 0, buffer + encoded, len - encoded)) < 0) return encoded_result; else encoded += encoded_result; if ((encoded_result = pdu_session_release_reject->pdu_session_identity .EncodePDUSessionIdentityMsg( &pdu_session_release_reject->pdu_session_identity, 0, buffer + encoded, len - encoded)) < 0) return encoded_result; else encoded += encoded_result; if ((encoded_result = pdu_session_release_reject->pti.EncodePTIMsg( &pdu_session_release_reject->pti, 0, buffer + encoded, len - encoded)) < 0) return encoded_result; else encoded += encoded_result; if ((encoded_result = pdu_session_release_reject->message_type.EncodeMessageTypeMsg( &pdu_session_release_reject->message_type, 0, buffer + encoded, len - encoded)) < 0) return encoded_result; else encoded += encoded_result; if ((encoded_result = pdu_session_release_reject->m5gsm_cause.EncodeM5GSMCauseMsg( &pdu_session_release_reject->m5gsm_cause, 0, buffer + encoded, len - encoded)) < 0) return encoded_result; else encoded += encoded_result; return encoded; } } // namespace magma5g
[ "noreply@github.com" ]
noreply@github.com
dbea1bd605c94ace5a33d37dc4bb065affee0699
bdc0812f014da529e1ec554bf97515011c917a25
/lab00/Insertion-Sort.cpp
ae704319f7135f78bdd406c943077f9473298e7d
[]
no_license
acreyes311/CSE100
0670bd15dafcbd89fbbc937108864c184eb3fd27
9968b079999222b7c429ae78ad702b19558f3e97
refs/heads/master
2020-04-17T16:01:09.269830
2019-01-21T00:31:08
2019-01-21T00:31:08
166,723,086
0
0
null
null
null
null
UTF-8
C++
false
false
537
cpp
#include <iostream> using namespace std; void insertionSort(int* arr,int n){ int key; int i; for (int j = 1; j < n; j++){ key = arr[j]; i = j - 1; while((i >=0) && (arr[i] < key)){ arr[i+1] = arr[i]; i = i-1; arr[i+1] = key; } } } int main(){ int size; //get size of array cin >> size; //create array int arr[size]; // fill array for(int i = 0; i < size; i++){ cin >> arr[i]; } // Call insertionSort function insertionSort(arr,size); //Print array for(int i = 0; i < size; i++){ cout << arr[i] << ";"; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
6cb41f1cdc3ecc71c2fb2ddf8e25b392b61345e2
9db9905b751e0b9f8acf731167d9a13a86716595
/basic_algorithm/memory/memory.cpp
35ac2c21f710a4fb9a0eb97286c06c355a649668
[]
no_license
jelllove/leetcode
7071c66e98fb31d746c653d1d03bb175fbdc362f
c8a21b7df6a694c958111a62980038266fd7e5e3
refs/heads/main
2023-08-28T10:17:38.544149
2021-10-20T15:07:21
2021-10-20T15:07:21
349,485,638
1
2
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include <iostream> int main(int argc, char *argv[]) { //这样的定义会导致栈溢出的,因为不同的OS给不同的APP定义的STACK的大小是固定的 long m[8111110] = {0}; }
[ "jelllove@126.com" ]
jelllove@126.com
b30bd51fa685adc834910b47606776f4d6c1acea
6ff225ced3f8ea771a0db118933907da4445690e
/logdevice/server/RebuildingCoordinator.cpp
34636c370c4eb96a5575f5147f75b7987b0515aa
[ "BSD-3-Clause" ]
permissive
mickvav/LogDevice
c5680d76b5ebf8f96de0eca0ba5e52357408997a
24a8b6abe4576418eceb72974083aa22d7844705
refs/heads/master
2020-04-03T22:33:29.633769
2018-11-07T12:17:25
2018-11-07T12:17:25
155,606,676
0
0
NOASSERTION
2018-10-31T18:39:23
2018-10-31T18:39:23
null
UTF-8
C++
false
false
57,254
cpp
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/server/RebuildingCoordinator.h" #include <folly/hash/Hash.h> #include "logdevice/common/AdminCommandTable.h" #include "logdevice/common/AppendRequest.h" #include "logdevice/common/LegacyLogToShard.h" #include "logdevice/common/configuration/Configuration.h" #include "logdevice/common/configuration/LocalLogsConfig.h" #include "logdevice/common/debug.h" #include "logdevice/server/RebuildingSupervisor.h" #include "logdevice/server/ServerProcessor.h" #include "logdevice/server/ServerWorker.h" #include "logdevice/server/locallogstore/LocalLogStore.h" #include "logdevice/server/read_path/AllServerReadStreams.h" #include "logdevice/server/rebuilding/ShardRebuildingV1.h" #include "logdevice/server/rebuilding/ShardRebuildingV2.h" #include "logdevice/server/storage_tasks/PerWorkerStorageTaskQueue.h" #include "logdevice/server/storage_tasks/ReadStorageTask.h" #include "logdevice/server/storage_tasks/ShardedStorageThreadPool.h" #include "logdevice/server/storage_tasks/StorageThreadPool.h" namespace facebook { namespace logdevice { class ShardedLocalLogStore; namespace { /** * A storage task used to write a marker in a local log store to indicate that * it was rebuilt. */ class WriteShardRebuildingCompleteMetadataTask : public StorageTask { public: explicit WriteShardRebuildingCompleteMetadataTask( RebuildingCoordinator* owner, lsn_t version) : StorageTask(StorageTask::Type::REBUILDING_WRITE_COMPLETE_METADATA), owner_(owner), version_(version) {} void execute() override { auto& store = storageThreadPool_->getLocalLogStore(); if (store.acceptingWrites() == E::DISABLED) { RATELIMIT_INFO(std::chrono::seconds(10), 10, "Not writing RebuildingCompleteMetadata for disabled " "shard %u", storageThreadPool_->getShardIdx()); status_ = E::DISABLED; return; } // With rebuilding complete, clear any dirty time ranges // for the shard. LocalLogStore::WriteOptions options; RebuildingRangesMetadata range_metadata; int rv = storageThreadPool_->getLocalLogStore().writeStoreMetadata( range_metadata, options); if (rv != 0) { RATELIMIT_ERROR(std::chrono::seconds(10), 10, "Could not write RebuildingRangesMetadata for " "shard %u: %s", storageThreadPool_->getShardIdx(), error_description(err)); status_ = err; return; } // Mark rebuilding complete. RebuildingCompleteMetadata complete_metadata; rv = storageThreadPool_->getLocalLogStore().writeStoreMetadata( complete_metadata, options); if (rv != 0) { RATELIMIT_ERROR(std::chrono::seconds(10), 10, "Could not write RebuildingCompleteMetadata for " "shard %u: %s", storageThreadPool_->getShardIdx(), error_description(err)); status_ = err; return; } status_ = E::OK; } void onDone() override { owner_->onMarkerWrittenForShard( storageThreadPool_->getShardIdx(), version_, status_); } void onDropped() override { ld_check(false); } bool isDroppable() const override { return false; } private: RebuildingCoordinator* owner_; lsn_t version_; Status status_{E::INTERNAL}; }; /** * A request to inform AllServerReadStreams running on a worker thread that a * shard was rebuilt. AllServerReadStreams will wake up all read streams that * were stalled waiting for this event to happen. */ class WakeUpServerReadStreamsRequest : public Request { public: WakeUpServerReadStreamsRequest(int worker_idx, uint32_t shard_idx) : Request(RequestType::WAKEUP_SERVER_READ_STREAMS), worker_idx_(worker_idx), shard_idx_(shard_idx) {} Request::Execution execute() override { ServerWorker::onThisThread()->serverReadStreams().onShardRebuilt( shard_idx_); return Execution::COMPLETE; } int getThreadAffinity(int /*nthreads*/) override { return worker_idx_; } private: int worker_idx_; uint32_t shard_idx_; }; } // end of anonymous namespace RebuildingCoordinator::RebuildingCoordinator( const std::shared_ptr<UpdateableConfig>& config, EventLogStateMachine* event_log, Processor* processor, UpdateableSettings<RebuildingSettings> rebuilding_settings, ShardedLocalLogStore* sharded_store) : config_(config), event_log_(event_log), processor_(processor), rebuildingSettings_(rebuilding_settings), shardedStore_(sharded_store) {} int RebuildingCoordinator::start() { writer_ = std::make_unique<EventLogWriter>(event_log_); myNodeId_ = getMyNodeID(); populateDirtyShardCache(dirtyShards_); if (checkMarkers() != 0) { return -1; } class InitRequest : public Request { public: explicit InitRequest(RebuildingCoordinator* self) : Request(RequestType::REBUILDING_COORDINATOR_INIT_REQUEST), self_(self) {} Execution execute() override { self_->startOnWorkerThread(); return Execution::COMPLETE; } int getThreadAffinity(int /* unused */) override { return 0; } RebuildingCoordinator* self_; }; if (processor_) { // may be nullptr in tests std::unique_ptr<Request> req = std::make_unique<InitRequest>(this); processor_->postWithRetrying(req); } return 0; } void RebuildingCoordinator::subscribeToEventLogIfNeeded() { if (!started_) { if (config_->getLogsConfig()->isFullyLoaded()) { subscribeToEventLog(); started_ = true; } else { ld_info("RebuildingCoordinator did not start yet because LogsConfig is " "not fully loaded yet"); } } } void RebuildingCoordinator::startOnWorkerThread() { Worker* w = Worker::onThisThread(); w->setRebuildingCoordinator(this); my_worker_id_ = w->idx_; // initialize the counter to 0. it will be updated based on the // rebuilding set. WORKER_STAT_SET(rebuilding_waiting_for_recoverable_shards, 0); scheduledRestarts_.reserve(numShards()); for (shard_index_t s = 0; s < numShards(); ++s) { auto timer = std::make_unique<Timer>([self = this, shard = s] { self->restartForShard(shard, self->event_log_->getCurrentRebuildingSet()); }); scheduledRestarts_.emplace_back(std::move(timer)); } subscribeToEventLogIfNeeded(); nonAuthoratitiveRebuildingChecker_ = std::make_unique<NonAuthoritativeRebuildingChecker>( rebuildingSettings_, event_log_, myNodeId_); } void RebuildingCoordinator::shutdown() { scheduledRestarts_.clear(); handle_.reset(); shardsRebuilding_.clear(); writer_.reset(); nonAuthoratitiveRebuildingChecker_.reset(); shuttingDown_ = true; } void RebuildingCoordinator::noteConfigurationChanged() { // NOTE: we don't care about node config changes. A node is not removed from // the rebuilding set if it was removed from the config. subscribeToEventLogIfNeeded(); for (auto& it : shardsRebuilding_) { ShardState& shard_state = it.second; if (shard_state.shardRebuilding != nullptr) { shard_state.shardRebuilding->noteConfigurationChanged(); } } } int RebuildingCoordinator::checkMarkers() { auto config = config_->get(); if (config->serverConfig()->getMyNodeID().generation() <= 1) { for (uint32_t shard = 0; shard < numShards(); ++shard) { RebuildingCompleteMetadata metadata; LocalLogStore::WriteOptions options; LocalLogStore* store = shardedStore_->getByIndex(shard); if (store->acceptingWrites() != E::DISABLED) { notifyProcessorShardRebuilt(shard); } int rv = store->writeStoreMetadata(metadata, options); if (rv != 0) { ld_error("Could not write RebuildingCompleteMetadata for shard %u: %s", shard, error_description(err)); if (store->acceptingWrites() != E::DISABLED) { // This shouldn't really happen with current LocalLogStore // implementations because a failed write transitions the store to // a disabled state. return -1; } } } return 0; } for (shard_index_t shard = 0; shard < numShards(); ++shard) { LocalLogStore* store = shardedStore_->getByIndex(shard); RebuildingCompleteMetadata meta; int rv = store->readStoreMetadata(&meta); if (rv == 0) { notifyProcessorShardRebuilt(shard); } else if (err == E::NOTFOUND) { ld_info("Did not find RebuildingCompleteMetadata for shard %u. Waiting " "for the shard to be rebuilt...", shard); // Request rebuilding of the shard. auto supervisor = processor_->rebuilding_supervisor_; ld_check(supervisor); supervisor->myShardNeedsRebuilding(shard); } else { // It's likely that the failing disk on which this shard resides has not // been repaired yet. Once the disk is repaired, logdeviced will be // restarted and we will try reading the marker again. ld_error("Error reading RebuildingCompleteMetadata for shard %u: %s", shard, error_description(err)); if (store->acceptingWrites() != E::DISABLED) { return -1; } } } return 0; } void RebuildingCoordinator::populateDirtyShardCache(DirtyShardMap& map) { for (uint32_t shard = 0; shard < numShards(); ++shard) { RebuildingRangesMetadata meta; LocalLogStore* store = shardedStore_->getByIndex(shard); int rv = store->readStoreMetadata(&meta); if (rv != 0) { if (err != E::NOTFOUND) { ld_error("Could not read RebuildingRangesMetadata for shard %u: %s", shard, error_description(err)); ld_check(store->acceptingWrites() == E::DISABLED); } // If we can't read from the shard, we'll be doing a full rebuild. // There's no point in claiming we have dirty state to publish/rebuild. processor_->markShardClean(shard); } else if (!meta.empty()) { map[shard] = meta; } else { processor_->markShardClean(shard); } } } RebuildingCoordinator::~RebuildingCoordinator() { // shutdown() must have ensured that all ShardRebuilding objects are destroyed // from the correct worker thread. ld_check(shardsRebuilding_.empty()); } void RebuildingCoordinator::writeMarkerForShard(uint32_t shard, lsn_t version) { ld_info("Writing marker for shard %u, version %s", shard, lsn_to_string(version).c_str()); auto task = std::make_unique<WriteShardRebuildingCompleteMetadataTask>(this, version); auto task_queue = ServerWorker::onThisThread()->getStorageTaskQueueForShard(shard); task_queue->putTask(std::move(task)); } void RebuildingCoordinator::onMarkerWrittenForShard(uint32_t shard, lsn_t version, Status status) { if (status != E::OK) { ld_error("Error writting RebuildingCompleteMetadata for shard %u.", shard); // It's likely that the failing disk on which this shard resides has not // been replaced yet. Once the disk is replaced, logdeviced will be // restarted and we will try writting the marker again. return; } notifyProcessorShardRebuilt(shard); notifyAckMyShardRebuilt(shard, version); wakeUpReadStreams(shard); } void RebuildingCoordinator::wakeUpReadStreams(uint32_t shard) { const int nworkers = processor_->getWorkerCount(WorkerType::GENERAL); for (int i = 0; i < nworkers; ++i) { std::unique_ptr<Request> req = std::make_unique<WakeUpServerReadStreamsRequest>(i, shard); processor_->postWithRetrying(req); } } void RebuildingCoordinator::notifyProcessorShardRebuilt(uint32_t shard) { if (!processor_->isDataMissingFromShard(shard) && !myShardIsDirty(shard)) { ld_warning("Shard %u was taking writes while its rebuilding was in " "progress. This can lead to underreplicated records " "(see task t10343616).", shard); } processor_->markShardAsNotMissingData(shard); } void RebuildingCoordinator::onShardRebuildingComplete(uint32_t shard_idx) { auto& shard_state = getShardState(shard_idx); /* * We are done rebuilding the shard. If the setting * disable-data-log-rebuilding was enabled, then we just skipped over the data * logs that have a retention specified. In that case, we want to delay * sending the SHARD_IS_REBULT message until the data logs expire. The timer * below handles that for us. */ auto now = RecordTimestamp::now(); RecordTimestamp maxBacklogTS = RecordTimestamp(shard_state.rebuilding_started_ts) + shard_state.max_rebuild_by_retention_backlog; if (maxBacklogTS > now) { std::chrono::milliseconds delay_ms = maxBacklogTS - now; // Planning stage requested a delay. ld_check(shard_state.rebuilding_started_ts.count()); ld_check(!shard_state.shardIsRebuiltDelayTimer->isActive()); ld_info("Planning requested a delay until %s for shard %u, " "before declaring the shard as rebuilt. Delaying " "SHARD_IS_REBUILT message by %ld ms", maxBacklogTS.toString().c_str(), shard_idx, delay_ms.count()); shard_state.shardIsRebuiltDelayTimer->activate(delay_ms); } else { // Immediately notify shard as rebuilt. notifyShardRebuiltCB(shard_idx); } } void RebuildingCoordinator::notifyShardRebuiltCB(uint32_t shard_idx) { auto& shard_state = getShardState(shard_idx); ld_check(shard_state.participating); ld_check(shard_state.logsWithPlan.empty()); notifyShardRebuilt( shard_idx, shard_state.version, shard_state.isAuthoritative); shard_state.shardRebuilding.reset(); shard_state.planner.reset(); shard_state.logsWithPlan.clear(); shard_state.participating = false; shard_state.max_rebuild_by_retention_backlog = std::chrono::milliseconds::zero(); shard_state.rebuilding_started_ts = std::chrono::milliseconds::zero(); shard_state.shardIsRebuiltDelayTimer.reset(); } void RebuildingCoordinator::trySlideGlobalWindow( uint32_t shard, const EventLogRebuildingSet& set) { auto& shard_state = getShardState(shard); if (!shard_state.participating || shard_state.globalWindowEnd == RecordTimestamp::max()) { return; } const RecordTimestamp::duration global_window = rebuildingSettings_->global_window; const auto* rsi = set.getForShardOffset(shard); ld_check(rsi); // Recompute the minimum next timestamp across all nodes. RecordTimestamp min_next_timestamp = RecordTimestamp::max(); for (auto& n : rsi->donor_progress) { min_next_timestamp = std::min(min_next_timestamp, RecordTimestamp(n.second)); } // Calculate new_global_window_end = min_next_timestamp + global_window, // but avoid overflow. RecordTimestamp new_global_window_end; if (global_window == RecordTimestamp::duration::max()) { // Treat global_window = max() as infinity. new_global_window_end = RecordTimestamp::max(); } else if (min_next_timestamp == RecordTimestamp::min()) { // If some donors haven't made any progress yet, don't bother moving global // window from min() to min() + window. new_global_window_end = RecordTimestamp::min(); } else if (min_next_timestamp.toMilliseconds().count() > 0 && RecordTimestamp::max() - min_next_timestamp < global_window) { // Addition would overflow, clamp to max(). new_global_window_end = RecordTimestamp::max(); } else { new_global_window_end = min_next_timestamp + global_window; } ld_check(new_global_window_end >= shard_state.globalWindowEnd); if (new_global_window_end <= shard_state.globalWindowEnd) { // The global window is not slid. return; } RecordTimestamp old_window_end = shard_state.globalWindowEnd; shard_state.globalWindowEnd = new_global_window_end; ld_info("Moving global window to %s for shard %u and rebuilding set %s", format_time(shard_state.globalWindowEnd).c_str(), shard, shard_state.rebuildingSet->describe().c_str()); PER_SHARD_STAT_SET(getStats(), rebuilding_global_window_end, shard, shard_state.globalWindowEnd.toMilliseconds().count()); if (old_window_end != RecordTimestamp::min()) { PER_SHARD_STAT_ADD( getStats(), rebuilding_global_window_slide_num, shard, 1); PER_SHARD_STAT_ADD( getStats(), rebuilding_global_window_slide_total, shard, RecordTimestamp(shard_state.globalWindowEnd - old_window_end) .toMilliseconds() .count()); } if (shard_state.shardRebuilding != nullptr) { shard_state.shardRebuilding->advanceGlobalWindow( shard_state.globalWindowEnd); } } void RebuildingCoordinator::onShardDonorProgress( node_index_t /*donor_node_idx*/, uint32_t shard_idx, RecordTimestamp /* next_ts */, lsn_t version, const EventLogRebuildingSet& set) { auto it_shard = shardsRebuilding_.find(shard_idx); if (it_shard == shardsRebuilding_.end()) { // We don't care about that information because we already finished // rebuilding the shard. return; } auto& shard_state = it_shard->second; if (shard_state.version != version || !shard_state.participating) { // This means the donor node sent this event before it received a // SHARD_NEEDS_REBUILD or SHARD_ABORT_REBUILD event. return; } // We may be able to slide the global timestamp window. trySlideGlobalWindow(shard_idx, set); } bool RebuildingCoordinator::shouldRebuildMetadataLogs(uint32_t shard_idx) { std::shared_ptr<Configuration> config = config_->get(); const auto& nodes = config->serverConfig()->getMetaDataNodeIndices(); // Don't schedule metadata logs for rebuilding if this node is not in their // nodeset. if (std::find(nodes.begin(), nodes.end(), myNodeId_) == nodes.end()) { return false; } // Otherwise, schedule them if at least one node in the rebuilding set is in // the metadata log nodeset. auto& shard_state = getShardState(shard_idx); for (auto& i : shard_state.rebuildingSet->shards) { if (std::find(nodes.begin(), nodes.end(), i.first.node()) != nodes.end()) { return true; } } return false; } bool RebuildingCoordinator::restartIsScheduledForShard(uint32_t shard_idx) { if (shard_idx >= numShards()) { return false; } auto& timer = scheduledRestarts_[shard_idx]; ld_check(timer); return timer->isActive(); } void RebuildingCoordinator::scheduleRestartForShard(uint32_t shard_idx) { if (shard_idx >= numShards()) { ld_error("Received request to rebuild shard %u, but there are" " only %lu shards", shard_idx, numShards()); return; } auto& timer = scheduledRestarts_[shard_idx]; ld_check(timer); timer->activate(rebuildingSettings_->rebuilding_restarts_grace_period); ld_info("Scheduling a restart for shard %u after %lums", shard_idx, rebuildingSettings_->rebuilding_restarts_grace_period.count()); } void RebuildingCoordinator::restartForShard(uint32_t shard_idx, const EventLogRebuildingSet& set) { if (shard_idx >= numShards()) { ld_error("Received request to rebuild shard %u, but there are" " only %lu shards", shard_idx, numShards()); return; } if (shardsRebuilding_.count(shard_idx)) { auto& shard_state = getShardState(shard_idx); ld_check(shard_state.restartVersion <= set.getLastSeenLSN()); if (shard_state.restartVersion == set.getLastSeenLSN()) { // Event log state was updated but last seen LSN didn't increase. // We are probably here because of a bug in ReplicatedStateMachine causing // the callback to be called more than once for the same state version. // Let's not restart rebuilding. RATELIMIT_ERROR(std::chrono::seconds(1), 1, "Not restarting rebuilding for shard %u because " "restartVersion has not changed: %s", shard_idx, lsn_to_string(set.getLastSeenLSN()).c_str()); // ld_check(false); // TODO(T17286647): add this assert back. return; } // Cancel the current rebuilding. abortShardRebuilding(shard_idx); } const auto* rsi = set.getForShardOffset(shard_idx); if (rsi == nullptr) { // There is nothing to restart. return; } std::shared_ptr<RebuildingSet> rebuildingSet = std::make_shared<RebuildingSet>(); rebuildingSet->all_dirty_time_intervals = rsi->all_dirty_time_intervals; if (!rebuildingSet->all_dirty_time_intervals.empty()) { normalizeTimeRanges(shard_idx, rebuildingSet->all_dirty_time_intervals); } bool my_shard_draining = false; for (auto& node : rsi->nodes_) { if (!node.second.acked) { ShardID shard(node.first, shard_idx); rebuildingSet->shards.emplace( shard, RebuildingNodeInfo(node.second.dc_dirty_ranges, node.second.mode)); if (node.second.auth_status == AuthoritativeStatus::AUTHORITATIVE_EMPTY) { rebuildingSet->empty.insert(shard); } } if (node.first == myNodeId_) { my_shard_draining = node.second.drain; } } ld_check(!rebuildingSet->shards.empty()); // Create a new ShardState object. shardsRebuilding_[shard_idx] = ShardState{}; auto& shard_state = getShardState(shard_idx); shard_state.rebuildingSet = rebuildingSet; shard_state.restartVersion = set.getLastSeenLSN(); shard_state.recoverableShards = set.getForShardOffset(shard_idx)->num_recoverable_; shard_state.rebuildingSetContainsMyself = rebuildingSet->shards.find(ShardID(myNodeId_, shard_idx)) != rebuildingSet->shards.end(); shard_state.version = rsi->version; shard_state.rebuilding_started_ts = set.getLastSeenShardNeedsRebuildTS(shard_idx); // Install a delay timer to support the feature to skip rebuilding data logs. // If the setting is enabled, the timer just delays the SHARD_IS_REBUILT // message until after all the data on this shard has expired. auto cb = [self = this, shard = shard_idx]() { self->notifyShardRebuiltCB(shard); }; // Always init the timer even though currently it is only // used if disable_data_log_rebuilding is enabled. if (rebuildingSettings_->disable_data_log_rebuilding) { shard_state.shardIsRebuiltDelayTimer = std::make_unique<LibeventTimer>( Worker::onThisThread()->getEventBase(), cb); } if (shard_state.rebuildingSetContainsMyself) { // Increment rebuilding_set_contains_myself stat. shard_state.rebuildingSetContainsMyselfStat.assign( getStats(), &PerShardStats::rebuilding_set_contains_myself, shard_idx); auto& s = rebuildingSet->shards.at(ShardID(myNodeId_, shard_idx)); if (s.mode == RebuildingMode::RESTORE && s.dc_dirty_ranges.empty()) { // Increment full_restore_set_contains_myself stat if we're in RESTORE // mode and not mini-rebuilding. shard_state.restoreSetContainsMyselfStat.assign( getStats(), &PerShardStats::full_restore_set_contains_myself, shard_idx); } } if (shouldAcknowledgeRebuilding(shard_idx, set)) { writeMarkerForShard(shard_idx, shard_state.version); } else if (shard_state.rebuildingSetContainsMyself) { // One of my shards is being rebuilt... Let's check several things: // 1/ If the shard is actually functioning, has the marker, is not being // drained, and is not dirty, we can abort the rebuilding; // 2/ If the shard is actually functioning, has the marker, is being drained // in RESTORE mode, and is not dirty, the drain can be restarted in // RELOCATE mode as we did not lose all data; // 3/ If the shard is rebuilding in RESTORE mode, is actually functioning // but has no marker (e.g. a broken disk was replaced with a new one), do // not abort rebuilding because data was lost, but mark the data as // unrecoverable. This will make readers unstall if they were stalled // hoping the data would be recovered due to the current rebuilding being // non-authoritative. Readers may in that case see dataloss. const bool is_restore = rebuildingSet->shards.at(ShardID(myNodeId_, shard_idx)).mode == RebuildingMode::RESTORE; if (myShardHasDataIntact(shard_idx)) { if (!my_shard_draining) { // 1/. The data is intact and the user does not wish to drain this // shard, abort rebuilding. abortForMyShard() will check for dirtiness // and respond appropriately. abortForMyShard(shard_idx, rsi->version, set.getNodeInfo(myNodeId_, shard_idx), "data is intact"); } else if (is_restore && !myShardIsDirty(shard_idx)) { // 2/. The data is intact. Restart the drain in RELOCATE mode. ld_info("The data on my shard %u is intact, restart rebuilding for " "this shard to continue the drain in RELOCATE mode.", shard_idx); auto f = SHARD_NEEDS_REBUILD_Header::RELOCATE | SHARD_NEEDS_REBUILD_Header::CONDITIONAL_ON_VERSION; restartForMyShard(shard_idx, f, nullptr, rsi->version); } } else if (is_restore && shouldMarkMyShardUnrecoverable(shard_idx)) { // 3/ We should mark the data unrecoverable. ld_info("Notifying the event log that my shard %u is unrecoverable.", shard_idx); auto* node_info = set.getNodeInfo(myNodeId_, shard_idx); if (!node_info->dc_dirty_ranges.empty()) { // The cluster was performing a ranged rebuild for this shard. // Since all data is lost, convert to a full shard rebuild. restartForMyShard(shard_idx, 0); } markMyShardUnrecoverable(shard_idx); } // Dirty, recoverable, shards remain in RESTORE mode since some records // may be missing. } if (!rsi->donor_progress.count(myNodeId_)) { // I am not a donor node for this rebuilding, do not create LogRebuilding // state machines. Our job is just to wait for all donors to notify they // finished to rebuild the shard so that we can acknowledge our shard was // rebuilt. return; } auto settings = rebuildingSettings_.get(); shard_state.participating = true; shard_state.globalWindowEnd = RecordTimestamp::min(); trySlideGlobalWindow(shard_idx, set); RebuildingPlanner::Options options{ .rebuild_metadata_logs = !rebuildUserLogsOnly_ && shouldRebuildMetadataLogs(shard_idx), .rebuild_internal_logs = !rebuildUserLogsOnly_, .min_timestamp = rsi->all_dirty_time_intervals.begin()->lower()}; shard_state.planner = createRebuildingPlanner(shard_idx, rsi->version, options, *shard_state.rebuildingSet, rebuildingSettings_, this); shard_state.planner->start(); } void RebuildingCoordinator::normalizeTimeRanges(uint32_t shard_idx, RecordTimeIntervals& rtis) { auto& store = ServerWorker::onThisThread() ->processor_->sharded_storage_thread_pool_->getByIndex(shard_idx) .getLocalLogStore(); store.normalizeTimeRanges(rtis); } std::unique_ptr<RebuildingPlanner> RebuildingCoordinator::createRebuildingPlanner( shard_index_t shard_idx, lsn_t version, RebuildingPlanner::Options options, RebuildingSet rebuilding_set, UpdateableSettings<RebuildingSettings> rebuilding_settings, RebuildingPlanner::Listener* listener) { return std::make_unique<RebuildingPlanner>(version, shard_idx, std::move(rebuilding_set), rebuilding_settings, config_, options, numShards(), listener); } std::unique_ptr<ShardRebuildingInterface> RebuildingCoordinator::createShardRebuilding( shard_index_t shard, lsn_t version, lsn_t restart_version, std::shared_ptr<const RebuildingSet> rebuilding_set, UpdateableSettings<RebuildingSettings> rebuilding_settings) { if (rebuilding_settings->enable_v2) { return std::make_unique<ShardRebuildingV2>(shard, version, restart_version, rebuilding_set, rebuilding_settings, config_, this); } else { return std::make_unique<ShardRebuildingV1>(shard, version, restart_version, rebuilding_set, shardedStore_->getByIndex(shard), rebuilding_settings, config_, this); } } void RebuildingCoordinator::abortShardRebuilding(uint32_t shard_idx) { auto it_shard = shardsRebuilding_.find(shard_idx); if (it_shard == shardsRebuilding_.end()) { // We are not rebuilding this shard. return; } auto& shard_state = getShardState(shard_idx); if (!shard_state.isAuthoritative && shard_state.recoverableShards > 0) { WORKER_STAT_DECR(rebuilding_waiting_for_recoverable_shards); } shard_state.shardRebuilding.reset(); shard_state.planner.reset(); shard_state.logsWithPlan.clear(); shard_state.waitingForMorePlans = 0; shard_state.participating = false; shard_state.isAuthoritative = true; shard_state.max_rebuild_by_retention_backlog = std::chrono::milliseconds::zero(); shard_state.rebuilding_started_ts = std::chrono::milliseconds::zero(); shard_state.shardIsRebuiltDelayTimer.reset(); } void RebuildingCoordinator::onShardMarkUnrecoverable( node_index_t /*node_idx*/, uint32_t shard_idx, const EventLogRebuildingSet& set) { auto it_shard = shardsRebuilding_.find(shard_idx); if (it_shard == shardsRebuilding_.end()) { return; } auto& shard_state = it_shard->second; if (shouldAcknowledgeRebuilding(shard_idx, set)) { // Issue a storage task to write a RebuildingCompleteMetadata marker // locally. Once the task comes back we will write SHARD_ACK_REBUILT to the // event log. writeMarkerForShard(shard_idx, shard_state.version); } else { if (!shard_state.isAuthoritative && shard_state.recoverableShards > 0) { WORKER_STAT_DECR(rebuilding_waiting_for_recoverable_shards); } shard_state.recoverableShards = set.getForShardOffset(shard_idx)->num_recoverable_; } } void RebuildingCoordinator::onShardIsRebuilt(node_index_t donor_node_idx, uint32_t shard_idx, lsn_t version, const EventLogRebuildingSet& set) { const auto* rsi = set.getForShardOffset(shard_idx); if (!rsi) { // We don't care about this shard because we are not rebuilding it or we // already rebuilt it. return; } auto it_shard = shardsRebuilding_.find(shard_idx); ld_check(it_shard != shardsRebuilding_.end()); auto& shard_state = it_shard->second; if (shard_state.version != version) { // This means the donor node sent this event before it received a // SHARD_NEEDS_REBUILD or SHARD_ABORT_REBUILD event. return; } if (donor_node_idx == myNodeId_) { // This is a SHARD_IS_REBUILT message that we sent ourself. We should not // have any running ShardRebuilding at this point. However, this message may // have been sent by this node before it crashed in which case it's possible // that we are just catching up reading the event log and have running // ShardRebuilding state machine. Abort them. // TODO (#13606244): This is not fully correct, probably better to use // local checkpoint instead. abortShardRebuilding(shard_idx); } if (shouldAcknowledgeRebuilding(shard_idx, set)) { // Issue a storage task to write a RebuildingCompleteMetadata marker // locally. Once the task comes back we will write SHARD_ACK_REBUILT to the // event log. writeMarkerForShard(shard_idx, shard_state.version); } if (rsi->donor_progress.empty()) { return; } // We may be able to slide the global timestamp window. trySlideGlobalWindow(shard_idx, set); } bool RebuildingCoordinator::shouldAcknowledgeRebuilding( uint32_t shard_idx, const EventLogRebuildingSet& set) { auto& shard_state = getShardState(shard_idx); if (!shard_state.rebuildingSetContainsMyself) { return false; } auto const* shard = set.getNodeInfo(myNodeId_, shard_idx); if (!shard) { return false; } if (shard->auth_status == AuthoritativeStatus::AUTHORITATIVE_EMPTY) { // Clear any dirty range data since the shard has gone to the empty // state. We'll persist this change when we write the rebuilding complete // marker which could be only after processing a SHARD_UNDRAIN. dirtyShards_.erase(shard_idx); if (shard->drain) { ld_info("Not ready to ack rebuilding of shard %u with version %s, " "rebuilding set %s because this shard is drained. Write a " "SHARD_UNDRAIN message to allow this shard to ack rebuilding and " "take writes again.", shard_idx, lsn_to_string(shard_state.version).c_str(), shard_state.rebuildingSet->describe().c_str()); shard_state.waitingForUndrainStat.assign( getStats(), &PerShardStats::shard_waiting_for_undrain, shard_idx); return false; } return true; } if (shard->donors_remaining.empty()) { // Dirty shards are always authoritatative. // Ack once rebuilt authoritatively or the data necessary to // rebuild authoritatively has been marked unrecoverable. auto const* shard_rebuilding_info = set.getForShardOffset(shard_idx); ld_check(shard_rebuilding_info != nullptr); if (!shard->dc_dirty_ranges.empty() && shard->auth_status == AuthoritativeStatus::FULLY_AUTHORITATIVE && shard_rebuilding_info != nullptr && shard_rebuilding_info->num_recoverable_ == 0) { ld_check(!shard->drain); return true; } ld_info("Rebuilding of my shard %u completed non authoritatively so not " "acking. Rebuilding can be acked once all shards in the " "rebuilding set are marked unrecoverable or enough shards in the " "rebuilding set come back with their data intact.", shard_idx); } return false; } void RebuildingCoordinator::onRetrievedPlanForLog( logid_t log, const uint32_t shard_idx, RebuildingPlanner::LogPlan log_plan, bool is_authoritative, lsn_t version) { ld_assert(shardsRebuilding_.find(shard_idx) != shardsRebuilding_.end()); auto& shard_state = getShardState(shard_idx); ld_check(version == shard_state.version); ld_check(shard_state.waitingForMorePlans); ld_check(shard_state.shardRebuilding == nullptr); ld_check(!shard_state.logsWithPlan.count(log)); if (!is_authoritative && shard_state.isAuthoritative && shard_state.recoverableShards > 0) { WORKER_STAT_INCR(rebuilding_waiting_for_recoverable_shards); } shard_state.isAuthoritative &= is_authoritative; if (log_plan.empty()) { // We don't need to rebuild this log because none of its epochs' nodesets // intersect with the rebuliding set. } else { // TODO(T15517759): Because we are not using Flexible Log Sharding yet, all // plans should be for `shard_idx`. ld_check(log_plan.size() == 1); auto it_plan = log_plan.find(shard_idx); ld_check(it_plan != log_plan.end()); ld_check(it_plan->second); ld_check(!it_plan->second->epochsToRead.empty()); shard_state.logsWithPlan.emplace(log, std::move(it_plan->second)); } } void RebuildingCoordinator::onLogsEnumerated( uint32_t shard_idx, lsn_t version, std::chrono::milliseconds max_rebuild_by_retention_backlog) { ld_info("All plans for logs were retrieved for shard %u in version %s. " "Planning stage requested a delay of %ld ms", shard_idx, lsn_to_string(version).c_str(), max_rebuild_by_retention_backlog.count()); auto& shard_state = getShardState(shard_idx); ld_check(version == shard_state.version); ld_check(shard_state.waitingForMorePlans); ld_check(shard_state.max_rebuild_by_retention_backlog == std::chrono::milliseconds::zero()); shard_state.max_rebuild_by_retention_backlog = max_rebuild_by_retention_backlog; } void RebuildingCoordinator::onFinishedRetrievingPlans(uint32_t shard_idx, lsn_t version) { ld_info("All plans for logs were retrieved for shard %u in version %s", shard_idx, lsn_to_string(version).c_str()); auto& shard_state = getShardState(shard_idx); ld_check(version == shard_state.version); ld_check(shard_state.waitingForMorePlans); shard_state.waitingForMorePlans = 0; // Remove logs that are not in config anymore. auto config = config_->get(); for (auto it = shard_state.logsWithPlan.begin(); it != shard_state.logsWithPlan.end();) { if (!config->getLogGroupByIDShared(it->first)) { it = shard_state.logsWithPlan.erase(it); } else { ++it; } } if (shard_state.logsWithPlan.empty()) { ld_info("Got empty rebuild plan for shard %u with rebuilding set: %s", shard_idx, shard_state.rebuildingSet->describe().c_str()); onShardRebuildingComplete(shard_idx); } else { ld_info("Got rebuilding plan (%lu logs) for shard %u, starting " "rebuilding. Rebuilding set: %s", shard_state.logsWithPlan.size(), shard_idx, shard_state.rebuildingSet->describe().c_str()); shard_state.shardRebuilding = createShardRebuilding(shard_idx, shard_state.version, shard_state.restartVersion, shard_state.rebuildingSet, rebuildingSettings_); shard_state.shardRebuilding->advanceGlobalWindow( shard_state.globalWindowEnd); shard_state.shardRebuilding->start(std::move(shard_state.logsWithPlan)); } } void RebuildingCoordinator::onShardUndrain(node_index_t node_idx, uint32_t shard_idx, const EventLogRebuildingSet& set) { if (node_idx != getMyNodeID()) { // We don't care about this event if it's not for this node. return; } ShardID shard(node_idx, shard_idx); const bool shard_is_rebuilding = shardsRebuilding_.count(shard_idx) != 0; if (!shard_is_rebuilding || shardsRebuilding_[shard_idx].rebuildingSet->shards.count(shard) == 0) { ld_error( "Received SHARD_UNDRAIN for shard %u with node_idx=%u but %u " "is not in the rebuilding set %s. Ignoring.", shard_idx, node_idx, node_idx, shard_is_rebuilding ? shardsRebuilding_[shard_idx].rebuildingSet->describe().c_str() : "{}"); return; } auto& shard_state = shardsRebuilding_[shard_idx]; // node_idx is in the rebuilding set && node_idx == getMyNodeID(), so this // should be true. ld_check(shard_state.rebuildingSetContainsMyself); if (myShardHasDataIntact(shard_idx)) { if (myShardIsDirty(shard_idx)) { // We still have dirty ranges and so must complete a time ranged rebuild. auto ds_kv = dirtyShards_.find(shard_idx); restartForMyShard(shard_idx, 0, &ds_kv->second); } else { // We just requested to cancel the ongoing drain on this node, and this // node has its data intact. This means we can simply abort rebuilding. abortForMyShard(shard_idx, shard_state.version, set.getNodeInfo(myNodeId_, shard_idx), "undrain and data is intact"); } return; } // Marking the shard as undrained may make it possible to ack rebuilding, // check that. if (shouldAcknowledgeRebuilding(shard_idx, set)) { // Issue a storage task to write a RebuildingCompleteMetadata marker // locally. Once the task comes back we will write SHARD_ACK_REBUILT to the // event log. writeMarkerForShard(shard_idx, shard_state.version); } } void RebuildingCoordinator::onShardAckRebuilt(node_index_t node_idx, uint32_t shard_idx, lsn_t version) { auto it_shard = shardsRebuilding_.find(shard_idx); if (it_shard == shardsRebuilding_.end()) { // We don't care about this shard because we are not rebuilding it or we // already rebuilt it. return; } auto& shard_state = it_shard->second; if (shard_state.version != version) { // This means the node sent this event before it could received a // SHARD_NEEDS_REBUILD event for the same shard. return; } ShardID shard(node_idx, shard_idx); if (shard_state.rebuildingSet->shards.find(shard) == shard_state.rebuildingSet->shards.end()) { ld_error("Received SHARD_ACK_REBUILT for shard %u with node_idx=%u, " "version=%s but %u is not in the rebuilding set %s. Ignoring.", shard_idx, node_idx, lsn_to_string(version).c_str(), node_idx, shard_state.rebuildingSet->describe().c_str()); return; } auto rebuildingSet = std::make_shared<RebuildingSet>(*shard_state.rebuildingSet); rebuildingSet->shards.erase(shard); shard_state.rebuildingSet = rebuildingSet; if (rebuildingSet->shards.empty()) { abortShardRebuilding(shard_idx); shardsRebuilding_.erase(it_shard); } else if (node_idx == myNodeId_) { // Decrement stat rebuilding_set_contains_myself after getting our own ack, // without waiting for other rebuilding nodes to ack. ld_check(shard_state.rebuildingSetContainsMyself); shard_state.rebuildingSetContainsMyselfStat.reset(); } } void RebuildingCoordinator::onEventLogTrimmed(lsn_t hi) { // The event log was trimmed. If there are active shard rebuildings, this // means we were reading a backlog in the event log and these rebuildings // actually completed earlier, so we should just abort them all. for (auto& s : shardsRebuilding_) { auto& shard_state = s.second; ld_check(shard_state.version <= hi); abortShardRebuilding(s.first); } shardsRebuilding_.clear(); } void RebuildingCoordinator::onUpdate(const EventLogRebuildingSet& set, const EventLogRecord* delta, lsn_t version) { if (shuttingDown_) { return; } last_seen_event_log_version_ = version; if (first_update_) { // The EventLog RSM releases its first update once it has caught up (read // the tail LSN that was discovered upon subscribing to the event log). Now // that we have processed something aproximating the current state of the // cluster, emit SHARD_NEEDS_REBUILD events for any shards that were left // dirty by an unsafe shutdown. first_update_ = false; publishDirtyShards(set); } if (!delta) { // We don't have a delta, just restart all rebuildings with the new // rebuilding set. for (auto& shard : set.getRebuildingShards()) { scheduleRestartForShard(shard.first); } return; } switch (delta->getType()) { case EventType::SHARD_NEEDS_REBUILD: { const auto ptr = static_cast<const SHARD_NEEDS_REBUILD_Event*>(delta); scheduleRestartForShard(ptr->header.shardIdx); } break; case EventType::SHARD_ABORT_REBUILD: { const auto ptr = static_cast<const SHARD_ABORT_REBUILD_Event*>(delta); scheduleRestartForShard(ptr->header.shardIdx); } break; case EventType::SHARD_IS_REBUILT: { const auto ptr = static_cast<const SHARD_IS_REBUILT_Event*>(delta); if (!restartIsScheduledForShard(ptr->header.shardIdx)) { onShardIsRebuilt(ptr->header.donorNodeIdx, ptr->header.shardIdx, ptr->header.version, set); } } break; case EventType::SHARD_DONOR_PROGRESS: { const auto ptr = static_cast<const SHARD_DONOR_PROGRESS_Event*>(delta); if (!restartIsScheduledForShard(ptr->header.shardIdx)) { RecordTimestamp next_ts( std::chrono::milliseconds(ptr->header.nextTimestamp)); onShardDonorProgress(ptr->header.donorNodeIdx, ptr->header.shardIdx, next_ts, ptr->header.version, set); } } break; case EventType::SHARD_ACK_REBUILT: { const auto ptr = static_cast<const SHARD_ACK_REBUILT_Event*>(delta); if (!restartIsScheduledForShard(ptr->header.shardIdx)) { onShardAckRebuilt( ptr->header.nodeIdx, ptr->header.shardIdx, ptr->header.version); } } break; case EventType::SHARD_UNDRAIN: { const auto ptr = static_cast<const SHARD_UNDRAIN_Event*>(delta); if (!restartIsScheduledForShard(ptr->header.shardIdx)) { onShardUndrain(ptr->header.nodeIdx, ptr->header.shardIdx, set); } } break; case EventType::SHARD_UNRECOVERABLE: { const auto ptr = static_cast<const SHARD_UNRECOVERABLE_Event*>(delta); if (!restartIsScheduledForShard(ptr->header.shardIdx)) { onShardMarkUnrecoverable( ptr->header.nodeIdx, ptr->header.shardIdx, set); } } break; default: // We don't care about any other event. break; } } void RebuildingCoordinator::publishDirtyShards( const EventLogRebuildingSet& set) { if (!rebuildingSettings_->rebuild_dirty_shards) { ld_info("Publishing dirty shard state to the event log is disabled."); return; } ld_info("Publishing dirty shards."); for (auto& ds_kv : dirtyShards_) { auto shard_idx = ds_kv.first; if (!myShardHasDataIntact(shard_idx)) { // Action should already have been taken to schedule a full // rebuild of this shard. continue; } ld_check(!ds_kv.second.empty()); auto info = set.getNodeInfo(myNodeId_, shard_idx); if (info) { // If rebuilding completed while this node was down, the // dirty state is no longer relevant. We should have already // scheduled a task to ack the rebuild. if (info->auth_status == AuthoritativeStatus::AUTHORITATIVE_EMPTY) { continue; } // If a drain is active, we ignore dirty state and allow // the drain of all data to proceed. Any rebuilding range // data will be cleared once we transition to AUTHORITATIVE_EMTPY. // If the drain is cancelled before completion, the non-empty // range data will cause us to perform a ranged rebuild. if (info->drain) { ld_info("Shard %u: Draining. Not publishing dirty state: %s", shard_idx, toString(info->dc_dirty_ranges).c_str()); if (info->mode == RebuildingMode::RELOCATE) { // Convert to a RESTORE drain since we are missing some // of our data. This is required unless/until we improve // the donor SCD filter to understand dirty ranges. ld_info( "Shard %u: Converting drain from RELOCATE to RESTORE", shard_idx); restartForMyShard(shard_idx, 0); } continue; } // If the time ranges all match, the cluster is already performing // the desired rebuild operation. if (info->dc_dirty_ranges == ds_kv.second.getDCDirtyRanges()) { ld_info("Shard %u: Current dirty ranges already published: %s", shard_idx, toString(info->dc_dirty_ranges).c_str()); continue; } } restartForMyShard(shard_idx, 0, &ds_kv.second); } } void RebuildingCoordinator::onDirtyStateChanged() { dirtyShards_.clear(); populateDirtyShardCache(dirtyShards_); publishDirtyShards(event_log_->getCurrentRebuildingSet()); } lsn_t RebuildingCoordinator::getLastSeenEventLogVersion() const { return last_seen_event_log_version_; } RebuildingCoordinator::ShardState& RebuildingCoordinator::getShardState(uint32_t shard_idx) { ld_check(shardsRebuilding_.find(shard_idx) != shardsRebuilding_.end()); return shardsRebuilding_[shard_idx]; } const RebuildingCoordinator::ShardState& RebuildingCoordinator::getShardState(uint32_t shard_idx) const { const auto it = shardsRebuilding_.find(shard_idx); ld_check(it != shardsRebuilding_.end()); return it->second; } void RebuildingCoordinator::abortForMyShard( uint32_t shard, lsn_t version, const EventLogRebuildingSet::NodeInfo* node_info, const char* reason) { auto ds_kv = dirtyShards_.find(shard); if (ds_kv != dirtyShards_.end()) { ld_info("Request to abort rebuilding of my shard %u because: %s. " "But shard is dirty. Downgrading to time ranged rebuild.", shard, reason); ld_info( "EventLogRebuildingSet NodeInfo: %s", node_info->toString().c_str()); ld_info("Local dirty ranges: %s", ds_kv->second.toString().c_str()); ld_check(node_info); if (node_info && ds_kv->second.getDCDirtyRanges() == node_info->dc_dirty_ranges) { ld_info("Cluster already rebuilding the correct dirty ranges for " "my shard %u. Converting abort into no-op.", shard); } else { restartForMyShard(shard, 0, &ds_kv->second); } return; } ld_info("Aborting rebuilding of my shard %u because: %s.", shard, reason); auto event = std::make_unique<SHARD_ABORT_REBUILD_Event>(myNodeId_, shard, version); writer_->writeEvent(std::move(event)); } void RebuildingCoordinator::restartForMyShard(uint32_t shard, SHARD_NEEDS_REBUILD_flags_t f, RebuildingRangesMetadata* rrm, lsn_t conditional_version) { if (f & SHARD_NEEDS_REBUILD_Header::CONDITIONAL_ON_VERSION) { ld_check(conditional_version != LSN_INVALID); } if (!rebuildingSettings_->allow_conditional_rebuilding_restarts) { // TODO(T22614431): conditional restart of rebuilding is gated as some // clients that run the EventLogStateMachine may be too old. It is meant to // be enabled by default and this logic removed once all clients are // updated. conditional_version = LSN_INVALID; f &= ~SHARD_NEEDS_REBUILD_Header::CONDITIONAL_ON_VERSION; } std::string source = "N" + std::to_string(myNodeId_); auto event = std::make_unique<SHARD_NEEDS_REBUILD_Event>( SHARD_NEEDS_REBUILD_Header{myNodeId_, shard, source, "RebuildingCoordinator", f, conditional_version}, rrm); writer_->writeEvent(std::move(event)); } void RebuildingCoordinator::markMyShardUnrecoverable(uint32_t shard) { auto event = std::make_unique<SHARD_UNRECOVERABLE_Event>(myNodeId_, shard); writer_->writeEvent(std::move(event)); } void RebuildingCoordinator::notifyShardRebuilt(uint32_t shard, lsn_t version, bool is_authoritative) { auto& s_state = getShardState(shard); ld_check(s_state.participating); ld_check(s_state.logsWithPlan.empty()); auto event = std::make_unique<SHARD_IS_REBUILT_Event>( myNodeId_, shard, version, is_authoritative ? 0 : SHARD_IS_REBUILT_Header::NON_AUTHORITATIVE); writer_->writeEvent(std::move(event)); } void RebuildingCoordinator::notifyAckMyShardRebuilt(uint32_t shard, lsn_t version) { auto event = std::make_unique<SHARD_ACK_REBUILT_Event>(myNodeId_, shard, version); writer_->writeEvent(std::move(event)); dirtyShards_.erase(shard); processor_->markShardClean(shard); } void RebuildingCoordinator::notifyShardDonorProgress(uint32_t shard, RecordTimestamp next_ts, lsn_t version) { if (rebuildingSettings_->global_window == RecordTimestamp::duration::max()) { // Don't bother sending SHARD_DONOR_PROGRESS if we are not using a global // window. // This will probably cause rebuilding to get stuck if global window // is enabled while a rebuilding is running. return; } // TODO (#T24665001): Only write an event if next_ts moved sufficiently far // forward, and add "IfNeeded" to this method's name. In particular, don't // write if next_ts moved back, which is possible with rebuilding v2. auto event = std::make_unique<SHARD_DONOR_PROGRESS_Event>( myNodeId_, shard, next_ts.toMilliseconds().count(), version); writer_->writeEvent(std::move(event)); } bool RebuildingCoordinator::myShardHasDataIntact(uint32_t shard) const { LocalLogStore* store = shardedStore_->getByIndex(shard); return !processor_->isDataMissingFromShard(shard) && store->acceptingWrites() != E::DISABLED; } bool RebuildingCoordinator::myShardIsDirty(uint32_t shard) const { auto ds_kv = dirtyShards_.find(shard); return ds_kv != dirtyShards_.end(); } bool RebuildingCoordinator::shouldMarkMyShardUnrecoverable( uint32_t shard) const { LocalLogStore* store = shardedStore_->getByIndex(shard); // If the shard does not have a marker but is available, it means it has no // data. return processor_->isDataMissingFromShard(shard) && store->acceptingWrites() != E::DISABLED; } StatsHolder* RebuildingCoordinator::getStats() { if (Worker::onThisThread(false)) { return Worker::stats(); } else { // We are shutting down. return nullptr; } } size_t RebuildingCoordinator::numShards() { return shardedStore_->numShards(); } void RebuildingCoordinator::subscribeToEventLog() { auto cb = [&](const EventLogRebuildingSet& set, const EventLogRecord* delta, lsn_t version) { ld_check(Worker::onThisThread()->idx_ == my_worker_id_); onUpdate(set, delta, version); }; ld_check(event_log_); handle_ = event_log_->subscribe(cb); ld_info("Subscribed to EventLog"); } node_index_t RebuildingCoordinator::getMyNodeID() { auto config = config_->get(); return config->serverConfig()->getMyNodeID().index(); } void RebuildingCoordinator::getDebugInfo( InfoShardsRebuildingTable& table) const { for (auto& s : shardsRebuilding_) { auto& shard_state = s.second; auto nLogsWaitingForPlan = (shard_state.planner ? shard_state.planner->getNumRemainingLogs() : 0); table.next() .set<0>(s.first) .set<1>(shard_state.rebuildingSet->describe( std::numeric_limits<size_t>::max())) .set<2>(shard_state.version) .set<3>(shard_state.globalWindowEnd.toMilliseconds()) .set<5>(nLogsWaitingForPlan) .set<13>(shard_state.participating); if (shard_state.shardRebuilding != nullptr) { shard_state.shardRebuilding->getDebugInfo(table); } } } RecordTimestamp RebuildingCoordinator::getGlobalWindowEnd(uint32_t shard) const { return getShardState(shard).globalWindowEnd; } std::set<uint32_t> RebuildingCoordinator::getLocalShardsRebuilding() { std::set<uint32_t> res; for (auto& s : shardsRebuilding_) { auto& nodes = s.second.rebuildingSet->shards; if (nodes.find(ShardID(myNodeId_, s.first)) != nodes.end()) { res.insert(s.first); } } return res; } }} // namespace facebook::logdevice
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
284b177c88c405eb1a60f667dee94a2ef9c839d5
ed999b931c8a8ebfffa6b727b4e8e0d6051af748
/include/Action.h
b7b4a6b3b9c7dbeaeac15b413de3a1271c571c8d
[ "MIT" ]
permissive
V4570/scheduler
483aa952088aca8e32194e5783e9f581985d6b81
80f3a90b508561b6c3e860b43624d8a9a3b6a450
refs/heads/master
2023-07-18T19:46:14.388089
2021-09-18T15:43:58
2021-09-18T15:43:58
367,954,322
0
0
null
2021-09-18T15:43:04
2021-05-16T18:14:01
C++
UTF-8
C++
false
false
1,348
h
#ifndef ACTION_H #define ACTION_H #include <string> #include <vector> #include "Parameter.h" #include "Precondition.h" #include "Effect.h" #include "Fact.h" using namespace std; class Action { public: Action(); Action (string); Parameter *getParameter (string); int getParameterPosition (string); bool addParameter(string); int getEffectsCount () {return effects.size();} Effect *getEffect (int i) {return effects[i];} int getPrecsCount () {return precs.size();} Precondition *getPrec (int i); string getName(){return name;} string toString (); void addPrecondition (Precondition *p) {precs.push_back(p);} void addEffect (Effect *p) {effects.push_back(p);} bool operator== (const Action &a) {return this->name==a.name;} vector<vector<Parameter>> isApplicable( vector <Rigid> &, vector <Fact> &) ; vector<vector<Parameter>> isApplicable(int, vector <Rigid> &, vector <Fact> &,vector <Parameter>) ; int getParameterCount() {return parameters.size();} Parameter getParameter (int i) {return parameters[i];} protected: private: string name; vector <Parameter> parameters; vector <Precondition *> precs; vector <Effect *> effects; }; #endif // ACTION_H
[ "vasilis.tos@gmail.com" ]
vasilis.tos@gmail.com
cbff1c1984a9d588bbcf792f0e2923b25958dc37
03cde7fe6f0e29cc8da8ff5d77054ba6cf21203d
/objet3d/Facet.cpp
850638ff33ae46c93e838a8d19a134a18274a900
[]
no_license
vidma/snowman-game-3d
a0263295014819868bbb76fadaa6d63ccd19c1ae
53803943fd53818667aee9b70773db2a7255207f
refs/heads/master
2021-01-22T02:40:52.493421
2010-04-02T12:11:50
2010-04-02T12:11:50
541,793
1
0
null
null
null
null
ISO-8859-1
C++
false
false
7,282
cpp
#include "Facet.h" #include "Error.h" #include <GL/gl.h> #include <iostream> #include "Soup.h" #include "UtilGL.h" #include <math.h> using namespace std; using namespace prog3d; /** Tableau de facettes */ void VFacet::draw() { ItVFacet itf; if (drawMode & DRAW_GRID) { glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1,1); } for(itf=begin();itf!=end();itf++) { (*itf)->setDrawMode(drawMode); (*itf)->draw(); } if (drawMode & DRAW_GRID) { glPushAttrib(GL_LIGHTING_BIT); glDisable(GL_POLYGON_OFFSET_FILL); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); glDisable(GL_LIGHTING); glColor3f(0.0,0.0,0.0); glLineWidth(2.0); for(itf=begin();itf!=end();itf++) { (*itf)->draw(); } glLineWidth(1.0); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glPopAttrib(); } } void VFacet::drawNormal(float k) { ItVFacet itf; for(itf=begin();itf!=end();itf++) { (*itf)->drawNormal(k); } } void VFacet::setDrawMode(unsigned int mode) { drawMode=mode; } void VFacet::computeNormal() { ItVFacet itf; for(itf=begin();itf!=end();itf++) { (*itf)->computeNormal(); } } /** Les facettes */ Facet::~Facet() { vv.clear(); // !!!!! do not delete the vertices in vv (can be shared vertices) } void Facet::print(const string &mesg) { cout << "Facet " << mesg << " =("; for(int i=0;i<nbVertex();i++) { cout << vv[i]->point(); } cout << ")" << endl; } void Facet::triangulate() { if (nbVertex()>3) { Vertex *s0=*(vertexBegin()); ItVVertex i=vertexBegin()+2; Facet *f; do { f=creator()->createFacet(); f->addVertex(s0); f->addVertex(*i); f->addVertex(*(i+1)); i++; } while ((i+1)!=vertexEnd()); vv.erase(vertexBegin()+3,vertexEnd()); } } bool Facet::isEmpty() const { return (vv.size()==0); } int Facet::nbVertex() const { return vv.size(); } void Facet::setNormal(const Vector3d &v) { n=v; } void Facet::setDrawMode(unsigned int mode) { drawMode=mode; } void Facet::clearVVertex() { vv.clear(); } void Facet::clearVNormal() { vn.clear(); } void Facet::clear() { vv.clear(); vn.clear(); } Facet::Facet() { vv.clear(); vn.clear(); drawMode = NORMAL_VERTEX | DRAW_FILL; } Facet::Facet(const Point3d &a,const Vector3d &n) { vv.clear(); vn.clear(); this->a=a; this->n=n; drawMode = NORMAL_VERTEX | DRAW_FILL; } Vertex *Facet::createVertex(const Point3d &p) { Vertex *v=new Vertex(); v->setCreator(this->creator()); v->setPoint(p); addVertex(v); return v; } ItVVertex Facet::vertexBegin() { return vv.begin(); } ItVVertex Facet::vertexEnd() { return vv.end(); } void Facet::addVertex(Vertex *v) { vv.push_back(v); } const Vector3d &Facet::normal() const { return n; } Vector3d *Facet::getNormal(int i) const { return vn[i]; } Vertex *Facet::getVertex(unsigned int i) const { return vv[i]; } const Point3d &Facet::point(unsigned int i) const { return vv[i]->point(); } VVertex &Facet::getAllVertex() { return vv; } void Facet::addNormal(Vector3d *v) { vn.push_back(v); } void Facet::computeNormal() { Point3d s1; Point3d s2; Point3d s3; double dist=0; ItVVertex it1=vv.begin(); ItVVertex it2=vv.begin()+1; ItVVertex it3=vv.begin()+2; bool stop=false; while ((dist<1e-05) && !stop) { if (it3!=vv.end()) { s1=(*(it1))->point(); s2=(*(it2))->point(); s3=(*(it3++))->point(); Vector3d v1(s1,s2); Vector3d v2(s2,s3); n.wedge(v1,v2); dist=n.length(); if (it3==vv.end()) { it2++; if (it2==vv.end()) { it1++; it2=it1+1; } it3=it2+1; } } else { stop=true; //throw Error("Normal problem",__LINE__,__FILE__); } } if (stop) n.set(0,0,0); else n.scale(1.0/dist); } void Facet::draw() { ItVVertex itv; glBegin((drawMode & DRAW_FILL)?GL_POLYGON:GL_LINE_LOOP); int k=0; for(itv=vv.begin();itv!=vv.end();itv++) { Vertex *v=*itv; if (drawMode & NORMAL_FACE) { glNormal3dv(n.dv()); } else if (vn.size()!=0) { glNormal3dv(vn[k]->dv()); k++; } else { glNormal3dv(v->normal().dv()); } glVertex3dv(v->point().dv()); } glEnd(); } const Vertex &Facet::vertex(unsigned int i) const { return *(vv[i]); } void Facet::drawNormal(float c) { ItVVertex itv; int k=0; for(itv=vv.begin();itv!=vv.end();itv++) { Vertex *v=*itv; Point3d p=v->point(); Vector3d u; if (drawMode & NORMAL_FACE) { u=n; } else if (vn.size()!=0) { u=*vn[k]; k++; } else { u=v->normal(); } v->point().drawTo(p+c*u); } } ESigne Facet::signe(Vertex *v) const { return signe(v->point()); } void Facet::erase(ItVVertex v) { vv.erase(v); } /// un peu pas clair : ajoute la facette non vide en éliminant les arêtes trop petites void AFacet::addEndValidate(Facet *f) { if (!f->isEmpty()) { ItVVertex new_s=f->vertexBegin()+1; ItVVertex old_s=f->vertexBegin(); Vector3d u; while (new_s!=f->vertexEnd()) { u.setVector((*old_s)->point(),(*(new_s))->point()); if (u.length2()<1e-5) {f->erase(new_s);} else old_s++; new_s=old_s+1; } old_s=f->vertexEnd()-1; new_s=f->vertexBegin(); u.setVector((*old_s)->point(),(*(new_s))->point()); if (u.length2()<1e-5) {f->erase(new_s);} if (f->nbVertex()>2) { addEnd(*f); } } } ESigne Facet::signe(const Point3d &p) const { /// méthodes utiles : /// - point(0) : vous donnera un point de la face /// - normal() : vous donnera la normale à la face /// - v1.dot(v2) : produit scalaire entre 2 Vector3d (ou Point3d) /// - Vector3d v(p1,p2) ou v.setVector(p1,p2) : construit v par p2-p1 ESigne res=MOINS; return res; } /// Donne le point d'intersection Point3d Facet::intersection(const Point3d &p1,const Point3d &p2) const { /// il suffit de résoudre AI.n=0 (plan (A,n)) et I=p1+k*p1p2 (droite (p1,p2)) /// - point(0) : vous donne le Point3d de la facette /// - normal() : vous donne la normale de la facette /// - on peut utiliser les opérateurs sur les Point3d et Vector3d. Exemple : p=a+k*u (avec a,p:Point3d et u:Vector3d) /// - u.setVector(p1,p2) : u= le vecteur p1p2 /// - u1.dot(u2) : produit scalaire Point3d res; /* */ return res; } /// coupe la facette selon f1 void Facet::cut(const Facet &f1,Facet *moins,Facet *plus) const { /// nbVertex() : nombre de sommets /// v=getVertex(i) : donne le sommet numéro i (pointeur), i dans [0..nbVertex()-1] /// v->point() : donne le Point3d du sommet v /// la création d'un nouveau sommet (sommet d'intersection) se fera par v=new Vertex(un Point3d) (memory leak, mais tant pis pour simplifier) /// moins->addVertex(v) : ajoute le sommet v (pointeur) à la facette moins plus->clear();moins->clear(); // initialisation à vide /* ESigne sgn_old,sgn_new; Vertex *s_old,*s_new; Point3d p_inter; */ moins->setNormal(normal());plus->setNormal(normal()); // les normales sont les mêmes que la normale de la facette coupée (évite de recalculer et les erreurs numériques) }
[ "vidmantas.zemleris@gmail.com" ]
vidmantas.zemleris@gmail.com
c5cfd70b17d606c488a9471a2e18042b93d6e588
445149290202ae1d383f8686cf80f142d6202ff8
/include/hermes/VM/Runtime.h
21339e4f8e8ae7da9815f4ba4bd8432f52f24f04
[ "MIT" ]
permissive
Jorgezz/hermes
7bacfdd96666549a5dbd634a1cc73fb32cb83164
cf9aab23399bdf6b3958653823d90f7d5b367c86
refs/heads/master
2023-02-07T05:42:31.966303
2020-12-19T02:14:35
2020-12-19T02:15:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
67,050
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifndef HERMES_VM_RUNTIME_H #define HERMES_VM_RUNTIME_H #include "hermes/Public/DebuggerTypes.h" #include "hermes/Public/RuntimeConfig.h" #include "hermes/Support/Compiler.h" #include "hermes/Support/ErrorHandling.h" #include "hermes/VM/AllocOptions.h" #include "hermes/VM/AllocResult.h" #include "hermes/VM/BasicBlockExecutionInfo.h" #include "hermes/VM/CallResult.h" #include "hermes/VM/Casting.h" #include "hermes/VM/Debugger/Debugger.h" #include "hermes/VM/Deserializer.h" #include "hermes/VM/GC.h" #include "hermes/VM/Handle-inline.h" #include "hermes/VM/HandleRootOwner-inline.h" #include "hermes/VM/IdentifierTable.h" #include "hermes/VM/InternalProperty.h" #include "hermes/VM/InterpreterState.h" #include "hermes/VM/JIT/JIT.h" #include "hermes/VM/PointerBase.h" #include "hermes/VM/Predefined.h" #include "hermes/VM/Profiler.h" #include "hermes/VM/PropertyCache.h" #include "hermes/VM/PropertyDescriptor.h" #include "hermes/VM/RegExpMatch.h" #include "hermes/VM/RuntimeModule.h" #include "hermes/VM/RuntimeStats.h" #include "hermes/VM/Serializer.h" #include "hermes/VM/StackFrame.h" #include "hermes/VM/StackTracesTree.h" #include "hermes/VM/SymbolRegistry.h" #include "hermes/VM/TwineChar16.h" #ifdef HERMESVM_PROFILER_BB #include "hermes/VM/Profiler/InlineCacheProfiler.h" #endif #include "llvh/ADT/DenseMap.h" #include "llvh/ADT/SmallVector.h" #include <atomic> #include <chrono> #include <functional> #include <memory> #include <type_traits> #include <vector> namespace hermes { // Forward declaration. class JSONEmitter; namespace inst { struct Inst; } namespace hbc { class BytecodeModule; struct CompileFlags; } // namespace hbc namespace vm { // External forward declarations. class CodeBlock; class ArrayStorage; class Environment; class Interpreter; class JSObject; class PropertyAccessor; struct RuntimeCommonStorage; struct RuntimeOffsets; class ScopedNativeDepthReducer; class ScopedNativeDepthTracker; class ScopedNativeCallFrame; class SamplingProfiler; class CodeCoverageProfiler; struct MockedEnvironment; #ifdef HERMESVM_PROFILER_BB class JSArray; #endif /// Number of stack words after the top of frame that we always ensure are /// available. This is necessary so we can perform native calls with small /// number of arguments without checking. static const unsigned STACK_RESERVE = 32; /// List of active experiments, corresponding to getVMExperimentFlags(). namespace experiments { enum { Default = 0, MAdviseSequential = 1 << 2, MAdviseRandom = 1 << 3, MAdviseStringsSequential = 1 << 4, MAdviseStringsRandom = 1 << 5, MAdviseStringsWillNeed = 1 << 6, VerifyBytecodeChecksum = 1 << 7, IgnoreMemoryWarnings = 1 << 9, }; /// Set of flags for active VM experiments. using VMExperimentFlags = uint32_t; } // namespace experiments /// Type used to assign object unique integer identifiers. using ObjectID = uint32_t; using DestructionCallback = std::function<void(Runtime *)>; #define PROP_CACHE_IDS(V) V(RegExpLastIndex, Predefined::lastIndex) /// Fixed set of ids used by the property cache in Runtime. enum class PropCacheID { #define V(id, predef) id, PROP_CACHE_IDS(V) #undef V _COUNT }; /// The Runtime encapsulates the entire context of a VM. Multiple instances can /// exist and are completely independent from each other. class Runtime : public HandleRootOwner, public PointerBase, private GCBase::GCCallbacks { public: static std::shared_ptr<Runtime> create(const RuntimeConfig &runtimeConfig); ~Runtime(); /// Add a custom function that will be executed at the start of every garbage /// collection to mark additional GC roots that may not be known to the /// Runtime. void addCustomRootsFunction( std::function<void(GC *, RootAndSlotAcceptor &)> markRootsFn); /// Add a custom function that will be executed sometime during garbage /// collection to mark additional weak GC roots that may not be known to the /// Runtime. void addCustomWeakRootsFunction( std::function<void(GC *, WeakRefAcceptor &)> markRootsFn); /// Make the runtime read from \p env to replay its environment-dependent /// behavior. void setMockedEnvironment(const MockedEnvironment &env); /// Runs the given UTF-8 \p code in a new RuntimeModule as top-level code. /// Note that if compileFlags.lazy is set, the code string will be copied. /// \param sourceURL the location of the source that's being run. /// \param compileFlags Flags controlling compilation. /// \return the status of the execution. CallResult<HermesValue> run( llvh::StringRef code, llvh::StringRef sourceURL, hbc::CompileFlags compileFlags); /// Runs the given UTF-8 \p code in a new RuntimeModule as top-level code. /// \param sourceURL the location of the source that's being run. /// \param compileFlags Flags controlling compilation. /// \return the status of the execution. CallResult<HermesValue> run( std::unique_ptr<Buffer> code, llvh::StringRef sourceURL, hbc::CompileFlags compileFlags); /// Runs the given \p bytecode with the given \p runtimeModuleFlags. The \p /// sourceURL, if not empty, is reported as the file name in backtraces. If \p /// environment is not null, set it as the environment associated with the /// initial JSFunction, which enables local eval. \p thisArg the "this" /// argument to use initially. \p isPersistent indicates whether the created /// runtime module should persist in memory. CallResult<HermesValue> runBytecode( std::shared_ptr<hbc::BCProvider> &&bytecode, RuntimeModuleFlags runtimeModuleFlags, llvh::StringRef sourceURL, Handle<Environment> environment, Handle<> thisArg); /// Runs the given \p bytecode. If \p environment is not null, set it as the /// environment associated with the initial JSFunction, which enables local /// eval. /// Uses global_ as the "this" value initially. /// \p isPersistent indicates whether the created runtime module should /// persist in memory. CallResult<HermesValue> runBytecode( std::shared_ptr<hbc::BCProvider> &&bytecode, RuntimeModuleFlags runtimeModuleFlags, llvh::StringRef sourceURL, Handle<Environment> environment) { heap_.runtimeWillExecute(); return runBytecode( std::move(bytecode), runtimeModuleFlags, sourceURL, environment, Handle<>(&global_)); } ExecutionStatus loadSegment( std::shared_ptr<hbc::BCProvider> &&bytecode, Handle<RequireContext> requireContext, RuntimeModuleFlags flags = {}); /// Runs the internal bytecode. This is called once during initialization. void runInternalBytecode(); /// A convenience function to print an exception to a stream. void printException(llvh::raw_ostream &os, Handle<> valueHandle); /// @name Heap management /// @{ /// Allocate a new cell of the specified size \p size. /// If necessary perform a GC cycle, which may potentially move allocated /// objects. /// The \p fixedSize template argument indicates whether the allocation is for /// a fixed-size cell, which can assumed to be small if true. The /// \p hasFinalizer template argument indicates whether the object /// being allocated will have a finalizer. template <bool fixedSize = true, HasFinalizer hasFinalizer = HasFinalizer::No> void *alloc(uint32_t size); /// Create a fixed size object of type T. /// If necessary perform a GC cycle, which may potentially move /// allocated objects. /// \return a pointer to the newly created object in the GC heap. template < typename T, HasFinalizer hasFinalizer = HasFinalizer::No, LongLived longLived = LongLived::No, class... Args> T *makeAFixed(Args &&... args); /// Create a variable size object of type T and size \p size. /// If necessary perform a GC cycle, which may potentially move /// allocated objects. /// \return a pointer to the newly created object in the GC heap. template < typename T, HasFinalizer hasFinalizer = HasFinalizer::No, LongLived longLived = LongLived::No, class... Args> T *makeAVariable(uint32_t size, Args &&... args); /// Used as a placeholder for places where we should be checking for OOM /// but aren't yet. /// TODO: do something when there is an uncaught exception, e.g. print /// stack traces. template <typename T> T ignoreAllocationFailure(CallResult<T> res); /// Used as a placeholder for places where we should be checking for OOM /// but aren't yet. void ignoreAllocationFailure(ExecutionStatus status); // Inform the VM that TTI has been reached. (In case, for example, the // runtime should change its behavior at that point.) void ttiReached(); /// Force a garbage collection cycle. void collect(std::string cause) { heap_.collect(std::move(cause)); } /// Potentially move the heap if handle sanitization is on. void potentiallyMoveHeap(); using HandleRootOwner::makeHandle; using HandleRootOwner::makeMutableHandle; /// Convenience function to create a Handle from a GCPointer. template <class T> inline Handle<T> makeHandle(const GCPointer<T> &p); /// Convenience function to create a MutableHandle from a GCPointer. template <class T> MutableHandle<T> makeMutableHandle(const GCPointer<T> &p); /// \return the \c StringPrimitive of a predefined string. StringPrimitive *getPredefinedString(Predefined::Str predefined); StringPrimitive *getPredefinedString(Predefined::Sym predefined); /// \return a \c Handle<StringPrimitive> to a predefined string. Handle<StringPrimitive> getPredefinedStringHandle(Predefined::Str predefined); Handle<StringPrimitive> getPredefinedStringHandle(Predefined::Sym predefined); /// \return the \c StringPrimitive given a symbol ID \p id. inline StringPrimitive *getStringPrimFromSymbolID(SymbolID id); /// \return true if a symbol specified by \p id has the same string content /// as a given string primitive \p strPrim. bool symbolEqualsToStringPrim(SymbolID id, StringPrimitive *strPrim); /// A wrapper to facilitate printing the name of a SymbolID to a stream. struct FormatSymbolID { Runtime *const runtime; SymbolID const symbolID; FormatSymbolID(Runtime *runtime, SymbolID symbolID) : runtime(runtime), symbolID(symbolID) {} }; /// Create an object that when serialized to a stream will print the contents /// of a SymbolID. FormatSymbolID formatSymbolID(SymbolID id); GC &getHeap() { return heap_; } /// @} /// Return a pointer to a builtin native function builtin identified by id. /// Unfortunately we can't use the enum here, since we don't want to include /// the builtins header header. inline NativeFunction *getBuiltinNativeFunction(unsigned builtinMethodID); IdentifierTable &getIdentifierTable() { return identifierTable_; } SymbolRegistry &getSymbolRegistry() { return symbolRegistry_; } /// Return a StringPrimitive representation of a single character. The first /// 256 characters are pre-allocated. The rest are allocated every time. Handle<StringPrimitive> getCharacterString(char16_t ch); CodeBlock *getEmptyCodeBlock() const { assert(emptyCodeBlock_ && "Invalid empty code block"); return emptyCodeBlock_; } CodeBlock *getReturnThisCodeBlock() const { assert(returnThisCodeBlock_ && "Invalid return this code block"); return returnThisCodeBlock_; } /// \return the next unique object ID. ObjectID generateNextObjectID() { return ++nextObjectID_; } /// Compute a hash value of a given HermesValue that is guaranteed to /// be stable with a moving GC. It however does not guarantee to be /// a perfect hash for strings. uint64_t gcStableHashHermesValue(Handle<HermesValue> value); /// @name Public VM State /// @{ /// \return the current stack pointer. PinnedHermesValue *getStackPointer() { return stackPointer_; } /// Pop the register stack down to a previously saved stack pointer. inline void popToSavedStackPointer(PinnedHermesValue *stackPointer); /// \return the number of elements in the stack. inline uint32_t getStackLevel() const; /// Return the available stack size (in registers). inline uint32_t availableStackSize() const; /// \return true if there is space to allocate <tt>count + STACK_RESERVE</tt> /// registers. inline bool checkAvailableStack(uint32_t count); /// Allocate stack space for \p registers, but keep it uninitialized. The /// caller should initialize it ASAP. /// \return the new stack pointer. inline PinnedHermesValue *allocUninitializedStack(uint32_t count); /// Allocate stack space for \p registers and initialize them with /// \p initValue. /// See implementation for why this is not inlined. LLVM_ATTRIBUTE_NOINLINE void allocStack(uint32_t count, HermesValue initValue); /// Check whether <tt>count + STACK_RESERVE</tt> stack registers are available /// and allocate \p count registers. /// \param count number of registers to allocate. /// \param initValue initialize the allocated registers with this value. /// \return \c true if allocation was successful. inline bool checkAndAllocStack(uint32_t count, HermesValue initValue); /// Pop the specified number of elements from the stack. inline void popStack(uint32_t count); /// \return the current frame pointer. StackFramePtr getCurrentFrame() { return currentFrame_; } /// Set the current frame pointer to the current top of the stack and return /// it. /// \param topFrame a frame constructed at the top of stack. It must equal /// stackPointer_, but it is more efficient to pass it in if it already /// is in a register. It also provides some additional error checking in /// debug builds, ensuring that the stack hasn't changed unexpectedly. inline void setCurrentFrameToTopOfStack(StackFramePtr topFrame); /// Set the current frame pointer to the current top of the stack and return /// it. /// \return the new value of the current frame pointer. inline StackFramePtr setCurrentFrameToTopOfStack(); /// Restore the stack pointer to the base of the current frame and then /// set the frame pointer to the previous frame. /// \param currentFrame the currentFrame. It must match the value of /// this->currentFrame_, but is more efficient to pass it in assuming it /// already is in a register. It also provides some additional error /// checking in debug builds, ensuring that the stack hasn't changed /// unexpectedly. /// \return the updated value of the current frame pointer. inline StackFramePtr restoreStackAndPreviousFrame(StackFramePtr currentFrame); /// Restore the stack pointer to the base of the current frame and then /// set the frame pointer to the previous frame. /// \return the updated value of the current frame pointer. inline StackFramePtr restoreStackAndPreviousFrame(); /// \return an iterator range that provides access to all stack frames /// starting from the top-most one. inline llvh::iterator_range<StackFrameIterator> getStackFrames(); /// \return an iterator range that provides access to all stack frames /// starting from the top-most one. inline llvh::iterator_range<ConstStackFrameIterator> getStackFrames() const; /// Dump information about all stack frames to \p OS. void dumpCallFrames(llvh::raw_ostream &OS); /// Dump information about all stack frames to llvh::errs(). This is a /// helper method intended to be called from a debugger. void dumpCallFrames(); /// \return `thrownValue`. HermesValue getThrownValue() const { return thrownValue_; } /// Set `thrownValue` to the specified value \p value, `returnValue` to /// empty and \return ExecutionResult::EXCEPTION. ExecutionStatus setThrownValue(HermesValue value); /// Set `thrownValue` to empty. void clearThrownValue(); /// Return a hidden class corresponding to the specified prototype object /// and number of reserved slots. For now we only use the latter. inline Handle<HiddenClass> getHiddenClassForPrototype( JSObject *proto, unsigned reservedSlots); /// Same as above but returns a raw pointer: standard warnings apply! /// TODO: Delete this function once all callers are replaced with /// getHiddenClassForPrototype. inline HiddenClass *getHiddenClassForPrototypeRaw( JSObject *proto, unsigned reservedSlots); /// Return the global object. Handle<JSObject> getGlobal(); /// Return the JIT context. JITContext &getJITContext() { return jitContext_; } /// Returns trailing data for all runtime modules. std::vector<llvh::ArrayRef<uint8_t>> getEpilogues(); /// \return the set of runtime stats. instrumentation::RuntimeStats &getRuntimeStats() { return runtimeStats_; } /// Print the heap and other misc. stats to the given stream. void printHeapStats(llvh::raw_ostream &os); /// Write IO tracking (aka HBC page access) info to the supplied /// stream as JSON. There will only be useful data for RuntimeModules /// backed by mmap'ed bytecode, and there will only be any data at all if /// RuntimeConfig::withTrackIO() has been set, and IO tracking is available on /// the current platform. void getIOTrackingInfoJSON(llvh::raw_ostream &os); #ifndef NDEBUG /// Iterate over all arrays in the heap and print their sizes and capacities. void printArrayCensus(llvh::raw_ostream &os); #endif /// Returns the common storage object. RuntimeCommonStorage *getCommonStorage() { return commonStorage_.get(); } const GCExecTrace &getGCExecTrace() { return getHeap().getGCExecTrace(); } #if defined(HERMES_ENABLE_DEBUGGER) /// Request the interpreter loop to take an asynchronous break at a convenient /// point due to debugger UI request. This may be called from any thread, or a /// signal handler. void triggerDebuggerAsyncBreak( ::facebook::hermes::debugger::AsyncPauseKind kind) { triggerAsyncBreak( kind == ::facebook::hermes::debugger::AsyncPauseKind::Explicit ? AsyncBreakReasonBits::DebuggerExplicit : AsyncBreakReasonBits::DebuggerImplicit); } #endif /// Request the interpreter loop to take an asynchronous break at a convenient /// point due to previous registered timeout. This may be called from any /// thread, or a signal handler. void triggerTimeoutAsyncBreak() { triggerAsyncBreak(AsyncBreakReasonBits::Timeout); } /// Register \p callback which will be called /// during runtime destruction. void registerDestructionCallback(DestructionCallback callback) { destructionCallbacks_.emplace_back(callback); } #ifdef HERMES_ENABLE_DEBUGGER /// Encapsulates useful information about a stack frame, needed by the /// debugger. It requres extra context and cannot be extracted from a /// single frame pointer. struct StackFrameInfo { ConstStackFramePtr frame; bool isGlobal; }; /// Extract \c StackFrameInfo of the specified stack frame. /// \param frameIdx a relative frame index where the top-most frame is 0. /// \return a populated StackFrameInfo, or llvh::None if the frame is invalid. llvh::Optional<StackFrameInfo> stackFrameInfoByIndex(uint32_t frameIdx) const; /// Calculate and \return the offset between the location of the specified /// frame and the start of the stack. This value increases with every nested /// call. uint32_t calcFrameOffset(ConstStackFrameIterator it) const; /// \return the offset between the location of the current frame and the /// start of the stack. This value increases with every nested call. uint32_t getCurrentFrameOffset() const; #endif /// Flag the interpreter that a type error with the specified message must be /// thrown when execution resumes. /// If the message is not a string, it is converted using toString(). LLVM_NODISCARD ExecutionStatus raiseTypeError(Handle<> message); /// Flag the interpreter that a type error must be thrown when execution /// resumes. /// \return ExecutionResult::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseTypeError(const TwineChar16 &msg); /// Flag the interpreter that a type error must be thrown when execution /// resumes. The string thrown concatenates a description of \p value /// with \p msg. /// \return ExecutionResult::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseTypeErrorForValue(Handle<> value, llvh::StringRef msg) { return raiseTypeErrorForValue("", value, msg); } /// Flag the interpreter that a type error must be thrown when execution /// resumes. The string thrown concatenates \p msg1, a description of \p /// value, and \p msg2. \return ExecutionResult::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseTypeErrorForValue( llvh::StringRef msg1, Handle<> value, llvh::StringRef msg2); /// Flag the interpreter that a syntax error must be thrown. /// \return ExecutionStatus::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseSyntaxError(const TwineChar16 &msg); /// Raise a special SyntaxError when attempting to eval when disallowed. LLVM_NODISCARD ExecutionStatus raiseEvalUnsupported(llvh::StringRef code); /// Raise a \c RangeError exception. /// \return ExecutionStatus::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseRangeError(const TwineChar16 &msg); /// Raise a \c ReferenceError exception. /// \return ExecutionStatus::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseReferenceError(const TwineChar16 &msg); /// Raise a \c URIError exception. /// \return ExecutionStatus::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseURIError(const TwineChar16 &msg); enum class StackOverflowKind { // The JS register stack was exhausted. JSRegisterStack, // A limit on the number of native stack frames used in // evaluation, intended to conservatively prevent native stack // overflow, was exceeded. NativeStack, // RuntimeJSONParser has a maximum number of "nesting levels", and // calls raiseStackOverflow if that is exceeded. JSONParser, // JSONStringifyer has the same limit as JSONParser. JSONStringify, }; /// Raise a stack overflow exception. This is special because constructing /// the object must not execute any custom or JavaScript code. The /// argument influences the exception's message, to aid debugging. /// \return ExecutionStatus::EXCEPTION LLVM_NODISCARD ExecutionStatus raiseStackOverflow(StackOverflowKind kind); /// Raise an error for the quit function. This error is not catchable. LLVM_NODISCARD ExecutionStatus raiseQuitError(); /// Raise an error for execution timeout. This error is not catchable. LLVM_NODISCARD ExecutionStatus raiseTimeoutError(); /// Utility function to raise a catchable JS error with \p errMessage. LLVM_NODISCARD ExecutionStatus raiseUncatchableError(Handle<JSObject> prototype, llvh::StringRef errMessage); /// Interpret the current function until it returns or throws and return /// CallResult<HermesValue> or the thrown object in 'thrownObject'. CallResult<HermesValue> interpretFunction(CodeBlock *newCodeBlock); #ifdef HERMES_ENABLE_DEBUGGER /// Single-step the provided function, update the interpreter state. ExecutionStatus stepFunction(InterpreterState &state); #endif /// Inserts an object into the string cycle checking stack. /// \return true if a cycle was found CallResult<bool> insertVisitedObject(Handle<JSObject> obj); /// Removes the last element (which must be obj) from the cycle check stack. /// \param obj the last element, which will be removed. Used for checking /// that invariants aren't violated in debug mode. void removeVisitedObject(Handle<JSObject> obj); /// Like calling JSObject::getNamed, but uses this runtime's property cache. CallResult<PseudoHandle<>> getNamed(Handle<JSObject> obj, PropCacheID id); /// Like calling JSObject::putNamed with the ThrowOnError flag, but uses this /// runtime's property cache. ExecutionStatus putNamedThrowOnError(Handle<JSObject> obj, PropCacheID id, HermesValue hv); /// @} #define RUNTIME_HV_FIELD(name) PinnedHermesValue name{}; #define RUNTIME_HV_FIELD_PROTOTYPE(name) RUNTIME_HV_FIELD(name) #define RUNTIME_HV_FIELD_INSTANCE(name) RUNTIME_HV_FIELD(name) #define RUNTIME_HV_FIELD_RUNTIMEMODULE(name) RUNTIME_HV_FIELD(name) #include "hermes/VM/RuntimeHermesValueFields.def" #undef RUNTIME_HV_FIELD /// Raw pointers to prototypes. JSObject *objectPrototypeRawPtr{}; JSObject *functionPrototypeRawPtr{}; RegExpMatch regExpLastMatch{}; /// Whether to allow eval and Function ctor. const bool enableEval; /// Whether to verify the IR being generated by eval and the Function ctor. const bool verifyEvalIR; /// Whether to optimize the code in the string passed to eval and the Function /// ctor. const bool optimizedEval; #ifdef HERMESVM_PROFILER_OPCODE /// Track the frequency of each opcode in the interpreter. uint32_t opcodeExecuteFrequency[256] = {0}; /// Track time spent of each opcode in the interpreter, in CPU cycles. uint64_t timeSpent[256] = {0}; /// Dump opcode stats to a stream. void dumpOpcodeStats(llvh::raw_ostream &os) const; #endif #if defined(HERMESVM_PROFILER_JSFUNCTION) || defined(HERMESVM_PROFILER_EXTERN) static std::atomic<ProfilerID> nextProfilerId; std::vector<ProfilerFunctionInfo> functionInfo{}; /// Get block's index in functionInfo (creating a new entry if needed). ProfilerID getProfilerID(CodeBlock *block); /// Get profiler info associated with given id or nullptr if the id /// is not associated with any function. const ProfilerFunctionInfo *getProfilerInfo(ProfilerID id); /// Track the maximum size of the stack. uint32_t maxStackLevel = 0; #endif #if defined(HERMESVM_PROFILER_JSFUNCTION) std::vector<ProfilerFunctionEvent> functionEvents{}; /// Total number of opcodes executed by this runtime. uint64_t opcodeCount = 0; /// Dump function profiling stats to stdout. enum class ProfileType{TIME, OPCODES, ALL}; void dumpJSFunctionStats(ProfileType type = ProfileType::ALL); #endif #ifdef HERMESVM_PROFILER_BB BasicBlockExecutionInfo &getBasicBlockExecutionInfo(); /// Dump basic block profile trace to \p OS in json format. void dumpBasicBlockProfileTrace(llvh::raw_ostream &OS); #endif CodeCoverageProfiler &getCodeCoverageProfiler() { return *codeCoverageProfiler_; } #ifdef HERMESVM_PROFILER_NATIVECALL /// Dump statistics about native calls. void dumpNativeCallStats(llvh::raw_ostream &OS); #endif #ifdef HERMES_ENABLE_DEBUGGER Debugger &getDebugger() { return debugger_; } #endif RuntimeModuleList &getRuntimeModules() { return runtimeModuleList_; } bool hasES6Promise() const { return hasES6Promise_; } bool hasES6Proxy() const { return hasES6Proxy_; } bool hasES6Symbol() const { return hasES6Symbol_; } bool hasES6Intl() const { return hasES6Intl_; } bool builtinsAreFrozen() const { return builtinsFrozen_; } bool shouldStabilizeInstructionCount(); experiments::VMExperimentFlags getVMExperimentFlags() const { return vmExperimentFlags_; } // Return a reference to the runtime's CrashManager. inline CrashManager &getCrashManager(); /// Returns a string representation of the JS stack. Does no operations /// that allocate on the JS heap, so safe to use for an out-of-memory /// exception. /// \p ip specifies the the IP of the leaf frame. std::string getCallStackNoAlloc(const Inst *ip); /// \return a string representation of the JS stack without knowing the leaf /// frame ip. Does no operations that allocate on the JS heap, so safe to use /// for an out-of-memory exception. std::string getCallStackNoAlloc() override { return getCallStackNoAlloc(nullptr); } /// Called when various GC events(e.g. collection start/end) happen. void onGCEvent(GCEventKind kind, const std::string &extraInfo) override; #ifdef HERMESVM_SERIALIZE /// Fill the header with current Runtime config void populateHeaderRuntimeConfig(SerializeHeader &header); /// Check if the SerializeHeader read from the file matches Runtime config of /// current run. void checkHeaderRuntimeConfig(SerializeHeader &header) const; /// Serialize the VM state. void serialize(Serializer &s); /// Set the closure function to execute after deserialization. void setSerializeClosure(Handle<JSFunction> function) { serializeClosure = function.getHermesValue(); } HermesValue getSerializeClosure() { return serializeClosure; } #endif #ifdef HERMESVM_PROFILER_BB using ClassId = InlineCacheProfiler::ClassId; /// Get filename, line number, and column number from /// code block and instruction pointer. It returns true if it succeeds. llvh::Optional<std::tuple<std::string, uint32_t, uint32_t>> getIPSourceLocation(const CodeBlock *codeBlock, const Inst *ip); /// Inserts the Hidden class as a root to prevent it from being garbage /// collected. void preventHCGC(HiddenClass *hc); /// Inserts Hidden Classes into InlineCacheProfiler void recordHiddenClass( CodeBlock *codeBlock, const Inst *cacheMissInst, SymbolID symbolID, HiddenClass *objectHiddenClass, HiddenClass *cachedHiddenClass); /// Resolve HiddenClass pointers from its hidden class Id. HiddenClass *resolveHiddenClassId(ClassId classId); /// Dumps inline cache profiler info. void getInlineCacheProfilerInfo(llvh::raw_ostream &ostream); #endif protected: /// Construct a Runtime on the stack. /// NOTE: This should only be used by StackRuntime. All other uses should use /// Runtime::create. explicit Runtime( std::shared_ptr<StorageProvider> provider, const RuntimeConfig &runtimeConfig); /// @} #if defined(HERMESVM_PROFILER_EXTERN) public: #else private: #endif /// Only called internally or by the wrappers used for profiling. CallResult<HermesValue> interpretFunctionImpl(CodeBlock *newCodeBlock); private: /// Called by the GC at the beginning of a collection. This method informs the /// GC of all runtime roots. The \p markLongLived argument /// indicates whether root data structures that contain only /// references to long-lived objects (allocated directly as long lived) /// are required to be scanned. void markRoots(RootAndSlotAcceptorWithNames &acceptor, bool markLongLived) override; /// Called by the GC during collections that may reset weak references. This /// method informs the GC of all runtime weak roots. void markWeakRoots(WeakRootAcceptor &weakAcceptor) override; /// Visits every entry in the identifier table and calls acceptor with /// the entry and its id as arguments. This is intended to be used only for /// snapshots, as it is slow. The function passed as acceptor shouldn't /// perform any heap operations. void visitIdentifiers( const std::function<void(SymbolID, const StringPrimitive *)> &acceptor) override; #ifdef HERMESVM_PROFILER_BB public: #endif /// Convert the given symbol into its UTF-8 string representation. std::string convertSymbolToUTF8(SymbolID id) override; private: /// Prints any statistics maintained in the Runtime about GC to \p /// os. At present, this means the breakdown of markRoots time by /// "phase" within markRoots. void printRuntimeGCStats(JSONEmitter &json) const override; /// \return one higher than the largest symbol in the identifier table. This /// enables the GC to size its internal structures for symbol marking. /// Optionally invoked at the beginning of a garbage collection. virtual unsigned getSymbolsEnd() const override; /// If any symbols are marked by the IdentifierTable, clear that marking. /// Optionally invoked at the beginning of some collections. virtual void unmarkSymbols() override; /// Called by the GC at the end of a collection to free all symbols not set in /// markedSymbols. virtual void freeSymbols(const llvh::BitVector &markedSymbols) override; #ifdef HERMES_SLOW_DEBUG /// \return true if the given symbol is a live entry in the identifier /// table. virtual bool isSymbolLive(SymbolID id) override; /// \return An associated heap cell for the symbol if one exists, null /// otherwise. virtual const void *getStringForSymbol(SymbolID id) override; #endif /// See \c GCCallbacks for details. size_t mallocSize() const override; /// Generate a bytecode buffer that contains a few special functions: /// 0) an empty function that returns undefined. /// 1) a function that returns the global object. static std::unique_ptr<Buffer> generateSpecialRuntimeBytecode(); /// Insert the predefined strings into the IdentifierTable. /// NOTE: this function does not do any allocations in the GC heap, it is safe /// to use at any time in initialization. void initPredefinedStrings(); /// Initialize the \c charStrings_ array with a StringPrimitive for each /// character. void initCharacterStrings(); /// \param methodIndex is the index of the method in the table that lists /// all the builtin methods, which is what we are iterating over. /// \param objectName is the id for the name of the object in the list of the /// predefined strings. /// \param object is the object where the builtin method is defined as a /// property. /// \param methodID is the SymbolID for the name of the method. using ForEachBuiltinCallback = ExecutionStatus( unsigned methodIndex, Predefined::Str objectName, Handle<JSObject> &object, SymbolID methodID); /// Enumerate the builtin methods, and invoke the callback on each method. ExecutionStatus forEachBuiltin( const std::function<ForEachBuiltinCallback> &callback); /// Populate the builtins table by extracting the values from the global /// object. void initBuiltinTable(); /// Walk all the builtin methods, assert that they are not overridden. If they /// are, throw an exception. This will be called at most once, before freezing /// the builtins. ExecutionStatus assertBuiltinsUnmodified(); /// Called after asserting all builtin methods are not overridden, to freeze /// those builtins. This will be called at most once. void freezeBuiltins(); /// The slow path for \c getCharacterString(). This function allocates a new /// string for the passed character \p ch. Handle<StringPrimitive> allocateCharacterString(char16_t ch); /// Add a \c RuntimeModule \p rm to the runtime module list. void addRuntimeModule(RuntimeModule *rm) { runtimeModuleList_.push_back(*rm); } /// Remove a \c RuntimeModule \p rm from the runtime module list. void removeRuntimeModule(RuntimeModule *rm); /// Called by CrashManager on the event of a crash to produce a stream of data /// to crash log. Output should be a JSON object. This is the central point /// for adding calls to further functions which dump specific elements of /// of crash dump data for a Hermes Runtime instance. void crashCallback(int fd); /// Write a JS stack trace as part of a \c crashCallback() run. void crashWriteCallStack(JSONEmitter &json); #ifdef HERMESVM_SERIALIZE void serializeIdentifierTable(Serializer &s); /// Serialize Runtime fields. void serializeRuntimeFields(Serializer &s); /// Deserialize Runtime fields. void deserializeRuntimeFields(Deserializer &d); /// Deserialize the VM state. /// \param inputFile MemoryBuffer to read from. /// \param currentlyInYoung Whether we are allocating from the young gen /// before deserialization starts and should we go back to allocating from the /// young gen after deserialziation. void deserializeImpl(Deserializer &d, bool currentlyInYoung); #endif private: GC heap_; std::vector<std::function<void(GC *, RootAndSlotAcceptor &)>> customMarkRootFuncs_; std::vector<std::function<void(GC *, WeakRefAcceptor &)>> customMarkWeakRootFuncs_; /// All state related to JIT compilation. JITContext jitContext_; /// Set to true if we should enable ES6 Promise. const bool hasES6Promise_; /// Set to true if we should enable ES6 Proxy. const bool hasES6Proxy_; /// Set to true if we should enable ES6 Symbol. const bool hasES6Symbol_; /// Set to true if we should enable ES6 Intl APIs. const bool hasES6Intl_; /// Set to true if we should randomize stack placement etc. const bool shouldRandomizeMemoryLayout_; // Percentage in [0,100] of bytecode we should eagerly read into page cache. const uint8_t bytecodeWarmupPercent_; // Signal-based I/O tracking. Slows down execution. const bool trackIO_; /// This value can be passed to the runtime as flags to test experimental /// features. Each experimental feature decides how to interpret these /// values. Generally each experiment is associated with one or more bits of /// this value. Interpretation of these bits is up to each experiment. /// To add an experiment, populate the VMExperimentFlags enum with additional /// bit values, typically 1 as test and 0 as control. experiments::VMExperimentFlags vmExperimentFlags_{experiments::Default}; friend class GCScope; friend class HandleBase; friend class Interpreter; friend class RuntimeModule; friend class MarkRootsPhaseTimer; friend struct RuntimeOffsets; friend class JITContext; friend class ScopedNativeDepthReducer; friend class ScopedNativeDepthTracker; friend class ScopedNativeCallFrame; class MarkRootsPhaseTimer; /// Whenever we pass through the first phase, we record the current time here, /// so we can calculate the total time after we pass through the last phase. std::chrono::time_point<std::chrono::steady_clock> startOfMarkRoots_; /// The duration of each GC root marking phase is accumulated here. double markRootsPhaseTimes_[static_cast<unsigned>( RootAcceptor::Section::NumSections)] = {}; /// The duration of the all root makring is accumulated here. double totalMarkRootsTime_ = 0.0; /// A global counter that increments and provide unique object IDs. ObjectID nextObjectID_{0}; /// The identifier table. IdentifierTable identifierTable_{}; /// The global symbol registry. SymbolRegistry symbolRegistry_{}; /// Set of runtime statistics. instrumentation::RuntimeStats runtimeStats_; /// Shared location to place native objects required by JSLib std::shared_ptr<RuntimeCommonStorage> commonStorage_; /// Empty code block that returns undefined. /// Owned by specialCodeBlockRuntimeModule_. CodeBlock *emptyCodeBlock_{}; /// Code block that returns the global object. /// Owned by specialCodeBlockRuntimeModule_. CodeBlock *returnThisCodeBlock_{}; /// The runtime module that owns emptyCodeBlock_ and returnThisCodeBlock_. /// We use a raw pointer here because it will be added to runtimeModuleList_, /// and will be freed when Runtime is freed. RuntimeModule *specialCodeBlockRuntimeModule_{}; /// A list of all active runtime modules. Each \c RuntimeModule adds itself /// on construction and removes itself on destruction. RuntimeModuleList runtimeModuleList_{}; /// @name Private VM State /// @{ PinnedHermesValue *registerStack_; PinnedHermesValue *registerStackEnd_; PinnedHermesValue *stackPointer_; /// Bytes of register stack to unmap on destruction. /// When set to zero, the register stack is not allocated /// by the runtime itself. uint32_t registerStackBytesToUnmap_{0}; /// Manages data to be used in the case of a crash. std::shared_ptr<CrashManager> crashMgr_; /// Points to the last register in the callers frame. The current frame (the /// callee frame) starts in the next register and continues up to and /// including \c stackPointer_. StackFramePtr currentFrame_{nullptr}; /// Current depth of native call frames, including recursive interpreter /// calls. unsigned nativeCallFrameDepth_{0}; public: /// A stack overflow exception is thrown when \c nativeCallFrameDepth_ exceeds /// this threshold. static constexpr unsigned MAX_NATIVE_CALL_FRAME_DEPTH = #ifdef HERMES_LIMIT_STACK_DEPTH // UBSAN builds will hit a native stack overflow much earlier, so make // this limit dramatically lower. 30 #elif defined(_MSC_VER) && defined(__clang__) && defined(HERMES_SLOW_DEBUG) 30 #elif defined(_MSC_VER) && defined(HERMES_SLOW_DEBUG) // On windows in dbg mode builds, stack frames are bigger, and a depth // limit of 384 results in a C++ stack overflow in testing. 128 #elif defined(_MSC_VER) && !NDEBUG 192 #else /// This depth limit was originally 256, and we /// increased when an app violated it. The new depth is 128 /// larger. See T46966147 for measurements/calculations indicating /// that this limit should still insulate us from native stack overflow.) 384 #endif ; /// rootClazzes_[i] is a PinnedHermesValue pointing to a hidden class with /// its i first slots pre-reserved. std::array<PinnedHermesValue, InternalProperty::NumInternalProperties + 1> rootClazzes_; /// Cache for property lookups in non-JS code. PropertyCacheEntry fixedPropCache_[(size_t)PropCacheID::_COUNT]; /// StringPrimitive representation of the first 256 characters. /// These are allocated as "long-lived" objects, so they don't need /// to be scanned as roots in young-gen collections. std::vector<PinnedHermesValue> charStrings_{}; /// Pointers to native implementations of builtins. std::vector<NativeFunction *> builtins_{}; /// True if the builtins are all frozen (non-writable, non-configurable). bool builtinsFrozen_{false}; #ifdef HERMESVM_PROFILER_BB BasicBlockExecutionInfo basicBlockExecInfo_; /// Store all inline caching miss information. InlineCacheProfiler inlineCacheProfiler_; #endif /// ScriptIDs to use for new RuntimeModules coming in. facebook::hermes::debugger::ScriptID nextScriptId_{1}; /// Store a key for the function that is executed if a crash occurs. /// This key will be unregistered in the destructor. const CrashManager::CallbackKey crashCallbackKey_; /// Keep a strong reference to the SamplingProfiler so that /// we are sure it's safe to unregisterRuntime in destructor. std::shared_ptr<SamplingProfiler> samplingProfiler_; /// Pointer to the code coverage profiler. const std::unique_ptr<CodeCoverageProfiler> codeCoverageProfiler_; /// A list of callbacks to call before runtime destruction. std::vector<DestructionCallback> destructionCallbacks_; /// Bit flags for async break request reasons. enum class AsyncBreakReasonBits : uint8_t { DebuggerExplicit = 0x1, DebuggerImplicit = 0x2, Timeout = 0x4, }; /// An atomic flag set when an async pause is requested. /// It is a bits flag with each bit reserved for different clients /// defined by AsyncBreakReasonBits. /// This may be manipulated from multiple threads. std::atomic<uint8_t> asyncBreakRequestFlag_{0}; #if defined(HERMES_ENABLE_DEBUGGER) /// \return zero if no debugger async pause was requested, the old nonzero /// async flags if an async pause was requested. If nonzero is returned, the /// flag is reset to 0. uint8_t testAndClearDebuggerAsyncBreakRequest() { return testAndClearAsyncBreakRequest( (uint8_t)AsyncBreakReasonBits::DebuggerExplicit | (uint8_t)AsyncBreakReasonBits::DebuggerImplicit); } Debugger debugger_{this}; #endif /// \return whether any async break is requested or not. bool hasAsyncBreak() const { return asyncBreakRequestFlag_.load(std::memory_order_relaxed) != 0; } /// \return whether async break was requested or not for \p reasonBits. Clear /// \p reasonBit request bit afterward. uint8_t testAndClearAsyncBreakRequest(uint8_t reasonBits) { /// Note that while the triggerTimeoutAsyncBreak() function may be called /// from any thread, this one may only be called from within the Interpreter /// loop. uint8_t flag = asyncBreakRequestFlag_.load(std::memory_order_relaxed); if (LLVM_LIKELY((flag & (uint8_t)reasonBits) == 0)) { // Fast path. return false; } // Clear the flag using CAS. uint8_t oldFlag = asyncBreakRequestFlag_.fetch_and( ~(uint8_t)reasonBits, std::memory_order_relaxed); assert(oldFlag != 0 && "Why is oldFlag zero?"); return oldFlag; } /// \return whether timeout async break was requsted or not. Clear the /// timeout request bit afterward. bool testAndClearTimeoutAsyncBreakRequest() { return testAndClearAsyncBreakRequest( (uint8_t)AsyncBreakReasonBits::Timeout); } /// Request the interpreter loop to take an asynchronous break /// at a convenient point. void triggerAsyncBreak(AsyncBreakReasonBits reason) { asyncBreakRequestFlag_.fetch_or((uint8_t)reason, std::memory_order_relaxed); } /// Notify runtime execution has timeout. ExecutionStatus notifyTimeout(); /// Holds references to persistent BC providers for the lifetime of the /// Runtime. This is needed because the identifier table may contain pointers /// into bytecode, and so memory backing these must be preserved. std::vector<std::shared_ptr<hbc::BCProvider>> persistentBCProviders_; /// Config-provided callback for GC events. std::function<void(GCEventKind, const char *)> gcEventCallback_; /// Set from RuntimeConfig. bool allowFunctionToStringWithRuntimeSource_; private: #ifdef NDEBUG /// See \c ::setCurrentIP() and \c ::getCurrentIP() . const inst::Inst *currentIP_{nullptr}; #else /// When assertions are enabled we track whether \c currentIP_ is "valid" by /// making it optional. If this is accessed when the optional value is cleared /// (the invalid state) we assert. llvh::Optional<const inst::Inst *> currentIP_{(const inst::Inst *)nullptr}; #endif public: /// Set the value of the current Instruction Pointer (IP). Generally this is /// called by the interpeter before it makes any major calls out of its main /// loop. However, the interpeter also reads the value held here back after /// major calls return so this can also be called by other code which wants to /// return to the interpreter at a different IP. This allows things external /// to the interpreter loop to affect the flow of bytecode execution. inline void setCurrentIP(const inst::Inst *ip) { currentIP_ = ip; } /// Get the current Instruction Pointer (IP). This can be used to find out /// the last bytecode executed if we're currently in the interpeter loop. If /// we are not in the interpeter loop (i.e. we've made it into the VM /// internals via a native call), this this will return nullptr. inline const inst::Inst *getCurrentIP() const { #ifdef NDEBUG return currentIP_; #else assert( currentIP_.hasValue() && "Current IP unknown - this probably means a CAPTURE_IP_* is missing in the interpreter."); return *currentIP_; #endif } /// This is slow compared to \c getCurrentIP() as it's virtual. inline const inst::Inst *getCurrentIPSlow() const override { return getCurrentIP(); } #ifdef NDEBUG void invalidateCurrentIP() {} #else void invalidateCurrentIP() { currentIP_.reset(); } #endif /// Save the return address in the caller in the stack frame. /// This needs to be called at the beginning of a function call, after the /// stack frame is set up. void saveCallerIPInStackFrame() { #ifndef NDEBUG assert( (!currentFrame_.getSavedIP() || (currentIP_.hasValue() && currentFrame_.getSavedIP() == currentIP_)) && "The ip should either be null or already have the expected value"); #endif currentFrame_.getSavedIPRef() = HermesValue::encodeNativePointer(getCurrentIP()); } void setAllowFunctionToStringWithRuntimeSource(bool v) { allowFunctionToStringWithRuntimeSource_ = v; } bool getAllowFunctionToStringWithRuntimeSource() const { return allowFunctionToStringWithRuntimeSource_; } private: /// Given the current last known IP used in the interpreter loop, returns the /// last known CodeBlock and IP combination. IP must not be null as this /// suggests we're not in the interpter loop, and there will be no CodeBlock /// to find. std::pair<const CodeBlock *, const inst::Inst *> getCurrentInterpreterLocation(const inst::Inst *initialSearchIP) const; public: /// Return a StackTraceTreeNode for the last known interpreter bytecode /// location. Returns nullptr if we're not in the interpeter loop, or /// allocation location tracking is not enabled. For this to function it /// needs to be passed the current IP from getCurrentIP(). We do not call /// this internally because it should always be called prior even if we /// do not really want a stack-traces node. This means we can leverage our /// library of tests to assert getCurrentIP() would return the right value /// at this point without actually collecting stack-trace data. StackTracesTreeNode *getCurrentStackTracesTreeNode( const inst::Inst *ip) override; /// Return the current StackTracesTree or nullptr if it's not available. StackTracesTree *getStackTracesTree() override { return stackTracesTree_.get(); } /// To facilitate allocation location tracking this must be called by the /// interpeter: /// * Just before we enter a new CodeBlock /// * At the entry point of a CodeBlock if this is the first entry into the /// interpter loop. inline void pushCallStack(const CodeBlock *codeBlock, const inst::Inst *ip) { if (stackTracesTree_) { pushCallStackImpl(codeBlock, ip); } } /// Must pair up with every call to \c pushCallStack . inline void popCallStack() { if (stackTracesTree_) { popCallStackImpl(); } } /// Enable allocation location tracking. Only works with /// HERMES_ENABLE_ALLOCATION_LOCATION_TRACES. void enableAllocationLocationTracker() { enableAllocationLocationTracker(nullptr); } void enableAllocationLocationTracker( std::function<void( uint64_t, std::chrono::microseconds, std::vector<GCBase::AllocationLocationTracker::HeapStatsUpdate>)> fragmentCallback); /// Disable allocation location tracking for new objects. Old objects tagged /// with stack traces continue to be tracked until they are freed. /// \param clearExistingTree is for use by tests and in general will break /// because old objects would end up with dead pointers to stack-trace nodes. void disableAllocationLocationTracker(bool clearExistingTree = false); private: void popCallStackImpl(); void pushCallStackImpl(const CodeBlock *codeBlock, const inst::Inst *ip); std::unique_ptr<StackTracesTree> stackTracesTree_; }; /// StackRuntime is meant to be used whenever a Runtime should be allocated on /// the stack. This should only be used by JSI, everything else should use the /// default creator. class StackRuntime final : public Runtime { public: StackRuntime(const RuntimeConfig &config); StackRuntime( std::shared_ptr<StorageProvider> provider, const RuntimeConfig &config); // A dummy virtual destructor to avoid problems when StackRuntime is used // in compilation units compiled with RTTI. virtual ~StackRuntime(); }; /// An RAII class for automatically tracking the native call frame depth. class ScopedNativeDepthTracker { Runtime *const runtime_; public: explicit ScopedNativeDepthTracker(Runtime *runtime) : runtime_(runtime) { ++runtime->nativeCallFrameDepth_; } ~ScopedNativeDepthTracker() { --runtime_->nativeCallFrameDepth_; } /// \return whether we overflowed the native call frame depth. bool overflowed() const { return runtime_->nativeCallFrameDepth_ > Runtime::MAX_NATIVE_CALL_FRAME_DEPTH; } }; /// An RAII class which creates a little headroom in the native depth /// tracking. This is used when calling into JSError to extract the /// stack, as the error may represent an overflow. Without this, a /// cascade of exceptions could occur, overflowing the C++ stack. class ScopedNativeDepthReducer { Runtime *const runtime_; bool undo = false; // This is empirically good enough. static constexpr int kDepthAdjustment = 3; public: explicit ScopedNativeDepthReducer(Runtime *runtime) : runtime_(runtime) { if (runtime->nativeCallFrameDepth_ >= kDepthAdjustment) { runtime->nativeCallFrameDepth_ -= kDepthAdjustment; undo = true; } } ~ScopedNativeDepthReducer() { if (undo) { runtime_->nativeCallFrameDepth_ += kDepthAdjustment; } } }; /// A ScopedNativeCallFrame is an RAII class that manipulates the Runtime /// stack and depth counter, and holds a stack frame. The stack frame contents /// may be accessed (as StackFramePtr) via ->. Note that constructing this may /// fail due to stack overflow, either via the register stack or the depth /// counter. It is necessary to check the overflowed() flag before access the /// stack frame contents. /// Note that the arguments to the call frame are left uninitialized. The caller /// must clear these before triggering a GC. The fillArgs() function may be used /// for this purpose. class ScopedNativeCallFrame { /// The runtime for this call frame. Runtime *const runtime_; /// The stack pointer that will be restored in the destructor. PinnedHermesValue *const savedSP_; /// The contents of the new frame. StackFramePtr frame_; /// Whether this call frame overflowed. bool overflowed_; #ifndef NDEBUG /// Whether the user has called overflowed() with a false result. mutable bool overflowHasBeenChecked_{false}; #endif /// \return whether the runtime can allocate a new frame with the given number /// of registers. This may fail if we've overflowed our register stack, or /// exceeded the native call frame depth. static bool runtimeCanAllocateFrame( Runtime *runtime, uint32_t registersNeeded) { return runtime->checkAvailableStack(registersNeeded) && runtime->nativeCallFrameDepth_ <= Runtime::MAX_NATIVE_CALL_FRAME_DEPTH; } public: /// Construct a native call frame for the given \p runtime in preparation of /// calling \p callee with \p argCount arguments and the given \p thisArg. /// \p callee is either a native pointer to CodeBlock, or an object pointer to /// a Callable (the two cases are distinguished by the type tag). /// \p newTarget is either \c undefined or the callable of the constructor /// currently being invoked by new. /// On overflow, the overflowed() flag is set, in which case the stack frame /// must not be used. /// The arguments are initially uninitialized. The caller should initialize /// them by storing into them, or via fillArguments(). ScopedNativeCallFrame( Runtime *runtime, uint32_t argCount, HermesValue callee, HermesValue newTarget, HermesValue thisArg) : runtime_(runtime), savedSP_(runtime->getStackPointer()) { runtime->nativeCallFrameDepth_++; uint32_t registersNeeded = StackFrameLayout::callerOutgoingRegisters(argCount); overflowed_ = !runtimeCanAllocateFrame(runtime, registersNeeded); if (LLVM_UNLIKELY(overflowed_)) { return; } // We have enough space. Increment the call frame depth and construct the // frame. The ScopedNativeCallFrame will restore both. auto *stack = runtime->allocUninitializedStack(registersNeeded); frame_ = StackFramePtr::initFrame( stack, runtime->currentFrame_, nullptr, nullptr, argCount, callee, newTarget); frame_.getThisArgRef() = thisArg; #if HERMES_SLOW_DEBUG // Poison the initial arguments to ensure the caller sets all of them before // a GC. assert(!overflowed_ && "Overflow should return early"); overflowHasBeenChecked_ = true; fillArguments(argCount, HermesValue::encodeInvalidValue()); // We still want the user to check for overflow. overflowHasBeenChecked_ = false; #endif } /// Construct a native call frame for the given \p runtime in preparation of /// calling \p callee with \p argCount arguments and the given \p thisArg. On /// overflow, the overflowed() flag is set, in which case the stack frame must /// not be used. /// The arguments are initially uninitialized. The caller should initialize /// them by storing into them, or via fillArguments(). ScopedNativeCallFrame( Runtime *runtime, uint32_t argCount, Callable *callee, bool construct, HermesValue thisArg) : ScopedNativeCallFrame( runtime, argCount, HermesValue::encodeObjectValue(callee), construct ? HermesValue::encodeObjectValue(callee) : HermesValue::encodeUndefinedValue(), thisArg) {} ~ScopedNativeCallFrame() { // Note that we unconditionally increment the native call frame depth and // save the SP to avoid branching in the dtor. runtime_->nativeCallFrameDepth_--; runtime_->popToSavedStackPointer(savedSP_); #ifndef NDEBUG // Clear the frame to detect use-after-free. frame_ = StackFramePtr{}; #endif } /// Fill \p argCount arguments with the given value \p fillValue. void fillArguments(uint32_t argCount, HermesValue fillValue) { assert(overflowHasBeenChecked_ && "ScopedNativeCallFrame could overflow"); assert(argCount == frame_.getArgCount() && "Arg count mismatch."); std::uninitialized_fill_n(&frame_.getArgRefUnsafe(0), argCount, fillValue); } /// \return whether the stack frame overflowed. bool overflowed() const { #ifndef NDEBUG overflowHasBeenChecked_ = !overflowed_; #endif return overflowed_; } /// Access the stack frame contents via ->. StackFramePtr operator->() { assert(overflowHasBeenChecked_ && "ScopedNativeCallFrame could overflow"); return frame_; } }; /// RAII class to temporarily disallow allocation. /// Enforced by the GC in slow debug mode only. class NoAllocScope { public: #ifdef NDEBUG explicit NoAllocScope(Runtime *runtime) {} explicit NoAllocScope(GC *gc) {} void release() {} #else explicit NoAllocScope(Runtime *runtime) : NoAllocScope(&runtime->getHeap()) {} explicit NoAllocScope(GC *gc) : noAllocLevel_(&gc->noAllocLevel_) { ++*noAllocLevel_; } ~NoAllocScope() { if (noAllocLevel_) release(); } /// End this scope early. May only be called once. void release() { assert(noAllocLevel_ && "already released"); assert(*noAllocLevel_ > 0 && "unbalanced no alloc"); --*noAllocLevel_; noAllocLevel_ = nullptr; } private: uint32_t *noAllocLevel_; #endif }; //===----------------------------------------------------------------------===// // Runtime inline methods. inline void Runtime::addCustomRootsFunction( std::function<void(GC *, RootAndSlotAcceptor &)> markRootsFn) { customMarkRootFuncs_.emplace_back(std::move(markRootsFn)); } inline void Runtime::addCustomWeakRootsFunction( std::function<void(GC *, WeakRefAcceptor &)> markRootsFn) { customMarkWeakRootFuncs_.emplace_back(std::move(markRootsFn)); } template < typename T, HasFinalizer hasFinalizer, LongLived longLived, class... Args> T *Runtime::makeAFixed(Args &&... args) { #if !defined(HERMES_ENABLE_ALLOCATION_LOCATION_TRACES) && !defined(NDEBUG) // If allocation location tracking is enabled we implicitly call // getCurrentIP() via newAlloc() below. Even if this isn't enabled, we // always call getCurrentIP() in a debug build as this has the effect of // asserting the IP is correctly set (not invalidated) at this point. This // allows us to leverage our whole test-suite to find missing cases of // CAPTURE_IP* macros in the interpreter loop. (void)getCurrentIP(); #endif const uint32_t sz = cellSize<T>(); T *ptr = heap_.makeA<T, true /* fixedSize */, hasFinalizer, longLived>( sz, std::forward<Args>(args)...); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES heap_.getAllocationLocationTracker().newAlloc(ptr, heapAlignSize(sz)); #endif return ptr; } template < typename T, HasFinalizer hasFinalizer, LongLived longLived, class... Args> T *Runtime::makeAVariable(uint32_t size, Args &&... args) { #if !defined(HERMES_ENABLE_ALLOCATION_LOCATION_TRACES) && !defined(NDEBUG) // If allocation location tracking is enabled we implicitly call // getCurrentIP() via newAlloc() below. Even if this isn't enabled, we // always call getCurrentIP() in a debug build as this has the effect of // asserting the IP is correctly set (not invalidated) at this point. This // allows us to leverage our whole test-suite to find missing cases of // CAPTURE_IP* macros in the interpreter loop. (void)getCurrentIP(); #endif T *ptr = heap_.makeA<T, false /* fixedSize */, hasFinalizer, longLived>( size, std::forward<Args>(args)...); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES heap_.getAllocationLocationTracker().newAlloc(ptr, heapAlignSize(size)); #endif return ptr; } template <typename T> inline T Runtime::ignoreAllocationFailure(CallResult<T> res) { if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) hermes_fatal("Unhandled out of memory exception"); // Use std::move here to account for specializations of CallResult, // (in particular, CallResult<PseudoHandle<U>>) // which wrap a class with a deleted copy constructor. return std::move(res.getValue()); } inline void Runtime::ignoreAllocationFailure(ExecutionStatus status) { if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) hermes_fatal("Unhandled out of memory exception"); } inline void Runtime::ttiReached() { // Currently, only the heap_ behavior can change at TTI. heap_.ttiReached(); } template <class T> inline Handle<T> Runtime::makeHandle(const GCPointer<T> &p) { return Handle<T>(this, p.get(this)); } template <class T> inline MutableHandle<T> Runtime::makeMutableHandle(const GCPointer<T> &p) { return MutableHandle<T>(this, p.get(this)); } inline StringPrimitive *Runtime::getPredefinedString( Predefined::Str predefined) { return getStringPrimFromSymbolID(Predefined::getSymbolID(predefined)); } inline StringPrimitive *Runtime::getPredefinedString( Predefined::Sym predefined) { return getStringPrimFromSymbolID(Predefined::getSymbolID(predefined)); } inline Handle<StringPrimitive> Runtime::getPredefinedStringHandle( Predefined::Str predefined) { return makeHandle(getPredefinedString(predefined)); } inline Handle<StringPrimitive> Runtime::getPredefinedStringHandle( Predefined::Sym predefined) { return makeHandle(getPredefinedString(predefined)); } inline StringPrimitive *Runtime::getStringPrimFromSymbolID(SymbolID id) { return identifierTable_.getStringPrim(this, id); } #ifdef HERMESVM_PROFILER_BB inline BasicBlockExecutionInfo &Runtime::getBasicBlockExecutionInfo() { return basicBlockExecInfo_; } inline void Runtime::dumpBasicBlockProfileTrace(llvh::raw_ostream &OS) { basicBlockExecInfo_.dump(OS); } #endif inline Runtime::FormatSymbolID Runtime::formatSymbolID(SymbolID id) { return FormatSymbolID(this, id); } inline void Runtime::popToSavedStackPointer(PinnedHermesValue *stackPointer) { assert( stackPointer >= stackPointer_ && "attempting to pop the stack to a higher level"); stackPointer_ = stackPointer; } inline uint32_t Runtime::getStackLevel() const { return (uint32_t)(registerStackEnd_ - stackPointer_); } inline uint32_t Runtime::availableStackSize() const { return (uint32_t)(stackPointer_ - registerStack_); } inline bool Runtime::checkAvailableStack(uint32_t count) { // Note: use 64-bit arithmetic to avoid overflow. We could also do it with // a couple of comparisons, but that is likely to be slower. return availableStackSize() >= (uint64_t)count + STACK_RESERVE; } inline PinnedHermesValue *Runtime::allocUninitializedStack(uint32_t count) { assert(availableStackSize() >= count && "register stack overflow"); return stackPointer_ -= count; } inline bool Runtime::checkAndAllocStack(uint32_t count, HermesValue initValue) { if (!checkAvailableStack(count)) return false; allocStack(count, initValue); return true; } inline void Runtime::popStack(uint32_t count) { assert(getStackLevel() >= count && "register stack underflow"); stackPointer_ += count; } inline void Runtime::setCurrentFrameToTopOfStack(StackFramePtr topFrame) { assert( topFrame.ptr() == stackPointer_ && "topFrame must equal the top of stack"); currentFrame_ = topFrame; } /// Set the current frame pointer to the current top of the stack and return /// it. /// \return the new value of the current frame pointer. inline StackFramePtr Runtime::setCurrentFrameToTopOfStack() { return currentFrame_ = StackFramePtr(stackPointer_); } inline StackFramePtr Runtime::restoreStackAndPreviousFrame( StackFramePtr currentFrame) { assert( currentFrame_ == currentFrame && "currentFrame parameter must match currentFrame_"); stackPointer_ = currentFrame.ptr(); return currentFrame_ = currentFrame.getPreviousFrame(); } inline StackFramePtr Runtime::restoreStackAndPreviousFrame() { return restoreStackAndPreviousFrame(currentFrame_); } inline llvh::iterator_range<StackFrameIterator> Runtime::getStackFrames() { return {StackFrameIterator{currentFrame_}, StackFrameIterator{registerStackEnd_}}; }; inline llvh::iterator_range<ConstStackFrameIterator> Runtime::getStackFrames() const { return {ConstStackFrameIterator{currentFrame_}, ConstStackFrameIterator{registerStackEnd_}}; }; inline ExecutionStatus Runtime::setThrownValue(HermesValue value) { thrownValue_ = value; return ExecutionStatus::EXCEPTION; } inline void Runtime::clearThrownValue() { thrownValue_ = HermesValue::encodeEmptyValue(); } inline CrashManager &Runtime::getCrashManager() { return *crashMgr_; } #ifndef HERMESVM_SANITIZE_HANDLES inline void Runtime::potentiallyMoveHeap() {} #endif //===----------------------------------------------------------------------===// /// Invoke the T constructor with the given args to construct the /// object in the given memory mem. template <typename T, typename... CtorArgs> inline void constructInHeapObj(void *mem, CtorArgs... args) { new (mem) T(args...); } /// Serialize a SymbolID. llvh::raw_ostream &operator<<( llvh::raw_ostream &OS, Runtime::FormatSymbolID format); } // namespace vm } // namespace hermes #endif // HERMES_VM_RUNTIME_H
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
0c6c9045113a546b559697b9fc9f68f5ae10d467
76aab74b58991e2cf8076d6b4ed6f4deba1c57bd
/codevs/1380.cpp
833ef4af7a7e730c0fc32e43ddd5f5f68d74c60c
[]
no_license
StudyingFather/my-code
9c109660c16b18f9974d37a2a1d809db4d6ce50a
8d02be445ac7affad58c2d71f3ef602f3d2801f6
refs/heads/master
2023-08-16T23:17:10.817659
2023-08-04T11:31:40
2023-08-04T11:31:40
149,898,152
6
2
null
null
null
null
UTF-8
C++
false
false
707
cpp
#include <cstdio> #include <algorithm> using namespace std; struct edge { int v,next; }e[6005]; int head[6005],n,cnt,f[6005][2],ans,is_h[6005],vis[6005]; void addedge(int u,int v) { e[++cnt].v=v; e[cnt].next=head[u]; head[u]=cnt; } void calc(int k) { vis[k]=1; for(int i=head[k];i;i=e[i].next) { if(vis[e[i].v])continue; calc(e[i].v); f[k][1]+=f[e[i].v][0]; f[k][0]+=max(f[e[i].v][0],f[e[i].v][1]); } return; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&f[i][1]); for(int i=1;i<n;i++) { int l,k; scanf("%d%d",&l,&k); is_h[l]=1; addedge(k,l); } for(int i=1;i<=n;i++) if(!is_h[i]) { calc(i); printf("%d",max(f[i][1],f[i][0])); return 0; } }
[ "594422141@qq.com" ]
594422141@qq.com
60b6ddd6e47ca1b5f6b9216e9071712854d1cf18
2239bfc546e44e29e55d4d0f258f1f78edb424b0
/MT/Led3TestDlg.h
01cfe0cd0c5a00bfc9f0b4535b97f7560816fb7b
[]
no_license
BhBjGit/MJFY
a13b0f156bf7ac6081998c8638ca51b76760e7ae
c43e62c1e795c844774feb91fdfd3509cfa0ac14
refs/heads/master
2021-01-11T22:46:18.805456
2017-01-15T13:34:02
2017-01-15T13:34:02
79,032,017
0
0
null
null
null
null
GB18030
C++
false
false
1,709
h
#pragma once #include "MT3Dlg.h" #include "ProtocolHelper.h" using std::wstring; // CLedTestDlg 对话框 enum RESULTSTATUE { MJ_NORMAL=1, MJ_SUCCESS, MJ_FAILED }; //PSN在主板量产版固件中的偏移地址 #define MB_PSNOFFSETADDR (0x00011800) //JFlash超时时间 #define MB_JFLASHTIMEOUTV (1000*30) class CLed3TestDlg : public CDialogEx { DECLARE_DYNAMIC(CLed3TestDlg) public: CLed3TestDlg(LPVOID p, TESTERTYPE type, CWnd* pParent = NULL); // 标准构造函数 virtual ~CLed3TestDlg(); // 对话框数据 enum { IDD = IDD_DLG_LED3_TEST }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CMT3Dlg* m_pParent; RESULTSTATUE m_Result; CFont m_font; HANDLE m_hDevice; TESTERTYPE m_testType; //测试类型及接口描述说明 wstring m_wstrDes; //psn string m_strPSN; //记录文件 string m_strFileContent; //依据津亚格式要求存储事件文件 string m_strJYFormatFileContent; string m_strJYTemp; //统计计数 INT m_nTotalNum; INT m_nPassNum; INT m_nFailNum; public: VOID RefreshDeviceList(); VOID RefreshDeviceListR(); VOID ShowInfo(PWCHAR pInfo, BOOL bNew); VOID SetResult(); //显示统计信息 VOID SetResultInfo(); BOOL LedCheck(); BOOL MainBoardCheck(); BOOL WifiCheck(); BOOL MainBoardSportCheck(); BOOL UpdaterMB(string strWorkDir); VOID SetBtnStatus(BOOL bEnable); //验证SN码的合法性 BOOL CheckSN(); public: afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); virtual BOOL OnInitDialog(); afx_msg void OnBnClickedBtnStart(); virtual BOOL PreTranslateMessage(MSG* pMsg); };
[ "fsc@sina.com" ]
fsc@sina.com
95d979c3efcc12bb37cab6c44d4c400757bc1ac0
5990f2851d3124da5e32763a82b5c1e00c992c10
/main.cpp
cdf2a45ea18f854d693b1c5b13c03da81a5368c4
[]
no_license
RSDT/jhsolver2
0fea579d59814eb138c8ce60b3350d86cc4aca66
2a4ae3651fe6e907f2025110df9d01cd41c5584c
refs/heads/master
2021-01-17T17:56:29.823305
2016-10-12T16:09:34
2016-10-12T16:09:34
70,715,760
0
0
null
null
null
null
UTF-8
C++
false
false
1,885
cpp
#include <iostream> #include "datastructures.h" #include <vector> #include <fstream> #include "kml_handling.h" int main() { std::string hqfilename = "homebases.jh"; std::string kmlfilename = "jotihunt2014.kml"; kml_h::create_homebase_file( hqfilename, kmlfilename); std::string s; std::ifstream f ("deelgebieden.jh"); std::ifstream fh ("homebases.jh") ; std::vector<std::vector< data::RD > > dgn = kml_h::read_deelgebieden_rd(f); std::vector< data::Homebase > HQs = kml_h::read_hombases(fh); kml_h::sort_hb(HQs); std::vector<data::Deelgebied> dg = kml_h::create_deelgebieden(dgn,HQs); // data::RD linksonder = get_linksonder(); // data::RD rechtsboven = get_rechtsboven(); /*vector<Hint> hints = test(dg); for (auto i = 0 ; i < hints.size(); i++) { read_sol(hints[i]); } vector<vector <int> > sol = find_sols(hints); for (auto i = 0 ; i < hints.size(); i++) { clean_sol(hints[i],sol); } ofstream out ("out.txt"); for (auto i = 0 ; i < hints.size(); i++) { show_sol(hints[i]); cout << ABCDEF[hints[i].deelgebied].Route[ABCDEF[hints[i].deelgebied].Route.size()-1]<< endl; cout << ABCDEF[hints[i].deelgebied].HQs.size()<< endl; cout << hints[i].SolRD.size() << endl; out << endl<<create_url(hints[i].SolRD,ABCDEF[hints[i].deelgebied].Route[ABCDEF[hints[i].deelgebied].Route.size()-1],ABCDEF[hints[i].deelgebied].HQs)<< endl; } for (auto i = 0; i < 1; i++) { cout << ABCDEF[i].naam << endl; cout << "naam\tP_gehad\tP_volgend\n"; for (auto j = 0; j < ABCDEF[i].HQs.size();j++) cout << ABCDEF[i].HQs[j].naam <<'\t'<< '%' <<'\t'<< '%'<<endl; cout << endl; }*/ // fill_database(linksonder,rechtsboven); // 7050s 1,5GB return 0; }
[ "git@mattijnkreuzen.nl" ]
git@mattijnkreuzen.nl
c9e86a8d8bfa9e4ecfb90c068c22ca0079502f1f
18d84805f138d390736104351fe2141332f9a092
/ESP32_cam.ino
8d821e65e52a5a3b6898509cbd0558fd05bdbbb5
[ "Apache-2.0" ]
permissive
hydrawei/TSENG-PET-BOX
40680e5a2e8f6b01dd9a7cfdbe78d612bb9ccfb5
aee49a13be6d8ed3ac3c5c36ec12902776f844e5
refs/heads/main
2023-07-13T09:30:04.603639
2021-08-22T06:45:50
2021-08-22T06:45:50
398,732,402
0
0
null
null
null
null
UTF-8
C++
false
false
4,214
ino
#include <WiFi.h> #include <WebServer.h> #include <WiFiClient.h> #include "OV2640.h" #include "SimStreamer.h" #include "OV2640Streamer.h" #include "CRtspSession.h" char *ssid = "SSID"; // Put your SSID here char *password = "PASSWORD"; // Put your PASSWORD here WebServer server(80); WiFiServer rtspServer(554); OV2640 cam; CStreamer *streamer; //mjpeg串流 void handle_jpg_stream(void) { WiFiClient client = server.client(); String response = "HTTP/1.1 200 OK\r\n"; response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n"; server.sendContent(response); while (1) { cam.run(); if (!client.connected()) break; response = "--frame\r\n"; response += "Content-Type: image/jpeg\r\n\r\n"; server.sendContent(response); client.write((char *)cam.getfb(), cam.getSize()); server.sendContent("\r\n"); if (!client.connected()) break; } } //靜態影像 void handle_jpg(void) { WiFiClient client = server.client(); cam.run(); if (!client.connected()) { return; } String response = "HTTP/1.1 200 OK\r\n"; response += "Content-disposition: inline; filename=capture.jpg\r\n"; response += "Content-type: image/jpeg\r\n\r\n"; server.sendContent(response); client.write((char *)cam.getfb(), cam.getSize()); } //錯誤處理 void handleNotFound() { String message = "Server is running!\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; server.send(200, "text/plain", message); } //WiFi連線 void WifiConnecte() { //開始WiFi連線 WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi連線成功"); Serial.print("IP Address:"); Serial.println(WiFi.localIP()); } void setup() { Serial.begin(115200); //設定影像大小:UXGA(1600x1200),SXGA(1280x1024),XGA(1024x768),SVGA(800x600),VGA(640x480),CIF(400x296),QVGA(320x240),HQVGA(240x176),QQVGA(160x120) esp32cam_aithinker_config.frame_size = FRAMESIZE_QVGA; esp32cam_aithinker_config.jpeg_quality = 10; cam.init(esp32cam_aithinker_config); //開始WiFi連線 WifiConnecte(); server.on("/", HTTP_GET, handle_jpg_stream); server.on("/jpg", HTTP_GET, handle_jpg); server.onNotFound(handleNotFound); server.begin(); rtspServer.begin(); streamer = new OV2640Streamer(cam);//啟動服務 Serial.println("WiFi connected"); Serial.print("Use 'http://"); Serial.print(WiFi.localIP()); Serial.println("/' to watch mjpeg stream"); Serial.print("Use 'http://"); Serial.print(WiFi.localIP()); Serial.println("/jpg' to see still jpg"); Serial.print("Use RTRP:'"); Serial.print(WiFi.localIP()); Serial.println("', URL:'/mjpeg/1' and port:554 to start rtsp stream"); } void loop() { if (WiFi.status() != WL_CONNECTED) { WifiConnecte(); } server.handleClient(); uint32_t msecPerFrame = 100; static uint32_t lastimage = millis(); // If we have an active client connection, just service that until gone streamer->handleRequests(0); // we don't use a timeout here, // instead we send only if we have new enough frames uint32_t now = millis(); if (streamer->anySessions()) { if (now > lastimage + msecPerFrame || now < lastimage) { // handle clock rollover streamer->streamImage(now); lastimage = now; // check if we are overrunning our max frame rate now = millis(); if (now > lastimage + msecPerFrame) { printf("warning exceeding max frame rate of %d ms\n", now - lastimage); } } } WiFiClient rtspClient = rtspServer.accept(); if (rtspClient) { Serial.print("client: "); Serial.print(rtspClient.remoteIP()); Serial.println(); streamer->addSession(rtspClient); } }
[ "noreply@github.com" ]
noreply@github.com
4c05119825fd1586e38e5058e25c5fa979002326
7f60be0889a94ba41fc4c4ddb886d90335f76649
/editStrings.cpp
ef46eb8b3904aa17611be0b8b906f3a429e63595
[]
no_license
JuliusBoateng/data_structs_and_algs
f657fe3d675b019c2d69c565b4dcab27183ca6f7
12005b90809de07aa24b9201160c1bc4e54359ae
refs/heads/master
2023-05-07T15:37:31.359050
2021-05-28T18:52:32
2021-05-28T18:52:32
277,998,646
0
0
null
null
null
null
UTF-8
C++
false
false
1,789
cpp
#include <iostream> #include <string> #include <unordered_map> void editStringChecker(std::string str1, std::string str2){ std::unordered_map<char, int> counter = {}; for (int i = 0; i < str1.length(); i++){ if (counter.find(str1[i]) == counter.end() ) { counter[str1[i]] = 1; } else { counter[str1[i]] = counter[str1[i]] + 1; } } for (int i = 0; i < str2.length(); i++){ if (counter.find(str1[i]) == counter.end() ) { counter[str2[i]] = -1; } else { counter[str2[i]] = counter[str2[i]] - 1; } } int numInsert = 0; int numRemove = 0; for (auto x : counter){ if (x.second == 0){ continue; } else if (x.second == 1){ numInsert += 1; } else if (x.second == -1){ numRemove += 1; } else { std::cout << "\"" << str1 << "\"" << " and " << "\"" << str2 << "\"" << " are not \"one away\"." << std::endl; return; } // std::cout << x.first << " " << x.second << std::endl; } if ( (numInsert == 0) && (numRemove == 0) ){ std::cout << "\"" << str1 << "\"" << " and " << "\"" << str2 << "\"" << " are \"zero edits away\"." << std::endl; } else if (numInsert > 1 || numRemove > 1){ std::cout << "\"" << str1 << "\"" << " and " << "\"" << str2 << "\"" << " are NOT \"one edit away\"." << std::endl; } else { std::cout << "\"" << str1 << "\"" << " and " << "\"" << str2 << "\"" << " are \"one edit away\"." << std::endl; } } int main(){ std::string str1 = "pale"; std::string str2 = "bake"; editStringChecker(str1, str2); return 0; }
[ "juliusopokuboateng@gmail.com" ]
juliusopokuboateng@gmail.com
b58746b39e621fc37ff8ced38f679b16a3984501
91ba0c0c42b3fcdbc2a7778e4a4684ab1942714b
/Cpp/SDK/BP_ShipCustomizationChestInteraction_functions.cpp
e41cf28eff4469886eab94431cc546089ded28c0
[]
no_license
zH4x/SoT-SDK-2.1.1
0f8c1ec3ad8821de82df3f75a0356642b581b8c6
35144dfc629aeddf96c1741e9e27e5113a2b1bb3
refs/heads/main
2023-05-12T09:03:32.050860
2021-06-05T01:54:15
2021-06-05T01:54:15
373,997,263
0
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
// Name: SoT, Version: 2.1.1 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_ShipCustomizationChestInteraction.BP_ShipCustomizationChestInteraction_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_ShipCustomizationChestInteraction_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_ShipCustomizationChestInteraction.BP_ShipCustomizationChestInteraction_C.UserConstructionScript"); ABP_ShipCustomizationChestInteraction_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
fc959d31372bef776209e1b79da532a16252db17
084a264ee1c2f1d36db03988970cdedc1846799a
/modules/audio_coding/audio_network_adaptor/bitrate_controller_unittest.cc
b6060a99e64152d36441393dbfbbbcae317cda39
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webm", "LicenseRef-scancode-google-patent-license-webrtc", "GPL-1.0-or-later", "LicenseRef-scancode-takuya-ooura", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "MS-LPL",...
permissive
nareix/webrtc
199410db65e18c1b277d50484673b9ffab54b124
123749a69270b2c0bf232887c3cf1cf6d03d016a
refs/heads/main
2023-04-20T09:39:56.531907
2023-03-10T11:01:52
2023-03-10T11:01:52
214,553,776
0
1
MIT
2019-10-12T01:08:20
2019-10-12T01:08:19
null
UTF-8
C++
false
false
12,126
cc
/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_coding/audio_network_adaptor/bitrate_controller.h" #include "test/field_trial.h" #include "test/gtest.h" namespace webrtc { namespace audio_network_adaptor { namespace { void UpdateNetworkMetrics( BitrateController* controller, const rtc::Optional<int>& target_audio_bitrate_bps, const rtc::Optional<size_t>& overhead_bytes_per_packet) { // UpdateNetworkMetrics can accept multiple network metric updates at once. // However, currently, the most used case is to update one metric at a time. // To reflect this fact, we separate the calls. if (target_audio_bitrate_bps) { Controller::NetworkMetrics network_metrics; network_metrics.target_audio_bitrate_bps = target_audio_bitrate_bps; controller->UpdateNetworkMetrics(network_metrics); } if (overhead_bytes_per_packet) { Controller::NetworkMetrics network_metrics; network_metrics.overhead_bytes_per_packet = overhead_bytes_per_packet; controller->UpdateNetworkMetrics(network_metrics); } } void CheckDecision(BitrateController* controller, const rtc::Optional<int>& frame_length_ms, int expected_bitrate_bps) { AudioEncoderRuntimeConfig config; config.frame_length_ms = frame_length_ms; controller->MakeDecision(&config); EXPECT_EQ(rtc::Optional<int>(expected_bitrate_bps), config.bitrate_bps); } } // namespace // These tests are named AnaBitrateControllerTest to distinguish from // BitrateControllerTest in // modules/bitrate_controller/bitrate_controller_unittest.cc. TEST(AnaBitrateControllerTest, OutputInitValueWhenTargetBitrateUnknown) { constexpr int kInitialBitrateBps = 32000; constexpr int kInitialFrameLengthMs = 20; constexpr size_t kOverheadBytesPerPacket = 64; BitrateController controller(BitrateController::Config( kInitialBitrateBps, kInitialFrameLengthMs, 0, 0)); UpdateNetworkMetrics(&controller, rtc::Optional<int>(), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(kInitialFrameLengthMs * 2), kInitialBitrateBps); } TEST(AnaBitrateControllerTest, OutputInitValueWhenOverheadUnknown) { constexpr int kInitialBitrateBps = 32000; constexpr int kInitialFrameLengthMs = 20; constexpr int kTargetBitrateBps = 48000; BitrateController controller(BitrateController::Config( kInitialBitrateBps, kInitialFrameLengthMs, 0, 0)); UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>()); CheckDecision(&controller, rtc::Optional<int>(kInitialFrameLengthMs * 2), kInitialBitrateBps); } TEST(AnaBitrateControllerTest, ChangeBitrateOnTargetBitrateChanged) { test::ScopedFieldTrials override_field_trials( "WebRTC-SendSideBwe-WithOverhead/Enabled/"); constexpr int kInitialFrameLengthMs = 20; BitrateController controller( BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0)); constexpr int kTargetBitrateBps = 48000; constexpr size_t kOverheadBytesPerPacket = 64; constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 * 1000 / kInitialFrameLengthMs; // Frame length unchanged, bitrate changes in accordance with // |metrics.target_audio_bitrate_bps| and |metrics.overhead_bytes_per_packet|. UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(kInitialFrameLengthMs), kBitrateBps); } TEST(AnaBitrateControllerTest, UpdateMultipleNetworkMetricsAtOnce) { // This test is similar to ChangeBitrateOnTargetBitrateChanged. But instead of // using ::UpdateNetworkMetrics(...), which calls // BitrateController::UpdateNetworkMetrics(...) multiple times, we // we call it only once. This is to verify that // BitrateController::UpdateNetworkMetrics(...) can handle multiple // network updates at once. This is, however, not a common use case in current // audio_network_adaptor_impl.cc. test::ScopedFieldTrials override_field_trials( "WebRTC-SendSideBwe-WithOverhead/Enabled/"); constexpr int kInitialFrameLengthMs = 20; BitrateController controller( BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0)); constexpr int kTargetBitrateBps = 48000; constexpr size_t kOverheadBytesPerPacket = 64; constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 * 1000 / kInitialFrameLengthMs; Controller::NetworkMetrics network_metrics; network_metrics.target_audio_bitrate_bps = rtc::Optional<int>(kTargetBitrateBps); network_metrics.overhead_bytes_per_packet = rtc::Optional<size_t>(kOverheadBytesPerPacket); controller.UpdateNetworkMetrics(network_metrics); CheckDecision(&controller, rtc::Optional<int>(kInitialFrameLengthMs), kBitrateBps); } TEST(AnaBitrateControllerTest, TreatUnknownFrameLengthAsFrameLengthUnchanged) { test::ScopedFieldTrials override_field_trials( "WebRTC-SendSideBwe-WithOverhead/Enabled/"); constexpr int kInitialFrameLengthMs = 20; BitrateController controller( BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0)); constexpr int kTargetBitrateBps = 48000; constexpr size_t kOverheadBytesPerPacket = 64; constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 * 1000 / kInitialFrameLengthMs; UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(), kBitrateBps); } TEST(AnaBitrateControllerTest, IncreaseBitrateOnFrameLengthIncreased) { test::ScopedFieldTrials override_field_trials( "WebRTC-SendSideBwe-WithOverhead/Enabled/"); constexpr int kInitialFrameLengthMs = 20; BitrateController controller( BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0)); constexpr int kTargetBitrateBps = 48000; constexpr size_t kOverheadBytesPerPacket = 64; constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 * 1000 / kInitialFrameLengthMs; UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(), kBitrateBps); constexpr int kFrameLengthMs = 60; constexpr size_t kPacketOverheadRateDiff = kOverheadBytesPerPacket * 8 * 1000 / 20 - kOverheadBytesPerPacket * 8 * 1000 / 60; UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(kFrameLengthMs), kBitrateBps + kPacketOverheadRateDiff); } TEST(AnaBitrateControllerTest, DecreaseBitrateOnFrameLengthDecreased) { test::ScopedFieldTrials override_field_trials( "WebRTC-SendSideBwe-WithOverhead/Enabled/"); constexpr int kInitialFrameLengthMs = 60; BitrateController controller( BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0)); constexpr int kTargetBitrateBps = 48000; constexpr size_t kOverheadBytesPerPacket = 64; constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 * 1000 / kInitialFrameLengthMs; UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(), kBitrateBps); constexpr int kFrameLengthMs = 20; constexpr size_t kPacketOverheadRateDiff = kOverheadBytesPerPacket * 8 * 1000 / 20 - kOverheadBytesPerPacket * 8 * 1000 / 60; UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(kFrameLengthMs), kBitrateBps - kPacketOverheadRateDiff); } TEST(AnaBitrateControllerTest, BitrateNeverBecomesNegative) { test::ScopedFieldTrials override_field_trials( "WebRTC-SendSideBwe-WithOverhead/Enabled/"); BitrateController controller(BitrateController::Config(32000, 20, 0, 0)); constexpr size_t kOverheadBytesPerPacket = 64; constexpr int kFrameLengthMs = 60; // Set a target rate smaller than overhead rate, the bitrate is bounded by 0. constexpr int kTargetBitrateBps = kOverheadBytesPerPacket * 8 * 1000 / kFrameLengthMs - 1; UpdateNetworkMetrics(&controller, rtc::Optional<int>(kTargetBitrateBps), rtc::Optional<size_t>(kOverheadBytesPerPacket)); CheckDecision(&controller, rtc::Optional<int>(kFrameLengthMs), 0); } TEST(AnaBitrateControllerTest, CheckBehaviorOnChangingCondition) { test::ScopedFieldTrials override_field_trials( "WebRTC-SendSideBwe-WithOverhead/Enabled/"); BitrateController controller(BitrateController::Config(32000, 20, 0, 0)); // Start from an arbitrary overall bitrate. int overall_bitrate = 34567; size_t overhead_bytes_per_packet = 64; int frame_length_ms = 20; int current_bitrate = overall_bitrate - overhead_bytes_per_packet * 8 * 1000 / frame_length_ms; UpdateNetworkMetrics(&controller, rtc::Optional<int>(overall_bitrate), rtc::Optional<size_t>(overhead_bytes_per_packet)); CheckDecision(&controller, rtc::Optional<int>(frame_length_ms), current_bitrate); // Next: increase overall bitrate. overall_bitrate += 100; current_bitrate += 100; UpdateNetworkMetrics(&controller, rtc::Optional<int>(overall_bitrate), rtc::Optional<size_t>(overhead_bytes_per_packet)); CheckDecision(&controller, rtc::Optional<int>(frame_length_ms), current_bitrate); // Next: change frame length. frame_length_ms = 60; current_bitrate += overhead_bytes_per_packet * 8 * 1000 / 20 - overhead_bytes_per_packet * 8 * 1000 / 60; UpdateNetworkMetrics(&controller, rtc::Optional<int>(overall_bitrate), rtc::Optional<size_t>(overhead_bytes_per_packet)); CheckDecision(&controller, rtc::Optional<int>(frame_length_ms), current_bitrate); // Next: change overhead. overhead_bytes_per_packet -= 30; current_bitrate += 30 * 8 * 1000 / frame_length_ms; UpdateNetworkMetrics(&controller, rtc::Optional<int>(overall_bitrate), rtc::Optional<size_t>(overhead_bytes_per_packet)); CheckDecision(&controller, rtc::Optional<int>(frame_length_ms), current_bitrate); // Next: change frame length. frame_length_ms = 20; current_bitrate -= overhead_bytes_per_packet * 8 * 1000 / 20 - overhead_bytes_per_packet * 8 * 1000 / 60; UpdateNetworkMetrics(&controller, rtc::Optional<int>(overall_bitrate), rtc::Optional<size_t>(overhead_bytes_per_packet)); CheckDecision(&controller, rtc::Optional<int>(frame_length_ms), current_bitrate); // Next: decrease overall bitrate and frame length. overall_bitrate -= 100; current_bitrate -= 100; frame_length_ms = 60; current_bitrate += overhead_bytes_per_packet * 8 * 1000 / 20 - overhead_bytes_per_packet * 8 * 1000 / 60; UpdateNetworkMetrics(&controller, rtc::Optional<int>(overall_bitrate), rtc::Optional<size_t>(overhead_bytes_per_packet)); CheckDecision(&controller, rtc::Optional<int>(frame_length_ms), current_bitrate); } } // namespace audio_network_adaptor } // namespace webrtc
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
8e47fd9399b19835f0cb700f6bb8577a020371da
1761b6c0cba549d76fcf11695a97ac58c655e53f
/profitAndLoss/Portfolio.cpp
162bf91979ea4290c62ecb3e548c141a61be18b7
[]
no_license
muleta33/Projet_PEPS
74be83f4caae6517de254325972903b0db57819a
cb6605bcc4158c6fd48e2c66069f6f3c79c2b0de
refs/heads/master
2021-01-10T06:47:40.318899
2016-03-31T18:41:09
2016-03-31T18:41:09
47,509,276
0
0
null
null
null
null
UTF-8
C++
false
false
971
cpp
#include "Portfolio.hpp" void Portfolio::initialisation(double optionPrice, const PnlVect *deltas, const PnlVect *prices) { if (deltas_->size != deltas->size) pnl_vect_resize(deltas_, deltas->size); pnl_vect_clone(deltas_, deltas); risk_free_investment_ = optionPrice - pnl_vect_scalar_prod(deltas, prices); } void Portfolio::rebalancing(const PnlVect *deltas, const PnlVect *prices, double interest_rate, double time_step) { pnl_vect_minus_vect(deltas_, deltas); risk_free_investment_ = risk_free_investment_ * exp(interest_rate * time_step) + pnl_vect_scalar_prod(deltas_, prices); pnl_vect_clone(deltas_, deltas); } double Portfolio::compute_value(const PnlVect *prices) { return risk_free_investment_ + pnl_vect_scalar_prod(deltas_, prices); } double Portfolio::compute_final_value(const PnlVect *prices, double interest_rate, double time_step) { return risk_free_investment_ * exp(interest_rate * time_step) + pnl_vect_scalar_prod(deltas_, prices); }
[ "antoine.mulet@ensimag.grenoble-inp.fr" ]
antoine.mulet@ensimag.grenoble-inp.fr
3508f205489c796958363805f0817f479459e8a1
f1fbb63275ff66a97c8e654cabe0301851e9c317
/VS_CPp/MFC/Anketa/Anketa/Anketa.h
11fd5eadb1c603847b997c824a0b5fcc01e02731
[]
no_license
AAMORENKO/EXAMPLS_CPP_JAVA
c0eeb489ef1cb10d14cbb8de565e18f6044d0f61
2a732c503be8ac569505f942328524b86d43791e
refs/heads/master
2021-10-28T22:13:44.605096
2021-10-14T09:42:07
2021-10-14T09:42:07
163,251,015
9
9
null
null
null
null
WINDOWS-1251
C++
false
false
596
h
// Anketa.h : главный файл заголовка для приложения PROJECT_NAME // #pragma once #ifndef __AFXWIN_H__ #error "включить stdafx.h до включения этого файла в PCH" #endif #include "resource.h" // основные символы // CAnketaApp: // О реализации данного класса см. Anketa.cpp // class CAnketaApp : public CWinApp { public: CAnketaApp(); // Переопределение public: virtual BOOL InitInstance(); // Реализация DECLARE_MESSAGE_MAP() }; extern CAnketaApp theApp;
[ "wzooks@gmail.com" ]
wzooks@gmail.com
aac6b7a2ac95f123a880da7a20b91ffa509b2683
1286c5b3d37b0785e99073c8234b44df47561f5a
/2019/0602_AGC034/B.cpp
e31f82de8fa28880ad1d08190c4b7e169476bf3d
[ "MIT" ]
permissive
kazunetakahashi/atcoder
930cb5a0f4378914cc643de2f0596a5de7e4a417
16ce65829ccc180260b19316e276c2fcf6606c53
refs/heads/master
2022-02-15T19:12:10.224368
2022-01-29T06:38:42
2022-01-29T06:38:42
26,685,318
7
1
null
null
null
null
UTF-8
C++
false
false
1,348
cpp
#define DEBUG 1 /** * File : B.cpp * Author : Kazune Takahashi * Created : 2019-6-2 21:27:51 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; /* void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } */ /* const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; */ // const ll MOD = 1000000007; string S; // A: 0, B: 1, C: 2 ll DP[200010][4][4]; int main() { cin >> S; int N = S.size(); for (auto n = 0; n < N; n++) { for (auto i = 0; i < 4; i++) { for (auto j = 0; j < 4; j++) { int k = S[n] - 'A'; DP[n + 1][j][k] = max(DP[n + 1][j][k], DP[n][i][j]); if (i == 0 && j == 1 && k == 2) { DP[n + 1][2][0] = max(DP[n + 1][2][0], DP[n][i][j] + 1); } } } } ll ans = 0; for (auto i = 0; i < 3; i++) { for (auto j = 0; j < 3; j++) { ans = max(ans, DP[N][i][j]); } } cout << ans << endl; }
[ "kazunetakahashi@gmail.com" ]
kazunetakahashi@gmail.com
44f7e1d678e7ee67c33a261b2bd75591a770d046
5b6e9f56c71e9706ca83c7327c332cfa93104485
/samples/opengles_20/shadow_map/MDRRenderable.h
27341dcdee3bf2ac7e889a8b695592ea3710b73c
[]
no_license
Taogal/mali_examples
bfe918d025bb63adfb74945b55a753f251f1ebca
a03ef597258ee306a9e177309e04aaaa605a8fa6
refs/heads/master
2020-03-19T02:42:54.949885
2018-03-06T20:24:44
2018-03-06T20:24:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,268
h
/* * This proprietary software may be used only as * authorised by a licensing agreement from ARM Limited * (C) COPYRIGHT 2013 ARM Limited * ALL RIGHTS RESERVED * The entire notice above must be reproduced on all authorised * copies and copies may only be made to the extent permitted * by a licensing agreement from ARM Limited. */ #ifndef M_SHADOWMAPDR_RENDERABLE_HPP #define M_SHADOWMAPDR_RENDERABLE_HPP //------------------------------------------ // INCLUDES #include "mCommon.h" #include "MDRRenderable.h" //------------------------------------------ // BEGIN OF CLASS DECLARATION /** * The class represents an abstract object, which could be used as a render target (e.g. FBO). */ class MDRRenderable { public: // ----- Types ----- // ----- Constructors and destructors ----- /// MDRRenderable(); /// virtual ~MDRRenderable(); // ----- Accessors and mutators ----- // ----- Miscellaneous ----- /// virtual bool initialize(unsigned int aWidth, unsigned int aHeight) = 0; /// virtual bool bindRT() const = 0; /// virtual void unbindRT() const = 0; /// virtual void bindTexture() const = 0; /// virtual bool destroy() = 0; private: // ----- Fields ----- }; #endif
[ "newyoko@163.com" ]
newyoko@163.com
9d58ca0c9dfd35174f7ac63748e26b0e875637c2
d4fa4acf7e9de1da42f3d2be21b476d2ff92c104
/QTEditor/Classes/Utils/MySqlLiteManager.cpp
994f053c38e70dc11e1d17e3d6d4ae9afb574d34
[]
no_license
lswzzz/QTEditor
0263a1731e68136b392f37f7c2b2a2ecdc7fc71c
7dbdfd6c3b24ecf37d73f39e1c03d34b12c2b853
refs/heads/master
2020-03-03T23:10:07.265359
2016-05-04T07:18:19
2016-05-04T07:18:19
46,868,574
0
0
null
null
null
null
UTF-8
C++
false
false
4,027
cpp
#include "MySqlLiteManager.h" #include "qdir.h" #include "qfile.h" #include "Global.h" #include "FontChina.h" MySqlLiteManager* MySqlLiteManager::instance = nullptr; QString MySqlLiteManager::dbname = "db"; QSqlDatabase MySqlLiteManager::db; MySqlLiteManager::MySqlLiteManager() { } MySqlLiteManager::~MySqlLiteManager() { } MySqlLiteManager* MySqlLiteManager::getInstance(){ if (instance == nullptr){ instance = new MySqlLiteManager; QString path; QDir dir; path = dir.currentPath(); bool isCreate = QFile::exists(path + "/" + dbname); if (!instance->openDatabase()){ addConsoleInfo("打开数据库失败"); } if (!isCreate){ if (!instance->createTable()){ addConsoleInfo("创建数据表失败"); } } } return instance; } bool MySqlLiteManager::openDatabase() { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(dbname); if (!db.open()){ return false; } return true; } bool MySqlLiteManager::createTable() { QSqlQuery query(db); query.exec("DROP table dbtable"); QString tablename = "dbtable"; bool result = query.exec("create table " + tablename + " (id int primary key, ConfFile varchar(255), dir varchar(255)," + " preShowPath varchar(255), logIndex int, textureCMD varchar(255), imageOptimizeCMD varchar(255), templateDir varchar(255))"); if (!result)return false; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) QString insert_table = "insert into " + tablename + " values(1, '', '" + QDir::currentPath() + "', '" + QDir::currentPath() + "/../Castle/Castle.exe" + "', 0, '../TexturePacker/bin/TexturePacker.exe', '../TexturePacker/pngquant.exe', '../Resources/template')"; #else QString insert_table = "insert into " + tablename + " values(1, '', '" + QDir::currentPath() + "', '" + QDir::currentPath() + "/../Castle.app/Contents/MacOS/Castle" + "', 0, '../TexturePacker.app/Contents/MacOS/TexturePacker', '../TexturePacker/pngquant.exe', '../Resources/template')"; #endif if (!query.exec(insert_table)){ return false; } return true; } QString MySqlLiteManager::getConfigFile() { return baseQuery("ConfFile", ""); } bool MySqlLiteManager::setConfigFile(QString file) { return baseUpdate("ConfFile", file); } QString MySqlLiteManager::getOpenDir() { return baseQuery("dir", ""); } bool MySqlLiteManager::setOpenDir(QString dir) { return baseUpdate("dir", dir); } QString MySqlLiteManager::getPreShowPath() { return baseQuery("preShowPath", ""); } bool MySqlLiteManager::setPreShowPath(QString path) { return baseUpdate("preShowPath", path); } int MySqlLiteManager::getLogIndex() { return baseQuery("logIndex", -1); } bool MySqlLiteManager::setLogIndex(int index) { return baseUpdate("logIndex", index); } QString MySqlLiteManager::getTemplateDir() { return baseQuery("templateDir", ""); } QString MySqlLiteManager::getTextureCMD() { return baseQuery("textureCMD", ""); } QString MySqlLiteManager::getImageOptimizeCMD() { return baseQuery("imageOptimizeCMD", ""); } bool MySqlLiteManager::baseUpdate(QString field, QString value) { QString update_sql = "update dbtable set " + field + " = :parameter where id = 1"; QSqlQuery query(db); query.prepare(update_sql); query.bindValue(":parameter", value); return query.exec(); } bool MySqlLiteManager::baseUpdate(QString field, int value) { QString update_sql = "update dbtable set " + field + " = :parameter where id = 1"; QSqlQuery query(db); query.prepare(update_sql); query.bindValue(":parameter", value); return query.exec(); } QString MySqlLiteManager::baseQuery(QString field, QString type_) { QString select_sql = "select " + field + " from dbtable where id = 1"; QSqlQuery query(db); query.exec(select_sql); while (query.next()){ return query.value(field).toString(); } return ""; } int MySqlLiteManager::baseQuery(QString field, int type_) { QString select_sql = "select " + field + " from dbtable where id = 1"; QSqlQuery query(db); query.exec(select_sql); while (query.next()){ return query.value(field).toInt(); } return -1; }
[ "793620896@qq.com" ]
793620896@qq.com
263d507c9b839c210a453dc2fb1571724dd0cb26
bd8fb057d74637d375cad5547fcaf4365204bfd3
/mbed.h
4849af633ee61e4c268539e4a5cfebe569bc5d8e
[]
no_license
trnila/apps-pwm-simulator
6c48b8c76b7e1f76a838e4191e3a82d1276b40fa
128159abc52b68a684c5a6d242522b7bdae04500
refs/heads/master
2021-01-13T22:03:30.721951
2020-02-25T20:51:44
2020-02-25T20:51:44
242,508,654
0
0
null
null
null
null
UTF-8
C++
false
false
3,806
h
#include <stdio.h> #include <stdlib.h> #include <vector> #include <stdint.h> #include <thread> #include <mutex> #include <chrono> #include <condition_variable> typedef enum { PTC0, PTC1, PTC2, PTC3, PTC4, PTC5, PTC7, PTC8, PinLast, } PinName; namespace sim { using namespace std::chrono_literals; const char *pin_names[] { "PTC0", "PTC1", "PTC2", "PTC3", "PTC4", "PTC5", "PTC7", "PTC8", }; struct Pin { uint64_t start_t; uint64_t change_t; int prev_state; int cur_state; uint32_t period_ms; uint32_t duty_ms; }; struct Pin pins[PinLast]; uint64_t tick; FILE *csv; std::thread ticker_thread_handle; std::mutex lock; std::mutex wait_lock; std::condition_variable wait_cv; typedef void (*Callback)(); typedef struct { Callback cb; uint64_t tick; } RegisteredCb; std::vector<RegisteredCb> callbacks; void ticker_thread() { char line[128]; for(;;) { tick++; { std::lock_guard<std::mutex> guard(sim::lock); for(auto &item: callbacks) { if(tick % item.tick == 0) { item.cb(); } } } int len = 0; for(int i = 0; i < PinLast; i++) { struct Pin *pin = &pins[i]; if(pin->prev_state == 0 && pin->cur_state == 1) { pin->period_ms = tick - pin->start_t; pin->duty_ms = pin->period_ms - (tick - pin->change_t); pin->start_t = tick; } else if(pin->prev_state == 1 && pin->cur_state == 0) { pin->change_t = tick; } pin->prev_state = pin->cur_state; len += sprintf(line + len, "%d", pin->cur_state); if(i + 1 != PinLast) { line[len++] = ','; } } line[len++] = '\n'; fwrite(line, len, 1, csv); fflush(csv); for(int i = 0; i < PinLast; i++) { struct Pin *pin = &pins[i]; int active_percent = 0; if(pin->period_ms != 0) { active_percent = pin->duty_ms * 100 / pin->period_ms; } if(tick - pin->start_t > 100) { printf("--/-- (%3d%%) ", pin->cur_state ? 100 : 0); } else { printf("%2d/%2d (%3d%%) ", pin->duty_ms, pin->period_ms, active_percent); } } printf("\n"); std::this_thread::sleep_for(1ms); wait_cv.notify_one(); } } void sim_init() { csv = fopen("record.csv", "w"); for(int i = 0; i < PinLast; i++) { fprintf(csv, "%s", pin_names[i]); if(i + 1 != PinLast) { fprintf(csv, ","); } } fprintf(csv, "\n"); ticker_thread_handle = std::thread(ticker_thread); } } class DigitalOut { private: PinName name; public: DigitalOut(PinName name): name(name) {} void write(int value) { sim::pins[name].cur_state = value; } DigitalOut& operator= (int value) { write(value); return *this; } int read() { return sim::pins[name].cur_state; } operator int() { return read(); } }; class Ticker { public: void attach(void (*fn)(), float sec) { std::lock_guard<std::mutex> guard(sim::lock); sim::callbacks.push_back({fn, (uint64_t) (sec * 1000)}); } void attach_us(void (*fn)(), uint64_t usec) { std::lock_guard<std::mutex> guard(sim::lock); sim::callbacks.push_back({fn, usec / 1000}); } }; void wait_us(int usec) { uint64_t start = sim::tick; std::unique_lock<std::mutex> guard(sim::wait_lock); sim::wait_cv.wait(guard, [=] { return sim::tick - start >= usec / 1000; }); } void wait_ms(int ms) { wait_us(ms * 1000); } void wait(float sec) { wait_us(sec * 1000000); } int your_main(); int main() { sim::sim_init(); your_main(); printf("main returned...\n"); } #define main your_main
[ "daniel.trnka@gmail.com" ]
daniel.trnka@gmail.com
b8a9599a722630d24a0699eb474f3d801a275bcb
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2259_httpd-2.0.58.cpp
42f0f94951f7238eaccbf39e769d95e454fb3967
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,152
cpp
static void wakeup_listener(void) { apr_status_t rv; listener_may_exit = 1; if (!idle_worker_stack) { return; } if ((rv = apr_thread_mutex_lock(idle_worker_stack->mutex)) != APR_SUCCESS) { return; } if ((rv = apr_thread_cond_signal(idle_worker_stack->cond)) != APR_SUCCESS) { return; } if ((rv = apr_thread_mutex_unlock(idle_worker_stack->mutex)) != APR_SUCCESS) { return; } if (!listener_os_thread) { /* XXX there is an obscure path that this doesn't handle perfectly: * right after listener thread is created but before * listener_os_thread is set, the first worker thread hits an * error and starts graceful termination */ return; } /* * we should just be able to "kill(ap_my_pid, LISTENER_SIGNAL)" on all * platforms and wake up the listener thread since it is the only thread * with SIGHUP unblocked, but that doesn't work on Linux */ #ifdef HAVE_PTHREAD_KILL pthread_kill(*listener_os_thread, LISTENER_SIGNAL); #else kill(ap_my_pid, LISTENER_SIGNAL); #endif }
[ "993273596@qq.com" ]
993273596@qq.com
99c8e2c2960b0c10fa866e5ae9ac17a14578f976
a8804f93227e46fd41ac9c6c4ba7e91ee5bf6a93
/cchef/aug14/ac/mou2h/tst.cpp
1508e3fb02ef0d998f4209224167708b8a8974d5
[]
no_license
caioaao/cp-solutions
9a2b3552a09fbc22ee8c3494d54ca1e7de7269a9
8a2941a394cf09913f9cae85ae7aedfafe76a43e
refs/heads/master
2021-01-17T10:22:27.607305
2020-07-04T15:37:01
2020-07-04T15:37:01
35,003,033
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
#include <bits/stdc++.h> using namespace std; set<vector<int> > poss; vector<int> vals; int main(){ int n; cin >> n; int last, x; cin >> last; for(int i = 1; i < n; i++){ cin >> x; vals.push_back(x-last); last = x; } int ant; for(int bm = 1; bm < (1<<vals.size()); bm++){ vector<int> s; for(int i = 0; i < (int)vals.size(); i++)if((1<<i) & bm){ s.push_back(vals[i]); } ant = poss.size(); poss.insert(s); if(ant != poss.size()){ cout << poss.size() << ':'; for(int i = 0; i < (int)s.size(); i++) cout << s[i] << ' '; cout << endl; } } }
[ "caioaao@gmail.com" ]
caioaao@gmail.com
0d31467836de4a078807d061b79561898855fad6
7c710df7e6287eb4585670ff3243903e8db3521a
/More Team References/testMCL team reference/acm biblio/number_theory/primitive_root.cpp
611a19723fc05081981db126f0b4016a4cad14b3
[]
no_license
e1Ru1o/UH-Top-reference
e71eeb6cc1bde9890513a8e2c6a6bb4856ee93aa
5ea4e1bfc6400ab4bec48eb193781ff13666c8d4
refs/heads/master
2023-06-04T02:52:15.826936
2021-06-21T21:35:22
2021-06-21T21:35:22
378,982,744
2
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
/* Find a primitive root of m Note: Only 2, 4, p^n, 2p^n have primitive roots Tested: http://codeforces.com/contest/488/problem/E */ ll primitive_root(ll m) { if (m == 1) return 0; if (m == 2) return 1; if (m == 4) return 3; auto pr = primes(0, sqrt(m) + 1); // fix upper bound ll t = m; if (!(t & 1)) t >>= 1; for (ll p : pr) { if(p > t) break; if (t % p) continue; do t /= p; while (t % p == 0); if (t > 1 || p == 2) return 0; } ll x = euler_phi(m), y = x, n = 0; vector<ll> f(32); for (ll p : pr) { if (p > y) break; if (y % p) continue; do y /= p; while (y % p == 0); f[n++] = p; } if (y > 1) f[n++] = y; for (ll i = 1; i < m; ++i) { if (__gcd(i, m) > 1) continue; bool flag = 1; for (ll j = 0; j < n; ++j) { if (pow(i, x / f[j], m) == 1) { flag = 0; break; } } if (flag) return i; } return 0; }
[ "riglesiasvera@gmail.com" ]
riglesiasvera@gmail.com
751216ff63f6e53ede6d65ee584a8f5fe0eb8c2e
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/core/include/functions/scalar/unique.hpp
d027787f1e01489da9be336089f98dbaefda331d
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
222
hpp
#ifndef NT2_CORE_INCLUDE_FUNCTIONS_SCALAR_UNIQUE_HPP_INCLUDED #define NT2_CORE_INCLUDE_FUNCTIONS_SCALAR_UNIQUE_HPP_INCLUDED #include <nt2/core/functions/unique.hpp> #include <nt2/core/functions/scalar/unique.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
dd84765c3a7635671191fc9f5956f349fad1ef3b
5ccdec8e96384389197d9f842ce7d9a93479b84c
/src/Model.h
a44ac64bdf0b6fddda623ad36c651c15c50363f4
[ "MIT" ]
permissive
bananu7/MiniCraft
521a107ca3421c3aa77ac86071eda896559886b9
3acfc0120ad7d49ed038106f27da3a3a6cc2d92f
refs/heads/master
2021-01-17T04:46:05.996109
2016-07-22T08:15:14
2016-07-22T08:15:14
8,126,518
6
0
null
2013-07-18T13:01:53
2013-02-10T18:58:04
C++
UTF-8
C++
false
false
5,058
h
#pragma once #include <assimp/cimport.h> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <glm/glm.hpp> #include "VertexBuffer.h" #include "VertexAttributeArray.h" #include "Shader.h" #include <string> #include <vector> #include <memory> class Model { std::unique_ptr<const aiScene, decltype(&aiReleaseImport)> scene; //std::unique_ptr<const aiScene, void (*)(const aiScene*)> scene; works engine::VertexBuffer vbo, texVbo, normVbo; engine::VertexAttributeArray vao; std::shared_ptr<engine::Program> shader; unsigned vertexCount; template<typename Functor> void recursiveIterate (Functor&& f, const aiNode* node, const aiScene* scene) { f(node, scene); for (int n = 0; n < node->mNumChildren; ++n) { recursiveIterate(std::forward<Functor>(f), node->mChildren[n], scene); } } void rebuildData () { std::vector<glm::vec3> vertices; std::vector<glm::vec3> normals; std::vector<glm::vec2> texCoords; auto addVertex = [&vertices, &normals, &texCoords](const aiNode* node, const aiScene* scene) { aiMatrix4x4 m = node->mTransformation; // update transform //aiTransposeMatrix4(&m); //glPushMatrix(); //glMultMatrixf((float*)&m); // draw all meshes assigned to this node for (unsigned n = 0; n < node->mNumMeshes; ++n) { const aiMesh* mesh = scene->mMeshes[node->mMeshes[n]]; //apply_material(scene->mMaterials[mesh->mMaterialIndex]); /*if(mesh->mNormals == NULL) { glDisable(GL_LIGHTING); } else { glEnable(GL_LIGHTING); }*/ for (unsigned t = 0; t < mesh->mNumFaces; ++t) { const aiFace* face = &mesh->mFaces[t]; GLenum face_mode; if (face->mNumIndices != 3) throw std::runtime_error("Non-triangulised mesh provided!"); //glBegin(face_mode); // TEMP : non indexed mode on. bool haveNormals = mesh->mNormals != nullptr; // texture coordinates and colors can have multiple layers bool haveTexcoords = mesh->mTextureCoords[0] != nullptr; //if(mesh->mColors[0] != NULL) if (!haveNormals) throw std::runtime_error("Model without normals provided!"); if (!haveTexcoords) throw std::runtime_error("Model without texture coords provided!"); for(unsigned i = 0; i < face->mNumIndices; i++) { int index = face->mIndices[i]; if (haveNormals) { normals.push_back(glm::vec3( mesh->mNormals[index].x, mesh->mNormals[index].y, mesh->mNormals[index].z )); } if (haveTexcoords) { texCoords.push_back(glm::vec2( mesh->mTextureCoords[0][index].x, mesh->mTextureCoords[0][index].y )); } vertices.push_back(glm::vec3( mesh->mVertices[index].x, mesh->mVertices[index].y, mesh->mVertices[index].z )); } } } }; recursiveIterate(addVertex, scene->mRootNode, scene.get()); vbo.LoadData(vertices.data(), vertices.size() * sizeof(glm::vec3)); normVbo.LoadData(normals.data(), normals.size() * sizeof(glm::vec3)); texVbo.LoadData(texCoords.data(), texCoords.size() * sizeof(glm::vec3)); vertexCount = vertices.size(); } public: Model(std::string const& path, std::shared_ptr<engine::Program> program) : scene(aiImportFile(path.c_str(),aiProcessPreset_TargetRealtime_MaxQuality), aiReleaseImport) , vbo(engine::VertexBuffer::DATA_BUFFER, engine::VertexBuffer::STATIC_DRAW) , vertexCount(0u) , shader(program) { rebuildData(); vao.EnableAttributeArray(0); vbo.Bind(); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); vao.EnableAttributeArray(1); texVbo.Bind(); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); vao.EnableAttributeArray(2); normVbo.Bind(); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); } std::shared_ptr<engine::Program>& getShader() { return shader; } void draw() { shader->Bind(); vao.Bind(); glDrawArrays(GL_TRIANGLES, 0, vertexCount); } };
[ "bananu7@o2.pl" ]
bananu7@o2.pl
29aee8164fca8c06776e076abc19995ec04db34e
b8abaaf2f7a1f94efe3bbc0d14ca49228471b43f
/MomokoMain/include/Window.h
ce7258ee4b5865f7cd1b68cfdc4e09f7214e44d3
[]
no_license
julsam/Momoko-Engine
e8cf8a2ad4de6b3925c8c85dc66272e7602e7e73
7503a2a81d53bf569eb760c890158d4f38d9baf9
refs/heads/master
2021-01-22T12:08:41.642354
2011-04-12T11:12:21
2011-04-12T11:12:21
1,494,202
2
0
null
null
null
null
UTF-8
C++
false
false
701
h
#ifndef _WINDOW_H #define _WINDOW_H #include <iostream> #include <string> #include "SDL.h" #include <GL/gl.h> #include "Vector2.h" class Window { public: Window(std::string _caption, int _w, int _h, bool _fullscreen); ~Window(); bool init(); static bool reshape(const int _w, const int _h); static Vector2 getWindowSize(); static void swapBuffers(); static void changeFullscreen(); static void setCaption(const std::string& title); private: bool setupVideoMode(); private: static Window *instance; SDL_Surface* m_surface; std::string m_caption; Vector2 m_windowSize; bool m_fullscreen; Vector2 m_sysResolution; }; #endif // _WINDOW_H
[ "bender@bender-labs.org" ]
bender@bender-labs.org
d9d3b7bd84c50fd98144cd7aa3fcd61755a8132c
0fc0a829054117da442f42d0c12cefcb03da6f62
/f4mp_server/main.cpp
d237e61f7ad5ddaf123397beb11f24fb1772a929
[]
no_license
SilentModders/F4MP
e439e08fab20caad24602a2c47e5f06df7f1dc61
d8e9dbb60a2656227c657f3becd6eede924c1e9e
refs/heads/master
2022-08-23T07:34:14.917487
2020-05-23T17:13:51
2020-05-23T17:13:51
273,619,118
1
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#define LIBRG_IMPLEMENTATION //#define LIBRG_DISABLE_FEATURE_ENTITY_VISIBILITY #include "Server.h" #include <iostream> #include <fstream> f4mp::Server* f4mp::Server::instance = nullptr; int main() { const std::string configFilePath = "server_config.txt"; std::string address; std::ifstream config(configFilePath); if (config) { config >> address; config.close(); } else { std::cout << "address? "; std::cin >> address; std::ofstream file(configFilePath); file << address; } f4mp::Server* server = new f4mp::Server(address); return 0; }
[ "rhrh1363@gmail.com" ]
rhrh1363@gmail.com
3e8aed9d89c1cc7927df9bc1aeb3434ba81fe9bf
8dff49c4dc92983cbd0934725f97224fd9754d1d
/CPE/299.cpp
e1925ee3c87181049adff4f5a4cead6a8bb2844c
[]
no_license
cherry900606/OJ_Solutions
1c7360ca35252aec459ef01d8e6a485778d32653
b70f8baed30f446421fd39f311f1d5071a441734
refs/heads/main
2023-05-14T13:38:44.475393
2021-06-19T07:29:35
2021-06-19T07:29:35
378,026,385
1
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
#include <iostream> using namespace std; int main() { int n; cin>>n; while(n--) { int l,train[51],times=0; cin>>l; for(int i=0;i<l;i++) cin>>train[i]; for(int i=0;i<l;i++) { for(int j=i;j<l;j++) { if(train[i]>train[j]) { swap(train[i],train[j]); times++; } } } cout<<"Optimal train swapping takes "<<times<<" swaps."<<endl; } return 0; }
[ "cherry900606@gmail.com" ]
cherry900606@gmail.com
4f8b3819584f6ac9d430816539c7a113411b07c9
0edbcda83b7a9542f15f706573a8e21da51f6020
/private/inet/urlmon/search/protbase.hxx
af956a2f3f6b2efa4b165cf3b535cb9bf47e70ef
[]
no_license
yair-k/Win2000SRC
fe9f6f62e60e9bece135af15359bb80d3b65dc6a
fd809a81098565b33f52d0f65925159de8f4c337
refs/heads/main
2023-04-12T08:28:31.485426
2021-05-08T22:47:00
2021-05-08T22:47:00
365,623,923
1
3
null
null
null
null
UTF-8
C++
false
false
3,902
hxx
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1995. // // File: protbase.hxx // // Contents: // // Classes: // // Functions: // // History: 11-07-1996 JohannP (Johann Posch) Created // //---------------------------------------------------------------------------- #ifndef _PROTBASE_HXX_ #define _PROTBASE_HXX_ #define offsetof(s,m) (size_t)&(((s *)0)->m) #define GETPPARENT(pmemb, struc, membname) ((struc FAR *)(((char FAR *)(pmemb))-offsetof(struc, membname))) #define MAX_URL_SIZE INTERNET_MAX_URL_LENGTH // this will be in a common header file #define S_NEEDMOREDATA ((HRESULT)0x00000002L) #define BSCF_ASYNCDATANOTIFICATION 0x00010000 #define BSCF_DATAFULLYAVAILABLE 0x00020000 class CBaseProtocol : public IOInetProtocol, public IOInetThreadSwitch, public IOInetPriority { public: // IUnknown methods STDMETHODIMP QueryInterface(REFIID iid, void **ppvObj); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); STDMETHODIMP Start(LPCWSTR szUrl,IOInetProtocolSink *pProtSink, IOInetBindInfo *pOIBindInfo,DWORD grfSTI,DWORD dwReserved); STDMETHODIMP Continue(PROTOCOLDATA *pStateInfo); STDMETHODIMP Abort(HRESULT hrReason,DWORD dwOptions); STDMETHODIMP Terminate(DWORD dwOptions); STDMETHODIMP Suspend(); STDMETHODIMP Resume(); STDMETHODIMP Read(void *pv,ULONG cb,ULONG *pcbRead); STDMETHODIMP Seek(LARGE_INTEGER dlibMove,DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition); STDMETHODIMP LockRequest(DWORD dwOptions); STDMETHODIMP UnlockRequest(); // IOInetPriority STDMETHODIMP SetPriority(LONG nPriority); STDMETHODIMP GetPriority(LONG * pnPriority); // IOInetThreadSwitch STDMETHODIMP Prepare(); STDMETHODIMP Continue(); public: CBaseProtocol(REFCLSID rclsid, IUnknown *pUnkOuter, IUnknown **ppUnkInner); virtual ~CBaseProtocol(); BOOL OpenTempFile(); BOOL CloseTempFile(); BOOL IsApartmentThread() { TransAssert((_dwThreadID != 0)); return (_dwThreadID == GetCurrentThreadId()); } protected: CRefCount _CRefs; // the total refcount of this object DWORD _dwThreadID; LPTSTR _pszUrl; TCHAR _szNewUrl[MAX_URL_SIZE + 1]; IOInetProtocolSink *_pProtSink; IOInetBindInfo *_pOIBindInfo; REFCLSID _pclsidProtocol; DWORD _bscf; DWORD _grfBindF; BINDINFO _BndInfo; IOInetProtocol *_pProt; class CPrivUnknown : public IUnknown { public: STDMETHOD(QueryInterface) ( REFIID riid, LPVOID FAR* ppvObj); STDMETHOD_(ULONG,AddRef) (void); STDMETHOD_(ULONG,Release) (void); ~CPrivUnknown() {} CPrivUnknown() : _CRefs() {} private: CRefCount _CRefs; // the total refcount of this object }; friend class CPrivUnknown; CPrivUnknown _Unknown; IUnknown *_pUnkOuter; STDMETHODIMP_(ULONG) PrivAddRef() { return _Unknown.AddRef(); } STDMETHODIMP_(ULONG) PrivRelease() { return _Unknown.Release(); } }; LPWSTR OLESTRDuplicate(LPWSTR ws); LPSTR DupW2A(const WCHAR *pwz); LPWSTR DupA2W(const LPSTR psz); HRESULT CreateAPP(REFCLSID rclsid, IUnknown *pUnkOuter, REFIID riid, IUnknown **ppUnk); inline void W2A(LPCWSTR lpwszWide, LPSTR lpszAnsi, int cchAnsi) { WideCharToMultiByte(CP_ACP,0,lpwszWide,-1,lpszAnsi,cchAnsi,NULL,NULL); } inline void A2W(LPSTR lpszAnsi,LPWSTR lpwszWide, int cchAnsi) { MultiByteToWideChar(CP_ACP,0,lpszAnsi,-1,lpwszWide,cchAnsi); } #ifndef ARRAYSIZE #define ARRAYSIZE(a) (sizeof(a)/sizeof(a[0])) #endif #endif // _PROTBASE_HXX_
[ "ykorokhov@pace.ca" ]
ykorokhov@pace.ca
539a1b64bca43c3d319c43b0f8c430b096aa4d56
09a43ac5b76aaebd2319c0b880e3078c8ea48e7e
/PROJEKT/classes/objects/Dirt.h
86a394f0c7c3454f0791eb407a6d08e385a2ecad
[ "Apache-2.0" ]
permissive
Darono87/boulderDash
89ea600a3dce4fbbf50e9addc2e8f7bd7fc8dcd8
31dd9235e0cffc34e2aa797c3eff193a6de60bcb
refs/heads/master
2020-12-22T01:06:30.607855
2020-01-28T00:18:30
2020-01-28T00:18:30
236,624,918
0
0
null
null
null
null
UTF-8
C++
false
false
891
h
#ifndef DIRTH #define DIRTH #include "Eventaware.h" using namespace std; class Dirt : public EventAwareSprite{ TextureManager& innerTexture; public: Dirt(int x, int y, Board* root) : EventAwareSprite(x,y,root), innerTexture(TextureManager::getTextureDirt()){ setTexture(innerTexture); }; int objectEnter(EventAwareSprite* another ,int direction){root->elements[boardX][boardY] = nullptr; delete this; return 1;}; virtual int eventCheck(int code){return -1;} //not a single event really concerns dirt // check function, whether an event with a code for example 101 can fire or not. Also detects the situation when the event isn't needed anymore virtual void eventExecute(int code){} virtual bool acceptEvent(int code){return false;} // Function to execute in case of an event with int code }; #endif
[ "darono87@gmail.com" ]
darono87@gmail.com
e9911ff9a2d44ce3c9c664868badc50f149d4da2
13c0eb1f39135849c6c5fd32b0edfdea55980f5e
/pLib/Containers/pMap.h
e18a5abed843c5aa2af5f9db00fb3df6c0a018d2
[ "Unlicense" ]
permissive
bendapootie/pLib
5027bfa3ae492573f6cc2ae04ea08f95bef42ca6
fc11f3e9006421590c398ad7a492447a011adeae
refs/heads/master
2023-03-14T03:28:49.825619
2021-02-26T15:37:35
2021-02-26T15:37:35
270,486,236
0
0
null
null
null
null
UTF-8
C++
false
false
2,382
h
#pragma once #include "pLib.h" // TODO: Remove all STL includes #include <map> template <class KeyType, class ValueType> class pMap { public: // Returns the number of entries in the map int Count() const { return (int)m_map.size(); } // Returns 'true' if the list has no entries (ie. Count == 0) bool IsEmpty() const { return Count() == 0; } // Removes all values from the map and sets its Count to 0 void Clear() { m_map.clear(); } // Returns true if map has an entry for the given key bool HasKey(const KeyType& _key) const { return m_map.find(_key) != m_map.end(); } // Adds a key/value pair to the map // If key already exists, sets the value associated with the key void Add(const KeyType& _key, const ValueType& _value) { m_map[_key] = _value; } // Bracket operator for accessing map values via key // Note: If the key does not exist, this will create an entry and return a default object ValueType& operator[](const KeyType& _key) { return m_map[_key]; } // Function for finding values without risk of creating a default value bool TryGetValue(const KeyType& _key, __out ValueType* _outValue) const { auto it = m_map.find(_key); if (it != m_map.end()) { *_outValue = it->second; return true; } return false; } // Returns pointer to value in map or null if key isn't found // Note: This pointer is only valid until an add or remove is made to the map const ValueType* FindPointerToValue(const KeyType& _key) const { auto it = m_map.find(_key); if (it != m_map.end()) { return &it->second; } return nullptr; } ValueType* FindPointerToValue(const KeyType& _key) { return const_cast<ValueType*>(const_cast<const pMap<KeyType, ValueType>*>(this)->FindPointerToValue(_key)); } pList<KeyType> GetListOfKeys() const { pList<KeyType> keys; for (auto it = m_map.begin(); it != m_map.end(); it++) { keys.Add(it->first); } return keys; } // Removes an element from the map by key void Remove(const KeyType& _key) { m_map.erase(_key); } // Returns 'true' if the given key has an entry in the map bool Contains(const KeyType& _key) const { return (m_map.find(_key) != m_map.end()); } // TODO: Support for-each operator // - Need iterator, const_iterator, and const/non-const versions of begin() and end() private: // TODO: Make this not use std::map std::map<KeyType, ValueType> m_map; };
[ "petejunk@bluesmith.com" ]
petejunk@bluesmith.com
477c9c8f9b358788ea53a1540331d90b548438da
28d10fd75717247883fc580b5347762e30294d4e
/sw/dragon_leds.cpp
99db2f92a5eda44c076b700929b8a58aa1c2e07b
[]
no_license
acornacorn/dragon2014
55fb9e353ed40b38ad9d5953bbfca3b389b1c3d9
31a725719eb187a42227260cd5ce1acde8fbb71d
refs/heads/master
2020-05-07T10:17:06.460902
2014-11-01T20:40:13
2014-11-01T20:40:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
cpp
#include <dragon_leds.h> #include <dragon_pins.h> #include <dragon.h> #include <ac_printf.h> #include <ac_led_rgb.h> #include <ac_counter.h> #include <Arduino.h> static const bool DEBUG_LEDS = false; AcLedRgb g_eyes; static AcCounter g_led_tst_cnt; void dragonLedInit() { g_eyes.init(dpin_eye_red, dpin_eye_green, dpin_eye_blue); g_led_tst_cnt.init(1000, 6); } void dragonLedColorSet( int r, int g, int b) { g_eyes.set(r,g,b); if (DEBUG_LEDS) acPrintf("Color: %d %d %d\n",r,g,b); } void dragonLedColorShiftTo( int r, int g, int b, int duration_millis) { g_eyes.shiftTo(r,g,b,duration_millis); if (DEBUG_LEDS) { acPrintf("Color: shift to %d %d %d dur=%d\n", r,g,b,duration_millis); } } void dragonLedUpdate() { g_eyes.update(); if (g_dragon.getMode() == Dragon::MODE_TEST) { uint32_t val; if (g_led_tst_cnt.check(&val)) { switch(val) { case 0: dragonLedColorShiftTo(255,0,0,500); break; case 1: dragonLedColorShiftTo(0,255,0,500); break; case 2: dragonLedColorShiftTo(0,0,255,500); break; case 3: dragonLedColorShiftTo(255,255,0,500); break; case 4: dragonLedColorShiftTo(255,0,255,500); break; case 5: dragonLedColorShiftTo(0,255,255,500); break; } } } }
[ "acorn@mad.scientist.com" ]
acorn@mad.scientist.com
e7543078b84b9aa24bd867ea7df9bb18dbf3d8b7
b2f9110eb40e8efc9c96769de6b128fda32e5e4c
/weak_ptr.cpp
d83268022e8da0bbfb372797971bb78c83d03e21
[]
no_license
sittu071/cpp
032d54384517f1aa0962ceec76e1b4f72f63062e
2078f38a10173b58c58f987017b9141c7a65f284
refs/heads/master
2023-07-19T20:04:37.287503
2023-07-18T03:23:22
2023-07-18T03:23:22
226,220,639
0
0
null
null
null
null
UTF-8
C++
false
false
434
cpp
#include <iostream> #include <memory> using namespace std; class B; class A { public: shared_ptr<B> bSharedPtr; ~A(){} }; class B { public: weak_ptr<A> aWeakPtr; ~B(){} }; int main() { shared_ptr<A> aPtr = make_shared<A>(); shared_ptr<B> bPtr = make_shared<B>(); aPtr->bSharedPtr = bPtr; bPtr->aWeakPtr = aPtr; cout<<aPtr.use_count()<<endl; cout<<bPtr.use_count()<<endl; }
[ "noreply@github.com" ]
noreply@github.com
fb064cca54d299d449642dcc662f43247b40c697
fda4f7b9bd0a0a834911de3e57820acb165f5e5e
/src/GameOverState.cpp
1cf01cc3a8d7500eb6b065de48bf024ad3476452
[]
no_license
keshav2010/SDLtest
89c69bb9683f7bf5a1d3df04990d67426713e3b2
2da02ec7b99ddb47c1452c264578273f60b07dbd
refs/heads/master
2021-08-30T05:28:59.289859
2017-12-03T10:57:30
2017-12-03T10:57:30
103,767,125
0
0
null
2017-09-26T21:24:30
2017-09-16T16:33:39
C++
UTF-8
C++
false
false
1,939
cpp
#include "GameOverState.h" #include "MenuButton.h" #include "AnimatedGraphic.h" #include "LoaderParams.h" using namespace std; const string GameOverState::s_gameOverID = "GAMEOVER"; string GameOverState::getStateID() const { return s_gameOverID; } void GameOverState::s_gameOverToMain() { TheGame::Instance()->getGameStateMachine()->changeState(new MenuState()); } void GameOverState::s_restartPlay() { TheGame::Instance()->getGameStateMachine()->changeState(new PlayState()); } void GameOverState::update() { for(int i=0; i<gameObjects.size(); i++) gameObjects[i]->update(); } void GameOverState::render() { for(int i=0; i<gameObjects.size(); i++) gameObjects[i]->draw(); } bool GameOverState::onEnter() { //load textures if(!TheTextureManager::Instance()->load("res/gameover.bmp", "gameovertext", TheGame::Instance()->getRenderer())) return false; if(!TheTextureManager::Instance()->load("res/main.bmp", "mainbutton", TheGame::Instance()->getRenderer())) return false; //init game objects, and assign loaded texture to them GameObject *gameOverText = new AnimatedGraphic(new LoaderParams(200,100,190,30,"gameovertext"), 1); GameObject *button1 = new MenuButton(new LoaderParams(200,200,200,80, "mainbutton"), s_gameOverToMain); GameObject *button2 = new MenuButton(new LoaderParams(200,300,200,80,"restartbutton"), s_restartPlay); //include game objects in the state objects list so as to manipulate them , render them gameObjects.push_back(gameOverText); gameObjects.push_back(button1); gameObjects.push_back(button2); return true; } bool GameOverState::onExit() { for(int i=0; i<gameObjects.size(); i++) gameObjects[i]->clean(); gameObjects.clear(); TheTextureManager::Instance()->clearFromTextureMap("gameovertext"); TheTextureManager::Instance()->clearFromTextureMap("mainbutton"); return true; }
[ "sharmakeshav15157@gmail.com" ]
sharmakeshav15157@gmail.com
88cf1ebfc6982f5c821fd8f36f9fff538091bdcf
1f0a59409972f72a2a766e2c33927f5aaf6646a6
/ex1/Person.cpp
161dab2224ee7beb9a05cbc32e8b3d1008e3de89
[]
no_license
BorisKolev/Cpp-Assignment
e671a15b5a246a29261bdea8483402188fd8b39e
8d4f3a4eaba6f59f5509777bc496110d28165463
refs/heads/master
2020-12-19T05:32:01.389863
2020-01-22T17:59:51
2020-01-22T17:59:51
235,620,819
0
0
null
null
null
null
UTF-8
C++
false
false
202
cpp
#include "Person.h" Person::Person(const string &name) { this->name = name; } string Person::getName() const { return name; } void Person::changeName(const string &newName) { name = newName; }
[ "bk18145@essex.ac.uk" ]
bk18145@essex.ac.uk
8be7a074c7c802f5aaf179fa43a807ada3f2631e
987425005f1abd95a749394716559375818a695a
/各种OJ/LeftistTree.cpp
91862bb32caa211b926794cc096cac11b9d29119
[]
no_license
duny31030/My_road_of_ACM
b01db0334f33ce7f26a9fe83bd9e0646bba49a28
2de8c8f2d402dfc36f635174104a4923e03030b3
refs/heads/master
2020-03-10T04:32:24.505006
2019-01-03T07:31:27
2019-01-03T07:31:27
129,194,697
1
0
null
null
null
null
UTF-8
C++
false
false
2,152
cpp
/* * ========================================================================= * * Filename: LeftistTree.cpp * * Link: * * Version: 1.0 * Created: 2018/10/29 11时09分00秒 * Revision: none * Compiler: g++ * * Author: 杜宁元 (https://duny31030.top/), duny31030@126.com * Organization: QLU_浪在ACM * * ========================================================================= */ #include <bits/stdc++.h> using namespace std; #define clr(a, x) memset(a, x, sizeof(a)) #define rep(i,a,n) for(int i=a;i<=n;i++) #define pre(i,a,n) for(int i=n;i>=a;i--) #define ll long long #define max3(a,b,c) fmax(a,fmax(b,c)) #define ios ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); const double eps = 1e-6; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; const int N = 1e5+100; int ch[N][2],v[N],ht[N],f[N]; int n,q,tmp,x,y; int gf(int u) { while(f[u]) u = f[u]; return u; } // 这里为小根堆 // int merge(int x,int y) { if(!x || !y) return x+y; if(v[x] > v[y] || (v[x] == v[y] && x > y)) swap(x,y); ch[x][1] = merge(ch[x][1],y); f[ch[x][1]] = x; if(ht[ch[x][0]] < ht[ch[x][1]]) swap(ch[x][0],ch[x][1]); ht[x] = ht[ch[x][1]]+1; return x; } void pop(int x) { v[x] = -1; f[ch[x][0]] = f[ch[x][1]] = 0; merge(ch[x][0],ch[x][1]); } int main() { ios #ifdef ONLINE_JUDGE #else freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); #endif scanf("%d %d",&n,&q); rep(i,1,n) scanf("%d",&v[i]); rep(i,1,q) { scanf("%d",&tmp); if(tmp == 1) { scanf("%d %d",&x,&y); if(v[x] == -1 || v[y] == -1) continue; x = gf(x); y = gf(y); if(x == y) continue; merge(x,y); } else { scanf("%d",&x); if(v[x] == -1) printf("-1\n"); else { y = gf(x); printf("%d\n",v[y]); pop(y); } } } fclose(stdin); // fclose(stdout); return 0; }
[ "duny31030@126.com" ]
duny31030@126.com
2789e8c1b80dd61433aa44fafecd7dfa64d18e97
e2aaf43eb816138675e05b8e39142a1984bc0b6f
/src/surface.h
50eee53f8dd8ca2b0721e3767c918c84c77988aa
[]
no_license
BlockCat/mov_practice_1
a99893f0d92a4b5ca8a95f8e172cf3ea3a43f1e7
81c67d6dfbd9583537587ab41749ba10d66958c1
refs/heads/master
2020-03-28T10:56:58.133514
2018-09-12T05:44:59
2018-09-12T05:44:59
148,162,480
1
1
null
null
null
null
UTF-8
C++
false
false
4,493
h
// Template, major revision 6, update for INFOMOV // IGAD/NHTV/UU - Jacco Bikker - 2006-2016 #pragma once #include "template.h" namespace Tmpl8 { #define REDMASK (0xff0000) #define GREENMASK (0x00ff00) #define BLUEMASK (0x0000ff) typedef unsigned int Pixel; // unsigned int is assumed to be 32-bit, which seems a safe assumption. inline Pixel ScaleColor(Pixel c, int s) { const unsigned int rb = (((c & (REDMASK | BLUEMASK)) * s) >> 5) & (REDMASK | BLUEMASK); const unsigned int g = (((c & GREENMASK) * s) >> 5) & GREENMASK; return rb + g; } inline Pixel AddBlend(Pixel a_Color1, Pixel a_Color2) { const unsigned int r = (a_Color1 & REDMASK) + (a_Color2 & REDMASK); const unsigned int g = (a_Color1 & GREENMASK) + (a_Color2 & GREENMASK); const unsigned int b = (a_Color1 & BLUEMASK) + (a_Color2 & BLUEMASK); const unsigned r1 = (r & REDMASK) | (REDMASK * (r >> 24)); const unsigned g1 = (g & GREENMASK) | (GREENMASK * (g >> 16)); const unsigned b1 = (b & BLUEMASK) | (BLUEMASK * (b >> 8)); return (r1 + g1 + b1); } // subtractive blending inline Pixel SubBlend(Pixel a_Color1, Pixel a_Color2) { int red = (a_Color1 & REDMASK) - (a_Color2 & REDMASK); int green = (a_Color1 & GREENMASK) - (a_Color2 & GREENMASK); int blue = (a_Color1 & BLUEMASK) - (a_Color2 & BLUEMASK); if (red < 0) red = 0; if (green < 0) green = 0; if (blue < 0) blue = 0; return (Pixel)(red + green + blue); } class Surface { enum { OWNER = 1 }; public: // constructor / destructor Surface(int a_Width, int a_Height, Pixel* a_Buffer, int a_Pitch); Surface(int a_Width, int a_Height); Surface(char* a_File); ~Surface(); // member data access Pixel* GetBuffer() { return m_Buffer; } void SetBuffer(Pixel* a_Buffer) { m_Buffer = a_Buffer; } int GetWidth() { return m_Width; } int GetHeight() { return m_Height; } int GetPitch() { return m_Pitch; } void SetPitch(int a_Pitch) { m_Pitch = a_Pitch; } // Special operations void InitCharset(); void SetChar(int c, char* c1, char* c2, char* c3, char* c4, char* c5); void Centre(char* a_String, int y1, Pixel color); void Print(char* a_String, int x1, int y1, Pixel color); void Clear(Pixel a_Color); void Line(float x1, float y1, float x2, float y2, Pixel color); void Plot(int x, int y, Pixel c); void LoadImage(char* a_File); void CopyTo(Surface* a_Dst, int a_X, int a_Y); void BlendCopyTo(Surface* a_Dst, int a_X, int a_Y); void ScaleColor(unsigned int a_Scale); void Box(int x1, int y1, int x2, int y2, Pixel color); void Bar(int x1, int y1, int x2, int y2, Pixel color); void Resize(Surface* a_Orig); private: // Attributes Pixel* m_Buffer; int m_Width, m_Height; int m_Pitch; int m_Flags; // Static attributes for the buildin font static char s_Font[51][5][6]; static bool fontInitialized; int s_Transl[256]; }; class Sprite { public: // Sprite flags enum { FLARE = (1 << 0), OPFLARE = (1 << 1), FLASH = (1 << 4), DISABLED = (1 << 6), GMUL = (1 << 7), BLACKFLARE = (1 << 8), BRIGHTEST = (1 << 9), RFLARE = (1 << 12), GFLARE = (1 << 13), NOCLIP = (1 << 14) }; // Structors Sprite(Surface* a_Surface, unsigned int a_NumFrames); ~Sprite(); // Methods void Draw(Surface* a_Target, int a_X, int a_Y); void DrawScaled(int a_X, int a_Y, int a_Width, int a_Height, Surface* a_Target); void SetFlags(unsigned int a_Flags) { m_Flags = a_Flags; } void SetFrame(unsigned int a_Index) { m_CurrentFrame = a_Index; } unsigned int GetFlags() const { return m_Flags; } int GetWidth() { return m_Width; } int GetHeight() { return m_Height; } Pixel* GetBuffer() { return m_Surface->GetBuffer(); } unsigned int Frames() { return m_NumFrames; } Surface* GetSurface() { return m_Surface; } // Methods void InitializeStartData(); // Attributes int m_Width, m_Height, m_Pitch; unsigned int m_NumFrames; unsigned int m_CurrentFrame; unsigned int m_Flags; unsigned int** m_Start; Surface* m_Surface; }; class Font { public: Font(); Font(char* a_File, char* a_Chars); ~Font(); void Print(Surface* a_Target, char* a_Text, int a_X, int a_Y, bool clip = false); void Centre(Surface* a_Target, char* a_Text, int a_Y); int Width(char* a_Text); int Height() { return m_Surface->GetHeight(); } void YClip(int y1, int y2) { m_CY1 = y1; m_CY2 = y2; } private: Surface* m_Surface; int* m_Offset, *m_Width, *m_Trans, m_Height, m_CY1, m_CY2; }; }; // namespace Tmpl8
[ "zinoonomiwo@gmail.com" ]
zinoonomiwo@gmail.com
df1bc76e69302e6609c3793a8edd664d6bc04c38
2c3d596da726a64759c6c27d131c87c33a4e0bf4
/Src/VC/bcgcbpro/BCGPRibbonFloaty.cpp
1928ae6027f91d1ae21b7c5fc3810b39690f29d0
[ "MIT" ]
permissive
iclosure/smartsoft
8edd8e5471d0e51b81fc1f6c09239cd8722000c0
62eaed49efd8306642b928ef4f2d96e36aca6527
refs/heads/master
2021-09-03T01:11:29.778290
2018-01-04T12:09:25
2018-01-04T12:09:25
116,255,998
0
1
null
null
null
null
UTF-8
C++
false
false
7,972
cpp
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2012 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPRibbonFloaty.cpp : implementation file // #include "stdafx.h" #include "bcgcbpro.h" #include "BCGPRibbonFloaty.h" #include "BCGPRibbonBar.h" #include "bcgglobals.h" #include "BCGPContextMenuManager.h" #ifndef BCGP_EXCLUDE_RIBBON #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define ID_VISIBILITY_TIMER 1 ///////////////////////////////////////////////////////////////////////////// // CBCGPRibbonFloaty IMPLEMENT_DYNCREATE(CBCGPRibbonFloaty, CBCGPRibbonPanelMenu) CBCGPRibbonFloaty* CBCGPRibbonFloaty::m_pCurrent = NULL; CBCGPRibbonFloaty::CBCGPRibbonFloaty() { if (m_pCurrent != NULL) { m_pCurrent->SendMessage (WM_CLOSE); m_pCurrent = NULL; } m_wndRibbonBar.m_bIsFloaty = TRUE; m_bContextMenuMode = FALSE; m_nTransparency = 0; m_bWasHovered = FALSE; m_bDisableAnimation = TRUE; m_bIsOneRow = FALSE; m_bWasDroppedDown = FALSE; } //******************************************************************************* CBCGPRibbonFloaty::~CBCGPRibbonFloaty() { ASSERT (m_pCurrent == this); m_pCurrent = NULL; if (m_bContextMenuMode) { g_pContextMenuManager->SetDontCloseActiveMenu (FALSE); } } BEGIN_MESSAGE_MAP(CBCGPRibbonFloaty, CBCGPRibbonPanelMenu) //{{AFX_MSG_MAP(CBCGPRibbonFloaty) ON_WM_TIMER() ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CBCGPRibbonFloaty::SetCommands ( CBCGPRibbonBar* pRibbonBar, const CList<UINT,UINT>& lstCommands) { ASSERT_VALID (this); ASSERT_VALID (pRibbonBar); CArray<CBCGPBaseRibbonElement*, CBCGPBaseRibbonElement*> arButtons; for (POSITION pos = lstCommands.GetHeadPosition (); pos != NULL;) { UINT uiCmd = lstCommands.GetNext (pos); if (uiCmd == 0) { // TODO: add separator continue; } CBCGPBaseRibbonElement* pSrcElem = pRibbonBar->FindByID (uiCmd, FALSE); if (pSrcElem == NULL) { continue; } arButtons.Add (pSrcElem); } m_wndRibbonBar.AddButtons (pRibbonBar, arButtons, TRUE); } //******************************************************************************* BOOL CBCGPRibbonFloaty::Show (int x, int y) { ASSERT_VALID (this); m_wndRibbonBar.m_bIsOneRowFloaty = m_bIsOneRow; CSize size = m_wndRibbonBar.CalcSize (FALSE); if (!Create (m_wndRibbonBar.m_pRibbonBar, x, y - size.cy - ::GetSystemMetrics (SM_CYCURSOR) / 2, (HMENU) NULL)) { return FALSE; } m_pCurrent = this; ModifyStyleEx (0, WS_EX_LAYERED); UpdateTransparency (); globalData.SetLayeredAttrib (GetSafeHwnd (), 0, m_nTransparency, LWA_ALPHA); UpdateShadowTransparency (m_nTransparency); return TRUE; } //******************************************************************************* BOOL CBCGPRibbonFloaty::ShowWithContextMenu (int x, int y, UINT uiMenuResID, CWnd* pWndOwner) { ASSERT_VALID (this); if (CBCGPPopupMenu::GetActiveMenu () != NULL) { return FALSE; } if ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0) // Left mouse button is pressed { return FALSE; } if (g_pContextMenuManager == NULL) { ASSERT (FALSE); return FALSE; } if (x == -1 || y == -1) { return g_pContextMenuManager->ShowPopupMenu (uiMenuResID, x, y, pWndOwner); } CSize size = m_wndRibbonBar.CalcSize (FALSE); const int yOffset = 15; m_bContextMenuMode = TRUE; if (!Create (m_wndRibbonBar.m_pRibbonBar, x, y - size.cy - yOffset, (HMENU) NULL)) { return FALSE; } m_pCurrent = this; ASSERT_VALID (g_pContextMenuManager); g_pContextMenuManager->SetDontCloseActiveMenu (); m_nMinWidth = size.cx; g_pContextMenuManager->ShowPopupMenu (uiMenuResID, x, y, pWndOwner); m_nMinWidth = 0; CBCGPPopupMenu* pPopup = CBCGPPopupMenu::GetActiveMenu (); if (pPopup != NULL) { ASSERT_VALID (pPopup); pPopup->m_hwndConnectedFloaty = GetSafeHwnd (); CRect rectMenu; pPopup->GetWindowRect (&rectMenu); if (rectMenu.top < y) { SetWindowPos (NULL, rectMenu.left, rectMenu.top - size.cy - yOffset, -1, -1, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); } CRect rectFloaty; GetWindowRect (rectFloaty); if (rectMenu.top < rectFloaty.bottom) { SetWindowPos (NULL, rectMenu.left, rectMenu.bottom + yOffset, -1, -1, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); } } return TRUE; } //************************************************************************************ void CBCGPRibbonFloaty::OnTimer(UINT_PTR nIDEvent) { CBCGPRibbonPanelMenu::OnTimer(nIDEvent); if (nIDEvent != ID_VISIBILITY_TIMER) { return; } if (m_bContextMenuMode) { KillTimer (ID_VISIBILITY_TIMER); return; } if (m_wndRibbonBar.GetPanel () != NULL) { if (m_wndRibbonBar.GetPanel ()->GetDroppedDown () != NULL) { m_bWasDroppedDown = TRUE; return; } } if (UpdateTransparency ()) { globalData.SetLayeredAttrib (GetSafeHwnd (), 0, m_nTransparency, LWA_ALPHA); UpdateShadowTransparency (m_nTransparency); } } //************************************************************************************ int CBCGPRibbonFloaty::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CBCGPRibbonPanelMenu::OnCreate(lpCreateStruct) == -1) return -1; if (!m_bContextMenuMode) { SetTimer (ID_VISIBILITY_TIMER, 100, NULL); } return 0; } //************************************************************************************ BOOL CBCGPRibbonFloaty::UpdateTransparency () { BYTE nTransparency = 0; CRect rect; GetWindowRect (rect); CPoint ptCursor; ::GetCursorPos (&ptCursor); if (m_wndRibbonBar.GetPanel ()->GetDroppedDown () != NULL || m_wndRibbonBar.GetPanel ()->GetHighlighted () != NULL || m_wndRibbonBar.GetPanel ()->GetPressed () != NULL) { nTransparency = 255; if (m_bWasDroppedDown && rect.PtInRect (ptCursor)) { m_bWasDroppedDown = FALSE; } } else { if (CBCGPPopupMenu::GetActiveMenu() != this) { PostMessage (WM_CLOSE); return FALSE; } if (rect.PtInRect (ptCursor)) { m_bWasHovered = TRUE; nTransparency = 255; m_bWasDroppedDown = FALSE; } else if (m_bWasDroppedDown) { nTransparency = 255; } else { const int x = ptCursor.x; const int y = ptCursor.y; int dx = 0; int dy = 0; if (x < rect.left) { dx = rect.left - x; } else if (x > rect.right) { dx = x - rect.right; } if (y < rect.top) { dy = rect.top - y; } else if (y > rect.bottom) { dy = y - rect.bottom; } const int nDistance = max (dx, dy); const int nRange = m_bWasHovered ? 22 : 11; const int nDimissDistance = m_bWasHovered ? 176 : 44; if (nDistance > nDimissDistance) { PostMessage (WM_CLOSE); return FALSE; } if (nDistance < nRange) { nTransparency = 200; } else if (nDistance < 2 * nRange) { nTransparency = 100; } else if (nDistance < 3 * nRange) { nTransparency = 50; } } } if (m_nTransparency == nTransparency) { return FALSE; } m_nTransparency = nTransparency; return TRUE; } //************************************************************************************ void CBCGPRibbonFloaty::CancelContextMenuMode () { ASSERT_VALID (this); if (!m_bContextMenuMode) { return; } m_bContextMenuMode = FALSE; SetTimer (ID_VISIBILITY_TIMER, 100, NULL); ModifyStyleEx (0, WS_EX_LAYERED); UpdateTransparency (); globalData.SetLayeredAttrib (GetSafeHwnd (), 0, m_nTransparency, LWA_ALPHA); UpdateShadowTransparency (m_nTransparency); } ///////////////////////////////////////////////////////////////////////////// // CBCGPRibbonFloaty message handlers #endif // BCGP_EXCLUDE_RIBBON
[ "iclosure@163.com" ]
iclosure@163.com
96048f8f9887e202e44ddd97427a9a43e0301132
930a2c0078e8c68f96c10370224d8057161cd647
/Jinaria/three problem per day/2020.1/2020.1.24/1328.cpp
5e82f566de39d257b52082b27b58204485a4a9c1
[]
no_license
JaechanAn/algorithm-study
bbc45f638bca00230a455e8fb5ef468b568ccce2
01b74f662cc4210f4c646f6a303cb3b8ba26ed99
refs/heads/master
2022-07-07T06:42:45.095078
2020-05-13T07:07:13
2020-05-13T07:07:13
175,931,313
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
#include <cstdio> #include <vector> #include <algorithm> using namespace std; #define M 1000000007 long long d[101][101][101]; int main() { int N, L, R; scanf("%d %d %d", &N, &L, &R); d[1][1][1] = 1; for (int i = 2; i <= N; ++i) { for (int l = 1; l <= L; ++l) { for (int r = 1; r <= R; ++r) { d[i][l][r] = (d[i - 1][l - 1][r] + d[i - 1][l][r - 1] + d[i - 1][l][r] * (i - 2)) % M; } } } printf("%lld\n", d[N][L][R]); }
[ "wlstmdrl0925@gmail.com" ]
wlstmdrl0925@gmail.com
bf8c353dc0a42086ff9c38cc23ec6fb99da7e9ae
fa13f57accece2474d91bf52d2d3ed435af7be0e
/installing-shibboleth3.re
cdc83726c196229dc609ea6341cfb5996577ed7e
[ "CC-BY-4.0" ]
permissive
dmiyakawa/TechBookFest2016-SAML-Book
8288649aaa043512f37bad4aa6fa9797af951eab
3d46216d359994511caf531bf64c09b578a900e7
refs/heads/master
2021-01-18T13:18:52.411419
2016-08-01T03:24:01
2016-08-01T03:24:01
59,977,069
0
0
null
null
null
null
UTF-8
C++
false
false
420
re
= Shibboleth IdP v3.2.1 をインストールする もうこれで人生10度目……とは言いませんがShibboleth IdP v3.2.1 をインストールします。 ちなみに「学認技術ガイド」はShibboelth IdP界では常にヲチしておく価値があると思います。 ここでは説明について手を抜いて「学人技術ガイドのここをどうぞ」なんて書いたりします。
[ "dmiyakawa@mokha.co.jp" ]
dmiyakawa@mokha.co.jp
3db7216032732478730d243dd38badfcae6a63de
e41f078dd0291b11cad935989b0b6f4ebcf0561b
/Common01/Source/CommonPCH.cpp
e846088416c493945e3ad4ac89b3e93fbdee6808
[ "Unlicense" ]
permissive
DavidCoenFish/game02
27eba00e188b1d5e5a80553fbea5434b0f24e8a9
3011cf2fe069b579759aa95333cb406a8ff52d53
refs/heads/main
2023-08-23T07:55:39.745268
2021-11-02T06:35:41
2021-11-02T06:35:41
340,514,855
0
0
null
null
null
null
UTF-8
C++
false
false
109
cpp
// // pch.cpp // Include the standard header and generate the precompiled header. // #include "CommonPCH.h"
[ "fish_dsc@yahoo.co.uk" ]
fish_dsc@yahoo.co.uk
7fde04ce74105c352cd1ff485e9a2fe464f5f8b5
eb2db55316acdb3a1cd3a501859ededd66d51c9d
/src/AkaoScanner.cpp
d2c8fb5f57ea41e3e53790a73e1514d59fdfee39
[]
no_license
soneek/vgmtrans
a7dd5f6c793cc23615585bc688747d3cd2cc4469
2eb83288e4386d24c51de8c8c43b42b6ac03400a
refs/heads/master
2020-12-25T22:28:38.282193
2013-08-23T14:30:04
2013-08-23T14:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,543
cpp
#include "stdafx.h" #include "AkaoScanner.h" #include "AkaoSeq.h" #include "AkaoInstr.h" AkaoScanner::AkaoScanner(void) { } AkaoScanner::~AkaoScanner(void) { } void AkaoScanner::Scan(RawFile* file, void* info) { UINT nFileLength = file->size(); for (UINT i=0; i+0x60<nFileLength; i++) { if (file->GetWordBE(i) != 0x414B414F) //sig must match ascii characters "AKAO" continue; if ( file->GetWord(i+0x20) != 0 && file->GetWord(i+8) != 0) //0x20 contains the num of tracks, via num positive bits { if (file->GetWord(i+0x2C) != 0 || file->GetWord(i+0x28) != 0) continue; if (file->GetWord(i+0x38) != 0 || file->GetWord(i+0x3C) != 0) continue; if (file->GetShort(i+6) == 0) //sequence length value must != 0 continue; AkaoSeq* NewAkaoSeq = new AkaoSeq(file, i); if (!NewAkaoSeq->LoadVGMFile()) delete NewAkaoSeq; } else { if (file->GetWord(i+8) != 0 || file->GetWord(i+0x0C) != 0 || file->GetWord(i+0x24) != 0 || file->GetWord(i+0x28) != 0 || file->GetWord(i+0x2C) != 0 && file->GetWord(i+0x30) != 0 || file->GetWord(i+0x34) != 0 || file->GetWord(i+0x38) != 0 && file->GetWord(i+0x3C) != 0 || file->GetWord(i+0x40) != 0 || file->GetWord(i+0x4C) == 0) //ADSR1 and ADSR2 will never be 0 in any real-world case. //file->GetWord(i+0x50) == 0 || file->GetWord(i+0x54) == 00) //Chrono Cross 311 is exception to this :-/ continue; AkaoSampColl* sampColl = new AkaoSampColl(file, i, 0); if (!sampColl->LoadVGMFile()) delete sampColl; } } return; }
[ "loveemu@gmail.com" ]
loveemu@gmail.com
8cf21746c22abeb19e65a8802bb659746f47cbd4
344db7c30f7bf34d8ae20d5ed040280a8c038f9c
/PAT_Code-master/A1097.cpp
0199f594c793d7ef5116dce2253d97b92860cc79
[]
no_license
CoderDXQ/Brush-Algorithm-problem
75d5a700eae5df8be600fea3a5427c94a9f941b9
78cf6a79c7c0fe1a9fc659101ba5ba9196912df5
refs/heads/master
2023-06-19T14:20:01.117764
2021-07-18T04:59:19
2021-07-18T04:59:19
253,854,814
4
0
null
null
null
null
UTF-8
C++
false
false
2,140
cpp
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 100005; const int TABLE = 1000010; struct Node { // 定义静态链表(第一步) int address, data, next; int order; // 结点在链表上的序号,无效结点记为2*maxn }node[maxn]; bool isExist[TABLE] = {false}; // 绝对值是否已经出现 bool cmp(Node a, Node b) { return a.order < b.order; // 按order从小到大排序 } int main() { memset(isExist, false, sizeof(isExist)); // 初始化isExist为未出现 for(int i = 0; i < maxn; i++) { // 初始化(第二步) node[i].order = 2 * maxn; // 表示初始时均为无效结点 } int n, begin, address; scanf("%d%d", &begin, &n); // 起始地址,结点个数 for(int i = 0; i < n; i++) { // 输入所有结点 scanf("%d", &address); scanf("%d%d", &node[address].data, &node[address].next); node[address].address = address; } // 未删除的有效结点个数、已删除的有效结点个数 int countValid = 0, countRemoved = 0, p = begin; while(p != -1) { // 枚举链表(第三步) if(!isExist[abs(node[p].data)]){ // data的绝对值不存在 isExist[abs(node[p].data)] = true; // 标记为已存在 node[p].order = countValid++; // 不删除,编号从0开始 } else { // data的绝对值已存在 node[p].order = maxn + countRemoved++; // 被删除,编号从maxn开始 } p = node[p].next; // 下一个结点 } sort(node, node + maxn, cmp); // 按order从小到大排序(第四步) // 输出结果(第五步) int count = countValid + countRemoved; // 有效结点个数 for(int i = 0; i < count; i++) { if (i != countValid - 1 && i != count - 1) { // 非最后一个结点 printf("%05d %d %05d\n", node[i].address, node[i].data, node[i+1].address); } else { // 最后一个结点单独处理 printf("%05d %d -1\n", node[i].address, node[i].data); } } return 0; }
[ "794055465@qq.com" ]
794055465@qq.com
06102ca5956c4fcaa58bd2afe6cc2b6b55508e9a
f4b88c1d810114149bb3479bdd460d6c5207b6a8
/src/xml/XmlNode.cpp
41bbed4d95f97a2b389ee27d4cb3c667d2a94b3e
[ "Apache-2.0" ]
permissive
crupest/cru
f0523639f791074cb272835d6a3b367846c2a3a7
6b14866d4cb0e496d28142f3f42e5f2624d6dc77
refs/heads/main
2023-07-09T23:56:34.977412
2022-09-06T07:24:04
2022-09-06T07:24:04
147,010,144
3
0
Apache-2.0
2022-10-27T12:44:40
2018-09-01T15:28:58
C++
UTF-8
C++
false
false
1,761
cpp
#include "cru/xml/XmlNode.h" #include <algorithm> namespace cru::xml { XmlElementNode* XmlNode::AsElement() { return static_cast<XmlElementNode*>(this); } XmlTextNode* XmlNode::AsText() { return static_cast<XmlTextNode*>(this); } XmlCommentNode* XmlNode::AsComment() { return static_cast<XmlCommentNode*>(this); } const XmlElementNode* XmlNode::AsElement() const { return static_cast<const XmlElementNode*>(this); } const XmlTextNode* XmlNode::AsText() const { return static_cast<const XmlTextNode*>(this); } const XmlCommentNode* XmlNode::AsComment() const { return static_cast<const XmlCommentNode*>(this); } XmlElementNode::~XmlElementNode() { for (auto child : children_) { delete child; } } void XmlElementNode::AddAttribute(String key, String value) { attributes_[std::move(key)] = std::move(value); } void XmlElementNode::AddChild(XmlNode* child) { Expects(child->GetParent() == nullptr); children_.push_back(child); child->parent_ = this; } Index XmlElementNode::GetChildElementCount() const { return std::count_if( children_.cbegin(), children_.cend(), [](xml::XmlNode* node) { return node->IsElementNode(); }); } XmlElementNode* XmlElementNode::GetFirstChildElement() const { for (auto child : children_) { if (child->GetType() == XmlNode::Type::Element) { return child->AsElement(); } } return nullptr; } XmlNode* XmlElementNode::Clone() const { XmlElementNode* node = new XmlElementNode(tag_, attributes_); for (auto child : children_) { node->AddChild(child->Clone()); } return node; } XmlCommentNode::~XmlCommentNode() {} XmlNode* XmlCommentNode::Clone() const { XmlCommentNode* node = new XmlCommentNode(text_); return node; } } // namespace cru::xml
[ "crupest@outlook.com" ]
crupest@outlook.com
d61b4a91b4e5947e9a5ea92beeb7c0e17ce8b13a
89f3e3fc1d814a51dfc3baa981a0303aed972009
/EnjoyEngine/EnjoyEngine/ECSComponent.cpp
7db7ad6eb414f19584d81c121c8d2b517b31b3b8
[ "MIT" ]
permissive
Jar0T/EnjoyEngine_dll
6e4acaf03c3f5a754a4e5f9cd87635f9bae02f45
41e242a35e886a103e44f82d65586f19e0f4f81e
refs/heads/develop
2022-12-22T03:58:03.245105
2020-09-29T14:06:10
2020-09-29T14:06:10
256,040,800
1
0
MIT
2020-09-29T14:06:11
2020-04-15T21:28:18
C++
UTF-8
C++
false
false
1,190
cpp
#include "pch.h" #include "ECSComponent.hpp" namespace EE { std::vector<std::tuple< ECSComponentCreateFunction, ECSComponentFreeFunction, size_t>>* BaseECSComponent::componentTypes = 0; std::uint32_t BaseECSComponent::registerComponentType(ECSComponentCreateFunction createfn, ECSComponentFreeFunction freefn, size_t size) { if (componentTypes == nullptr) { componentTypes = new std::vector<std::tuple< ECSComponentCreateFunction, ECSComponentFreeFunction, size_t>>; } std::uint32_t componentTypeID = componentTypes->size(); componentTypes->push_back( std::tuple< ECSComponentCreateFunction, ECSComponentFreeFunction, size_t>( createfn, freefn, size ) ); return componentTypeID; } ECSComponentCreateFunction BaseECSComponent::getTypeCreateFunction(std::uint32_t id) { return std::get<0>((*componentTypes)[id]); } ECSComponentFreeFunction BaseECSComponent::getTypeFreeFunction(std::uint32_t id) { return std::get<1>((*componentTypes)[id]); } size_t BaseECSComponent::getTypeSize(std::uint32_t id) { return std::get<2>((*componentTypes)[id]); } bool BaseECSComponent::isTypeValid(std::uint32_t id) { return id < componentTypes->size(); } }
[ "jarotumula4@gmail.com" ]
jarotumula4@gmail.com
615d80c05d4ab41b904a21bfcebbd052a7c2316b
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/polynomials/include/functions/simd/hermite.hpp
af5c5ad52244481daaa5d9aa4b82d6a3e6354ec5
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
311
hpp
#ifndef NT2_POLYNOMIALS_INCLUDE_FUNCTIONS_SIMD_HERMITE_HPP_INCLUDED #define NT2_POLYNOMIALS_INCLUDE_FUNCTIONS_SIMD_HERMITE_HPP_INCLUDED #include <nt2/polynomials/functions/hermite.hpp> #include <nt2/polynomials/functions/scalar/hermite.hpp> #include <nt2/polynomials/functions/simd/common/hermite.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
566b6dd0ccc56f995b6e32d969d87d735b9f25ad
3a9958147415bb7355fc4e43c9e16e7b95db8b76
/src/tecgraf/cd/src/gdiplus/cdwinp.cpp
7bfee728b1e5c143e6175fce66edab1e973a7b61
[ "MIT" ]
permissive
sanikoyes/lua-tools
4bd8d4ce1b77e3c811616894cd86cb17bcf32a8c
513b3bbc316d8a35896528253415bbe189ede665
refs/heads/master
2021-01-21T05:02:52.642050
2016-05-30T10:24:38
2016-05-30T10:24:38
37,987,656
2
1
null
null
null
null
UTF-8
C++
false
false
86,352
cpp
/** \file * \brief Windows GDI+ Base Driver * * See Copyright Notice in cd.h */ #include "cdwinp.h" #include "cdgdiplus.h" #include "wd.h" #include <stdlib.h> #include <stdio.h> #include <math.h> static void cdstipple(cdCtxCanvas* ctxcanvas, int w, int h, const unsigned char *index); // For debuging, NOT exported in the DLL void cdwpShowStatus(const char* title, Status status) { char* status_str = ""; switch(status) { case Ok: status_str = "Ok"; break; case GenericError: status_str = "GenericError"; break; case InvalidParameter: status_str = "InvalidParameter"; break; case OutOfMemory: status_str = "OutOfMemory"; break; case ObjectBusy: status_str = "ObjectBusy"; break; case InsufficientBuffer: status_str = "InsufficientBuffer"; break; case NotImplemented: status_str = "NotImplemented"; break; case Win32Error: status_str = "Win32Error"; break; case WrongState: status_str = "WrongState"; break; case Aborted: status_str = "Aborted"; break; case FileNotFound: status_str = "FileNotFound"; break; case ValueOverflow: status_str = "ValueOverflow"; break; case AccessDenied: status_str = "AccessDenied"; break; case UnknownImageFormat: status_str = "UnknownImageFormat"; break; case FontFamilyNotFound: status_str = "FontFamilyNotFound"; break; case FontStyleNotFound: status_str = "FontStyleNotFound"; break; case NotTrueTypeFont: status_str = "NotTrueTypeFont"; break; case UnsupportedGdiplusVersion: status_str = "UnsupportedGdiplusVersion"; break; case GdiplusNotInitialized: status_str = "GdiplusNotInitialized"; break; case PropertyNotFound: status_str = "PropertyNotFound"; break; case PropertyNotSupported: status_str = "PropertyNotSupported"; break; } if (status != Ok) MessageBoxA(NULL, status_str, title, MB_OK); } WCHAR* cdwpStringToUnicode(const char* str, int utf8mode) { static WCHAR wstr[10240] = L""; int len; if (utf8mode) len = MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, 10240); else len = MultiByteToWideChar(CP_ACP, 0, str, -1, wstr, 10240); if (len<0) len = 0; wstr[len] = 0; return wstr; } WCHAR* cdwpStringToUnicodeLen(const char* str, int *len, int utf8mode) { static WCHAR wstr[10240] = L""; if (utf8mode) *len = MultiByteToWideChar(CP_UTF8, 0, str, *len, wstr, 10240); else *len = MultiByteToWideChar(CP_ACP, 0, str, *len, wstr, 10240); if (*len<0) *len = 0; wstr[*len] = 0; return wstr; } char* cdwpStringFromUnicode(const WCHAR* wstr, int utf8mode) { static char str[10240] = ""; int len; if (utf8mode) len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, 10240, NULL, NULL); /* str must has a large buffer */ else len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, 10240, NULL, NULL); if (len<0) len = 0; str[len] = 0; return str; } /* %F Libera memoria e handles alocados pelo driver Windows. */ void cdwpKillCanvas(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->clip_poly) delete[] ctxcanvas->clip_poly; if (ctxcanvas->clip_fpoly) delete[] ctxcanvas->clip_fpoly; if (ctxcanvas->clip_region) delete ctxcanvas->clip_region; if (ctxcanvas->new_region) delete ctxcanvas->new_region; if (ctxcanvas->font) delete ctxcanvas->font; delete ctxcanvas->fillBrush; delete ctxcanvas->lineBrush; delete ctxcanvas->linePen; delete ctxcanvas->graphics; /* ctxcanvas e?liberado em cada driver */ } static int sAddTransform(cdCtxCanvas* ctxcanvas, Matrix &transformMatrix, const double* matrix) { if (matrix) { // configure a bottom-up coordinate system Matrix Matrix1((REAL)1, (REAL)0, (REAL)0, (REAL)-1, (REAL)0, (REAL)(ctxcanvas->canvas->h-1)); transformMatrix.Multiply(&Matrix1); // add the global transform Matrix Matrix2((REAL)matrix[0], (REAL)matrix[1], (REAL)matrix[2], (REAL)matrix[3], (REAL)matrix[4], (REAL)matrix[5]); transformMatrix.Multiply(&Matrix2); return 1; } else if (ctxcanvas->rotate_angle) { /* the rotation must be corrected because of the Y axis orientation */ transformMatrix.Translate((REAL)ctxcanvas->rotate_center_x, (REAL)_cdInvertYAxis(ctxcanvas->canvas, ctxcanvas->rotate_center_y)); transformMatrix.Rotate((REAL)-ctxcanvas->rotate_angle); transformMatrix.Translate((REAL)-ctxcanvas->rotate_center_x, (REAL)-_cdInvertYAxis(ctxcanvas->canvas, ctxcanvas->rotate_center_y)); return 1; } return 0; } static void sUpdateTransform(cdCtxCanvas* ctxcanvas) { Matrix transformMatrix; ctxcanvas->graphics->ResetTransform(); // reset to the identity. if (sAddTransform(ctxcanvas, transformMatrix, ctxcanvas->canvas->use_matrix? ctxcanvas->canvas->matrix: NULL)) ctxcanvas->graphics->SetTransform(&transformMatrix); } /*********************************************************************/ /* %S Cor */ /*********************************************************************/ static Color sColor2Windows(long int cd_color) { return Color(cdAlpha(cd_color),cdRed(cd_color),cdGreen(cd_color),cdBlue(cd_color)); } static void sUpdateFillBrush(cdCtxCanvas* ctxcanvas) { // must update the fill brush that is dependent from the Foreground and Background Color. BrushType type = ctxcanvas->fillBrush->GetType(); switch(type) { case BrushTypeSolidColor: { SolidBrush* solidbrush = (SolidBrush*)ctxcanvas->fillBrush; solidbrush->SetColor(ctxcanvas->fg); break; } case BrushTypeHatchFill: { HatchBrush* hatchbrush = (HatchBrush*)ctxcanvas->fillBrush; HatchStyle hatchStyle = hatchbrush->GetHatchStyle(); delete ctxcanvas->fillBrush; ctxcanvas->fillBrush = new HatchBrush(hatchStyle, ctxcanvas->fg, ctxcanvas->bg); break; } case BrushTypeLinearGradient: { LinearGradientBrush* gradientbrush = (LinearGradientBrush*)ctxcanvas->fillBrush; gradientbrush->SetLinearColors(ctxcanvas->fg, ctxcanvas->bg); break; } case BrushTypeTextureFill: { // only stipple depends on Foreground and Background Color. if (ctxcanvas->canvas->interior_style == CD_STIPPLE) cdstipple(ctxcanvas, ctxcanvas->canvas->stipple_w, ctxcanvas->canvas->stipple_h, ctxcanvas->canvas->stipple); break; } } } static long int cdforeground(cdCtxCanvas* ctxcanvas, long int color) { ctxcanvas->fg = sColor2Windows(color); ctxcanvas->linePen->SetColor(ctxcanvas->fg); ctxcanvas->lineBrush->SetColor(ctxcanvas->fg); sUpdateFillBrush(ctxcanvas); return color; } static Color sTranspAlpha(const Color& c) { return Color(0, c.GetRed(), c.GetGreen(), c.GetBlue()); } static long int cdbackground(cdCtxCanvas* ctxcanvas, long int color) { ctxcanvas->bg = sColor2Windows(color); if (ctxcanvas->canvas->back_opacity == CD_TRANSPARENT) ctxcanvas->bg = sTranspAlpha(ctxcanvas->bg); /* set background as full transparent */ sUpdateFillBrush(ctxcanvas); return color; } static int cdbackopacity(cdCtxCanvas* ctxcanvas, int opacity) { switch (opacity) { case CD_TRANSPARENT: ctxcanvas->bg = sTranspAlpha(ctxcanvas->bg); /* set background as full transparent */ break; case CD_OPAQUE: ctxcanvas->bg = sColor2Windows(ctxcanvas->canvas->background); break; } sUpdateFillBrush(ctxcanvas); return opacity; } static void cdpalette(cdCtxCanvas* ctxcanvas, int pal_size, const long int *colors, int mode) { (void)mode; if (ctxcanvas->wtype == CDW_BMP && (ctxcanvas->bitmap->GetPixelFormat() == PixelFormat1bppIndexed || ctxcanvas->bitmap->GetPixelFormat() == PixelFormat4bppIndexed || ctxcanvas->bitmap->GetPixelFormat() == PixelFormat8bppIndexed)) { UINT size = ctxcanvas->bitmap->GetPaletteSize(); ColorPalette* palette = new ColorPalette [size]; palette->Count = pal_size; palette->Flags = 0; for (int c = 0; c < pal_size; c++) { palette->Entries[c] = sColor2Windows(colors[c]).GetValue(); } ctxcanvas->bitmap->SetPalette(palette); delete [] palette; } } /*********************************************************************/ /* %S Canvas e clipping */ /*********************************************************************/ static void sClipRect(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->clip_region) delete ctxcanvas->clip_region; Rect rect(ctxcanvas->canvas->clip_rect.xmin, ctxcanvas->canvas->clip_rect.ymin, ctxcanvas->canvas->clip_rect.xmax-ctxcanvas->canvas->clip_rect.xmin+1, ctxcanvas->canvas->clip_rect.ymax-ctxcanvas->canvas->clip_rect.ymin+1); ctxcanvas->clip_region = new Region(rect); ctxcanvas->graphics->SetClip(ctxcanvas->clip_region); } static void sClipPoly(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->clip_region) delete ctxcanvas->clip_region; GraphicsPath path; path.SetFillMode(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); if (ctxcanvas->clip_fpoly) path.AddPolygon(ctxcanvas->clip_fpoly, ctxcanvas->clip_poly_n); else path.AddPolygon(ctxcanvas->clip_poly, ctxcanvas->clip_poly_n); ctxcanvas->clip_region = new Region(&path); ctxcanvas->graphics->SetClip(ctxcanvas->clip_region); } static int cdclip(cdCtxCanvas* ctxcanvas, int clip_mode) { switch (clip_mode) { case CD_CLIPOFF: ctxcanvas->graphics->ResetClip(); if (ctxcanvas->clip_region) delete ctxcanvas->clip_region; ctxcanvas->clip_region = NULL; break; case CD_CLIPAREA: sClipRect(ctxcanvas); break; case CD_CLIPPOLYGON: sClipPoly(ctxcanvas); break; case CD_CLIPREGION: if (ctxcanvas->clip_region) delete ctxcanvas->clip_region; ctxcanvas->clip_region = ctxcanvas->new_region->Clone(); ctxcanvas->graphics->SetClip(ctxcanvas->clip_region); break; } return clip_mode; } static void cdcliparea(cdCtxCanvas* ctxcanvas, int xmin, int xmax, int ymin, int ymax) { if (ctxcanvas->canvas->clip_mode == CD_CLIPAREA) { ctxcanvas->canvas->clip_rect.xmin = xmin; ctxcanvas->canvas->clip_rect.xmax = xmax; ctxcanvas->canvas->clip_rect.ymin = ymin; ctxcanvas->canvas->clip_rect.ymax = ymax; sClipRect(ctxcanvas); } } static void cdnewregion(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->new_region) delete ctxcanvas->new_region; ctxcanvas->new_region = new Region(); ctxcanvas->new_region->MakeEmpty(); } static int cdispointinregion(cdCtxCanvas* ctxcanvas, int x, int y) { if (!ctxcanvas->new_region) return 0; if (ctxcanvas->new_region->IsVisible(x, y)) return 1; return 0; } static void cdoffsetregion(cdCtxCanvas* ctxcanvas, int x, int y) { if (!ctxcanvas->new_region) return; ctxcanvas->new_region->Translate(x, y); } static void cdgetregionbox(cdCtxCanvas* ctxcanvas, int *xmin, int *xmax, int *ymin, int *ymax) { Rect rect; if (!ctxcanvas->new_region) return; ctxcanvas->new_region->GetBounds(&rect, ctxcanvas->graphics); *xmin = rect.X; *xmax = rect.X+rect.Width-1; *ymin = rect.Y; *ymax = rect.Y+rect.Height-1; } static void sCombineRegion(cdCtxCanvas* ctxcanvas, Region& region) { switch(ctxcanvas->canvas->combine_mode) { case CD_UNION: ctxcanvas->new_region->Union(&region); break; case CD_INTERSECT: ctxcanvas->new_region->Intersect(&region); break; case CD_DIFFERENCE: ctxcanvas->new_region->Exclude(&region); break; case CD_NOTINTERSECT: ctxcanvas->new_region->Xor(&region); break; } } /******************************************************************/ /* %S Primitivas e seus atributos */ /******************************************************************/ static int cdlinestyle(cdCtxCanvas* ctxcanvas, int style) { switch (style) { case (CD_CONTINUOUS): { ctxcanvas->linePen->SetDashStyle(DashStyleSolid); break; } case CD_DASHED: { if (ctxcanvas->canvas->line_width == 1) { REAL dashed[2] = {18.0f, 6.0f}; ctxcanvas->linePen->SetDashPattern(dashed, 2); } else ctxcanvas->linePen->SetDashStyle(DashStyleDash); break; } case CD_DOTTED: { if (ctxcanvas->canvas->line_width == 1) { REAL dotted[2] = {3.0f, 3.0f}; ctxcanvas->linePen->SetDashPattern(dotted, 2); } else ctxcanvas->linePen->SetDashStyle(DashStyleDot); break; } case CD_DASH_DOT: { if (ctxcanvas->canvas->line_width == 1) { REAL dash_dot[6] = {9.0f, 6.0f, 3.0f, 6.0f}; ctxcanvas->linePen->SetDashPattern(dash_dot, 4); } else ctxcanvas->linePen->SetDashStyle(DashStyleDashDot); break; } case CD_DASH_DOT_DOT: { if (ctxcanvas->canvas->line_width == 1) { REAL dash_dot_dot[6] = {9.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f}; ctxcanvas->linePen->SetDashPattern(dash_dot_dot, 6); } else ctxcanvas->linePen->SetDashStyle(DashStyleDashDotDot); break; } case CD_CUSTOM: { REAL* dash_style = new REAL [ctxcanvas->canvas->line_dashes_count]; for (int i = 0; i < ctxcanvas->canvas->line_dashes_count; i++) dash_style[i] = (REAL)ctxcanvas->canvas->line_dashes[i]/(REAL)ctxcanvas->canvas->line_width; ctxcanvas->linePen->SetDashPattern(dash_style, ctxcanvas->canvas->line_dashes_count); delete [] dash_style; break; } } return style; } static int cdlinecap(cdCtxCanvas* ctxcanvas, int cap) { LineCap cd2win_lcap[] = {LineCapFlat, LineCapSquare, LineCapRound}; DashCap cd2win_dcap[] = {DashCapFlat, DashCapFlat, DashCapRound}; ctxcanvas->linePen->SetLineCap(cd2win_lcap[cap], cd2win_lcap[cap], cd2win_dcap[cap]); return cap; } static int cdlinejoin(cdCtxCanvas* ctxcanvas, int join) { LineJoin cd2win_join[] = {LineJoinMiter, LineJoinBevel, LineJoinRound}; ctxcanvas->linePen->SetLineJoin(cd2win_join[join]); return join; } static int cdlinewidth(cdCtxCanvas* ctxcanvas, int width) { ctxcanvas->linePen->SetWidth((REAL)width); cdlinestyle(ctxcanvas, ctxcanvas->canvas->line_style); return width; } static int cdhatch(cdCtxCanvas* ctxcanvas, int hatch_style) { HatchStyle hatchStyle; switch (hatch_style) { default: // CD_HORIZONTAL: hatchStyle = HatchStyleHorizontal; break; case CD_VERTICAL: hatchStyle = HatchStyleVertical; break; case CD_FDIAGONAL: hatchStyle = HatchStyleForwardDiagonal; break; case CD_BDIAGONAL: hatchStyle = HatchStyleBackwardDiagonal; break; case CD_CROSS: hatchStyle = HatchStyleCross; break; case CD_DIAGCROSS: hatchStyle = HatchStyleDiagonalCross; break; } delete ctxcanvas->fillBrush; ctxcanvas->fillBrush = new HatchBrush(hatchStyle, ctxcanvas->fg, ctxcanvas->bg); return hatch_style; } static void cdstipple(cdCtxCanvas* ctxcanvas, int w, int h, const unsigned char *index) { ULONG* bitmap_data = new ULONG [w*h]; for(int j = 0; j < h; j++) { int line_offset_index; int line_offset = j*w; if (ctxcanvas->canvas->invert_yaxis) line_offset_index = ((h - 1) - j)*w; // Fix up side down else line_offset_index = line_offset; for(int i = 0; i < w; i++) { if (index[line_offset_index+i] != 0) bitmap_data[line_offset+i] = ctxcanvas->fg.GetValue(); else bitmap_data[line_offset+i] = ctxcanvas->bg.GetValue(); } } Bitmap StippleImage(w, h, 4*w, PixelFormat32bppARGB, (BYTE*)bitmap_data); StippleImage.SetResolution(ctxcanvas->graphics->GetDpiX(), ctxcanvas->graphics->GetDpiX()); delete ctxcanvas->fillBrush; ctxcanvas->fillBrush = new TextureBrush(&StippleImage); delete [] bitmap_data; } static void cdpattern(cdCtxCanvas* ctxcanvas, int w, int h, const long int *colors) { int stride = 4*w; BYTE* bitmap_data = new BYTE [stride*h]; for(int j = 0; j < h; j++) { int line_offset_colors; int line_offset = j*stride; /* internal transform, affects also pattern orientation */ if (ctxcanvas->canvas->invert_yaxis) line_offset_colors = ((h - 1) - j)*w; // Fix up side down else line_offset_colors = j*w; memcpy(bitmap_data + line_offset, colors + line_offset_colors, stride); // Fix alpha values for(int i = 3; i < stride; i+=4) bitmap_data[line_offset+i] = ~bitmap_data[line_offset+i]; } Bitmap PatternImage(w, h, stride, PixelFormat32bppARGB, bitmap_data); PatternImage.SetResolution(ctxcanvas->graphics->GetDpiX(), ctxcanvas->graphics->GetDpiX()); delete ctxcanvas->fillBrush; ctxcanvas->fillBrush = new TextureBrush(&PatternImage); delete [] bitmap_data; } static int cdinteriorstyle(cdCtxCanvas* ctxcanvas, int style) { switch (style) { case CD_SOLID: delete ctxcanvas->fillBrush; ctxcanvas->fillBrush = new SolidBrush(ctxcanvas->fg); break; /* the remaining styles must recreate the current brush */ case CD_HATCH: cdhatch(ctxcanvas, ctxcanvas->canvas->hatch_style); break; case CD_STIPPLE: cdstipple(ctxcanvas, ctxcanvas->canvas->stipple_w, ctxcanvas->canvas->stipple_h, ctxcanvas->canvas->stipple); break; case CD_PATTERN: cdpattern(ctxcanvas, ctxcanvas->canvas->pattern_w, ctxcanvas->canvas->pattern_h, ctxcanvas->canvas->pattern); break; } return style; } static void cdline(cdCtxCanvas* ctxcanvas, int x1, int y1, int x2, int y2) { ctxcanvas->graphics->DrawLine(ctxcanvas->linePen, x1, y1, x2, y2); ctxcanvas->dirty = 1; } static void cdfline(cdCtxCanvas* ctxcanvas, double x1, double y1, double x2, double y2) { ctxcanvas->graphics->DrawLine(ctxcanvas->linePen, (REAL)x1, (REAL)y1, (REAL)x2, (REAL)y2); ctxcanvas->dirty = 1; } static void cdrect(cdCtxCanvas* ctxcanvas, int xmin, int xmax, int ymin, int ymax) { Rect rect(xmin, ymin, xmax-xmin, ymax-ymin); // in this case Size = Max - Min ctxcanvas->graphics->DrawRectangle(ctxcanvas->linePen, rect); ctxcanvas->dirty = 1; } static void cdfrect(cdCtxCanvas* ctxcanvas, double xmin, double xmax, double ymin, double ymax) { RectF rect((REAL)xmin, (REAL)ymin, (REAL)(xmax-xmin), (REAL)(ymax-ymin)); // in this case Size = Max - Min ctxcanvas->graphics->DrawRectangle(ctxcanvas->linePen, rect); ctxcanvas->dirty = 1; } static void cdbox(cdCtxCanvas* ctxcanvas, int xmin, int xmax, int ymin, int ymax) { Rect rect(xmin, ymin, xmax-xmin+1, ymax-ymin+1); if (ctxcanvas->canvas->new_region) { Region region(rect); sCombineRegion(ctxcanvas, region); } else { ctxcanvas->graphics->FillRectangle(ctxcanvas->fillBrush, rect); ctxcanvas->dirty = 1; } } static void cdfbox(cdCtxCanvas* ctxcanvas, double xmin, double xmax, double ymin, double ymax) { RectF rect((REAL)xmin, (REAL)ymin, (REAL)(xmax-xmin+1), (REAL)(ymax-ymin+1)); if (ctxcanvas->canvas->new_region) { Region region(rect); sCombineRegion(ctxcanvas, region); } else { ctxcanvas->graphics->FillRectangle(ctxcanvas->fillBrush, rect); ctxcanvas->dirty = 1; } } static void sFixAngles(cdCanvas* canvas, double *a1, double *a2, double w, double h) { // the angles relative to the center are dependent from the ellipse size. // in GDI+ must use the actual angle if (*a1!=0 && *a1!=90 && *a1!=180 && *a1!=360 && w!=h) { *a1 = atan2((h/2.0)*sin(*a1*CD_DEG2RAD), (w/2.0)*cos(*a1*CD_DEG2RAD))*CD_RAD2DEG; if (*a1 < 0) *a1 += 360; } if (*a2!=0 && *a2!=90 && *a2!=180 && *a2!=360 && w!=h) { *a2 = atan2((h/2.0)*sin(*a2*CD_DEG2RAD), (w/2.0)*cos(*a2*CD_DEG2RAD))*CD_RAD2DEG; if (*a2 < 0) *a2 += 360; } // GDI+ angles are clock-wise by default, in degrees /* if NOT inverted means a transformation is set, so the angle will follow the transformation that includes the axis invertion, then it is already counter-clockwise */ if (canvas->invert_yaxis) { /* change orientation */ *a1 *= -1; *a2 *= -1; /* no need to swap, because we will use (angle2-angle1) */ } } static void cdarc(cdCtxCanvas* ctxcanvas, int xc, int yc, int w, int h, double angle1, double angle2) { Rect rect(xc - w/2, yc - h/2, w, h); if (angle1 == 0 && angle2 == 360) ctxcanvas->graphics->DrawEllipse(ctxcanvas->linePen, rect); else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); ctxcanvas->graphics->DrawArc(ctxcanvas->linePen, rect, (REAL)angle1, (REAL)(angle2-angle1)); } ctxcanvas->dirty = 1; } static void cdfarc(cdCtxCanvas* ctxcanvas, double xc, double yc, double w, double h, double angle1, double angle2) { RectF rect((REAL)(xc - w/2.0), (REAL)(yc - h/2.0), (REAL)w, (REAL)h); if (angle1 == 0 && angle2 == 360) ctxcanvas->graphics->DrawEllipse(ctxcanvas->linePen, rect); else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); ctxcanvas->graphics->DrawArc(ctxcanvas->linePen, rect, (REAL)angle1, (REAL)(angle2-angle1)); } ctxcanvas->dirty = 1; } static void cdsector(cdCtxCanvas* ctxcanvas, int xc, int yc, int w, int h, double angle1, double angle2) { Rect rect(xc - w/2, yc - h/2, w, h); if (ctxcanvas->canvas->new_region) { GraphicsPath path; if (angle1==0 && angle2==360) path.AddEllipse(rect); else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); path.AddPie(rect, (REAL)angle1, (REAL)(angle2-angle1)); } Region region(&path); sCombineRegion(ctxcanvas, region); } else { // complete the remaining pixels using an Arc Pen pen(ctxcanvas->fillBrush); if (angle1==0 && angle2==360) { ctxcanvas->graphics->FillEllipse(ctxcanvas->fillBrush, rect); ctxcanvas->graphics->DrawEllipse(&pen, rect); } else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); ctxcanvas->graphics->FillPie(ctxcanvas->fillBrush, rect, (REAL)angle1, (REAL)(angle2-angle1)); ctxcanvas->graphics->DrawArc(&pen, rect, (REAL)angle1, (REAL)(angle2-angle1)); } ctxcanvas->dirty = 1; } } static void cdfsector(cdCtxCanvas* ctxcanvas, double xc, double yc, double w, double h, double angle1, double angle2) { RectF rect((REAL)(xc - w/2.0), (REAL)(yc - h/2.0), (REAL)w, (REAL)h); if (ctxcanvas->canvas->new_region) { GraphicsPath path; if (angle1==0 && angle2==360) path.AddEllipse(rect); else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); path.AddPie(rect, (REAL)angle1, (REAL)(angle2-angle1)); } Region region(&path); sCombineRegion(ctxcanvas, region); } else { // complete the remaining pixels using an Arc Pen pen(ctxcanvas->fillBrush); if (angle1==0 && angle2==360) { ctxcanvas->graphics->FillEllipse(ctxcanvas->fillBrush, rect); ctxcanvas->graphics->DrawEllipse(&pen, rect); } else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); ctxcanvas->graphics->FillPie(ctxcanvas->fillBrush, rect, (REAL)angle1, (REAL)(angle2-angle1)); ctxcanvas->graphics->DrawArc(&pen, rect, (REAL)angle1, (REAL)(angle2-angle1)); } ctxcanvas->dirty = 1; } } static void cdchord(cdCtxCanvas* ctxcanvas, int xc, int yc, int w, int h, double angle1, double angle2) { Rect rect(xc - w/2, yc - h/2, w, h); if (ctxcanvas->canvas->new_region) { GraphicsPath path; if (angle1==0 && angle2==360) path.AddEllipse(rect); else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); path.AddArc(rect, (REAL)angle1, (REAL)(angle2-angle1)); path.CloseFigure(); } Region region(&path); sCombineRegion(ctxcanvas, region); } else { if (angle1==0 && angle2==360) ctxcanvas->graphics->FillEllipse(ctxcanvas->fillBrush, rect); else { GraphicsPath path; sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); path.AddArc(rect, (REAL)angle1, (REAL)(angle2-angle1)); ctxcanvas->graphics->FillPath(ctxcanvas->fillBrush, &path); } Pen pen(ctxcanvas->fillBrush); // complete the remaining pixels using an Arc ctxcanvas->graphics->DrawArc(&pen, rect, (REAL)angle1, (REAL)(angle2-angle1)); ctxcanvas->dirty = 1; } } static void cdfchord(cdCtxCanvas* ctxcanvas, double xc, double yc, double w, double h, double angle1, double angle2) { RectF rect((REAL)(xc - w/2.0), (REAL)(yc - h/2.0), (REAL)w, (REAL)h); if (ctxcanvas->canvas->new_region) { GraphicsPath path; if (angle1==0 && angle2==360) path.AddEllipse(rect); else { sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); path.AddArc(rect, (REAL)angle1, (REAL)(angle2-angle1)); path.CloseFigure(); } Region region(&path); sCombineRegion(ctxcanvas, region); } else { if (angle1==0 && angle2==360) ctxcanvas->graphics->FillEllipse(ctxcanvas->fillBrush, rect); else { GraphicsPath path; sFixAngles(ctxcanvas->canvas, &angle1, &angle2, w, h); path.AddArc(rect, (REAL)angle1, (REAL)(angle2-angle1)); ctxcanvas->graphics->FillPath(ctxcanvas->fillBrush, &path); } Pen pen(ctxcanvas->fillBrush); // complete the remaining pixels using an Arc ctxcanvas->graphics->DrawArc(&pen, rect, (REAL)angle1, (REAL)(angle2-angle1)); ctxcanvas->dirty = 1; } } static void cdpoly(cdCtxCanvas* ctxcanvas, int mode, cdPoint* poly, int n) { switch (mode) { case CD_PATH: { int p, i, current_x = 0, current_y = 0, current_set = 0; GraphicsPath* graphics_path; PointF lastPoint; /* starts a new path */ graphics_path = new GraphicsPath(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); i = 0; for (p=0; p<ctxcanvas->canvas->path_n; p++) { switch(ctxcanvas->canvas->path[p]) { case CD_PATH_NEW: graphics_path->Reset(); graphics_path->SetFillMode(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); current_set = 0; break; case CD_PATH_MOVETO: if (i+1 > n) break; current_x = poly[i].x; current_y = poly[i].y; current_set = 1; i++; break; case CD_PATH_LINETO: if (i+1 > n) break; if (current_set) graphics_path->AddLine(current_x, current_y, poly[i].x, poly[i].y); current_x = poly[i].x; current_y = poly[i].y; current_set = 1; i++; break; case CD_PATH_ARC: { int xc, yc, w, h; double a1, a2; if (i+3 > n) break; if (!cdCanvasGetArcPath(poly+i, &xc, &yc, &w, &h, &a1, &a2)) return; if (current_set) { int StartX, StartY; if (ctxcanvas->canvas->invert_yaxis) cdCanvasGetArcStartEnd(xc, yc, w, h, -a1, -a2, &StartX, &StartY, NULL, NULL); else cdCanvasGetArcStartEnd(xc, yc, w, h, a1, a2, &StartX, &StartY, NULL, NULL); graphics_path->AddLine(current_x, current_y, StartX, StartY); } Rect rect(xc - w/2, yc - h/2, w, h); if (a1 == 0 && a2 == 360) graphics_path->AddEllipse(rect); else { sFixAngles(ctxcanvas->canvas, &a1, &a2, w, h); graphics_path->AddArc(rect, (REAL)a1, (REAL)(a2-a1)); } graphics_path->GetLastPoint(&lastPoint); current_x = (int)lastPoint.X; current_y = (int)lastPoint.Y; current_set = 1; i += 3; } break; case CD_PATH_CURVETO: if (i+3 > n) break; if (!current_set) { current_x = poly[i].x; current_y = poly[i].y; } graphics_path->AddBezier(current_x, current_y, poly[i].x, poly[i].y, poly[i+1].x, poly[i+1].y, poly[i+2].x, poly[i+2].y); graphics_path->GetLastPoint(&lastPoint); current_x = (int)lastPoint.X; current_y = (int)lastPoint.Y; current_set = 1; i += 3; break; case CD_PATH_CLOSE: graphics_path->CloseFigure(); break; case CD_PATH_FILL: ctxcanvas->graphics->FillPath(ctxcanvas->fillBrush, graphics_path); break; case CD_PATH_STROKE: ctxcanvas->graphics->DrawPath(ctxcanvas->linePen, graphics_path); break; case CD_PATH_FILLSTROKE: ctxcanvas->graphics->FillPath(ctxcanvas->fillBrush, graphics_path); ctxcanvas->graphics->DrawPath(ctxcanvas->linePen, graphics_path); break; case CD_PATH_CLIP: ctxcanvas->graphics->SetClip(graphics_path, CombineModeIntersect); break; } } delete graphics_path; break; } case CD_BEZIER: if (n < 4) return; ctxcanvas->graphics->DrawBeziers(ctxcanvas->linePen, (Point*)poly, n); break; case CD_FILLSPLINE: if (n < 4) return; if (ctxcanvas->canvas->new_region) { GraphicsPath path(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); path.AddClosedCurve((Point*)poly, n); Region region(&path); sCombineRegion(ctxcanvas, region); } else ctxcanvas->graphics->FillClosedCurve(ctxcanvas->fillBrush, (Point*)poly, n); break; case CD_SPLINE: if (n < 4) return; ctxcanvas->graphics->DrawClosedCurve(ctxcanvas->linePen, (Point*)poly, n); break; case CD_CLOSED_LINES: poly[n].x = poly[0].x; poly[n].y = poly[0].y; n++; /* continue */ case CD_OPEN_LINES: ctxcanvas->graphics->DrawLines(ctxcanvas->linePen, (Point*)poly, n); break; case CD_FILLGRADIENT: { int count = n; PathGradientBrush* brush = new PathGradientBrush((Point*)poly, n); brush->SetSurroundColors(ctxcanvas->pathGradient, &count); brush->SetCenterColor(ctxcanvas->pathGradient[n]); ctxcanvas->graphics->FillPolygon(brush, (Point*)poly, n, ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); } break; case CD_FILL: poly[n].x = poly[0].x; poly[n].y = poly[0].y; n++; if (ctxcanvas->canvas->new_region) { GraphicsPath path(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); path.AddPolygon((Point*)poly, n); Region region(&path); sCombineRegion(ctxcanvas, region); } else ctxcanvas->graphics->FillPolygon(ctxcanvas->fillBrush, (Point*)poly, n, ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); break; case CD_CLIP: poly[n].x = poly[0].x; poly[n].y = poly[0].y; n++; if (ctxcanvas->clip_poly) delete[] ctxcanvas->clip_poly; if (ctxcanvas->clip_fpoly) { delete[] ctxcanvas->clip_fpoly; ctxcanvas->clip_fpoly = NULL; } ctxcanvas->clip_poly = new Point [n]; Point* pnt = (Point*)poly; int t = n; int nc = 1; ctxcanvas->clip_poly[0] = *pnt; pnt++; for (int i = 1; i < t-1; i++, pnt++) { if (!((pnt->X == ctxcanvas->clip_poly[nc-1].X && pnt->X == (pnt + 1)->X) || (pnt->Y == ctxcanvas->clip_poly[nc-1].Y && pnt->Y == (pnt + 1)->Y))) { ctxcanvas->clip_poly[nc] = *pnt; nc++; } } ctxcanvas->clip_poly_n = nc; if (ctxcanvas->canvas->clip_mode == CD_CLIPPOLYGON) sClipPoly(ctxcanvas); break; } ctxcanvas->dirty = 1; } static PointF* sPolyToFloat(cdfPoint* poly, int n) { PointF* fpoly = new PointF[n+1]; for (int i = 0; i < n; i++) { fpoly[i].X = (REAL)poly[i].x; fpoly[i].Y = (REAL)poly[i].y; } return fpoly; } static void cdfpoly(cdCtxCanvas* ctxcanvas, int mode, cdfPoint* poly, int n) { PointF* fpoly = NULL; switch (mode) { case CD_PATH: { int p, i, current_set = 0; double current_x = 0, current_y = 0; GraphicsPath* graphics_path; PointF lastPoint; /* starts a new path */ graphics_path = new GraphicsPath(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); i = 0; for (p=0; p<ctxcanvas->canvas->path_n; p++) { switch(ctxcanvas->canvas->path[p]) { case CD_PATH_NEW: graphics_path->Reset(); graphics_path->SetFillMode(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); current_set = 0; break; case CD_PATH_MOVETO: if (i+1 > n) break; current_x = poly[i].x; current_y = poly[i].y; current_set = 1; i++; break; case CD_PATH_LINETO: if (i+1 > n) break; if (current_set) graphics_path->AddLine((REAL)current_x, (REAL)current_y, (REAL)poly[i].x, (REAL)poly[i].y); current_x = poly[i].x; current_y = poly[i].y; current_set = 1; i++; break; case CD_PATH_ARC: { double xc, yc, w, h; double a1, a2; if (i+3 > n) break; if (!cdfCanvasGetArcPath(poly+i, &xc, &yc, &w, &h, &a1, &a2)) return; if (current_set) { double StartX, StartY; if (ctxcanvas->canvas->invert_yaxis) cdfCanvasGetArcStartEnd(xc, yc, w, h, -a1, -a2, &StartX, &StartY, NULL, NULL); else cdfCanvasGetArcStartEnd(xc, yc, w, h, a1, a2, &StartX, &StartY, NULL, NULL); graphics_path->AddLine((REAL)current_x, (REAL)current_y, (REAL)StartX, (REAL)StartY); } RectF rect((REAL)(xc - w/2.0), (REAL)(yc - h/2.0), (REAL)w, (REAL)h); if (a1 == 0 && a2 == 360) graphics_path->AddEllipse(rect); else { sFixAngles(ctxcanvas->canvas, &a1, &a2, w, h); graphics_path->AddArc(rect, (REAL)a1, (REAL)(a2-a1)); } graphics_path->GetLastPoint(&lastPoint); current_x = lastPoint.X; current_y = lastPoint.Y; current_set = 1; i += 3; } break; case CD_PATH_CURVETO: if (i+3 > n) break; if (!current_set) { current_x = poly[i].x; current_y = poly[i].y; } graphics_path->AddBezier((REAL)current_x, (REAL)current_y, (REAL)poly[i].x, (REAL)poly[i].y, (REAL)poly[i+1].x, (REAL)poly[i+1].y, (REAL)poly[i+2].x, (REAL)poly[i+2].y); graphics_path->GetLastPoint(&lastPoint); current_x = lastPoint.X; current_y = lastPoint.Y; current_set = 1; i += 3; break; case CD_PATH_CLOSE: graphics_path->CloseFigure(); break; case CD_PATH_FILL: ctxcanvas->graphics->FillPath(ctxcanvas->fillBrush, graphics_path); break; case CD_PATH_STROKE: ctxcanvas->graphics->DrawPath(ctxcanvas->linePen, graphics_path); break; case CD_PATH_FILLSTROKE: ctxcanvas->graphics->FillPath(ctxcanvas->fillBrush, graphics_path); ctxcanvas->graphics->DrawPath(ctxcanvas->linePen, graphics_path); break; case CD_PATH_CLIP: ctxcanvas->graphics->SetClip(graphics_path, CombineModeIntersect); break; } } delete graphics_path; break; } case CD_BEZIER: if (n < 4) return; fpoly = sPolyToFloat(poly, n); ctxcanvas->graphics->DrawBeziers(ctxcanvas->linePen, (PointF*)fpoly, n); break; case CD_FILLSPLINE: if (n < 4) return; fpoly = sPolyToFloat(poly, n); if (ctxcanvas->canvas->new_region) { GraphicsPath path(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); path.AddClosedCurve((PointF*)fpoly, n); Region region(&path); sCombineRegion(ctxcanvas, region); } else ctxcanvas->graphics->FillClosedCurve(ctxcanvas->fillBrush, (PointF*)fpoly, n); break; case CD_SPLINE: if (n < 4) return; fpoly = sPolyToFloat(poly, n); ctxcanvas->graphics->DrawClosedCurve(ctxcanvas->linePen, (PointF*)fpoly, n); break; case CD_CLOSED_LINES: poly[n].x = poly[0].x; poly[n].y = poly[0].y; n++; /* continue */ case CD_OPEN_LINES: fpoly = sPolyToFloat(poly, n); ctxcanvas->graphics->DrawLines(ctxcanvas->linePen, (PointF*)fpoly, n); break; case CD_FILLGRADIENT: { int count = n; PathGradientBrush* brush = new PathGradientBrush((PointF*)fpoly, n); fpoly = sPolyToFloat(poly, n); brush->SetSurroundColors(ctxcanvas->pathGradient, &count); brush->SetCenterColor(ctxcanvas->pathGradient[n]); ctxcanvas->graphics->FillPolygon(brush, (PointF*)fpoly, n, ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); delete brush; } break; case CD_FILL: poly[n].x = poly[0].x; poly[n].y = poly[0].y; n++; fpoly = sPolyToFloat(poly, n); if (ctxcanvas->canvas->new_region) { GraphicsPath path(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); path.AddPolygon((PointF*)fpoly, n); Region region(&path); sCombineRegion(ctxcanvas, region); } else ctxcanvas->graphics->FillPolygon(ctxcanvas->fillBrush, (PointF*)fpoly, n, ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); break; case CD_CLIP: poly[n].x = poly[0].x; poly[n].y = poly[0].y; n++; if (ctxcanvas->clip_fpoly) delete[] ctxcanvas->clip_fpoly; if (ctxcanvas->clip_poly) { delete[] ctxcanvas->clip_poly; ctxcanvas->clip_poly = NULL; } ctxcanvas->clip_fpoly = new PointF [n]; cdfPoint* pnt = poly; int t = n; int nc = 1; ctxcanvas->clip_fpoly[0].X = (REAL)pnt->x; ctxcanvas->clip_fpoly[0].Y = (REAL)pnt->y; pnt++; for (int i = 1; i < t-1; i++, pnt++) { if (!(((REAL)pnt->x == ctxcanvas->clip_fpoly[nc-1].X && pnt->x == (pnt + 1)->x) || ((REAL)pnt->y == ctxcanvas->clip_fpoly[nc-1].Y && pnt->y == (pnt + 1)->y))) { ctxcanvas->clip_fpoly[nc].X = (REAL)pnt->x; ctxcanvas->clip_fpoly[nc].Y = (REAL)pnt->y; nc++; } } ctxcanvas->clip_poly_n = nc; if (ctxcanvas->canvas->clip_mode == CD_CLIPPOLYGON) sClipPoly(ctxcanvas); break; } if (fpoly) delete[] fpoly; ctxcanvas->dirty = 1; } static int cdwpCompensateHeight(int height) { return (int)floor(height/10. + 0.5); /* 10% */ } static void cdgettextsize(cdCtxCanvas* ctxcanvas, const char *s, int len, int *width, int *height) { RectF boundingBox; WCHAR* wstr = cdwpStringToUnicodeLen(s, &len, ctxcanvas->utf8mode); ctxcanvas->graphics->MeasureString(wstr, len, ctxcanvas->font, PointF(0,0), &boundingBox); if (width) *width = (int)boundingBox.Width; if (height) *height = (int)boundingBox.Height - cdwpCompensateHeight(ctxcanvas->fontinfo.height); } static void sTextBox(cdCtxCanvas* ctxcanvas, WCHAR *ws, int len, int x, int y, int *w, int *h, int *xmin, int *ymin) { int ydir = 1; if (ctxcanvas->canvas->invert_yaxis) ydir = -1; RectF boundingBox; ctxcanvas->graphics->MeasureString(ws, len, ctxcanvas->font, PointF(0,0), &boundingBox); *w = (int)boundingBox.Width; *h = (int)boundingBox.Height - cdwpCompensateHeight(ctxcanvas->fontinfo.height); // distance from bottom to baseline int baseline = ctxcanvas->fontinfo.height - ctxcanvas->fontinfo.ascent; // move to bottom-left cdTextTranslatePoint(ctxcanvas->canvas, x, y, *w, *h, baseline, xmin, ymin); // move to top-left *ymin += ydir * (*h); } static void sGetTransformTextHeight(cdCanvas* canvas, int x, int y, int w, int h, int *hbox) { int xmin, xmax, ymin, ymax; // distance from bottom to baseline int baseline = canvas->ctxcanvas->fontinfo.height - canvas->ctxcanvas->fontinfo.ascent; /* move to bottom-left */ cdTextTranslatePoint(canvas, x, y, w, h, baseline, &xmin, &ymin); xmax = xmin + w-1; ymax = ymin + h-1; if (canvas->text_orientation) { double angle = canvas->text_orientation*CD_DEG2RAD; double cos_theta = cos(angle); double sin_theta = sin(angle); int rectY[4]; cdRotatePointY(canvas, xmin, ymin, x, y, &rectY[0], sin_theta, cos_theta); cdRotatePointY(canvas, xmax, ymin, x, y, &rectY[1], sin_theta, cos_theta); cdRotatePointY(canvas, xmax, ymax, x, y, &rectY[2], sin_theta, cos_theta); cdRotatePointY(canvas, xmin, ymax, x, y, &rectY[3], sin_theta, cos_theta); ymin = ymax = rectY[0]; if (rectY[1] < ymin) ymin = rectY[1]; if (rectY[2] < ymin) ymin = rectY[2]; if (rectY[3] < ymin) ymin = rectY[3]; if (rectY[1] > ymax) ymax = rectY[1]; if (rectY[2] > ymax) ymax = rectY[2]; if (rectY[3] > ymax) ymax = rectY[3]; } *hbox = ymax-ymin+1; } static void sAddTextTransform(cdCtxCanvas* ctxcanvas, int *x, int *y, int w, int h, Matrix &transformMatrix) { int hbox; Matrix m1; sGetTransformTextHeight(ctxcanvas->canvas, *x, *y, w, h, &hbox); // move to (x,y) and remove a vertical offset since text reference point is top-left m1.SetElements((REAL)1, (REAL)0, (REAL)0, (REAL)1, (REAL)*x, (REAL)(*y - (hbox-1))); transformMatrix.Multiply(&m1); // invert the text vertical orientation, relative to itself m1.SetElements((REAL)1, (REAL)0, (REAL)0, (REAL)-1, (REAL)0, (REAL)(hbox-1)); transformMatrix.Multiply(&m1); *x = 0; *y = 0; } static void cdtext(cdCtxCanvas* ctxcanvas, int x, int y, const char *s, int len) { Matrix transformMatrix; int use_transform = 0, w, h; WCHAR* ws = cdwpStringToUnicodeLen(s, &len, ctxcanvas->utf8mode); if (ctxcanvas->canvas->text_orientation) { double angle = ctxcanvas->canvas->text_orientation; // in degrees transformMatrix.Translate((REAL)x, (REAL)y); transformMatrix.Rotate((REAL)-angle); transformMatrix.Translate((REAL)-x, (REAL)-y); use_transform = 1; } // Move (x,y) to top-left sTextBox(ctxcanvas, ws, len, x, y, &w, &h, &x, &y); if (ctxcanvas->canvas->use_matrix) { double* matrix = ctxcanvas->canvas->matrix; sAddTransform(ctxcanvas, transformMatrix, matrix); sAddTextTransform(ctxcanvas, &x, &y, w, h, transformMatrix); use_transform = 1; } else if (sAddTransform(ctxcanvas, transformMatrix, NULL)) use_transform = 1; if (ctxcanvas->canvas->new_region) { GraphicsPath path(ctxcanvas->canvas->fill_mode==CD_EVENODD?FillModeAlternate:FillModeWinding); if (use_transform) path.Transform(&transformMatrix); FontFamily family; ctxcanvas->font->GetFamily(&family); path.AddString(ws, len, &family, ctxcanvas->font->GetStyle(), ctxcanvas->font->GetSize(), Point(x, y), NULL); Region region(&path); sCombineRegion(ctxcanvas, region); return; } if (use_transform) ctxcanvas->graphics->SetTransform(&transformMatrix); ctxcanvas->graphics->DrawString(ws, len, ctxcanvas->font, PointF((REAL)x, (REAL)y), ctxcanvas->lineBrush); if (use_transform) sUpdateTransform(ctxcanvas); // reset transform ctxcanvas->dirty = 1; } static int sDesign2Pixel(int x, REAL size, int height) { return cdRound((x * size) / (REAL)height); } static int cdfont(cdCtxCanvas* ctxcanvas, const char *type_face, int style, int size) { FontFamily* fontFamily; if (cdStrEqualNoCase(type_face, "Courier") || cdStrEqualNoCase(type_face, "Monospace")) fontFamily = new FontFamily(L"Courier New"); else if (cdStrEqualNoCase(type_face, "Times") || cdStrEqualNoCase(type_face, "Serif")) fontFamily = new FontFamily(L"Times New Roman"); else if (cdStrEqualNoCase(type_face, "Helvetica") || cdStrEqualNoCase(type_face, "Sans")) fontFamily = new FontFamily(L"Arial"); else if (cdStrEqualNoCase(type_face, "System")) fontFamily = FontFamily::GenericSansSerif()->Clone(); else fontFamily = new FontFamily(cdwpStringToUnicode(type_face, ctxcanvas->utf8mode)); REAL emSize = (REAL)(cdGetFontSizePixels(ctxcanvas->canvas, size)); INT fontStyle = FontStyleRegular; if (style&CD_BOLD) fontStyle |= FontStyleBold; if (style&CD_ITALIC) fontStyle |= FontStyleItalic; if (style&CD_UNDERLINE) fontStyle |= FontStyleUnderline; if (style&CD_STRIKEOUT) fontStyle |= FontStyleStrikeout; if (ctxcanvas->font) delete ctxcanvas->font; ctxcanvas->font = new Font(fontFamily, emSize, fontStyle, UnitPixel); REAL fontSize = ctxcanvas->font->GetSize(); int emHeight = fontFamily->GetEmHeight(fontStyle); ctxcanvas->fontinfo.height = sDesign2Pixel(fontFamily->GetLineSpacing(fontStyle), fontSize, emHeight); ctxcanvas->fontinfo.ascent = sDesign2Pixel(fontFamily->GetCellAscent(fontStyle), fontSize, emHeight); ctxcanvas->fontinfo.descent = sDesign2Pixel(fontFamily->GetCellDescent(fontStyle), fontSize, emHeight); delete fontFamily; return 1; } static int cdnativefont(cdCtxCanvas* ctxcanvas, const char* nativefont) { int size = 12, bold = 0, italic = 0, underline = 0, strikeout = 0, style = CD_PLAIN; char type_face[1024]; if (nativefont[0] == '-' && nativefont[1] == 'd') { COLORREF rgbColors; LOGFONTW lf; ctxcanvas->font->GetLogFontW(ctxcanvas->graphics, &lf); CHOOSEFONTW cf; ZeroMemory(&cf, sizeof(CHOOSEFONTW)); cf.lStructSize = sizeof(CHOOSEFONTW); cf.hwndOwner = GetForegroundWindow(); cf.lpLogFont = &lf; cf.Flags = CF_SCREENFONTS | CF_EFFECTS | CF_INITTOLOGFONTSTRUCT; rgbColors = cf.rgbColors = ctxcanvas->fg.ToCOLORREF(); if (!ChooseFontW(&cf)) return 0; if (rgbColors != cf.rgbColors) cdCanvasSetForeground(ctxcanvas->canvas, cdEncodeColor(GetRValue(cf.rgbColors),GetGValue(cf.rgbColors),GetBValue(cf.rgbColors))); bold = lf.lfWeight>FW_NORMAL? 1: 0; italic = lf.lfItalic; size = lf.lfHeight; strcpy(type_face, cdwpStringFromUnicode(lf.lfFaceName, ctxcanvas->utf8mode)); underline = lf.lfUnderline; strikeout = lf.lfStrikeOut; if (bold) style |= CD_BOLD; if (italic) style |= CD_ITALIC; if (underline) style |= CD_UNDERLINE; if (strikeout) style |= CD_STRIKEOUT; } else { if (!cdParseIupWinFont(nativefont, type_face, &style, &size)) { if (!cdParsePangoFont(nativefont, type_face, &style, &size)) return 0; } if (style&CD_BOLD) bold = 1; if (style&CD_ITALIC) italic = 1; if (style&CD_UNDERLINE) underline = 1; if (style&CD_STRIKEOUT) strikeout = 1; } REAL emSize = (REAL)(cdGetFontSizePixels(ctxcanvas->canvas, size)); INT fontStyle = FontStyleRegular; if (bold) fontStyle |= FontStyleBold; if (italic) fontStyle |= FontStyleItalic; if (underline) fontStyle |= FontStyleUnderline; if (strikeout) fontStyle |= FontStyleStrikeout; const char* new_type_face = type_face; if (strstr(type_face, "Times") != NULL) new_type_face = "Times"; if (strstr(type_face, "Courier") != NULL) new_type_face = "Courier"; if (strstr(type_face, "Arial") != NULL) new_type_face = "Helvetica"; if (strstr(type_face, "Helv") != NULL) new_type_face = "Helvetica"; FontFamily *fontFamily; if (strstr(type_face, "System") != NULL) { new_type_face = "System"; fontFamily = FontFamily::GenericSansSerif()->Clone(); } else fontFamily = new FontFamily(cdwpStringToUnicode(type_face, ctxcanvas->utf8mode)); if (!fontFamily->IsAvailable()) { delete fontFamily; return 0; } Font* font = new Font(fontFamily, emSize, fontStyle, UnitPixel); if (!font->IsAvailable()) { delete fontFamily; delete font; return 0; } if (ctxcanvas->font) delete ctxcanvas->font; ctxcanvas->font = font; REAL fontSize = ctxcanvas->font->GetSize(); int emHeight = fontFamily->GetEmHeight(fontStyle); ctxcanvas->fontinfo.height = sDesign2Pixel(fontFamily->GetLineSpacing(fontStyle), fontSize, emHeight); ctxcanvas->fontinfo.ascent = sDesign2Pixel(fontFamily->GetCellAscent(fontStyle), fontSize, emHeight); ctxcanvas->fontinfo.descent = sDesign2Pixel(fontFamily->GetCellDescent(fontStyle), fontSize, emHeight); delete fontFamily; /* update cdfont parameters */ ctxcanvas->canvas->font_style = style; ctxcanvas->canvas->font_size = size; strcpy(ctxcanvas->canvas->font_type_face, new_type_face); return 1; } static void cdgetfontdim(cdCtxCanvas* ctxcanvas, int *max_width, int *line_height, int *ascent, int *descent) { if (max_width) { RectF boundingBox; ctxcanvas->graphics->MeasureString(L"W", 1, ctxcanvas->font, PointF(0,0), &boundingBox); *max_width = cdRound(boundingBox.Width); } if (line_height) *line_height = ctxcanvas->fontinfo.height; if (ascent) *ascent = ctxcanvas->fontinfo.ascent; if (descent) *descent = ctxcanvas->fontinfo.descent; } static void cdtransform(cdCtxCanvas *ctxcanvas, const double* matrix) { Matrix transformMatrix; ctxcanvas->graphics->ResetTransform(); // reset to the identity. if (matrix) ctxcanvas->canvas->invert_yaxis = 0; /* let the transformation do the axis invertion */ else ctxcanvas->canvas->invert_yaxis = 1; if (sAddTransform(ctxcanvas, transformMatrix, matrix)) ctxcanvas->graphics->SetTransform(&transformMatrix); } static void cdclear(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->canvas->clip_mode != CD_CLIPOFF) ctxcanvas->graphics->ResetClip(); /* do NOT use "ctxcanvas->bg" here, because it depends on backopacity */ ctxcanvas->graphics->Clear(sColor2Windows(ctxcanvas->canvas->background)); if (ctxcanvas->canvas->clip_mode != CD_CLIPOFF) cdclip(ctxcanvas, ctxcanvas->canvas->clip_mode); ctxcanvas->dirty = 1; } /******************************************************************/ /* %S Funcoes de imagens do cliente */ /******************************************************************/ static void sRGB2Bitmap(Bitmap& image, int width, int height, const unsigned char *red, const unsigned char *green, const unsigned char *blue, int xmin, int xmax, int ymin, int ymax, int topdown) { BitmapData bitmapData; Rect rect(0,0,image.GetWidth(),image.GetHeight()); image.LockBits(&rect, ImageLockModeWrite, PixelFormat24bppRGB, &bitmapData); /* ymin and xmax unused */ (void)ymin; (void)xmax; int line_offset; for(int j = 0; j < rect.Height; j++) { if (topdown) line_offset = (height - (ymax - j) - 1)*width; else line_offset = (ymax - j)*width; BYTE* line_data = (BYTE*)bitmapData.Scan0 + j*bitmapData.Stride; for(int i = 0; i < rect.Width; i++) { int offset = line_offset + i + xmin; int offset_data = i*3; line_data[offset_data+0] = blue[offset]; line_data[offset_data+1] = green[offset]; line_data[offset_data+2] = red[offset]; } } image.UnlockBits(&bitmapData); } static void sRGBA2Bitmap(Bitmap& image, int width, int height, const unsigned char *red, const unsigned char *green, const unsigned char *blue, const unsigned char *alpha, int xmin, int xmax, int ymin, int ymax, int topdown) { BitmapData bitmapData; Rect rect(0,0,image.GetWidth(),image.GetHeight()); image.LockBits(&rect, ImageLockModeWrite, PixelFormat32bppARGB, &bitmapData); /* ymin and xmax unused */ (void)ymin; (void)xmax; int line_offset; for(int j = 0; j < rect.Height; j++) { if (topdown) line_offset = (height - (ymax - j) - 1)*width; else line_offset = (ymax - j)*width; BYTE* line_data = (BYTE*)bitmapData.Scan0 + j*bitmapData.Stride; for(int i = 0; i < rect.Width; i++) { int offset = line_offset + i + xmin; int offset_data = i*4; line_data[offset_data+0] = blue? blue[offset]: 0; line_data[offset_data+1] = green? green[offset]: 0; line_data[offset_data+2] = red? red[offset]: 0; line_data[offset_data+3] = alpha[offset]; } } image.UnlockBits(&bitmapData); } static void sAlpha2Bitmap(Bitmap& image, int width, int height, const unsigned char *alpha, int xmin, int xmax, int ymin, int ymax, int topdown) { BitmapData bitmapData; Rect rect(0,0,image.GetWidth(),image.GetHeight()); image.LockBits(&rect, ImageLockModeWrite, PixelFormat32bppARGB, &bitmapData); /* ymin and xmax unused */ (void)ymin; (void)xmax; int line_offset; for(int j = 0; j < rect.Height; j++) { if (topdown) line_offset = (height - (ymax - j) - 1)*width; else line_offset = (ymax - j)*width; BYTE* line_data = (BYTE*)bitmapData.Scan0 + j*bitmapData.Stride; for(int i = 0; i < rect.Width; i++) { int offset = line_offset + i + xmin; int offset_data = i*4; line_data[offset_data+3] = alpha[offset]; } } image.UnlockBits(&bitmapData); } /* GDI+ does not natively work with palettized images. GDI+ will not try to draw on a palettized image as it would require color reducing the drawing result. GDI+ will work natively with 32bpp image data behind the scenes anyway so there is no economy in trying to work with 8bpp images. Full support for palettized images was on the feature list but it did not make the cut for version 1 of GDI+. */ static void sMap2Bitmap(Bitmap& image, int width, int height, const unsigned char *index, const long int *colors, int xmin, int xmax, int ymin, int ymax, int topdown) { BitmapData bitmapData; Rect rect(0,0,image.GetWidth(),image.GetHeight()); image.LockBits(&rect, ImageLockModeWrite, PixelFormat24bppRGB, &bitmapData); /* ymin and xmax unused */ (void)ymin; (void)xmax; int line_offset; for(int j = 0; j < rect.Height; j++) { if (topdown) line_offset = (height - (ymax - j) - 1)*width; else line_offset = (ymax - j)*width; BYTE* line_data = (BYTE*)bitmapData.Scan0 + j*bitmapData.Stride; for(int i = 0; i < rect.Width; i++) { int map_index = index[line_offset + i + xmin]; long color = colors[map_index]; int offset_data = i*3; line_data[offset_data+0] = cdBlue(color); line_data[offset_data+1] = cdGreen(color); line_data[offset_data+2] = cdRed(color); } } image.UnlockBits(&bitmapData); } static void sBitmap2RGB(Bitmap& image, unsigned char *red, unsigned char *green, unsigned char *blue) { BitmapData bitmapData; Rect rect(0,0,image.GetWidth(),image.GetHeight()); image.LockBits(&rect, ImageLockModeRead, PixelFormat24bppRGB, &bitmapData); for(int j = 0; j < rect.Height; j++) { int line_offset = ((rect.Height-1) - j)*rect.Width; BYTE* line_data = (BYTE*)bitmapData.Scan0 + j*bitmapData.Stride; for(int i = 0; i < rect.Width; i++) { int offset = line_offset + i; int offset_data = i*3; blue[offset] = line_data[offset_data+0]; green[offset] = line_data[offset_data+1]; red[offset] = line_data[offset_data+2]; } } image.UnlockBits(&bitmapData); } static void cdgetimagergb(cdCtxCanvas* ctxcanvas, unsigned char *red, unsigned char *green, unsigned char *blue, int x, int y, int w, int h) { Matrix transformMatrix; ctxcanvas->graphics->GetTransform(&transformMatrix); if (!transformMatrix.IsIdentity()) ctxcanvas->graphics->ResetTransform(); // reset to the identity. /* if 0, invert because the transform was reset */ if (!ctxcanvas->canvas->invert_yaxis) y = _cdInvertYAxis(ctxcanvas->canvas, y); y -= (h - 1); /* y starts at the bottom of the image */ Bitmap image(w, h, PixelFormat24bppRGB); image.SetResolution(ctxcanvas->graphics->GetDpiX(), ctxcanvas->graphics->GetDpiX()); Graphics* imggraphics = new Graphics(&image); if (ctxcanvas->wtype == CDW_BMP) { imggraphics->DrawImage(ctxcanvas->bitmap, Rect(0, 0, w, h), x, y, w, h, UnitPixel, NULL, NULL, NULL); } else { HDC hdc = ctxcanvas->graphics->GetHDC(); HDC img_hdc = imggraphics->GetHDC(); BitBlt(img_hdc,0,0,w,h,hdc,x,y,SRCCOPY); imggraphics->ReleaseHDC(img_hdc); ctxcanvas->graphics->ReleaseHDC(hdc); } delete imggraphics; sBitmap2RGB(image, red, green, blue); if (!transformMatrix.IsIdentity()) ctxcanvas->graphics->SetTransform(&transformMatrix); } static void sFixImageY(cdCanvas* canvas, int *topdown, int *y, int *h) { if (canvas->invert_yaxis) { if (*h < 0) *topdown = 1; else *topdown = 0; } else { if (*h < 0) *topdown = 0; else *topdown = 1; } if (*h < 0) *h = -(*h); // y is at top-left corner (UNDOCUMENTED FEATURE) if (!(*topdown)) *y -= ((*h) - 1); // move Y to top-left corner, since it was at the bottom of the image } static void cdputimagerectmap(cdCtxCanvas* ctxcanvas, int width, int height, const unsigned char *index, const long int *colors, int x, int y, int w, int h, int xmin, int xmax, int ymin, int ymax) { int topdown; Bitmap image(xmax-xmin+1, ymax-ymin+1, PixelFormat24bppRGB); image.SetResolution(ctxcanvas->graphics->GetDpiX(), ctxcanvas->graphics->GetDpiX()); sFixImageY(ctxcanvas->canvas, &topdown, &y, &h); sMap2Bitmap(image, width, height, index, colors, xmin, xmax, ymin, ymax, topdown); ImageAttributes imageAttributes; if (ctxcanvas->use_img_transp) imageAttributes.SetColorKey(ctxcanvas->img_transp[0], ctxcanvas->img_transp[1], ColorAdjustTypeBitmap); if(ctxcanvas->use_img_points) { Point pts[3]; pts[0] = ctxcanvas->img_points[0]; pts[1] = ctxcanvas->img_points[1]; pts[2] = ctxcanvas->img_points[2]; if (ctxcanvas->canvas->invert_yaxis) { pts[0].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[0].Y); pts[1].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[1].Y); pts[2].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[2].Y); } ctxcanvas->graphics->DrawImage(&image, pts, 3, 0, 0, image.GetWidth(), image.GetHeight(), UnitPixel, &imageAttributes, NULL, NULL); } else { REAL bw = (REAL)image.GetWidth(); REAL bh = (REAL)image.GetHeight(); if (w > bw) bw-=0.5; // Fix the problem of not using PixelOffsetModeHalf if (h > bh) bh-=0.5; ctxcanvas->graphics->DrawImage(&image, RectF((REAL)x, (REAL)y, (REAL)w, (REAL)h), 0, 0, bw, bh, UnitPixel, &imageAttributes, NULL, NULL); } ctxcanvas->dirty = 1; } static void cdputimagerectrgb(cdCtxCanvas* ctxcanvas, int width, int height, const unsigned char *red, const unsigned char *green, const unsigned char *blue, int x, int y, int w, int h, int xmin, int xmax, int ymin, int ymax) { int topdown; Bitmap image(xmax-xmin+1, ymax-ymin+1, PixelFormat24bppRGB); image.SetResolution(ctxcanvas->graphics->GetDpiX(), ctxcanvas->graphics->GetDpiX()); sFixImageY(ctxcanvas->canvas, &topdown, &y, &h); sRGB2Bitmap(image, width, height, red, green, blue, xmin, xmax, ymin, ymax, topdown); ImageAttributes imageAttributes; if (ctxcanvas->use_img_transp) imageAttributes.SetColorKey(ctxcanvas->img_transp[0], ctxcanvas->img_transp[1], ColorAdjustTypeBitmap); if(ctxcanvas->use_img_points) { Point pts[3]; pts[0] = ctxcanvas->img_points[0]; pts[1] = ctxcanvas->img_points[1]; pts[2] = ctxcanvas->img_points[2]; if (ctxcanvas->canvas->invert_yaxis) { pts[0].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[0].Y); pts[1].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[1].Y); pts[2].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[2].Y); } ctxcanvas->graphics->DrawImage(&image, pts, 3, 0, 0, image.GetWidth(), image.GetHeight(), UnitPixel, &imageAttributes, NULL, NULL); } else { REAL bw = (REAL)image.GetWidth(); REAL bh = (REAL)image.GetHeight(); if (w > bw) bw-=0.5; // Fix the problem of not using PixelOffsetModeHalf if (h > bh) bh-=0.5; ctxcanvas->graphics->DrawImage(&image, RectF((REAL)x, (REAL)y, (REAL)w, (REAL)h), 0, 0, bw, bh, UnitPixel, &imageAttributes, NULL, NULL); } ctxcanvas->dirty = 1; } static void cdputimagerectrgba(cdCtxCanvas* ctxcanvas, int width, int height, const unsigned char *red, const unsigned char *green, const unsigned char *blue, const unsigned char *alpha, int x, int y, int w, int h, int xmin, int xmax, int ymin, int ymax) { int topdown; Bitmap image(xmax-xmin+1, ymax-ymin+1, PixelFormat32bppARGB); image.SetResolution(ctxcanvas->graphics->GetDpiX(), ctxcanvas->graphics->GetDpiX()); sFixImageY(ctxcanvas->canvas, &topdown, &y, &h); sRGBA2Bitmap(image, width, height, red, green, blue, alpha, xmin, xmax, ymin, ymax, topdown); ImageAttributes imageAttributes; if(ctxcanvas->use_img_points) { Point pts[3]; pts[0] = ctxcanvas->img_points[0]; pts[1] = ctxcanvas->img_points[1]; pts[2] = ctxcanvas->img_points[2]; if (ctxcanvas->canvas->invert_yaxis) { pts[0].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[0].Y); pts[1].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[1].Y); pts[2].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[2].Y); } ctxcanvas->graphics->DrawImage(&image, pts, 3, 0, 0, image.GetWidth(), image.GetHeight(), UnitPixel, &imageAttributes, NULL, NULL); } else { REAL bw = (REAL)image.GetWidth(); REAL bh = (REAL)image.GetHeight(); if (w > bw) bw-=0.5; // Fix the problem of not using PixelOffsetModeHalf if (h > bh) bh-=0.5; ctxcanvas->graphics->DrawImage(&image, RectF((REAL)x, (REAL)y, (REAL)w, (REAL)h), 0, 0, bw, bh, UnitPixel, &imageAttributes, NULL, NULL); } ctxcanvas->dirty = 1; } /********************************************************************/ /* %S Funcoes de imagens do servidor */ /********************************************************************/ static void cdpixel(cdCtxCanvas* ctxcanvas, int x, int y, long int cd_color) { if (!ctxcanvas->graphics->IsVisible(x, y)) return; if (ctxcanvas->wtype == CDW_BMP) { ctxcanvas->bitmap->SetPixel(x, y, sColor2Windows(cd_color)); } else { if (ctxcanvas->canvas->use_matrix) { Point p = Point(x, y); ctxcanvas->graphics->TransformPoints(CoordinateSpacePage, CoordinateSpaceWorld, &p, 1); x = p.X; y = p.Y; } HDC hdc = ctxcanvas->graphics->GetHDC(); SetPixelV(hdc, x, y, sColor2Windows(cd_color).ToCOLORREF()); ctxcanvas->graphics->ReleaseHDC(hdc); } ctxcanvas->dirty = 1; } static int sFormat2Bpp(PixelFormat pixelFormat) { switch(pixelFormat) { case PixelFormat1bppIndexed: return 1; case PixelFormat4bppIndexed: return 4; case PixelFormat8bppIndexed: return 8; case PixelFormat16bppARGB1555: case PixelFormat16bppGrayScale: case PixelFormat16bppRGB555: case PixelFormat16bppRGB565: return 16; case PixelFormat24bppRGB: return 24; case PixelFormat32bppARGB: case PixelFormat32bppPARGB: case PixelFormat32bppRGB: return 32; case PixelFormat48bppRGB: return 48; case PixelFormat64bppARGB: case PixelFormat64bppPARGB: return 64; } return 0; } static cdCtxImage *cdcreateimage(cdCtxCanvas* ctxcanvas, int width, int height) { cdCtxImage *ctximage = new cdCtxImage; ctximage->alpha = NULL; if (ctxcanvas->img_format) { ctximage->bitmap = new Bitmap(width, height, ctxcanvas->img_format==24? PixelFormat24bppRGB: PixelFormat32bppARGB); if (!ctximage->bitmap) { delete ctximage; return NULL; } if (ctxcanvas->img_format==32 && ctxcanvas->img_alpha) ctximage->alpha = ctxcanvas->img_alpha; ctximage->bitmap->SetResolution(ctxcanvas->graphics->GetDpiX(), ctxcanvas->graphics->GetDpiX()); } else { ctximage->bitmap = new Bitmap(width, height, ctxcanvas->graphics); if (!ctximage->bitmap) { delete ctximage; return NULL; } } ctximage->w = width; ctximage->h = height; ctximage->bpp = sFormat2Bpp(ctximage->bitmap->GetPixelFormat()); ctximage->xres = ctximage->bitmap->GetHorizontalResolution() / 25.4; ctximage->yres = ctximage->bitmap->GetVerticalResolution() / 25.4; ctximage->w_mm = ctximage->w / ctximage->xres; ctximage->h_mm = ctximage->h / ctximage->yres; Graphics imggraphics(ctximage->bitmap); imggraphics.Clear(Color((ARGB)Color::White)); return ctximage; } static void cdgetimage(cdCtxCanvas* ctxcanvas, cdCtxImage *ctximage, int x, int y) { Matrix transformMatrix; ctxcanvas->graphics->GetTransform(&transformMatrix); if (!transformMatrix.IsIdentity()) ctxcanvas->graphics->ResetTransform(); // reset to the identity. /* if 0, invert because the transform was reset */ if (!ctxcanvas->canvas->invert_yaxis) y = _cdInvertYAxis(ctxcanvas->canvas, y); /* y is the bottom-left of the image in CD, must be at upper-left */ y -= ctximage->h-1; if (ctxcanvas->wtype == CDW_BMP) { Graphics imggraphics(ctximage->bitmap); imggraphics.DrawImage(ctxcanvas->bitmap, Rect(0, 0, ctximage->w,ctximage->h), x, y, ctximage->w, ctximage->h, UnitPixel, NULL, NULL, NULL); } else { Graphics imggraphics(ctximage->bitmap); HDC hdc = ctxcanvas->graphics->GetHDC(); HDC img_hdc = imggraphics.GetHDC(); BitBlt(img_hdc,0,0,ctximage->w,ctximage->h,hdc,x,y,SRCCOPY); imggraphics.ReleaseHDC(img_hdc); ctxcanvas->graphics->ReleaseHDC(hdc); } if (!transformMatrix.IsIdentity()) ctxcanvas->graphics->SetTransform(&transformMatrix); } static void cdputimagerect(cdCtxCanvas* ctxcanvas, cdCtxImage *ctximage, int x, int y, int xmin, int xmax, int ymin, int ymax) { y -= (ymax-ymin+1)-1; /* y starts at the bottom of the image */ INT srcx = xmin; INT srcy = (ctximage->h-1)-ymax; INT srcwidth = xmax-xmin+1; INT srcheight = ymax-ymin+1; Rect destRect(x, y, srcwidth, srcheight); ImageAttributes imageAttributes; if (ctxcanvas->use_img_transp) imageAttributes.SetColorKey(ctxcanvas->img_transp[0], ctxcanvas->img_transp[1], ColorAdjustTypeBitmap); if (ctximage->bpp == 32 && ctximage->alpha) { sAlpha2Bitmap(*ctximage->bitmap, ctximage->w, ctximage->h, ctximage->alpha, 0, ctximage->w-1, 0, ctximage->h-1, 0); } if(ctxcanvas->use_img_points) { Point pts[3]; pts[0] = ctxcanvas->img_points[0]; pts[1] = ctxcanvas->img_points[1]; pts[2] = ctxcanvas->img_points[2]; if (ctxcanvas->canvas->invert_yaxis) { pts[0].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[0].Y); pts[1].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[1].Y); pts[2].Y = _cdInvertYAxis(ctxcanvas->canvas, pts[2].Y); } ctxcanvas->graphics->DrawImage(ctximage->bitmap, pts, 3, srcx, srcy, srcwidth, srcheight, UnitPixel, &imageAttributes, NULL, NULL); } else { ctxcanvas->graphics->DrawImage(ctximage->bitmap, destRect, srcx, srcy, srcwidth, srcheight, UnitPixel, &imageAttributes, NULL, NULL); } ctxcanvas->dirty = 1; } static void cdkillimage(cdCtxImage *ctximage) { delete ctximage->bitmap; delete ctximage; } static void cdscrollarea(cdCtxCanvas* ctxcanvas, int xmin, int xmax, int ymin, int ymax, int dx, int dy) { Matrix transformMatrix; ctxcanvas->graphics->GetTransform(&transformMatrix); if (!transformMatrix.IsIdentity()) ctxcanvas->graphics->ResetTransform(); // reset to the identity. // if 0, invert because the transform was reset if (!ctxcanvas->canvas->invert_yaxis) { dy = -dy; ymin = _cdInvertYAxis(ctxcanvas->canvas, ymin); ymax = _cdInvertYAxis(ctxcanvas->canvas, ymax); _cdSwapInt(ymin, ymax); } if (ctxcanvas->wtype == CDW_BMP) { Rect rect(xmin, ymin, xmax-xmin+1, ymax-ymin+1); Bitmap* bitmap = ctxcanvas->bitmap->Clone(rect, ctxcanvas->bitmap->GetPixelFormat()); rect.Offset(dx, dy); ctxcanvas->graphics->DrawImage(bitmap, rect, 0, 0, rect.Width, rect.Height, UnitPixel, NULL, NULL, NULL); delete bitmap; } else { RECT rect; rect.left = xmin; rect.right = xmax+1; rect.top = ymin; rect.bottom = ymax+1; HDC hdc = ctxcanvas->graphics->GetHDC(); ScrollDC(hdc, dx, dy, &rect, NULL, NULL, NULL); ctxcanvas->graphics->ReleaseHDC(hdc); } ctxcanvas->dirty = 1; if (!transformMatrix.IsIdentity()) ctxcanvas->graphics->SetTransform(&transformMatrix); } static void cdflush(cdCtxCanvas* ctxcanvas) { ctxcanvas->graphics->Flush(FlushIntentionSync); } /********************************************************************/ /* %S Atributos personalizados */ /********************************************************************/ static void set_img_format_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (!data) ctxcanvas->img_format = 0; else { int bpp = 0; sscanf(data, "%d", &bpp); if (bpp == 0) return; if (bpp == 32) ctxcanvas->img_format = 32; else ctxcanvas->img_format = 24; } } static char* get_img_format_attrib(cdCtxCanvas* ctxcanvas) { if (!ctxcanvas->img_format) return NULL; if (ctxcanvas->img_format == 32) return "32"; else return "24"; } static cdAttribute img_format_attrib = { "IMAGEFORMAT", set_img_format_attrib, get_img_format_attrib }; static void set_img_alpha_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (!data) ctxcanvas->img_alpha = NULL; else ctxcanvas->img_alpha = (unsigned char*)data; } static char* get_img_alpha_attrib(cdCtxCanvas* ctxcanvas) { return (char*)ctxcanvas->img_alpha; } static cdAttribute img_alpha_attrib = { "IMAGEALPHA", set_img_alpha_attrib, get_img_alpha_attrib }; static void set_img_transp_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (!data) ctxcanvas->use_img_transp = 0; else { int r1, g1, b1, r2, g2, b2; ctxcanvas->use_img_transp = 1; sscanf(data, "%d %d %d %d %d %d", &r1, &g1, &b1, &r2, &g2, &b2); ctxcanvas->img_transp[0] = Color((BYTE)r1, (BYTE)g1, (BYTE)b1); ctxcanvas->img_transp[1] = Color((BYTE)r2, (BYTE)g2, (BYTE)b2); } } static char* get_img_transp_attrib(cdCtxCanvas* ctxcanvas) { if (!ctxcanvas->use_img_transp) return NULL; int r1 = ctxcanvas->img_transp[0].GetRed(); int g1 = ctxcanvas->img_transp[0].GetGreen(); int b1 = ctxcanvas->img_transp[0].GetBlue(); int r2 = ctxcanvas->img_transp[1].GetRed(); int g2 = ctxcanvas->img_transp[1].GetGreen(); int b2 = ctxcanvas->img_transp[1].GetBlue(); static char data[50]; sprintf(data, "%d %d %d %d %d %d", r1, g1, b1, r2, g2, b2); return data; } static cdAttribute img_transp_attrib = { "IMAGETRANSP", set_img_transp_attrib, get_img_transp_attrib }; static void set_gradientcolor_attrib(cdCtxCanvas* ctxcanvas, char* data) { // used by CD_FILLGRADIENT if (data) { int r, g, b, cur_vertex; sscanf(data, "%d %d %d", &r, &g, &b); cur_vertex = ctxcanvas->canvas->poly_n; if (cur_vertex < 500) ctxcanvas->pathGradient[cur_vertex] = Color((BYTE)r, (BYTE)g, (BYTE)b); } } static cdAttribute gradientcolor_attrib = { "GRADIENTCOLOR", set_gradientcolor_attrib, NULL }; static void set_linegradient_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (data) { int x1, y1, x2, y2; sscanf(data, "%d %d %d %d", &x1, &y1, &x2, &y2); Point p1 = Point(x1, y1); Point p2 = Point(x2, y2); ctxcanvas->gradient[0] = p1; ctxcanvas->gradient[1] = p2; if (ctxcanvas->canvas->invert_yaxis) { p1.Y = _cdInvertYAxis(ctxcanvas->canvas, p1.Y); p2.Y = _cdInvertYAxis(ctxcanvas->canvas, p2.Y); } delete ctxcanvas->fillBrush; ctxcanvas->fillBrush = new LinearGradientBrush(p1, p2, ctxcanvas->fg, ctxcanvas->bg); } } static char* get_linegradient_attrib(cdCtxCanvas* ctxcanvas) { static char data[100]; sprintf(data, "%d %d %d %d", ctxcanvas->gradient[0].X, ctxcanvas->gradient[0].Y, ctxcanvas->gradient[1].X, ctxcanvas->gradient[1].Y); return data; } static cdAttribute linegradient_attrib = { "LINEGRADIENT", set_linegradient_attrib, get_linegradient_attrib }; static void set_linecap_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (data) { LineCap cap = LineCapFlat; switch(data[0]) { case 'T': cap = LineCapTriangle; ctxcanvas->linePen->SetDashCap(DashCapTriangle); break; case 'N': cap = LineCapNoAnchor; break; case 'S': cap = LineCapSquareAnchor; break; case 'R': cap = LineCapRoundAnchor; break; case 'D': cap = LineCapDiamondAnchor; break; case 'A': cap = LineCapArrowAnchor; break; default: return; } ctxcanvas->linePen->SetStartCap(cap); ctxcanvas->linePen->SetEndCap(cap); } } static cdAttribute linecap_attrib = { "LINECAP", set_linecap_attrib, NULL }; static void set_rotate_attrib(cdCtxCanvas* ctxcanvas, char* data) { /* ignore ROTATE if transform is set, because there is native support for transformations */ if (ctxcanvas->canvas->use_matrix) return; if (data) { sscanf(data, "%lg %d %d", &ctxcanvas->rotate_angle, &ctxcanvas->rotate_center_x, &ctxcanvas->rotate_center_y); } else { ctxcanvas->rotate_angle = 0; ctxcanvas->rotate_center_x = 0; ctxcanvas->rotate_center_y = 0; } cdtransform(ctxcanvas, NULL); } static char* get_rotate_attrib(cdCtxCanvas* ctxcanvas) { static char data[100]; sprintf(data, "%g %d %d", ctxcanvas->rotate_angle, ctxcanvas->rotate_center_x, ctxcanvas->rotate_center_y); return data; } static cdAttribute rotate_attrib = { "ROTATE", set_rotate_attrib, get_rotate_attrib }; static void set_img_points_attrib(cdCtxCanvas* ctxcanvas, char* data) { int p[6]; if (!data) { ctxcanvas->use_img_points = 0; return; } sscanf(data, "%d %d %d %d %d %d", &p[0], &p[1], &p[2], &p[3], &p[4], &p[5]); ctxcanvas->img_points[0] = Point(p[0], p[1]); ctxcanvas->img_points[1] = Point(p[2], p[3]); ctxcanvas->img_points[2] = Point(p[4], p[5]); ctxcanvas->use_img_points = 1; } static char* get_img_points_attrib(cdCtxCanvas* ctxcanvas) { static char data[100]; if (!ctxcanvas->use_img_points) return NULL; sprintf(data, "%d %d %d %d %d %d", ctxcanvas->img_points[0].X, ctxcanvas->img_points[0].Y, ctxcanvas->img_points[1].X, ctxcanvas->img_points[1].Y, ctxcanvas->img_points[2].X, ctxcanvas->img_points[2].Y); return data; } static cdAttribute img_points_attrib = { "IMAGEPOINTS", set_img_points_attrib, get_img_points_attrib }; /* check IUP code from iupwin_info.c for Windows 8.1 compatibility */ static BOOL Is_WinXP_or_WinSrv03(void) { OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx (&osvi); BOOL bIsWindowsXP = (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1)); BOOL bIsWindowsServer2003 = (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2)); return bIsWindowsXP || bIsWindowsServer2003; } static void set_aa_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (!data || data[0] == '0') { ctxcanvas->graphics->SetInterpolationMode(InterpolationModeNearestNeighbor); ctxcanvas->graphics->SetSmoothingMode(SmoothingModeNone); ctxcanvas->antialias = 0; } else { ctxcanvas->graphics->SetInterpolationMode(InterpolationModeBilinear); ctxcanvas->graphics->SetSmoothingMode(SmoothingModeAntiAlias); /* Do NOT set PixelOffsetMode because some graphic objects move their position and size. ctxcanvas->graphics->SetPixelOffsetMode(PixelOffsetModeHalf); */ ctxcanvas->antialias = 1; } } static char* get_aa_attrib(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->antialias) return "1"; else return "0"; } static cdAttribute aa_attrib = { "ANTIALIAS", set_aa_attrib, get_aa_attrib }; static void set_txtaa_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (!data || data[0] == '0') { ctxcanvas->graphics->SetTextRenderingHint(TextRenderingHintSingleBitPerPixelGridFit); ctxcanvas->txt_antialias = 0; } else { if (Is_WinXP_or_WinSrv03()) /* Microsoft Windows XP and Windows Server 2003 only: ClearType rendering is supported only on Windows XP and Windows Server 2003. Therefore, TextRenderingHintClearTypeGridFit is ignored on other operating systems. */ ctxcanvas->graphics->SetTextRenderingHint(TextRenderingHintClearTypeGridFit); else ctxcanvas->graphics->SetTextRenderingHint(TextRenderingHintAntiAliasGridFit); ctxcanvas->txt_antialias = 1; } } static char* get_txtaa_attrib(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->txt_antialias) return "1"; else return "0"; } static cdAttribute txtaa_attrib = { "TEXTANTIALIAS", set_txtaa_attrib, get_txtaa_attrib }; static void set_utf8mode_attrib(cdCtxCanvas* ctxcanvas, char* data) { if (!data || data[0] == '0') ctxcanvas->utf8mode = 0; else ctxcanvas->utf8mode = 1; } static char* get_utf8mode_attrib(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->utf8mode) return "1"; else return "0"; } static cdAttribute utf8mode_attrib = { "UTF8MODE", set_utf8mode_attrib, get_utf8mode_attrib }; static void set_window_rgn(cdCtxCanvas* ctxcanvas, char* data) { if (data) { HRGN hrgn = ctxcanvas->new_region->GetHRGN(ctxcanvas->graphics); SetWindowRgn(ctxcanvas->hWnd, hrgn, TRUE); } else SetWindowRgn(ctxcanvas->hWnd, NULL, TRUE); } static cdAttribute window_rgn_attrib = { "WINDOWRGN", set_window_rgn, NULL }; static char* get_hdc_attrib(cdCtxCanvas* ctxcanvas) { return (char*)ctxcanvas->hDC; } static cdAttribute hdc_attrib = { "HDC", NULL, get_hdc_attrib }; static cdAttribute gc_attrib = { "GC", NULL, get_hdc_attrib }; static char* get_gdiplus_attrib(cdCtxCanvas* ctxcanvas) { (void)ctxcanvas; return "1"; } static cdAttribute gdiplus_attrib = { "GDI+", NULL, get_gdiplus_attrib }; void cdwpUpdateCanvas(cdCtxCanvas* ctxcanvas) { if (ctxcanvas->wtype == CDW_EMF && ctxcanvas->metafile) // first update metafile is NULL. { MetafileHeader metaHeader; ctxcanvas->metafile->GetMetafileHeader(&metaHeader); ctxcanvas->canvas->xres = metaHeader.GetDpiX() / 25.4; ctxcanvas->canvas->yres = metaHeader.GetDpiY() / 25.4; } else { ctxcanvas->canvas->xres = ctxcanvas->graphics->GetDpiX() / 25.4; ctxcanvas->canvas->yres = ctxcanvas->graphics->GetDpiY() / 25.4; } ctxcanvas->canvas->w_mm = ((double)ctxcanvas->canvas->w) / ctxcanvas->canvas->xres; ctxcanvas->canvas->h_mm = ((double)ctxcanvas->canvas->h) / ctxcanvas->canvas->yres; ctxcanvas->graphics->SetPageScale(1); ctxcanvas->graphics->SetPageUnit(UnitPixel); ctxcanvas->graphics->SetCompositingMode(CompositingModeSourceOver); ctxcanvas->graphics->SetCompositingQuality(CompositingQualityDefault); if (ctxcanvas->antialias) set_aa_attrib(ctxcanvas, "1"); else set_aa_attrib(ctxcanvas, NULL); if (ctxcanvas->txt_antialias) set_txtaa_attrib(ctxcanvas, "1"); else set_txtaa_attrib(ctxcanvas, NULL); sUpdateTransform(ctxcanvas); } /* %F Cria o canvas para o driver Windows. */ cdCtxCanvas *cdwpCreateCanvas(cdCanvas* canvas, Graphics* graphics, int wtype) { cdCtxCanvas* ctxcanvas = new cdCtxCanvas; memset(ctxcanvas, 0, sizeof(cdCtxCanvas)); /* update canvas context */ ctxcanvas->canvas = canvas; canvas->ctxcanvas = ctxcanvas; ctxcanvas->wtype = wtype; ctxcanvas->graphics = graphics; ctxcanvas->linePen = new Pen(Color()); ctxcanvas->lineBrush = new SolidBrush(Color()); ctxcanvas->fillBrush = new SolidBrush(Color()); ctxcanvas->font = NULL; // will be created in the update default attrib set_aa_attrib(ctxcanvas, "1"); // default is ANTIALIAS=1 set_txtaa_attrib(ctxcanvas, "1"); // default is TEXTANTIALIAS=1 ctxcanvas->fg = Color(); // black,opaque ctxcanvas->bg = Color(255, 255, 255); // white,opaque => used only for fill canvas->invert_yaxis = 1; ctxcanvas->clip_poly = NULL; ctxcanvas->clip_fpoly = NULL; ctxcanvas->clip_poly_n = 0; ctxcanvas->clip_region = NULL; ctxcanvas->new_region = NULL; cdRegisterAttribute(canvas, &img_points_attrib); cdRegisterAttribute(canvas, &img_transp_attrib); cdRegisterAttribute(canvas, &img_format_attrib); cdRegisterAttribute(canvas, &img_alpha_attrib); cdRegisterAttribute(canvas, &aa_attrib); cdRegisterAttribute(canvas, &txtaa_attrib); cdRegisterAttribute(canvas, &gradientcolor_attrib); cdRegisterAttribute(canvas, &linegradient_attrib); cdRegisterAttribute(canvas, &rotate_attrib); cdRegisterAttribute(canvas, &linecap_attrib); cdRegisterAttribute(canvas, &hdc_attrib); cdRegisterAttribute(canvas, &gc_attrib); cdRegisterAttribute(canvas, &window_rgn_attrib); cdRegisterAttribute(canvas, &gdiplus_attrib); cdRegisterAttribute(canvas, &utf8mode_attrib); cdwpUpdateCanvas(ctxcanvas); return ctxcanvas; } static ULONG_PTR cd_gdiplusToken = (ULONG_PTR)0; static void __stdcall cd_DebugEvent(int level, char* msg) { (void)level; MessageBoxA(NULL, msg, "GDI+ Debug", 0); } void cdwpGdiPlusStartup(int debug) { if (!cd_gdiplusToken) { GdiplusStartupInput input; if (debug) input.DebugEventCallback = (DebugEventProc)cd_DebugEvent; // Initialize GDI+. GdiplusStartup(&cd_gdiplusToken, &input, NULL); } } void cdwpGdiPlusShutdown(void) { if (cd_gdiplusToken) GdiplusShutdown(cd_gdiplusToken); } void cdwpInitTable(cdCanvas* canvas) { cdCtxCanvas* ctxcanvas = canvas->ctxcanvas; canvas->cxFlush = cdflush; canvas->cxPixel = cdpixel; canvas->cxLine = cdline; canvas->cxPoly = cdpoly; canvas->cxRect = cdrect; canvas->cxBox = cdbox; canvas->cxArc = cdarc; canvas->cxSector = cdsector; canvas->cxChord = cdchord; canvas->cxText = cdtext; canvas->cxFLine = cdfline; canvas->cxFPoly = cdfpoly; canvas->cxFRect = cdfrect; canvas->cxFBox = cdfbox; canvas->cxFArc = cdfarc; canvas->cxFSector = cdfsector; canvas->cxFChord = cdfchord; canvas->cxNewRegion = cdnewregion; canvas->cxIsPointInRegion = cdispointinregion; canvas->cxOffsetRegion = cdoffsetregion; canvas->cxGetRegionBox = cdgetregionbox; canvas->cxGetFontDim = cdgetfontdim; canvas->cxGetTextSize = cdgettextsize; canvas->cxPutImageRectRGB = cdputimagerectrgb; canvas->cxPutImageRectMap = cdputimagerectmap; canvas->cxPutImageRectRGBA = cdputimagerectrgba; canvas->cxClip = cdclip; canvas->cxClipArea = cdcliparea; canvas->cxBackOpacity = cdbackopacity; canvas->cxLineStyle = cdlinestyle; canvas->cxLineWidth = cdlinewidth; canvas->cxLineCap = cdlinecap; canvas->cxLineJoin = cdlinejoin; canvas->cxInteriorStyle = cdinteriorstyle; canvas->cxHatch = cdhatch; canvas->cxStipple = cdstipple; canvas->cxPattern = cdpattern; canvas->cxFont = cdfont; canvas->cxNativeFont = cdnativefont; canvas->cxBackground = cdbackground; canvas->cxForeground = cdforeground; canvas->cxPalette = cdpalette; canvas->cxTransform = cdtransform; if (ctxcanvas->wtype == CDW_WIN || ctxcanvas->wtype == CDW_BMP) { canvas->cxClear = cdclear; canvas->cxGetImageRGB = cdgetimagergb; canvas->cxCreateImage = cdcreateimage; canvas->cxGetImage = cdgetimage; canvas->cxPutImageRect = cdputimagerect; canvas->cxKillImage = cdkillimage; canvas->cxScrollArea = cdscrollarea; } }
[ "sanikoyes@163.com" ]
sanikoyes@163.com
cea1b5755295983d0170618c60a830fb47b6c586
7a610bf0f786f25b35cf70e9f08ebfc8a95ce5c8
/FPSim2/src/include/utils.hpp
3c54330d974830841153d04ee844163a1a64d6a9
[ "MIT" ]
permissive
chembl/FPSim2
6aad8a1113ab8e721c35ef9cb74b26048a4da42e
814bbb5c3c609ecc8bb624b625a694c1d0723963
refs/heads/master
2023-07-23T21:07:39.914384
2023-06-26T21:56:35
2023-07-18T20:17:46
154,705,090
82
16
MIT
2023-07-18T20:17:48
2018-10-25T16:41:26
Python
UTF-8
C++
false
false
775
hpp
#pragma once #include <pybind11/numpy.h> #include <pybind11/pybind11.h> #include "result.hpp" namespace py = pybind11; namespace utils { uint64_t PyPopcount(const py::array_t<uint64_t> py_query); py::list BitStrToIntList(const std::string &bit_string); bool cmp(const Result &l, const Result &r); void SortResults(py::array_t<Result> py_res); // zero-copy C++ vector to NumPy array template<typename T> inline py::array_t<T> Vector2NumPy(std::vector<T> *vec) { // memory freed when the NumPy object is destroyed auto free_when_done = py::capsule(vec, [](void* ptr) { delete reinterpret_cast<std::vector<T> *>(ptr); }); return py::array_t<T>(vec->size(), vec->data(), free_when_done); } }
[ "noreply@github.com" ]
noreply@github.com
4e54f06692a8419749ade8a0ed8d6731f38b7b5e
dcdeb3d7233612c19db10eb24916d2fd2db45213
/src/Game.cc
ad5eb88ae45b61f0d35e957478c8682d512a0dad
[]
no_license
lordvlads77/sfml_Examen_Eva
f8826e18c46f73f19489adf41618605ed8b140de
249ed0d2907f8fdf0b015470b166a3958c093146
refs/heads/master
2023-08-15T07:41:07.301842
2021-09-15T15:54:11
2021-09-15T15:54:11
405,277,799
0
0
null
null
null
null
UTF-8
C++
false
false
20,263
cc
#include "Game.hh" #include "Constants.hh" #include "Rectangle.hh" Rectangle* rectangle{new Rectangle(20, 20, 415, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle1{new Rectangle(20, 20, 415, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle2{new Rectangle(20, 20, 415, 115, sf::Color(0, 6, 18))}; Rectangle* rectangle3{new Rectangle(20, 20, 415, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle4{new Rectangle(20, 20, 395, 115, sf::Color(0, 6, 18))}; Rectangle* rectangle5{new Rectangle(20, 20, 395, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle6{new Rectangle(20, 20, 455, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle7{new Rectangle(20, 20, 475, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle8{new Rectangle(20, 20, 495, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle9{new Rectangle(20, 20, 475, 115, sf::Color(0, 6, 18))}; Rectangle* rectangle10{new Rectangle(20, 20, 495, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle11{new Rectangle(20, 20, 515, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle12{new Rectangle(20, 20, 535, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle13{new Rectangle(20, 20, 555, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle14{new Rectangle(20, 20, 555, 115, sf::Color(1, 27, 50))}; Rectangle* rectangle15{new Rectangle(20, 20, 575, 115, sf::Color(0, 6, 18))}; Rectangle* rectangle16{new Rectangle(20, 20, 575, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle17{new Rectangle(20, 20, 535, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle18{new Rectangle(20, 20, 555, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle19{new Rectangle(20, 20, 575, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle20{new Rectangle(20, 20, 595, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle21{new Rectangle(20, 20, 615, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle22{new Rectangle(20, 20, 635, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle23{new Rectangle(20, 20, 655, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle24{new Rectangle(20, 20, 675, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle25{new Rectangle(20, 20, 695, 95, sf::Color(0, 109, 194))}; Rectangle* rectangle26{new Rectangle(20, 20, 695, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle27{new Rectangle(20, 20, 715, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle28{new Rectangle(20, 20, 735, 75, sf::Color(0, 6, 18))}; //Rectangle* rectangle29{new Rectangle(20, 20, 755, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle30{new Rectangle(20, 20, 775, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle31{new Rectangle(20, 20, 575, 95, sf::Color(0, 109, 194))}; Rectangle* rectangle32{new Rectangle(20, 20, 595, 95, sf::Color(0, 109, 194))}; Rectangle* rectangle33{new Rectangle(20, 20, 615, 95, sf::Color(0, 109, 194))}; Rectangle* rectangle34{new Rectangle(20, 20, 635, 95, sf::Color(0, 109, 194))}; Rectangle* rectangle35{new Rectangle(20, 20, 655, 95, sf::Color(0, 6, 18))}; Rectangle* rectangle36{new Rectangle(20, 20, 715, 95, sf::Color(0, 65, 137))}; Rectangle* rectangle37{new Rectangle(20, 20, 735, 95, sf::Color(0, 6, 18))}; //Rectangle* rectangle38{new Rectangle(20, 20, 755, 95, sf::Color(0, 65, 137))}; Rectangle* rectangle39{new Rectangle(20, 20, 495, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle40{new Rectangle(20, 20, 515, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle41{new Rectangle(20, 20, 535, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle42{new Rectangle(20, 20, 595, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle43{new Rectangle(20, 20, 615, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle44{new Rectangle(20, 20, 635, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle45{new Rectangle(20, 20, 655, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle46{new Rectangle(20, 20, 675, 115, sf::Color(1, 27, 50))}; Rectangle* rectangle47{new Rectangle(20, 20, 695, 115, sf::Color(0, 6, 18))}; Rectangle* rectangle48{new Rectangle(20, 20, 715, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle49{new Rectangle(20, 20, 735, 115, sf::Color(0, 65, 137))}; Rectangle* rectangle50{new Rectangle(20, 20, 755, 115, sf::Color(0, 6, 18))}; Rectangle* rectangle51{new Rectangle(20, 20, 775, 115, sf::Color(0, 109, 194))}; Rectangle* rectangle52{new Rectangle(20, 20, 795, 115, sf::Color(0, 6, 18))}; Rectangle* rectangle53{new Rectangle(20, 20, 675, 75, sf::Color(0, 6, 18))}; Rectangle* rectangle54{new Rectangle(20, 20, 515, 135, sf::Color(0, 109, 194))}; Rectangle* rectangle55{new Rectangle(20, 20, 535, 135, sf::Color(0, 109, 194))}; Rectangle* rectangle56{new Rectangle(20, 20, 555, 135, sf::Color(0, 109, 194))}; Rectangle* rectangle57{new Rectangle(20, 20, 595, 135, sf::Color(0, 109, 194))}; Rectangle* rectangle58{new Rectangle(20, 20, 615, 135, sf::Color(0, 109, 194))}; Rectangle* rectangle59{new Rectangle(20, 20, 635, 135, sf::Color(0, 65, 137))}; Rectangle* rectangle60{new Rectangle(20, 20, 655, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle61{new Rectangle(20, 20, 675, 135, sf::Color(0, 65, 137))}; Rectangle* rectangle62{new Rectangle(20, 20, 695, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle63{new Rectangle(20, 20, 715, 135, sf::Color(0, 65, 137))}; Rectangle* rectangle64{new Rectangle(20, 20, 735, 135, sf::Color(0, 65, 137))}; Rectangle* rectangle65{new Rectangle(20, 20, 755, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle66{new Rectangle(20, 20, 775, 135, sf::Color(0, 109, 194))}; Rectangle* rectangle67{new Rectangle(20, 20, 795, 135, sf::Color(0, 65, 137))}; Rectangle* rectangle68{new Rectangle(20, 20, 815, 135, sf::Color(0, 6, 18))}; Rectangle* rectangle69{new Rectangle(20, 20, 375, 155, sf::Color(0, 6, 18))}; Rectangle* rectangle70{new Rectangle(20, 20, 395, 155, sf::Color(194, 142, 0))}; Rectangle* rectangle71{new Rectangle(20, 20, 415, 155, sf::Color(194, 142, 0))}; Rectangle* rectangle72{new Rectangle(20, 20, 435, 155, sf::Color(0, 6, 18))}; Rectangle* rectangle73{new Rectangle(20, 20, 455, 155, sf::Color(0, 65, 137))}; Rectangle* rectangle74{new Rectangle(20, 20, 475, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle75{new Rectangle(20, 20, 495, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle76{new Rectangle(20, 20, 515, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle77{new Rectangle(20, 20, 535, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle78{new Rectangle(20, 20, 555, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle79{new Rectangle(20, 20, 575, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle80{new Rectangle(20, 20, 595, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle81{new Rectangle(20, 20, 615, 155, sf::Color(0, 65, 137))}; Rectangle* rectangle82{new Rectangle(20, 20, 635, 155, sf::Color(0, 6, 18))}; Rectangle* rectangle83{new Rectangle(20, 20, 655, 155, sf::Color(245, 192, 0))}; Rectangle* rectangle84{new Rectangle(20, 20, 675, 155, sf::Color(0, 6, 18))}; Rectangle* rectangle85{new Rectangle(20, 20, 695, 155, sf::Color(0, 65, 137))}; Rectangle* rectangle86{new Rectangle(20, 20, 715, 155, sf::Color(0, 65, 137))}; Rectangle* rectangle87{new Rectangle(20, 20, 735, 155, sf::Color(0, 6, 18))}; Rectangle* rectangle88{new Rectangle(20, 20, 755, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle89{new Rectangle(20, 20, 775, 155, sf::Color(0, 109, 194))}; Rectangle* rectangle90{new Rectangle(20, 20, 795, 155, sf::Color(0, 65, 137))}; Rectangle* rectangle91{new Rectangle(20, 20, 815, 155, sf::Color(0, 6, 18))}; Rectangle* rectangle92{new Rectangle(20, 20, 375, 175, sf::Color(0, 6, 18))}; Rectangle* rectangle93{new Rectangle(20, 20, 395, 175, sf::Color(245, 192, 0))}; Rectangle* rectangle94{new Rectangle(20, 20, 415, 175, sf::Color(194, 142, 0))}; Rectangle* rectangle95{new Rectangle(20, 20, 435, 175, sf::Color(0, 6, 18))}; Rectangle* rectangle96{new Rectangle(20, 20, 455, 175, sf::Color(1, 27, 50))}; Rectangle* rectangle97{new Rectangle(20, 20, 475, 175, sf::Color(0, 65, 137))}; Rectangle* rectangle98{new Rectangle(20, 20, 495, 175, sf::Color(0, 109, 194))}; Rectangle* rectangle99{new Rectangle(20, 20, 515, 175, sf::Color(0, 109, 194))}; Rectangle* rectangle100{new Rectangle(20, 20, 535, 175, sf::Color(0, 109, 194))}; Rectangle* rectangle101{new Rectangle(20, 20, 555, 175, sf::Color(0, 109, 194))}; Rectangle* rectangle102{new Rectangle(20, 20, 575, 175, sf::Color(0, 109, 194))}; Rectangle* rectangle103{new Rectangle(20, 20, 595, 175, sf::Color(0, 65, 137))}; Rectangle* rectangle104{new Rectangle(20, 20, 615, 175, sf::Color(0, 6, 18))}; Rectangle* rectangle105{new Rectangle(20, 20, 635, 175, sf::Color(245, 192, 0))}; Rectangle* rectangle106{new Rectangle(20, 20, 655, 175, sf::Color(245, 192, 0))}; Rectangle* rectangle107{new Rectangle(20, 20, 675, 175, sf::Color(245, 192, 0))}; Rectangle* rectangle108{new Rectangle(20, 20, 695, 175, sf::Color(0, 6, 18))}; Rectangle* rectangle109{new Rectangle(20, 20, 715, 175, sf::Color(0, 65, 137))}; Rectangle* rectangle110{new Rectangle(20, 20, 735, 175, sf::Color(0, 109, 194))}; Rectangle* rectangle111{new Rectangle(20, 20, 755, 175, sf::Color(0, 109, 194))}; Rectangle* rectangle112{new Rectangle(20, 20, 795, 175, sf::Color(1, 27, 50))}; Rectangle* rectangle113{new Rectangle(20, 20, 815, 175, sf::Color(0, 6, 18))}; Rectangle* rectangle114{new Rectangle(20, 20, 775, 175, sf::Color(0, 65, 137))}; Rectangle* rectangle115{new Rectangle(20, 20, 375, 195, sf::Color(1, 6, 18))}; Rectangle* rectangle116{new Rectangle(20, 20, 395, 195, sf::Color(245, 192, 0))}; Rectangle* rectangle117{new Rectangle(20, 20, 415, 195, sf::Color(245, 192, 0))}; Rectangle* rectangle118{new Rectangle(20, 20, 435, 195, sf::Color(194, 142, 0))}; Rectangle* rectangle119{new Rectangle(20, 20, 455, 195, sf::Color(1, 6, 18))}; Rectangle* rectangle120{new Rectangle(20, 20, 475, 195, sf::Color(1, 27, 50))}; Rectangle* rectangle121{new Rectangle(20, 20, 495, 195, sf::Color(0, 65, 137))}; Rectangle* rectangle122{new Rectangle(20, 20, 515, 195, sf::Color(0, 109, 194))}; Rectangle* rectangle123{new Rectangle(20, 20, 535, 195, sf::Color(0, 109, 194))}; Rectangle* rectangle124{new Rectangle(20, 20, 555, 195, sf::Color(0, 65, 137))}; Rectangle* rectangle125{new Rectangle(20, 20, 575, 195, sf::Color(1, 6, 18))}; Rectangle* rectangle126{new Rectangle(20, 20, 595, 195, sf::Color(1, 6, 18))}; Rectangle* rectangle127{new Rectangle(20, 20, 615, 195, sf::Color(245, 192, 0))}; Rectangle* rectangle128{new Rectangle(20, 20, 635, 195, sf::Color(245, 192, 0))}; Rectangle* rectangle129{new Rectangle(20, 20, 655, 195, sf::Color(15, 0, 81))}; Rectangle* rectangle130{new Rectangle(20, 20, 675, 195, sf::Color(245, 192, 0))}; Rectangle* rectangle131{new Rectangle(20, 20, 695, 195, sf::Color(194, 142, 0))}; Rectangle* rectangle132{new Rectangle(20, 20, 715, 195, sf::Color(0, 6, 18))}; Rectangle* rectangle133{new Rectangle(20, 20, 735, 195, sf::Color(0, 65, 137))}; Rectangle* rectangle134{new Rectangle(20, 20, 755, 195, sf::Color(0, 65, 137))}; Rectangle* rectangle135{new Rectangle(20, 20, 775, 195, sf::Color(1, 27, 50))}; Rectangle* rectangle136{new Rectangle(20, 20, 795, 195, sf::Color(0, 6, 18))}; Rectangle* rectangle137{new Rectangle(20, 20, 375, 215, sf::Color(0, 6, 18))}; Rectangle* rectangle138{new Rectangle(20, 20, 395, 215, sf::Color(245, 192, 0))}; Rectangle* rectangle139{new Rectangle(20, 20, 415, 215, sf::Color(245, 192, 0))}; Rectangle* rectangle140{new Rectangle(20, 20, 435, 215, sf::Color(245, 192, 0))}; Rectangle* rectangle141{new Rectangle(20, 20, 455, 215, sf::Color(194, 142, 0))}; Rectangle* rectangle142{new Rectangle(20, 20, 475, 215, sf::Color(0, 6, 18))}; Rectangle* rectangle143{new Rectangle(20, 20, 495, 215, sf::Color(1, 27, 50))}; Rectangle* rectangle144{new Rectangle(20, 20, 515, 215, sf::Color(1, 27, 50))}; Rectangle* rectangle145{new Rectangle(20, 20, 535, 215, sf::Color(0, 6, 18))}; Rectangle* rectangle146{new Rectangle(20, 20, 555, 215, sf::Color(0, 6, 18))}; Rectangle* rectangle147{new Rectangle(20, 20, 575, 215, sf::Color(245, 192, 0))}; Rectangle* rectangle148{new Rectangle(20, 20, 595, 215, sf::Color(245, 192, 0))}; Rectangle* rectangle149{new Rectangle(20, 20, 615, 215, sf::Color(245, 192, 0))}; /*Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))}; Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))}; Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))}; Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))}; Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))}; Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))}; Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))}; Rectangle* rectangle114{new Rectangle(20, 20, 835, 17, sf::Color(194, 142, 0))};*/ Game::Game(/* args */) { window = new sf::RenderWindow(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT),GAME_NAME); event = new sf::Event(); } Game::~Game() { } //Starting things void Game::Start() { } void Game::Initialize() { Start(); MainLoop(); } //Logic, animations, etc void Game::Update() { } void Game::MainLoop() { while (window->isOpen()) { //Request for closing the window while(window->pollEvent(*event)) { if(event->type == sf::Event::Closed) { window->close(); } } Input(); Update(); Render(); } Destroy(); } void Game::Render() { window->clear(sf::Color(31, 37, 49)); Draw(); window->display(); } //Drawing sprites or geometry. void Game::Draw() { window->draw(*rectangle->GetShape()); window->draw(*rectangle1->GetShape()); window->draw(*rectangle2->GetShape()); window->draw(*rectangle3->GetShape()); window->draw(*rectangle4->GetShape()); window->draw(*rectangle5->GetShape()); window->draw(*rectangle6->GetShape()); window->draw(*rectangle7->GetShape()); window->draw(*rectangle8->GetShape()); window->draw(*rectangle9->GetShape()); window->draw(*rectangle10->GetShape()); window->draw(*rectangle11->GetShape()); window->draw(*rectangle12->GetShape()); window->draw(*rectangle13->GetShape()); window->draw(*rectangle14->GetShape()); window->draw(*rectangle15->GetShape()); window->draw(*rectangle16->GetShape()); window->draw(*rectangle17->GetShape()); window->draw(*rectangle18->GetShape()); window->draw(*rectangle19->GetShape()); window->draw(*rectangle20->GetShape()); window->draw(*rectangle21->GetShape()); window->draw(*rectangle22->GetShape()); //window->draw(*rectangle23->GetShape()); window->draw(*rectangle24->GetShape()); window->draw(*rectangle25->GetShape()); window->draw(*rectangle26->GetShape()); window->draw(*rectangle27->GetShape()); //window->draw(*rectangle28->GetShape()); //window->draw(*rectangle29->GetShape()); window->draw(*rectangle30->GetShape()); window->draw(*rectangle31->GetShape()); window->draw(*rectangle32->GetShape()); window->draw(*rectangle33->GetShape()); window->draw(*rectangle34->GetShape()); window->draw(*rectangle35->GetShape()); window->draw(*rectangle36->GetShape()); window->draw(*rectangle37->GetShape()); //window->draw(*rectangle38->GetShape()); window->draw(*rectangle39->GetShape()); window->draw(*rectangle40->GetShape()); window->draw(*rectangle41->GetShape()); window->draw(*rectangle42->GetShape()); window->draw(*rectangle43->GetShape()); window->draw(*rectangle44->GetShape()); window->draw(*rectangle45->GetShape()); window->draw(*rectangle46->GetShape()); window->draw(*rectangle47->GetShape()); window->draw(*rectangle48->GetShape()); window->draw(*rectangle49->GetShape()); window->draw(*rectangle50->GetShape()); window->draw(*rectangle51->GetShape()); window->draw(*rectangle52->GetShape()); window->draw(*rectangle53->GetShape()); window->draw(*rectangle54->GetShape()); window->draw(*rectangle55->GetShape()); window->draw(*rectangle56->GetShape()); window->draw(*rectangle57->GetShape()); window->draw(*rectangle58->GetShape()); window->draw(*rectangle59->GetShape()); window->draw(*rectangle60->GetShape()); window->draw(*rectangle61->GetShape()); window->draw(*rectangle62->GetShape()); window->draw(*rectangle63->GetShape()); window->draw(*rectangle64->GetShape()); window->draw(*rectangle65->GetShape()); window->draw(*rectangle66->GetShape()); window->draw(*rectangle67->GetShape()); window->draw(*rectangle68->GetShape()); window->draw(*rectangle69->GetShape()); window->draw(*rectangle70->GetShape()); window->draw(*rectangle71->GetShape()); window->draw(*rectangle72->GetShape()); window->draw(*rectangle73->GetShape()); window->draw(*rectangle74->GetShape()); window->draw(*rectangle75->GetShape()); window->draw(*rectangle76->GetShape()); window->draw(*rectangle77->GetShape()); window->draw(*rectangle78->GetShape()); window->draw(*rectangle79->GetShape()); window->draw(*rectangle80->GetShape()); window->draw(*rectangle81->GetShape()); window->draw(*rectangle82->GetShape()); window->draw(*rectangle83->GetShape()); window->draw(*rectangle84->GetShape()); window->draw(*rectangle85->GetShape()); window->draw(*rectangle86->GetShape()); window->draw(*rectangle87->GetShape()); window->draw(*rectangle88->GetShape()); window->draw(*rectangle89->GetShape()); window->draw(*rectangle90->GetShape()); window->draw(*rectangle91->GetShape()); window->draw(*rectangle92->GetShape()); window->draw(*rectangle93->GetShape()); window->draw(*rectangle94->GetShape()); window->draw(*rectangle95->GetShape()); window->draw(*rectangle96->GetShape()); window->draw(*rectangle97->GetShape()); window->draw(*rectangle98->GetShape()); window->draw(*rectangle99->GetShape()); window->draw(*rectangle100->GetShape()); window->draw(*rectangle101->GetShape()); window->draw(*rectangle102->GetShape()); window->draw(*rectangle103->GetShape()); window->draw(*rectangle104->GetShape()); window->draw(*rectangle105->GetShape()); window->draw(*rectangle106->GetShape()); window->draw(*rectangle107->GetShape()); window->draw(*rectangle108->GetShape()); window->draw(*rectangle109->GetShape()); window->draw(*rectangle110->GetShape()); window->draw(*rectangle111->GetShape()); window->draw(*rectangle112->GetShape()); window->draw(*rectangle113->GetShape()); window->draw(*rectangle114->GetShape()); window->draw(*rectangle115->GetShape()); window->draw(*rectangle116->GetShape()); window->draw(*rectangle117->GetShape()); window->draw(*rectangle118->GetShape()); window->draw(*rectangle119->GetShape()); window->draw(*rectangle120->GetShape()); window->draw(*rectangle121->GetShape()); window->draw(*rectangle122->GetShape()); window->draw(*rectangle123->GetShape()); window->draw(*rectangle124->GetShape()); window->draw(*rectangle125->GetShape()); window->draw(*rectangle126->GetShape()); window->draw(*rectangle127->GetShape()); window->draw(*rectangle128->GetShape()); window->draw(*rectangle129->GetShape()); window->draw(*rectangle130->GetShape()); window->draw(*rectangle131->GetShape()); window->draw(*rectangle132->GetShape()); window->draw(*rectangle133->GetShape()); window->draw(*rectangle134->GetShape()); window->draw(*rectangle135->GetShape()); window->draw(*rectangle136->GetShape()); window->draw(*rectangle137->GetShape()); window->draw(*rectangle138->GetShape()); window->draw(*rectangle139->GetShape()); window->draw(*rectangle140->GetShape()); window->draw(*rectangle141->GetShape()); window->draw(*rectangle142->GetShape()); window->draw(*rectangle143->GetShape()); window->draw(*rectangle144->GetShape()); window->draw(*rectangle145->GetShape()); window->draw(*rectangle146->GetShape()); window->draw(*rectangle147->GetShape()); window->draw(*rectangle148->GetShape()); window->draw(*rectangle149->GetShape()); } //Keyboard, joysticks, etc. void Game::Input() { } void Game::Destroy() { delete window; delete event; }
[ "81182279+lordvlads77@users.noreply.github.com" ]
81182279+lordvlads77@users.noreply.github.com
f0eb3b0a068a5eeab00454a282d6c0d01b83c3e4
9cd376a388eb6a812a8c86340256d92149fc72eb
/ABI/third_party/android-emugl/host/libs/Translator/EGL/EglDisplay.cpp
abd29f712ac153ae6a601d2ee6f4b2dc01b14c14
[]
no_license
frankKiwi/aid
f290372b031d797cad32264a55110096a777aaf5
0207d6101b349cb338e982b4b22ed25dae27dda1
refs/heads/master
2023-08-04T12:40:35.996158
2021-09-17T06:24:04
2021-09-17T06:24:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,658
cpp
/* * Copyright (C) 2011 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 "EglDisplay.h" #include "android/base/containers/Lookup.h" #include "android/base/files/StreamSerializing.h" #include "EglConfig.h" #include "EglOsApi.h" #include <GLcommon/GLutils.h> #include <algorithm> EglDisplay::EglDisplay(EGLNativeDisplayType dpy, EglOS::Display* idpy) : m_dpy(dpy), m_idpy(idpy) { m_manager[GLES_1_1] = new ObjectNameManager(&m_globalNameSpace); m_manager[GLES_2_0] = new ObjectNameManager(&m_globalNameSpace); m_manager[GLES_3_0] = m_manager[GLES_2_0]; m_manager[GLES_3_1] = m_manager[GLES_2_0]; }; EglDisplay::~EglDisplay() { emugl::Mutex::AutoLock mutex(m_lock); // // Destroy the global context if one was created. // (should be true for windows platform only) // if (m_globalSharedContext != NULL) { m_idpy->destroyContext(m_globalSharedContext); } m_configs.clear(); delete m_manager[GLES_1_1]; delete m_manager[GLES_2_0]; delete m_idpy; } void EglDisplay::initialize(int renderableType) { emugl::Mutex::AutoLock mutex(m_lock); m_initialized = true; initConfigurations(renderableType); m_configInitialized = true; } bool EglDisplay::isInitialize() { return m_initialized;} void EglDisplay::terminate(){ emugl::Mutex::AutoLock mutex(m_lock); m_contexts.clear(); m_surfaces.clear(); m_initialized = false; } namespace CompareEglConfigs { // Old compare function used to initialize to something decently sorted. struct StaticCompare { bool operator()(const std::unique_ptr<EglConfig>& first, const std::unique_ptr<EglConfig>& second) const { return *first < *second; } }; // In actual usage, we need to dynamically re-sort configs // that are returned to the user. struct DynamicCompare; // This is because the sorting order of configs is affected // based on dynamic properties. // // See https://www.khronos.org/registry/egl/sdk/docs/man/html/eglChooseConfig.xhtml // and the section on config sorting. // // If the user requests an EGL config with a particular EGL_RED_SIZE, // for example, we must sort configs based on that criteria, while if that // was not specified, we would just skip right on to sorting by buffer size. // Below is an implementation of EGL config sorting according // to spec, that takes the dynamic properties into account. static int ColorBufferTypeVal(EGLenum type) { switch (type) { case EGL_RGB_BUFFER: return 0; case EGL_LUMINANCE_BUFFER: return 1; case EGL_YUV_BUFFER_EXT: return 2; } return 3; } static bool nonTrivialAttribVal(EGLint val) { return val != 0 && val != EGL_DONT_CARE; } struct DynamicCompare { public: DynamicCompare(const EglConfig& wantedAttribs) { EGLint wantedRVal = wantedAttribs.getConfAttrib(EGL_RED_SIZE); EGLint wantedGVal = wantedAttribs.getConfAttrib(EGL_GREEN_SIZE); EGLint wantedBVal = wantedAttribs.getConfAttrib(EGL_BLUE_SIZE); EGLint wantedLVal = wantedAttribs.getConfAttrib(EGL_LUMINANCE_SIZE); EGLint wantedAVal = wantedAttribs.getConfAttrib(EGL_ALPHA_SIZE); wantedR = wantedAttribs.isWantedAttrib(EGL_RED_SIZE) && nonTrivialAttribVal(wantedRVal); wantedG = wantedAttribs.isWantedAttrib(EGL_GREEN_SIZE) && nonTrivialAttribVal(wantedGVal); wantedB = wantedAttribs.isWantedAttrib(EGL_BLUE_SIZE) && nonTrivialAttribVal(wantedBVal); wantedL = wantedAttribs.isWantedAttrib(EGL_LUMINANCE_SIZE) && nonTrivialAttribVal(wantedLVal); wantedA = wantedAttribs.isWantedAttrib(EGL_ALPHA_SIZE) && nonTrivialAttribVal(wantedAVal); } bool operator()(EglConfig* a, EglConfig* b) const { EGLint aConformant = a->getConfAttrib(EGL_CONFORMANT); EGLint bConformant = b->getConfAttrib(EGL_CONFORMANT); if (aConformant != bConformant) { return aConformant != 0; } EGLint aCaveat = a->getConfAttrib(EGL_CONFIG_CAVEAT); EGLint bCaveat = b->getConfAttrib(EGL_CONFIG_CAVEAT); if (aCaveat != bCaveat) { return aCaveat < bCaveat; } EGLint aCbType = a->getConfAttrib(EGL_COLOR_BUFFER_TYPE); EGLint bCbType = b->getConfAttrib(EGL_COLOR_BUFFER_TYPE); if (aCbType != bCbType) { return ColorBufferTypeVal(aCbType) < ColorBufferTypeVal(bCbType); } EGLint aCbSize = 0; EGLint bCbSize = 0; if (wantedR) { aCbSize += a->getConfAttrib(EGL_RED_SIZE); bCbSize += b->getConfAttrib(EGL_RED_SIZE); } if (wantedG) { aCbSize += a->getConfAttrib(EGL_GREEN_SIZE); bCbSize += b->getConfAttrib(EGL_GREEN_SIZE); } if (wantedB) { aCbSize += a->getConfAttrib(EGL_BLUE_SIZE); bCbSize += b->getConfAttrib(EGL_BLUE_SIZE); } if (wantedL) { aCbSize += a->getConfAttrib(EGL_LUMINANCE_SIZE); bCbSize += b->getConfAttrib(EGL_LUMINANCE_SIZE); } if (wantedA) { aCbSize += a->getConfAttrib(EGL_ALPHA_SIZE); bCbSize += b->getConfAttrib(EGL_ALPHA_SIZE); } if (aCbSize != bCbSize) { return aCbSize > bCbSize; } EGLint aBufferSize = a->getConfAttrib(EGL_BUFFER_SIZE); EGLint bBufferSize = b->getConfAttrib(EGL_BUFFER_SIZE); if (aBufferSize != bBufferSize) { return aBufferSize < bBufferSize; } EGLint aSampleBuffersNum = a->getConfAttrib(EGL_SAMPLE_BUFFERS); EGLint bSampleBuffersNum = b->getConfAttrib(EGL_SAMPLE_BUFFERS); if (aSampleBuffersNum != bSampleBuffersNum) { return aSampleBuffersNum < bSampleBuffersNum; } EGLint aSPP = a->getConfAttrib(EGL_SAMPLES); EGLint bSPP = b->getConfAttrib(EGL_SAMPLES); if (aSPP != bSPP) { return aSPP < bSPP; } EGLint aDepthSize = a->getConfAttrib(EGL_DEPTH_SIZE); EGLint bDepthSize = b->getConfAttrib(EGL_DEPTH_SIZE); if (aDepthSize != bDepthSize) { return aDepthSize < bDepthSize; } EGLint aStencilSize = a->getConfAttrib(EGL_STENCIL_SIZE); EGLint bStencilSize = b->getConfAttrib(EGL_STENCIL_SIZE); if (aStencilSize != bStencilSize) { return aStencilSize < bStencilSize; } return a->getConfAttrib(EGL_CONFIG_ID) < b->getConfAttrib(EGL_CONFIG_ID); } bool wantedR; bool wantedG; bool wantedB; bool wantedL; bool wantedA; }; } void EglDisplay::addSimplePixelFormat(int red_size, int green_size, int blue_size, int alpha_size) { std::sort(m_configs.begin(), m_configs.end(), CompareEglConfigs::StaticCompare()); EGLConfig match; EglConfig dummy(red_size, green_size, blue_size, alpha_size, // RGB_565 EGL_DONT_CARE, EGL_DONT_CARE, 16, // Depth EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, EGL_DONT_CARE, NULL); if(!doChooseConfigs(dummy, &match, 1)) { return; } const EglConfig* config = (EglConfig*)match; int bSize; config->getConfAttrib(EGL_BUFFER_SIZE,&bSize); if(bSize == 16) { return; } int max_config_id = 0; for(ConfigsList::iterator it = m_configs.begin(); it != m_configs.end() ;++it) { EGLint id; (*it)->getConfAttrib(EGL_CONFIG_ID, &id); if(id > max_config_id) max_config_id = id; } std::unique_ptr<EglConfig> newConfig( new EglConfig(*config,max_config_id+1, red_size, green_size, blue_size, alpha_size)); if (m_uniqueConfigs.insert(*newConfig).second) { m_configs.emplace_back(newConfig.release()); } } void EglDisplay::addMissingConfigs() { addSimplePixelFormat(5, 6, 5, 0); // RGB_565 addSimplePixelFormat(8, 8, 8, 0); // RGB_888 // (Host GPUs that are newer may not list RGB_888 // out of the box.) } void EglDisplay::initConfigurations(int renderableType) { if (m_configInitialized) { return; } m_idpy->queryConfigs(renderableType, addConfig, this); addMissingConfigs(); std::sort(m_configs.begin(), m_configs.end(), CompareEglConfigs::StaticCompare()); #if EMUGL_DEBUG for (ConfigsList::const_iterator it = m_configs.begin(); it != m_configs.end(); ++it) { EglConfig* config = it->get(); EGLint red, green, blue, alpha, depth, stencil, renderable, surface; config->getConfAttrib(EGL_RED_SIZE, &red); config->getConfAttrib(EGL_GREEN_SIZE, &green); config->getConfAttrib(EGL_BLUE_SIZE, &blue); config->getConfAttrib(EGL_ALPHA_SIZE, &alpha); config->getConfAttrib(EGL_DEPTH_SIZE, &depth); config->getConfAttrib(EGL_STENCIL_SIZE, &stencil); config->getConfAttrib(EGL_RENDERABLE_TYPE, &renderable); config->getConfAttrib(EGL_SURFACE_TYPE, &surface); } #endif // EMUGL_DEBUG } EglConfig* EglDisplay::getConfig(EGLConfig conf) const { emugl::Mutex::AutoLock mutex(m_lock); for(ConfigsList::const_iterator it = m_configs.begin(); it != m_configs.end(); ++it) { if(static_cast<EGLConfig>(it->get()) == conf) { return it->get(); } } return NULL; } SurfacePtr EglDisplay::getSurface(EGLSurface surface) const { emugl::Mutex::AutoLock mutex(m_lock); /* surface is "key" in map<unsigned int, SurfacePtr>. */ unsigned int hndl = SafeUIntFromPointer(surface); SurfacesHndlMap::const_iterator it = m_surfaces.find(hndl); return it != m_surfaces.end() ? (*it).second : SurfacePtr(); } ContextPtr EglDisplay::getContext(EGLContext ctx) const { emugl::Mutex::AutoLock mutex(m_lock); /* ctx is "key" in map<unsigned int, ContextPtr>. */ unsigned int hndl = SafeUIntFromPointer(ctx); ContextsHndlMap::const_iterator it = m_contexts.find(hndl); return it != m_contexts.end() ? (*it).second : ContextPtr(); } bool EglDisplay::removeSurface(EGLSurface s) { emugl::Mutex::AutoLock mutex(m_lock); /* s is "key" in map<unsigned int, SurfacePtr>. */ unsigned int hndl = SafeUIntFromPointer(s); SurfacesHndlMap::iterator it = m_surfaces.find(hndl); if(it != m_surfaces.end()) { m_surfaces.erase(it); return true; } return false; } bool EglDisplay::removeContext(EGLContext ctx) { emugl::Mutex::AutoLock mutex(m_lock); /* ctx is "key" in map<unsigned int, ContextPtr>. */ unsigned int hndl = SafeUIntFromPointer(ctx); ContextsHndlMap::iterator it = m_contexts.find(hndl); if(it != m_contexts.end()) { m_contexts.erase(it); return true; } return false; } bool EglDisplay::removeContext(ContextPtr ctx) { emugl::Mutex::AutoLock mutex(m_lock); ContextsHndlMap::iterator it; for(it = m_contexts.begin(); it != m_contexts.end();++it) { if((*it).second.get() == ctx.get()){ break; } } if(it != m_contexts.end()) { m_contexts.erase(it); return true; } return false; } EglConfig* EglDisplay::getConfig(EGLint id) const { emugl::Mutex::AutoLock mutex(m_lock); for(ConfigsList::const_iterator it = m_configs.begin(); it != m_configs.end(); ++it) { if((*it)->id() == id) { return it->get(); } } return NULL; } int EglDisplay::getConfigs(EGLConfig* configs,int config_size) const { emugl::Mutex::AutoLock mutex(m_lock); int i = 0; for(ConfigsList::const_iterator it = m_configs.begin(); it != m_configs.end() && i < config_size; i++, ++it) { configs[i] = static_cast<EGLConfig>(it->get()); } return i; } int EglDisplay::chooseConfigs(const EglConfig& dummy, EGLConfig* configs, int config_size) const { emugl::Mutex::AutoLock mutex(m_lock); return doChooseConfigs(dummy, configs, config_size); } int EglDisplay::doChooseConfigs(const EglConfig& dummy, EGLConfig* configs, int config_size) const { int added = 0; std::vector<EglConfig*> validConfigs; CHOOSE_CONFIG_DLOG("returning configs. ids: {"); for(ConfigsList::const_iterator it = m_configs.begin(); it != m_configs.end() && (added < config_size || !configs); ++it) { if( (*it)->chosen(dummy)){ if(configs) { CHOOSE_CONFIG_DLOG("valid config: id=0x%x", it->get()->id()); validConfigs.push_back(it->get()); } added++; } } CHOOSE_CONFIG_DLOG("sorting valid configs..."); std::sort(validConfigs.begin(), validConfigs.end(), CompareEglConfigs::DynamicCompare(dummy)); for (int i = 0; i < added; i++) { configs[i] = static_cast<EGLConfig>(validConfigs[i]); } CHOOSE_CONFIG_DLOG("returning configs. ids end }"); return added; } EGLSurface EglDisplay::addSurface(SurfacePtr s ) { emugl::Mutex::AutoLock mutex(m_lock); unsigned int hndl = s.get()->getHndl(); EGLSurface ret =reinterpret_cast<EGLSurface> (hndl); if(m_surfaces.find(hndl) != m_surfaces.end()) { return ret; } m_surfaces[hndl] = s; return ret; } EGLContext EglDisplay::addContext(ContextPtr ctx ) { emugl::Mutex::AutoLock mutex(m_lock); unsigned int hndl = ctx.get()->getHndl(); EGLContext ret = reinterpret_cast<EGLContext> (hndl); if(m_contexts.find(hndl) != m_contexts.end()) { return ret; } m_contexts[hndl] = ctx; return ret; } EGLImageKHR EglDisplay::addImageKHR(ImagePtr img) { emugl::Mutex::AutoLock mutex(m_lock); do { ++m_nextEglImageId; } while(m_nextEglImageId == 0 || android::base::contains(m_eglImages, m_nextEglImageId)); img->imageId = m_nextEglImageId; m_eglImages[m_nextEglImageId] = img; return reinterpret_cast<EGLImageKHR>(m_nextEglImageId); } ImagePtr EglDisplay::getImage(EGLImageKHR img) const { emugl::Mutex::AutoLock mutex(m_lock); /* img is "key" in map<unsigned int, ImagePtr>. */ unsigned int hndl = SafeUIntFromPointer(img); ImagesHndlMap::const_iterator i( m_eglImages.find(hndl) ); return (i != m_eglImages.end()) ? (*i).second :ImagePtr(); } bool EglDisplay:: destroyImageKHR(EGLImageKHR img) { emugl::Mutex::AutoLock mutex(m_lock); /* img is "key" in map<unsigned int, ImagePtr>. */ unsigned int hndl = SafeUIntFromPointer(img); ImagesHndlMap::iterator i( m_eglImages.find(hndl) ); if (i != m_eglImages.end()) { m_eglImages.erase(i); return true; } return false; } EglOS::Context* EglDisplay::getGlobalSharedContext() const { emugl::Mutex::AutoLock mutex(m_lock); #ifndef _WIN32 // find an existing OpenGL context to share with, if exist EglOS::Context* ret = (EglOS::Context*)m_manager[GLES_1_1]->getGlobalContext(); if (!ret) ret = (EglOS::Context*)m_manager[GLES_2_0]->getGlobalContext(); return ret; #else if (!m_globalSharedContext) { // // On windows we create a dummy context to serve as the // "global context" which all contexts share with. // This is because on windows it is not possible to share // with a context which is already current. This dummy context // will never be current to any thread so it is safe to share with. // Create that context using the first config if (m_configs.empty()) { // Should not happen! config list should be initialized at this point return NULL; } EglConfig *cfg = m_configs.front().get(); m_globalSharedContext = m_idpy->createContext( cfg->nativeFormat(), NULL); } return m_globalSharedContext; #endif } // static void EglDisplay::addConfig(void* opaque, const EglOS::ConfigInfo* info) { EglDisplay* display = static_cast<EglDisplay*>(opaque); // Greater than 24 bits of color, // or having no depth/stencil causes some // unexpected behavior in real usage, such // as frame corruption and wrong drawing order. // Also, disallow high MSAA. // Just don't use those configs. if (info->red_size > 8 || info->green_size > 8 || info->blue_size > 8 || info->depth_size < 24 || info->stencil_size < 8 || info->samples_per_pixel > 4) { return; } std::unique_ptr<EglConfig> config(new EglConfig( info->red_size, info->green_size, info->blue_size, info->alpha_size, info->caveat, info->config_id, info->depth_size, info->frame_buffer_level, info->max_pbuffer_width, info->max_pbuffer_height, info->max_pbuffer_size, info->native_renderable, info->renderable_type, info->native_visual_id, info->native_visual_type, info->samples_per_pixel, info->stencil_size, info->surface_type, info->transparent_type, info->trans_red_val, info->trans_green_val, info->trans_blue_val, info->recordable_android, info->frmt)); if (display->m_uniqueConfigs.insert(*config).second) { display->m_configs.emplace_back(config.release()); } } void EglDisplay::onSaveAllImages(android::base::Stream* stream, SaveableTexture::saver_t saver) { // we could consider calling presave for all ShareGroups from here // but it would introduce overheads because not all share groups need to be // saved emugl::Mutex::AutoLock mutex(m_lock); for (const auto& image : m_eglImages) { getGlobalNameSpace()->preSaveAddEglImage(image.second.get()); } m_globalNameSpace.onSave(stream, saver); saveCollection(stream, m_eglImages, []( android::base::Stream* stream, const ImagesHndlMap::value_type& img) { stream->putBe32(img.first); stream->putBe32(img.second->globalTexObj->getGlobalName()); // We do not need to save other fields in EglImage. We can load them // from SaveableTexture. }); } void EglDisplay::onLoadAllImages(android::base::Stream* stream, SaveableTexture::loader_t loader) { if (!m_eglImages.empty()) { // Could be triggered by this bug: // b/36654917 fprintf(stderr, "Warning: unreleased EGL image handles\n"); } m_eglImages.clear(); emugl::Mutex::AutoLock mutex(m_lock); m_globalNameSpace.onLoad(stream, loader); loadCollection(stream, &m_eglImages, [this]( android::base::Stream* stream) { unsigned int hndl = stream->getBe32(); unsigned int globalName = stream->getBe32(); ImagePtr eglImg(m_globalNameSpace.makeEglImageFromLoad(globalName)); eglImg->imageId = hndl; return std::make_pair(hndl, std::move(eglImg)); }); } void EglDisplay::postLoadAllImages(android::base::Stream* stream) { m_globalNameSpace.postLoad(stream); }
[ "voquanghoa@gmail.com" ]
voquanghoa@gmail.com
4927ea532a8e29d0f318cbee8e5097c1d94f7fcb
751251a0dbb68dc3e8e117c1d4d128cc5ac6d2e9
/HPC_HW1/hw1/HPC_hw1.cpp
d9f02beb5b9431f6394c62deb440014c59361e95
[]
no_license
23sanj/High-Performance-Computing-Assignments
de1db1da6adb7fbbcd66207c2c244e9b40cea76d
16f87e400191fc18c0be4f34067f1eabaf2d2697
refs/heads/master
2020-05-22T10:29:51.935801
2017-03-12T01:34:26
2017-03-12T01:34:26
84,691,509
0
0
null
null
null
null
UTF-8
C++
false
false
744
cpp
%..................HPC ASSIGNMENT-1, PROBLEM 1......................% // dgemm0 #include <iostream> using namespace std { /* data */ }; void MatrixMul(int n) { // generate random matrices int A[3][2] = {{1, 4}, {2, 5}, {3, 6}}; int B[2][3] = {{7, 8, 9}, {10, 11, 12}}; int C[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; // start timer for (i=0; i<n; i++) { for (j=0; j<n; j++) { for (k=0; k<n; k++) { A[i*n+j] += B[i*n+k] * C[k*n+j];} } } //end timer cout << product[row][col] << " "; } cout << "\n"<< timer; } } void main() { cout<<"enter the matrix size"; cin>>int n ; Matrix mul(n); getchar(); }
[ "ssand024@codenames.cs.ucr.edu" ]
ssand024@codenames.cs.ucr.edu
49c140f65d05a6e4e764cfda4fdf6366bb344bdd
8e317fcdd3e39ba3702bfca8938592bfb39c3a5b
/SingleCharacterSeparater.cpp
d9397abc481734b2ccdf5227b178c1d4a668f5ae
[]
no_license
PolarLion/CPP-TextClassifer
9223abbad4cd49b2aa2f257902a6f247b7de2cc8
d82a8f2eeaa0512f7f52f1b82b26d2f0fbf565e5
refs/heads/master
2020-12-02T16:35:05.363646
2015-02-04T08:07:58
2015-02-04T08:07:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,652
cpp
#include "SingleCharacterSeparater.h" #include <iomanip> #include <iostream> #include <stdlib.h> #include <string.h> using std::vector; using std::string; using std::cout; using std::endl; using namespace codingtype; const char SPACE = 32; SingleCharacterSeparater::SingleCharacterSeparater() : buffer(nullptr) { } SingleCharacterSeparater::~SingleCharacterSeparater() { freebuffer(); } void SingleCharacterSeparater::gbk_separater(const string& s, vector<string>& vc) { char str[3] = {0, 0, 0}; int state = 0; string asc_s; for (auto p = s.begin(); p != s.end(); ++p) { char c = *p; if (0 == state) { if (!(c & 0x80)) { // do nothing if ( ('a' <= c && 'z' >= c) || ('A' <= c && 'Z' >= c)) { asc_s += c; state = 11; } } else if (c ^ 0x80 || c ^ 0xff) { str[0] = c; ++state; } } else if(1 == state) { ////cout << std::setbase(16) << (unsigned)c << " " << std::setbase(16) << (c & 0xc0) << endl; ////cout << std::setbase(16) << (unsigned)c << " " << std::setbase(16) << (c & 0x80) << endl; if ((!((c & 0xc0) ^ 0x40) && (c ^ 0x7f)) || (!((c & 0x80) ^ 0x80) && (c ^ 0xff))) { str[1] = c; vc.push_back(str); } str[1] = 0; state = 0; } else if(11 == state) { if ( ('a' <= c && 'z' >= c) || ('A' <= c && 'Z' >= c)) { asc_s += c; state = 11; } else { vc.push_back(asc_s); asc_s.clear(); state = 0; } } } if (asc_s.size() > 1 && 11 == state) vc.push_back(asc_s); } void SingleCharacterSeparater::utf8_separater(const string& s, vector<string>& vc) { int state = 0; int character_length = 0; char str[6] = {0, 0, 0, 0, 0, 0}; string asc_s; for (auto p = s.begin(); p != s.end(); ++p) { //unsigned short c = s[i] - 0xff00; char c = *p; if (0 == state) { if (!(c & 0x80)) { //do nothing if ( ('a' <= c && 'z' >= c) || ('A' <= c && 'Z' >= c)) { asc_s += c; state = 11; } } else if(!((c & 0xfe) ^ 0xfc)) { //1111 110x str[state++] = c; character_length = 5; } else if(!((c & 0xfc) ^ 0xf8)) { //1111 10xx str[state++] = c; character_length = 4; } else if(!((c & 0xf8) ^ 0xf0)) { //1111 00xx str[state++] = c; character_length = 3; } else if(!((c & 0xf0) ^ 0xe0)) { //1110 xxxx str[state++] = c; character_length = 2; } else if (!((c & 0xe0) ^ 0xc0)) { //1100 xxxx str[state++] = c; character_length = 1; } } else if(1 == state){ if (!((c & 0xc0) ^ 0x80)) { str[state++] = c; if(state > character_length){ //cout << "2 2\n"; vc.push_back(str); for (int i = 1; i <= state; ++i) str[i] = 0; state = 0; character_length = 0; } } else { for (int i = 1; i <= state; ++i) str[i] = 0; state = 0; character_length = 0; } } else if(11 == state) { if ( ('a' <= c && 'z' >= c) || ('A' <= c && 'Z' >= c)) { asc_s += c; state = 11; } else { vc.push_back(asc_s); asc_s.clear(); state = 0; } } } if (asc_s.size() > 1 && 11 == state) vc.push_back(asc_s); } const char* SingleCharacterSeparater::gbk_separater(const char* s) { freebuffer(); const unsigned old_length = strlen(s); const unsigned new_length = old_length * 2 + 1; char* buffer = new char[new_length]; if (nullptr == buffer) { printf("can't allocate memory\n"); return nullptr; } buffer[new_length-1] = 0; int count = 0; int state = 0; bool lack_space = false; for (unsigned i = 0; i < old_length; ++i) { //unsigned short c = s[i] - 0xff00; char c = s[i]; if (0 == state) { if (!(c & 0x80)) { buffer[count++] = c; if (!lack_space) lack_space = true; //buffer[count++] = SPACE; } else if (c ^ 0x80 || c ^ 0xff) { if (lack_space) buffer[count++] = SPACE; buffer[count++] = c; ++state; } } else if(1 == state) { ////cout << std::setbase(16) << (unsigned)c << " " << std::setbase(16) << (c & 0xc0) << endl; ////cout << std::setbase(16) << (unsigned)c << " " << std::setbase(16) << (c & 0x80) << endl; if (((!((c & 0xc0) ^ 0x40) && (c ^ 0x7f))) || ((!((c & 0x80) ^ 0x80) && (c ^ 0xff)))) { buffer[count++] = c; buffer[count++] = SPACE; } else { buffer[count-1] = SPACE; } lack_space = false; state = 0; } } buffer[count] = 0; return buffer; } const char* SingleCharacterSeparater::utf8_separater(const char* s) { freebuffer(); const unsigned old_length = strlen(s); const unsigned new_length = old_length * 2 + 1; char* buffer = new char[new_length]; if (nullptr == buffer) { printf("can't allocate memory\n"); return nullptr; } buffer[new_length-1] = 0; int count = 0; int state = 0; int character_length; bool lack_space = false; for (unsigned i = 0; i < old_length; ++i) { //unsigned short c = s[i] - 0xff00; char c = s[i]; if (0 == state) { if (!(c & 0x80)) { buffer[count++] = c; if (!lack_space) lack_space = true; } else if(!((c & 0xfe) ^ 0xfc)) { //1111 110x //cout << "1 1\n"; if (lack_space) buffer[count++] = SPACE; ; ++state; buffer[count++] = c; character_length = 5; } else if(!((c & 0xfc) ^ 0xf8)) { //1111 10xx //cout << "1 1\n"; if (lack_space) buffer[count++] = SPACE; ; ++state; buffer[count++] = c; character_length = 4; } else if(!((c & 0xf8) ^ 0xf0)) { //1111 00xx //cout << "1 1\n"; if (lack_space) buffer[count++] = SPACE; ; ++state; buffer[count++] = c; character_length = 3; } else if(!((c & 0xf0) ^ 0xe0)) { //1110 xxxx //cout << "1 1\n"; if (lack_space) buffer[count++] = SPACE; ; ++state; buffer[count++] = c; character_length = 2; } else if (!((c & 0xe0) ^ 0xc0)) { //1100 xxxx //cout << "1 1\n"; if (lack_space) buffer[count++] = SPACE; ; ++state; buffer[count++] = c; character_length = 1; } } else { if (!((c & 0xc0) ^ 0x80)) { //cout << "2 1\n"; buffer[count++] = c; if(state >= character_length){ //cout << "2 2\n"; buffer[count++] = SPACE; lack_space = false; state = 0; character_length = 0; } else state++; } else { buffer[count++] = SPACE; lack_space = false; character_length = 0; state = 0; } } } buffer[count] = 0; return buffer; }
[ "545135082@qq.com" ]
545135082@qq.com
36df590ec1fd9f89fb3ca71c4bf41227d9a4501c
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/services/service_manager/sandbox/switches.h
a1615980a0af83d969d357c6e16af54401ac523c
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
3,773
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_SERVICE_MANAGER_SANDBOX_SWITCHES_H_ #define SERVICES_SERVICE_MANAGER_SANDBOX_SWITCHES_H_ #include "build/build_config.h" #include "services/service_manager/embedder/switches.h" #include "services/service_manager/sandbox/export.h" namespace service_manager { namespace switches { // Type of sandbox to apply to the process running the service, one of the // values in the next block. SERVICE_MANAGER_SANDBOX_EXPORT extern const char kServiceSandboxType[]; // Must be in sync with "sandbox_type" values as used in service manager's // manifest.json catalog files. SERVICE_MANAGER_SANDBOX_EXPORT extern const char kNoneSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kNoneSandboxAndElevatedPrivileges[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kNetworkSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kPpapiSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kUtilitySandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kCdmSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kXrCompositingSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kPdfCompositorSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kProfilingSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kAudioSandbox[]; // Flags owned by the service manager sandbox. SERVICE_MANAGER_SANDBOX_EXPORT extern const char kAllowNoSandboxJob[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kAllowSandboxDebugging[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableAppContainer[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableGpuSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableNamespaceSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableSeccompFilterSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableSetuidSandbox[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableWin32kLockDown[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kEnableAppContainer[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kGpuSandboxAllowSysVShm[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kGpuSandboxFailuresFatal[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kNoSandbox[]; #if defined(OS_WIN) SERVICE_MANAGER_SANDBOX_EXPORT extern const char kAllowThirdPartyModules[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kAddGpuAppContainerCaps[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableGpuAppContainer[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kDisableGpuLpac[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kEnableGpuAppContainer[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kNoSandboxAndElevatedPrivileges[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kAddXrAppContainerCaps[]; #endif #if defined(OS_MACOSX) SERVICE_MANAGER_SANDBOX_EXPORT extern const char kEnableSandboxLogging[]; #endif // Flags spied upon from other layers. SERVICE_MANAGER_SANDBOX_EXPORT extern const char kGpuProcess[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kPpapiBrokerProcess[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kPpapiPluginProcess[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kRendererProcess[]; SERVICE_MANAGER_SANDBOX_EXPORT extern const char kUtilityProcess[]; } // namespace switches #if defined(OS_WIN) // Returns whether Win32k lockdown is enabled for child processes or not. // Not really a switch, but uses one under the covers. SERVICE_MANAGER_SANDBOX_EXPORT bool IsWin32kLockdownEnabled(); #endif } // namespace service_manager #endif // SERVICES_SERVICE_MANAGER_SANDBOX_SWITCHES_H_
[ "artem@brave.com" ]
artem@brave.com
75b81eaedcdf17e535e34e24ea6b07d2ca61771c
87c8e87ca0064bb2dbe2f0da461d6cdaafe58dc2
/COM classes/ShapeEditor.h
b9de7422b52c25d8d907b6bfebdba0e52dde7ed7
[]
no_license
jamil-g/MapWInGIS5.2.4
5392551ef92ca3dbc4ccd37241caf74e8e2b5ac3
3b3b10dba0e1c78af8df398544505a48472ed416
refs/heads/main
2023-07-29T02:46:01.453327
2021-09-03T22:58:03
2021-09-03T22:58:03
369,660,295
0
0
null
null
null
null
UTF-8
C++
false
false
10,119
h
// ShapeEditor.h : Declaration of the CShapeEditor #pragma once #include "EditorBase.h" #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) #error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." #endif // CShapeEditor class ATL_NO_VTABLE CShapeEditor : public CComObjectRootEx<CComObjectThreadModel>, public CComCoClass<CShapeEditor, &CLSID_ShapeEditor>, public IDispatchImpl<IShapeEditor, &IID_IShapeEditor, &LIBID_MapWinGIS, /*wMajor =*/ VERSION_MAJOR, /*wMinor =*/ VERSION_MINOR> { public: CShapeEditor() { _pUnkMarshaler = NULL; _activeShape = new EditorBase(); _activeShape->AreaDisplayMode = admMetric; _lastErrorCode = tkNO_ERROR; _globalCallback = NULL; _key = SysAllocString(L""); _layerHandle = -1; _shapeIndex = -1; _visible = true; _highlightShapes = lsAllLayers; _snapTolerance = 10; _snapBehavior = lsAllLayers; _snapMode = smVerticesAndLines; _state = esNone; _mapCallback = NULL; _isSubjectShape = false; _validationMode = evCheckWithGeos; _redrawNeeded = false; _layerRedrawNeeded = false; _overlayType = eoAddPart; _behavior = ebVertexEditor; _startingUndoCount = -1; } ~CShapeEditor() { SysFreeString(_key); Clear(); delete _activeShape; } DECLARE_REGISTRY_RESOURCEID(IDR_EDITSHAPE) BEGIN_COM_MAP(CShapeEditor) COM_INTERFACE_ENTRY(IShapeEditor) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, _pUnkMarshaler.p) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() DECLARE_GET_CONTROLLING_UNKNOWN() HRESULT FinalConstruct() { return CoCreateFreeThreadedMarshaler(GetControllingUnknown(), &_pUnkMarshaler.p); return S_OK; } void FinalRelease() { _pUnkMarshaler.Release(); } CComPtr<IUnknown> _pUnkMarshaler; public: STDMETHOD(get_LastErrorCode)(/*[out, retval]*/ long *pVal); STDMETHOD(get_ErrorMsg)(/*[in]*/ long ErrorCode, /*[out, retval]*/ BSTR *pVal); STDMETHOD(get_GlobalCallback)(/*[out, retval]*/ ICallback * *pVal); STDMETHOD(put_GlobalCallback)(/*[in]*/ ICallback * newVal); STDMETHOD(get_Key)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(put_Key)(/*[in]*/ BSTR newVal); STDMETHOD(Clear)(); STDMETHOD(get_numPoints)(long* retVal); STDMETHOD(get_PointXY)(long pointIndex, double* x, double* y, VARIANT_BOOL* retVal); STDMETHOD(put_PointXY)(long pointIndex, double x, double y, VARIANT_BOOL* retVal); STDMETHOD(UndoPoint)(VARIANT_BOOL* retVal); STDMETHOD(AddPoint)(IPoint *newPoint, VARIANT_BOOL* retVal); STDMETHOD(get_SegmentLength)(int segmentIndex, double* retVal); STDMETHOD(get_SegmentAngle)(int segmentIndex, double* retVal); STDMETHOD(get_IsDigitizing)(VARIANT_BOOL* retVal); STDMETHOD(get_ShapeType)(ShpfileType* retVal); STDMETHOD(put_ShapeType)(ShpfileType newVal); STDMETHOD(SetShape)(IShape* shp); STDMETHOD(get_ValidatedShape)(IShape** retVal); STDMETHOD(get_LayerHandle)(LONG* retVal); STDMETHOD(put_LayerHandle)(LONG newVal); STDMETHOD(get_ShapeIndex)(LONG* retVal); STDMETHOD(put_ShapeIndex)(LONG newVal); STDMETHOD(get_Area)(double* retVal); STDMETHOD(get_ShapeVisible)(VARIANT_BOOL* val); STDMETHOD(put_ShapeVisible)(VARIANT_BOOL newVal); STDMETHOD(get_SelectedVertex)(int* val); STDMETHOD(put_SelectedVertex)(int newVal); STDMETHOD(get_RawData)(IShape** pVal); STDMETHOD(get_FillColor)(OLE_COLOR* pVal); STDMETHOD(put_FillColor)(OLE_COLOR newVal); STDMETHOD(get_FillTransparency)(BYTE* pVal); STDMETHOD(put_FillTransparency)(BYTE newVal); STDMETHOD(get_LineColor)(OLE_COLOR* pVal); STDMETHOD(put_LineColor)(OLE_COLOR newVal); STDMETHOD(get_LineWidth)(FLOAT* pVal); STDMETHOD(put_LineWidth)(FLOAT newVal); STDMETHOD(CopyOptionsFrom)(IShapeDrawingOptions* options); STDMETHOD(get_IsEmpty)(VARIANT_BOOL* pVal); STDMETHOD(get_SnapTolerance)(DOUBLE* pVal); STDMETHOD(put_SnapTolerance)(DOUBLE newVal); STDMETHOD(get_HighlightVertices)(tkLayerSelection* pVal); STDMETHOD(put_HighlightVertices)(tkLayerSelection newVal); STDMETHOD(get_SnapBehavior)(tkLayerSelection* pVal); STDMETHOD(put_SnapBehavior)(tkLayerSelection newVal); STDMETHOD(get_SnapMode)(tkSnapMode* pVal); STDMETHOD(put_SnapMode)(tkSnapMode newVal); STDMETHOD(get_EditorState)(tkEditorState* pVal); STDMETHOD(put_EditorState)(tkEditorState newVal); STDMETHOD(StartEdit)(LONG LayerHandle, LONG ShapeIndex, VARIANT_BOOL* retVal); STDMETHOD(get_IndicesVisible)(VARIANT_BOOL* pVal); STDMETHOD(put_IndicesVisible)(VARIANT_BOOL newVal); STDMETHOD(get_AreaDisplayMode)(tkAreaDisplayMode* retVal); STDMETHOD(put_AreaDisplayMode)(tkAreaDisplayMode newVal); STDMETHOD(get_BearingType)(tkBearingType* retVal); STDMETHOD(put_BearingType)(tkBearingType newVal); STDMETHOD(get_LengthDisplayMode)(tkLengthDisplayMode* pVal); STDMETHOD(put_LengthDisplayMode)(tkLengthDisplayMode newVal); STDMETHOD(ClearSubjectShapes)(); STDMETHOD(get_NumSubjectShapes)(LONG* pVal); STDMETHOD(StartUnboundShape)(ShpfileType shpTYpe, VARIANT_BOOL* retVal); STDMETHOD(get_VerticesVisible)(VARIANT_BOOL* pVal); STDMETHOD(put_VerticesVisible)(VARIANT_BOOL newVal); STDMETHOD(get_ValidationMode)(tkEditorValidation* pVal); STDMETHOD(put_ValidationMode)(tkEditorValidation newVal); STDMETHOD(StartOverlay)(tkEditorOverlay overlayType, VARIANT_BOOL* retVal); STDMETHOD(get_EditorBehavior)(tkEditorBehavior* pVal); STDMETHOD(put_EditorBehavior)(tkEditorBehavior newVal); STDMETHOD(SaveChanges)(VARIANT_BOOL* retVal); STDMETHOD(get_HasChanges)(VARIANT_BOOL* pVal); STDMETHOD(get_IsUsingEllipsoid)(VARIANT_BOOL* pVal); STDMETHOD(get_Length)(DOUBLE* pVal); STDMETHOD(get_ShowArea)(VARIANT_BOOL* pVal); STDMETHOD(put_ShowArea)(VARIANT_BOOL newVal); STDMETHOD(get_AreaPrecision)(LONG* pVal); STDMETHOD(put_AreaPrecision)(LONG newVal); STDMETHOD(get_LengthPrecision)(LONG* pVal); STDMETHOD(put_LengthPrecision)(LONG newVal); STDMETHOD(get_AngleFormat)(tkAngleFormat* pVal); STDMETHOD(put_AngleFormat)(tkAngleFormat newVal); STDMETHOD(get_AnglePrecision)(LONG* pVal); STDMETHOD(put_AnglePrecision)(LONG newVal); private: BSTR _key; ICallback * _globalCallback; VARIANT_BOOL _visible; tkLayerSelection _highlightShapes; tkSnapMode _snapMode; double _snapTolerance; tkLayerSelection _snapBehavior; EditorBase* _activeShape; long _layerHandle; long _shapeIndex; long _lastErrorCode; tkEditorState _state; vector<CShapeEditor*> _subjects; bool _isSubjectShape; tkEditorValidation _validationMode; bool _redrawNeeded; bool _layerRedrawNeeded; tkEditorOverlay _overlayType; tkEditorBehavior _behavior; long _startingUndoCount; public: IMapViewCallback* _mapCallback; public: void ErrorMessage(long ErrorCode); void CopyData(int firstIndex, int lastIndex, IShape* target); void SetMapCallback(IMapViewCallback* callback) { _activeShape->SetMapCallback(callback, simEditing); _mapCallback = callback; } bool GetRedrawNeeded(RedrawTarget target) { if (target == rtShapeEditor) return _redrawNeeded; if (target == rtVolatileLayer) return _layerRedrawNeeded; return false; } void SetRedrawNeeded(RedrawTarget target) { if (target == rtShapeEditor) _redrawNeeded = true; if (target == rtVolatileLayer) _layerRedrawNeeded = true; } void ClearRedrawFlag() { _redrawNeeded = false; _layerRedrawNeeded = false; } EditorBase* GetActiveShape() { return _activeShape; } void SetIsSubject(bool value) { _isSubjectShape = value; } void DiscardState(); void SaveState(); void MoveShape(double offsetX, double offsetY); void MovePart(double offsetX, double offsetY); bool InsertVertex(double xProj, double yProj); bool RemoveVertex(); bool RemovePart(); bool CheckState(); void Render(Gdiplus::Graphics* g, bool dynamicBuffer, DraggingOperation offsetType, int screenOffsetX, int screenOffsetY); void EndOverlay(IShape* overlayShape); IShape* GetLayerShape(long layerHandle, long shapeIndex); bool GetClosestPoint(double projX, double projY, double& xResult, double& yResult); bool HandleDelete(); bool RemoveShape(); int GetClosestPart(double projX, double projY, double tolerance); bool RestoreState(IShape* shp, long layerHandle, long shapeIndex); bool TryStop(); void HandleProjPointAdd(double projX, double projY); bool HasSubjectShape(int LayerHandle, int ShapeIndex); bool ValidateWithGeos(IShape** shp); bool Validate(IShape** shp); ShpfileType GetShapeTypeForTool(tkCursorMode cursor); void ApplyColoringForTool(tkCursorMode mode); bool StartUnboundShape(tkCursorMode cursor); CShapeEditor* Clone(); void ApplyOverlayColoring(tkEditorOverlay overlay); bool TrySaveShape(IShape* shp); IShape* CalculateOverlay(IShape* overlay); void CopyOptionsFromShapefile(); void CancelOverlay(bool restoreSubjectShape); bool ClearCore(bool all); void DiscardChangesFromUndoList(); // exposing active shape API bool SetSelectedVertex(int vertexIndex) { return _activeShape->SetSelectedVertex(vertexIndex); } bool SetSelectedPart(int partIndex) { return _activeShape->SetSelectedPart(partIndex); } bool HasSelectedVertex() { return _activeShape->HasSelectedVertex(); } bool HasSelectedPart() { return _activeShape->HasSelectedPart(); } int SelectPart(double xProj, double yProj) { return _activeShape->SelectPart(xProj, yProj); } int GetClosestVertex(double projX, double projY, double tolerance) { return _activeShape->GetClosestVertex(projX, projY, tolerance); } STDMETHOD(get_ShowBearing)(VARIANT_BOOL* pVal); STDMETHOD(put_ShowBearing)(VARIANT_BOOL newVal); STDMETHOD(get_ShowLength)(VARIANT_BOOL* pVal); STDMETHOD(put_ShowLength)(VARIANT_BOOL newVal); STDMETHOD(Serialize)(BSTR* retVal); STDMETHOD(Deserialize)(BSTR state, VARIANT_BOOL* retVal); }; OBJECT_ENTRY_AUTO(__uuidof(ShapeEditor), CShapeEditor)
[ "jamil.garzuzi@gmail.com" ]
jamil.garzuzi@gmail.com
6a145e540fbd374b419e3ad2d59a24770a995059
20df56bfcab462811b4900abf8500123753ed6b6
/jsoncpp/src/lib_json/json_value.cpp
d07b7ffdc2ad68bcfd63b200c3dae6b7d0ba0382
[ "BSD-3-Clause" ]
permissive
skonst/tSIP
b477ffe3ea45d53a6bba296fcb03d69b0586d0d6
242295ccc24b2a1f8ce3c2fe3afaa60c425096b2
refs/heads/master
2022-07-21T15:10:46.044594
2020-05-12T22:13:17
2020-05-12T22:13:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
40,248
cpp
#ifdef __BORLANDC__ # pragma hdrstop #endif #include <iostream> #include <json/value.h> #include <json/writer.h> #include <utility> #include <stdexcept> #include <cstring> #include <cassert> #include <mem.h> #ifdef JSON_USE_CPPTL # include <cpptl/conststring.h> #endif #include <cstddef> // size_t #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR # include "json_batchallocator.h" #endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR #define JSON_ASSERT_UNREACHABLE assert( false ) #define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw #define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) throw std::runtime_error( message ); namespace Json { const Value Value::null; const Value::Int Value::minInt = Value::Int( ~(Value::UInt(-1)/2) ); const Value::Int Value::maxInt = Value::Int( Value::UInt(-1)/2 ); const Value::UInt Value::maxUInt = Value::UInt(-1); // A "safe" implementation of strdup. Allow null pointer to be passed. // Also avoid warning on msvc80. // //inline char *safeStringDup( const char *czstring ) //{ // if ( czstring ) // { // const size_t length = (unsigned int)( strlen(czstring) + 1 ); // char *newString = static_cast<char *>( malloc( length ) ); // memcpy( newString, czstring, length ); // return newString; // } // return 0; //} // //inline char *safeStringDup( const std::string &str ) //{ // if ( !str.empty() ) // { // const size_t length = str.length(); // char *newString = static_cast<char *>( malloc( length + 1 ) ); // memcpy( newString, str.c_str(), length ); // newString[length] = 0; // return newString; // } // return 0; //} ValueAllocator::~ValueAllocator() { } class DefaultValueAllocator : public ValueAllocator { public: virtual ~DefaultValueAllocator() { } virtual char *makeMemberName( const char *memberName ) { return duplicateStringValue( memberName ); } virtual void releaseMemberName( char *memberName ) { releaseStringValue( memberName ); } virtual char *duplicateStringValue( const char *value, unsigned int length = unknown ) { //@todo invesgate this old optimization //if ( !value || value[0] == 0 ) // return 0; if ( length == (unsigned int)unknown ) length = (unsigned int)strlen(value); char *newString = static_cast<char *>( malloc( length + 1 ) ); memcpy( newString, value, length ); newString[length] = 0; return newString; } virtual void releaseStringValue( char *value ) { if ( value ) free( value ); } }; static ValueAllocator *&valueAllocator() { static DefaultValueAllocator defaultAllocator; static ValueAllocator *valueAllocator = &defaultAllocator; return valueAllocator; } static struct DummyValueAllocatorInitializer { DummyValueAllocatorInitializer() { valueAllocator(); // ensure valueAllocator() statics are initialized before main(). } } dummyValueAllocatorInitializer; // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ValueInternals... // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// #ifdef JSON_VALUE_USE_INTERNAL_MAP # include "json_internalarray.inl" # include "json_internalmap.inl" #endif // JSON_VALUE_USE_INTERNAL_MAP # include "json_valueiterator.inl" // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::CommentInfo // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// Value::CommentInfo::CommentInfo() : comment_( 0 ) { } Value::CommentInfo::~CommentInfo() { if ( comment_ ) valueAllocator()->releaseStringValue( comment_ ); } void Value::CommentInfo::setComment( const char *text ) { if ( comment_ ) valueAllocator()->releaseStringValue( comment_ ); JSON_ASSERT( text ); JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /"); // It seems that /**/ style comments are acceptable as well. comment_ = valueAllocator()->duplicateStringValue( text ); } // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::CZString // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// # ifndef JSON_VALUE_USE_INTERNAL_MAP // Notes: index_ indicates if the string was allocated when // a string is stored. Value::CZString::CZString( int index ) : cstr_( 0 ) , index_( index ) { } Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate ) : cstr_( allocate == duplicate ? valueAllocator()->makeMemberName(cstr) : cstr ) , index_( allocate ) { } Value::CZString::CZString( const CZString &other ) : cstr_( other.index_ != noDuplication && other.cstr_ != 0 ? valueAllocator()->makeMemberName( other.cstr_ ) : other.cstr_ ) , index_( other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate) : other.index_ ) { } Value::CZString::~CZString() { if ( cstr_ && index_ == duplicate ) valueAllocator()->releaseMemberName( const_cast<char *>( cstr_ ) ); } void Value::CZString::swap( CZString &other ) { std::swap( cstr_, other.cstr_ ); std::swap( index_, other.index_ ); } Value::CZString & Value::CZString::operator =( const CZString &other ) { CZString temp( other ); swap( temp ); return *this; } bool Value::CZString::operator<( const CZString &other ) const { if ( cstr_ ) return strcmp( cstr_, other.cstr_ ) < 0; return index_ < other.index_; } bool Value::CZString::operator==( const CZString &other ) const { if ( cstr_ ) return strcmp( cstr_, other.cstr_ ) == 0; return index_ == other.index_; } int Value::CZString::index() const { return index_; } const char * Value::CZString::c_str() const { return cstr_; } bool Value::CZString::isStaticString() const { return index_ == noDuplication; } #endif // ifndef JSON_VALUE_USE_INTERNAL_MAP // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::Value // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// /*! \internal Default constructor initialization must be equivalent to: * memset( this, 0, sizeof(Value) ) * This optimization is used in ValueInternalMap fast allocator. */ Value::Value( ValueType type ) : type_( type ) , allocated_( 0 ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { switch ( type ) { case nullValue: break; case intValue: case uintValue: value_.int_ = 0; break; case realValue: value_.real_ = 0.0; break; case stringValue: value_.string_ = 0; break; #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: value_.map_ = new ObjectValues(); break; #else case arrayValue: value_.array_ = arrayAllocator()->newArray(); break; case objectValue: value_.map_ = mapAllocator()->newMap(); break; #endif case booleanValue: value_.bool_ = false; break; default: JSON_ASSERT_UNREACHABLE; } } Value::Value( Int value ) : type_( intValue ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.int_ = value; } Value::Value( UInt value ) : type_( uintValue ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.uint_ = value; } Value::Value( double value ) : type_( realValue ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.real_ = value; } Value::Value( const char *value ) : type_( stringValue ) , allocated_( true ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.string_ = valueAllocator()->duplicateStringValue( value ); } Value::Value( const std::string &value ) : type_( stringValue ) , allocated_( true ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.string_ = valueAllocator()->duplicateStringValue( value.c_str(), (unsigned int)value.length() ); } #ifdef __BORLANDC__ Value::Value( const AnsiString &value ) : type_( stringValue ) , allocated_( true ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.string_ = valueAllocator()->duplicateStringValue( value.c_str(), (unsigned int)value.Length() ); } #endif Value::Value( const StaticString &value ) : type_( stringValue ) , allocated_( false ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.string_ = const_cast<char *>( value.c_str() ); } # ifdef JSON_USE_CPPTL Value::Value( const CppTL::ConstString &value ) : type_( stringValue ) , allocated_( true ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.string_ = valueAllocator()->duplicateStringValue( value, value.length() ); } # endif Value::Value( bool value ) : type_( booleanValue ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { value_.bool_ = value; } Value::Value( const Value &other ) : type_( other.type_ ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP , itemIsUsed_( 0 ) #endif { switch ( type_ ) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: value_ = other.value_; break; case stringValue: if ( other.value_.string_ ) { value_.string_ = valueAllocator()->duplicateStringValue( other.value_.string_ ); allocated_ = true; } else value_.string_ = 0; break; #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: value_.map_ = new ObjectValues( *other.value_.map_ ); break; #else case arrayValue: value_.array_ = arrayAllocator()->newArrayCopy( *other.value_.array_ ); break; case objectValue: value_.map_ = mapAllocator()->newMapCopy( *other.value_.map_ ); break; #endif default: JSON_ASSERT_UNREACHABLE; } if ( other.comments_ ) { comments_ = new CommentInfo[numberOfCommentPlacement]; for ( int comment =0; comment < numberOfCommentPlacement; ++comment ) { const CommentInfo &otherComment = other.comments_[comment]; if ( otherComment.comment_ ) comments_[comment].setComment( otherComment.comment_ ); } } } Value::~Value() { switch ( type_ ) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: break; case stringValue: if ( allocated_ ) valueAllocator()->releaseStringValue( value_.string_ ); break; #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: delete value_.map_; break; #else case arrayValue: arrayAllocator()->destructArray( value_.array_ ); break; case objectValue: mapAllocator()->destructMap( value_.map_ ); break; #endif default: JSON_ASSERT_UNREACHABLE; } if ( comments_ ) delete[] comments_; } Value & Value::operator=( const Value &other ) { Value temp( other ); swap( temp ); return *this; } void Value::swap( Value &other ) { ValueType temp = type_; type_ = other.type_; other.type_ = temp; std::swap( value_, other.value_ ); int temp2 = allocated_; allocated_ = other.allocated_; other.allocated_ = temp2; } ValueType Value::type() const { return type_; } int Value::compare( const Value &other ) { /* int typeDelta = other.type_ - type_; switch ( type_ ) { case nullValue: return other.type_ == type_; case intValue: if ( other.type_.isNumeric() case uintValue: case realValue: case booleanValue: break; case stringValue, break; case arrayValue: delete value_.array_; break; case objectValue: delete value_.map_; default: JSON_ASSERT_UNREACHABLE; } */ return 0; // unreachable } bool Value::operator <( const Value &other ) const { int typeDelta = type_ - other.type_; if ( typeDelta ) return typeDelta < 0 ? true : false; switch ( type_ ) { case nullValue: return false; case intValue: return value_.int_ < other.value_.int_; case uintValue: return value_.uint_ < other.value_.uint_; case realValue: return value_.real_ < other.value_.real_; case booleanValue: return value_.bool_ < other.value_.bool_; case stringValue: return ( value_.string_ == 0 && other.value_.string_ ) || ( other.value_.string_ && value_.string_ && strcmp( value_.string_, other.value_.string_ ) < 0 ); #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: { int delta = int( value_.map_->size() - other.value_.map_->size() ); if ( delta ) return delta < 0; return (*value_.map_) < (*other.value_.map_); } #else case arrayValue: return value_.array_->compare( *(other.value_.array_) ) < 0; case objectValue: return value_.map_->compare( *(other.value_.map_) ) < 0; #endif default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable } bool Value::operator <=( const Value &other ) const { return !(other > *this); } bool Value::operator >=( const Value &other ) const { return !(*this < other); } bool Value::operator >( const Value &other ) const { return other < *this; } bool Value::operator ==( const Value &other ) const { //if ( type_ != other.type_ ) // GCC 2.95.3 says: // attempt to take address of bit-field structure member `Json::Value::type_' // Beats me, but a temp solves the problem. int temp = other.type_; if ( type_ != temp ) return false; switch ( type_ ) { case nullValue: return true; case intValue: return value_.int_ == other.value_.int_; case uintValue: return value_.uint_ == other.value_.uint_; case realValue: return value_.real_ == other.value_.real_; case booleanValue: return value_.bool_ == other.value_.bool_; case stringValue: return ( value_.string_ == other.value_.string_ ) || ( other.value_.string_ && value_.string_ && strcmp( value_.string_, other.value_.string_ ) == 0 ); #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: return value_.map_->size() == other.value_.map_->size() && (*value_.map_) == (*other.value_.map_); #else case arrayValue: return value_.array_->compare( *(other.value_.array_) ) == 0; case objectValue: return value_.map_->compare( *(other.value_.map_) ) == 0; #endif default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable } bool Value::operator !=( const Value &other ) const { return !( *this == other ); } const char * Value::asCString() const { JSON_ASSERT( type_ == stringValue ); return value_.string_; } std::string Value::asString() const { switch ( type_ ) { case nullValue: return ""; case stringValue: return value_.string_ ? value_.string_ : ""; case booleanValue: return value_.bool_ ? "true" : "false"; case intValue: case uintValue: case realValue: case arrayValue: case objectValue: #pragma warn -8008 JSON_ASSERT_MESSAGE( false, "Type is not convertible to string" ); #pragma warn .8008 default: JSON_ASSERT_UNREACHABLE; } return ""; // unreachable } #ifdef __BORLANDC__ AnsiString Value::asAString() const { switch ( type_ ) { case nullValue: return ""; case stringValue: return value_.string_ ? value_.string_ : ""; case booleanValue: return value_.bool_ ? "true" : "false"; case intValue: case uintValue: case realValue: case arrayValue: case objectValue: #pragma warn -8008 JSON_ASSERT_MESSAGE( false, "Type is not convertible to string" ); #pragma warn .8008 default: JSON_ASSERT_UNREACHABLE; } return ""; // unreachable } #endif # ifdef JSON_USE_CPPTL CppTL::ConstString Value::asConstString() const { return CppTL::ConstString( asString().c_str() ); } # endif Value::Int Value::asInt() const { switch ( type_ ) { case nullValue: return 0; case intValue: return value_.int_; case uintValue: JSON_ASSERT_MESSAGE( value_.uint_ < (unsigned)maxInt, "integer out of signed integer range" ); return value_.uint_; case realValue: JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" ); return Int( value_.real_ ); case booleanValue: return value_.bool_ ? 1 : 0; case stringValue: case arrayValue: case objectValue: #pragma warn -8008 JSON_ASSERT_MESSAGE( false, "Type is not convertible to int" ); #pragma warn .8008 default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable; } Value::UInt Value::asUInt() const { switch ( type_ ) { case nullValue: return 0; case intValue: JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" ); return value_.int_; case uintValue: return value_.uint_; case realValue: JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" ); return UInt( value_.real_ ); case booleanValue: return value_.bool_ ? 1 : 0; case stringValue: case arrayValue: case objectValue: #pragma warn -8008 JSON_ASSERT_MESSAGE( false, "Type is not convertible to uint" ); #pragma warn .8008 default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable; } double Value::asDouble() const { switch ( type_ ) { case nullValue: return 0.0; case intValue: return value_.int_; case uintValue: return value_.uint_; case realValue: return value_.real_; case booleanValue: return value_.bool_ ? 1.0 : 0.0; case stringValue: case arrayValue: case objectValue: #pragma warn -8008 JSON_ASSERT_MESSAGE( false, "Type is not convertible to double" ); #pragma warn .8008 default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable; } bool Value::asBool() const { switch ( type_ ) { case nullValue: return false; case intValue: case uintValue: return value_.int_ != 0; case realValue: return value_.real_ != 0.0; case booleanValue: return value_.bool_; case stringValue: return value_.string_ && value_.string_[0] != 0; case arrayValue: case objectValue: return value_.map_->size() != 0; default: JSON_ASSERT_UNREACHABLE; } return false; // unreachable; } bool Value::isConvertibleTo( ValueType other ) const { switch ( type_ ) { case nullValue: return true; case intValue: return ( other == nullValue && value_.int_ == 0 ) || other == intValue || ( other == uintValue && value_.int_ >= 0 ) || other == realValue || other == stringValue || other == booleanValue; case uintValue: return ( other == nullValue && value_.uint_ == 0 ) || ( other == intValue && value_.uint_ <= (unsigned)maxInt ) || other == uintValue || other == realValue || other == stringValue || other == booleanValue; case realValue: return ( other == nullValue && value_.real_ == 0.0 ) || ( other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt ) || ( other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt ) || other == realValue || other == stringValue || other == booleanValue; case booleanValue: return ( other == nullValue && value_.bool_ == false ) || other == intValue || other == uintValue || other == realValue || other == stringValue || other == booleanValue; case stringValue: return other == stringValue || ( other == nullValue && (!value_.string_ || value_.string_[0] == 0) ); case arrayValue: return other == arrayValue || ( other == nullValue && value_.map_->size() == 0 ); case objectValue: return other == objectValue || ( other == nullValue && value_.map_->size() == 0 ); default: JSON_ASSERT_UNREACHABLE; } return false; // unreachable; } /// Number of values in array or object Value::UInt Value::size() const { switch ( type_ ) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: case stringValue: return 0; #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: // size of the array is highest index + 1 if ( !value_.map_->empty() ) { ObjectValues::const_iterator itLast = value_.map_->end(); --itLast; return (*itLast).first.index()+1; } return 0; case objectValue: return Int( value_.map_->size() ); #else case arrayValue: return Int( value_.array_->size() ); case objectValue: return Int( value_.map_->size() ); #endif default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable; } bool Value::empty() const { if ( isNull() || isArray() || isObject() ) return size() == 0u; else return false; } bool Value::operator!() const { return isNull(); } void Value::clear() { JSON_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue ); switch ( type_ ) { #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: value_.map_->clear(); break; #else case arrayValue: value_.array_->clear(); break; case objectValue: value_.map_->clear(); break; #endif default: break; } } void Value::resize( UInt newSize ) { JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); if ( type_ == nullValue ) *this = Value( arrayValue ); #ifndef JSON_VALUE_USE_INTERNAL_MAP UInt oldSize = size(); if ( newSize == 0 ) clear(); else if ( newSize > oldSize ) (*this)[ newSize - 1 ]; else { for ( UInt index = newSize; index < oldSize; ++index ) value_.map_->erase( index ); assert( size() == newSize ); } #else value_.array_->resize( newSize ); #endif } Value & Value::operator[]( UInt index ) { JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); if ( type_ == nullValue ) *this = Value( arrayValue ); #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString key( index ); ObjectValues::iterator it = value_.map_->lower_bound( key ); if ( it != value_.map_->end() && (*it).first == key ) return (*it).second; ObjectValues::value_type defaultValue( key, null ); it = value_.map_->insert( it, defaultValue ); return (*it).second; #else return value_.array_->resolveReference( index ); #endif } const Value & Value::operator[]( UInt index ) const { JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); if ( type_ == nullValue ) return null; #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString key( index ); ObjectValues::const_iterator it = value_.map_->find( key ); if ( it == value_.map_->end() ) return null; return (*it).second; #else Value *value = value_.array_->find( index ); return value ? *value : null; #endif } Value & Value::operator[]( const char *key ) { return resolveReference( key, false ); } Value & Value::resolveReference( const char *key, bool isStatic ) { JSON_ASSERT( type_ == nullValue || type_ == objectValue ); if ( type_ == nullValue ) *this = Value( objectValue ); #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString actualKey( key, isStatic ? CZString::noDuplication : CZString::duplicateOnCopy ); ObjectValues::iterator it = value_.map_->lower_bound( actualKey ); if ( it != value_.map_->end() && (*it).first == actualKey ) return (*it).second; ObjectValues::value_type defaultValue( actualKey, null ); it = value_.map_->insert( it, defaultValue ); Value &value = (*it).second; return value; #else return value_.map_->resolveReference( key, isStatic ); #endif } Value Value::get( UInt index, const Value &defaultValue ) const { const Value *value = &((*this)[index]); return value == &null ? defaultValue : *value; } bool Value::isValidIndex( UInt index ) const { return index < size(); } const Value & Value::operator[]( const char *key ) const { JSON_ASSERT( type_ == nullValue || type_ == objectValue ); if ( type_ == nullValue ) return null; #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString actualKey( key, CZString::noDuplication ); ObjectValues::const_iterator it = value_.map_->find( actualKey ); if ( it == value_.map_->end() ) return null; return (*it).second; #else const Value *value = value_.map_->find( key ); return value ? *value : null; #endif } Value & Value::operator[]( const std::string &key ) { return (*this)[ key.c_str() ]; } const Value & Value::operator[]( const std::string &key ) const { return (*this)[ key.c_str() ]; } Value & Value::operator[]( const StaticString &key ) { return resolveReference( key, true ); } # ifdef JSON_USE_CPPTL Value & Value::operator[]( const CppTL::ConstString &key ) { return (*this)[ key.c_str() ]; } const Value & Value::operator[]( const CppTL::ConstString &key ) const { return (*this)[ key.c_str() ]; } # endif Value & Value::append( const Value &value ) { return (*this)[size()] = value; } Value Value::get( const char *key, const Value &defaultValue ) const { const Value *value = &((*this)[key]); return value == &null ? defaultValue : *value; } Value Value::get( const std::string &key, const Value &defaultValue ) const { return get( key.c_str(), defaultValue ); } #ifdef __BORLANDC__ void Value::getAString(const char* key, AnsiString &val) const { val = get(key, val).asAString(); } #endif void Value::getInt(const char* key, int &val) const { val = get(key, val).asInt(); } void Value::getUInt(const char* key, unsigned int &val) const { val = get(key, val).asUInt(); } void Value::getBool(const char* key, bool &val) const { val = get(key, val).asBool(); } void Value::getDouble(const char* key, double &val) const { val = get(key, val).asDouble(); } Value Value::removeMember( const char* key ) { JSON_ASSERT( type_ == nullValue || type_ == objectValue ); if ( type_ == nullValue ) return null; #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString actualKey( key, CZString::noDuplication ); ObjectValues::iterator it = value_.map_->find( actualKey ); if ( it == value_.map_->end() ) return null; Value old(it->second); value_.map_->erase(it); return old; #else Value *value = value_.map_->find( key ); if (value){ Value old(*value); value_.map_.remove( key ); return old; } else { return null; } #endif } Value Value::removeMember( const std::string &key ) { return removeMember( key.c_str() ); } # ifdef JSON_USE_CPPTL Value Value::get( const CppTL::ConstString &key, const Value &defaultValue ) const { return get( key.c_str(), defaultValue ); } # endif bool Value::isMember( const char *key ) const { const Value *value = &((*this)[key]); return value != &null; } bool Value::isMember( const std::string &key ) const { return isMember( key.c_str() ); } # ifdef JSON_USE_CPPTL bool Value::isMember( const CppTL::ConstString &key ) const { return isMember( key.c_str() ); } #endif Value::Members Value::getMemberNames() const { JSON_ASSERT( type_ == nullValue || type_ == objectValue ); if ( type_ == nullValue ) return Value::Members(); Members members; members.reserve( value_.map_->size() ); #ifndef JSON_VALUE_USE_INTERNAL_MAP ObjectValues::const_iterator it = value_.map_->begin(); ObjectValues::const_iterator itEnd = value_.map_->end(); for ( ; it != itEnd; ++it ) members.push_back( std::string( (*it).first.c_str() ) ); #else ValueInternalMap::IteratorState it; ValueInternalMap::IteratorState itEnd; value_.map_->makeBeginIterator( it ); value_.map_->makeEndIterator( itEnd ); for ( ; !ValueInternalMap::equals( it, itEnd ); ValueInternalMap::increment(it) ) members.push_back( std::string( ValueInternalMap::key( it ) ) ); #endif return members; } // //# ifdef JSON_USE_CPPTL //EnumMemberNames //Value::enumMemberNames() const //{ // if ( type_ == objectValue ) // { // return CppTL::Enum::any( CppTL::Enum::transform( // CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ), // MemberNamesTransform() ) ); // } // return EnumMemberNames(); //} // // //EnumValues //Value::enumValues() const //{ // if ( type_ == objectValue || type_ == arrayValue ) // return CppTL::Enum::anyValues( *(value_.map_), // CppTL::Type<const Value &>() ); // return EnumValues(); //} // //# endif bool Value::isNull() const { return type_ == nullValue; } bool Value::isBool() const { return type_ == booleanValue; } bool Value::isInt() const { return type_ == intValue; } bool Value::isUInt() const { return type_ == uintValue; } bool Value::isIntegral() const { return type_ == intValue || type_ == uintValue || type_ == booleanValue; } bool Value::isDouble() const { return type_ == realValue; } bool Value::isNumeric() const { return isIntegral() || isDouble(); } bool Value::isString() const { return type_ == stringValue; } bool Value::isArray() const { return type_ == nullValue || type_ == arrayValue; } bool Value::isObject() const { return type_ == nullValue || type_ == objectValue; } void Value::setComment( const char *comment, CommentPlacement placement ) { if ( !comments_ ) comments_ = new CommentInfo[numberOfCommentPlacement]; comments_[placement].setComment( comment ); } void Value::setComment( const std::string &comment, CommentPlacement placement ) { setComment( comment.c_str(), placement ); } bool Value::hasComment( CommentPlacement placement ) const { return comments_ != 0 && comments_[placement].comment_ != 0; } std::string Value::getComment( CommentPlacement placement ) const { if ( hasComment(placement) ) return comments_[placement].comment_; return ""; } std::string Value::toStyledString() const { StyledWriter writer; return writer.write( *this ); } Value::const_iterator Value::begin() const { switch ( type_ ) { #ifdef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: if ( value_.array_ ) { ValueInternalArray::IteratorState it; value_.array_->makeBeginIterator( it ); return const_iterator( it ); } break; case objectValue: if ( value_.map_ ) { ValueInternalMap::IteratorState it; value_.map_->makeBeginIterator( it ); return const_iterator( it ); } break; #else case arrayValue: case objectValue: if ( value_.map_ ) return const_iterator( value_.map_->begin() ); break; #endif default: break; } return const_iterator(); } Value::const_iterator Value::end() const { switch ( type_ ) { #ifdef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: if ( value_.array_ ) { ValueInternalArray::IteratorState it; value_.array_->makeEndIterator( it ); return const_iterator( it ); } break; case objectValue: if ( value_.map_ ) { ValueInternalMap::IteratorState it; value_.map_->makeEndIterator( it ); return const_iterator( it ); } break; #else case arrayValue: case objectValue: if ( value_.map_ ) return const_iterator( value_.map_->end() ); break; #endif default: break; } return const_iterator(); } Value::iterator Value::begin() { switch ( type_ ) { #ifdef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: if ( value_.array_ ) { ValueInternalArray::IteratorState it; value_.array_->makeBeginIterator( it ); return iterator( it ); } break; case objectValue: if ( value_.map_ ) { ValueInternalMap::IteratorState it; value_.map_->makeBeginIterator( it ); return iterator( it ); } break; #else case arrayValue: case objectValue: if ( value_.map_ ) return iterator( value_.map_->begin() ); break; #endif default: break; } return iterator(); } Value::iterator Value::end() { switch ( type_ ) { #ifdef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: if ( value_.array_ ) { ValueInternalArray::IteratorState it; value_.array_->makeEndIterator( it ); return iterator( it ); } break; case objectValue: if ( value_.map_ ) { ValueInternalMap::IteratorState it; value_.map_->makeEndIterator( it ); return iterator( it ); } break; #else case arrayValue: case objectValue: if ( value_.map_ ) return iterator( value_.map_->end() ); break; #endif default: break; } return iterator(); } // class PathArgument // ////////////////////////////////////////////////////////////////// PathArgument::PathArgument() : kind_( kindNone ) { } PathArgument::PathArgument( Value::UInt index ) : index_( index ) , kind_( kindIndex ) { } PathArgument::PathArgument( const char *key ) : key_( key ) , kind_( kindKey ) { } PathArgument::PathArgument( const std::string &key ) : key_( key.c_str() ) , kind_( kindKey ) { } // class Path // ////////////////////////////////////////////////////////////////// Path::Path( const std::string &path, const PathArgument &a1, const PathArgument &a2, const PathArgument &a3, const PathArgument &a4, const PathArgument &a5 ) { InArgs in; in.push_back( &a1 ); in.push_back( &a2 ); in.push_back( &a3 ); in.push_back( &a4 ); in.push_back( &a5 ); makePath( path, in ); } void Path::makePath( const std::string &path, const InArgs &in ) { const char *current = path.c_str(); const char *end = current + path.length(); InArgs::const_iterator itInArg = in.begin(); while ( current != end ) { if ( *current == '[' ) { ++current; if ( *current == '%' ) addPathInArg( path, in, itInArg, PathArgument::kindIndex ); else { Value::UInt index = 0; for ( ; current != end && *current >= '0' && *current <= '9'; ++current ) index = index * 10 + Value::UInt(*current - '0'); args_.push_back( index ); } if ( current == end || *current++ != ']' ) invalidPath( path, int(current - path.c_str()) ); } else if ( *current == '%' ) { addPathInArg( path, in, itInArg, PathArgument::kindKey ); ++current; } else if ( *current == '.' ) { ++current; } else { const char *beginName = current; while ( current != end && !strchr( "[.", *current ) ) ++current; args_.push_back( std::string( beginName, current ) ); } } } void Path::addPathInArg( const std::string &path, const InArgs &in, InArgs::const_iterator &itInArg, PathArgument::Kind kind ) { if ( itInArg == in.end() ) { // Error: missing argument %d } else if ( (*itInArg)->kind_ != kind ) { // Error: bad argument type } else { args_.push_back( **itInArg ); } } void Path::invalidPath( const std::string &path, int location ) { // Error: invalid path. } const Value & Path::resolve( const Value &root ) const { const Value *node = &root; for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) { const PathArgument &arg = *it; if ( arg.kind_ == PathArgument::kindIndex ) { if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) { // Error: unable to resolve path (array value expected at position... } node = &((*node)[arg.index_]); } else if ( arg.kind_ == PathArgument::kindKey ) { if ( !node->isObject() ) { // Error: unable to resolve path (object value expected at position...) } node = &((*node)[arg.key_]); if ( node == &Value::null ) { // Error: unable to resolve path (object has no member named '' at position...) } } } return *node; } Value Path::resolve( const Value &root, const Value &defaultValue ) const { const Value *node = &root; for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) { const PathArgument &arg = *it; if ( arg.kind_ == PathArgument::kindIndex ) { if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) return defaultValue; node = &((*node)[arg.index_]); } else if ( arg.kind_ == PathArgument::kindKey ) { if ( !node->isObject() ) return defaultValue; node = &((*node)[arg.key_]); if ( node == &Value::null ) return defaultValue; } } return *node; } Value & Path::make( Value &root ) const { Value *node = &root; for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) { const PathArgument &arg = *it; if ( arg.kind_ == PathArgument::kindIndex ) { if ( !node->isArray() ) { // Error: node is not an array at position ... } node = &((*node)[arg.index_]); } else if ( arg.kind_ == PathArgument::kindKey ) { if ( !node->isObject() ) { // Error: node is not an object at position... } node = &((*node)[arg.key_]); } } return *node; } } // namespace Json
[ "tomasz.o.ostrowski@gmail.com" ]
tomasz.o.ostrowski@gmail.com
bf1d59bc7118a359f97a1a874dd56c9bc1f1fa38
a1e3bb549b958818becf3408de436b7967cc15c4
/part2/server.cpp
be676930c01c2d79f75c03cbe211a9ba558aeff5
[]
no_license
SailakshmiPisupati/os_berkeleys
14e43e18401a5f7f946429e24b3a7004b69fc407
85a1ca1ee3b15b8082bcd4612a26cb6ed255bfa9
refs/heads/master
2021-07-11T13:42:28.345763
2021-06-07T19:05:05
2021-06-07T19:05:05
88,349,744
1
0
null
2021-06-07T19:05:06
2017-04-15T13:48:46
C++
UTF-8
C++
false
false
3,599
cpp
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #include <stdbool.h> void create_server(short server_port); void *sendmessages(void *socket_desc); void *receivemessages(void *socket_desc); void create_sender_thread(); void create_receiver_thread(); int main(int argc , char *argv[]){ short server_port, connect_to; int *new_sock; int number_of_nodes = 4; int node_ports[number_of_nodes] ={8098,8099,8067,8077}; //char[] *COORDINATOR = "coordinator"; create_sender_thread(); create_receiver_thread(); return 0; } void create_sender_thread(){ pthread_t sniffer_thread; if( pthread_create( &sniffer_thread , NULL , sendmessages , (void*) new_sock) < 0){ perror("Could not create sender thread"); } } void create_receiver_thread(){ pthread_t sniffer_thread; if( pthread_create( &sniffer_thread , NULL , receivemessages , (void*) new_sock) < 0){ perror("Could not create receiver thread"); } } void create_server(short server_port){ int socket_desc , c , *new_sock; int client_sock; struct sockaddr_in server , client; char message[2000]; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket\n"); } printf("Server up and running....\n"); //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( server_port ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0){ //print the error message perror("bind failed. Error"); } printf("bind done\n"); //Listen listen(socket_desc , 3); //Accept and incoming connection printf("Waiting for communication with the other nodes.\n"); c = sizeof(struct sockaddr_in); while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) ) { printf("New client connected. Node connected count %d\n",client_sock); printf("Creating a new thread for time synchronization.\n"); pthread_t sniffer_thread; new_sock = (int *) malloc(1); *new_sock = client_sock; //sleep till all the clients connect. if( pthread_create( &sniffer_thread , NULL , sendmessages , (void*) new_sock) < 0) { perror("could not create thread"); } if( pthread_create( &sniffer_thread , NULL , receivemessages , (void*) new_sock) < 0) { perror("could not create thread"); } } if (client_sock < 0) { perror("accept failed"); } close(socket_desc); } void *sendmessages(void *socket_desc){ //Get the socket descriptor int sock = *(int*)socket_desc; int read_size; char node_message[2000]; char message[2000], client_message[2000]; printf("New thread created for sendmessages\n"); } void *receivemessages(void *socket_desc){ //Get the socket descriptor int sock = *(int*)socket_desc; int read_size; char node_message[2000]; char message[2000], client_message[2000]; printf("New thread created for receivemessages\n"); }
[ "pika1@umbc.edu" ]
pika1@umbc.edu
66dd7a45d01c4735fc6378e64749ceaaa8f273c9
66e586a13848fb140984102d7513406af73e8bcb
/FileUtil.h
717a2b481041fe37e9086c8d59854429d4e37945
[]
no_license
ajunlonglive/chat-2
6d11611b436896b7b21dc337c7dd0ee8ae3316aa
6fa606ecfd9c8effc95b1127c31ed8ed55794200
refs/heads/master
2023-03-15T11:43:07.915467
2016-09-05T07:01:28
2016-09-05T07:01:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,919
h
// Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // Author: Shuo Chen (chenshuo at chenshuo dot com) // // This is a public header file, it must only include public header files. #ifndef MUDUO_BASE_FILEUTIL_H #define MUDUO_BASE_FILEUTIL_H #include "StringPiece.h" #include <boost/noncopyable.hpp> namespace FileUtil { // read small file < 64KB class ReadSmallFile : boost::noncopyable { public: ReadSmallFile(StringArg filename); ~ReadSmallFile(); // return errno template<typename String> int readToString(int maxSize, String* content, int64_t* fileSize, int64_t* modifyTime, int64_t* createTime); /// Read at maxium kBufferSize into buf_ // return errno int readToBuffer(int* size); const char* buffer() const { return buf_; } static const int kBufferSize = 64*1024; private: int fd_; int err_; char buf_[kBufferSize]; }; // read the file content, returns errno if error happens. template<typename String> int readFile(StringArg filename, int maxSize, String* content, int64_t* fileSize = NULL, int64_t* modifyTime = NULL, int64_t* createTime = NULL) { ReadSmallFile file(filename); return file.readToString(maxSize, content, fileSize, modifyTime, createTime); } // not thread safe class AppendFile : boost::noncopyable { public: explicit AppendFile(StringArg filename); ~AppendFile(); void append(const char* logline, const size_t len); void flush(); size_t writtenBytes() const { return writtenBytes_; } private: size_t write(const char* logline, size_t len); FILE* fp_; char buffer_[64*1024]; size_t writtenBytes_; }; } #endif // MUDUO_BASE_FILEUTIL_H
[ "615810790@qq.com" ]
615810790@qq.com
b0b18fc5dc241cc2ce4df6afe7b5e64d23d0e62b
0adb6fe81350f912d04895977018ba1bd30109fd
/ex1.cpp
50d6f9552559bdbe23342c037249818688578278
[]
no_license
shoedog/Game-of-Life
b608bea9bd55c291819f7d011abb7243cc224561
50adc49bff6b7c92bb43589fb9559a7c84fe62c2
refs/heads/master
2021-01-10T03:17:10.650969
2015-12-22T09:10:17
2015-12-22T09:10:17
48,421,887
0
0
null
null
null
null
UTF-8
C++
false
false
11,810
cpp
/****************************************************************************** ** Program Filename: Ex1.cpp ** Author: Wesley Jinks ** Date: 1/11/2015 ** Description: The main file to implement a Game of Life. Has a menu with options to input a cell/cells, view world, insert a glider, insert a glider gun, insert a fixed simple oscillator, choose and watch number of generations pass, clear the worlf and start over, and exit. ** Input: The option in the menu, location to insert life in the world, and number of generations to watch pass and options to continue. ** Output: The game board, prompts for input, iterations of generations on the board. * ***************************************************************************/ #include <iostream> #include <cstdlib> #include <unistd.h> #include <cctype> #include "world.hpp" #include "cells.hpp" /**************************************************************************************** * Function: outputWorld( char[ROW][COL] ) * Description: loops through array, printing a 22 Row and 80 Column array to the screen * Parameters: a character array * Pre-Conditions: a character array must be passed * Post-Conditions: a 22 row and 80 column array is printed to the screen * *************************************************************************************/ void outputWorld( char[ROW][COL] ); /**************************************************************************************** * Function: inputCoords( World & ) * Description: Prompts for and gets input for row and column coordinatesn * Parameters: a world object passed by reference * Pre-Conditions: a world object must be passed * Post-Conditions: world objects row and column coordinates are updated ****************************************************************************************/ void inputCoords( World & ); /**************************************************************************************** * Function: passTime( char[ROW][COL], char[ROW][COL], Cells & ) * Description: Prompts for and gets input for number of generations to pass. * Parameters: 2 character arrays to update between generations and a Cells object * Pre-Conditions: 2 character arrays must be passed, a Cells object must be passed * Post-Conditions: character arrays are updated as generations change ****************************************************************************************/ void passTime( char[ROW][COL], char[ROW][COL], Cells & ); /**************************************************************************************** * Function: displayMenu() * Description: Outputs menu * Parameters: None * Pre-Conditions: None * Post-Conditions: A menu is output to the screen ****************************************************************************************/ void displayMenu(); int main() { World world1; //Creates a world object Cells cell; //Creates a cell object char display1[ROW][COL]; //Creates an array to display a world char display2[ROW][COL]; //Creates a second array to display a world int option; //Menu option variable char YN; //Yes or No option variable // Initialize first and second world display arrays, clear screen, and output world world1.createWorld( display1 ); world1.createWorld( display2 ); system("clear"); outputWorld( display1 ); /*Displays menu while choice does not equal 8(exit). Case 1: output world. Case 2: Add cell/cells Case 3: Add fixed simple oscillator Case 4: Add glider Case 5: Add glider gun Case 6: Choose and watch an amount of generations to pass Case 7: Clear world and start over Case 8: Exit */ do { std::cout << std::endl << std::endl << std::endl; displayMenu(); std::cout << std::endl << "Enter your choice from the menu 1-8: "; std::cin >> option; switch(option) { case 1: outputWorld(display1); break; case 2: outputWorld(display1); do { std::cout << std::endl; inputCoords( world1 ); world1.addLife( display1, world1.getRCoord(), world1.getCCoord() ); world1.copyWorldState( display1, display2 ); outputWorld( display1 ); std::cout << std::endl << "Add another cell (Y/N)? "; std::cin >> YN; YN = toupper(YN); }while( YN == 'Y' ); break; case 3: std::cout << std::endl; inputCoords( world1 ); cell.createLFSO( display1, world1.getRCoord(), world1.getCCoord() ); outputWorld( display1 ); world1.copyWorldState( display1, display2 ); break; case 4: std::cout << std::endl; inputCoords( world1 ); cell.createGlider( display1, world1.getRCoord(), world1.getCCoord() ); world1.copyWorldState( display1, display2 ); outputWorld( display1 ); break; case 5: std::cout << std::endl; inputCoords( world1 ); cell.createGliderGun( display1, world1.getRCoord(), world1.getCCoord() ); world1.copyWorldState( display1, display2); outputWorld( display1 ); break; case 6: if( cell.getCurrentGeneration() == 0 ) world1.copyWorldState( display1, display2 ); else if( cell.getCurrentGeneration() == 1 ) world1.copyWorldState( display1, display2 ); passTime( display1, display2, cell ); break; case 7: std::cout << std::endl << "World Cleared. " << std::endl; world1.createWorld( display1 ); world1.createWorld( display2 ); outputWorld( display1 ); break; case 8: std::cout << "Exiting..." << std::endl; break; default: std::cout << "You did not enter a valid choice. Enter option 1-8. " << std::endl; } }while( option != 8 ); return 0; } /**************************************************************************************** * Function: displayMenu() * Description: Outputs menu * Parameters: None * Pre-Conditions: None * Post-Conditions: A menu is output to the screen ****************************************************************************************/ void displayMenu() { std::cout << "********* Welcome to the Game of Life *********" << std::endl; std::cout << "* *" << std::endl; std::cout << "* ** Menu ** *" << std::endl; std::cout << "* *" << std::endl; std::cout << "* 1: See World *" << std::endl; std::cout << "* 2: Add Cell/Cells *" << std::endl; std::cout << "* 3: Add Fixed Simple Oscillator *" << std::endl; std::cout << "* 4: Add Glider *" << std::endl; std::cout << "* 5: Add Glider Gun *" << std::endl; std::cout << "* 6: Watch Time Pass *" << std::endl; std::cout << "* 7: Clear World and Start Over *" << std::endl; std::cout << "* 8: Exit *" << std::endl; std::cout << "* *" << std::endl; std::cout << "***********************************************" << std::endl; } /**************************************************************************************** * Function: outputWorld( char[ROW][COL] ) * Description: loops through array, printing a 22 Row and 80 Column array to the screen * Parameters: a character array * Pre-Conditions: a character array must be passed * Post-Conditions: a 22 row and 80 column array is printed to the screen * *************************************************************************************/ void outputWorld( char arr[ROW][COL] ) { system("clear"); for( int i = 21; i < ROW-23; i++ ) { std::cout << std::endl; for( int j = 79; j < COL-81; j++ ) std::cout << arr[i][j]; } } /**************************************************************************************** * Function: inputCoords( World & ) * Description: Prompts for and gets input for row and column coordinatesn * Parameters: a world object passed by reference * Pre-Conditions: a world object must be passed * Post-Conditions: world objects row and column coordinates are updated ****************************************************************************************/ void inputCoords( World &view ) { int row; //row coordinate int col; //column coordinate bool rowFlag = 1; //Tests to see if coordinates are within range bool colFlag = 1; //Tests to see if coordinates are within range //Prompt for, get input, and validate input. do { std::cout << "Enter coordinates for a cell. " << std::endl; std::cout << "Enter Row Number 1-22: "; std::cin >> row; std::cout << "Enter Column Number 1-80: "; std::cin >> col; if( row < 1 || row > 22 ) { rowFlag = 0; std::cout << "Row input must be between 1 and 22." << std::endl; } else rowFlag = 1; if( col < 1 || col > 80 ) { colFlag = 0; std::cout << "Column input must be between 1 and 80." << std::endl; } else colFlag = 1; }while( rowFlag == 0 || colFlag == 0 ); //Shifts row and column input to be in visible 22 Row and 80 Column display row += 20; col += 78; view.setRCoord( row ); view.setCCoord( col ); } /**************************************************************************************** * Function: passTime( char[ROW][COL], char[ROW][COL], Cells & ) * Description: Prompts for and gets input for number of generations to pass, outputs * the changes in generations to the screen * Parameters: 2 character arrays to update between generations and a Cells object * Pre-Conditions: 2 character arrays must be passed, a Cells object must be passed * Post-Conditions: character arrays are updated as generations change and output to * the screen ****************************************************************************************/ void passTime( char world1[ROW][COL], char world2[ROW][COL], Cells &cell ) { char YN; int speed; /* * Prompts for, gets, and validates input for the number of generations and the speed * to watch them pass. * Pauses based on user input between each generation. Update world based on cell * newGeneration() function and outputs new world to screen. * Gives option to input and watch more generations */ do { int generations = 0; std::cout << "How many generations would you like to pass? "; std::cin >> generations; while( generations <= 0 ) { std::cout << "The number of generations must be a positive integer. " << std::endl; std::cout << "How many generations would you like to pass? "; std::cin >> generations; } std::cout << std::endl; std::cout << "How fast would you like to see them change? Enter 1 for slow, " << "2 for medium, and 3 for fast: "; std::cin >> speed; std::cout << std::endl; while( speed < 1 || speed > 3 ) { std::cout << "Speed can only be slow, medium, or fast. Enter 1 for slow, " << "2 for medium, or 3 for fast. " << std::endl << "Enter speed: "; std::cin >> speed; } for( int i = 0; i < generations; i++ ) { if( speed == 1 ) usleep(100000); else if( speed == 2 ) usleep(70000); else if( speed == 3 ) usleep(40000); cell.advanceGeneration( world1, world2 ); // cell.newGeneration( world1, world2 ); if( cell.getCurrentGeneration() == 1 ) { outputWorld( world2 ); // std::cout << "World2"; //Test for which array is output } else if( cell.getCurrentGeneration() == 0 ) { outputWorld( world1 ); // std::cout << "World1"; //Test for which array is output } // std::cout << cell.getWorldCheck(); //Test to see if worlds are switchin std::cout << std::endl; } std::cout << std::endl << "Would you like to see more generations (Y/N)? "; std::cin >> YN; YN = toupper( YN ); }while( YN != 'N' ); }
[ "jinksw@flip2.engr.oregonstate.edu" ]
jinksw@flip2.engr.oregonstate.edu
5a8d38c7f71f54d2f4f2817f50df4657befffd23
e8081684aa867947f91b8592900329bcd66e8540
/src/psc_harris_xz.cxx
8117dfb29d84a59d36f406bf4341c4c8aa27fcb2
[]
no_license
QJohn2017/psc
9ec3363d4400f911c838093917275be6177df758
ffbcc3be154337780a15b343fecb9d48c389ac6d
refs/heads/master
2023-03-02T05:21:35.787589
2020-10-04T23:48:37
2020-10-04T23:48:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,559
cxx
#define VPIC 1 #include <psc.hxx> #include <setup_fields.hxx> #include <setup_particles.hxx> #include "../libpsc/vpic/fields_item_vpic.hxx" #include "../libpsc/vpic/setup_fields_vpic.hxx" #include "OutputFieldsDefault.h" #include "psc_config.hxx" #include "rngpool_iface.h" extern Grid* vgrid; // FIXME static RngPool* rngpool; // FIXME, should be member (of struct psc, really) // FIXME, helper should go somewhere... static inline double trunc_granular(double a, double b) { return b * (int)(a / b); } // ====================================================================== // PSC configuration // // This sets up compile-time configuration for the code, in particular // what data structures and algorithms to use // // EDIT to change order / floating point type / cuda / 2d/3d #ifdef VPIC #ifdef DO_VPIC using PscConfig = PscConfigVpicWrap; #else using PscConfig = PscConfigVpicPsc; #endif #else using PscConfig = PscConfig1vbecSingle<dim_xz>; #endif // ---------------------------------------------------------------------- using MfieldsState = typename PscConfig::MfieldsState; #ifdef VPIC using MaterialList = typename MfieldsState::MaterialList; #endif using Mparticles = typename PscConfig::Mparticles; using Balance = typename PscConfig::Balance; using Collision = typename PscConfig::Collision; using Checks = typename PscConfig::Checks; using Marder = typename PscConfig::Marder; using OutputParticles = PscConfig::OutputParticles; // FIXME! MfieldsC evalMfields(const MfieldsState& _exp) { auto& exp = const_cast<MfieldsState&>(_exp); MfieldsC mflds{exp.grid(), exp.n_comps(), exp.ibn()}; for (int p = 0; p < mflds.n_patches(); p++) { auto flds = mflds[p]; for (int m = 0; m < exp.n_comps(); m++) { mflds.Foreach_3d(0, 0, [&](int i, int j, int k) { flds(m, i, j, k) = exp[p](m, i, j, k); }); } } return mflds; } // ====================================================================== // PscHarrisParams struct PscHarrisParams { double L_di; // Sheet thickness / ion inertial length double Ti_Te; // Ion temperature / electron temperature double nb_n0; // background plasma density double Tbe_Te; // Ratio of background T_e to Harris T_e double Tbi_Ti; // Ratio of background T_i to Harris T_i double bg; // Guide field double theta; double Lpert_Lx; // wavelength of perturbation in terms of Lx double dbz_b0; // perturbation in Bz relative to B0 double nppc; // Average number of macro particle per cell per species bool open_bc_x; // Flag to signal we want to do open boundary condition in x bool driven_bc_z; // Flag to signal we want to do driven boundary condition in z // FIXME, not really harris-specific double wpedt_max; double wpe_wce; // electron plasma freq / electron cyclotron freq double mi_me; // Ion mass / electron mass double Lx_di, Ly_di, Lz_di; // Size of box in d_i int ion_sort_interval; int electron_sort_interval; double taui; // simulation wci's to run double t_intervali; // output interval in terms of 1/wci double output_particle_interval; // particle output interval in terms of 1/wci double overalloc; // Overallocation factor (> 1) for particle arrays Int3 gdims; Int3 np; }; // ====================================================================== // Global parameters // // I'm not a big fan of global parameters, but they're only for // this particular case and they help make things simpler. // An "anonymous namespace" makes these variables visible in this source file // only namespace { // Parameters specific to this case. They don't really need to be collected in a // struct, but maybe it's nice that they are PscHarrisParams g; std::string read_checkpoint_filename; // This is a set of generic PSC params (see include/psc.hxx), // like number of steps to run, etc, which also should be set by the case PscParams psc_params; } // namespace // ====================================================================== // setupHarrisParams() void setupHarrisParams() { g.wpedt_max = .36; g.wpe_wce = 2.; g.mi_me = 25.; g.Lx_di = 40.; g.Ly_di = 1.; g.Lz_di = 10.; g.electron_sort_interval = 25; g.ion_sort_interval = 25; g.taui = 40.; g.t_intervali = 1.; g.output_particle_interval = 10.; g.overalloc = 2.; g.gdims = {512, 1, 128}; g.np = {4, 1, 1}; g.L_di = .5; g.Ti_Te = 5.; g.nb_n0 = .05; g.Tbe_Te = .333; g.Tbi_Ti = .333; g.bg = 0.; g.theta = 0.; g.Lpert_Lx = 1.; g.dbz_b0 = .03; g.nppc = 10; g.open_bc_x = false; g.driven_bc_z = false; } // ====================================================================== // globals_physics // // FIXME rename / merge? struct globals_physics { double ec; double me; double c; double eps0; double de; double mi; double di; double wpe; double wpi; double wce; double wci; // calculated double b0; // B0 double n0; double v_A; double rhoi_L; double Lx, Ly, Lz; // size of box double L; // Harris sheet thickness double Lpert; // wavelength of perturbation double dbx; // Perturbation in Bz relative to Bo (Only change here) double dbz; // Set Bx perturbation so that div(B) = 0 double tanhf; double Ne; // Total number of macro electrons double Ne_sheet; // Number of macro electrons in Harris sheet double weight_s; // Charge per macro electron double vthe; // Electron thermal velocity double vthi; // Ion thermal velocity double vdre; // Electron drift velocity double vdri; // Ion drift velocity double gdri; // gamma of ion drift frame double gdre; // gamma of electron drift frame double udri; // 4-velocity of ion drift frame double udre; // 4-velocity of electron drift frame double Ne_back; // Number of macro electrons in background double weight_b; // Charge per macro electron double vtheb; // normalized background e thermal vel. double vthib; // normalized background ion thermal vel. int n_global_patches; // ---------------------------------------------------------------------- // ctor // FIXME, do we want to keep this? globals_physics() {} globals_physics(const PscHarrisParams& p) { assert(p.np[2] <= 2); // For load balance, keep "1" or "2" for Harris sheet // FIXME, the general normalization stuff should be shared somehow // use natural PIC units ec = 1; // Charge normalization me = 1; // Mass normalization c = 1; // Speed of light de = 1; // Length normalization (electron inertial length) eps0 = 1; // Permittivity of space // derived quantities mi = me * p.mi_me; // Ion mass double Te = me * sqr(c) / (2. * eps0 * sqr(p.wpe_wce) * (1. + p.Ti_Te)); // Electron temperature double Ti = Te * p.Ti_Te; // Ion temperature vthe = sqrt(Te / me); // Electron thermal velocity vthi = sqrt(Ti / mi); // Ion thermal velocity vtheb = sqrt(p.Tbe_Te * Te / me); // normalized background e thermal vel. vthib = sqrt(p.Tbi_Ti * Ti / mi); // normalized background ion thermal vel. wci = 1. / (p.mi_me * p.wpe_wce); // Ion cyclotron frequency wce = wci * p.mi_me; // Electron cyclotron freqeuncy wpe = wce * p.wpe_wce; // electron plasma frequency wpi = wpe / sqrt(p.mi_me); // ion plasma frequency di = c / wpi; // ion inertial length L = p.L_di * di; // Harris sheet thickness rhoi_L = sqrt(p.Ti_Te / (1. + p.Ti_Te)) / p.L_di; v_A = (wci / wpi) / sqrt(p.nb_n0); // based on nb Lx = p.Lx_di * di; // size of box in x dimension Ly = p.Ly_di * di; // size of box in y dimension Lz = p.Lz_di * di; // size of box in z dimension b0 = me * c * wce / ec; // Asymptotic magnetic field strength n0 = me * eps0 * wpe * wpe / (ec * ec); // Peak electron (ion) density vdri = 2 * c * Ti / (ec * b0 * L); // Ion drift velocity vdre = -vdri / (p.Ti_Te); // electron drift velocity n_global_patches = p.np[0] * p.np[1] * p.np[2]; double Npe_sheet = 2 * n0 * Lx * Ly * L * tanh(0.5 * Lz / L); // N physical e's in sheet double Npe_back = p.nb_n0 * n0 * Ly * Lz * Lx; // N physical e's in backgrnd double Npe = Npe_sheet + Npe_back; Ne = p.nppc * p.gdims[0] * p.gdims[1] * p.gdims[2]; // total macro electrons in box Ne_sheet = Ne * Npe_sheet / Npe; Ne_back = Ne * Npe_back / Npe; Ne_sheet = trunc_granular( Ne_sheet, n_global_patches); // Make it divisible by # subdomains Ne_back = trunc_granular( Ne_back, n_global_patches); // Make it divisible by # subdomains Ne = Ne_sheet + Ne_back; weight_s = ec * Npe_sheet / Ne_sheet; // Charge per macro electron weight_b = ec * Npe_back / Ne_back; // Charge per macro electron gdri = 1. / sqrt(1. - sqr(vdri) / sqr(c)); // gamma of ion drift frame gdre = 1. / sqrt(1. - sqr(vdre) / sqr(c)); // gamma of electron drift frame udri = vdri * gdri; // 4-velocity of ion drift frame udre = vdre * gdre; // 4-velocity of electron drift frame tanhf = tanh(0.5 * Lz / L); Lpert = p.Lpert_Lx * Lx; // wavelength of perturbation dbz = p.dbz_b0 * b0; // Perturbation in Bz relative to Bo (Only change here) dbx = -dbz * Lpert / (2. * Lz); // Set Bx perturbation so that div(B) = 0 } }; globals_physics phys; // ====================================================================== // setupGrid // // This helper function is responsible for setting up the "Grid", // which is really more than just the domain and its decomposition, it // also encompasses PC normalization parameters, information about the // particle kinds, etc. Grid_t* setupGrid() { auto comm = MPI_COMM_WORLD; // --- set up domain auto domain = Grid_t::Domain{g.gdims, {phys.Lx, phys.Ly, phys.Lz}, {0., -.5 * phys.Ly, -.5 * phys.Lz}, g.np}; mpi_printf(comm, "Conducting fields on Z-boundaries\n"); mpi_printf(comm, "Reflect particles on Z-boundaries\n"); auto bc = psc::grid::BC{{BND_FLD_PERIODIC, BND_FLD_PERIODIC, BND_FLD_CONDUCTING_WALL}, {BND_FLD_PERIODIC, BND_FLD_PERIODIC, BND_FLD_CONDUCTING_WALL}, {BND_PRT_PERIODIC, BND_PRT_PERIODIC, BND_PRT_REFLECTING}, {BND_PRT_PERIODIC, BND_PRT_PERIODIC, BND_PRT_REFLECTING}}; if (g.open_bc_x) { mpi_printf(comm, "Absorbing fields on X-boundaries\n"); bc.fld_lo[0] = BND_FLD_ABSORBING; bc.fld_hi[0] = BND_FLD_ABSORBING; mpi_printf(comm, "Absorb particles on X-boundaries\n"); bc.prt_lo[1] = BND_PRT_ABSORBING; bc.prt_hi[1] = BND_PRT_ABSORBING; } if (g.driven_bc_z) { mpi_printf(comm, "Absorb particles on Z-boundaries\n"); bc.prt_lo[2] = BND_PRT_ABSORBING; bc.prt_hi[2] = BND_PRT_ABSORBING; } auto kinds = Grid_t::Kinds(NR_KINDS); kinds[KIND_ELECTRON] = {-phys.ec, phys.me, "e"}; kinds[KIND_ION] = {phys.ec, phys.mi, "i"}; // determine the time step double dg = courant_length(domain); double dt = psc_params.cfl * dg / phys.c; // courant limited time step if (phys.wpe * dt > g.wpedt_max) { dt = g.wpedt_max / phys.wpe; // override timestep if plasma frequency limited } assert(phys.c == 1. && phys.eps0 == 1.); auto norm_params = Grid_t::NormalizationParams::dimensionless(); norm_params.nicell = 1; auto norm = Grid_t::Normalization{norm_params}; #ifdef VPIC Int3 ibn = {1, 1, 1}; #else Int3 ibn = {2, 2, 2}; if (Dim::InvarX::value) { ibn[0] = 0; } if (Dim::InvarY::value) { ibn[1] = 0; } if (Dim::InvarZ::value) { ibn[2] = 0; } #endif auto grid_ptr = new Grid_t{domain, bc, kinds, norm, dt, -1, ibn}; vpic_define_grid(*grid_ptr); return grid_ptr; } // ---------------------------------------------------------------------- // setupMaterials void setupMaterials(MaterialList& material_list) { MPI_Comm comm = MPI_COMM_WORLD; mpi_printf(comm, "Setting up materials.\n"); // -- set up MaterialList vpic_define_material(material_list, "vacuum", 1., 1., 0., 0.); #if 0 struct material *resistive = vpic_define_material(material_list, "resistive", 1., 1., 1., 0.); #endif // Note: define_material defaults to isotropic materials with mu=1,sigma=0 // Tensor electronic, magnetic and conductive materials are supported // though. See "shapes" for how to define them and assign them to regions. // Also, space is initially filled with the first material defined. } // ---------------------------------------------------------------------- // vpic_setup_species // // FIXME, half-redundant to the PSC species setup void vpic_setup_species(Mparticles& mprts) { mpi_printf(mprts.grid().comm(), "Setting up species.\n"); double nmax = g.overalloc * phys.Ne / phys.n_global_patches; double nmovers = .1 * nmax; double sort_method = 1; // 0=in place and 1=out of place mprts.define_species("electron", -phys.ec, phys.me, nmax, nmovers, g.electron_sort_interval, sort_method); mprts.define_species("ion", phys.ec, phys.mi, nmax, nmovers, g.ion_sort_interval, sort_method); } // ---------------------------------------------------------------------- // setup_log void setup_log(const Grid_t& grid) { MPI_Comm comm = grid.comm(); mpi_printf(comm, "***********************************************\n"); mpi_printf(comm, "* Topology: %d x %d x %d\n", g.np[0], g.np[1], g.np[2]); mpi_printf(comm, "tanhf = %g\n", phys.tanhf); mpi_printf(comm, "L_di = %g\n", g.L_di); mpi_printf(comm, "rhoi/L = %g\n", phys.rhoi_L); mpi_printf(comm, "Ti/Te = %g\n", g.Ti_Te); mpi_printf(comm, "nb/n0 = %g\n", g.nb_n0); mpi_printf(comm, "wpe/wce = %g\n", g.wpe_wce); mpi_printf(comm, "mi/me = %g\n", g.mi_me); mpi_printf(comm, "theta = %g\n", g.theta); mpi_printf(comm, "Lpert/Lx = %g\n", g.Lpert_Lx); mpi_printf(comm, "dbz/b0 = %g\n", g.dbz_b0); mpi_printf(comm, "taui = %g\n", g.taui); mpi_printf(comm, "t_intervali = %g\n", g.t_intervali); mpi_printf(comm, "num_step = %d\n", psc_params.nmax); mpi_printf(comm, "Lx/di = %g\n", phys.Lx / phys.di); mpi_printf(comm, "Lx/de = %g\n", phys.Lx / phys.de); mpi_printf(comm, "Ly/di = %g\n", phys.Ly / phys.di); mpi_printf(comm, "Ly/de = %g\n", phys.Ly / phys.de); mpi_printf(comm, "Lz/di = %g\n", phys.Lz / phys.di); mpi_printf(comm, "Lz/de = %g\n", phys.Lz / phys.de); mpi_printf(comm, "nx = %d\n", g.gdims[0]); mpi_printf(comm, "ny = %d\n", g.gdims[1]); mpi_printf(comm, "nz = %d\n", g.gdims[2]); mpi_printf(comm, "n_global_patches = %d\n", phys.n_global_patches); mpi_printf(comm, "nppc = %g\n", g.nppc); mpi_printf(comm, "b0 = %g\n", phys.b0); mpi_printf(comm, "v_A (based on nb) = %g\n", phys.v_A); mpi_printf(comm, "di = %g\n", phys.di); mpi_printf(comm, "Ne = %g\n", phys.Ne); mpi_printf(comm, "Ne_sheet = %g\n", phys.Ne_sheet); mpi_printf(comm, "Ne_back = %g\n", phys.Ne_back); mpi_printf(comm, "total # of particles = %g\n", 2 * phys.Ne); mpi_printf(comm, "dt*wpe = %g\n", phys.wpe * grid.dt); mpi_printf(comm, "dt*wce = %g\n", phys.wce * grid.dt); mpi_printf(comm, "dt*wci = %g\n", phys.wci * grid.dt); mpi_printf(comm, "dx/de = %g\n", phys.Lx / (phys.de * g.gdims[0])); mpi_printf(comm, "dy/de = %g\n", phys.Ly / (phys.de * g.gdims[1])); mpi_printf(comm, "dz/de = %g\n", phys.Lz / (phys.de * g.gdims[2])); mpi_printf(comm, "dx/rhoi = %g\n", (phys.Lx / g.gdims[0]) / (phys.vthi / phys.wci)); mpi_printf(comm, "dx/rhoe = %g\n", (phys.Lx / g.gdims[0]) / (phys.vthe / phys.wce)); mpi_printf(comm, "L/debye = %g\n", phys.L / (phys.vthe / phys.wpe)); mpi_printf(comm, "dx/debye = %g\n", (phys.Lx / g.gdims[0]) / (phys.vthe / phys.wpe)); mpi_printf(comm, "n0 = %g\n", phys.n0); mpi_printf(comm, "vthi/c = %g\n", phys.vthi / phys.c); mpi_printf(comm, "vthe/c = %g\n", phys.vthe / phys.c); mpi_printf(comm, "vdri/c = %g\n", phys.vdri / phys.c); mpi_printf(comm, "vdre/c = %g\n", phys.vdre / phys.c); mpi_printf(comm, "Open BC in x? = %d\n", g.open_bc_x); mpi_printf(comm, "Driven BC in z? = %d\n", g.driven_bc_z); } // ====================================================================== // Diagnostics class Diagnostics { public: Diagnostics(OutputFields& outf, OutputParticles& outp, DiagEnergies& oute) : outf_{outf}, outp_{outp}, oute_{oute} { io_pfd_.open("pfd"); } void operator()(Mparticles& mprts, MfieldsState& mflds) { vpic_run_diagnostics(mprts, mflds); const auto& grid = mprts.grid(); MPI_Comm comm = grid.comm(); int timestep = grid.timestep(); if (outf_.pfield_interval > 0 && timestep % outf_.pfield_interval == 0) { mpi_printf(comm, "***** Writing PFD output\n"); io_pfd_.begin_step(grid); { OutputFieldsVpic<MfieldsState> out_fields; auto result = out_fields(mflds); io_pfd_.write(result.mflds, grid, result.name, result.comp_names); } { // FIXME, would be better to keep "out_hydro" around OutputHydro out_hydro{grid}; auto result = out_hydro(mprts, *hydro, *interpolator); io_pfd_.write(result.mflds, grid, result.name, result.comp_names); } io_pfd_.end_step(); } psc_stats_start(st_time_output); outp_(mprts); psc_stats_stop(st_time_output); #ifndef VPIC oute_(mprts, mflds); #endif } private: WriterMRC io_pfd_; OutputFields& outf_; OutputParticles& outp_; DiagEnergies& oute_; }; // ---------------------------------------------------------------------- // setup_particles // // set particles x^{n+1/2}, p^{n+1/2} void setup_particles(Mparticles& mprts, std::vector<uint>& nr_particles_by_patch, bool count_only) { const auto& grid = mprts.grid(); MPI_Comm comm = grid.comm(); double cs = cos(g.theta), sn = sin(g.theta); double Ne_sheet = phys.Ne_sheet, vthe = phys.vthe, vthi = phys.vthi; int n_global_patches = phys.n_global_patches; double weight_s = phys.weight_s; double tanhf = phys.tanhf, L = phys.L; double gdre = phys.gdre, udre = phys.udre, gdri = phys.gdri, udri = phys.udri; double Ne_back = phys.Ne_back, vtheb = phys.vtheb, vthib = phys.vthib; double weight_b = phys.weight_b; if (count_only) { for (int p = 0; p < grid.n_patches(); p++) { nr_particles_by_patch[p] = 2 * (Ne_sheet / n_global_patches + Ne_back / n_global_patches); } return; } // LOAD PARTICLES mpi_printf(comm, "Loading particles\n"); // Do a fast load of the particles rngpool = RngPool_create(); // FIXME, should be part of ctor (of struct psc, really) int rank; MPI_Comm_rank(comm, &rank); RngPool_seed(rngpool, rank); Rng* rng = RngPool_get(rngpool, 0); assert(grid.n_patches() > 0); const Grid_t::Patch& patch = grid.patches[0]; double xmin = patch.xb[0], xmax = patch.xe[0]; double ymin = patch.xb[1], ymax = patch.xe[1]; double zmin = patch.xb[2], zmax = patch.xe[2]; // Load Harris population { auto inj = mprts.injector(); auto injector = inj[0]; mpi_printf(comm, "-> Main Harris Sheet\n"); for (int64_t n = 0; n < Ne_sheet / n_global_patches; n++) { double x, y, z, ux, uy, uz, d0; do { z = L * atanh(Rng_uniform(rng, -1., 1.) * tanhf); } while (z <= zmin || z >= zmax); x = Rng_uniform(rng, xmin, xmax); y = Rng_uniform(rng, ymin, ymax); // inject_particles() will return an error for particles not on this // node and will not inject particle locally ux = Rng_normal(rng, 0, vthe); uy = Rng_normal(rng, 0, vthe); uz = Rng_normal(rng, 0, vthe); d0 = gdre * uy + sqrt(ux * ux + uy * uy + uz * uz + 1) * udre; uy = d0 * cs - ux * sn; ux = d0 * sn + ux * cs; injector.reweight(psc::particle::Inject{ {x, y, z}, {ux, uy, uz}, weight_s, KIND_ELECTRON}); ux = Rng_normal(rng, 0, vthi); uy = Rng_normal(rng, 0, vthi); uz = Rng_normal(rng, 0, vthi); d0 = gdri * uy + sqrt(ux * ux + uy * uy + uz * uz + 1) * udri; uy = d0 * cs - ux * sn; ux = d0 * sn + ux * cs; injector.reweight( psc::particle::Inject{{x, y, z}, {ux, uy, uz}, weight_s, KIND_ION}); } mpi_printf(comm, "-> Background Population\n"); for (int64_t n = 0; n < Ne_back / n_global_patches; n++) { Double3 pos{Rng_uniform(rng, xmin, xmax), Rng_uniform(rng, ymin, ymax), Rng_uniform(rng, zmin, zmax)}; Double3 u{Rng_normal(rng, 0, vtheb), Rng_normal(rng, 0, vtheb), Rng_normal(rng, 0, vtheb)}; injector.reweight(psc::particle::Inject{pos, u, weight_b, KIND_ELECTRON}); u = {Rng_normal(rng, 0, vthib), Rng_normal(rng, 0, vthib), Rng_normal(rng, 0, vthib)}; injector.reweight(psc::particle::Inject{pos, u, weight_b, KIND_ION}); } } mpi_printf(comm, "Finished loading particles\n"); } // ====================================================================== // initializeParticles void initializeParticles(Balance& balance, Grid_t*& grid_ptr, Mparticles& mprts) { auto comm = grid_ptr->comm(); mpi_printf(comm, "**** Partitioning...\n"); std::vector<uint> n_prts_by_patch(mprts.n_patches()); setup_particles(mprts, n_prts_by_patch, true); balance.initial(grid_ptr, n_prts_by_patch); mprts.reset(*grid_ptr); mpi_printf(comm, "**** Setting up particles...\n"); mprts.reserve_all(n_prts_by_patch); setup_particles(mprts, n_prts_by_patch, false); } // ====================================================================== // initializeFields void initializeFields(MfieldsState& mflds) { double b0 = phys.b0, dbx = phys.dbx, dbz = phys.dbz; double L = phys.L, Lx = phys.Lx, Lz = phys.Lz, Lpert = phys.Lpert; double cs = cos(g.theta), sn = sin(g.theta); setupFields(mflds, [&](int m, double crd[3]) { double x = crd[0], z = crd[2]; switch (m) { case HX: return cs * b0 * tanh(z / L) + dbx * cos(2. * M_PI * (x - .5 * Lx) / Lpert) * sin(M_PI * z / Lz); case HY: return -sn * b0 * tanh(z / L) + b0 * g.bg; case HZ: return dbz * cos(M_PI * z / Lz) * sin(2.0 * M_PI * (x - 0.5 * Lx) / Lpert); case JYI: return 0.; // FIXME default: return 0.; } }); } // ====================================================================== // run void run() { auto comm = MPI_COMM_WORLD; mpi_printf(comm, "*** Setting up simulation\n"); setupHarrisParams(); phys = globals_physics{g}; psc_params.cfl = 0.99; psc_params.stats_every = 100; // ---------------------------------------------------------------------- // Set up grid, state fields, particles auto grid_ptr = setupGrid(); auto& grid = *grid_ptr; psc_params.nmax = int(g.taui / (phys.wci * grid.dt)); // number of steps from taui // --- create Simulation #if 0 // set high level VPIC simulation parameters // FIXME, will be unneeded eventually setParams(psc_params.nmax, psc_params.stats_every, psc_params.stats_every / 2, psc_params.stats_every / 2, psc_params.stats_every / 2); #endif // --- setup field data structure #ifdef VPIC // --- setup materials MaterialList material_list; setupMaterials(material_list); // FIXME, mv assert into MfieldsState ctor assert(!material_list.empty()); double damp = 0.; MfieldsState mflds{grid, vgrid, material_list, damp}; vpic_define_fields(grid); #else MfieldsState mflds{grid}; #endif mpi_printf(comm, "*** Finalizing Field Advance\n"); #if 0 assert(grid.nr_patches() > 0); Simulation_set_region_resistive_harris(sub->sim, &sub->prm, phys, psc_->patch[0].dx, 0., resistive); #endif /// --- setup particle data structure #ifdef VPIC Mparticles mprts{grid, vgrid}; vpic_setup_species(mprts); #else Mparticles mprts{grid}; #endif // -- Balance psc_params.balance_interval = 0; Balance balance{psc_params.balance_interval}; // -- Sort // FIXME: the "vpic" sort actually keeps track of per-species sorting // intervals internally, so it needs to be called every step #ifdef VPIC psc_params.sort_interval = 1; #endif // -- Collision int collision_interval = 0; double collision_nu = .1; // FIXME, != 0 needed to avoid crash Collision collision{grid, collision_interval, collision_nu}; // -- Checks ChecksParams checks_params{}; Checks checks{grid, comm, checks_params}; // -- Marder correction // FIXME, these are ignored for vpic (?) double marder_diffusion = 0.9; int marder_loop = 3; bool marder_dump = false; // FIXME, how do we make sure that we don't forget to set this? // (maybe make it part of the Marder object, or provide a base class // interface define_marder() that takes the object and the interval #ifdef VPIC psc_params.marder_interval = 1; #else psc_params.marder_interval = 0; #endif #if 0 // FIXME, marder "vpic" manages its own cleaning intervals psc_marder_set_param_int(psc_->marder, "every_step", 1); psc_marder_set_param_int(psc_->marder, "clean_div_e_interval", 50); psc_marder_set_param_int(psc_->marder, "clean_div_b_interval", 50); psc_marder_set_param_int(psc_->marder, "sync_shared_interval", 50); psc_marder_set_param_int(psc_->marder, "num_div_e_round", 2); psc_marder_set_param_int(psc_->marder, "num_div_b_round", 2); #endif Marder marder(grid, marder_diffusion, marder_loop, marder_dump); // -- output fields OutputFieldsParams outf_params; double output_field_interval = 1.; outf_params.pfield_interval = int((output_field_interval / (phys.wci * grid.dt))); OutputFields outf{grid, outf_params}; OutputParticlesParams outp_params{}; outp_params.every_step = int((g.output_particle_interval / (phys.wci * grid.dt))); outp_params.data_dir = "."; outp_params.basename = "prt"; outp_params.lo = {192, 0, 48}; outp_params.hi = {320, 0, 80}; OutputParticles outp{grid, outp_params}; int oute_interval = 100; DiagEnergies oute{grid.comm(), oute_interval}; Diagnostics diagnostics{outf, outp, oute}; // --- int interval = int(g.t_intervali / (phys.wci * grid.dt)); vpic_create_diagnostics(interval); vpic_setup_diagnostics(); setup_log(grid); mpi_printf(comm, "*** Finished with user-specified initialization ***\n"); // ---------------------------------------------------------------------- initializeParticles(balance, grid_ptr, mprts); initializeFields(mflds); // ---------------------------------------------------------------------- // hand off to PscIntegrator to run the simulation auto psc = makePscIntegrator<PscConfig>(psc_params, *grid_ptr, mflds, mprts, balance, collision, checks, marder, diagnostics); #if 0 // FIXME, checkpoint reading should be moved to before the integrator if (!read_checkpoint_filename.empty()) { mpi_printf(MPI_COMM_WORLD, "**** Reading checkpoint...\n"); psc.read_checkpoint(read_checkpoint_filename); } #endif psc.integrate(); } // ====================================================================== // main int main(int argc, char** argv) { psc_init(argc, argv); run(); psc_finalize(); return 0; }
[ "kai.germaschewski@unh.edu" ]
kai.germaschewski@unh.edu
1a41a7e5bccb12700b6cdf4f4b3cb4203ed96a51
f67bec1896bd19dd602b76fec785c9af4defd1a8
/modules/xnet/src/xnetcache.cpp
bf85a9b21f19dc3ae34381ac2ba95c00e408182b
[]
no_license
dharc/Cadence-Embedded
2dab66bcc499f46f1ee990c40906790204df9450
bd9df11edc114ba00386b439791eb9f9a549aec2
refs/heads/master
2016-09-06T04:35:49.923343
2013-04-22T11:22:39
2013-04-22T11:22:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,377
cpp
#include "xnetcache.h" #include "xnetconnection.h" #include "xnetprotocol.h" using namespace cadence; using namespace cadence::core; XNetCache::XNetCache(XNetConnection *conn) : Handler(OID::local()+OID(0,0,16,0), OID::local()+OID(0,0,17,0xFFFFFFF)) { for (int i=0; i<CACHE_SIZE; i++) m_cache[i] = 0; m_conn = conn; } XNetCache::~XNetCache() { } CacheEntry *XNetCache::lookup(const OID &n, const OID &e) { int hash = hashOIDS(n,e); CacheEntry *res = m_cache[hash]; while (res != 0 && ((res->n != n) || (res->e != e))) res = res->next; if (res == 0) { res = new CacheEntry; res->n = n; res->e = e; res->out_of_date = true; res->next = m_cache[hash]; m_cache[hash] = res; } return res; } int XNetCache::lookupCount(CacheEntry *e, int hash) { CacheEntry *r = m_cache[hash]; int count = 0; while ((r != 0) && (r != e)) { count++; r = r->next; } return count; } const OID &XNetCache::get(const OID &n, const OID &e) { CacheEntry *ent = lookup(n,e); if (ent->out_of_date) { Event *evt = new Event(Event::GET, n); evt->param<0>(e); //Also need to add dependency int hash = hashOIDS(n,e); int count = lookupCount(ent,hash); Event *evt2 = new Event(Event::ADDDEP, n); evt2->param<0>(e); evt2->param<1>(OID::local()+OID(0,0,16,(hash << 8) + count)); m_conn->protocol()->begin(); m_conn->protocol()->event(*evt2, 0); int id = m_conn->protocol()->event(*evt, XNetProtocol::EFLAG_WAITRESULT); m_conn->protocol()->end(); delete evt; delete evt2; while (m_conn->protocol()->wait(id)) { XNetConnection::update(); } ent->value = m_conn->protocol()->getResult(id); ent->out_of_date = false; } else { //std::cout << "USING CACHE\n"; } return ent->value; } bool XNetCache::handle(Event &evt) { int count = evt.dest().d() & 0xFF; int hash = evt.dest().d() >> 8; CacheEntry *ent = m_cache[hash]; while ((ent != 0) && (count > 0)) { ent = ent->next; count --; } ent->out_of_date = true; /*ent->value = evt.param<3>(); //int hash = hashOIDS(n,e); //int count = lookupCount(ent,hash); Event *evt2 = new Event(Event::ADDDEP, ent->n); evt2->param<0>(ent->e); evt2->param<1>(OID::local()+OID(0,0,16,(hash << 8) + count)); m_conn->protocol()->begin(); m_conn->protocol()->event(*evt2, 0); m_conn->protocol()->end(); delete evt2;*/ return true; }
[ "nwpope@gmail.com" ]
nwpope@gmail.com
7a9db9b67386ead3d9a58db808fd96f387be167f
31b351b6e5cf30d62e20f573c9cfb067f015ba95
/c++/classes/operator_overloading.cpp
f8694c1672ba2acafd91f713306747ecacaf0c76
[]
no_license
SebastianMocny/Gnosis
69c2013fd9891cfd8027393b940d17286cacc4ed
791d26859da4911f5cc0f03a6f83ba9b57007beb
refs/heads/master
2020-12-24T17:27:15.932560
2018-11-27T01:46:37
2018-11-27T01:46:37
13,897,781
0
0
null
null
null
null
UTF-8
C++
false
false
679
cpp
/* * * This is my template for document boilerplate. * Last update to this template is: November 12, 2018 * * TODO: Add licensing info. For example, Apache 2.0 * * * Author: Sebastian Mocny * Date of file creation: Some time before November 12, 2018 */ #include <iostream> class Foo { private: int val; public: void set_val(int); void operator+(Foo const&); int get_val() const { return val; } }; void Foo::set_val (int x) { val = x; } void Foo::operator+(Foo const& f) { val += f.get_val(); } int main() { Foo a, b; a.set_val(1); b.set_val(2); std::cout << a.get_val() << b.get_val() << std::endl; a + b; std::cout << a.get_val(); return 0; }
[ "biggi3lue@gmail.com" ]
biggi3lue@gmail.com
d00ffe0f17c8f8f76f43b6f3e73d957b6aaaa0da
880712af57cd0217561a4288e38f4ccfdd376abf
/hlib/src/hoserversocket.cpp
7389ba7161e48e9c532c41ed405e89def0142b3a
[]
no_license
honzour/hlib
9ccdfda1221e9fd6d58a183d74e21c2bafb96b15
7f250dbd44ee8ba8bcfb33b6a10f33225d846007
refs/heads/master
2021-01-01T16:55:11.134043
2014-05-26T06:22:46
2014-05-26T06:22:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,091
cpp
#include "hoserversocket.h" #include "holog.h" #if hplatform==XW #include <unistd.h> #include <fcntl.h> #elif hplatform==MW #include <windows.h> #endif HoServerSocket::HoServerSocket(int port, int maxConnection) { this->port = port; this->maxConnection = maxConnection; connected = false; } bool HoServerSocket::listenBind() { struct sockaddr_in sockName; if ((handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { return false; } sockName.sin_family = AF_INET; sockName.sin_port = htons(port); sockName.sin_addr.s_addr = INADDR_ANY; if (bind(handle, (struct sockaddr *)&sockName, sizeof(sockName)) == -1) { uklid: close(); handle = -1; return false; } if (listen(handle, maxConnection) == -1) { goto uklid; return false; } connected = true; return true; } HoSocket* HoServerSocket::accept() { if (handle == -1 ) { return NULL; } struct sockaddr_in clientInfo; #if hplatform==XW socklen_t #else int #endif addrlen = sizeof(clientInfo); int client = ::accept(handle, (struct sockaddr*)&clientInfo, &addrlen); if (client == -1) { return NULL; } HoSocket *r = new HoSocket(); r->connected = 1; r->handle = client; return r; } void HoServerSocket::close() { holog.log(I4, "close(%i)\n", handle); #if hplatform==XW ::close #else ::closesocket #endif (handle); connected = false; } bool HoServerSocket::setBlocking(bool blocking) { #if hplatform==XW long arg = fcntl(handle, F_GETFL, 0); if (blocking) { arg &= ~O_NONBLOCK; } else { arg |= O_NONBLOCK; } if (fcntl(handle, F_SETFL, arg) == -1) { return false; } return true; #else return false; #endif } bool HoServerSocket::waitForEvent(bool &error, bool &connection) { fd_set chyby, spojeni; FD_ZERO(&chyby); FD_ZERO(&spojeni); FD_SET(handle, &chyby); FD_SET(handle, &spojeni); int ret = select(1, &spojeni, NULL, &chyby, NULL); if (ret == -1) { return false; } error = FD_ISSET(handle, &chyby); connection = FD_ISSET(handle, &spojeni); return true; }
[ "jnem6403@seznam.cz" ]
jnem6403@seznam.cz
a4055c5cd43b09da2da0c8697892f02ac6ebfadc
dceff34eaceed8f7a52ea908958645104167e3e1
/src/backup-redundant-features/combined-extern/model/ModelParams.h
04628c0469d3035c4ce507507ecf86f678f0510f
[]
no_license
zhangmeishan/NNRelationExtraction
a100acc0f6c9d5fd0db7686249b647a21ae908b2
8efd8173b2503bc75274b2238b2392476a86a8e9
refs/heads/master
2021-01-11T19:48:25.552293
2017-07-30T13:23:56
2017-07-30T13:23:56
79,401,948
14
2
null
null
null
null
UTF-8
C++
false
false
3,891
h
#ifndef SRC_ModelParams_H_ #define SRC_ModelParams_H_ #include "HyperParams.h" // Each model consists of two parts, building neural graph and defining output losses. class ModelParams { public: //neural parameters Alphabet embeded_chars; // chars LookupTable char_table; // should be initialized outside Alphabet embeded_words; // words LookupTable word_table; // should be initialized outside Alphabet embeded_ext_words; LookupTable word_ext_table; Alphabet embeded_tags; // tags LookupTable tag_table; // should be initialized outside Alphabet embeded_actions; LookupTable action_table; // should be initialized outside Alphabet embeded_ners; LookupTable ner_table; // should be initialized outside UniParams char_tanh_conv; UniParams word_tanh_conv1; LSTM1Params word_left_lstm1; //left lstm LSTM1Params word_right_lstm1; //right lstm BiParams word_tanh_conv2; BiParams ext_word_tanh_conv; LSTM1Params ext_word_left_lstm; //left lstm LSTM1Params ext_word_right_lstm; //right lstm BiParams ext_word_tanh_conv1; BiParams action_conv; LSTM1Params action_lstm; UniParams ner_state_hidden; UniParams rel_state_hidden; LookupTable scored_action_table; public: bool initial(HyperParams &opts, AlignedMemoryPool *mem) { char_tanh_conv.initial(opts.char_hidden_dim, opts.char_represent_dim, true, mem); word_tanh_conv1.initial(opts.word_hidden_dim, opts.word_represent_dim, true, mem); word_left_lstm1.initial(opts.word_lstm_dim, opts.word_hidden_dim, mem); //left lstm word_right_lstm1.initial(opts.word_lstm_dim, opts.word_hidden_dim, mem); //right lstm word_tanh_conv2.initial(opts.word_hidden_dim, opts.word_lstm_dim, opts.word_lstm_dim, true, mem); ext_word_tanh_conv.initial(opts.word_hidden_dim, opts.ext_lstm_dim, opts.ext_lstm_dim, true, mem); ext_word_left_lstm.initial(opts.word_lstm_dim, opts.word_hidden_dim, mem); //left lstm ext_word_right_lstm.initial(opts.word_lstm_dim, opts.word_hidden_dim, mem); //right lstm ext_word_tanh_conv1.initial(opts.word_hidden_dim, opts.word_lstm_dim, opts.word_lstm_dim, true, mem); action_conv.initial(opts.action_hidden_dim, opts.action_dim, opts.action_dim, true, mem); action_lstm.initial(opts.action_lstm_dim, opts.action_hidden_dim, mem); ner_state_hidden.initial(opts.state_hidden_dim, opts.ner_state_concat_dim, true, mem); rel_state_hidden.initial(opts.state_hidden_dim, opts.rel_state_concat_dim, true, mem); scored_action_table.initial(&embeded_actions, opts.state_hidden_dim, true); scored_action_table.E.val.random(0.01); return true; } void exportModelParams(ModelUpdate &ada) { //neural features char_table.exportAdaParams(ada); word_table.exportAdaParams(ada); //word_ext_table.exportAdaParams(ada); tag_table.exportAdaParams(ada); action_table.exportAdaParams(ada); ner_table.exportAdaParams(ada); char_tanh_conv.exportAdaParams(ada); word_tanh_conv1.exportAdaParams(ada); word_left_lstm1.exportAdaParams(ada); word_right_lstm1.exportAdaParams(ada); word_tanh_conv2.exportAdaParams(ada); ext_word_tanh_conv.exportAdaParams(ada); ext_word_left_lstm.exportAdaParams(ada); ext_word_right_lstm.exportAdaParams(ada); ext_word_tanh_conv1.exportAdaParams(ada); action_conv.exportAdaParams(ada); action_lstm.exportAdaParams(ada); ner_state_hidden.exportAdaParams(ada); rel_state_hidden.exportAdaParams(ada); scored_action_table.exportAdaParams(ada); } // will add it later void saveModel() { } void loadModel(const string &inFile) { } }; #endif /* SRC_ModelParams_H_ */
[ "mason.zms@gmail.com" ]
mason.zms@gmail.com
ef2a9051bd47e936f96184754b5bfaf01ba1e273
7881ead3610b10517dbfdd2878af73cb8852a940
/心率模块读取端/src/ads1292r/ads1292r.cpp
f2798bb9a8be8966c5502d43a52c3ef84bee3461
[ "MIT" ]
permissive
amedues/2020_TI_competion_question_A
b49ed4a97e7bc0acb0f9da887a47b6dbc86654ec
7f421ebcd034b5aecf387188ff065d782bef3a7f
refs/heads/main
2023-01-06T17:21:32.818118
2020-11-11T09:23:11
2020-11-11T09:23:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,595
cpp
////////////////////////////////////////////////////////////////////////////////////////// // // Arduino Library for ADS1292R Shield/Breakout // // Copyright (c) 2017 ProtoCentral // // This software is licensed under the MIT License(http://opensource.org/licenses/MIT). // // 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. // // Requires g4p_control graphing library for processing. Built on V4.1 // Downloaded from Processing IDE Sketch->Import Library->Add Library->G4P Install // ///////////////////////////////////////////////////////////////////////////////////////// #include <Arduino.h> #include <ads1292r/ads1292r.h> #include <SPI.h> char* ads1292r::ads1292_Read_Data() { static char SPI_Dummy_Buff[10]; digitalWrite(ADS1292_CS_PIN, LOW); for (int i = 0; i < 9; ++i) { SPI_Dummy_Buff[i] = SPI.transfer(CONFIG_SPI_MASTER_DUMMY); } digitalWrite(ADS1292_CS_PIN, HIGH); return SPI_Dummy_Buff; } void ads1292r::ads1292_Init() { // start the SPI library: SPI.begin(); SPI.setBitOrder(MSBFIRST); //CPOL = 0, CPHA = 1 SPI.setDataMode(SPI_MODE1); // Selecting 1Mhz clock for SPI SPI.setClockDivider(SPI_CLOCK_DIV16); ads1292_Reset(); delay(100); ads1292_Disable_Start(); ads1292_Enable_Start(); ads1292_Hard_Stop(); ads1292_Start_Data_Conv_Command(); ads1292_Soft_Stop(); delay(50); ads1292_Stop_Read_Data_Continuous(); // SDATAC command delay(300); ads1292_Reg_Write(ADS1292_REG_CONFIG1, 0x00); //Set sampling rate to 125 SPS delay(10); ads1292_Reg_Write(ADS1292_REG_CONFIG2, 0b10100000); //Lead-off comp off, test signal disabled delay(10); ads1292_Reg_Write(ADS1292_REG_LOFF, 0b00010000); //Lead-off defaults delay(10); ads1292_Reg_Write(ADS1292_REG_CH1SET, 0b01000000); //Ch 1 enabled, gain 6, connected to electrode in delay(10); ads1292_Reg_Write(ADS1292_REG_CH2SET, 0b01100000); //Ch 2 enabled, gain 6, connected to electrode in delay(10); ads1292_Reg_Write(ADS1292_REG_RLDSENS, 0b00101100); //RLD settings: fmod/16, RLD enabled, RLD inputs from Ch2 only delay(10); ads1292_Reg_Write(ADS1292_REG_LOFFSENS, 0x00); //LOFF settings: all disabled delay(10); //Skip register 8, LOFF Settings default ads1292_Reg_Write(ADS1292_REG_RESP1, 0b11110010); //Respiration: MOD/DEMOD turned only, phase 0 delay(10); ads1292_Reg_Write(ADS1292_REG_RESP2, 0b00000011); //Respiration: Calib OFF, respiration freq defaults delay(10); ads1292_Start_Read_Data_Continuous(); delay(10); ads1292_Enable_Start(); } void ads1292r::ads1292_Reset() { digitalWrite(ADS1292_PWDN_PIN, HIGH); delay(100); // Wait 100 mSec digitalWrite(ADS1292_PWDN_PIN, LOW); delay(100); digitalWrite(ADS1292_PWDN_PIN, HIGH); delay(100); } void ads1292r::ads1292_Disable_Start() { digitalWrite(ADS1292_START_PIN, LOW); delay(20); } void ads1292r::ads1292_Enable_Start() { digitalWrite(ADS1292_START_PIN, HIGH); delay(20); } void ads1292r::ads1292_Hard_Stop (void) { digitalWrite(ADS1292_START_PIN, LOW); delay(100); } void ads1292r::ads1292_Start_Data_Conv_Command (void) { ads1292_SPI_Command_Data(START); // Send 0x08 to the ADS1x9x } void ads1292r::ads1292_Soft_Stop (void) { ads1292_SPI_Command_Data(STOP); // Send 0x0A to the ADS1x9x } void ads1292r::ads1292_Start_Read_Data_Continuous (void) { ads1292_SPI_Command_Data(RDATAC); // Send 0x10 to the ADS1x9x } void ads1292r::ads1292_Stop_Read_Data_Continuous (void) { ads1292_SPI_Command_Data(SDATAC); // Send 0x11 to the ADS1x9x } void ads1292r::ads1292_SPI_Command_Data(unsigned char data_in) { byte data[1]; //data[0] = data_in; digitalWrite(ADS1292_CS_PIN, LOW); delay(2); digitalWrite(ADS1292_CS_PIN, HIGH); delay(2); digitalWrite(ADS1292_CS_PIN, LOW); delay(2); SPI.transfer(data_in); delay(2); digitalWrite(ADS1292_CS_PIN, HIGH); } //Sends a write command to SCP1000 void ads1292r::ads1292_Reg_Write (unsigned char READ_WRITE_ADDRESS, unsigned char DATA) { switch (READ_WRITE_ADDRESS) { case 1: DATA = DATA & 0x87; break; case 2: DATA = DATA & 0xFB; DATA |= 0x80; break; case 3: DATA = DATA & 0xFD; DATA |= 0x10; break; case 7: DATA = DATA & 0x3F; break; case 8: DATA = DATA & 0x5F; break; case 9: DATA |= 0x02; break; case 10: DATA = DATA & 0x87; DATA |= 0x01; break; case 11: DATA = DATA & 0x0F; break; default: break; } // now combine the register address and the command into one byte: byte dataToSend = READ_WRITE_ADDRESS | WREG; digitalWrite(ADS1292_CS_PIN, LOW); delay(2); digitalWrite(ADS1292_CS_PIN, HIGH); delay(2); // take the chip select low to select the device: digitalWrite(ADS1292_CS_PIN, LOW); delay(2); SPI.transfer(dataToSend); //Send register location SPI.transfer(0x00); //number of register to wr SPI.transfer(DATA); //Send value to record into register delay(2); // take the chip select high to de-select: digitalWrite(ADS1292_CS_PIN, HIGH); }
[ "1020401660@qq.com" ]
1020401660@qq.com
0916765d28c689450ab1e5ac356db0ae2afbd633
4f8f7b4e2b4819392adb8357047fb49f5c1e2af4
/BattleTank/Source/BattleTank/Public/Tank.h
13d6c2b3e204fc3e3ea915ff5da9bb6547859adb
[]
no_license
Puppetz17/04_BattleTank
b48c8715b7b6a2cf164b6de8f2c2222df4c6266e
569a4054093b37b8d0af7e4aa97be5e747c6c026
refs/heads/master
2021-07-13T05:28:22.909287
2017-10-13T22:23:30
2017-10-13T22:23:30
105,777,466
0
0
null
null
null
null
UTF-8
C++
false
false
925
h
// Copyright me #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "Tank.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE(FTankEvent); UCLASS() class BATTLETANK_API ATank : public APawn { GENERATED_BODY() public: // Called by the engine when actor damage is dealt virtual float TakeDamage(float DamageAmount, struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor* DamageCauser) override; // Returns current health as a percentage of starting health between 0 and 1 UFUNCTION(BlueprintPure, Category = "Health") float GetHealthPercent() const; FTankEvent OnDeath; private: // Sets default values for this pawn's properties ATank(); virtual void BeginPlay() override; UPROPERTY(EditDefaultsOnly, Category = "Setup") int32 StartingHealth = 100; UPROPERTY(VisibleAnywhere, Category = "Health") int32 CurrentHealth; // Initialized in BeginPlay };
[ "hadar.itzhaik@gmail.com" ]
hadar.itzhaik@gmail.com
cf4d91aeeddb08ce178273e3d51f32e8a64da4d7
85ea04aceca198cad335672e5eb3009298899cbf
/Algorithms/Greedy/N meetings in one room.cpp
1f703d406b0fda8d8690eb00461f7e0f57a5dcdd
[]
no_license
sahilalam/CodingPracticeCpp
b0eb877a11fa7b1a79ad9bb73cd8f8de75427afb
285e83203e434f9779c8c3f77c3ba2a8676a0170
refs/heads/master
2023-03-02T01:10:01.727552
2021-02-02T19:03:01
2021-02-02T19:03:01
298,071,610
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
cpp
void merge(int *start,int *end,int s1,int e1,int s2,int e2) { int* tmp=new int[e2-s1+1]; int* tmp2=new int[e2-s1+1]; int k=0; while(s1<=e1 && s2<=e2) { if(end[s1]<end[s2]) { tmp[k]=end[s1]; tmp2[k]=start[s1]; s1++; k++; } else { tmp[k]=end[s2]; tmp2[k]=start[s2]; s2++; k++; } } while(s1<=e1) { tmp[k]=end[s1]; tmp2[k]=start[s1]; s1++; k++; } while(s2<=e2) { tmp[k]=end[s2]; tmp2[k]=start[s2]; s2++; k++; } k--; while(k>=0) { end[e2]=tmp[k]; start[e2]=tmp2[k]; k--; e2--; } delete []tmp; tmp=NULL; delete []tmp2; tmp2=NULL; } void fn(int *start,int *end,int i,int j) { if(i>=j) { return ; } int mid=(i+j)/2; fn(start,end,i,mid); fn(start,end,mid+1,j); merge(start,end,i,mid,mid+1,j); } int maxMeetings(int start[], int end[], int n) { fn(start,end,0,n-1); int tmp=end[0]; int ans=1; for(int i=1;i<n;i++) { if(start[i]>tmp) { ans++; tmp=end[i]; } } return ans; }
[ "alamsahil939@gmail.com" ]
alamsahil939@gmail.com
b3f8b70f95ae5c4c282c98a74d251abab9dc8fcd
6fd67c8a4b4e5de2eec30af3ed679fbdaee90a99
/Diploma/Diploma/SelectMouse.cpp
1ffd922099dcb8e8ed01b83a5051ad59187fd36e
[]
no_license
Aeshylus/Test
6912ef08828094a2840d87b61fc48c63630442e3
d4ae1ff98b84cb67650ff6681dc6145fc7e8afb9
refs/heads/master
2021-01-25T05:35:40.187114
2014-01-29T18:12:37
2014-01-29T18:12:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,184
cpp
#include "stdafx.h" #include "SelectMouse.h" #include "Camera.h" #include "CDiploma3DView.h" #include "IMouseMovementLogic.h" #include "MiceMovementLogicFactory.h" namespace { bool _IsWndValid(CWnd* ip_wnd) { return nullptr != dynamic_cast<CDiploma3DView*>(ip_wnd); } } ////////////////////////////////////////////////////////////////////////// SelectMouse::SelectMouse() : mp_movement_logic(nullptr) { } ////////////////////////////////////////////////////////////////////////// void SelectMouse::OnMouseMove( CWnd* ip_wnd, UINT nFlags, CPoint point ) { if (mp_movement_logic) { mp_movement_logic->MakeMove(ip_wnd, m_prev_point, point); m_prev_point = point; } } ////////////////////////////////////////////////////////////////////////// void SelectMouse::OnLButtonUp( CWnd* ip_wnd, UINT nFlags, CPoint point ) { mp_movement_logic.reset(); } ////////////////////////////////////////////////////////////////////////// void SelectMouse::OnLButtonDown( CWnd* ip_wnd, UINT nFlags, CPoint point ) { if (!_IsWndValid(ip_wnd)) return; m_prev_point = point; } ////////////////////////////////////////////////////////////////////////// void SelectMouse::OnRButtonUp( CWnd* ip_wnd, UINT nFlags, CPoint point ) { mp_movement_logic.reset(); } ////////////////////////////////////////////////////////////////////////// void SelectMouse::OnRButtonDown( CWnd* ip_wnd, UINT nFlags, CPoint point ) { if (!_IsWndValid(ip_wnd)) return; m_prev_point = point; mp_movement_logic = CreateMovementLogic(MiceMovementType::E_TYPE_SELECT_RBUTTON); } ////////////////////////////////////////////////////////////////////////// void SelectMouse::OnMButtonDown( CWnd* ip_wnd, UINT nFlags, CPoint point ) { if (!_IsWndValid(ip_wnd)) return; m_prev_point = point; mp_movement_logic = CreateMovementLogic(MiceMovementType::E_TYPE_SELECT_MBUTTON); } ////////////////////////////////////////////////////////////////////////// void SelectMouse::OnMButtonUp( CWnd* ip_wnd, UINT nFlags, CPoint point ) { mp_movement_logic.reset(); } //////////////////////////////////////////////////////////////////////////
[ "nosatskyy.slava@gmail.com" ]
nosatskyy.slava@gmail.com
d76a7244a4eb7cfa0601387729ff74b857c85e3f
49268fd1857d86f2af7b8aba559b833da465c5ca
/MPMissions/DayZ_Epoch_11.Chernarus/build_recipe_dialog.hpp
993d8f30b6401e673e02a4d83f1fc2e1c1b9aab0
[]
no_license
Razorsoft/0.6
f6e0d5172e04b24d2395ceadf90bdd19894e2916
1ce65b5c280db252421debc56205ca27fb7f2807
refs/heads/master
2021-01-10T21:30:54.782388
2013-11-25T22:22:55
2013-11-25T22:22:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,525
hpp
class Build_Recipe_Dialog{ idd = -1; onLoad="uiNamespace setVariable ['Build_Recipe_Dialog', _this select 0]"; movingenable = true; onUnLoad="uiNamespace setVariable ['Build_Recipe_Dialog', nil]"; class Controls{ class DialogBox: BOX{ idc = -1; text = ""; x = 0.211851 * safezoneW + safezoneX; y = 0.194721 * safezoneH + safezoneY; w = 0.575881 * safezoneW; h = 0.631944 * safezoneH;}; class RecipeFrame: RscFrame{ idc = 1800; text = "Base Building Recipe Book"; x = 0.211851 * safezoneW + safezoneX; y = 0.194721 * safezoneH + safezoneY; w = 0.575881 * safezoneW; h = 0.631944 * safezoneH;}; class ObjectImage: RscPicture{ idc = 1200; text = "#(argb,8,8,3)color(1,1,1,1)"; x = 0.621195 * safezoneW + safezoneX; y = 0.347186 * safezoneH + safezoneY; w = 0.162083 * safezoneW; h = 0.30952 * safezoneH;}; class ClassNameFrame: RscFrame{ idc = 1801; text = "Materials needed:"; x = 0.214286 * safezoneW + safezoneX; y = 0.2375 * safezoneH + safezoneY; w = 0.571685 * safezoneW; h = 0.542594 * safezoneH;}; class TankQtyText: RscText{ idc = 1000; text = "x 1"; x = 0.258929 * safezoneW + safezoneX; y = 0.2625 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class WireQuanty: RscText{ idc = 1001; text = "1"; x = 0.258929 * safezoneW + safezoneX; y = 0.35 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class SandQuanty: RscText{ idc = 1002; text = "1"; x = 0.258929 * safezoneW + safezoneX; y = 0.4375 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class LumberQuanty: RscText{ idc = 1003; text = "1"; x = 0.258929 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class PlywoodQty: RscText{ idc = 1004; text = "1"; x = 0.258929 * safezoneW + safezoneX; y = 0.6125 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class GrenadeQty: RscText{ idc = 1005; text = "1"; x = 0.258929 * safezoneW + safezoneX; y = 0.7 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class PrevButton: RscButton{ idc = 1603; action = "_nil=[]ExecVM 'buildRecipeBook\prevBuildRecipe.sqf'"; text = "Previous Page"; x = 0.214286 * safezoneW + safezoneX; y = 0.7875 * safezoneH + safezoneY; w = 0.0727273 * safezoneW; h = 0.0333333 * safezoneH;}; class ClassNameText: RscText{ idc = 1006; text = "CLASS NAME"; x = 0.216212 * safezoneW + safezoneX; y = 0.209861 * safezoneH + safezoneY; w = 0.372727 * safezoneW; h = 0.0166667 * safezoneH;}; class NextButton: RscButton{ idc = 1604; action = "_nil=[]ExecVM 'buildRecipeBook\nextBuildRecipe.sqf'"; text = "Next Page"; x = 0.712724 * safezoneW + safezoneX; y = 0.7875 * safezoneH + safezoneY; w = 0.0727273 * safezoneW; h = 0.0333333 * safezoneH;}; class ShowButton: RscButton{ idc = 1600; action = "closeDialog 0;_nil=[]ExecVM 'dayz_code\compile\player_basebuild.sqf'"; text = "Build!"; x = 0.348214 * safezoneW + safezoneX; y = 0.7875 * safezoneH + safezoneY; w = 0.0727273 * safezoneW; h = 0.0333333 * safezoneH;}; class ShowListButton: RscButton{ idc = 1601; action = "closeDialog 0;_nil=[]ExecVM 'buildRecipeBook\build_recipe_list_dialog.sqf'"; text = "Show List"; x = 0.579836 * safezoneW + safezoneX; y = 0.7875 * safezoneH + safezoneY; w = 0.0727273 * safezoneW; h = 0.0333333 * safezoneH;}; class ReqFrame: RscFrame{ idc = 1802; text = "Requirements"; x = 0.5 * safezoneW + safezoneX; y = 0.300167 * safezoneH + safezoneY; w = 0.115998 * safezoneW; h = 0.395369 * safezoneH;}; class InBuildingText: RscText{ idc = 1007; text = "In Building:"; x = 0.5 * safezoneW + safezoneX; y = 0.488245 * safezoneH + safezoneY; w = 0.0542709 * safezoneW; h = 0.0249579 * safezoneH;}; class OnRoadText: RscText{ idc = 1008; text = "On Road:"; x = 0.5 * safezoneW + safezoneX; y = 0.52351 * safezoneH + safezoneY; w = 0.0542709 * safezoneW; h = 0.0249579 * safezoneH;}; class RscText_1009: RscText{ idc = 1009; text = "In Town:"; x = 0.5 * safezoneW + safezoneX; y = 0.558775 * safezoneH + safezoneY; w = 0.0542709 * safezoneW; h = 0.0249579 * safezoneH;}; class RemText: RscText{ idc = 1010; text = "Removable:"; x = 0.5 * safezoneW + safezoneX; y = 0.605794 * safezoneH + safezoneY; w = 0.0542709 * safezoneW; h = 0.0249579 * safezoneH;}; class building: RscText{ idc = 1014; text = "building"; x = 0.582633 * safezoneW + safezoneX; y = 0.488245 * safezoneH + safezoneY; w = 0.0313546 * safezoneW; h = 0.0221405 * safezoneH;}; class road: RscText{ idc = 1011; text = "etool"; x = 0.582633 * safezoneW + safezoneX; y = 0.52351 * safezoneH + safezoneY; w = 0.0297918 * safezoneW; h = 0.0221405 * safezoneH;}; class town: RscText{ idc = 1012; text = "False"; x = 0.582633 * safezoneW + safezoneX; y = 0.558775 * safezoneH + safezoneY; w = 0.0297918 * safezoneW; h = 0.0221405 * safezoneH;}; class removable: RscText{ idc = 1013; text = "False"; x = 0.582633 * safezoneW + safezoneX; y = 0.605794 * safezoneH + safezoneY; w = 0.0297918 * safezoneW; h = 0.0221405 * safezoneH;}; class chance: RscText{ idc = 1018; text = "Chance: 30% (50% lt)"; x = 0.511018 * safezoneW + safezoneX; y = 0.652814 * safezoneH + safezoneY; w = 0.0959376 * safezoneW; h = 0.0221405 * safezoneH;}; class time: RscText{ idc = 1015; text = "False"; x = 0.582633 * safezoneW + safezoneX; y = 0.441225 * safezoneH + safezoneY; w = 0.0297918 * safezoneW; h = 0.0221405 * safezoneH;}; class etool: RscText{ idc = 1016; text = "False"; x = 0.582633 * safezoneW + safezoneX; y = 0.394206 * safezoneH + safezoneY; w = 0.0297918 * safezoneW; h = 0.0221405 * safezoneH;}; class toolbox: RscText{ idc = 1017; text = "False"; x = 0.582633 * safezoneW + safezoneX; y = 0.347186 * safezoneH + safezoneY; w = 0.0297918 * safezoneW; h = 0.0221405 * safezoneH;}; class SandBagLargQuanty: RscText{ idc = 1020; text = "1"; x = 0.348214 * safezoneW + safezoneX; y = 0.35 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class BurlapQty: RscText{ idc = 1021; text = "1"; x = 0.4375 * safezoneW + safezoneX; y = 0.6125 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class ScrapQty: RscText{ idc = 1022; text = "1"; x = 0.348214 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class PoleQty: RscText{ idc = 1023; text = "1"; x = 0.348214 * safezoneW + safezoneX; y = 0.6125 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class GlassQty: RscText{ idc = 1024; text = "1"; x = 0.4375 * safezoneW + safezoneX; y = 0.7 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class ForestNetKit: RscText{ idc = 1025; text = "1"; x = 0.4375 * safezoneW + safezoneX; y = 0.4375 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class desert_net_kit: RscText{ idc = 1026; text = "1"; x = 0.4375 * safezoneW + safezoneX; y = 0.35 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class SotrageShedKit: RscText{ idc = 1027; text = "1"; x = 0.4375 * safezoneW + safezoneX; y = 0.2625 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class wooden_shed_kitQuanty: RscText{ idc = 1028; text = "1"; x = 0.4375 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class SandBagNestKitQuanty: RscText{ idc = 1029; text = "1"; x = 0.348214 * safezoneW + safezoneX; y = 0.4375 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class FenceQuanty: RscText{ idc = 1030; text = "1"; x = 0.348214 * safezoneW + safezoneX; y = 0.7 * safezoneH + safezoneY; w = 0.050625 * safezoneW; h = 0.0277753 * safezoneH;}; class TankImage: RscPicture{ idc = 1201; text = "dayz_equip\textures\equip_tanktrap_kit_CA.paa"; x = 0.232143 * safezoneW + safezoneX; y = 0.2625 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Tank Trap";}; class WireImage: RscPicture{ idc = 1202; text = "dayz_equip\textures\equip_wire_CA.paa"; x = 0.232143 * safezoneW + safezoneX; y = 0.35 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Wire";}; class SandBagImage: RscPicture{ idc = 1203; text = "dayz_equip\textures\equip_sandbag_CA.paa"; x = 0.232143 * safezoneW + safezoneX; y = 0.4375 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Sand Bag";}; class LumberImage: RscPicture{ idc = 1204; text = "\z\addons\dayz_epoch\pictures\equip_wood_planks_CA.paa"; x = 0.232143 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Lumber";}; class PlyWoodImage: RscPicture{ idc = 1205; text = "\z\addons\dayz_epoch\pictures\equip_plywood_CA.paa"; x = 0.232143 * safezoneW + safezoneX; y = 0.6125 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "PlyWood";}; class GrenadeImage: RscPicture{ idc = 1206; text = "\CA\weapons\data\equip\m_M67_CA.paa"; x = 0.232143 * safezoneW + safezoneX; y = 0.7 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Grenades";}; class ToolboxImage: RscPicture{ idc = 1207; text = "dayz_equip\textures\equip_toolbox_CA.paa"; x = 0.511018 * safezoneW + safezoneX; y = 0.347186 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "ToolBox";}; class EToolImage: RscPicture{ idc = 1208; text = "dayz_equip\textures\equip_etool_CA.paa"; x = 0.511018 * safezoneW + safezoneX; y = 0.394206 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Etool";}; class TimeImage: RscPicture{ idc = 1209; text = "buildRecipeBook\images\timer.paa"; x = 0.511018 * safezoneW + safezoneX; y = 0.441225 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Timer";}; class SandbagLargeImage: RscPicture{ idc = 1211; text = "buildRecipeBook\images\ItemSandbagLarge.paa"; x = 0.321429 * safezoneW + safezoneX; y = 0.35 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "SandbagLarge";}; class BurlapImage: RscPicture{ idc = 1212; text = "\z\addons\dayz_epoch\pictures\equip_burlap_ca.paa"; x = 0.321429 * safezoneW + safezoneX; y = 0.4375 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Burlap";}; class ScrapImage: RscPicture{ idc = 1213; text = "dayz_equip\textures\equip_genericparts_CA.paa"; x = 0.321429 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Scrap";}; class PoleImage: RscPicture{ idc = 1214; text = "\z\addons\dayz_epoch\pictures\equip_pipe_CA.paa"; x = 0.321429 * safezoneW + safezoneX; y = 0.6125 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Pole";}; class PartGlassImage: RscPicture{ idc = 1215; text = "dayz_equip\textures\equip_carglass_CA.paa"; x = 0.321429 * safezoneW + safezoneX; y = 0.7 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Glass";}; class ForestNetKitKitImage: RscPicture{ idc = 1216; text = "buildRecipeBook\images\Forest_Net_Kit.paa"; x = 0.410714 * safezoneW + safezoneX; y = 0.2625 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "forest_net_kit";}; class desert_net_kitImage: RscPicture{ idc = 1217; text = "buildRecipeBook\images\desert_net_kit.paa"; x = 0.410714 * safezoneW + safezoneX; y = 0.35 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "desert_net_kit";}; class StorageShedKitkitImage: RscPicture{ idc = 1218; text = "buildRecipeBook\images\Storage_shed_kit.paa"; x = 0.410714 * safezoneW + safezoneX; y = 0.4375 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "SotrageShedKit";}; class ItemWoodShed: RscPicture{ idc = 1219; text = "buildRecipeBook\images\wood_shack_kit.paa"; x = 0.410714 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "WoodShedKit";}; class SandBagNestKitImage: RscPicture{ idc = 1220; text = "buildRecipeBook\images\sandbag_nest_kit.paa"; x = 0.410714 * safezoneW + safezoneX; y = 0.6125 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "SandBagNestKit";}; class FenceImage: RscPicture{ idc = 1221; text = "buildRecipeBook\images\ItemCorrugated.paa"; x = 0.410714 * safezoneW + safezoneX; y = 0.7 * safezoneH + safezoneY; w = 0.019375 * safezoneW; h = 0.0315319 * safezoneH; tooltip = "Fence";}; class TankTrapText: RscText{ idc = 1031; text = "Tank Trap"; x = 0.232143 * safezoneW + safezoneX; y = 0.3125 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class WireFenceKitText: RscText{ idc = 1032; text = "Wire Fence Kit"; x = 0.232143 * safezoneW + safezoneX; y = 0.4 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class SandBagsText: RscText{ idc = 1033; text = "Sand Bags"; x = 0.232143 * safezoneW + safezoneX; y = 0.4875 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class LumberText: RscText{ idc = 1034; text = "Lumber"; x = 0.232143 * safezoneW + safezoneX; y = 0.575 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class PlyWoodText: RscText{ idc = 1035; text = "PlyWood"; x = 0.232143 * safezoneW + safezoneX; y = 0.6625 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class GrenadeText: RscText{ idc = 1036; text = "Grenade"; x = 0.232143 * safezoneW + safezoneX; y = 0.75 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class HbarrierText: RscText{ idc = 1038; text = "HBarrier"; x = 0.321429 * safezoneW + safezoneX; y = 0.4 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class BurlapText: RscText{ idc = 1039; text = "Burlap"; x = 0.321429 * safezoneW + safezoneX; y = 0.4875 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class ScrapMetalText: RscText{ idc = 1040; text = "Scrap Metal"; x = 0.321429 * safezoneW + safezoneX; y = 0.575 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class PolesText: RscText{ idc = 1041; text = "Poles"; x = 0.321429 * safezoneW + safezoneX; y = 0.6625 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class WindscreenText: RscText{ idc = 1042; text = "Windscreen"; x = 0.321429 * safezoneW + safezoneX; y = 0.75 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class ForestNetKitText: RscText{ idc = 1043; text = "Forest Net Kit"; x = 0.410714 * safezoneW + safezoneX; y = 0.3125 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class DesertNetkitText: RscText{ idc = 1044; text = "Desert Net Kit"; x = 0.410714 * safezoneW + safezoneX; y = 0.4 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class StorageShedText: RscText{ idc = 1045; text = "Storage Shed Kit"; x = 0.410714 * safezoneW + safezoneX; y = 0.4875 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class WoodenShedKitText: RscText{ idc = 1046; text = "Wooden Shed Kit"; x = 0.410714 * safezoneW + safezoneX; y = 0.575 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class SandBagNestKitText: RscText{ idc = 1047; text = "SandBag Nest Kit"; x = 0.410714 * safezoneW + safezoneX; y = 0.6625 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; class CorrugatedFenceText: RscText{ idc = 1048; text = "Corrugated Fence Kit"; x = 0.410714 * safezoneW + safezoneX; y = 0.75 * safezoneH + safezoneY; w = 0.0995834 * safezoneW; h = 0.0188889 * safezoneH;}; }; };
[ "evaneo01@hotmail.com" ]
evaneo01@hotmail.com
98af169b429c431226e712d64ce35b5aced33542
d353838a4547c9e8d3d678350d9888e52417d65d
/tesseract_4.1.1/src/ccutil/tessdatamanager.h
3f6da32c9c0546d9dcfce8178cd6d19d3803e3c9
[ "MIT" ]
permissive
yym439/Tesseract-OCR_for_Windows
d74198d08436abe0121d8c952c096e441f65d9e6
c4a2b24b26f8f5c686311359f1096db7151da06b
refs/heads/master
2022-11-07T09:33:23.633294
2020-06-30T08:44:29
2020-06-30T08:44:29
268,446,368
1
0
MIT
2020-06-01T06:48:53
2020-06-01T06:48:53
null
UTF-8
C++
false
false
9,957
h
/////////////////////////////////////////////////////////////////////// // File: tessdatamanager.h // Description: Functions to handle loading/combining tesseract data files. // Author: Daria Antonova // // (C) Copyright 2009, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCUTIL_TESSDATAMANAGER_H_ #define TESSERACT_CCUTIL_TESSDATAMANAGER_H_ #include "genericvector.h" #include "strngs.h" // for STRING static const char kTrainedDataSuffix[] = "traineddata"; // When adding new tessdata types and file suffixes, please make sure to // update TessdataType enum, kTessdataFileSuffixes and kTessdataFileIsText. static const char kLangConfigFileSuffix[] = "config"; static const char kUnicharsetFileSuffix[] = "unicharset"; static const char kAmbigsFileSuffix[] = "unicharambigs"; static const char kBuiltInTemplatesFileSuffix[] = "inttemp"; static const char kBuiltInCutoffsFileSuffix[] = "pffmtable"; static const char kNormProtoFileSuffix[] = "normproto"; static const char kPuncDawgFileSuffix[] = "punc-dawg"; static const char kSystemDawgFileSuffix[] = "word-dawg"; static const char kNumberDawgFileSuffix[] = "number-dawg"; static const char kFreqDawgFileSuffix[] = "freq-dawg"; static const char kFixedLengthDawgsFileSuffix[] = "fixed-length-dawgs"; static const char kCubeUnicharsetFileSuffix[] = "cube-unicharset"; static const char kCubeSystemDawgFileSuffix[] = "cube-word-dawg"; static const char kShapeTableFileSuffix[] = "shapetable"; static const char kBigramDawgFileSuffix[] = "bigram-dawg"; static const char kUnambigDawgFileSuffix[] = "unambig-dawg"; static const char kParamsModelFileSuffix[] = "params-model"; static const char kLSTMModelFileSuffix[] = "lstm"; static const char kLSTMPuncDawgFileSuffix[] = "lstm-punc-dawg"; static const char kLSTMSystemDawgFileSuffix[] = "lstm-word-dawg"; static const char kLSTMNumberDawgFileSuffix[] = "lstm-number-dawg"; static const char kLSTMUnicharsetFileSuffix[] = "lstm-unicharset"; static const char kLSTMRecoderFileSuffix[] = "lstm-recoder"; static const char kVersionFileSuffix[] = "version"; namespace tesseract { enum TessdataType { TESSDATA_LANG_CONFIG, // 0 TESSDATA_UNICHARSET, // 1 TESSDATA_AMBIGS, // 2 TESSDATA_INTTEMP, // 3 TESSDATA_PFFMTABLE, // 4 TESSDATA_NORMPROTO, // 5 TESSDATA_PUNC_DAWG, // 6 TESSDATA_SYSTEM_DAWG, // 7 TESSDATA_NUMBER_DAWG, // 8 TESSDATA_FREQ_DAWG, // 9 TESSDATA_FIXED_LENGTH_DAWGS, // 10 // deprecated TESSDATA_CUBE_UNICHARSET, // 11 // deprecated TESSDATA_CUBE_SYSTEM_DAWG, // 12 // deprecated TESSDATA_SHAPE_TABLE, // 13 TESSDATA_BIGRAM_DAWG, // 14 TESSDATA_UNAMBIG_DAWG, // 15 TESSDATA_PARAMS_MODEL, // 16 TESSDATA_LSTM, // 17 TESSDATA_LSTM_PUNC_DAWG, // 18 TESSDATA_LSTM_SYSTEM_DAWG, // 19 TESSDATA_LSTM_NUMBER_DAWG, // 20 TESSDATA_LSTM_UNICHARSET, // 21 TESSDATA_LSTM_RECODER, // 22 TESSDATA_VERSION, // 23 TESSDATA_NUM_ENTRIES }; /** * kTessdataFileSuffixes[i] indicates the file suffix for * tessdata of type i (from TessdataType enum). */ static const char *const kTessdataFileSuffixes[] = { kLangConfigFileSuffix, // 0 kUnicharsetFileSuffix, // 1 kAmbigsFileSuffix, // 2 kBuiltInTemplatesFileSuffix, // 3 kBuiltInCutoffsFileSuffix, // 4 kNormProtoFileSuffix, // 5 kPuncDawgFileSuffix, // 6 kSystemDawgFileSuffix, // 7 kNumberDawgFileSuffix, // 8 kFreqDawgFileSuffix, // 9 kFixedLengthDawgsFileSuffix, // 10 // deprecated kCubeUnicharsetFileSuffix, // 11 // deprecated kCubeSystemDawgFileSuffix, // 12 // deprecated kShapeTableFileSuffix, // 13 kBigramDawgFileSuffix, // 14 kUnambigDawgFileSuffix, // 15 kParamsModelFileSuffix, // 16 kLSTMModelFileSuffix, // 17 kLSTMPuncDawgFileSuffix, // 18 kLSTMSystemDawgFileSuffix, // 19 kLSTMNumberDawgFileSuffix, // 20 kLSTMUnicharsetFileSuffix, // 21 kLSTMRecoderFileSuffix, // 22 kVersionFileSuffix, // 23 }; /** * TessdataType could be updated to contain more entries, however * we do not expect that number to be astronomically high. * In order to automatically detect endianness TessdataManager will * flip the bits if actual_tessdata_num_entries_ is larger than * kMaxNumTessdataEntries. */ static const int kMaxNumTessdataEntries = 1000; class TessdataManager { public: TessdataManager(); explicit TessdataManager(FileReader reader); ~TessdataManager() = default; bool swap() const { return swap_; } bool is_loaded() const { return is_loaded_; } // Lazily loads from the the given filename. Won't actually read the file // until it needs it. void LoadFileLater(const char *data_file_name); /** * Opens and reads the given data file right now. * @return true on success. */ bool Init(const char *data_file_name); // Loads from the given memory buffer as if a file, remembering name as some // arbitrary source id for caching. bool LoadMemBuffer(const char *name, const char *data, int size); // Overwrites a single entry of the given type. void OverwriteEntry(TessdataType type, const char *data, int size); // Saves to the given filename. bool SaveFile(const STRING &filename, FileWriter writer) const; // Serializes to the given vector. void Serialize(GenericVector<char> *data) const; // Resets to the initial state, keeping the reader. void Clear(); // Prints a directory of contents. void Directory() const; // Returns true if the component requested is present. bool IsComponentAvailable(TessdataType type) const { return !entries_[type].empty(); } // Opens the given TFile pointer to the given component type. // Returns false in case of failure. bool GetComponent(TessdataType type, TFile *fp); // As non-const version except it can't load the component if not already // loaded. bool GetComponent(TessdataType type, TFile *fp) const; // Returns the current version string. std::string VersionString() const; // Sets the version string to the given v_str. void SetVersionString(const std::string &v_str); // Returns true if the base Tesseract components are present. bool IsBaseAvailable() const { return !entries_[TESSDATA_UNICHARSET].empty() && !entries_[TESSDATA_INTTEMP].empty(); } // Returns true if the LSTM components are present. bool IsLSTMAvailable() const { return !entries_[TESSDATA_LSTM].empty(); } // Return the name of the underlying data file. const STRING &GetDataFileName() const { return data_file_name_; } /** * Reads all the standard tesseract config and data files for a language * at the given path and bundles them up into one binary data file. * Returns true if the combined traineddata file was successfully written. */ bool CombineDataFiles(const char *language_data_path_prefix, const char *output_filename); /** * Gets the individual components from the data_file_ with which the class was * initialized. Overwrites the components specified by component_filenames. * Writes the updated traineddata file to new_traineddata_filename. */ bool OverwriteComponents(const char *new_traineddata_filename, char **component_filenames, int num_new_components); /** * Extracts tessdata component implied by the name of the input file from * the combined traineddata loaded into TessdataManager. * Writes the extracted component to the file indicated by the file name. * E.g. if the filename given is somepath/somelang.unicharset, unicharset * will be extracted from the data loaded into the TessdataManager and will * be written to somepath/somelang.unicharset. * @return true if the component was successfully extracted, false if the * component was not present in the traineddata loaded into TessdataManager. */ bool ExtractToFile(const char *filename); private: // Use libarchive. bool LoadArchiveFile(const char *filename); /** * Fills type with TessdataType of the tessdata component represented by the * given file name. E.g. tessdata/eng.unicharset -> TESSDATA_UNICHARSET. * @return true if the tessdata component type could be determined * from the given file name. */ static bool TessdataTypeFromFileSuffix(const char *suffix, TessdataType *type); /** * Tries to determine tessdata component file suffix from filename, * returns true on success. */ static bool TessdataTypeFromFileName(const char *filename, TessdataType *type); // Name of file it came from. STRING data_file_name_; // Function to load the file when we need it. FileReader reader_; // True if the file has been loaded. bool is_loaded_; // True if the bytes need swapping. bool swap_; // Contents of each element of the traineddata file. GenericVector<char> entries_[TESSDATA_NUM_ENTRIES]; }; } // namespace tesseract #endif // TESSERACT_CCUTIL_TESSDATAMANAGER_H_
[ "438603353@qq.com" ]
438603353@qq.com
2fb0edc6850d7228fb44e7c38e3a871964725e0b
299f8ec0ee8b647be3a60aa6998595fd0306fa65
/WasabiEngine/WasabiEngine/GraphicEngine/GUI/CEGUIMouseButtonInjectorHandler.cpp
30216a3bf627a6b057c4f3034d7246c6c052fd6a
[]
no_license
wasabi-labs/wasabi-engine
c210b206aa11a763c5d6fefbbc9331626148939d
6ea7bbe680086852f2d901e42a568ae0adc28693
refs/heads/master
2016-09-05T12:13:27.175503
2015-06-29T20:37:44
2015-06-29T20:37:44
38,264,663
0
0
null
null
null
null
UTF-8
C++
false
false
1,647
cpp
/* * File: CEGUIMouseButtonInjectorHandler.cpp * Author: Fran_2 * * Created on 24 de abril de 2011, 16:58 */ #include "CEGUIMouseButtonInjectorHandler.h" using namespace WasabiEngine; void CEGUIMouseButtonInjectorHandler::handle(const Event* event) { if (getButtonState(event) == MOUSE_BUTTON_DOWN) { switch (getButtonType(event)) { case MOUSE_BUTTON_LEFT: CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::LeftButton); break; case MOUSE_BUTTON_MIDDLE: CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::MiddleButton); break; case MOUSE_BUTTON_RIGHT: CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::RightButton); break; case MOUSE_BUTTON_WHEELDOWN: CEGUI::System::getSingleton().injectMouseWheelChange(-1); break; case MOUSE_BUTTON_WHEELUP: CEGUI::System::getSingleton().injectMouseWheelChange(+1); break; } } else if (getButtonState(event) == MOUSE_BUTTON_UP) { switch (getButtonType(event)) { case MOUSE_BUTTON_LEFT: CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::LeftButton); break; case MOUSE_BUTTON_MIDDLE: CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::MiddleButton); break; case MOUSE_BUTTON_RIGHT: CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::RightButton); break; } } }
[ "gotusso@gmail.com" ]
gotusso@gmail.com
f9645dcb7a8784f2604c058db2e007b534df9bf5
aa1bf1cb584de17ba919b8d547eeb06b953978e3
/src/rtc_rtp_receive_imp.cc
f6ce1514de57deebfb91d17267fba585fb89c816
[ "MIT" ]
permissive
wskfjtheqian/libwebrtc
c80844f278be72fa1cd62b81ed454c1f94a77512
57aafdc64cd8da06621aaabf4973bd56df712794
refs/heads/master
2023-06-17T10:03:00.727463
2021-07-05T02:11:34
2021-07-05T02:11:34
373,116,763
1
0
MIT
2021-07-05T01:48:41
2021-06-02T09:53:35
C++
UTF-8
C++
false
false
3,211
cc
#include "rtc_rtp_receive_imp.h" #include "base/refcountedobject.h" #include "rtc_audio_track_impl.h" #include "rtc_dtls_transport_impl.h" #include "rtc_media_stream_impl.h" #include "rtc_rtp_parameters_impl.h" #include "rtc_video_track_impl.h" namespace libwebrtc { RTCRtpReceiverImpl::RTCRtpReceiverImpl( rtc::scoped_refptr<webrtc::RtpReceiverInterface> rtp_receiver) : rtp_receiver_(rtp_receiver), observer_(nullptr) {} rtc::scoped_refptr<webrtc::RtpReceiverInterface> RTCRtpReceiverImpl::rtp_receiver() { return rtp_receiver_; } void RTCRtpReceiverImpl::OnFirstPacketReceived(cricket::MediaType media_type) { if (nullptr != observer_) { observer_->OnFirstPacketReceived(static_cast<RTCMediaType>(media_type)); } } scoped_refptr<RTCMediaTrack> RTCRtpReceiverImpl::track() const { rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track = rtp_receiver_->track(); if (nullptr == track.get()) { return scoped_refptr<RTCMediaTrack>(); } if (track->kind() == webrtc::MediaStreamTrackInterface::kVideoKind) { return new RefCountedObject<VideoTrackImpl>( static_cast<webrtc::VideoTrackInterface*>(track.get())); } else if (track->kind() == webrtc::MediaStreamTrackInterface::kAudioKind) { return new RefCountedObject<AudioTrackImpl>( static_cast<webrtc::AudioTrackInterface*>(track.get())); } return scoped_refptr<RTCMediaTrack>(); } scoped_refptr<RTCDtlsTransport> RTCRtpReceiverImpl::dtls_transport() const { if (nullptr == rtp_receiver_->dtls_transport().get()) { return scoped_refptr<RTCDtlsTransport>(); } return new RefCountedObject<RTCDtlsTransportImpl>( rtp_receiver_->dtls_transport()); } const vector<string> RTCRtpReceiverImpl::stream_ids() const { vector<string> vec; for (auto item : rtp_receiver_->stream_ids()) { vec.push_back(item.c_str()); } return vec; } vector<scoped_refptr<RTCMediaStream>> RTCRtpReceiverImpl::streams() const { vector<scoped_refptr<RTCMediaStream>> streams; for (auto item : rtp_receiver_->streams()) { streams.push_back(new RefCountedObject<MediaStreamImpl>(item)); } return streams; } RTCMediaType RTCRtpReceiverImpl::media_type() const { return static_cast<RTCMediaType>(rtp_receiver_->media_type()); } const string RTCRtpReceiverImpl::id() const { return rtp_receiver_->id().c_str(); } scoped_refptr<RTCRtpParameters> RTCRtpReceiverImpl::parameters() const { return new RefCountedObject<RTCRtpParametersImpl>( rtp_receiver_->GetParameters()); } bool RTCRtpReceiverImpl::set_parameters( scoped_refptr<RTCRtpParameters> parameters) { return rtp_receiver_->SetParameters( static_cast<RTCRtpParametersImpl*>(parameters.get())->rtp_parameters()); } void RTCRtpReceiverImpl::SetObserver(RTCRtpReceiverObserver* observer) { observer_ = observer; if (nullptr == observer) { rtp_receiver_->SetObserver(nullptr); } else { rtp_receiver_->SetObserver(this); } } void RTCRtpReceiverImpl::SetJitterBufferMinimumDelay(double delay_seconds) { rtp_receiver_->SetJitterBufferMinimumDelay(delay_seconds); } } // namespace libwebrtc
[ "wskfjtheqian@163.com" ]
wskfjtheqian@163.com
3f8b965ef8d377fd7bfd74ddb9c61d814c96b8f2
8b5819e69f264ee3d14a4e1c6aebfd338baee237
/app/src/main/cpp/native-lib.cpp
3a5c8a87bfb3c4cd1a7047328e5723719eb7ce3a
[ "Apache-2.0" ]
permissive
loy2000/Jiagu
06b9db3960e80935e9f8b020dea4c78f3f1d674e
2def77d970ebbaf23a9916f6f78311f7a05922e5
refs/heads/main
2023-09-05T07:24:53.821737
2021-11-19T06:13:31
2021-11-19T06:13:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
#include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_com_frezrik_jiagu_MainActivity_stringFromJNI( JNIEnv* env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); }
[ "zhouming@paxsz.com" ]
zhouming@paxsz.com
0395cf3bd469d98011b37c7f1545ff9a78644bc9
77170cbcd2c87952763f770d50abd2d8b671f9d2
/aws-cpp-sdk-ec2/source/model/CreateVolumePermissionModifications.cpp
e65672647adf1c9137c09651d1510b6b2ca6085f
[ "JSON", "MIT", "Apache-2.0" ]
permissive
bittorrent/aws-sdk-cpp
795f1cdffb92f6fccb4396d8f885f7bf99829ce7
3f84fee22a0f4d5926aadf8d3303ea15a76421fd
refs/heads/master
2020-12-03T00:41:12.194688
2016-03-04T01:41:51
2016-03-04T01:41:51
53,150,048
1
1
null
2016-03-04T16:43:12
2016-03-04T16:43:12
null
UTF-8
C++
false
false
3,412
cpp
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/ec2/model/CreateVolumePermissionModifications.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::EC2::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; CreateVolumePermissionModifications::CreateVolumePermissionModifications() : m_addHasBeenSet(false), m_removeHasBeenSet(false) { } CreateVolumePermissionModifications::CreateVolumePermissionModifications(const XmlNode& xmlNode) : m_addHasBeenSet(false), m_removeHasBeenSet(false) { *this = xmlNode; } CreateVolumePermissionModifications& CreateVolumePermissionModifications::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode addNode = resultNode.FirstChild("Add"); if(!addNode.IsNull()) { XmlNode addMember = addNode.FirstChild("item"); while(!addMember.IsNull()) { m_add.push_back(addMember); addMember = addMember.NextNode("item"); } m_addHasBeenSet = true; } XmlNode removeNode = resultNode.FirstChild("Remove"); if(!removeNode.IsNull()) { XmlNode removeMember = removeNode.FirstChild("item"); while(!removeMember.IsNull()) { m_remove.push_back(removeMember); removeMember = removeMember.NextNode("item"); } m_removeHasBeenSet = true; } } return *this; } void CreateVolumePermissionModifications::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_addHasBeenSet) { unsigned addIdx = 1; for(auto& item : m_add) { Aws::StringStream addSs; addSs << location << index << locationValue << ".Add." << addIdx++; item.OutputToStream(oStream, addSs.str().c_str()); } } if(m_removeHasBeenSet) { unsigned removeIdx = 1; for(auto& item : m_remove) { Aws::StringStream removeSs; removeSs << location << index << locationValue << ".Remove." << removeIdx++; item.OutputToStream(oStream, removeSs.str().c_str()); } } } void CreateVolumePermissionModifications::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_addHasBeenSet) { unsigned addIdx = 1; for(auto& item : m_add) { Aws::StringStream addSs; addSs << location << ".item." << addIdx++; item.OutputToStream(oStream, addSs.str().c_str()); } } if(m_removeHasBeenSet) { unsigned removeIdx = 1; for(auto& item : m_remove) { Aws::StringStream removeSs; removeSs << location << ".item." << removeIdx++; item.OutputToStream(oStream, removeSs.str().c_str()); } } }
[ "henso@amazon.com" ]
henso@amazon.com
a4be4c5e86005f394249ec8d012984eab5f9dc00
36c84b0e38534f768d119cebfd744ed44b04192f
/Tetris/ScreenDef.h
985c5bbfef1058459556d3919a3ec0e37a3f9df6
[]
no_license
grygorek/TetrisInMemory
ed849d4ea0af590ba893db766b6f0f99cf7b34f4
c219fbff389db1afea37eae795be4e6d4e4061a9
refs/heads/master
2020-09-09T20:36:26.517615
2019-11-13T22:33:21
2019-11-13T22:33:21
221,561,857
2
0
null
2019-11-13T22:33:22
2019-11-13T22:15:16
null
UTF-8
C++
false
false
1,943
h
/// @file /// /// @author: Piotr Grygorczuk grygorek@gmail.com /// /// @copyright Copyright 2019 Piotr Grygorczuk /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// /// o Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// /// o 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. /// /// o My name may not 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. /// /// @brief #ifndef __TETRIS_SCREEN_DEF_H__ #define __TETRIS_SCREEN_DEF_H__ #include "Screen.h" namespace Tetris { /// @brief Tetris screen definition /// /// Satisfies requirements: /// [REQ_ScreenSize](https://github.com/grygorek/TetrisArch#REQ_ScreenSize) using TetrisScreen = Screen<10, 8>; } #endif //__TETRIS_SCREEN_DEF_H__
[ "grygorek@gmail.com" ]
grygorek@gmail.com
65368944eace3b3caad5b819cd00196c0454c12a
e0aeb029f72bf1f14780aa5d57458da6fca95016
/PDFs/JohnsonSUPdf.hh
de36fe26592e46160b0f20d07c6db06d44ffe4d1
[]
no_license
AdrianoDee/MyGooFit
ac19ec6352c07fd6d276e425059a133609ffedbe
4a5ab51ef34e728935e5d607da5d22ec961da1e3
refs/heads/master
2021-01-17T01:54:25.248996
2017-05-05T17:01:56
2017-05-05T17:01:56
52,297,083
1
2
null
null
null
null
UTF-8
C++
false
false
370
hh
#ifndef JOHNSONSU_PDF_HH #define JOHNSONSU_PDF_HH #include "GooPdf.hh" class JohnsonSUPdf : public GooPdf { public: JohnsonSUPdf (std::string n, Variable* _x, Variable* m, Variable* s, Variable* g, Variable* d); __host__ fptype integrate (fptype lo, fptype hi) const; __host__ virtual bool hasAnalyticIntegral () const {return true;} private: }; #endif
[ "adriano.diflorio@ba.infn.it" ]
adriano.diflorio@ba.infn.it
3a34dd5697b3590d209e6fd642d55e015854f4f9
1bf8b46afad5402fe6fa74293b464e1ca5ee5fd7
/SDK/BPF_Experience_parameters.h
e02c9d7616d18a344e23c09c883838f82aff77de
[]
no_license
LemonHaze420/ShenmueIIISDK
a4857eebefc7e66dba9f667efa43301c5efcdb62
47a433b5e94f171bbf5256e3ff4471dcec2c7d7e
refs/heads/master
2021-06-30T17:33:06.034662
2021-01-19T20:33:33
2021-01-19T20:33:33
214,824,713
4
0
null
null
null
null
UTF-8
C++
false
false
5,382
h
#pragma once #include "../SDK.h" // Name: Shenmue3SDK, Version: 1.4.1 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function BPF_Experience.BPF_Experience_C.BPF_UpdateTrainingLevelUpData struct UBPF_Experience_C_BPF_UpdateTrainingLevelUpData_Params { struct FST_SparringResultLevelUpData Player; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FST_SparringResultLevelUpData ATK; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FST_SparringResultLevelUpData VIT; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function BPF_Experience.BPF_Experience_C.BPF_InitializeTrainingLevelUpData struct UBPF_Experience_C_BPF_InitializeTrainingLevelUpData_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FST_SparringResultLevelUpData Player; // (Parm, OutParm) struct FST_SparringResultLevelUpData ATK; // (Parm, OutParm) struct FST_SparringResultLevelUpData VIT; // (Parm, OutParm) }; // Function BPF_Experience.BPF_Experience_C.BPF_ShouldShowExpHintPostTraining struct UBPF_Experience_C_BPF_ShouldShowExpHintPostTraining_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function BPF_Experience.BPF_Experience_C.BPF_CalcPlayerExpModifer_Energy_Lerp struct UBPF_Experience_C_BPF_CalcPlayerExpModifer_Energy_Lerp_Params { float Min; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float Max; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float Multiplier; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function BPF_Experience.BPF_Experience_C.BPF_DebugLogPlayerExpModifier struct UBPF_Experience_C_BPF_DebugLogPlayerExpModifier_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function BPF_Experience.BPF_Experience_C.BPF_CalcPlayerExpModifier_Energy struct UBPF_Experience_C_BPF_CalcPlayerExpModifier_Energy_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float Multiplier; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function BPF_Experience.BPF_Experience_C.BPF_CalcPlayerExpModifier_Difficulty struct UBPF_Experience_C_BPF_CalcPlayerExpModifier_Difficulty_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function BPF_Experience.BPF_Experience_C.BPF_CalcPlayerExpModifier struct UBPF_Experience_C_BPF_CalcPlayerExpModifier_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "35783139+LemonHaze420@users.noreply.github.com" ]
35783139+LemonHaze420@users.noreply.github.com
0c1c267f1b870c8877da73a53a4c06cec92b5431
15f92601d47d390ac454a717074d9661dae6a3ac
/src/zaf/control/layout/anchor_layouter.cpp
0cc9bed344bf4a33a22c3f4da76b371ec5091277
[ "MIT" ]
permissive
Zplutor/zaf
14ddf27bfb61a43fe9cfb5a38b519b25964ce1d7
312278af4f2f9cc99748ee8cc357532caafe62a0
refs/heads/master
2023-08-05T11:15:30.437396
2023-08-02T16:32:42
2023-08-02T16:32:42
45,374,274
15
8
null
null
null
null
UTF-8
C++
false
false
2,949
cpp
#include <zaf/control/layout/anchor_layouter.h> #include <zaf/control/control.h> #include <zaf/creation.h> namespace zaf { namespace { void LayoutChild( const Rect& current_rect, const Rect& previous_rect, Control& child ) { auto change_single_dimension_with_anchor = []( bool has_front_anchor, bool has_back_anchor, float parent_old_size, float parent_new_size, float old_position, float old_size, float& new_position, float& new_size ) { if (has_front_anchor && !has_back_anchor) { new_position = old_position; new_size = old_size; } else if (!has_front_anchor && has_back_anchor) { float old_back = parent_old_size - old_position - old_size; new_position = parent_new_size - old_back - old_size; new_size = old_size; } else if (has_front_anchor && has_back_anchor) { new_position = old_position; float old_back = parent_old_size - old_position - old_size; new_size = parent_new_size - old_back - new_position; } else { new_position = old_position; new_size = old_size; } }; Anchor anchor = child.Anchor(); bool has_left_anchor = (anchor & Anchor::Left) == Anchor::Left; bool has_right_anchor = (anchor & Anchor::Right) == Anchor::Right; bool has_top_anchor = (anchor & Anchor::Top) == Anchor::Top; bool has_bottom_anchor = (anchor & Anchor::Bottom) == Anchor::Bottom; const Rect& child_old_rect = child.Rect(); Rect child_new_rect; change_single_dimension_with_anchor( has_left_anchor, has_right_anchor, previous_rect.size.width, current_rect.size.width, child_old_rect.position.x, child_old_rect.size.width, child_new_rect.position.x, child_new_rect.size.width ); change_single_dimension_with_anchor( has_top_anchor, has_bottom_anchor, previous_rect.size.height, current_rect.size.height, child_old_rect.position.y, child_old_rect.size.height, child_new_rect.position.y, child_new_rect.size.height ); child.SetRect(child_new_rect); } class AnchorLayouter : public Layouter { public: void Layout( const Control& parent, const Rect& parent_old_rect, const std::vector<std::shared_ptr<Control>>& children ) override { //Do nothing when previous rect is empty, or the layouts of chilren //are incorrect. if (parent_old_rect.IsEmpty()) { return; } for (const auto& child : children) { LayoutChild(parent.Rect(), parent_old_rect, *child); } } }; } std::shared_ptr<Layouter> GetAnchorLayouter() { static auto layouter = zaf::Create<AnchorLayouter>(); return layouter; } }
[ "zplutor@qq.com" ]
zplutor@qq.com
e7dbeabab1680520593115bd6ecc2141844f66c1
f4db3fa275cf032eaa0c1db657c23a36d7e62577
/engine/src/TextureChangeEvent.cpp
395cdf88a2ff414d06974af41bcc8f83b6bd8bca
[ "MIT" ]
permissive
skryabiin/core
0e5f7af0c08ebd0118466b5b21023914820eb442
13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7
refs/heads/master
2016-09-05T14:46:03.261125
2016-03-02T16:01:56
2016-03-02T16:01:56
34,462,571
0
0
null
null
null
null
UTF-8
C++
false
false
605
cpp
#include "TextureChangeEvent.hpp" #include "Console.hpp" #include "EventProcessor.hpp" namespace core { TextureChangeEvent::TextureChangeEvent() { lua_reg("entityId", &entity); lua_reg("textureName", &textureName); lua_reg("sourceTextureRect", &sourceTextureRect); lua_reg("facetId", &facetId); } std::string TextureChangeEvent::getEventTypeNameImpl() { return "TextureChangeEvent"; } bool TextureChangeEvent::createFromLua(LuaState& lua) { auto tce = TextureChangeEvent{}; tce.fromLua(lua); single<EventProcessor>().process(tce); return true; } } //end namespace core
[ "jlynem@gmail.com" ]
jlynem@gmail.com
88d0eaf7580482a98f0f7e4f6c6aa48912e6de06
3e5a1b0b6fbede2fbbe495635d86ec3370a2054f
/example/01_basic/main.cpp
214420335d08aae7d6ba6b73d8a53756ea0da0a2
[ "Apache-2.0" ]
permissive
TNCT-Mechatech/SerialBridgeMbed
354364e33be3e6fa167c51f8cb31ee86fc6ccda2
6c34823b26eccb3b2ec659820df9ae229cb6c5c6
refs/heads/main
2023-03-29T22:59:26.152141
2021-04-07T08:13:12
2021-04-07T08:13:12
338,263,212
0
0
Apache-2.0
2021-04-07T08:13:12
2021-02-12T08:37:00
C++
UTF-8
C++
false
false
157
cpp
#include "mbed.h" #include "SerialBridge.h" BufferSerial _serial(USBTX, USBRX,9600,1000); SerialBridge dev(&_serial); int main(){ return 0; }
[ "silverbro007@icloud.com" ]
silverbro007@icloud.com
d855991a69896977f8ba46c584331638b9ff6d2b
bbac388eb6b53daec63190e2f271a18fe9bfb163
/abc017/D.cpp
c014ac0d6abca01c74e88927ba6efac147744ae5
[]
no_license
tatsumack/atcoder
8d94cf29160b6553b0c089cb795c54efd3fb0f7b
fbe1e1eab80c4c0680ec046acdc6214426b19650
refs/heads/master
2023-06-17T23:09:54.056132
2021-07-04T13:03:59
2021-07-04T13:03:59
124,963,709
0
0
null
null
null
null
UTF-8
C++
false
false
1,539
cpp
#include <algorithm> #include <bitset> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <numeric> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> #define int long long #define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i) #define REPS(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i) #define FOR(i, a, b) for (int i = (a), i##_len = (b); i <= i##_len; ++i) #define REV(i, a, b) for (int i = (a); i >= (b); --i) #define CLR(a, b) memset((a), (b), sizeof(a)) #define DUMP(x) cout << #x << " = " << (x) << endl; #define INF (3e15) using namespace std; int N, M, F[100005], dp[100005], sum[100005]; int mod = 1e9 + 7; signed main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> N >> M; REP(i, N) cin >> F[i]; int l = 0; vector<int> L(N + 1, 0); map<int, int> cnt; FOR(r, 0, N - 1) { cnt[F[r]]++; while (l + 1 <= r && cnt[F[r]] > 1) { cnt[F[l]]--; l++; } L[r + 1] = l; } dp[0] = 1; sum[0] = 1; FOR(i, 1, N) { if (L[i] > 0) { dp[i] = (sum[i - 1] - sum[L[i] - 1] + mod) % mod; } else { dp[i] = sum[i - 1]; } sum[i] = (sum[i - 1] + dp[i]) % mod; } cout << dp[N] << endl; return 0; }
[ "tatsu.mack@gmail.com" ]
tatsu.mack@gmail.com
3a7cd853ac876b4e8292ed94a587ea079f0ea5dc
4cf3985b76da8af9b43d96cec1bb72258a6434d4
/LODConvert/FALCLIB/INCLUDE/MsgInc/LandingMessage.h
f009c3a019f7362a688a35d3dfaac181e14f8f12
[]
no_license
d16/freefalcon-contrib
6d235885c1629739d2bc47006c4ec0d1838fa63c
9995379bd5ed734acfccd30918117c3b3765e5ca
refs/heads/master
2020-12-24T17:45:02.978021
2013-01-17T18:41:28
2013-01-17T18:41:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,530
h
/* * Machine Generated include file for message "Landing Message". * NOTE: This file is read only. DO NOT ATTEMPT TO MODIFY IT BY HAND. * Generated on 01-April-1997 at 18:57:03 * Generated from file EVENTS.XLS by Kevin Klemmick */ #ifndef _LANDINGMESSAGE_H #define _LANDINGMESSAGE_H /* * Required Include Files */ #include "F4vu.h" #include "mission.h" #pragma pack (1) /* * Message Type Landing Message */ class FalconLandingMessage : public FalconEvent { public: FalconLandingMessage(VU_ID entityId, VuTargetEntity *target, VU_BOOL loopback=TRUE); FalconLandingMessage(VU_MSG_TYPE type, VU_ID senderid, VU_ID target); ~FalconLandingMessage(void); int Size (void) { return sizeof(dataBlock) + FalconEvent::Size();}; int Decode (VU_BYTE **buf, int length) { int size; size = FalconEvent::Decode (buf, length); memcpy (&dataBlock, *buf, sizeof (dataBlock)); *buf += sizeof (dataBlock); size += sizeof (dataBlock); return size; }; int Encode (VU_BYTE **buf) { int size; size = FalconEvent::Encode (buf); memcpy (*buf, &dataBlock, sizeof (dataBlock)); *buf += sizeof (dataBlock); size += sizeof (dataBlock); return size; }; class DATA_BLOCK { public: ushort campID; uchar pilotID; } dataBlock; protected: int Process(uchar autodisp); }; #pragma pack () #endif
[ "pmvstrm@yahoo.de" ]
pmvstrm@yahoo.de
98cb46dd684951751d437e9732143752d2f5c21c
f290b09be681c454b4e0f2714f6dbe75caab1fa3
/src/Quantize.cpp
8e3189ca909e1e8317db3f86b565eff3718a6084
[]
no_license
ayu1992/Photoshop
bbd81de80f2c52fa6c7fef8019cd7c26d1dafd2f
bd97f08d8ddedd4459c1afe8dd98a6b1ddb912bd
refs/heads/master
2020-06-02T18:39:43.203391
2015-04-05T22:47:41
2015-04-05T22:47:41
33,431,249
0
1
null
null
null
null
UTF-8
C++
false
false
626
cpp
#include "Quantize.h" #include "PixelBuffer.h" #include "ColorData.h" #include <iostream> #include <cmath> using std::cout; using std::endl; Quantize::Quantize(int size){}; Quantize::~Quantize(){}; void Quantize::applyQuantize(PixelBuffer * canvas, int bins){ float values = 1.0 / (bins-1); for(int x = 0; x < canvas->getWidth(); x++){ for(int y = 0; y < canvas->getHeight(); y++){ ColorData c = canvas->getPixel(x,y); c.setRed( round(c.getRed() / values) * values ); c.setGreen( round(c.getGreen() / values) * values); c.setBlue( round(c.getBlue() / values) * values); canvas->setPixel(x,y,c); } } }
[ "tisisfrustrating@gmail.com" ]
tisisfrustrating@gmail.com