text
stringlengths
8
6.88M
//==================================================================================== // @Title: DIALOGUE BOX //------------------------------------------------------------------------------------ // @Location: /prolix/interface/include/cmpDialogueBox.cpp // @Author: Kevin Chen // @Rights: Copyright(c) 2011 Visionary Games //==================================================================================== #include "../include/cmpDialogueBox.h" //==================================================================================== // cmpDialogueBox //==================================================================================== cmpDialogueBox::cmpDialogueBox(std::string rScript, cSprite *rFaceset, int rFaceFrame, cFont rFont, eDirection rOrientation, eDirection rLocation, Point rPos, Dimensions rDim, cTextureId rSkinId): cmpWindow(rPos, rDim, rSkinId) { // setting default values faceset = rFaceset; face_frames.push_back(rFaceFrame); orientation = rOrientation; location = rLocation; script = rScript; font = rFont; currentPage = 0; Configure(); } cmpDialogueBox::cmpDialogueBox(std::string rScript, cFont rFont, Point rPos, Dimensions rDim, cTextureId rSkinId): cmpWindow(rPos, rDim, rSkinId) { script = rScript; font = rFont; faceset = NULL; currentPage = 0; Configure(); } cmpDialogueBox::cmpDialogueBox(std::string rScript, cSprite *rFaceset, std::vector<int> rFaceFrames, cFont rFont, eDirection rOrientation, eDirection rLocation, Point rPos, Dimensions rDim, cTextureId rSkinId): cmpWindow(rPos, rDim, rSkinId) { script = rScript; faceset = rFaceset; face_frames = rFaceFrames; font = rFont; orientation = rOrientation; location = rLocation; currentPage = 0; Configure(); } void cmpDialogueBox::Configure() { // configure flipping page command flipPage = new cCommand(SDLK_z, 100, false); std::string page; int width; while (script.find ("@") != std::string::npos) { page = script.substr(0, script.find ("@") + 1); if (faceset != NULL) width = dim.w - faceset->spriteset[0].dim.w - 32; else width = dim.w - 32; pages.push_back(LineWrapParagraph (font, page, width)); script = script.substr(script.find ("@") + 1, script.length()); } } void cmpDialogueBox::Move() { if (flipPage->Pollable()) { currentPage++; } if (currentPage == pages.size()) { currentPage = pages.size() - 1; alive = false; } if (currentPage == face_frames.size()) { faceset = NULL; } } void cmpDialogueBox::Draw() { cmpWindow::Draw(); if (faceset != NULL) { int line = 0; Point facePos; if (location == LEFT) { facePos = pos + Point(16,16); } else { facePos = Point(pos.x + dim.w - faceset->spriteset[0].dim.w - 16, pos.y + 16); } float flip = 1; if (orientation == LEFT) flip = -1; faceset->spritesheet->Draw(flip, 1, facePos, &faceset->spriteset[currentPage]); cTexture *rendered = Engine->Text->Prerender(font, pages[currentPage][0]); for (unsigned int i=0; i<pages[currentPage].size(); i++) { int linespacing = line*rendered->dim.h; if (location == LEFT) { Engine->Text->Write(font, pages[currentPage][i], pos + Point(32 + faceset->spriteset[face_frames[0]].dim.w, 16 + linespacing)); } else { Engine->Text->Write(font, pages[currentPage][i], pos + Point(16, 16 + linespacing)); } line++; } } else { cTexture *rendered = Engine->Text->Prerender(font, pages[currentPage][0]); int line = 0; for (unsigned int i=0; i<pages[currentPage].size(); i++) { int linespacing = line*rendered->dim.h; Engine->Text->Write(font, pages[currentPage][i], pos + Point(16, 16 + linespacing)); line++; } } // draw continuation arrow if (pages.size() > 1) { frames->DrawFrame(F_L2N2, Point(pos.x + (dim.w - frames->spriteset[F_L2N2].dim.w)/2, pos.y + dim.h - 32)); } } void cmpDialogueBox::Update() { Draw(); Move(); } cmpDialogueBox::~cmpDialogueBox() { // remove all lines of text from text stack for (unsigned int i=0; i<pages.size(); i++) { for (unsigned int j=0; j<pages[i].size(); j++) { AssetMgr->Remove<Texture>(font.id + font.color.Format() + pages[i][j]); } } LogMgr->Write(VERBOSE, "cmpDialogueBox::~cmpDialogueBox >>>> Deleted a dialogue window"); }
//==================================================================================== // @Title: PROLIX ENGINE //------------------------------------------------------------------------------------ // @Location: /prolix/engine/include/PrlxEngine.h // @Author: Kevin Chen // @Rights: Copyright(c) 2011 Visionary Games //------------------------------------------------------------------------------------ // @Description: // // The PROLIX Game Engine, created and developed by Visionary Games, is designed to // interface with SDL and OpenGL to create Cadabolg. // //==================================================================================== #ifndef __PROLIX_ENGINE_H__ #define __PROLIX_ENGINE_H__ #include <SDL.h> #include "../include/PrlxInput.h" #include "../include/PrlxGraphics.h" #include "../include/PrlxText.h" #include "../include/PrlxPhysics.h" #include "../include/PrlxMixer.h" #include "../../common/include/cTimer.h" //==================================================================================== // **** ENGINE CONSTANTS AND SETTINGS **** //==================================================================================== // [PROLIX RESOLUTION SETTINGS] #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 640 #define SCREEN_BPP 32 // [WINDOW STATE DEFINITIONS] #define FULLSCREEN SDL_HWPALETTE | SDL_DOUBLEBUF | SDL_FULLSCREEN #define RESIZABLE SDL_HWPALETTE | SDL_DOUBLEBUF | SDL_RESIZABLE #define WINDOWED SDL_HWPALETTE | SDL_DOUBLEBUF // [FRAME RATE SETTINGS] #define FRAMES_PER_SECOND 120 // singleton accessor #define Engine PrlxEngine::GetInstance() //==================================================================================== // PrlxEngine //==================================================================================== class PrlxEngine { friend class cGame; static PrlxEngine *mInstance; // instance of the singleton class // frame regulating variables cTimer mFps; cTimer mTimer; // engine state variables bool mExit; bool mWindowed; bool mFirstIter; SDL_Surface *mScreen; bool Initialize(); // intializes Engine and window properties/attributes void RegulateFps(); // regulates the frames per second bool Update(); // poll inputs, regulate frame rate and refresh window bool Loop(); // returns true if Engine is still in operation void HandleInput(); // poll inputs and executes actions PrlxEngine(); // Constructor PrlxEngine(const PrlxEngine &); // Copy constructor PrlxEngine &operator=(const PrlxEngine &); // Assignment operator ~PrlxEngine(); // Destructor public: // Get instance of the singleton class static PrlxEngine *GetInstance(); // PROLIX components PrlxGraphics *Graphics; // Graphics manager PrlxInput *Input; // Keyboard/Mouse handler PrlxText *Text; // Font and text blit manager PrlxPhysics *Physics; // Physics manager PrlxMixer *Mixer; // Audio manager // set the caption and icon for the application void SetCaptionAndIcon(std::string caption, std::string iconPath); void ToggleWindow(); // toggles between windowed and fullscreen mode void CloseApplication(); // terminate application void Shutdown(); // safely close application and free resources }; #endif
#include<bits/stdc++.h> using namespace std; struct tree{ int l,r,tag,sum; }; struct ope{ int l,r; }; tree tr[600000]; ope o[300000]; int ans[300000],n,m; void readit(){ scanf("%d%d",&n,&m); for (int i=1;i<=m;i++) scanf("%d%d",&o[i].l,&o[i].r); } void writeit(){ for (int i=1;i<=m;i++) printf("%d\n",ans[i]); } void build(int k,int s,int t){ tr[k].l=s; tr[k].r=t; if (s==t){ tr[k].sum=1; return; } int mid=(s+t)>>1; build(k<<1,s,mid); build(k<<1|1,mid+1,t); tr[k].sum=tr[k<<1].sum+tr[k<<1|1].sum; } void pushdown(int k){ int x=tr[k].r-tr[k].l+1; tr[k<<1].tag=1; tr[k<<1|1].tag=1; tr[k<<1].sum=0; tr[k<<1|1].sum=0; tr[k].tag=0; } void updata(int k,int s,int t){ int l=tr[k].l,r=tr[k].r; if (s==l&&t==r){ tr[k].tag=1; tr[k].sum=0; return; } if (tr[k].tag) pushdown(k); int mid=(l+r)>>1; if (t<=mid) updata(k<<1,s,t); else if (s>mid) updata(k<<1|1,s,t); else{ updata(k<<1,s,mid); updata(k<<1|1,mid+1,t); } tr[k].sum=tr[k<<1].sum+tr[k<<1|1].sum; } void work(){ build(1,1,n); for (int i=1;i<=m;i++){ updata(1,o[i].l,o[i].r); ans[i]=tr[1].sum; } } int main(){ readit(); work(); writeit(); return 0; }
#include "RandomWalkModel.hpp" void RandomWalkModel::move(Human & h) { h.getPos(); }
/******************** *-=baseobject.hpp=-* ******************** Auteur : My?terious Description : Contient la base pour créer un objet. */ #ifndef HEADER_SCENE_BASEOBJECT #define HEADER_SCENE_BASEOBJECT //-=Inclusion des headers=-// #include <irrlicht.h> #include "core/basemodule.hpp" //-=Fin de la section=-// namespace ohm { namespace scene { class BaseObject : public ohm::core::BaseModule, public irr::scene::ISceneNode { public: BaseObject(ohm::core::IrrlichtEngine* engine, irr::scene::ISceneNode* parent, irr::core::vector3df position, irr::core::vector3df rotation, irr::core::vector3df scale, irr::core::stringc name, irr::s32 id); virtual ~BaseObject(); virtual void OnRegisterSceneNode(); virtual void render(); virtual irr::core::aabbox3d<irr::f32> getBoundingBox(); private: irr::core::aabbox3d<irr::f32> _bbox; }; } } #endif
// Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. // Example 1: // Input: nums = [-4,-1,0,3,10] // Output: [0,1,9,16,100] // Explanation: After squaring, the array becomes [16,1,0,9,100]. // After sorting, it becomes [0,1,9,16,100]. // Example 2: // Input: nums = [-7,-3,2,3,11] // Output: [4,9,9,49,121] // Constraints: // 1 <= nums.length <= 104 // -104 <= nums[i] <= 104 // nums is sorted in non-decreasing order. #include<bits/stdc++.h> using namespace std; class Solution { public: vector<int> sortedSquares(vector<int>& nums) { for(int i=0;i<nums.size();i++){ nums[i] = nums[i]*nums[i]; } sort(nums.begin(), nums.end()); return nums; } };
#include "rvstereocamera.h" #include "math.h" RVStereoCamera::RVStereoCamera(float eyeDistance, float focalDistance, int cameraType): RVCamera(), m_eyeDistance(eyeDistance), m_focalDistance(focalDistance), m_cameraType(cameraType) { } float RVStereoCamera::eyeDistance() const { return m_eyeDistance; } void RVStereoCamera::setEyeDistance(float eyeDistance) { m_eyeDistance = eyeDistance; } float RVStereoCamera::focalDistance() const { return m_focalDistance; } void RVStereoCamera::setFocalDistance(float focalDistance) { m_focalDistance = focalDistance; } QMatrix4x4 RVStereoCamera::viewMatrix() { switch (m_cameraType) { case RV_CAMERA_MONO : return RVCamera::viewMatrix(); break; case RV_CAMERA_LEFT : return leftViewMatrix(); break; case RV_CAMERA_RIGHT : return rightViewMatrix(); break; } } QMatrix4x4 RVStereoCamera::projectionMatrix() { switch (m_cameraType) { case RV_CAMERA_MONO : return RVCamera::projectionMatrix(); break; case RV_CAMERA_LEFT : return leftProjectionMatrix(); break; case RV_CAMERA_RIGHT : return rightProjectionMatrix(); break; } } QMatrix4x4 RVStereoCamera::leftViewMatrix() { QMatrix4x4 view; QVector3D v = (m_target-m_position); v.crossProduct(v, m_up); QVector3D posOG = m_position - (m_eyeDistance/2)*(v/v.length()); QVector3D cibleOG = m_target - (m_eyeDistance/2)*(v/v.length()); view.lookAt(posOG, cibleOG, m_up); return view; } QMatrix4x4 RVStereoCamera::leftProjectionMatrix() { QMatrix4x4 proj; if (m_isOrthogonal) { proj.ortho(-m_fov * m_aspect/10, m_fov * m_aspect/10, -m_fov/10, m_fov/10, m_zMin, m_zMax); } else { float top = m_zMin * tan((m_fov*M_PI)/360); float bottom = -top; float a = (m_focalDistance*top)/m_zMin; float b = a -(m_eyeDistance/2); float c = a +(m_eyeDistance/2); float left = (m_zMin * b) / m_focalDistance; float right = (m_zMin * c) / m_focalDistance; proj.frustum(-left, right, bottom, top, m_zMin, m_zMax); } return proj; } QMatrix4x4 RVStereoCamera::rightViewMatrix() { QMatrix4x4 view; QVector3D v = (m_target-m_position); v.crossProduct(v, m_up); v.normalize(); QVector3D posOG = m_position + (m_eyeDistance/2)*v; QVector3D cibleOG = m_target + (m_eyeDistance/2)*v; view.lookAt(posOG, cibleOG, m_up); return view; } QMatrix4x4 RVStereoCamera::rightProjectionMatrix() { QMatrix4x4 proj; if (m_isOrthogonal) { proj.ortho(-m_fov * m_aspect/10, m_fov * m_aspect/10, -m_fov/10, m_fov/10, m_zMin, m_zMax); } else { float top = m_zMin * tan((m_fov*M_PI)/360); float bottom = -top; float a = (m_focalDistance*top)/m_zMin; float b = a +(m_eyeDistance/2); float c = a - (m_eyeDistance/2); float left = (m_zMin * b) / m_focalDistance; float right = (m_zMin * c) / m_focalDistance; proj.frustum(-left, right, bottom, top, m_zMin, m_zMax); } return proj; } int RVStereoCamera::cameraType() const { return m_cameraType; } void RVStereoCamera::setCameraType(int cameraType) { m_cameraType = cameraType; }
#ifndef VISUAL_ELEMENT_H #define VISUAL_ELEMENT_H #include <SDL2/SDL.h> #include <memory> #include "../Geometry.h" #include "PhysicsElement.h" using namespace std; class VisualElement: public PhysicsElement { public: VisualElement(SDL_Texture* tex, const Rectangle& rect); virtual ~VisualElement(); void draw(SDL_Renderer* ren); private: SDL_Texture* tex; public: virtual string getActorType() { return "VisualElement"; } }; #endif
#pragma once #include "Turret.h" class TurretSkinnedMesh : public hg::IComponent { DECLARE_COMPONENT_TYPEID public: TurretSkinnedMesh(); hg::IComponent* MakeCopyDerived() const; void Start(); void Update(); void OnMessage(hg::Message* msg); private: hg::Transform* GetMuzzle() const; bool CanSeePlayer(hg::Entity* player) const; bool m_bInitTransform; hg::Entity* m_Player; hg::Transform* m_Gun; hg::Animation* m_Animation; hg::Transform m_Muzzle; float m_Yaw; XMVECTOR m_GunForward; XMVECTOR m_GunRight; };
#include<bits/stdc++.h> #define rep(i, s, n) for (int i = (s); i < (int)(n); i++) #define INF ((1LL<<62)-(1LL<<31)) /*オーバーフローしない程度に大きい数*/ #define MOD 1000000007 using namespace std; using ll = long long; using Graph = vector<vector<int>>; using pint = pair<int,int>; const double PI = 3.14159265358979323846; int main(){ ll a,b,x; cin >> a >> b >> x; //b以下のxの数はb/x(切り捨て),そっからa以下の数を引けばいい ll p = a/x; ll q = b/x; ll ans = q - p; if(a % x == 0)ans++; cout << ans << endl; }
// // KObject.cpp <Keepi> // // Made by Julien Fortin // contact <julien.fortin.it@gmail.com> // #include "DEBUG.h" #include "KObject.hpp" #include "KTypeException.hpp" KObject::KObject(long long int integer) { this->__init(); this->__integer = new KInteger(integer); } KObject::KObject(double real) { this->__init(); this->__double = new KDouble(real); } KObject::KObject(char *str) { size_t len = strlen(str); str[len - 1] = 0; this->__init(); this->__string = new KString(str); } KObject::KObject(std::string str) { this->__init(); this->__string = new KString(str); } KObject::KObject(bool b) { this->__init(); this->__bool = new KBool(b); } KObject::~KObject() { delete this->__integer; delete this->__string; delete this->__double; delete this->__bool; } void KObject::__init() { this->__integer = 0; this->__string = 0; this->__double = 0; this->__bool = 0; } KInteger* KObject::getInteger() const { return this->__integer; } KString* KObject::getString() const { return this->__string; } KDouble* KObject::getDouble() const { return this->__double; } KBool* KObject::getBool() const { return this->__bool; } const std::string& KObject::getType() const { if (this->getInteger()) return this->getInteger()->getType(); else if (this->getString()) return this->getString()->getType(); else if (this->getDouble()) return this->getDouble()->getType(); else if (this->getBool()) return this->getBool()->getType(); throw KTypeException("TypeInternalError: Empty interface KObject."); } bool KObject::toBool() const { if (this->getInteger()) return this->getInteger()->toBool(); else if (this->getString()) return this->getString()->toBool(); else if (this->getDouble()) return this->getDouble()->toBool(); else if (this->getBool()) return this->getBool()->getValue(); throw KTypeException("TypeInternalError: Empty interface KObject.");} KObject* KObject::add(KObject* obj1, KObject* obj2) { KInteger* integer1 = obj1->getInteger(); KInteger* integer2 = obj2->getInteger(); KDouble* double1 = obj1->getDouble(); KDouble* double2 = obj2->getDouble(); KString* string1 = obj1->getString(); KString* string2 = obj2->getString(); KBool* bool1 = obj1->getBool(); KBool* bool2 = obj2->getBool(); if (integer1 && integer2) return new KObject(*integer1 + *integer2); else if (integer1 && double2) return new KObject(*integer1 + *double2); else if (integer1 && string2) return new KObject(*integer1 + *string2); else if (integer2 && double2) return new KObject(*integer1 + *bool2); else if (double1 && double2) return new KObject(*double1 + *double2); else if (double1 && integer2) return new KObject(*double1 + *integer2); else if (double1 && string2) return new KObject(*double1 + *string2); else if (double1 && bool2) return new KObject(*double1 + *bool2); else if (string1 && string2) return new KObject(*string1 + *string2); else if (string1 && integer2) return new KObject(*string1 + *integer2); else if (string1 && double2) return new KObject(*string1 + *double2); else if (string1 && bool2) return new KObject(*string1 + *bool2); else if (bool1 && bool2) return new KObject(*bool1 + *bool2); else if (bool1 && integer2) return new KObject(*bool1 + *integer2); else if (bool1 && double2) return new KObject(*bool1 + *double2); else if (bool1 && string2) return new KObject(*bool1 + *string2); throw KTypeException("TypeError: unsupported operand type(s) for +"); } KObject* KObject::sub(KObject* obj1, KObject* obj2) { KInteger* integer1 = obj1->getInteger(); KInteger* integer2 = obj2->getInteger(); KDouble* double1 = obj1->getDouble(); KDouble* double2 = obj2->getDouble(); if (integer1 && integer2) return new KObject(*integer1 - *integer2); else if (integer1 && double2) return new KObject(*integer1 - *double2); else if (double1 && double2) return new KObject(*double1 - *double2); else if (double1 && integer2) return new KObject(*double1 - *integer2); throw KTypeException("TypeError: unsupported operand type(s) for -"); } KObject* KObject::div(KObject* obj1, KObject* obj2) { KInteger* integer1 = obj1->getInteger(); KInteger* integer2 = obj2->getInteger(); KDouble* double1 = obj1->getDouble(); KDouble* double2 = obj2->getDouble(); if (integer1 && integer2) return new KObject(*integer1 / *integer2); else if (integer1 && double2) return new KObject(*integer1 / *double2); else if (double1 && double2) return new KObject(*double1 / *double2); else if (double1 && integer2) return new KObject(*double1 / *integer2); throw KTypeException("TypeError: unsupported operand type(s) for /"); } KObject* KObject::mul(KObject* obj1, KObject* obj2) { KInteger* integer1 = obj1->getInteger(); KInteger* integer2 = obj2->getInteger(); KDouble* double1 = obj1->getDouble(); KDouble* double2 = obj2->getDouble(); KString* string1 = obj1->getString(); KString* string2 = obj2->getString(); if (integer1 && integer2) return new KObject(*integer1 * *integer2); else if (integer1 && double2) return new KObject(*integer1 * *double2); else if (integer1 && string2) return new KObject(*integer1 * *string2); else if (double1 && double2) return new KObject(*double1 * *double2); else if (double1 && integer2) return new KObject(*double1 * *integer2); else if (double1 && string2) return new KObject(*double1 * *string2); else if (string1 && string2) return new KObject(*string1 * *string2); else if (string1 && integer2) return new KObject(*string1 * *integer2); else if (string1 && double2) return new KObject(*string1 * *double2); throw KTypeException("TypeError: unsupported operand type(s) for *"); } KObject* KObject::neg(KObject* obj) { KInteger* integer = obj->getInteger(); KDouble* real = obj->getDouble(); if (integer) integer->neg(); else if (real) real->neg(); else throw KTypeException("TypeError: bad operand type for unary -"); return obj; } KObject* KObject::_and(KObject* obj1, KObject* obj2) { return new KObject(obj1->toBool() && obj2->toBool()); } KObject* KObject::_or(KObject*obj1, KObject* obj2) { return new KObject(obj1->toBool() || obj2->toBool()); }
//=========================================================================== /* This file is part of the CHAI 3D visualization and haptics libraries. Copyright (C) 2003-2004 by CHAI 3D. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License("GPL") version 2 as published by the Free Software Foundation. For using the CHAI 3D libraries with software that can not be combined with the GNU GPL, and for taking advantage of the additional benefits of our support services, please contact CHAI 3D about acquiring a Professional Edition License. \author: <http://www.chai3d.org> \author: Francois Conti \author: Dan Morris \version 1.1 \date 01/2004 */ //=========================================================================== //--------------------------------------------------------------------------- #include "CColor.h" //--------------------------------------------------------------------------- cColorf CHAI_COLOR_RED(1.0f,0.0f,0.0f,1.0f); cColorf CHAI_COLOR_GREEN(0.0f,1.0f,0.0f,1.0f); cColorf CHAI_COLOR_BLUE(0.0f,0.0f,1.0f,1.0f); cColorf CHAI_COLOR_WHITE(1.0f,1.0f,1.0f,1.0f); cColorf CHAI_COLOR_BLACK(0.0f,0.0f,0.0f,1.0f); cColorf CHAI_COLOR_YELLOW(1.0f,1.0f,0.0f,1.0f); cColorf CHAI_COLOR_AQUA(0.0f,1.0f,1.0f,1.0f); cColorf CHAI_COLOR_PURPLE(1.0f,0.0f,1.0f,1.0f); cColorf CHAI_BASIC_COLORS[N_CHAI_BASIC_COLORS] = { CHAI_COLOR_RED, CHAI_COLOR_GREEN, CHAI_COLOR_BLUE, CHAI_COLOR_WHITE, CHAI_COLOR_BLACK, CHAI_COLOR_YELLOW, CHAI_COLOR_AQUA, CHAI_COLOR_PURPLE }; cColorf CHAI_COLOR_PASTEL_RED(1.0f,0.5f,0.5f,1.0f); cColorf CHAI_COLOR_PASTEL_GREEN(0.5f,1.0f,0.5f,1.0f); cColorf CHAI_COLOR_PASTEL_BLUE(0.5f,0.5f,1.0f,1.0f); cColorf CHAI_COLOR_PASTEL_AQUA(0.0f,1.0f,1.0f,1.0f); cColorf CHAI_COLOR_PASTEL_VIOLET(1.0f,0.5f,1.0f,1.0f); cColorf CHAI_COLOR_PASTEL_YELLOW(0.5F,1.0f,1.0f,1.0f); cColorf CHAI_COLOR_PASTEL_GRAY(0.5f,0.5f,0.5f,1.0f); cColorf CHAI_PASTEL_COLORS[N_CHAI_PASTEL_COLORS] = { CHAI_COLOR_PASTEL_RED, CHAI_COLOR_PASTEL_GREEN, CHAI_COLOR_PASTEL_BLUE, CHAI_COLOR_PASTEL_AQUA, CHAI_COLOR_PASTEL_VIOLET, CHAI_COLOR_PASTEL_YELLOW, CHAI_COLOR_PASTEL_GRAY };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2011 Opera Software ASA. 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 "modules/hardcore/component/Messages.h" #include "platforms/windows/IPC/SharedPluginBitmap.h" #include "platforms/windows/IPC/SharedMemory.h" /*static*/ OpAutoPtr<WindowsSharedBitmapManager> WindowsSharedBitmapManager::s_shared_bitmap_manager; /*static*/ WindowsSharedBitmapManager* WindowsSharedBitmapManager::GetInstance() { if (WindowsSharedMemoryManager::GetCM0PID() == 0) return NULL; if (!s_shared_bitmap_manager.get()) s_shared_bitmap_manager = OP_NEW(WindowsSharedBitmapManager, ()); return s_shared_bitmap_manager.get(); } WindowsSharedBitmap* WindowsSharedBitmapManager::CreateMemory(OpPluginImageID identifier, int width, int height) { OP_ASSERT(!m_shared_bitmaps.Contains(identifier)); OpAutoPtr<WindowsSharedBitmap> wsb = OP_NEW(WindowsSharedBitmap, ()); RETURN_VALUE_IF_NULL(wsb.get(), NULL); if (OpStatus::IsError(wsb->Init(identifier, true)) || OpStatus::IsError(wsb->ConstructMemory(width, height)) || OpStatus::IsError(m_shared_bitmaps.Add(identifier, wsb.get()))) return NULL; return wsb.release(); } WindowsSharedBitmap* WindowsSharedBitmapManager::OpenMemory(OpPluginImageID identifier) { if (m_shared_bitmaps.Contains(identifier)) { WindowsSharedBitmap* bitmap = NULL; m_shared_bitmaps.GetData(identifier, &bitmap); return bitmap; } OpAutoPtr<WindowsSharedBitmap> wsb = OP_NEW(WindowsSharedBitmap, ()); RETURN_VALUE_IF_NULL(wsb.get(), NULL); if (OpStatus::IsError(wsb->Init(identifier, false)) || OpStatus::IsError(wsb->OpenMemory()) || OpStatus::IsError(m_shared_bitmaps.Add(identifier, wsb.get()))) return NULL; return wsb.release(); } void WindowsSharedBitmapManager::CloseMemory(OpPluginImageID identifier) { if (!m_shared_bitmaps.Contains(identifier)) return; WindowsSharedBitmap* sm; if (OpStatus::IsSuccess(m_shared_bitmaps.Remove(identifier, &sm))) OP_DELETE(sm); } WindowsSharedBitmap::WindowsSharedBitmap() : m_close_wait_handle(NULL), m_close_callback_handle(NULL), m_opened_remotely_handle(NULL), m_mapped_memory(NULL), m_mapping_handle(NULL), m_shared_mem(NULL), m_opened(false) { } WindowsSharedBitmap::~WindowsSharedBitmap() { if (m_close_callback_handle) UnregisterWait(m_close_callback_handle); if (m_opened) m_shared_mem->opened = 0; if (m_mapped_memory) UnmapViewOfFile(m_mapped_memory); if (m_mapping_handle) CloseHandle(m_mapping_handle); if (m_close_wait_handle) { ResetEvent(m_close_wait_handle); CloseHandle(m_close_wait_handle); } if (m_opened_remotely_handle) { SetEvent(m_opened_remotely_handle); CloseHandle(m_opened_remotely_handle); } } OP_STATUS WindowsSharedBitmap::Init(OpPluginImageID identifier, bool owner) { UniString name; RETURN_IF_ERROR(name.AppendFormat(UNI_L("OperaPluginBitmap_%d_%llu"), WindowsSharedMemoryManager::GetCM0PID(), identifier)); m_memory_name = OP_NEWA(uni_char, name.Length() + 1); RETURN_OOM_IF_NULL(m_memory_name.get()); name.CopyInto(m_memory_name.get(), name.Length()); m_memory_name.get()[name.Length()] = 0; m_identifier = identifier; m_owner = owner; return OpStatus::OK; } OP_STATUS WindowsSharedBitmap::ConstructMemory(int width, int height) { // Size consists of the header + memory for the bitmap. */ DWORD size = sizeof(SharedBitmap) + width * height * sizeof(UINT32); RETURN_OOM_IF_NULL(m_mapping_handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, m_memory_name.get())); RETURN_OOM_IF_NULL(m_mapped_memory = MapViewOfFile(m_mapping_handle, FILE_MAP_ALL_ACCESS, 0, 0, 0)); m_shared_mem = static_cast<SharedBitmap*>(m_mapped_memory); m_shared_mem->width = width; m_shared_mem->height = height; m_shared_mem->owner_pid = GetCurrentProcessId(); RETURN_OOM_IF_NULL(m_shared_mem->close_wait_event = m_close_wait_handle = CreateEvent(NULL, FALSE, FALSE, NULL)); /* Create event used to block owner when waiting for remote user. Create in signaled state - won't block owner unless someone opened this memory and changed state. */ RETURN_OOM_IF_NULL(m_shared_mem->opened_remotely_event = m_opened_remotely_handle = CreateEvent(NULL, FALSE, TRUE, NULL)); return OpStatus::OK; } OP_STATUS WindowsSharedBitmap::OpenMemory() { OP_ASSERT(!m_opened && "Don't call OpenMemory on already open memory!"); RETURN_OOM_IF_NULL(m_mapping_handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, m_memory_name.get())); RETURN_OOM_IF_NULL(m_mapped_memory = MapViewOfFile(m_mapping_handle, FILE_MAP_ALL_ACCESS, 0, 0, 0)); m_shared_mem = static_cast<SharedBitmap*>(m_mapped_memory); // Duplicate event handles that owner has created. OpAutoHANDLE owner_process(OpenProcess(PROCESS_DUP_HANDLE, FALSE, m_shared_mem->owner_pid)); RETURN_OOM_IF_NULL(owner_process.get()); if (!DuplicateHandle(owner_process, m_shared_mem->close_wait_event, GetCurrentProcess(), &m_close_wait_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) return OpStatus::ERR; if (!DuplicateHandle(owner_process, m_shared_mem->opened_remotely_event, GetCurrentProcess(), &m_opened_remotely_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) return OpStatus::ERR; // Set to nonsignaled state to let owner know that it should wait when closing memory. ResetEvent(m_opened_remotely_handle); if (!RegisterWaitForSingleObject(&m_close_callback_handle, m_close_wait_handle, WindowsSharedBitmap::CloseCallback, reinterpret_cast<void*>(m_identifier), INFINITE, WT_EXECUTEDEFAULT)) return OpStatus::ERR; if (InterlockedCompareExchange(&m_shared_mem->opened, TRUE, FALSE)) { //Reaching this means that multiple concurrent accesses to the shared memory for reading are attempted. //If this is needed, then some assumptions don't hold anymore and the implementation needs //to be changed. F.ex: m_close_wait_handle needs to be implemented using a semaphore instead. OP_ASSERT(false); return OpStatus::ERR; } m_opened = true; return OpStatus::OK; } OP_STATUS WindowsSharedBitmap::ResizeMemory(int width, int height) { OP_ASSERT(m_owner && "Only owner should resize shared memory!"); // Signal an event and wait for remote users to close this memory. SignalObjectAndWait(m_close_wait_handle, m_opened_remotely_handle, INFINITE, FALSE); // Reset event to non-signaled state. ResetEvent(m_opened_remotely_handle); if (m_mapped_memory) { UnmapViewOfFile(m_mapped_memory); m_mapped_memory = NULL; m_shared_mem = NULL; } if (m_mapping_handle) { CloseHandle(m_mapping_handle); m_mapping_handle = NULL; } // Size consists of the header + memory for the bitmap. */ DWORD size = sizeof(SharedBitmap) + width * height * sizeof(UINT32); RETURN_OOM_IF_NULL(m_mapping_handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, m_memory_name.get())); RETURN_OOM_IF_NULL(m_mapped_memory = MapViewOfFile(m_mapping_handle, FILE_MAP_ALL_ACCESS, 0, 0, 0)); m_shared_mem = static_cast<SharedBitmap*>(m_mapped_memory); m_shared_mem->width = width; m_shared_mem->height = height; m_shared_mem->owner_pid = GetCurrentProcessId(); m_shared_mem->close_wait_event = m_close_wait_handle; m_shared_mem->opened_remotely_event = m_opened_remotely_handle; return OpStatus::OK; } /* static */ VOID WindowsSharedBitmap::CloseCallback(PVOID identifier, BOOLEAN timeout) { if (WindowsSharedBitmapManager* bitmap_manager = WindowsSharedBitmapManager::GetInstance()) bitmap_manager->CloseMemory(reinterpret_cast<OpPluginImageID>(identifier)); }
#ifndef RUNE_H #define RUNE_H class Rune { int index; int value; SDL_Rect movingPosition; float targetPosX; float targetPosY; int steps; }; #endif
/* * 题目:全排列 * 链接:https://leetcode-cn.com/problems/permutations/ */ class Solution { public: void dfs(vector<vector<int>> &ans, vector<int> &nums, vector<int> &temp, int n) { if (nums.size() == n) { ans.push_back(temp); return; } for (int i = 0; i < nums.size(); i++) { if (!vis.count(i)) { vis.insert(i); temp.push_back(nums[i]); dfs(ans, nums, temp, n + 1); // 递归 vis.erase(i); temp.pop_back(); } } } vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> ans; vector<int> temp; dfs(ans, nums, temp, 0); return ans; } private: unordered_set<int> vis; };
class Path{ public: int start_x; int start_y; int dist; string s; Path(int a, int b, int c, string str): start_x(a), start_y(b), dist(c), s(str){} bool operator < (const Path& p) const{ if(dist == p.dist){ return s > p.s; } return dist > p.dist; } }; class Solution { private: vector<int> delta = {0,1,0,-1,0}; string movement = "rdlu"; public: string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) { vector<vector<bool>> visited(maze.size(), vector<bool>(maze[0].size(),false)); priority_queue<Path> q; q.push(Path(ball[0], ball[1], 0, "")); while(!q.empty()){ int x = q.top().start_x; int y = q.top().start_y; int dist = q.top().dist; string path = q.top().s; q.pop(); if(x == hole[0] && y == hole[1]){return path;} if(visited[x][y]) continue; visited[x][y] = true; for(int i = 0; i < 4; ++i){ int newx = x, newy = y, newdist = dist; while(newx >= 0 && newx < maze.size() && newy >= 0 && newy < maze[0].size() && !maze[newx][newy] && (newx != hole[0] || newy != hole[1])){ newx += delta[i]; newy += delta[i+1]; ++newdist; } if(newx != hole[0] || newy != hole[1]){ newx -= delta[i]; newy -= delta[i+1]; --newdist; } if(visited[newx][newy]) continue; q.push(Path(newx, newy, newdist, path + movement[i])); } } return "impossible"; } };
/* * Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com> * Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com> * Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com> * Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com> * Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net> * Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com> * Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "alg/ContextALG.hh" #include "alg/dummyStrategyOptim/DummyStrategyOptim.hh" #include "alg/StrategySelecter.hh" #include "dtoin/InstanceReaderDtoin.hh" #include "dtoin/SolutionDtoin.hh" #include "dtoout/InstanceWriterDtoout.hh" #include "dtoout/SolutionDtoout.hh" #include "tools/ParseCmdLine.hh" #include "tools/Log.hh" #include <boost/thread.hpp> #include <ctime> #include <string> #include <sstream> #include <iostream> using namespace std; using namespace boost; struct Run { void operator()(const variables_map& opt_p){ LOG(INFO) << "temps limite : " << opt_p["time"].as<int>() << " s" << endl << "instance file : ./" << opt_p["param"].as<string>() << endl << "original sol : ./" << opt_p["init"].as<string>() << endl << "new sol : ./" << opt_p["out"].as<string>() << endl << "seed : " << opt_p["seed"].as<int>() << endl; try { /* Lecture du fichier d'instance et de solution initiale */ LOG(INFO) << "reading instance" << endl; InstanceReaderDtoin reader_l; ContextBO contextBO_l = reader_l.read(opt_p["param"].as<string>()); SolutionDtoin::read(opt_p["init"].as<string>(), &contextBO_l); /* Lancement de la sequence d'optim. */ LOG(INFO) << "creating context" << endl; ContextALG contextALG_l(&contextBO_l); //Initialise SolutionDtoout::bestSol_m contextALG_l.checkCompletAndMajBestSol(contextALG_l.getCurrentSol(), false); StrategyOptim* pStrategy_l = StrategySelecter::buildStrategy(opt_p); LOG(INFO) << "running method" << endl; pStrategy_l->run(contextALG_l, time(0) + opt_p["time"].as<int>(), opt_p); /* Risque de fuite de memoire : si une exception est levee pendant l'optim, * on ne deletera jamais cette strategie. * (bon, ok, reflexion de puriste n'ayant que peu de consequences pratiques vu le contexte...) */ delete pStrategy_l; } catch (string s_l){ LOG(ERREUR) << "Levee de l'exception : " << s_l << endl; } } }; int main(int argc, char **argv) { variables_map opt_l = ParseCmdLine::parse(argc, argv); ParseCmdLine::traitementOptionsSimples(opt_l); Run run_l; thread thread_l(run_l, opt_l); if ( thread_l.timed_join(posix_time::seconds(opt_l["time"].as<int>())) ){ LOG(INFO) << "Run killed because time limit has been reached" << endl; } return 0; }
#include"Display.h" #include "iostream" void Display::Create(ContextAttr attr) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, attr.major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, attr.minor); if (attr.bProfileCore) { glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); } mWindow = glfwCreateWindow(mDisplayMode.width, mDisplayMode.height, title, nullptr, nullptr); if (!mWindow) { std::cout << "create window failed." << std::endl; return; } glfwMakeContextCurrent(mWindow); //load all OpenGL funtion potints glfwSetFramebufferSizeCallback(mWindow, &Display::frameBuffSizeCallback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return; } } EMDisplayState Display::Update() { //检查并调用时间,交换缓冲 glfwPollEvents(); glfwSwapBuffers(mWindow); return processEvent(); } void Display::destroy() { glfwDestroyWindow(mWindow); glfwTerminate(); mWindow = nullptr; } void Display::SetTitle(const char* _title) { title = _title; } void Display::SetDisplayMode(DisplayMode mode) { mDisplayMode = mode; } void Display::frameBuffSizeCallback(GLFWwindow* _window, int _w, int _h) { glViewport(0,0,_w,_h); } EMDisplayState Display::processEvent() { if (glfwGetKey(mWindow,GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(mWindow,true); return EMDisplayState::State_Success; } else if (glfwGetKey(mWindow, GLFW_KEY_R) == GLFW_PRESS) { return EMDisplayState::State_Reload; } return EMDisplayState::State_Max; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 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" #ifdef ACCESSIBILITY_EXTENSION_SUPPORT #include "WindowsOpAccessibilityAdapter.h" #include "modules/unicode/unicode_segmenter.h" #include "platforms/windows/pi/WindowsOpWindow.h" #include "platforms/windows/IDL/Accessible2_i.c" #include "platforms/windows/IDL/AccessibleText_i.c" #include "platforms/windows/IDL/AccessibleRole.h" //Table indicating the MSAA equivalent role of each of our accessibility roles DWORD WindowsOpAccessibilityAdapter::IAccRole[] = { ROLE_SYSTEM_APPLICATION, //kElementKindApplication ROLE_SYSTEM_CLIENT, //kElementKindWindow ROLE_SYSTEM_ALERT, //kElementKindAlert ROLE_SYSTEM_DIALOG, //kElementKindAlertDialog ROLE_SYSTEM_DIALOG, //kElementKindDialog ROLE_SYSTEM_GROUPING, //kElementKindView ROLE_SYSTEM_DOCUMENT, //kElementKindWebView ROLE_SYSTEM_TOOLBAR, //kElementKindToolbar ROLE_SYSTEM_PUSHBUTTON, //kElementKindButton ROLE_SYSTEM_CHECKBUTTON, //kElementKindCheckbox ROLE_SYSTEM_COMBOBOX, //kElementKindDropdown ROLE_SYSTEM_GROUPING, //kElementKindRadioTabGroup ROLE_SYSTEM_RADIOBUTTON, //kElementKindRadioButton ROLE_SYSTEM_PAGETAB, //kElementKindTab ROLE_SYSTEM_STATICTEXT, //kElementKindStaticText ROLE_SYSTEM_TEXT, //kElementKindSinglelineTextedit ROLE_SYSTEM_TEXT, //kElementKindMultilineTextedit ROLE_SYSTEM_SCROLLBAR, //kElementKindHorizontalScrollbar ROLE_SYSTEM_SCROLLBAR, //kElementKindVerticalScrollbar ROLE_SYSTEM_CLIENT, //kElementKindScrollview ROLE_SYSTEM_SLIDER, //kElementKindSlider ROLE_SYSTEM_PROGRESSBAR, //kElementKindProgress ROLE_SYSTEM_STATICTEXT, //kElementKindLabel ROLE_SYSTEM_STATICTEXT, //kElementKindDescriptor ROLE_SYSTEM_LINK, //kElementKindLink ROLE_SYSTEM_GRAPHIC, //kElementKindImage ROLE_SYSTEM_MENUBAR, //kElementKindMenuBar ROLE_SYSTEM_MENUPOPUP, //kElementKindMenu ROLE_SYSTEM_MENUITEM, //kElementKindMenuItem ROLE_SYSTEM_LIST, //kElementKindList ROLE_SYSTEM_TABLE, //kElementKindGrid ROLE_SYSTEM_OUTLINE, //kElementKindOutlineList ROLE_SYSTEM_TABLE, //kElementKindTable ROLE_SYSTEM_LIST, //kElementKindHeaderList ROLE_SYSTEM_LISTITEM, //kElementKindListRow ROLE_SYSTEM_COLUMNHEADER, //kElementKindListHeader ROLE_SYSTEM_COLUMN, //kElementKindListColumn ROLE_SYSTEM_CELL, //kElementKindListCell ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartArrowUp ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartArrowDown ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartPageUp ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartPageDown ROLE_SYSTEM_INDICATOR, //kElementKindScrollbarPartKnob ROLE_SYSTEM_BUTTONDROPDOWN, //kElementKindDropdownButtonPart ROLE_SYSTEM_LIST, //kElementKindDirectory ROLE_SYSTEM_DOCUMENT, //kElementKindDocument ROLE_SYSTEM_DOCUMENT, //kElementKindLog ROLE_SYSTEM_PANE, //kElementKindPanel ROLE_SYSTEM_CLIENT, //kElementKindWorkspace ROLE_SYSTEM_SEPARATOR, //kElementKindSplitter ROLE_SYSTEM_GROUPING, //kElementKindSection ROLE_SYSTEM_GROUPING, //kElementKindParagraph ROLE_SYSTEM_GROUPING, //kElementKindForm 0, //kElementKindUnknown }; //Table indicating the IAccessible2 equivalent role of each of our accessibility roles DWORD WindowsOpAccessibilityAdapter::IAcc2Role[] = { ROLE_SYSTEM_APPLICATION, //kElementKindApplication ROLE_SYSTEM_CLIENT, //kElementKindWindow ROLE_SYSTEM_ALERT, //kElementKindAlert ROLE_SYSTEM_ALERT, //kElementKindAlertDialog ROLE_SYSTEM_DIALOG, //kElementKindDialog ROLE_SYSTEM_GROUPING, //kElementKindView ROLE_SYSTEM_DOCUMENT, //kElementKindWebView ROLE_SYSTEM_TOOLBAR, //kElementKindToolbar ROLE_SYSTEM_PUSHBUTTON, //kElementKindButton ROLE_SYSTEM_CHECKBUTTON, //kElementKindCheckbox ROLE_SYSTEM_COMBOBOX, //kElementKindDropdown ROLE_SYSTEM_GROUPING, //kElementKindRadioTabGroup ROLE_SYSTEM_RADIOBUTTON, //kElementKindRadioButton ROLE_SYSTEM_PAGETAB, //kElementKindTab ROLE_SYSTEM_STATICTEXT, //kElementKindStaticText ROLE_SYSTEM_TEXT, //kElementKindSinglelineTextedit ROLE_SYSTEM_TEXT, //kElementKindMultilineTextedit ROLE_SYSTEM_SCROLLBAR, //kElementKindHorizontalScrollbar ROLE_SYSTEM_SCROLLBAR, //kElementKindVerticalScrollbar ROLE_SYSTEM_CLIENT, //kElementKindScrollview ROLE_SYSTEM_SLIDER, //kElementKindSlider ROLE_SYSTEM_PROGRESSBAR, //kElementKindProgress IA2_ROLE_LABEL, //kElementKindLabel ROLE_SYSTEM_STATICTEXT, //kElementKindDescriptor ROLE_SYSTEM_LINK, //kElementKindLink ROLE_SYSTEM_GRAPHIC, //kElementKindImage ROLE_SYSTEM_MENUBAR, //kElementKindMenuBar ROLE_SYSTEM_MENUPOPUP, //kElementKindMenu ROLE_SYSTEM_MENUITEM, //kElementKindMenuItem ROLE_SYSTEM_LIST, //kElementKindList ROLE_SYSTEM_TABLE, //kElementKindGrid ROLE_SYSTEM_OUTLINE, //kElementKindOutlineList ROLE_SYSTEM_TABLE, //kElementKindTable ROLE_SYSTEM_LIST, //kElementKindHeaderList ROLE_SYSTEM_LISTITEM, //kElementKindListRow ROLE_SYSTEM_COLUMNHEADER, //kElementKindListHeader ROLE_SYSTEM_COLUMN, //kElementKindListColumn ROLE_SYSTEM_CELL, //kElementKindListCell ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartArrowUp ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartArrowDown ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartPageUp ROLE_SYSTEM_PUSHBUTTON, //kElementKindScrollbarPartPageDown ROLE_SYSTEM_INDICATOR, //kElementKindScrollbarPartKnob ROLE_SYSTEM_BUTTONDROPDOWN, //kElementKindDropdownButtonPart ROLE_SYSTEM_LIST, //kElementKindDirectory ROLE_SYSTEM_DOCUMENT, //kElementKindDocument ROLE_SYSTEM_DOCUMENT, //kElementKindLog ROLE_SYSTEM_PANE, //kElementKindPanel IA2_ROLE_DESKTOP_PANE, //kElementKindWorkspace ROLE_SYSTEM_SEPARATOR, //kElementKindSplitter IA2_ROLE_SECTION, //kElementKindSection IA2_ROLE_PARAGRAPH, //kElementKindParagraph IA2_ROLE_FORM, //kElementKindForm IA2_ROLE_UNKNOWN, //kElementKindUnknown }; //Table indicating which MSAA state should be always set for each of our accessibility roles DWORD WindowsOpAccessibilityAdapter::IAccStateMask[] = { 0, //kElementKindApplication STATE_SYSTEM_FOCUSABLE, //kElementKindWindow 0, //kElementKindAlert 0, //kElementKindAlertDialog 0, //kElementKindDialog 0, //kElementKindView 0, //kElementKindWebView 0, //kElementKindToolbar STATE_SYSTEM_FOCUSABLE | STATE_SYSTEM_HOTTRACKED, //kElementKindButton STATE_SYSTEM_SELECTABLE | STATE_SYSTEM_HOTTRACKED, //kElementKindCheckbox STATE_SYSTEM_HOTTRACKED, //kElementKindDropdown 0, //kElementKindRadioTabGroup STATE_SYSTEM_FOCUSABLE, //kElementKindRadioButton STATE_SYSTEM_SELECTABLE | STATE_SYSTEM_HOTTRACKED, //kElementKindTab 0, //kElementKindStaticText STATE_SYSTEM_FOCUSABLE | STATE_SYSTEM_HOTTRACKED, //kElementKindSinglelineTextedit 0, //kElementKindMultilineTextedit 0, //kElementKindHorizontalScrollbar 0, //kElementKindVerticalScrollbar 0, //kElementKindScrollview STATE_SYSTEM_HOTTRACKED, //kElementKindSlider 0, //kElementKindProgress 0, //kElementKindLabel 0, //kElementKindDescriptor 0, //kElementKindLink 0, //kElementKindImage 0, //kElementKindMenuBar 0, //kElementKindMenu STATE_SYSTEM_FOCUSABLE | STATE_SYSTEM_HOTTRACKED |STATE_SYSTEM_HASPOPUP, //kElementKindMenuItem 0, //kElementKindList 0, //kElementKindGrid 0, //kElementKindOutlineList 0, //kElementKindTable 0, //kElementKindHeaderList STATE_SYSTEM_SELECTABLE, //kElementKindListRow STATE_SYSTEM_READONLY, //kElementKindListHeader STATE_SYSTEM_SELECTABLE, //kElementKindListColumn STATE_SYSTEM_SELECTABLE, //kElementKindListCell 0, //kElementKindScrollbarPartArrowUp 0, //kElementKindScrollbarPartArrowDown 0, //kElementKindScrollbarPartPageUp 0, //kElementKindScrollbarPartPageDown 0, //kElementKindScrollbarPartKnob STATE_SYSTEM_HOTTRACKED, //kElementKindDropdownButtonPart 0, //kElementKindDirectory 0, //kElementKindDocument 0, //kElementKindLog 0, //kElementKindPanel 0, //kElementKindWorkspace 0, //kElementKindSplitter 0, //kElementKindSection 0, //kElementKindParagraph 0 //kElementKindUnknown }; #if defined _DEBUG && defined ACC_DEBUG_OUTPUT int WindowsOpAccessibilityExtension::s_last_id = 0; #endif OP_STATUS OpAccessibilityAdapter::Create(OpAccessibilityAdapter** adapter, OpAccessibleItem* accessible_item) { *adapter = (OpAccessibilityAdapter*)(new WindowsOpAccessibilityAdapter(accessible_item)); if(*adapter == NULL) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } WindowsOpWindow* WindowsOpAccessibilityAdapter::GetWindowForAccessibleItem(OpAccessibleItem* item) { WindowsOpWindow* window = NULL; while ((!item->AccessibilityIsReady() || (window = (WindowsOpWindow*)(item->AccessibilityGetWindow())) == NULL) && (item = item->GetAccessibleParent()) != NULL); return window; } // maps OpAccessibleItem instances to a unique id //OpPointerHashTable<OpAccessibleItem, LONG> g_accessibleitem_id_hashtable; LONG GetAccessibleItemID(OpAccessibleItem* item) { return (LONG)((LONG_PTR)item) >> 2; /* LONG* id = 0; if(OpStatus::IsSuccess(g_accessibleitem_id_hashtable.GetData(item, &id))) { return (LONG)(LONG_PTR)id; } id = (LONG *)++g_unique_id_counter; g_accessibleitem_id_hashtable.Add(item, id); return (LONG)(LONG_PTR)id; */ } void FreeAccessibleItemID(OpAccessibleItem* item) { /* LONG* id; if(g_accessibleitem_id_hashtable.Contains(item)) g_accessibleitem_id_hashtable.Remove(item, &id); */ } OP_STATUS OpAccessibilityAdapter::SendEvent(OpAccessibleItem* sender, Accessibility::Event evt) { if (!g_op_system_info->IsScreenReaderRunning() && evt.is_state_event) return OpStatus::OK; WindowsOpWindow* window = WindowsOpAccessibilityAdapter::GetWindowForAccessibleItem(sender); if (window == NULL) return OpStatus::ERR; if (evt.is_state_event) { LONG id = GetAccessibleItemID(sender); Accessibility::State state = sender->AccessibilityGetState(); if (evt.event_info.state_event & Accessibility::kAccessibilityStateInvisible && !(state & Accessibility::kAccessibilityStateInvisible)) NotifyWinEvent(EVENT_OBJECT_SHOW, window->m_hwnd, id, CHILDID_SELF); if (evt.event_info.state_event & Accessibility::kAccessibilityStateInvisible && state & Accessibility::kAccessibilityStateInvisible) NotifyWinEvent(EVENT_OBJECT_HIDE, window->m_hwnd, id, CHILDID_SELF); if (evt.event_info.state_event & Accessibility::kAccessibilityStateFocused && state & Accessibility::kAccessibilityStateFocused) NotifyWinEvent(EVENT_OBJECT_FOCUS, window->m_hwnd, id, CHILDID_SELF); NotifyWinEvent(EVENT_OBJECT_STATECHANGE, window->m_hwnd, id, CHILDID_SELF); return OpStatus::OK; } switch (evt.event_info.event_type) { case Accessibility::kAccessibilityEventMoved: case Accessibility::kAccessibilityEventResized: NotifyWinEvent(EVENT_OBJECT_LOCATIONCHANGE, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventTextChanged: { Accessibility::ElementKind role = sender->AccessibilityGetRole(); if (role == Accessibility::kElementKindSinglelineTextedit || role == Accessibility::kElementKindMultilineTextedit || role == Accessibility::kElementKindDropdown) NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); else NotifyWinEvent(EVENT_OBJECT_NAMECHANGE, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; } case Accessibility::kAccessibilityEventTextChangedBykeyboard: NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventDescriptionChanged: NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventURLChanged: break; case Accessibility::kAccessibilityEventSelectedTextRangeChanged: case Accessibility::kAccessibilityEventSelectionChanged: NotifyWinEvent(EVENT_OBJECT_SELECTIONWITHIN, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventSetLive: break; case Accessibility::kAccessibilityEventStartDragAndDrop: NotifyWinEvent(EVENT_SYSTEM_DRAGDROPSTART, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventEndDragAndDrop: NotifyWinEvent(EVENT_SYSTEM_DRAGDROPEND, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventStartScrolling: NotifyWinEvent(EVENT_SYSTEM_SCROLLINGSTART, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventEndScrolling: NotifyWinEvent(EVENT_SYSTEM_SCROLLINGEND, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; case Accessibility::kAccessibilityEventReorder: NotifyWinEvent(EVENT_OBJECT_REORDER, window->m_hwnd, GetAccessibleItemID(sender), CHILDID_SELF); break; } #if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_info; GetDebugInfo(dbg_info); OutputDebugString(dbg_info); dbg_info.Empty(); dbg_info.AppendFormat(UNI_L(": sent event %d\n"),event_constant); OutputDebugString(dbg_info); #endif return OpStatus::OK; } #if defined _DEBUG && defined ACC_DEBUG_OUTPUT void WindowsOpAccessibilityExtension::GetDebugInfo(OpString &info) { if (!m_listener) return; OpString name; m_listener->AccessibilityGetText(name); if (name.Length() > 15) *(name.CStr() + 16) = 0; OpAccessibilityExtension::AccessibilityState state = m_listener->AccessibilityGetState(); OpString status; status.Set(UNI_L("")); if (state & OpAccessibilityExtension::kAccessibilityStateInvisible) status.Append(UNI_L("H")); if (state & OpAccessibilityExtension::kAccessibilityStateDisabled) status.Append(UNI_L("D")); if (state & OpAccessibilityExtension::kAccessibilityStateCheckedOrSelected) status.Append(UNI_L("S")); if (state & OpAccessibilityExtension::kAccessibilityStateReadOnly) status.Append(UNI_L("R")); info.Empty(); if (m_IAccessible) info.AppendFormat(UNI_L("(Acc #%d {%d} %s - \"%s\")"), m_IAccessible->m_id, m_listener->AccessibilityGetRole(), status.CStr(), name.CStr()); else info.AppendFormat(UNI_L("(Acc #N/A {%d} %s - \"%s\")"), m_listener->AccessibilityGetRole(), status.CStr(), name.CStr()); } #endif HRESULT WindowsOpAccessibilityAdapter::QueryService(REFGUID guidService, REFIID riid, void **ppv) { if (guidService != IID_IAccessible && guidService != IID_IAccessible2 && guidService != IID_IAccessibleText) return E_INVALIDARG; return QueryInterface(riid, ppv); } HRESULT WindowsOpAccessibilityAdapter::QueryInterface(REFIID iid, void ** pvvObject) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; if (iid == IID_IUnknown || iid == IID_IDispatch || iid == IID_IAccessible || iid == IID_IAccessible2) { *pvvObject=(IAccessible2*)this; AddRef(); return S_OK; } else if (iid == IID_IAccessibleText) { OpString text; if (OpStatus::IsSuccess(m_accessible_item->AccessibilityGetText(text)) && (text.HasContent() || m_accessible_item->AccessibilityGetRole() == Accessibility::kElementKindSinglelineTextedit || m_accessible_item->AccessibilityGetRole() == Accessibility::kElementKindMultilineTextedit ) ) { *pvvObject=(IAccessibleText*)this; AddRef(); return S_OK; } } else if (iid == IID_IServiceProvider) { *pvvObject=(IServiceProvider*)this; AddRef(); return S_OK; } *pvvObject=NULL; return E_NOINTERFACE; } ULONG WindowsOpAccessibilityAdapter::AddRef() { /*#if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_msg; if (!m_accessibility_extension) dbg_msg.AppendFormat(UNI_L("(Acc #%d )"), m_id); else m_accessibility_extension->GetDebugInfo(dbg_msg); dbg_msg.AppendFormat(UNI_L(": AddRef - %d -> %d\n"), m_ref_counter, m_ref_counter+1); OutputDebugString(dbg_msg.CStr()); #endif*/ return ++m_ref_counter; } ULONG WindowsOpAccessibilityAdapter::Release() { /*#if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_msg; if (!m_accessibility_extension) dbg_msg.AppendFormat(UNI_L("(Acc #%d )"), m_id); else m_accessibility_extension->GetDebugInfo(dbg_msg); dbg_msg.AppendFormat(UNI_L(": Release - %d -> %d\n"), m_ref_counter, m_ref_counter-1); OutputDebugString(dbg_msg.CStr()); #endif*/ if (!(--m_ref_counter)) { OP_ASSERT(!m_accessible_item); if (!m_accessible_item) delete this; return 0; } return m_ref_counter; } HRESULT WindowsOpAccessibilityAdapter::GetTypeInfoCount(unsigned int FAR* pctinfo) { *pctinfo=0; return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::GetTypeInfo(unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo) { *ppTInfo=0; return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::GetIDsOfNames(REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_accName(VARIANT varID, BSTR* pszName) { #if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_msg; if (!m_accessibility_extension) dbg_msg.AppendFormat(UNI_L("(Acc #%d )"), m_id); else m_accessibility_extension->GetDebugInfo(dbg_msg); dbg_msg.AppendFormat(UNI_L(": get_accName - "), m_ref_counter, m_ref_counter-1); #endif if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpAccessibleItem* acc_dest; if (varID.lVal==CHILDID_SELF) acc_dest=m_accessible_item; else { acc_dest = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_dest) return E_INVALIDARG; if (!acc_dest->AccessibilityIsReady()) return E_FAIL; } OpAccessibleItem* acc_label= m_accessible_item->GetAccessibleLabelForControl(); OpString string; *pszName = NULL; if (acc_label) { if (!acc_label->AccessibilityIsReady()) return E_FAIL; if (OpStatus::IsError(acc_label->AccessibilityGetText(string))) return S_FALSE; } else { Accessibility::ElementKind role = acc_dest->AccessibilityGetRole(); OpAccessibleItem* acc_parent = ReadyOrNull(acc_dest->GetAccessibleParent()); if (role == Accessibility::kElementKindListRow && acc_parent && acc_parent->AccessibilityGetRole() != Accessibility::kElementKindTable) { acc_dest->AccessibilityGetText(string); int n = acc_dest->GetAccessibleChildrenCount(); for (int i = 0; i < n; i++) { OpAccessibleItem* child = ReadyOrNull(acc_dest->GetAccessibleChild(i)); OpString text; if (child) { child->AccessibilityGetText(text); if (text.HasContent()) { if (string.HasContent()) string.Append(UNI_L(" ")); string.Append(text); } } } } else if (role == Accessibility::kElementKindSinglelineTextedit || role == Accessibility::kElementKindMultilineTextedit || role == Accessibility::kElementKindSection || role == Accessibility::kElementKindParagraph ) { return S_FALSE; } else if (OpStatus::IsError(acc_dest->AccessibilityGetText(string))) return S_FALSE; } *pszName = SysAllocString(string.CStr()); #if defined _DEBUG && defined ACC_DEBUG_OUTPUT dbg_msg.AppendFormat(UNI_L("%s\n"), string.CStr()); OutputDebugString(dbg_msg.CStr()); #endif return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accRole(VARIANT varID, VARIANT* pvarRole) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpAccessibleItem* acc_dest; if (varID.lVal==CHILDID_SELF) acc_dest=m_accessible_item; else { acc_dest = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_dest) return E_INVALIDARG; if (!acc_dest->AccessibilityIsReady()) return E_FAIL; } VariantInit(pvarRole); pvarRole->vt=VT_I4; Accessibility::ElementKind role = acc_dest->AccessibilityGetRole(); OpAccessibleItem* acc_parent = ReadyOrNull(acc_dest->GetAccessibleParent()); OpAccessibleItem* first_child = NULL; if (m_accessible_item->GetAccessibleChildrenCount() >= 1) first_child = ReadyOrNull(m_accessible_item->GetAccessibleChild(0)); //Groups of tabs have a specific role if (role == Accessibility::kElementKindWindow && acc_dest->AccessibilityGetWindow() && ((WindowsOpWindow*)acc_dest->AccessibilityGetWindow())->IsDialog()) pvarRole->lVal = ROLE_SYSTEM_DIALOG; else if (role == Accessibility::kElementKindWindow && acc_dest->AccessibilityGetWindow() && ((WindowsOpWindow*)acc_dest->AccessibilityGetWindow())->m_type == OpTypedObject::WINDOW_TYPE_BROWSER) pvarRole->lVal = ROLE_SYSTEM_APPLICATION; else if (role == Accessibility::kElementKindView && acc_parent && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindTab) pvarRole->lVal = ROLE_SYSTEM_PROPERTYPAGE; else if (role == Accessibility::kElementKindRadioTabGroup && first_child && first_child->AccessibilityGetRole() == Accessibility::kElementKindTab) pvarRole->lVal = ROLE_SYSTEM_PAGETABLIST; else if (role == Accessibility::kElementKindListRow && acc_parent && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindOutlineList) pvarRole->lVal = ROLE_SYSTEM_OUTLINEITEM; else if (role == Accessibility::kElementKindListRow && acc_parent && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindTable) pvarRole->lVal = ROLE_SYSTEM_ROW; else pvarRole->lVal = WindowsOpAccessibilityAdapter::IAccRole[role]; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accState(VARIANT varID, VARIANT* pvarState) { Accessibility::State state; Accessibility::ElementKind role; if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) { pvarState->lVal= STATE_SYSTEM_UNAVAILABLE; return S_OK; } VariantInit(pvarState); pvarState->vt=VT_I4; if (varID.lVal==CHILDID_SELF) { state = m_accessible_item->AccessibilityGetState(); role = m_accessible_item->AccessibilityGetRole(); } else { OpAccessibleItem* acc_child = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_child) return E_INVALIDARG; if (!acc_child->AccessibilityIsReady()) { pvarState->lVal= STATE_SYSTEM_UNAVAILABLE; return S_OK; } state = acc_child->AccessibilityGetState(); role = acc_child->AccessibilityGetRole(); } pvarState->lVal = WindowsOpAccessibilityAdapter::IAccStateMask[role]; if (state & Accessibility::kAccessibilityStateFocused) pvarState->lVal |= STATE_SYSTEM_FOCUSED; if (state & Accessibility::kAccessibilityStateDisabled) pvarState->lVal |= STATE_SYSTEM_UNAVAILABLE; if (state & Accessibility::kAccessibilityStateInvisible) pvarState->lVal |= STATE_SYSTEM_INVISIBLE; if (state & Accessibility::kAccessibilityStateCheckedOrSelected) if (role == Accessibility::kElementKindCheckbox || role == Accessibility::kElementKindRadioButton) pvarState->lVal |= STATE_SYSTEM_CHECKED; else if(role == Accessibility::kElementKindButton) pvarState->lVal |= STATE_SYSTEM_PRESSED; else pvarState->lVal |= STATE_SYSTEM_SELECTED; if (state & Accessibility::kAccessibilityStateGrayed) pvarState->lVal |= STATE_SYSTEM_MIXED; if (state & Accessibility::kAccessibilityStateAnimated) pvarState->lVal |= STATE_SYSTEM_ANIMATED; if (state & Accessibility::kAccessibilityStateExpanded) pvarState->lVal |= STATE_SYSTEM_EXPANDED; else if (state & Accessibility::kAccessibilityStateExpandable) pvarState->lVal |= STATE_SYSTEM_COLLAPSED; if (state & Accessibility::kAccessibilityStatePassword) pvarState->lVal |= STATE_SYSTEM_PROTECTED; if (state & Accessibility::kAccessibilityStateReadOnly) pvarState->lVal |= STATE_SYSTEM_READONLY; if (state & Accessibility::kAccessibilityStateTraversedLink) pvarState->lVal |= STATE_SYSTEM_TRAVERSED; if (state & Accessibility::kAccessibilityStateDefaultButton) pvarState->lVal |= STATE_SYSTEM_DEFAULT; if (state & Accessibility::kAccessibilityStateMultiple) pvarState->lVal |= STATE_SYSTEM_MIXED; if (state & Accessibility::kAccessibilityStateOffScreen) pvarState->lVal |= STATE_SYSTEM_OFFSCREEN; if (state & Accessibility::kAccessibilityStateBusy) pvarState->lVal |= STATE_SYSTEM_BUSY; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::accLocation(long* pxLeft, long* pyTop, long* pcxWidth, long* pcyHeight, VARIANT varID) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpRect position; if (varID.lVal==CHILDID_SELF) { if (OpStatus::IsError(m_accessible_item->AccessibilityGetAbsolutePosition(position))) return DISP_E_MEMBERNOTFOUND; *pxLeft = position.x; *pyTop = position.y; *pcxWidth = position.width; *pcyHeight = position.height; } else { OpAccessibleItem* acc_child = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_child) return E_INVALIDARG; if (!acc_child->AccessibilityIsReady()) return E_FAIL; if (OpStatus::IsError(acc_child->AccessibilityGetAbsolutePosition(position))) return DISP_E_MEMBERNOTFOUND; *pxLeft = position.x; *pyTop = position.y; *pcxWidth = position.width; *pcyHeight = position.height; } return S_OK; } HRESULT WindowsOpAccessibilityAdapter::accHitTest(long xLeft, long yTop, VARIANT* pvarID) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; VariantInit(pvarID); OpAccessibleItem* acc_child = m_accessible_item->GetAccessibleChildOrSelfAt(xLeft, yTop); if (!acc_child) { pvarID->vt=VT_EMPTY; return S_FALSE; } else if (acc_child==m_accessible_item) { pvarID->vt=VT_I4; pvarID->lVal=CHILDID_SELF; AddRef(); } else { pvarID->vt=VT_DISPATCH; pvarID->pdispVal=(WindowsOpAccessibilityAdapter*)(AccessibilityManager::GetInstance()->GetAdapterForAccessibleItem(acc_child)); pvarID->pdispVal->AddRef(); } return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accParent(IDispatch** ppdispParent) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; OpAccessibleItem* acc_parent = m_accessible_item->GetAccessibleParent(); if (acc_parent == NULL && m_accessible_item->AccessibilityGetWindow() != NULL) { HWND hwnd = ((WindowsOpWindow*)(m_accessible_item->AccessibilityGetWindow()))->m_hwnd; IAccessible* native_iaccessible; AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, (void**)(&native_iaccessible)); *ppdispParent= native_iaccessible; (*ppdispParent)->AddRef(); } else if (acc_parent == NULL) { *ppdispParent = NULL; return S_FALSE; } else { *ppdispParent= (WindowsOpAccessibilityAdapter*)(AccessibilityManager::GetInstance()->GetAdapterForAccessibleItem(acc_parent)); (*ppdispParent)->AddRef(); } return S_OK; } HRESULT WindowsOpAccessibilityAdapter::accNavigate(long navDir, VARIANT varStart, VARIANT* pvarEnd) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; VariantInit(pvarEnd); OpAccessibleItem* start; OpAccessibleItem* end= NULL; if (varStart.lVal==CHILDID_SELF) start = m_accessible_item; else start = m_accessible_item->GetAccessibleChild(varStart.lVal-1); if (!start) return E_INVALIDARG; switch (navDir) { case NAVDIR_FIRSTCHILD: end= start->GetAccessibleChild(0); break; case NAVDIR_LASTCHILD: end= start->GetAccessibleChild(start->GetAccessibleChildrenCount()-1); break; case NAVDIR_PREVIOUS: end= start->GetPreviousAccessibleSibling(); break; case NAVDIR_NEXT: end= start->GetNextAccessibleSibling(); break; case NAVDIR_LEFT: end= start->GetLeftAccessibleObject(); break; case NAVDIR_RIGHT: end= start->GetRightAccessibleObject(); break; case NAVDIR_UP: end= start->GetUpAccessibleObject(); break; case NAVDIR_DOWN: end= start->GetDownAccessibleObject(); break; } if (!end) { pvarEnd->vt= VT_EMPTY; return S_FALSE; } else { pvarEnd->vt= VT_DISPATCH; pvarEnd->pdispVal=(WindowsOpAccessibilityAdapter*)AccessibilityManager::GetInstance()->GetAdapterForAccessibleItem(end); pvarEnd->pdispVal->AddRef(); return S_OK; } } HRESULT WindowsOpAccessibilityAdapter::get_accChild(VARIANT varChildID, IDispatch** ppdispChild) { #if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_msg; if (!m_accessibility_extension) dbg_msg.AppendFormat(UNI_L("(Acc #%d )"), m_id); else m_accessibility_extension->GetDebugInfo(dbg_msg); dbg_msg.AppendFormat(UNI_L(": get_accChild - "), m_ref_counter, m_ref_counter-1); #endif if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; *ppdispChild=NULL; if (varChildID.vt != VT_I4) return E_INVALIDARG; if (varChildID.lVal==CHILDID_SELF) { *ppdispChild=this; AddRef(); return S_OK; } if (varChildID.lVal>(m_accessible_item->GetAccessibleChildrenCount()) || varChildID.lVal<1) return E_INVALIDARG; OpAccessibleItem* child = m_accessible_item->GetAccessibleChild(varChildID.lVal-1); *ppdispChild=(WindowsOpAccessibilityAdapter*)AccessibilityManager::GetInstance()->GetAdapterForAccessibleItem(child); (*ppdispChild)->AddRef(); #if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_info; child->GetDebugInfo(dbg_info); dbg_msg.AppendFormat(UNI_L("%s\n"), dbg_info.CStr()); OutputDebugString(dbg_msg.CStr()); #endif return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accChildCount(long* pcountChildren) { #if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_msg; if (!m_accessibility_extension) dbg_msg.AppendFormat(UNI_L("(Acc #%d )"), m_id); else m_accessibility_extension->GetDebugInfo(dbg_msg); dbg_msg.AppendFormat(UNI_L(": get_accChildCount - "), m_ref_counter, m_ref_counter-1); #endif if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; *pcountChildren = m_accessible_item->GetAccessibleChildrenCount(); #if defined _DEBUG && defined ACC_DEBUG_OUTPUT dbg_msg.AppendFormat(UNI_L("%d\n"), *pcountChildren); OutputDebugString(dbg_msg.CStr()); #endif return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accFocus(VARIANT* pvarID) { #if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_msg; if (!m_accessibility_extension) dbg_msg.AppendFormat(UNI_L("(Acc #%d )"), m_id); else m_accessibility_extension->GetDebugInfo(dbg_msg); dbg_msg.AppendFormat(UNI_L(": get_accFocus - "), m_ref_counter, m_ref_counter-1); #endif if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpAccessibleItem* focused= m_accessible_item->GetAccessibleFocusedChildOrSelf(); VariantInit(pvarID); if (!focused) { pvarID->vt= VT_EMPTY; return S_FALSE; } else if (focused == m_accessible_item) { AddRef(); pvarID->vt= VT_I4; pvarID->lVal= CHILDID_SELF; } else { pvarID->vt= VT_DISPATCH; pvarID->pdispVal= (WindowsOpAccessibilityAdapter*)AccessibilityManager::GetInstance()->GetAdapterForAccessibleItem(focused); pvarID->pdispVal->AddRef(); } #if defined _DEBUG && defined ACC_DEBUG_OUTPUT OpString dbg_info; focused->GetDebugInfo(dbg_info); dbg_msg.AppendFormat(UNI_L("%s\n"), dbg_info.CStr()); OutputDebugString(dbg_msg.CStr()); #endif return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accSelection(VARIANT* pvarChildren) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; int children = m_accessible_item->GetAccessibleChildrenCount(); int selected_count = 0; VariantEnum* selected= new VariantEnum(); for (int i=0;i<children; i++) { OpAccessibleItem* child = ReadyOrNull(m_accessible_item->GetAccessibleChild(i)); if (child && child->AccessibilityGetState() & Accessibility::kAccessibilityStateCheckedOrSelected) { VARIANT* v= new VARIANT; VariantInit(v); v->vt=VT_DISPATCH; ((WindowsOpAccessibilityAdapter*)AccessibilityManager::GetInstance()->GetAdapterForAccessibleItem(child))->QueryInterface(IID_IAccessible,(void**)&(v->pdispVal)); v->pdispVal->AddRef(); selected->Add(v); selected_count++; } } VariantInit(pvarChildren); if (!selected_count) { delete selected; pvarChildren->vt= VT_EMPTY; return VT_EMPTY; } pvarChildren->vt=VT_UNKNOWN; pvarChildren->punkVal=selected; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accDescription(VARIANT varID, BSTR* pszDescription) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpAccessibleItem* acc_dest; if (varID.lVal==CHILDID_SELF) acc_dest = m_accessible_item; else { acc_dest = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_dest) return E_INVALIDARG; if (!acc_dest->AccessibilityIsReady()) return E_FAIL; } OpString string; //changes the description of radio buttons to "x of n" (similar to what Firefox seems to be doing /* if (acc_dest->AccessibilityGetRole() == Accessibility::kElementKindRadioButton) { string.Set(""); OpAccessibleItem *acc_dest_parent= acc_dest->GetAccessibleParent(); if (!acc_dest_parent) { *pszDescription = NULL; return S_FALSE; } int n=acc_dest_parent->GetAccessibleChildrenCount(); for (int i=0; i<n ;i++) if (acc_dest_parent->GetAccessibleChild(i) == acc_dest) { string.AppendFormat(UNI_L("%d of %d"), i+1, n); break; } } else*/ if(OpStatus::IsError(acc_dest->AccessibilityGetDescription(string))) { *pszDescription = NULL; return S_FALSE; } *pszDescription = SysAllocString(string.CStr()); return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accValue(VARIANT varID, BSTR* pszValue) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpAccessibleItem* acc_dest; if (varID.lVal==CHILDID_SELF) acc_dest = m_accessible_item; else { acc_dest = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_dest) return E_INVALIDARG; if (!acc_dest->AccessibilityIsReady()) return E_FAIL; } Accessibility::ElementKind role = acc_dest->AccessibilityGetRole(); if (role == Accessibility::kElementKindProgress || role == Accessibility::kElementKindHorizontalScrollbar || role == Accessibility::kElementKindVerticalScrollbar) { int value; if (OpStatus::IsError(acc_dest->AccessibilityGetValue(value))) return S_FALSE; uni_char str[63]; uni_itoa(value, str, 10); *pszValue = SysAllocString(str); return S_OK; } else if (role == Accessibility::kElementKindSinglelineTextedit || role == Accessibility::kElementKindMultilineTextedit || role == Accessibility::kElementKindDropdown) { OpString string; if (OpStatus::IsError(acc_dest->AccessibilityGetText(string))) { *pszValue = NULL; return S_FALSE; } *pszValue = SysAllocString(string.CStr()); return S_OK; } else return S_FALSE; } HRESULT WindowsOpAccessibilityAdapter::get_accHelp(VARIANT varID, BSTR* pszHelp) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_accHelpTopic(BSTR* pszHelpFile, VARIANT varChild, long* pidTopic) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_accKeyboardShortcut(VARIANT varID, BSTR* pszKeyboardShortcut) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpAccessibleItem* acc_dest; if (varID.lVal==CHILDID_SELF) acc_dest = m_accessible_item; else { acc_dest = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_dest) return E_INVALIDARG; if (!acc_dest->AccessibilityIsReady()) return E_FAIL; } uni_char key; ShiftKeyState shifts; if(OpStatus::IsError(acc_dest->AccessibilityGetKeyboardShortcut(&shifts, &key))) { *pszKeyboardShortcut = NULL; return S_FALSE; } OpString shortcut; BOOL append_plus = FALSE; if (shifts & SHIFTKEY_CTRL) { shortcut.Append(UNI_L("Ctrl")); append_plus= TRUE; } if (shifts & SHIFTKEY_ALT) { if (append_plus) shortcut.Append(UNI_L("+")); shortcut.Append(UNI_L("Alt")); append_plus= TRUE; } if (shifts & SHIFTKEY_SHIFT) { if (append_plus) shortcut.Append(UNI_L("+")); shortcut.Append(UNI_L("Shift")); append_plus= TRUE; } if (key) { if (append_plus) shortcut.Append(UNI_L("+")); shortcut.Append(&key,1); } *pszKeyboardShortcut = SysAllocString(shortcut.CStr()); return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_accDefaultAction(VARIANT varID, BSTR* pszDefaultAction) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::accSelect(long flagsSelect, VARIANT varID) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpAccessibleItem* acc_dest; if (varID.lVal==CHILDID_SELF) acc_dest = m_accessible_item; else { acc_dest = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_dest) return E_INVALIDARG; if (!acc_dest->AccessibilityIsReady()) return E_FAIL; } Accessibility::SelectionSet flags = 0; if (flagsSelect & SELFLAG_TAKEFOCUS) acc_dest->AccessibilitySetFocus(); if (flagsSelect & SELFLAG_TAKESELECTION) flags |= Accessibility::kSelectionSetSelect; if (flagsSelect & SELFLAG_EXTENDSELECTION) flags |= Accessibility::kSelectionSetExtend; if (flagsSelect & SELFLAG_ADDSELECTION) flags |= Accessibility::kSelectionSetAdd; if (flagsSelect & SELFLAG_REMOVESELECTION) flags |= Accessibility::kSelectionSetRemove; if (flags) { OpAccessibleItem* acc_parent = ReadyOrNull(acc_dest->GetAccessibleParent()); if (acc_parent && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindListRow) { acc_dest = acc_parent; acc_parent = ReadyOrNull(acc_dest->GetAccessibleParent()); } if (acc_parent && acc_dest->AccessibilityChangeSelection(flags, acc_dest)) return S_OK; else return S_FALSE; } return S_OK; } HRESULT WindowsOpAccessibilityAdapter::accDoDefaultAction(VARIANT varID) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; if (varID.lVal==CHILDID_SELF) m_accessible_item->AccessibilityClicked(); else { OpAccessibleItem* acc_dest = m_accessible_item->GetAccessibleChild(varID.lVal-1); if (!acc_dest) return E_INVALIDARG; if (!acc_dest->AccessibilityIsReady()) return E_FAIL; acc_dest->AccessibilityClicked(); } return S_OK; } HRESULT WindowsOpAccessibilityAdapter::put_accValue(VARIANT varID, BSTR pszValue) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::put_accName(VARIANT varID, BSTR pszName) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_nRelations(long *nRelations) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_relation(long relationIndex, IAccessibleRelation **relation) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_relations(long maxRelations, IAccessibleRelation **relations, long *nRelations) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::role(long *role) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; Accessibility::ElementKind int_role = m_accessible_item->AccessibilityGetRole(); OpAccessibleItem* acc_parent = ReadyOrNull(m_accessible_item->GetAccessibleParent()); OpAccessibleItem* first_child = NULL; if (m_accessible_item->GetAccessibleChildrenCount() >= 1) first_child = ReadyOrNull(m_accessible_item->GetAccessibleChild(0)); //Groups of tabs have a specific role if (int_role == Accessibility::kElementKindWindow && m_accessible_item->AccessibilityGetWindow() && ((WindowsOpWindow*)m_accessible_item->AccessibilityGetWindow())->IsDialog()) (*role) = ROLE_SYSTEM_DIALOG; else if (int_role == Accessibility::kElementKindWindow && m_accessible_item->AccessibilityGetWindow() && ((WindowsOpWindow*)m_accessible_item->AccessibilityGetWindow())->m_type == OpTypedObject::WINDOW_TYPE_BROWSER) (*role) = IA2_ROLE_FRAME; else if (int_role == Accessibility::kElementKindWindow && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindWorkspace) (*role) = IA2_ROLE_INTERNAL_FRAME; else if (int_role == Accessibility::kElementKindView && m_accessible_item && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindTab) (*role) = ROLE_SYSTEM_PROPERTYPAGE; else if (int_role == Accessibility::kElementKindRadioTabGroup && first_child && first_child->AccessibilityGetRole() == Accessibility::kElementKindTab) (*role) = ROLE_SYSTEM_PAGETABLIST; else if (int_role == Accessibility::kElementKindListRow && acc_parent && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindOutlineList) (*role) = ROLE_SYSTEM_OUTLINEITEM; else if (int_role == Accessibility::kElementKindListRow && acc_parent && acc_parent->AccessibilityGetRole() == Accessibility::kElementKindTable) (*role) = ROLE_SYSTEM_ROW; else (*role) = WindowsOpAccessibilityAdapter::IAcc2Role[int_role]; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::scrollTo(enum IA2ScrollType scrollType) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; switch (scrollType) { case IA2_SCROLL_TYPE_TOP_LEFT: case IA2_SCROLL_TYPE_TOP_EDGE: case IA2_SCROLL_TYPE_LEFT_EDGE: m_accessible_item->AccessibilityScrollTo(Accessibility::kScrollToTop); break; case IA2_SCROLL_TYPE_BOTTOM_RIGHT: case IA2_SCROLL_TYPE_BOTTOM_EDGE: case IA2_SCROLL_TYPE_RIGHT_EDGE: m_accessible_item->AccessibilityScrollTo(Accessibility::kScrollToBottom); break; case IA2_SCROLL_TYPE_ANYWHERE: m_accessible_item->AccessibilityScrollTo(Accessibility::kScrollToAnywhere); break; default: return E_INVALIDARG; } return S_OK; } HRESULT WindowsOpAccessibilityAdapter::scrollToPoint(enum IA2CoordinateType coordinateType, long x, long y) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_groupPosition(long *groupLevel, long *similarItemsInGroup, long *positionInGroup) { return S_FALSE; } HRESULT WindowsOpAccessibilityAdapter::get_states(AccessibleStates *states) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_extendedRole(BSTR *extendedRole) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_localizedExtendedRole(BSTR *localizedExtendedRole) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_nExtendedStates(long *nExtendedStates) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_extendedStates(long maxExtendedStates, BSTR **extendedStates, long *nExtendedStates) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_localizedExtendedStates(long maxLocalizedExtendedStates, BSTR **localizedExtendedStates, long *nLocalizedExtendedStates) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_uniqueID(long *uniqueID) { OP_ASSERT(m_accessible_item); (*uniqueID) = (long)GetAccessibleItemID(m_accessible_item); return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_windowHandle(HWND *windowHandle) { WindowsOpWindow* window = WindowsOpAccessibilityAdapter::GetWindowForAccessibleItem(m_accessible_item); if (window == NULL) return E_FAIL; *windowHandle = window->m_hwnd; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_indexInParent(long *indexInParent) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; OpAccessibleItem* acc_parent = m_accessible_item->GetAccessibleParent(); if (acc_parent == NULL) { *indexInParent = -1; return S_FALSE; } if (!acc_parent->AccessibilityIsReady()) return E_FAIL; *indexInParent = acc_parent->GetAccessibleChildIndex(m_accessible_item); if (*indexInParent == Accessibility::NoSuchChild) return E_FAIL; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_locale(IA2Locale *locale) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_attributes(BSTR *attributes) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpString attrs; m_accessible_item->AccessibilityGetAttributes(attrs); *attributes = SysAllocString(attrs.CStr()); return S_OK; } HRESULT WindowsOpAccessibilityAdapter::addSelection(long startOffset, long endOffset) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; if (OpStatus::IsError(m_accessible_item->AccessibilitySetSelectedTextRange(startOffset, endOffset))) return E_FAIL; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_attributes(long offset, long *startOffset, long *endOffset, BSTR *textAttributes) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_caretOffset(long *offset) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_characterExtents(long offset, enum IA2CoordinateType coordType, long *x, long *y, long *width, long *height) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_nSelections(long *nSelections) { *nSelections = 1; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_offsetAtPoint(long x, long y, enum IA2CoordinateType coordType, long *offset) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_selection(long selectionIndex, long *startOffset, long *endOffset) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_text(long startOffset, long endOffset, BSTR *text) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpString acc_text; if (OpStatus::IsError(m_accessible_item->AccessibilityGetText(acc_text))) return E_FAIL; if (startOffset < 0 || endOffset < startOffset || endOffset > acc_text.Length()) return E_INVALIDARG; *text=SysAllocString(acc_text.SubString(startOffset, endOffset-startOffset).CStr()); return S_OK; } HRESULT WindowsOpAccessibilityAdapter::get_textBeforeOffset(long offset, enum IA2TextBoundaryType boundaryType, long *startOffset, long *endOffset, BSTR *text) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_textAfterOffset(long offset, enum IA2TextBoundaryType boundaryType, long *startOffset, long *endOffset,BSTR *text) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_textAtOffset(long offset, enum IA2TextBoundaryType boundaryType, long *startOffset, long *endOffset, BSTR *text) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpString acc_text; if (OpStatus::IsError(m_accessible_item->AccessibilityGetText(acc_text))) return E_FAIL; if (offset < 0 || offset > acc_text.Length()) return E_INVALIDARG; if (boundaryType == IA2_TEXT_BOUNDARY_ALL) { *text = SysAllocString(acc_text.CStr()); return S_OK; } if (boundaryType == IA2_TEXT_BOUNDARY_CHAR || boundaryType == IA2_TEXT_BOUNDARY_WORD || boundaryType == IA2_TEXT_BOUNDARY_SENTENCE) { UnicodeSegmenter::Type type; switch (boundaryType) { case IA2_TEXT_BOUNDARY_CHAR: type = UnicodeSegmenter::Grapheme; break; case IA2_TEXT_BOUNDARY_WORD: type = UnicodeSegmenter::Word; break; case IA2_TEXT_BOUNDARY_SENTENCE: type = UnicodeSegmenter::Sentence; break; default: return E_FAIL; break; } int new_offset = 0; int old_offset = 0; int length = acc_text.Length() + 1; //We want the length including null char UnicodeSegmenter seg = UnicodeSegmenter(type); while (new_offset <= offset) { old_offset = new_offset; new_offset += seg.FindBoundary(acc_text.CStr() + new_offset, length - new_offset); } *startOffset=old_offset; *endOffset=new_offset; *text = SysAllocString(acc_text.SubString(old_offset,new_offset - old_offset).CStr()); return S_OK; } return E_FAIL; } HRESULT WindowsOpAccessibilityAdapter::removeSelection(long selectionIndex) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::setCaretOffset(long offset) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::setSelection(long selectionIndex, long startOffset, long endOffset) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_nCharacters(long *nCharacters) { if (!m_accessible_item) return CO_E_OBJNOTCONNECTED; if (!m_accessible_item->AccessibilityIsReady()) return E_FAIL; OpString acc_text; if (OpStatus::IsError(m_accessible_item->AccessibilityGetText(acc_text))) return E_FAIL; *nCharacters = acc_text.Length(); return S_OK; } HRESULT WindowsOpAccessibilityAdapter::scrollSubstringTo(long startIndex, long endIndex, enum IA2ScrollType scrollType) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::scrollSubstringToPoint(long startIndex, long endIndex, enum IA2CoordinateType coordinateType, long x, long y) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_newText(IA2TextSegment *newText) { return E_NOTIMPL; } HRESULT WindowsOpAccessibilityAdapter::get_oldText(IA2TextSegment *oldText) { return E_NOTIMPL; } WindowsOpAccessibilityAdapter::VariantEnum::VariantEnum(long* num_clones) : m_position(0), m_ref_counter(0), m_num_clones(num_clones) {} WindowsOpAccessibilityAdapter::VariantEnum::VariantEnum() : m_position(0), m_ref_counter(1) { m_num_clones= new long; *m_num_clones=1; m_contents= new OpVector<VARIANT>; } WindowsOpAccessibilityAdapter::VariantEnum::~VariantEnum() { if(!--(*m_num_clones)) { delete m_num_clones; for (unsigned int i = 0; i < m_contents->GetCount(); i++) { VARIANT *v=m_contents->Get(i); VariantClear(v); delete (v); } m_contents->Clear(); delete m_contents; } } HRESULT WindowsOpAccessibilityAdapter::VariantEnum::QueryInterface(REFIID iid, void ** pvvObject) { if (iid == IID_IUnknown || iid == IID_IEnumVARIANT) { *pvvObject=(IEnumVARIANT*)this; AddRef(); return S_OK; } else { *pvvObject=NULL; return E_NOINTERFACE; } } ULONG WindowsOpAccessibilityAdapter::VariantEnum::AddRef() { return ++m_ref_counter; } ULONG WindowsOpAccessibilityAdapter::VariantEnum::Release() { if (!(--m_ref_counter)) { delete this; return 0; } return m_ref_counter; } OP_STATUS WindowsOpAccessibilityAdapter::VariantEnum::Add(VARIANT *item) { return m_contents->Add(item); } HRESULT WindowsOpAccessibilityAdapter::VariantEnum::Next(unsigned long celt, VARIANT *rgvar, unsigned long *pceltFetched) { unsigned long i; if (pceltFetched) *pceltFetched = 0; if (rgvar == NULL) return E_INVALIDARG; for (i = m_position; i < m_contents->GetCount() && (celt--) > 0; i++) rgvar[i-m_position]=*(m_contents->Get(i)); if (pceltFetched) *pceltFetched = i-m_position; m_position=i; if (celt) return S_FALSE; else return S_OK; } HRESULT WindowsOpAccessibilityAdapter::VariantEnum::Reset() { m_position=0; return S_OK; } HRESULT WindowsOpAccessibilityAdapter::VariantEnum::Skip(unsigned long celt) { m_position=m_position+celt; if (m_position >= m_contents->GetCount()) { m_position = m_contents->GetCount(); return S_FALSE; } else return S_OK; } HRESULT WindowsOpAccessibilityAdapter::VariantEnum::Clone(IEnumVARIANT** ppenum) { VariantEnum *clone = new VariantEnum(m_num_clones); if (!clone) return E_OUTOFMEMORY; clone->m_contents=m_contents; clone->m_position=m_position; (*m_num_clones)++; clone->QueryInterface(IID_IEnumVARIANT, (void**)ppenum); return S_OK; } #endif //ACCESSIBILITY_EXTENSION_SUPPORT
#pragma once namespace NDT { namespace internal { template <typename T, int D> struct IndexList { T head; IndexList<T, D - 1> tail; template <typename Derived> inline __NDT_CUDA_HD_PREFIX__ IndexList(const Eigen::MatrixBase <Derived> & indices) : head(indices(0)), tail(indices.template tail<D - 1>()) {} // inline __NDT_CUDA_HD_PREFIX__ IndexList(const Eigen::Matrix<T,D,1> & indices) // : head(indices(0)), tail(indices.template tail<D-1>()) { } // template <int D2> // __NDT_CUDA_HD_PREFIX__ // inline IndexList(const Eigen::VectorBlock<const Eigen::Matrix<T,D2,1>,D> & indices)) __NDT_CUDA_HD_PREFIX__ inline T sum() const { return head + tail.sum(); } __NDT_CUDA_HD_PREFIX__ inline T product() const { return head * tail.product(); } }; template <typename T> struct IndexList<T, 0> { template <typename Derived> __NDT_CUDA_HD_PREFIX__ inline IndexList(const Eigen::MatrixBase <Derived> & indices) {} __NDT_CUDA_HD_PREFIX__ inline T sum() const { return 0; } __NDT_CUDA_HD_PREFIX__ inline T product() const { return 1; } }; template <typename T> inline __NDT_CUDA_HD_PREFIX__ IndexList<T, 1> IndexList1(const T i0) { return {i0, IndexList < T, 0 > ()}; } template <typename T> inline __NDT_CUDA_HD_PREFIX__ IndexList<T, 2> IndexList2(const T i0, const T i1) { return {i0, IndexList1(i1)}; } template <typename T> inline __NDT_CUDA_HD_PREFIX__ IndexList<T, 3> IndexList3(const T i0, const T i1, const T i2) { return {i0, IndexList2(i1, i2)}; } template <typename T> inline __NDT_CUDA_HD_PREFIX__ IndexList<T, 4> IndexList4(const T i0, const T i1, const T i2, const T i3) { return {i0, IndexList3(i1, i2, i3)}; } } // namespace internal } // namespace NDT
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef GADGET_REMOTE_DEBUG_HANDLER_H #define GADGET_REMOTE_DEBUG_HANDLER_H #ifdef WIDGET_RUNTIME_SUPPORT #include "modules/hardcore/timer/optimer.h" #include "modules/hardcore/mh/messobj.h" #include "modules/util/adt/oplisteners.h" #include "modules/prefs/prefsmanager/collections/pc_tools.h" #include "modules/prefs/prefsmanager/opprefscollection_default.h" #include "modules/scope/scope_module.h" #include "modules/scope/src/scope_manager.h" class DesktopGadget; class IPrefsCollectionTools; class IScopeManager; class IMessageHandler; class RegularPrefsCollectionTools; class RegularLocalScopeManager; class RegularMessageHandler; /** * The logic behind remote debugging connection handling for standalone gadgets. * * @author Bazyli Zygan (bazyl) * @author Wojciech Dzierzanowski (wdzierzanowski) */ class GadgetRemoteDebugHandler : public MessageObject { public: /** * Represents the remote debugging connection state. */ struct State { State(); /** Because OpString has no real copying support. */ State(const State& rhs); /** Because OpString has no real copying support. */ State& operator=(const State& rhs); OpString m_ip_address; int m_port_no; BOOL m_connected; }; /** * Interface for listening on remote debug connection state changes. */ class Listener { public: virtual ~Listener() {} virtual void OnConnectionSuccess() = 0; virtual void OnConnectionFailure() = 0; }; /** * @param isTestRun - default is zero, which means that regular global * object will be used to connection and messages handling for test purposes * you can specify objects that will be used instad of singletion objects. */ GadgetRemoteDebugHandler(BOOL isTestRun = 0, IPrefsCollectionTools* prefsm = NULL, IScopeManager* scpm = NULL, IMessageHandler* msgh = NULL); ~GadgetRemoteDebugHandler(); /** * Registers a connection state change listener. * * @param listener the listener object * @return status */ OP_STATUS AddListener(Listener& listener); /** * Removes a previously registered connection state change listener. * * @param listener the listener object * @return status */ OP_STATUS RemoveListener(Listener& listener); /** * Retrieves the current connection state. * * @return the current connection state */ State GetState() const; /** * Sets the connection state. May trigger reconnecting. * * @param rhs the new connection state * @return status */ OP_STATUS SetState(const State& rhs); // // MessageObject // virtual void HandleCallback( OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); /** * l_[something] - pointers used for switch global singleton objects for test purposes */ static IScopeManager* l_scope_manager; private: IPrefsCollectionTools* l_pctools; IMessageHandler* l_message_handler; BOOL m_is_test_run; /** * A helper, OpTimer-based remote debugging connection state poller. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class ConnectionPoller : public OpTimerListener { public: class Listener { public: virtual ~Listener() {} /** * The poller has detected that the remote debugging connection is * closed. */ virtual void OnConnectionClosed() = 0; /** * The poller has reached its poll count limit and will not be * polling anymore. */ virtual void OnMaxPollCount() = 0; }; ConnectionPoller(); BOOL IsPolling() const; /** * (Re)starts the polling procedure using the specified intervals and * timeout. * * @param interval the polling interval [ms] * @param timeout the time after which the polling is aborted [ms] * @param listener the object that will be notified about * polling-related events */ void Start(INT32 interval, INT32 timeout, Listener& listener); // OpTimerListener virtual void OnTimeOut(OpTimer* timer); private: OpTimer m_timer; INT32 m_interval; INT32 m_max_poll_count; INT32 m_poll_count; Listener* m_listener; }; friend class Reconnector; /** * A ConnectionPoller::Listener that reconnects to the remote debugger as * soon as the previous connection is closed. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class Reconnector : public ConnectionPoller::Listener { public: Reconnector(); void Init(GadgetRemoteDebugHandler& handler, const State& state); virtual void OnConnectionClosed(); virtual void OnMaxPollCount(); private: void Connect(); GadgetRemoteDebugHandler* m_handler; State m_state; }; OP_STATUS Connect(const State& state); OP_STATUS Reconnect(const State& state); OP_STATUS Disconnect(); ConnectionPoller m_reconnecting_poller; Reconnector m_reconnector; OpListeners<Listener> m_listeners; }; /** * Interface class used to wrap global object for selftest purposes */ class IScopeManager { public: virtual BOOL IsConnected() = 0; }; class RegularScopeManager : public IScopeManager { public: virtual BOOL IsConnected() { return g_scope_manager->IsConnected(); } }; /** * Interface class used to wrap global object for selftest purposes */ class IPrefsCollectionTools { public: virtual const OpStringC GetStringPref(PrefsCollectionTools::stringpref which) const = 0; virtual OP_STATUS WriteStringL(PrefsCollectionTools::stringpref which, const OpStringC &value) = 0; virtual int GetIntegerPref(PrefsCollectionTools::integerpref which) const = 0; virtual OP_STATUS WriteIntegerL(PrefsCollectionTools::integerpref which, int value) = 0; }; class RegularPrefsCollectionTools : public IPrefsCollectionTools { public: const OpStringC GetStringPref(PrefsCollectionTools::stringpref which) const { return g_pctools->GetStringPref(which); } OP_STATUS WriteStringL(PrefsCollectionTools::stringpref which, const OpStringC &value) { return g_pctools->WriteStringL(which,value); } int GetIntegerPref(PrefsCollectionTools::integerpref which) const { return g_pctools->GetIntegerPref(which); } OP_STATUS WriteIntegerL(PrefsCollectionTools::integerpref which, int value) { return g_pctools->WriteIntegerL(which,value); } }; /** * Interface class used to wrap global object for selftest purposes */ class IMessageHandler { public: virtual void UnsetCallBacks(MessageObject* obj) = 0; virtual OP_STATUS SetCallBack(MessageObject* obj, OpMessage msg, MH_PARAM_1 id) = 0; virtual BOOL PostMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay=0) = 0; }; class RegularMessageHandler: public IMessageHandler { public: void UnsetCallBacks(MessageObject* obj) { g_main_message_handler->UnsetCallBacks(obj); } OP_STATUS SetCallBack(MessageObject* obj, OpMessage msg, MH_PARAM_1 id) { return g_main_message_handler->SetCallBack(obj,msg,id); } BOOL PostMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay=0) { return g_main_message_handler->PostMessage(msg,par1,par2,delay); } }; #endif // WIDGET_RUNTIME_SUPPORT #endif // GADGET_REMOTE_DEBUG_HANDLER_H
/**************************************** @_@ Cat Got Bored *_* #_# *****************************************/ #include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define INF 1000000000 //10e9 #define EPS 1e-9 using namespace std; #define MX_N 30009 ull BIT[MX_N + 5]; map<string,int>ID; string Yoda[MX_N]; string Ori[MX_N]; void update(int idx,ll val) { while(idx<=MX_N) { BIT[idx]+=val; idx+=(idx&-idx); } } ull query(int idx) { ull sum =0; while(idx>0) { sum+=BIT[idx]; idx-=(idx&-idx); } return sum; } int main() { int tc; cin>>tc; while(tc--) { int N; cin>>N; ms(BIT,0); loop(x,1,N) { cin>>Yoda[x]; } loop(x,1,N) { cin>>Ori[x]; ID[Ori[x]] = x; } ull ans = 0; for(int x=N;x>=1;x--) { ull nta = query( ID[Yoda[x] ] ); ans+=nta; update( ID[ Yoda[x] ] , 1); } cout<<ans<<endl; } return 0; }
// Copyright 2020 Fuji-Iot authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "fuji_frame.h" #include "gtest/gtest.h" namespace fuji_iot { namespace test { class FujiFrameTest : public testing::Test { protected: void MakeMasterFrame(std::array<uint8_t, 8> data) { frame_ = std::unique_ptr<FujiMasterFrame>(new FujiMasterFrame(data)); } void SetUp() { std::array<uint8_t, 8> data = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; frame_ = std::unique_ptr<FujiMasterFrame>(new FujiMasterFrame(data)); } std::unique_ptr<FujiMasterFrame> frame_; }; TEST_F(FujiFrameTest, Address) { MakeMasterFrame({0x00, 0x81, 0x00, 0x46, 0x12, 0xa0, 0x00, 0x20}); EXPECT_EQ(frame_->Destination(), DestinationAddr::OTHER); MakeMasterFrame({0x00, 0xa0, 0x00, 0x46, 0x12, 0xa0, 0x00, 0x20}); EXPECT_EQ(frame_->Destination(), DestinationAddr::WIRED_CONTROLLER_ADDR); MakeMasterFrame({0x00, 0xf0, 0x00, 0x46, 0x12, 0xa0, 0x00, 0x20}); EXPECT_EQ(frame_->Destination(), DestinationAddr::UNKNOWN); } TEST_F(FujiFrameTest, Type) { MakeMasterFrame({0x00, 0x81, 0x00, 0x46, 0x12, 0xa0, 0x00, 0x20}); EXPECT_EQ(frame_->Type(), RegisterType::STATUS); MakeMasterFrame({0x00, 0xa0, 0x20, 0x46, 0x12, 0xa0, 0x00, 0x20}); EXPECT_EQ(frame_->Type(), RegisterType::LOGIN); MakeMasterFrame({0x00, 0xf0, 0x10, 0x46, 0x12, 0xa0, 0x00, 0x20}); EXPECT_EQ(frame_->Type(), RegisterType::ERROR); MakeMasterFrame({0x00, 0xa0, 0x70, 0x46, 0x12, 0xa0, 0x00, 0x20}); EXPECT_EQ(frame_->Type(), RegisterType::UNKNOWN); } TEST_F(FujiFrameTest, Payload) { MakeMasterFrame({0x00, 0x81, 0x00, 0x01, 0x23, 0x34, 0x56, 0x78}); EXPECT_EQ(frame_->Payload(), (std::array<uint8_t, 5>({0x01, 0x23, 0x34, 0x56, 0x78}))); } TEST_F(FujiFrameTest, TypeAccessor) { frame_->WithType(RegisterType::STATUS); EXPECT_EQ(RegisterType::STATUS, frame_->Type()); frame_->WithType(RegisterType::ERROR); EXPECT_EQ(RegisterType::ERROR, frame_->Type()); frame_->WithType(RegisterType::LOGIN); EXPECT_EQ(RegisterType::LOGIN, frame_->Type()); } } // namespace test } // namespace fuji_iot
#include "drone_esc.h" int DroneESC::intensity_to_servo(double intensity) { int temp_min = 0, temp_max = 10000; int temp, ret; temp = ((int) round(intensity * (temp_max - temp_min))) + temp_min; ret = map(temp, temp_min, temp_max, SERVO_OUTPUT_MIN, SERVO_OUTPUT_MAX); return ret; } void DroneESC::apply_intensity(int16_t direction) { int value; double intensity; intensity = intensities[direction]; value = intensity_to_servo(intensity); escs[direction].writeMicroseconds(value); } void DroneESC::apply_intensities() { int i; for (i = 0; i < 4; ++i) { apply_intensity(i); } } DroneESC::DroneESC(int16_t pin_nw, int16_t pin_ne, int16_t pin_se, int16_t pin_sw) { pins[0] = pin_nw; pins[1] = pin_ne; pins[2] = pin_se; pins[3] = pin_sw; } void DroneESC::initialize() { int i; for (i = 0; i < 4; ++i) { escs[i].attach(pins[i]); set_intensities(INTENSITY_MIN); } } void DroneESC::set_intensities(double intensity) { int i; for (i = 0; i < 4; ++i) { set_intensity(i, intensity); } } void DroneESC::set_intensity(int16_t direction, double intensity) { intensity = min(max(intensity, INTENSITY_MIN), INTENSITY_MAX); intensities[direction] = intensity; apply_intensity(direction); } void DroneESC::set_max_intensities() { set_intensities(INTENSITY_MAX); } void DroneESC::set_min_intensities() { set_intensities(INTENSITY_MIN); } void DroneESC::set_max_intensity(int16_t direction) { set_intensity(direction, INTENSITY_MAX); } void DroneESC::set_min_intensities(int16_t direction) { set_intensity(direction, INTENSITY_MIN); } void DroneESC::change_intensity(int16_t direction, double pcn) { double intensity = intensities[direction]; intensity = intensity * (1 + pcn); set_intensity(direction, intensity); } void DroneESC::change_intensities(double pcn) { int i; for (i = 0; i < 4; ++i) { change_intensity(i, pcn); } } void DroneESC::set_intensity_linear(int16_t direction, double intensity_before, double intensity_after, int duration) { int i, n; double delta, intensity; n = duration / TIME_QUANTUM; delta = (intensity_after - intensity_before) / n; for (i = 0; i < n; ++i) { intensity = intensity_before + i * delta; set_intensity(direction, intensity); delay(TIME_QUANTUM); } } void DroneESC::set_intensities_linear(double intensity_before, double intensity_after, int duration) { int i, n; double delta, intensity; n = duration / TIME_QUANTUM; delta = (intensity_after - intensity_before) / n; for (i = 0; i < n; ++i) { intensity = intensity_before + i * delta; set_intensities(intensity); delay(TIME_QUANTUM); } } void DroneESC::calibrate() { set_max_intensities(); delay(CALI_MAX_DURATION); set_min_intensities(); delay(CALI_MIN_DURATION); set_intensities_linear(INTENSITY_MIN, INTENSITY_MAX, CALI_GRAD_DURATION); }
#include "shape.h" #include <iostream> using namespace std; Shape::Shape(string new_name, string new_colour){ ////cout << "Creating shape object for part 1." << endl; ////cout << "\tSetting shape object name to be: Shape." << endl; ////cout << "\tSetting shape object colour to be: Green." << endl; name = new_name; colour = new_colour; } string Shape::get_name(){ return name; } string Shape::get_colour(){ return colour; } void Shape::set_name(string new_name){ name = new_name; } void Shape::set_colour(string new_colour){ colour = new_colour; }
#include "Help.h" #include <fstream> #include "PointLocator.h" namespace help { void printStartCount(const std::vector<dax::Id>& pointStarts, const std::vector<int>& pointCounts, std::iostream& stream) { stream << std::setw(10) << "Pt Start: "; for (unsigned int i = 0; i < pointStarts.size(); ++i) stream << std::setw(3) << pointStarts[i] << ", "; stream << std::endl; stream << std::setw(10) << "Pt Count: "; for (unsigned int i = 0; i < pointCounts.size(); ++i) stream << std::setw(3) << pointCounts[i] << ", "; stream << std::endl; } void printBinPoint(float x, float y, float z, const PointLocator& locator, std::iostream& stream) { stream << std::setw(10) << "X: " << x << std::endl; stream << std::setw(10) << "Y: " << y << std::endl; stream << std::setw(10) << "Z: " << z << std::endl; dax::Vector3 point(x, y, z); // find the bucket id the point belongs to dax::Id id = locator.locatePoint(point); // find the points in the same bucket std::vector<dax::Vector3> points = locator.getBucketPoints(id); // print stream << std::setw(10) << "Bucket Id: " << id << std::endl; stream << std::setw(10) << "Bin Count: " << points.size() << std::endl; } void printCompare(const std::string& output, const std::string& filename) { // output string that needs to be verified std::cout << "Output: " << std::endl << output << std::endl << std::endl; // read in the correct output std::ifstream fin(filename.c_str(), std::ios::binary); assert(fin.good()); std::string correct_output; fin.seekg(0, std::ios::end); correct_output.resize(fin.tellg()); fin.seekg(0, std::ios::beg); fin.read(&correct_output[0], correct_output.size()); fin.close(); std::cout << "Correct Output: " << std::endl << correct_output << std::endl; // compare the output and the correct output assert(output == correct_output); } void printCoinPoints(const std::vector<dax::Vector3>& testPoints, const std::vector<dax::Id>& testBucketIds, const std::vector<int>& testCounts, const std::vector<dax::Vector3>& testCoinPoints, std::iostream& stream) { // print stream << std::setw(10) << "Test X: "; for (unsigned int i = 0; i < testPoints.size(); ++i) stream << std::setw(6) << testPoints[i][0] << ", "; stream << std::endl; stream << std::setw(10) << "Test Y: "; for (unsigned int i = 0; i < testPoints.size(); ++i) stream << std::setw(6) << testPoints[i][1] << ", "; stream << std::endl; stream << std::setw(10) << "Test Z: "; for (unsigned int i = 0; i < testPoints.size(); ++i) stream << std::setw(6) << testPoints[i][2] << ", "; stream << std::endl; stream << std::setw(10) << "Bucket: "; for (unsigned int i = 0; i < testBucketIds.size(); ++i) stream << std::setw(6) << testBucketIds[i] << ", "; stream << std::endl; stream << std::setw(10) << "Count: "; for (unsigned int i = 0; i < testCounts.size(); ++i) stream << std::setw(6) << testCounts[i] << ", "; stream << std::endl; stream << std::setw(10) << "Coin X: "; for (unsigned int i = 0; i < testCoinPoints.size(); ++i) stream << std::setw(6) << testCoinPoints[i][0] << ", "; stream << std::endl; stream << std::setw(10) << "Coin Y: "; for (unsigned int i = 0; i < testCoinPoints.size(); ++i) stream << std::setw(6) << testCoinPoints[i][1] << ", "; stream << std::endl; stream << std::setw(10) << "Coin Z: "; for (unsigned int i = 0; i < testCoinPoints.size(); ++i) stream << std::setw(6) << testCoinPoints[i][2] << ", "; stream << std::endl; } }
#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <reactor/net/PollPoller.h> #include <assert.h> #include <errno.h> #include <stdio.h> #include <algorithm> #include <reactor/net/Channel.h> namespace reactor { namespace net { PollPoller::PollPoller(): Poller(), channels_(), pollfds_() { } PollPoller::~PollPoller() { } void PollPoller::update_channel(Channel *channel) { int fd = channel->fd(); short events = channel->events(); struct pollfd pollfd; pollfd.fd = fd; pollfd.events = 0; pollfd.revents = 0; if (events & EVENT_READ) pollfd.events |= POLLIN; // 不支持urgent data(POLLPRI) if (events & EVENT_WRITE) pollfd.events |= POLLOUT; if (events & EVENT_CLOSE) pollfd.events |= POLLRDHUP; auto it = channels_.find(fd); if (it == channels_.end()) { // add assert(channel->index() < 0); channels_[fd] = channel; pollfds_.push_back(pollfd); channel->set_index(static_cast<int>(pollfds_.size() - 1)); } else { // update int idx = channel->index(); assert(0 <= idx && idx < static_cast<int>(pollfds_.size())); assert(pollfds_[idx].fd == fd); pollfds_[idx] = pollfd; } } void PollPoller::remove_channel(Channel *channel) { auto it = channels_.find(channel->fd()); if ((it != channels_.end()) && (channel->index() >= 0)) { int idx = channel->index(); assert(0 <= idx && idx < static_cast<int>(pollfds_.size())); if (idx != static_cast<int>(pollfds_.size())- 1) { channels_[ pollfds_.back().fd ]->set_index(idx); std::swap(pollfds_.back(), pollfds_[idx]); } channel->set_index(-1); channels_.erase(it); pollfds_.pop_back(); } } int PollPoller::poll(ChannelList *active_channels, int timeout_ms) { nfds_t nfds = static_cast<nfds_t>(pollfds_.size()); int num_event = ::poll(&pollfds_[0], nfds, timeout_ms); active_channels->clear(); if (num_event < 0) { int save_errno = errno; if (errno != EINTR) { perror("PollPoller::poll"); } errno = save_errno; } else if (num_event > 0) { for (int i=0, sz=static_cast<int>(pollfds_.size()); i < sz; i++) { struct pollfd pollfd = pollfds_[i]; if (pollfd.fd >= 0 && pollfd.revents != 0) { Channel *channel = channels_[pollfd.fd]; short revents = EVENT_NONE; if (pollfd.revents & (POLLRDHUP | POLLHUP)) { revents |= EVENT_CLOSE; } if (pollfd.revents & (POLLERR | POLLNVAL)) { revents |= EVENT_ERROR; } if (pollfd.revents & (POLLIN | POLLPRI)) { revents |= EVENT_READ; } if (pollfd.revents & POLLOUT) { revents |= EVENT_WRITE; } if ((revents & EVENT_CLOSE) && (revents & EVENT_READ)) { revents &= ~EVENT_CLOSE; } channel->set_revents(revents); active_channels->push_back(channel); if (static_cast<int>(active_channels->size()) == num_event) break; } } } return num_event; } } // namespace net } // namespace reactor
#include "SyntaxTree.h" SyntaxTree::SyntaxTree() { head = int(nodes.size()-1); } SyntaxTree::~SyntaxTree() { } int SyntaxTree::addNode(treeNode& t) { nodes.push_back(t); head = nodes.size() - 1; // 默认指向最后一个位置,适用于递归建树 return head; // 返回指向刚刚加入的node的 位置,方便建树 } void SyntaxTree::outputTreeAsFile(ofstream& fout,int subTree , int widthset , int heightset ) { queue<treeNode> treeNodeQueue; //利用队列进行深度遍历 vector<pair<treeNode,int>> currentNodes; int depth = getTreeDepth(subTree); //根节点 if (nodes[subTree].child_ptrs.size() > 1) { fout << setiosflags(ios::left) << setw(widthset)<<setfill('-') << nodes[subTree].t.get_token_name() << setw(' ')<<endl; } else { fout << setiosflags(ios::left) << setw(widthset) << nodes[subTree].t.get_token_name() << endl; } // 把根节点的孩子入队列 if (nodes[subTree].child_ptrs.size() == 0) { // 如果没有孩子,需要补空检点 treeNode t = treeNode(); t.width = nodes[subTree].width; // -1表示是空节点 treeNodeQueue.push(t); } else { for (int j = 0; j < nodes[subTree].child_ptrs.size(); j++) { treeNodeQueue.push(nodes[nodes[subTree].child_ptrs[j]]); } } // 跟节点之后的 for (int h = 0; h < depth-1; h++) { //把队列里需要打印的节点转移到vector中,同时计算需要打印的横树枝的宽度 //见vector清空 currentNodes.clear(); while(treeNodeQueue.size()>0) { int printwidth = 0; treeNode n = treeNodeQueue.front(); for (int j = 0; j < int(n.child_ptrs.size() - 1); j++) { //孩子数 -1 printwidth += nodes[n.child_ptrs[j]].width; } currentNodes.push_back(make_pair(treeNodeQueue.front(),printwidth)); treeNodeQueue.pop(); //队列里弹出节点 } //按深度进行输出 for (int line = 0; line < heightset; line++) { //分行输出 for (int n = 0; n < currentNodes.size(); n++) { //分结点输出 //输出当前的节点 pair<treeNode, int> current = currentNodes[n]; if (line == heightset - 1) { //输出本节点内容 if (current.first.t.get_token_name() == "none") { fout << setiosflags(ios::left) << setw(widthset) << " "; } else if (current.first.t.get_value() == "_") { //如果token值是非关键字,不需要把值打印出来 if (current.first.child_ptrs.size() > 1) { fout << setiosflags(ios::left) << setw(widthset) << setfill('-') << current.first.t.get_token_name() << setfill(' '); } else { fout << setiosflags(ios::left) << setw(widthset) << current.first.t.get_token_name(); } } else { if (current.first.child_ptrs.size() > 1) { fout << setiosflags(ios::left) << setw(widthset) << setfill('-') << current.first.t.get_token_name() + "=" + current.first.t.get_value() << setfill(' '); } else { fout << setiosflags(ios::left) << setw(widthset) << current.first.t.get_token_name() + "=" + current.first.t.get_value() ; } } // 输出 ”横树枝“ for (int i = 0; i < current.first.width-1; i++) { //打印该节点所需要的横树枝 if (current.first.t.get_token_name() == "none") { fout << setiosflags(ios::left) << setw(widthset) << " "; } else if (i < current.second-1) { fout << setiosflags(ios::left) << setw(widthset)<<setfill('-') << "-" << setfill(' '); //打印横树枝 } else { fout << setiosflags(ios::left) << setw(widthset) << " "; } } } // 输出 "纵树枝" else { for (int i = 0; i < current.first.width; i++) { if (current.first.t.get_token_name() == "none") { fout << setiosflags(ios::left) << setw(widthset) << " "; continue; } if (i == 0) { fout << setiosflags(ios::left) << setw(widthset) << "|"; } else { fout << setiosflags(ios::left) << setw(widthset) << " "; } } } } fout << endl; } // 计算下一层需要输出的节点 while(treeNodeQueue.size()>0){ treeNodeQueue.pop(); } for (int i = 0; i < currentNodes.size(); i++) { if (currentNodes[i].first.child_ptrs.size() == 0) { // 如果没有孩子,需要补空检点 treeNode t = treeNode(); t.width = currentNodes[i].first.width; // -1表示是空节点 treeNodeQueue.push(t); } else { for (int j = 0; j < currentNodes[i].first.child_ptrs.size(); j++) { treeNodeQueue.push(nodes[currentNodes[i].first.child_ptrs[j]]); } } } } } int SyntaxTree::getTreeWidth( int subTree) { //计算树的宽度,最宽的节点数 int width = 0; if (nodes[subTree].child_ptrs.size() == 0) { //如果是叶子节点 width = 1; nodes[subTree].width = width; return 1; //出口条件 } for (int i = 0; i < nodes[subTree].child_ptrs.size(); i++) { width += getTreeWidth(nodes[subTree].child_ptrs[i]); //递归计算宽度 } nodes[subTree].width = width; return width; } int SyntaxTree::getTreeDepth(int subTree) { //计算树的深度 int depth = 0; if (nodes[subTree].child_ptrs.size() == 0) { //如果是叶子节点 return 1; //出口条件 } int maxDepth = 0; for (int i = 0; i < nodes[subTree].child_ptrs.size(); i++) { int subDepth = getTreeDepth(nodes[subTree].child_ptrs[i]); //递归计算宽度 if (subDepth > maxDepth) { maxDepth = subDepth; } } return maxDepth+1; }
#include "WindowComparison.hh" #include "str.hh" WindowComparison::WindowComparison(PG_Widget *parent, const std::string &reference, const std::string &hypothesis) : WindowChild(parent, "Comparison results", 300, 530, true, true, "OK"), m_reference(reference), m_hypothesis(hypothesis) { this->m_comparer = NULL; this->m_waiting_label = NULL; } WindowComparison::~WindowComparison() { if (this->m_comparer) { delete this->m_comparer; this->m_comparer = NULL; } } void WindowComparison::initialize() { WindowChild::initialize(); } void WindowComparison::do_opening() { WindowChild::do_opening(); this->m_waiting_label = new PG_Label(this->m_window, PG_Rect(10, 30, 100, 30), "Comparing..."); try { this->m_comparer = new TextComparer(this->m_reference, this->m_hypothesis); } catch (Exception excep) { this->error(excep.what(), ERROR_CLOSE); } } void WindowComparison::do_running() { if (this->m_comparer) { if (this->m_comparer->run_comparer()) { bool ok = true; TextComparisonResult result = this->m_comparer->get_result(ok); if (!ok) { this->error("Comparing failed.\nMost probable reason is that SCLite " "was not found", ERROR_CLOSE); } else { if (this->m_waiting_label) { delete this->m_waiting_label; this->m_waiting_label = NULL; } this->construct_result_array(result); this->m_window->Update(true); } delete this->m_comparer; this->m_comparer = NULL; } } } void WindowComparison::do_closing(int return_value) { if (this->m_waiting_label) { delete this->m_waiting_label; this->m_waiting_label = NULL; } if (this->m_comparer) { delete this->m_comparer; this->m_comparer = NULL; } } void WindowComparison::construct_result_array(const TextComparisonResult &result) { // Array for word comparison. this->construct_label(0, 0, "WORD", PG_Label::RIGHT); this->construct_label(1, 0, "N", PG_Label::CENTER); this->construct_label(2, 0, "%", PG_Label::CENTER); this->construct_label(0, 1, "Accuracy", PG_Label::RIGHT); this->construct_label(0, 2, "Correct", PG_Label::RIGHT); this->construct_label(0, 3, "Substitution", PG_Label::RIGHT); this->construct_label(0, 4, "Deletion", PG_Label::RIGHT); this->construct_label(0, 5, "Insertion", PG_Label::RIGHT); // Array for character comparison. this->construct_label(0, 7, "CHARACTER", PG_Label::RIGHT); this->construct_label(1, 7, "N", PG_Label::CENTER); this->construct_label(2, 7, "%", PG_Label::CENTER); this->construct_label(0, 8, "Accuracy", PG_Label::RIGHT); this->construct_label(0, 9, "Correct", PG_Label::RIGHT); this->construct_label(0, 10, "Substitution", PG_Label::RIGHT); this->construct_label(0, 11, "Deletion", PG_Label::RIGHT); this->construct_label(0, 12, "Insertion", PG_Label::RIGHT); // Numeric results for word comparison. this->construct_numeric_label(1, 2, result._word.correct); this->construct_numeric_label(1, 3, result._word.substitution); this->construct_numeric_label(1, 4, result._word.deletion); this->construct_numeric_label(1, 5, result._word.insertion); // Numeric results for character comparison. this->construct_numeric_label(1, 9, result._char.correct); this->construct_numeric_label(1, 10, result._char.substitution); this->construct_numeric_label(1, 11, result._char.deletion); this->construct_numeric_label(1, 12, result._char.insertion); // Percentage results for word comparison. long correct = (long)result._word.correct - result._word.insertion; unsigned int ref_words = result._word.correct + result._word.substitution + result._word.deletion;// - result._word.insertion; unsigned int total = result._word.correct + result._word.substitution + result._word.deletion + result._word.insertion; this->construct_percentage_label(2, 1, correct, ref_words); this->construct_percentage_label(2, 2, result._word.correct, total); this->construct_percentage_label(2, 3, result._word.substitution, total); this->construct_percentage_label(2, 4, result._word.deletion, total); this->construct_percentage_label(2, 5, result._word.insertion, total); // Percentage results for character comparison. correct = (long)result._char.correct - result._char.insertion; ref_words = result._char.correct + result._char.substitution + result._char.deletion;// - result._char.insertion; total = result._char.correct + result._char.substitution + result._char.deletion + result._char.insertion; this->construct_percentage_label(2, 8, correct, ref_words); this->construct_percentage_label(2, 9, result._char.correct, total); this->construct_percentage_label(2, 10, result._char.substitution, total); this->construct_percentage_label(2, 11, result._char.deletion, total); this->construct_percentage_label(2, 12, result._char.insertion, total); } PG_Label* WindowComparison::construct_numeric_label(unsigned int column, unsigned int row, unsigned int value) { return this->construct_label(column, row, str::fmt(10, "%d", value), PG_Label::CENTER); } PG_Label* WindowComparison::construct_percentage_label(unsigned int column, unsigned int row, long value, unsigned int total) { float percent = 0; if (total > 0) percent = ((float)value / total) * 100; return this->construct_label(column, row, str::fmt(10, "%.1f%%", percent), PG_Label::CENTER); } PG_Label* WindowComparison::construct_label(unsigned int column, unsigned int row, const std::string &text, PG_Label::TextAlign align) { const unsigned int left_margin = 30; const unsigned int top_margin = 35; const unsigned int horizontal_space = 10; const unsigned int vertical_space = 5; const unsigned int first_extra_width = 40; const unsigned int first_extra_space = 10; const unsigned int width = 60; const unsigned int height = 25; unsigned int x = left_margin + (column > 0) * (first_extra_width + first_extra_space) + column * (width + horizontal_space); unsigned int y = top_margin + row * (height + vertical_space); PG_Label *label = new PG_Label(this->m_window, PG_Rect(x, y, width + (column == 0) * first_extra_width, height), text.data()); label->SetAlignment(align); label->SetVisible(true); return label; }
#ifndef BUTTONS_H #define BUTTONS_H #include <QWidget> #include <QMouseEvent> #include <QTime> #include <QPainter> #include <string> class Buttons { public: Buttons(int X=0, int Y=0, int wi=0, int he=0, QString = ""); bool isClicked(QMouseEvent *e); bool isHovering(QMouseEvent *e); QColor getColor(); QColor getRevColor(); void setColor(QColor c); void setRevColor(QColor c); void updateTime(); void setString(QString t); void drawButton(QPainter &painter, Buttons button); QString getString(); int getX(); int getY(); int getHeight(); int getWidth(); bool getHov(); void setHov(); void setX(int X); private: int x; int y; int width; int height; QString text; QColor colorr; QColor revcolor; bool hov; signals: }; #endif // BUTTONS_H
#ifndef GNLISTMANAGER_H #define GNLISTMANAGER_H #include "GnList.h" template<class TListType, class TListSmartPointer> class GnListManager : public GnSmartObject { protected: GnList<TListSmartPointer> mList; typedef GnListIterator<TListSmartPointer> ElementIterator; typedef TListType ElementType; public: GnListManager(){}; virtual ~GnListManager() { RemoveAll(); }; inline void Append(TListType* val) { mList.Append(val); } inline void Prepend(TListType* val) { mList.Prepend(val); } inline void Remove(TListType* val) { GnListRemove(mList, val); } inline void RemoveAll() { mList.RemoveAll(); } inline GnList<TListSmartPointer>& GetList() { return mList; } inline const GnList<TListSmartPointer>& GetList() const { return mList; } }; #endif // GNLISTMANAGER_H
// -*- LSST-C++ -*- /* * LSST Data Management System * Copyright 2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ // Class header #include "ccontrol/UserQueryDropTable.h" // System headers #include <ctime> // LSST headers #include "lsst/log/Log.h" // Qserv headers #include "css/CssAccess.h" #include "css/CssError.h" #include "qdisp/MessageStore.h" #include "qmeta/Exceptions.h" #include "qmeta/QMeta.h" #include "sql/SqlConnection.h" #include "sql/SqlErrorObject.h" #include "util/IterableFormatter.h" namespace { LOG_LOGGER getLogger() { static LOG_LOGGER logger = LOG_GET("lsst.qserv.ccontrol.UserQueryDropTable"); return logger; } } namespace lsst { namespace qserv { namespace ccontrol { // Constructor UserQueryDropTable::UserQueryDropTable(std::shared_ptr<css::CssAccess> const& css, std::string const& dbName, std::string const& tableName, sql::SqlConnection* resultDbConn, std::string const& resultTable, std::shared_ptr<qmeta::QMeta> const& queryMetadata, qmeta::CzarId qMetaCzarId) : _css(css), _dbName(dbName), _tableName(tableName), _resultDbConn(resultDbConn), _resultTable(resultTable), _queryMetadata(queryMetadata), _qMetaCzarId(qMetaCzarId), _qState(UNKNOWN), _messageStore(std::make_shared<qdisp::MessageStore>()), _sessionId(0) { } std::string UserQueryDropTable::getError() const { return std::string(); } // Attempt to kill in progress. void UserQueryDropTable::kill() { } // Submit or execute the query. void UserQueryDropTable::submit() { // Just mark this table in CSS with special status, watcher // will take care of the actual delete process LOGF(getLogger(), LOG_LVL_INFO, "going to drop table - %s.%s" % _dbName % _tableName); // create result table first, exact schema does not matter but mysql // needs at least one column in table DDL LOGF(getLogger(), LOG_LVL_DEBUG, "creating result table: %s" % _resultTable); std::string sql = "CREATE TABLE " + _resultTable + " (CODE INT)"; sql::SqlErrorObject sqlErr; if (not _resultDbConn->runQuery(sql, sqlErr)) { // There is no way to return success if we cannot create result table so just stop here std::string message = "Failed to create result table: " + sqlErr.errMsg(); _messageStore->addMessage(-1, 1005, message, MessageSeverity::MSG_ERROR); _qState = ERROR; return; } // check current table status, if not READY then fail try { auto statusMap = _css->getTableStatus(_dbName); LOGF(getLogger(), LOG_LVL_DEBUG, "all table status: %s" % util::printable(statusMap)); if (statusMap.count(_tableName) != 1) { std::string message = "Unknown table " + _dbName + "." + _tableName; _messageStore->addMessage(-1, 1051, message, MessageSeverity::MSG_ERROR); _qState = ERROR; return; } LOGF(getLogger(), LOG_LVL_DEBUG, "table status: %s" % statusMap[_tableName]); if (statusMap[_tableName] != css::KEY_STATUS_READY) { std::string message = "Unexpected status for table: " + _dbName + "." + _tableName + ": " + statusMap[_tableName]; _messageStore->addMessage(-1, 1051, message, MessageSeverity::MSG_ERROR); _qState = ERROR; return; } } catch (css::CssError const& exc) { LOGF(getLogger(), LOG_LVL_ERROR, "css failure: %s" % exc.what()); std::string message = "CSS error: " + std::string(exc.what()); _messageStore->addMessage(-1, 1051, message, MessageSeverity::MSG_ERROR); _qState = ERROR; return; } // Add this query to QMeta so that progress can be tracked, // QMeta needs to be updated by watcher when it finishes with the table // so we embed query id into CSS table status below qmeta::QInfo::QType qType = qmeta::QInfo::ASYNC; std::string user = "anonymous"; // we do not have access to that info yet std::string query = "DROP TABLE " + _dbName + "." + _tableName; qmeta::QInfo qInfo(qType, _qMetaCzarId, user, query, "", "", ""); qmeta::QMeta::TableNames tableNames; qmeta::QueryId qMetaQueryId = 0; try { qMetaQueryId = _queryMetadata->registerQuery(qInfo, tableNames); } catch (qmeta::Exception const& exc) { // not fatal, just print error message and continue LOGF(getLogger(), LOG_LVL_WARN, "QMeta failure (non-fatal): %s" % exc.what()); } // update status to trigger watcher std::string newStatus = css::KEY_STATUS_DROP_PFX + std::to_string(::time(nullptr)) + ":qid=" + std::to_string(qMetaQueryId); LOGF(getLogger(), LOG_LVL_DEBUG, "new table status: %s" % newStatus); try { // TODO: it's better to do it in one atomic operation with // getTableStatus, but CSS API does not have this option yet _css->setTableStatus(_dbName, _tableName, newStatus); _qState = SUCCESS; } catch (css::NoSuchTable const& exc) { // Has it disappeared already? LOGF(getLogger(), LOG_LVL_ERROR, "table disappeared from CSS"); std::string message = "Unknown table " + _dbName + "." + _tableName; _messageStore->addMessage(-1, 1051, message, MessageSeverity::MSG_ERROR); _qState = ERROR; } catch (css::CssError const& exc) { LOGF(getLogger(), LOG_LVL_ERROR, "CSS failure: %s" % exc.what()); std::string message = "CSS error: " + std::string(exc.what()); _messageStore->addMessage(-1, 1051, message, MessageSeverity::MSG_ERROR); _qState = ERROR; } // if failed then update status in QMeta if (_qState == ERROR) { if (qMetaQueryId) { try { _queryMetadata->completeQuery(qMetaQueryId, qmeta::QInfo::FAILED); } catch (qmeta::Exception const& exc) { // not fatal, just print error message and continue LOGF(getLogger(), LOG_LVL_WARN, "QMeta failure (non-fatal): %s" % exc.what()); } } } } // Block until a submit()'ed query completes. QueryState UserQueryDropTable::join() { // everything should be done in submit() return _qState; } // Release resources. void UserQueryDropTable::discard() { // no resources } }}} // lsst::qserv::ccontrol
#pragma once #include "bricks/threading/mutex.h" namespace Bricks { namespace Threading { class Condition : public Mutex { protected: void* conditionHandle; public: Condition(); ~Condition(); void Wait(); bool Wait(const Timespan& timeout) { return Wait(Time::GetCurrentTime() + timeout); } bool Wait(const Time& timeout); void Signal(); void Broadcast(); using Mutex::Lock; using Mutex::TryLock; template<typename T> void Lock(const T& condition) { Lock(); while (!condition()) Wait(); } template<typename T> bool Lock(const T& condition, const Timespan& timeout) { return Lock(condition, Time::GetCurrentTime() + timeout); } template<typename T> bool Lock(const T& condition, const Time& timeout) { if (!Lock(timeout)) return false; while (!condition()) { if (!Wait(timeout)) { Unlock(); return false; } } return true; } template<typename T> bool TryLock(const T& condition) { if (TryLock()) { if (condition()) return true; Unlock(); } return false; } }; } }
#ifndef TASK_H #define TASK_H namespace tsk { namsespace task { enum task_state { TASK_CREATED, TASK_WAITING, TASK_STARTED, TASK_COMPLETED }; typedef error_code int; class base_task { protected : task_state state; error_code err; public : base_task():state(task_state::TASK_CREATED) {} void start() { state = task_state::TASK_STARTED; err = performTask(); state = task_state::TASK_COMPLETED; taskCompleted(); } virtual error_code performTask() = 0; virtual void taskCompleted() = 0; }; class sync_task : public base_task { private : std::mutex _mutex; std::condition_variable _cond; public : void wait() { std::unique_lock<std::mutex> lck(_mutex); while (state != task_state::TASK_COMPLETED) wait(_lck); } } template<typename T> task_queue : cqueue<T*> { protrected : tsk::tpool::ThreadPool *p; private: task_queue() { p = new ThreadPool(10); } task_queue::pushTask(T *task) { add(task); } void wait() { p->wait(); } } } // namespace task } // namespace tsk
#ifndef __STDX_TTYCOLOR_H #define __STDX_TTYCOLOR_H // Posix header files #include <sys/types.h> #include <termios.h> #include <unistd.h> // C 89 header files #include <assert.h> #include <errno.h> // C++ 98 header files #include <string> #include <sstream> #include <iomanip> namespace stdx { const char* const _Text_endcolor = "\033[0m"; const char* const _Text_black = "\033[22;30m"; const char* const _Text_red = "\033[22;31m"; const char* const _Text_green = "\033[22;32m"; const char* const _Text_brown = "\033[22;33m"; const char* const _Text_blue = "\033[22;34m"; const char* const _Text_magenta = "\033[22;35m"; const char* const _Text_cyan = "\033[22;36m"; const char* const _Text_gran = "\033[22;37m"; const char* const _Text_dark = "\033[01;30m"; const char* const _Text_lightred = "\033[01;31m"; const char* const _Text_lightgreen = "\033[01;32m"; const char* const _Text_yellow = "\033[01;33m"; const char* const _Text_lightblue = "\033[01;34m"; const char* const _Text_lightmagenta = "\033[01;35m"; const char* const _Text_lightcyan = "\033[01;36m"; const char* const _Text_white = "\033[01;37m"; const char* const _Back_black = "\033[22;40m"; const char* const _Back_red = "\033[22;41m"; const char* const _Back_green = "\033[22;42m"; const char* const _Back_brown = "\033[22;43m"; const char* const _Back_blue = "\033[22;44m"; const char* const _Back_magenta = "\033[22;45m"; const char* const _Back_cyan = "\033[22;46m"; const char* const _Back_gran = "\033[22;47m"; const char* const _Back_dark = "\033[01;40m"; const char* const _Back_lightred = "\033[01;41m"; const char* const _Back_lightgreen = "\033[01;42m"; const char* const _Back_yellow = "\033[01;43m"; const char* const _Back_lightblue = "\033[01;44m"; const char* const _Back_lightmagenta = "\033[01;45m"; const char* const _Back_lightcyan = "\033[01;46m"; const char* const _Back_white = "\033[01;47m"; struct _Log_color { std::string m_color; }; inline _Log_color setcolor(const std::string& clr) { _Log_color __x; __x.m_color = clr; return __x; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, _Log_color __f) { __os << __f.m_color << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& endcolor(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_endcolor << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& black(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_black << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& red(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_red << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& green(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_green << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& brown(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_brown << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& blue(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_blue << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& magenta(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_magenta << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& cyan(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_cyan << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& gran(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_gran << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& dark(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_dark << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& lightred(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_lightred << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& lightgreen(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_lightgreen << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& yellow(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_yellow << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& lightblue(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_lightblue << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& lightmagenta(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_lightmagenta << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& lightcyan(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_lightcyan << std::flush; return __os; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& white(std::basic_ostream<_CharT, _Traits>& __os) { __os << _Text_white << std::flush; return __os; } struct _Log_dump { const void* _M_addr; int _M_len; }; inline _Log_dump dump(const void* __addr, int __len) { _Log_dump __x; __x._M_addr = __addr; __x._M_len = __len; return __x; } template <typename _CharT, typename _Traits> inline std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, _Log_dump __f) { const std::string __table("0123456789ABCDEF"); const int __line = 32; const int __interval = 4; int __hexlen = __f._M_len * 2; // one byte == two hex character const char* __p = static_cast<const char*>(__f._M_addr); while (__hexlen > 0) { // print memory address int __count = 0; if ((__count % __line) == 0) { std::ostringstream __ostrm; __ostrm << std::setw((sizeof __p)*2) << std::setfill('0'); __ostrm << std::hex << reinterpret_cast<unsigned long>(__p); __os << white; __os << __ostrm.str() + ":"; __os << endcolor; } // print memory as hex int __min = std::min<int>(__hexlen, __line); std::string __chardump(__p, __p + __min/2); __count = 0; while (__count < __min) { if ((__count % __interval) == 0) __os << ' '; unsigned char __ch = *__p++; std::ostringstream __ostrm; __ostrm << std::setw(2) << std::setfill('0'); __ostrm << std::hex << std::noshowbase << static_cast<unsigned>(__ch); __os << __ostrm.str(); __count += 2; } __hexlen -= __min; __os << std::string(__line - __min + (__line - __min)/__interval, ' '); // print memory as character __os << yellow; __os << " "; for (std::string::size_type i = 0; i < __chardump.size(); ++i) { if (isprint(__chardump[i])) { __os << yellow; __os << __chardump[i]; } else { __os << lightmagenta; __os << '.'; } // if (!isprint(__chardump[i])) // __chardump[i] = '.'; } // __os << " " + __chardump; __os << endcolor; // newline __os << '\n'; } return __os; } } // namespace stdx #endif // __STDX_TTYCOLOR_H
#include "ServerSocket.hpp" namespace net { ServerSocket::ServerSocket(int port, bool ipv4) { m_socket = socket(ipv4 ? AF_INET : AF_INET6, SOCK_STREAM, IPPROTO_TCP); if(m_socket == -1) throw Exception(__PRETTY_FUNCTION__, "Failed to create a socket, error: " + std::string(strerror(errno))); int status; if(ipv4) { sockaddr_in local; memset(&local, 0, sizeof(local)); local.sin_addr.s_addr = INADDR_ANY; local.sin_port = htons(port); local.sin_family = AF_INET; status = ::bind(m_socket, (sockaddr*)&local, sizeof(local)); } else { sockaddr_in6 local; memset(&local, 0, sizeof(local)); local.sin6_addr = in6addr_any; local.sin6_port = htons(port); local.sin6_family = AF_INET6; status = ::bind(m_socket, (sockaddr*)&local, sizeof(local)); } if(status == -1) throw Exception(__PRETTY_FUNCTION__, "Failed to bind to local address, error: " + std::string(strerror(errno))); ::listen(m_socket, 5); } ServerSocket::~ServerSocket() { close(m_socket); } Socket* ServerSocket::accept() { sockaddr_in6 sin; socklen_t size = sizeof(sin); int socket = ::accept(m_socket, (sockaddr*)&sin, &size); if(socket == -1) throw Exception(__PRETTY_FUNCTION__, "Failed to accept connection on serversocket, error: " + std::string(strerror(errno))); return new Socket(socket); } NetAddress ServerSocket::get_local_address() const { sockaddr_in6 sin; socklen_t size = sizeof(sin); getsockname(m_socket, (sockaddr*)&sin, &size); if(sin.sin6_family == AF_INET) return NetAddress(*(sockaddr_in*)&sin); else return NetAddress(sin); } std::string ServerSocket::to_string() const { return "Serversocket listening on: " + get_local_address().to_string(); } }
#include <bits/stdc++.h> #include <stdlib.h> using namespace std; // Complete the formingMagicSquare function below. int formingMagicSquare(vector<vector<int>> s) { int cost = 46, costTmp = 0; int i, j, k, l; vector<vector<int>> matRotate = { {4, 3, 8, 9, 5, 1, 2, 7, 6}, {6, 7, 2, 1, 5, 9, 8, 3, 4}, {2, 7, 6, 9, 5, 1, 4, 3, 8}, {8, 1, 6, 3, 5, 7, 4, 9, 2}, {6, 1, 8, 7, 5, 3, 2, 9, 4}, {4, 9, 2, 3, 5, 7, 8, 1, 6}, {2, 9, 4, 7, 5, 3, 6, 1, 8}, {8, 3, 4, 1, 5, 9, 6, 7, 2} }; for (k = 0; k < 8; k++) { l = 0; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { costTmp += abs(matRotate[k][l] - s[i][j]); l++; } } cost = min(costTmp, cost); costTmp = 0; } return cost; } int main() { ofstream fout(getenv("OUTPUT_PATH")); vector<vector<int>> s(3); for (int i = 0; i < 3; i++) { s[i].resize(3); for (int j = 0; j < 3; j++) { cin >> s[i][j]; } cin.ignore(numeric_limits<streamsize>::max(), '\n'); } int result = formingMagicSquare(s); fout << result << "\n"; fout.close(); return 0; }
#include <iostream> #ifndef TABLERO_H #define TABLERO_H class Tablero{ private: char** matriz; public: Tablero(); void crearMatriz(); void imprimirMatriz(); void llenarMatriz(); bool validarPosicionMas(int,int); bool validarPosicionNumeral(int,int); bool validarPosicionMasMover(int,int, int, int); bool validarPosicionNumeralMover(int,int, int, int); void moverPiezaMas(int,int); void moverPiezaNumeral(int,int); bool validarWin(); int winner(); ~Tablero(); }; #endif
// // GActionDamage.h // Core // // Created by Max Yoon on 11. 7. 13.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #ifndef __Core__GActionDamage__ #define __Core__GActionDamage__ #include "GAction.h" #include "GAttackDamageInfo.h" class GnIProgressBar; class GActionDamage : public GAction { GnDeclareFlags(guint16); enum { MASK_PUSHDAMAGE = 0x0001, MASK_DOWNDAMGE = 0x0002, MASK_DONTMOVE = 0x0004, MASK_ENDMOTION = 0x0010, MASK_ENDEFFECTANIMATION = 0x0020, MASK_ENDPUSHPOSITION = 0x0040, MASK_ICE = 0x0100, MASK_ENABLE_SETSTARTACTION = 0x0200, }; protected: GLayer* mpActorLayer; gint mEffectIndex; Gn2DMeshObjectPtr mpsMeshObject; GAttackDamageInfo mAttackDamage; float mDownTime; float mDownAcumTime; GnTimer mPushTimer; GnVector2 mPushDownPosition; GnVector2 mPushDamagePosition; GnVector2 mPushDelta; GnVector2 mPushAcum; float mDontMoveTime; float mDontMoveAcumTime; public: GActionDamage(GActorController* pController); virtual ~ GActionDamage(); GnVector2ExtraData* CreateDamageEffect(); void SetAttackDamage(GAttackDamageInfo* pInfo); bool IsEnableDamage(); public: void Update(float fTime); void AttachActionToController(); void DetachActionToController(); inline gtint GetActionType() { return ACTION_DAMAGE; } protected: bool UpdatePush(float fTime, GnVector2& cPosition); public: inline void SetActorLayer(GLayer* pActorLayer) { mpActorLayer = pActorLayer; } inline gint GetEffectIndex() { return mEffectIndex; } inline void SetEffectIndex(gint uiIndex) { mEffectIndex = uiIndex; } inline bool IsPushDamage() { return GetBit( MASK_PUSHDAMAGE ); } inline void SetIsPushDamage(bool val) { SetBit( val, MASK_PUSHDAMAGE ); } inline bool IsDownDamage() { return GetBit( MASK_DOWNDAMGE ); } inline void SetIsDownDamage(bool val) { SetBit( val, MASK_DOWNDAMGE ); } inline bool IsDontMove() { return GetBit( MASK_DONTMOVE ); } inline bool IsIce() { return GetBit( MASK_ICE ); } inline void SetIsIce(bool val) { SetBit( val, MASK_ICE ); } inline void SetIsDontMove(bool val, bool bIce = true) { SetBit( val, MASK_DONTMOVE ); SetBit( bIce, MASK_ICE ); } inline bool IsEnableSetStartAction() { return GetBit( MASK_ENABLE_SETSTARTACTION ); } inline void SetIsEnableSetStartAction(bool val) { SetBit( val, MASK_ENABLE_SETSTARTACTION ); } inline void SetPushDelta(GnVector2 cPos) { mPushDelta = cPos; } inline void SetDontMoveTime(float val) { mDontMoveTime = val; mDontMoveAcumTime = 0.0f; } protected: inline bool IsEndMotion() { return GetBit( MASK_ENDMOTION ); } inline void SetIsEndMotion(bool val) { SetBit( val, MASK_ENDMOTION ); } inline bool IsEndEffectAnimation() { return GetBit( MASK_ENDEFFECTANIMATION ); } inline void SetIsEndEffectAnimation(bool val) { SetBit( val, MASK_ENDEFFECTANIMATION ); } inline bool IsEndPushPosition() { return GetBit( MASK_ENDPUSHPOSITION ); } inline void SetIsEndPushPosition(bool val) { SetBit( val, MASK_ENDPUSHPOSITION ); } protected: GAttackDamageInfo* GetAttackDamageInfo() { return &mAttackDamage; } protected: inline GLayer* GetActorLayer() { return mpActorLayer; } inline void RemoveMeshParent() { if( mpsMeshObject && mpsMeshObject->GetMesh()->getParent() ) GetActorLayer()->RemoveChild( mpsMeshObject ); } }; //class GnIProgressBar; //class GActionDownDamage : public GActionDamage //{ //public: // GActionDownDamage(GActorController* pController); // virtual ~GActionDownDamage(); // //public: // void Update(float fTime); // void AttachActionToController(); // //public: // inline gtint GetActionType() { // return ACTION_DOWNDAMAGE; // } // inline void DetachActionToController() { // if( mpsMeshObject && mpsMeshObject->GetMesh()->getParent() ) // GetActorLayer()->RemoveChild( mpsMeshObject ); // }; //}; #endif
#include <stdio.h> #include <stdlib.h> #define MAX 50 void printArray(int arr[], int size) { int i; for (i=0; i<size; i++) { printf("%d ", arr[i]); } printf("\n"); } void merge(int arr[], int begin, int mid, int end) { int temp[MAX]; int i, j, itemp; i = begin; j = mid + 1; itemp = begin; while ((i<=mid) && (j<=end)) { if (arr[i] < arr[j]) { temp[itemp++] = arr[i++]; } else { temp[itemp++] = arr[j++]; } } if ((i>mid)) { while (j<=end) { temp[itemp++] = arr[j++]; } } else if (j>end) { while (i<=mid) { temp[itemp++] = arr[i++]; } } //copy temp back to arr for (i=begin; i<=end; i++) arr[i] = temp[i]; } void mergeSort(int arr[], int begin, int end) { int mid; if (begin < end) { mid = (end+begin)/2; mergeSort(arr, begin, mid); mergeSort(arr, mid+1, end); merge(arr, begin, mid, end); } } int main(){ int intArr[] = {88, 34, 56, 79, 102, 534, 46, 90, 1970, 1}; printArray(intArr, 10); mergeSort(intArr, 0, 9); printf("sorting\n"); printArray(intArr, 10); }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "TankTrack.generated.h" /** * Tank Track allows movement of the tank */ UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent)) class BATTLE_TANK_API UTankTrack : public UStaticMeshComponent { GENERATED_BODY() public: // Sets throttle between -1 and 1 UFUNCTION(BlueprintCallable, Category = Input) void SetThrottle(float Throttle); protected: virtual void BeginPlay() override; virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; private: UTankTrack(); void CorrectSidewaysSlipping(float DeltaTime); /*UFUNCTION() void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit); */ UPROPERTY(EditDefaultsOnly, Category = Debug) bool bDebug = false; // Force applied on tank at maximum throttle UPROPERTY(EditDefaultsOnly, Category = Movement) float MaxTrackForce = 40000000.f; // Root component of tank UPrimitiveComponent* TankBody = nullptr; };
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "MainScene.h" #include "AppMacros.h" #include "math.h" #include "EndScene.h" #include <fstream> USING_NS_CC; #define BOX_TAG 7 #define BULLET_TAG 10 #define BARREL_TAG 8 #define PLAYER_TAG 2 #define FIREBALL_TAG 11 #define BOSS_TAG 12 #define SMALL_TAG 13 #define NOR_MONSTER_TAG 15 std::string MainScene::filename = "highest_score.txt"; Scene* MainScene::scene() { return MainScene::create(); } bool MainScene::init() { ////////////////////////////// // 1. 首先继承 if (!Scene::init()) { return false; } // 物理效果初始化用于继承 if (!Scene::initWithPhysics()) { return false; } getPhysicsWorld(); //getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); //窗口尺寸和原点 auto winSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); //设置游戏背景 auto background = Sprite::create("background.png"); if (background) { background->setPosition(Vec2(origin.x + CENTER_X, origin.y + CENTER_Y)); background->setScale(1.0f); this->addChild(background); } background->setGlobalZOrder(-1); //显示在最下层 auto frontground = Sprite::create("frontground.png"); if (frontground) { frontground->setPosition(Vec2(origin.x + CENTER_X, origin.y + CENTER_Y)); frontground->setScale(1.0f); this->addChild(frontground); } frontground->setGlobalZOrder(1); //显示在最上层 //背景音乐 auto backgroundAudioID = AudioEngine::play2d("sound/bk.mp3", true); AudioEngine::setVolume(backgroundAudioID, 0.5); //记分牌 current_score_label = Label::createWithTTF("Score:0000", "fonts/score.ttf", 24); current_score_label->setPosition(Vec2(winSize.width * 0.5-120, winSize.height*0.9)); this->addChild(current_score_label); current_level_label = Label::createWithTTF("level:0", "fonts/score.ttf", 24); current_level_label->setPosition(Vec2(winSize.width * 0.5+120, winSize.height * 0.9)); this->addChild(current_level_label); current_score_label->setGlobalZOrder(1); current_level_label->setGlobalZOrder(1); //渲染顺序的调度器 this->schedule(CC_SCHEDULE_SELECTOR(MainScene::set_z_oder)); //玩家初始化 _player = player::create("DO_02.png"); _player->setPosition(Vec2(winSize.width * 0.1, winSize.height * 0.5)); _player->init(); //玩家的物理引擎 auto physicsBody = PhysicsBody::createBox(_player->getContentSize()/3, PhysicsMaterial(0.0f, 0.0f, 0.0f)); physicsBody->setDynamic(false); physicsBody->setContactTestBitmask(0xFFFFFFFF); _player->setPhysicsBody(physicsBody); _player->setTag(PLAYER_TAG);//设立标签 this->addChild(_player); //添加进场景 //添加油漆桶,箱子和大怪物 this->addBarrel(Vec2(550, 150)); this->addBox(Vec2(300, 350)); this->addBigMonster(0); this->addSmallMonster(1); //僵尸的移动和攻击调度器和死亡 this->schedule(CC_SCHEDULE_SELECTOR(MainScene::monster_move), 3.0, -1, 0); this->schedule(CC_SCHEDULE_SELECTOR(MainScene::monster_attack), 1.0, -1, 0); this->schedule(CC_SCHEDULE_SELECTOR(MainScene::monster_death), 1.0, -1, 0); this->schedule(CC_SCHEDULE_SELECTOR(MainScene::border)); //实时更新血量 schedule(CC_SCHEDULE_SELECTOR(MainScene::scheduleBlood), 0.1f); //更新血条的显示 schedule(CC_SCHEDULE_SELECTOR(MainScene::addhp), 1.0f);//每秒钟自动回血 //人物移动调度器 schedule(CC_SCHEDULE_SELECTOR(MainScene::always_move), 0.2f); //人物一直攻击调度器 schedule(CC_SCHEDULE_SELECTOR(MainScene::always_attack_normal), 0.2f); schedule(CC_SCHEDULE_SELECTOR(MainScene::always_attack_uzi), 0.1f); //碰撞检测 // 子弹和油漆桶 auto contactListener0 = EventListenerPhysicsContact::create(); contactListener0->onContactBegin = CC_CALLBACK_1(MainScene::onContactBegin_bullet_barrel, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener0, this); //箱子和玩家 auto contactListener1 = EventListenerPhysicsContact::create(); contactListener1->onContactBegin = CC_CALLBACK_1(MainScene::onContactBegin_player_box, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener1, this); //火球和人物 auto contactListener2 = EventListenerPhysicsContact::create(); contactListener2->onContactBegin = CC_CALLBACK_1(MainScene::onContactBegin_player_fireball, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener2, this); //子弹和僵尸 auto contactListener3 = EventListenerPhysicsContact::create(); contactListener3->onContactBegin = CC_CALLBACK_1(MainScene::onContactBegin_bullet_monster, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener3, this); // 键盘回调事件 auto listener = EventListenerKeyboard::create(); listener->onKeyPressed = CC_CALLBACK_2(MainScene::onKeyPressed, this); listener->onKeyReleased = CC_CALLBACK_2(MainScene::onKeyReleased, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true; } //用于控制人物移动、攻击、换枪的按键回调函数 bool MainScene::onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode,cocos2d::Event* event) { //keyboard callbackfunction to controll the player log("Key with keycode %d pressed", keyCode); //控制人物移动 if (keyCode == EventKeyboard::KeyCode::KEY_W || keyCode== EventKeyboard::KeyCode::KEY_A || keyCode == EventKeyboard::KeyCode::KEY_S || keyCode == EventKeyboard::KeyCode::KEY_D) { _player->player_move(keyCode); } if (keyCode == EventKeyboard::KeyCode::KEY_J) { judge_and_attack(); } if (keyCode == EventKeyboard::KeyCode::KEY_U) { _player->player_invincible(); } keys[keyCode] = true; if (keyCode == EventKeyboard::KeyCode::KEY_1 || keyCode == EventKeyboard::KeyCode::KEY_2 || keyCode == EventKeyboard::KeyCode::KEY_3 || keyCode == EventKeyboard::KeyCode::KEY_4) { bool success_change; switch (keyCode) { case cocos2d::EventKeyboard::KeyCode::KEY_1: success_change=_player->change_weapon(0); break; case cocos2d::EventKeyboard::KeyCode::KEY_2: success_change = _player->change_weapon(1); break; case cocos2d::EventKeyboard::KeyCode::KEY_3: success_change = _player->change_weapon(2); break; default: success_change = _player->change_weapon(3); break; } if (success_change) { change_weapon_animation((_player->get_weapon_attribute()).weapon_name); auto soundchange_weapon = AudioEngine::play2d("sound/change_weapon.mp3", false); } } return true; } void MainScene::judge_and_attack() { if (!(_player->invincible)) { //当前武器子弹耗尽 if (_player->Is_out_of_bullet()) { change_weapon_animation((_player->get_weapon_attribute()).weapon_name, true); return; } } //武器声音 auto gun_name = (_player->get_weapon_attribute()).weapon_name; attack_sound(gun_name); //当前武器为油漆桶 if ((_player->get_weapon_attribute()).weapon_name == "barrel") { int tmp_barrel_distance = 100; Vec2 shootAmount; switch (_player->get_direction()) { case player::UP: shootAmount = Vec2(0, tmp_barrel_distance); break; case player::DOWN: shootAmount = Vec2(0, -tmp_barrel_distance); break; case player::LEFT: shootAmount = Vec2(-tmp_barrel_distance, 0); break; case player::RIGHT: shootAmount = Vec2(tmp_barrel_distance, 0); break; } addBarrel(_player->getPosition() + shootAmount); if (!(_player->invincible)) { _player->decrease_weapon_num(); } _player->renew_display_num(); return; } else _player->player_attack(); } bool MainScene::onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event) { keys[keyCode] = false; return true; } void MainScene::always_move(float delta) {//用于长时间按的调度函数 EventKeyboard::KeyCode keyCode= EventKeyboard::KeyCode::KEY_P; if (keys[EventKeyboard::KeyCode::KEY_W]) keyCode = EventKeyboard::KeyCode::KEY_W; else if (keys[EventKeyboard::KeyCode::KEY_A]) keyCode = EventKeyboard::KeyCode::KEY_A; else if (keys[EventKeyboard::KeyCode::KEY_S]) keyCode = EventKeyboard::KeyCode::KEY_S; else if (keys[EventKeyboard::KeyCode::KEY_D]) keyCode = EventKeyboard::KeyCode::KEY_D; if (keyCode == EventKeyboard::KeyCode::KEY_W || keyCode == EventKeyboard::KeyCode::KEY_A || keyCode == EventKeyboard::KeyCode::KEY_S || keyCode == EventKeyboard::KeyCode::KEY_D) { _player->player_move(keyCode); } } //换枪的动画 void MainScene::change_weapon_animation(const std::string& weapon_name,bool out_of_bullet) { auto change_label = cocos2d::Label::createWithSystemFont("change:"+weapon_name, "Arial", 20); if (out_of_bullet) change_label->setString("Out of " + weapon_name); change_label->setColor(Color3B::BLACK); change_label->setPosition(Vec2(512,0)); this->addChild(change_label); auto actionMove = MoveBy::create(0.3f , Vec2(0,100)); auto actionRemove = RemoveSelf::create(); change_label->runAction(Sequence::create(actionMove, actionRemove, nullptr)); } //血条显示更新 void MainScene::scheduleBlood(float delta) { auto progress = (ProgressTimer*)_player->getChildByTag(1); progress->setPercentage((((float)(_player->get_hp())) / 100) * 100); //这里是百分制显示 if (progress->getPercentage() < 0) { this->unschedule(CC_SCHEDULE_SELECTOR(MainScene::scheduleBlood)); } } void MainScene::addBox(const cocos2d::Vec2& pos) { auto Box = Sprite::create("box.png"); // Add Box auto BoxContentSize = Box->getContentSize(); Box->setPosition(pos); // Add Box's physicsBody auto physicsBody = PhysicsBody::createBox(Box->getContentSize()/2, PhysicsMaterial(0.0f, 0.0f, 0.0f)); physicsBody->setDynamic(false); physicsBody->setContactTestBitmask(0xFFFFFFFF); Box->setPhysicsBody(physicsBody); Box->setTag(BOX_TAG); // Add Box's physicsBody this->addChild(Box); } void MainScene::addBarrel(const cocos2d::Vec2& s) { auto Barrel = Sprite::create("barrel.png"); // Add Barrel auto BarrelContentSize = Barrel->getContentSize(); Barrel->setPosition(s); { auto x = Barrel->getPositionX(); auto y = Barrel->getPositionY(); if (x < 10) x = 10; if (x > 1014) x = 1014; if (y < 10) y = 10; if (y > 700) y = 700; Barrel->setPosition(Vec2(x, y)); } // Add Barrel's physicsBody auto physicsBody = PhysicsBody::createBox(Barrel->getContentSize()/2, PhysicsMaterial(0.0f, 0.0f, 0.0f)); physicsBody->setDynamic(false); physicsBody->setContactTestBitmask(0xFFFFFFFF); Barrel->setPhysicsBody(physicsBody); Barrel->setTag(BARREL_TAG); // Add Barrel's physicsBody this->addChild(Barrel); } void MainScene::addhp(float delta) { _player->add_hp_timely(); } void MainScene::menuCloseCallback(Ref* sender) { Director::getInstance()->end(); } int MainScene::read_highest_score_from_file() { std::ifstream file(filename); try{ std::string line; std::getline(file, line); file.close(); return std::stoi(line); } catch (...) { throw "unable to read highest score from file"; file.close(); } } void MainScene::save_highest_score() { try { // Warning: unclosed file handler int score_from_file = read_highest_score_from_file(); if (score > score_from_file) { std::ofstream ofile(filename, std::ios::trunc); ofile << score; ofile.close(); } } catch (...) { std::ofstream ofile(filename, std::ios::trunc); ofile << score; ofile.close(); } } bool MainScene::onContactBegin_bullet_barrel(cocos2d::PhysicsContact& contact) { try { auto nodeA = contact.getShapeA()->getBody()->getNode(); auto nodeB = contact.getShapeB()->getBody()->getNode(); Vec2 position_tmp; bool c = false; if (nodeA && nodeB) { if (nodeA->getTag() == BARREL_TAG && nodeB->getTag() == BULLET_TAG) { c = true; position_tmp = nodeA->getPosition(); if (abs(_player->getPosition().x - position_tmp.x) + abs(_player->getPosition().y - position_tmp.y) < 500) { _player->decrease_hp_barrel(); } for (auto k : _BigMonster) { if (abs(k->getPosition().x - position_tmp.x) + abs(k->getPosition().y - position_tmp.y) < 100) { k->under_attack(position_tmp - k->getPosition(), 50); } } for (auto k : _SmallMonster) { if (abs(k->getPosition().x - position_tmp.x) + abs(k->getPosition().y - position_tmp.y) < 100) { k->under_attack(position_tmp - k->getPosition(), 50); } } nodeA->removeFromParentAndCleanup(true); nodeB->removeFromParentAndCleanup(true); } else if (nodeB->getTag() == BARREL_TAG && nodeA->getTag() == BULLET_TAG) { c = true; position_tmp = nodeB->getPosition(); if (abs(_player->getPosition().x - position_tmp.x) + abs(_player->getPosition().y - position_tmp.y) < 200) { _player->decrease_hp_barrel(); } for (auto k : _BigMonster) { if (abs(k->getPosition().x - position_tmp.x) + abs(k->getPosition().y - position_tmp.y) < 200) { k->under_attack(position_tmp - k->getPosition(), 50); } } for (auto k : _SmallMonster) { if (abs(k->getPosition().x - position_tmp.x) + abs(k->getPosition().y - position_tmp.y) < 200) { k->under_attack(position_tmp - k->getPosition(), 50); } } nodeA->removeFromParentAndCleanup(true); nodeB->removeFromParentAndCleanup(true); } } if (c) { auto sound_boom = AudioEngine::play2d("sound/boom.mp3", false); auto boom = Sprite::create("boom0.png"); boom->setPosition(position_tmp); this->addChild(boom); auto fade = cocos2d::FadeTo::create(1, 0); auto actionRemove = RemoveSelf::create(); boom->runAction(Sequence::create(fade, actionRemove, nullptr)); } return true; } catch (...) { ; } } bool MainScene::onContactBegin_player_fireball(cocos2d::PhysicsContact& contact){ try { auto nodeA = contact.getShapeA()->getBody()->getNode(); auto nodeB = contact.getShapeB()->getBody()->getNode(); bool contact_flag = false; Vec2 position_tmp1; Vec2 pos1, pos2, diff; if (nodeA && nodeB) { if (nodeA->getTag() == FIREBALL_TAG && nodeB->getTag() == PLAYER_TAG) { position_tmp1 = nodeA->getPosition(); Node* parent = nodeA->getParent(); if (!parent) { throw "Too many fireballs in the scene; multiple fireballs contacted player"; } pos1 = parent->convertToWorldSpace(position_tmp1); pos2 = nodeB->getPosition(); nodeA->removeFromParentAndCleanup(true); contact_flag = true; } else if (nodeB->getTag() == FIREBALL_TAG && nodeA->getTag() == PLAYER_TAG) { position_tmp1 = nodeB->getPosition(); Node* parent = nodeB->getParent(); if (!parent) { throw "Too many fireballs in the scene; multiple fireballs contacted player"; } pos1 = parent->convertToWorldSpace(position_tmp1); pos2 = nodeA->getPosition(); nodeB->removeFromParentAndCleanup(true); contact_flag = true; } } if (contact_flag) { diff = pos1 - pos2; int dir = getdirection(diff); //0->上方 1->下 2->左 3->右 _player->Is_under_attack(dir); if (_player->hp < 0) { save_highest_score(); auto soundEffectID = AudioEngine::play2d("sound/enter_game.mp3", false); Director::getInstance()->replaceScene(TransitionSlideInT::create(0.5f, End::scene())); } } return true; } catch (...) { return true; } } //子弹 僵尸 bool MainScene::onContactBegin_bullet_monster(cocos2d::PhysicsContact& contact){ try { auto nodeA = contact.getShapeA()->getBody()->getNode(); auto nodeB = contact.getShapeB()->getBody()->getNode(); BigMonster* a = nullptr; SmallMonster* b = nullptr; bool contact_flag = false; bool contact_flag2 = false; Vec2 pos1, pos2, diff; if (nodeA && nodeB) { if (nodeA->getTag() == BOSS_TAG && nodeB->getTag() == BULLET_TAG) { a = (BigMonster*)nodeA; pos1 = nodeA->getPosition(); pos2 = nodeB->getPosition(); Node* parent = nodeB->getParent(); if (!parent) { throw "Too many bullets in the scene; multiple zombies contacted bullet"; } pos2 = parent->convertToWorldSpace(pos2); if (a->hp > 0) nodeB->removeFromParentAndCleanup(true); contact_flag = true; } else if (nodeB->getTag() == BOSS_TAG && nodeA->getTag() == BULLET_TAG) { a = (BigMonster*)nodeB; pos2 = nodeA->getPosition(); Node* parent = nodeA->getParent(); if (!parent) { throw "Too many fireballs in the scene; multiple fireballs contacted player"; } pos2 = parent->convertToWorldSpace(pos2); pos1 = nodeB->getPosition(); if (a->hp > 0) nodeA->removeFromParentAndCleanup(true); contact_flag = true; } else if (nodeA->getTag() == SMALL_TAG && nodeB->getTag() == BULLET_TAG) { b = (SmallMonster*)nodeA; pos1 = nodeA->getPosition(); pos2 = nodeB->getPosition(); Node* parent = nodeB->getParent(); if (!parent) { throw "Too many bullets in the scene; multiple zombies contacted bullet"; } pos2 = parent->convertToWorldSpace(pos2); if (b->hp > 0) nodeB->removeFromParentAndCleanup(true); contact_flag2 = true; } else if (nodeB->getTag() == SMALL_TAG && nodeA->getTag() == BULLET_TAG) { b = (SmallMonster*)nodeB; pos2 = nodeA->getPosition(); Node* parent = nodeA->getParent(); if (!parent) { throw "Too many bullets in the scene; multiple zombies contacted bullet"; } pos2 = parent->convertToWorldSpace(pos2); pos1 = nodeB->getPosition(); if (b->hp > 0) nodeA->removeFromParentAndCleanup(true); contact_flag2 = true; } } if (contact_flag) { diff = pos1 - pos2; if (a->hp > 0) a->under_attack(diff, _player->get_weapon_attribute().Damage / 5 * 20); } if (contact_flag2) { diff = pos1 - pos2; if (b->hp > 0) b->under_attack(diff, _player->get_weapon_attribute().Damage / 5 * 20); } return true; } catch (...) { return true; } } bool MainScene::onContactBegin_player_box(cocos2d::PhysicsContact& contact) { auto nodeA = contact.getShapeA()->getBody()->getNode(); auto nodeB = contact.getShapeB()->getBody()->getNode(); bool contact_flag = false; if (nodeA && nodeB) { if (nodeA->getTag() == BOX_TAG && nodeB->getTag() ==PLAYER_TAG) { auto position_tmp = nodeA->getPosition(); nodeA->removeFromParentAndCleanup(true); contact_flag = true; } else if (nodeB->getTag() == BOX_TAG && nodeA->getTag() == PLAYER_TAG) { auto position_tmp = nodeB->getPosition(); nodeB->removeFromParentAndCleanup(true); contact_flag = true; } } if (contact_flag) { auto sound_box = AudioEngine::play2d("sound/change_weapon.mp3", false); _player->add_bullet(); _player->renew_display_num(); } return true; } //添加boss僵尸的方法 birthpoint: 0->上 1->下 2->左 3->右 void MainScene::addBigMonster(int birth_point) { auto boss = BigMonster::create("Boss_DO_01.png"); //物理引擎 auto physicsBody = PhysicsBody::createBox(boss->getContentSize() / 3, PhysicsMaterial(0.0f, 0.0f, 0.0f)); physicsBody->setDynamic(false); physicsBody->setContactTestBitmask(0xFFFFFFFF); boss->setPhysicsBody(physicsBody); boss->setTag(BOSS_TAG); _BigMonster.push_back(boss); //随机波动 std::random_device rd; auto eng = std::default_random_engine{ rd() }; auto dis = std::uniform_int_distribution<>{ -40,40 }; auto rand = Vec2{ (float)dis(eng),(float)dis(eng) }; //根据出生地选择初始的位置 768*1024 switch (birth_point) { case 0: { boss->setPosition(Vec2(512, 786) + rand); break; } case 1: { boss->setPosition(Vec2(512, 0) + rand); break; } case 2: { boss->setPosition(Vec2(0, 393) + rand); break; } case 3: { boss->setPosition(Vec2(1024, 393) + rand); break; } default: { boss->setPosition(Vec2(300, 300) + rand); break; } } this->addChild(boss); } void MainScene::addSmallMonster(int birth_point){ auto boss = SmallMonster::create("0_01.png"); //物理引擎 auto physicsBody = PhysicsBody::createBox(boss->getContentSize() / 3, PhysicsMaterial(0.0f, 0.0f, 0.0f)); physicsBody->setDynamic(false); physicsBody->setContactTestBitmask(0xFFFFFFFF); boss->setPhysicsBody(physicsBody); boss->setTag(SMALL_TAG); _SmallMonster.push_back(boss); //随机波动 std::random_device rd; auto eng = std::default_random_engine{ rd() }; auto dis = std::uniform_int_distribution<>{ -40,40 }; auto rand = Vec2{ (float)dis(eng),(float)dis(eng) }; //根据出生地选择初始的位置 768*1024 switch (birth_point) { case 0: { boss->setPosition(Vec2(512, 786)+rand); break; } case 1: { boss->setPosition(Vec2(512, 0) + rand); break; } case 2: { boss->setPosition(Vec2(0, 393) + rand); break; } case 3: { boss->setPosition(Vec2(1024, 393) + rand); break; } default: { boss->setPosition(Vec2(300, 300) + rand); break; } } this->addChild(boss); } //对所有项目进行渲染顺序的调整,解决覆盖问题,用于调度器 void MainScene::set_z_oder(float dt){ //_player->setLocalZOrder(get_z_odre(_player)); auto all_children = getChildren(); for (auto k : all_children) { k->setLocalZOrder(get_z_odre(k)); } } int MainScene::get_z_odre(cocos2d::Node* spr){ auto p = spr->getPosition(); int ry = 800*1024 - p.y*1024; int x = p.x; return ry+x; } //僵尸移动的调度器 void MainScene::monster_move(float dt) { auto destination = _player->getPosition(); for (auto k : _BigMonster) { if (k->hp > 0) { auto source = k->getPosition(); auto diff = destination - source; if (fabs(diff.x) > 200 || fabs(diff.y) > 200) { auto direction = getdirection(diff); k->move(direction); } } } for (auto k : _SmallMonster) { if (k->hp > 0) { auto source = k->getPosition(); auto diff = destination - source; if (fabs(diff.x) > 100 || fabs(diff.y) > 100) { auto direction = getdirection(diff); k->move(direction); } } } } //僵尸攻击的调度器 void MainScene::monster_attack(float dt) { auto destination = _player->getPosition(); for (auto k : _BigMonster) { if (k->hp > 0) { auto source = k->getPosition(); auto diff = destination - source; if (fabs(diff.x) <= 200 && fabs(diff.y) <= 200) { auto direction = getdirection(diff); k->attack(diff); } } } for (auto k : _SmallMonster) { if (k->hp > 0) { auto source = k->getPosition(); auto diff = destination - source; if (fabs(diff.x) <= 100 && fabs(diff.y) <= 100) { auto direction = getdirection(diff); k->attack(diff); } } } } //僵尸死亡调度器 void MainScene::monster_death(float dt){ bool Is_level_up = true; for (auto k : _BigMonster) { if (k->hp <= 0) { k->death(); score += 1000; current_score_label->setString("Score:" + std::to_string(score)); } else Is_level_up = false; } _BigMonster.erase(remove_if(_BigMonster.begin(), _BigMonster.end(), [](BigMonster* x) { return (x->hp <= 0); }), _BigMonster.end()); for (auto k : _SmallMonster) { if (k->hp <= 0) { k->death(); score += 100; current_score_label->setString("Score:" + std::to_string(score)); } else Is_level_up = false; } _SmallMonster.erase(remove_if(_SmallMonster.begin(), _SmallMonster.end(), [](SmallMonster* x) { return (x->getOpacity() <= 0); }), _SmallMonster.end()); if (Is_level_up) level_up(); } void MainScene::border(float dt){ { auto x = _player->getPositionX(); auto y = _player->getPositionY(); if (x < 10) x = 10; if (x > 1014) x = 1014; if (y < 10) y = 10; if (y > 700) y = 700; _player->setPosition(Vec2(x, y)); } for (auto k : _BigMonster) { auto x = k->getPositionX(); auto y = k->getPositionY(); if (x < 10) x = 10; if (x > 1014) x = 1014; if (y < 10) y = 10; if (y > 700) y = 700; k->setPosition(Vec2(x, y)); } for (auto k : _SmallMonster) { auto x = k->getPositionX(); auto y = k->getPositionY(); if (x < 10) x = 10; if (x > 1014) x = 1014; if (y < 10) y = 10; if (y > 700) y = 700; k->setPosition(Vec2(x, y)); } } void MainScene::level_up() { //进游戏音效 auto sound_level_up = AudioEngine::play2d("sound/enter_game.mp3", false); current_level++; auto a = _SmallMonster.size(); current_level_label->setString("level:" + std::to_string(current_level)); for (int i = 0; i < 10 * current_level; i++) { addSmallMonster(i % 4); } for (int i = 0; i < current_level; i++) { addBigMonster(i % 4); } auto winSize = Director::getInstance()->getVisibleSize(); std::random_device rd_x; auto eng_x = std::default_random_engine{ rd_x() }; auto dis_x = std::uniform_int_distribution<>{10 ,1014 }; std::random_device rd_y; auto eng_y = std::default_random_engine{ rd_y() }; auto dis_y = std::uniform_int_distribution<>{ 10 ,700 }; for (int i = 0; i < current_level; i++) { int rand_x = dis_x(eng_x); int rand_y = dis_y(eng_y); addBox(Vec2(rand_x, rand_y)); } for (int i = 0; i < current_level; i++) { int rand_x = dis_x(eng_x); int rand_y = dis_y(eng_y); addBarrel(Vec2(rand_x, rand_y)); } } void MainScene::always_attack_normal(float delta) { if (_player->get_weapon_attribute().weapon_name != "uzi") { if (keys[EventKeyboard::KeyCode::KEY_J]) { judge_and_attack(); } } } void MainScene::always_attack_uzi(float delta) { if (_player->get_weapon_attribute().weapon_name == "uzi") { if (keys[EventKeyboard::KeyCode::KEY_J]) { judge_and_attack(); } } } void attack_sound(std::string gun_name) { if (gun_name == "pistol") auto sound_pistol = AudioEngine::play2d("sound/pistol.mp3", false); else if (gun_name == "UZI") auto sound_pistol = AudioEngine::play2d("sound/uzi.mp3", false); else if (gun_name == "shotgun") auto sound_pistol = AudioEngine::play2d("sound/shotgun.mp3", false); else if (gun_name == "barrel") auto sound_pistol = AudioEngine::play2d("sound/add_barrel.mp3", false); }
#include "predict_update.h" #include "particle.h" #include "compute_steering.h" #include "predict_true.h" #include "add_control_noise.h" #include "predict.h" #include "configfile.h" #include "pi_to_pi.h" #include "trigonometry.h" #include <math.h> #include "tscheb_sine.h" #include "linalg.h" void predict_update(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { #ifdef __AVX2__ predict_update_fast(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles); #else #warning "Using predict_update_base because AVX2 is not supported!" predict_update_base(wp, N_waypoints, V, Q, dt, N, xtrue, iwp, G, particles); #endif } //! --------------- !// //! --- VP BASE --- !// //! --------------- !// void predict_VP(Vector3d state, double V_, double G_, double *Q, double WB, double dt, bool add_control_noise) { V_ = V_/(1.0-tan(G_) *0.76/2.83); if (add_control_noise) { double VG[2] = {V_,G_}; double VnGn[2]; multivariate_gauss_base(VG,Q,VnGn); V_=VnGn[0]; G_=VnGn[1]; } double a=3.78; double b=0.5; state[0]+= V_*dt*cos(state[2]) - V_ /WB *tan(G_) * dt* (a*sin(state[2]) + b * cos(state[2])); state[1]+= V_*dt*sin(state[2]) + V_ /WB *tan(G_) * dt* (a*cos(state[2]) - b * sin(state[2])); state[2] = pi_to_pi_base(state[2] + V_*dt*tan(G_)/WB); } void predict_update_VP_base(double* controls, size_t N_controls, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { predict_VP(xtrue,V,*G, Q, WHEELBASE, dt, false); double VnGn[2]; add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO for (size_t i = 0; i < N; i++) { predict_VP(particles[i].xv, VnGn[0], VnGn[1], Q, WHEELBASE, dt,SWITCH_PREDICT_NOISE); } } //! --------------- !// //! -- VP ACTIVE -- !// //! --------------- !// void predict_VP_active(Vector3d state, double V_, double G_, double *S, double WB, double dt, bool add_control_noise) { V_ = V_ / ( 1.0 - tan(G_)*0.76/2.83 ); if (add_control_noise) { double X[2]; fill_rand(X, 2, -1.0, 1.0); double VnGn[2] = {V_, G_}; mvadd_2x2(S, X, VnGn); V_ = VnGn[0]; G_ = VnGn[1]; } double a = 3.78; double b = 0.5; const double V_dt = V_*dt; const double alpha = V_dt * tan(G_) / WB; const double cos2 = cos(state[2]); const double sin2 = sin(state[2]); const double alpha_a = alpha*a; const double alpha_b = alpha*b; const double beta = V_dt - alpha_b; state[0] += beta*cos2 - alpha_a*sin2; state[1] += beta*sin2 + alpha_a*cos2; state[2] = pi_to_pi_active(state[2] + alpha); } void predict_VP_unrolledx4_active(Vector3d state0, Vector3d state1, Vector3d state2, Vector3d state3, double V_, double G_, double *S, double WB, double dt, bool add_control_noise) { double V0_ = V_; double V1_ = V_; double V2_ = V_; double V3_ = V_; double G0_ = G_; double G1_ = G_; double G2_ = G_; double G3_ = G_; if (add_control_noise) { double VnGn01[4] = {V_, G_, V_, G_}; double VnGn23[4] = {V_, G_, V_, G_}; double X01[4], X23[4]; fill_rand(X01, 4, -1.0, 1.0); fill_rand(X23, 4, -1.0, 1.0); double ST[4] = { }; transpose_2x2(S, ST); mmadd_2x2(X01, ST, VnGn01); // S transpose mmadd_2x2(X23, ST, VnGn23); // S transpose V0_ = VnGn01[0]; G0_ = VnGn01[1]; V1_ = VnGn01[2]; G1_ = VnGn01[3]; V2_ = VnGn23[0]; G2_ = VnGn23[1]; V3_ = VnGn23[2]; G3_ = VnGn23[3]; } const double a = 3.78; const double b = 0.5; const double V0_dt = V0_*dt; const double V1_dt = V1_*dt; const double V2_dt = V2_*dt; const double V3_dt = V3_*dt; const double alpha0 = V0_dt * tan( G0_ ) / WB; const double alpha1 = V1_dt * tan( G1_ ) / WB; const double alpha2 = V2_dt * tan( G2_ ) / WB; const double alpha3 = V3_dt * tan( G3_ ) / WB; const double cos02 = cos( state0[2] ); const double cos12 = cos( state1[2] ); const double cos22 = cos( state2[2] ); const double cos32 = cos( state3[2] ); const double sin02 = sin( state0[2] ); const double sin12 = sin( state1[2] ); const double sin22 = sin( state2[2] ); const double sin32 = sin( state3[2] ); const double alpha0_a = alpha0*a; const double alpha1_a = alpha1*a; const double alpha2_a = alpha2*a; const double alpha3_a = alpha3*a; const double alpha0_b = alpha0*b; const double alpha1_b = alpha1*b; const double alpha2_b = alpha2*b; const double alpha3_b = alpha3*b; const double beta0 = V0_dt - alpha0_b; const double beta1 = V1_dt - alpha1_b; const double beta2 = V2_dt - alpha2_b; const double beta3 = V3_dt - alpha3_b; state0[0] += beta0*cos02 - alpha0_a*sin02; state1[0] += beta1*cos12 - alpha1_a*sin12; state2[0] += beta2*cos22 - alpha2_a*sin22; state3[0] += beta3*cos32 - alpha3_a*sin32; state0[1] += beta0*sin02 + alpha0_a*cos02; state1[1] += beta1*sin12 + alpha1_a*cos12; state2[1] += beta2*sin22 + alpha2_a*cos22; state3[1] += beta3*sin32 + alpha3_a*cos32; state0[2] = pi_to_pi_active(state0[2] + alpha0); state1[2] = pi_to_pi_active(state1[2] + alpha1); state2[2] = pi_to_pi_active(state2[2] + alpha2); state3[2] = pi_to_pi_active(state3[2] + alpha3); } void predict_VP_unrolledx4_active_avx(Vector3d state0, Vector3d state1, Vector3d state2, Vector3d state3, double V_, double G_, double *S, double WB, double dt, bool add_control_noise) { double const a = 3.78; double const b = 0.5; __m256d const as = _mm256_set1_pd( a ); __m256d const bs = _mm256_set1_pd( b ); __m256d const dts = _mm256_set1_pd( dt ); __m256d const Ss = _mm256_load_pd( S ); __m256d const invWB = _mm256_set1_pd( 1.0 / WB ); __m256d Vs = _mm256_set1_pd( V_ ); __m256d Gs = _mm256_set1_pd( G_ ); __m256d state_0 = _mm256_set_pd( state3[0], state2[0], state1[0], state0[0] ); __m256d state_1 = _mm256_set_pd( state3[1], state2[1], state1[1], state0[1] ); __m256d state_2 = _mm256_set_pd( state3[2], state2[2], state1[2], state0[2] ); if (add_control_noise) { __m256d const VnGn = _mm256_set_pd(G_, V_, G_, V_); double X02[4] __attribute__ ((aligned(32))); double X13[4] __attribute__ ((aligned(32))); fill_rand(X02+0, 2, -1.0, 1.0); fill_rand(X13+0, 2, -1.0, 1.0); fill_rand(X02+2, 2, -1.0, 1.0); fill_rand(X13+2, 2, -1.0, 1.0); __m256d const x02 = _mm256_load_pd( X02 ); __m256d const x13 = _mm256_load_pd( X13 ); // __m256d const x02 = fill_rand_avx(-1.0, 1.0); // __m256d const x13 = fill_rand_avx(-1.0, 1.0); __m256d const VnGn02 = _mmTadd_2x2_avx_v2(x02, Ss, VnGn); __m256d const VnGn13 = _mmTadd_2x2_avx_v2(x13, Ss, VnGn); Vs = _mm256_shuffle_pd(VnGn02, VnGn13, 0b0000); Gs = _mm256_shuffle_pd(VnGn02, VnGn13, 0b1111); } __m256d const Vsdt = _mm256_mul_pd(Vs, dts); __m256d const sinGs = tscheb_sin_avx( Gs ); __m256d const cosGs = tscheb_cos_avx( Gs ); __m256d const tanGs = _mm256_div_pd( sinGs, cosGs ); __m256d const alpha = _mm256_mul_pd( _mm256_mul_pd( Vsdt, tanGs ), invWB ); __m256d const sin_state_2 = tscheb_sin_avx( state_2 ); __m256d const cos_state_2 = tscheb_cos_avx( state_2 ); __m256d const alpha_a = _mm256_mul_pd(alpha, as); __m256d const alpha_b = _mm256_mul_pd(alpha, bs); __m256d const beta = _mm256_sub_pd(Vsdt, alpha_b); state_0 = _mm256_fmadd_pd(beta, cos_state_2, state_0); state_0 = _mm256_sub_pd( state_0, _mm256_mul_pd(alpha_a, sin_state_2)); state_1 = _mm256_fmadd_pd(beta, sin_state_2, state_1); state_1 = _mm256_fmadd_pd(alpha_a, cos_state_2, state_1); state_2 = simple_pi_to_pi_avx(_mm256_add_pd(state_2, alpha)); __m256d state_3 = _mm256_setzero_pd(); // dummy __m256d t0, t1, t2, t3; register_transpose(state_0, state_1, state_2, state_3, &t0, &t1, &t2, &t3); __m256i mask = _mm256_set_epi64x(+1, -1, -1, -1); // store only the first 3 _mm256_maskstore_pd(state0, mask, t0); _mm256_maskstore_pd(state1, mask, t1); _mm256_maskstore_pd(state2, mask, t2); _mm256_maskstore_pd(state3, mask, t3); } // __m256d tscheb_sin_avx(__m256d alphas) // __m256d tscheb_cos_avx(__m256d alphas) void predict_update_VP_active(double* controls, size_t N_controls, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { double S[4] __attribute__((aligned(32))) = {}; llt_2x2(Q, S); predict_VP_active(xtrue, V, *G, S, WHEELBASE, dt, false); // Pass Cholesky factor S instead of Q double VnGn[2]; add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); double const a = 3.78; double const b = 0.5; __m256d const as = _mm256_set1_pd( a ); __m256d const bs = _mm256_set1_pd( b ); __m256d const dts = _mm256_set1_pd( dt ); __m256d const Ss = _mm256_load_pd( S ); __m256d const invWB = _mm256_set1_pd( 1.0 / WHEELBASE); VnGn[0] = VnGn[0] / ( 1.0 - tan( VnGn[1] )*0.76/2.83 ); // predict_VP_unrolledx4 takes as input the transformed VnGn[0] ( reuse ) __m256d Vs = _mm256_set1_pd( VnGn[0] ); __m256d Gs = _mm256_set1_pd( VnGn[1] ); __m256d const VnGnv = _mm256_set_pd(VnGn[1], VnGn[0], VnGn[1], VnGn[0]); __m256d state_3 = _mm256_setzero_pd(); // dummy __m256i mask = _mm256_set_epi64x(+1, -1, -1, -1); // store only the first 3 for (size_t i = 0; i < N; i+=4) { //predict_VP_unrolledx4_active_avx(particles[i+0].xv, // particles[i+1].xv, // particles[i+2].xv, // particles[i+3].xv, // VnGn[0], VnGn[1], S, // Pass Cholesky factor S instead of Q for reuse // WHEELBASE, dt, SWITCH_PREDICT_NOISE); // Load transposed states //__m256i mask = _mm256_set_epi64x(+1, -1, -1, -1); // store only the first 3 //__m256d p0 = _mm256_maskload_pd(particles[i+0].xv, mask); //__m256d p1 = _mm256_maskload_pd(particles[i+1].xv, mask); //__m256d p2 = _mm256_maskload_pd(particles[i+2].xv, mask); //__m256d p3 = _mm256_maskload_pd(particles[i+3].xv, mask); //__m256d state_0, state_1, state_2, state_3; //register_transpose(p0, p1, p2, p3, &state_0, &state_1, &state_2, &state_3); __m256d state_0 = _mm256_set_pd( particles[i+3].xv[0], particles[i+2].xv[0], particles[i+1].xv[0], particles[i+0].xv[0] ); __m256d state_1 = _mm256_set_pd( particles[i+3].xv[1], particles[i+2].xv[1], particles[i+1].xv[1], particles[i+0].xv[1] ); __m256d state_2 = _mm256_set_pd( particles[i+3].xv[2], particles[i+2].xv[2], particles[i+1].xv[2], particles[i+0].xv[2] ); if (add_control_noise) { //double X02[4] __attribute__ ((aligned(32))); //double X13[4] __attribute__ ((aligned(32))); //fill_rand(X02+0, 2, -1.0, 1.0); //fill_rand(X13+0, 2, -1.0, 1.0); //fill_rand(X02+2, 2, -1.0, 1.0); //fill_rand(X13+2, 2, -1.0, 1.0); //__m256d const x02 = _mm256_load_pd( X02 ); //__m256d const x13 = _mm256_load_pd( X13 ); __m256d const x02 = fill_rand_avx(-1.0, 1.0); __m256d const x13 = fill_rand_avx(-1.0, 1.0); __m256d const VnGn02 = _mmTadd_2x2_avx_v2(x02, Ss, VnGnv); __m256d const VnGn13 = _mmTadd_2x2_avx_v2(x13, Ss, VnGnv); Vs = _mm256_shuffle_pd(VnGn02, VnGn13, 0b0000); Gs = _mm256_shuffle_pd(VnGn02, VnGn13, 0b1111); } __m256d const Vsdt = _mm256_mul_pd(Vs, dts); __m256d const sinGs = tscheb_sin_avx( Gs ); __m256d const cosGs = tscheb_cos_avx( Gs ); __m256d const tanGs = _mm256_div_pd( sinGs, cosGs ); __m256d const alpha = _mm256_mul_pd( _mm256_mul_pd( Vsdt, tanGs ), invWB ); __m256d const sin_state_2 = tscheb_sin_avx( state_2 ); __m256d const cos_state_2 = tscheb_cos_avx( state_2 ); __m256d const alpha_a = _mm256_mul_pd(alpha, as); __m256d const alpha_b = _mm256_mul_pd(alpha, bs); __m256d const beta = _mm256_sub_pd(Vsdt, alpha_b); state_0 = _mm256_fmadd_pd(beta, cos_state_2, state_0); state_0 = _mm256_sub_pd( state_0, _mm256_mul_pd(alpha_a, sin_state_2)); state_1 = _mm256_fmadd_pd(beta, sin_state_2, state_1); state_1 = _mm256_fmadd_pd(alpha_a, cos_state_2, state_1); state_2 = simple_pi_to_pi_avx(_mm256_add_pd(state_2, alpha)); //__m256d state_3 = _mm256_setzero_pd(); // dummy __m256d t0, t1, t2, t3; register_transpose(state_0, state_1, state_2, state_3, &t0, &t1, &t2, &t3); //__m256i mask = _mm256_set_epi64x(+1, -1, -1, -1); // store only the first 3 _mm256_maskstore_pd(particles[i+0].xv, mask, t0); _mm256_maskstore_pd(particles[i+1].xv, mask, t1); _mm256_maskstore_pd(particles[i+2].xv, mask, t2); _mm256_maskstore_pd(particles[i+3].xv, mask, t3); } } /***************************************************************************** * PERFORMANCE STATUS (N=NPARTICLES) * Work, best: 20 (pred_true) + 22(com_steer.) + N*20 (predict) = 42 + N*20 flops * Work, worst: 29 (pred_true) +17 (con_noise) + 37(com_steer.) + N*46 (predict) = 83 + N*46 flops * * * #work best, det: 1 atan2 + 2 pow_2 + 3*N+3 sin/cos + 9*N+9+3 mults + 3*N+3+8 adds + 1*N+1+1 neg + 4*N+4+7 fl-comp + 1*N+1 div * #work, worst, det: 1 atan2 + 2 pow_2 + 3*N+3+2 neg + 17*N+12+9 mults + 4*N+2+1 div + 1*N+1+1 floor + 4*N+4+11 fl-comp + 3*N+3 sin + 12*N+5+10 adds + 2*N sqrt * #Work best, detailed: * Memory moved: TBD * Cycles: 48000 with N = 100 * Performance: 0.04 * Optimal: TBD * Status: TBD ****************************************************************************/ void predict_update_base(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering_base(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true_base(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2]; add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step for (size_t i = 0; i < N; i++) { predict_base(&particles[i], VnGn[0], VnGn[1], Q, WHEELBASE, dt); } } double predict_update_base_flops(double *wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { int iwp_reset = *iwp; double G_reset = *G; double flop_count = compute_steering_base_flops(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); flop_count += predict_true_base_flops(V, *G, WHEELBASE, dt, xtrue); double VnGn[2] = {0,0}; flop_count +=add_control_noise_base_flops(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); //add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); //flop_count += add_control_noise_base_flops(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO for (size_t i = 0; i < N; i++) { flop_count += predict_base_flops(&particles[i], VnGn[0], VnGn[1], Q, WHEELBASE, dt); } *iwp = iwp_reset; *G = G_reset; return flop_count; } double predict_update_base_memory(double *wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { int iwp_reset = *iwp; double G_reset = *G; double memory_moved = compute_steering_base_memory(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); memory_moved += predict_true_base_memory(V, *G, WHEELBASE, dt, xtrue); double VnGn[2] = {0,0}; //add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); //memory_moved += add_control_noise_base_memory(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO for (size_t i = 0; i < N; i++) { memory_moved += predict_base_memory(&particles[i], VnGn[0], VnGn[1], Q, WHEELBASE, dt); } return memory_moved; } void predict_update_active(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2]; add_control_noise(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step for (size_t i = 0; i < N; i++) { predict(&particles[i], VnGn[0], VnGn[1], Q, WHEELBASE, dt); } } #ifdef __AVX2__ void predict_update_fast_plain(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering_base(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true_base(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2] __attribute__ ((aligned(32))); add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step double Vn, Gn, Vn1, Gn1, Vn2, Gn2, Vn3, Gn3; __m256d Vns, VndtWB, Vndt; __m256d Gns, Gn_theta, Gnsin; __m256d angles; __m256d dtv = _mm256_set1_pd(dt); __m256d WBv = _mm256_set1_pd(WHEELBASE); __m256d dtWBv = _mm256_div_pd(dtv, WBv); __m256i load_mask = _mm256_set_epi64x(9,6,3,0); __m256d thetas, xs, ys, xv1, xv2, xv3, xv, Gn_theta_sin, Gn_theta_cos; Vns = _mm256_set1_pd(VnGn[0]); Gns = _mm256_set1_pd(VnGn[1]); double angle_buffer[4] __attribute__ ((aligned(32))); double S[4] __attribute__ ((aligned(32))); llt_2x2(Q,S); __m256d SMat = _mm256_load_pd(S); __m256d VG = _mm256_set_pd(VnGn[1], VnGn[0], VnGn[1], VnGn[0]); for (size_t i = 0; i < N; i+=4) { if (SWITCH_PREDICT_NOISE == 1) { //Vector2d noise; //multivariate_gauss_base(VnGn,Q,noise); __m256d rand_vec1 = fill_rand_avx(-1.0,1.0); __m256d rand_vec2 = fill_rand_avx(-1.0,1.0); __m256d mul_gauss1 = _mmTadd_2x2_avx_v2(rand_vec1, SMat, VG); __m256d mul_gauss2 = _mmTadd_2x2_avx_v2(rand_vec2, SMat, VG); // S*rand + VnGn Vns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b0000); Gns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b1111); } xs = _mm256_i64gather_pd(particles[i].xv, load_mask, 8); ys = _mm256_i64gather_pd(particles[i].xv + 1, load_mask, 8); thetas = _mm256_i64gather_pd(particles[i].xv +2, load_mask, 8); Vndt = _mm256_mul_pd(Vns, dtv); VndtWB = _mm256_mul_pd(Vns, dtWBv); Gn_theta = _mm256_add_pd(Gns, thetas); Gn_theta_cos = tscheb_cos_avx(Gn_theta); Gn_theta_sin = tscheb_sin_avx(Gn_theta); Gnsin = tscheb_sin_avx(Gns); xs = _mm256_fmadd_pd(Vndt, Gn_theta_cos, xs); ys = _mm256_fmadd_pd(Vndt, Gn_theta_sin, ys); angles = _mm256_fmadd_pd(VndtWB, Gnsin, thetas); xv1 = _mm256_shuffle_pd(xs,ys,0b0000); // x1, y1, x3, y3 xv2 = _mm256_shuffle_pd(xs,ys,0b1111); // x2, y2, x4, y4 _mm256_store2_m128d(particles[i+2].xv, particles[i].xv, xv1); _mm256_store2_m128d(particles[i+3].xv, particles[i+1].xv, xv2); angles = simple_pi_to_pi_avx(angles); _mm256_store_pd(angle_buffer, angles); //double xv2 = particles[i].xv[2]; //particles[i].xv[0] += Vn*dt*tscheb_cos(Gn + xv2); //particles[i].xv[1] += Vn*dt*tscheb_sin(Gn + xv2); for (int j = 0; j<4; j++) { particles[i+j].xv[2] = angle_buffer[j]; } //particles[i].xv[2] = pi_to_pi_base(xv2 + Vn*dt*tscheb_sin(Gn)/WHEELBASE); } } #endif double predict_update_active_flops(double *wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { int iwp_reset = *iwp; double G_reset = *G; double _xtrue[3] = {xtrue[0], xtrue[1], xtrue[2]}; double flop_count = compute_steering_active_flops(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); flop_count += predict_true_base_flops(V, *G, WHEELBASE, dt, xtrue); double VnGn[2]; flop_count +=add_control_noise_base_flops(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); //add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // flop_count += add_control_noise_base_flops(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO if (SWITCH_PREDICT_NOISE) { flop_count+=N*(2*tp.fastrand + 2* mmadd_2x2_flops(Q,Q,Q)); } flop_count+= N* (5*tp.mul + 4* tp.add+ 2*tp.sin /*tscheb_sin*/ + 1* tp.cos /*tscheb_cos*/+ pi_to_pi_active_flops(3.0) /*simple pi_to_pi*/); *iwp = iwp_reset; *G = G_reset; copy(_xtrue, 3, xtrue); return flop_count; } double predict_update_active_memory(double *wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { int iwp_reset = *iwp; double G_reset = *G; double memory_moved = compute_steering_active_memory(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); memory_moved += predict_true_base_memory(V, *G, WHEELBASE, dt, xtrue); // memory_moved += add_control_noise_base_memory(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO //add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); memory_moved += 2*3*N; //We load xv and write to xv //The angle_buffer[4] is supposed to stay in cache, so I didnt count that *iwp = iwp_reset; *G = G_reset; return memory_moved; } #ifdef __AVX2__ void predict_update_fast(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering_base(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true_base(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2] __attribute__ ((aligned(32))); add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step double Vn, Gn, Vn1, Gn1, Vn2, Gn2, Vn3, Gn3; __m256d Vns, VndtWB, Vndt; __m256d Gns, Gn_theta, Gnsin; __m256d angles; __m256d dtv = _mm256_set1_pd(dt); __m256d WBv = _mm256_set1_pd(WHEELBASE); __m256d dtWBv = _mm256_div_pd(dtv, WBv); __m256i load_mask = _mm256_set_epi64x(9,6,3,0); __m256d thetas, xs, ys, xv1, xv2, xv3, xv, Gn_theta_sin, Gn_theta_cos; Vns = _mm256_set1_pd(VnGn[0]); Gns = _mm256_set1_pd(VnGn[1]); double angle_buffer[4] __attribute__ ((aligned(32))); double S[4] __attribute__ ((aligned(32))); llt_2x2(Q,S); __m256d SMat = _mm256_load_pd(S); __m256d VG = _mm256_set_pd(VnGn[1], VnGn[0], VnGn[1], VnGn[0]); for (size_t i = 0; i < N; i+=4) { if (SWITCH_PREDICT_NOISE == 1) { //Vector2d noise; //multivariate_gauss_base(VnGn,Q,noise); __m256d rand_vec1 = fill_rand_avx(-1.0,1.0); __m256d rand_vec2 = fill_rand_avx(-1.0,1.0); __m256d mul_gauss1 = _mmTadd_2x2_avx_v2(rand_vec1, SMat, VG); __m256d mul_gauss2 = _mmTadd_2x2_avx_v2(rand_vec2, SMat, VG); // S*rand + VnGn Vns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b0000); Gns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b1111); } xs = _mm256_i64gather_pd(particles[i].xv, load_mask, 8); ys = _mm256_i64gather_pd(particles[i].xv + 1, load_mask, 8); thetas = _mm256_i64gather_pd(particles[i].xv +2, load_mask, 8); Vndt = _mm256_mul_pd(Vns, dtv); VndtWB = _mm256_mul_pd(Vns, dtWBv); Gn_theta = _mm256_add_pd(Gns, thetas); Gn_theta_cos = tscheb_cos_avx(Gn_theta); Gn_theta_sin = tscheb_sin_avx(Gn_theta); Gnsin = tscheb_sin_avx(Gns); #ifdef __FMA__ xs = _mm256_fmadd_pd(Vndt, Gn_theta_cos, xs); #else xs = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_cos), xs); #endif #ifdef __FMA__ ys = _mm256_fmadd_pd(Vndt, Gn_theta_sin, ys); #else ys = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_sin), ys); #endif #ifdef __FMA__ angles = _mm256_fmadd_pd(VndtWB, Gnsin, thetas); #else angles = _mm256_add_pd( _mm256_mul_pd(VndtWB, Gnsin), thetas); #endif xv1 = _mm256_shuffle_pd(xs,ys,0b0000); // x1, y1, x3, y3 xv2 = _mm256_shuffle_pd(xs,ys,0b1111); // x2, y2, x4, y4 _mm256_store2_m128d(particles[i+2].xv, particles[i].xv, xv1); _mm256_store2_m128d(particles[i+3].xv, particles[i+1].xv, xv2); angles = simple_pi_to_pi_avx(angles); _mm256_store_pd(angle_buffer, angles); //double xv2 = particles[i].xv[2]; //particles[i].xv[0] += Vn*dt*tscheb_cos(Gn + xv2); //particles[i].xv[1] += Vn*dt*tscheb_sin(Gn + xv2); for (int j = 0; j<4; j++) { particles[i+j].xv[2] = angle_buffer[j]; } //particles[i].xv[2] = pi_to_pi_base(xv2 + Vn*dt*tscheb_sin(Gn)/WHEELBASE); } } #endif #ifdef __AVX2__ void predict_update_fast_normal_rand(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering_base(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true_base(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2] __attribute__ ((aligned(32))); add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step double Vn, Gn, Vn1, Gn1, Vn2, Gn2, Vn3, Gn3; __m256d Vns, VndtWB, Vndt; __m256d Gns, Gn_theta, Gnsin; __m256d angles; __m256d dtv = _mm256_set1_pd(dt); __m256d WBv = _mm256_set1_pd(WHEELBASE); __m256d dtWBv = _mm256_div_pd(dtv, WBv); __m256i load_mask = _mm256_set_epi64x(9,6,3,0); __m256d thetas, xs, ys, xv1, xv2, xv3, xv, Gn_theta_sin, Gn_theta_cos; Vns = _mm256_set1_pd(VnGn[0]); Gns = _mm256_set1_pd(VnGn[1]); double angle_buffer[4] __attribute__ ((aligned(32))); double S[4] __attribute__ ((aligned(32))); llt_2x2(Q,S); __m256d SMat = _mm256_load_pd(S); __m256d VG = _mm256_set_pd(VnGn[1], VnGn[0], VnGn[1], VnGn[0]); double rng[8] __attribute__ ((aligned(32))); for (size_t i = 0; i < N; i+=4) { if (SWITCH_PREDICT_NOISE == 1) { //BEGIN multivariate_gauss fill_rand(rng, 8, -1.0,1.0); __m256d rand_vec1 = _mm256_i64gather_pd(rng, _mm256_set_epi64x(5,4,1,0), 8); __m256d rand_vec2 = _mm256_i64gather_pd(rng, _mm256_set_epi64x(7,6,3,2), 8); __m256d mul_gauss1 = _mmTadd_2x2_avx_v2(rand_vec1, SMat, VG); __m256d mul_gauss2 = _mmTadd_2x2_avx_v2(rand_vec2, SMat, VG); Vns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b0000); Gns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b1111); //END multivariate_gauss } xs = _mm256_i64gather_pd(particles[i].xv, load_mask, 8); ys = _mm256_i64gather_pd(particles[i].xv + 1, load_mask, 8); thetas = _mm256_i64gather_pd(particles[i].xv +2, load_mask, 8); Vndt = _mm256_mul_pd(Vns, dtv); VndtWB = _mm256_mul_pd(Vns, dtWBv); Gn_theta = _mm256_add_pd(Gns, thetas); Gn_theta_cos = tscheb_cos_avx(Gn_theta); Gn_theta_sin = tscheb_sin_avx(Gn_theta); Gnsin = tscheb_sin_avx(Gns); #ifdef __FMA__ xs = _mm256_fmadd_pd(Vndt, Gn_theta_cos, xs); #else xs = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_cos), xs); #endif #ifdef __FMA__ ys = _mm256_fmadd_pd(Vndt, Gn_theta_sin, ys); #else ys = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_sin), ys); #endif #ifdef __FMA__ angles = _mm256_fmadd_pd(VndtWB, Gnsin, thetas); #else angles = _mm256_add_pd( _mm256_mul_pd(VndtWB, Gnsin), thetas); #endif xv1 = _mm256_shuffle_pd(xs,ys,0b0000); // x1, y1, x3, y3 xv2 = _mm256_shuffle_pd(xs,ys,0b1111); // x2, y2, x4, y4 _mm256_store2_m128d(particles[i+2].xv, particles[i].xv, xv1); _mm256_store2_m128d(particles[i+3].xv, particles[i+1].xv, xv2); _mm256_store_pd(angle_buffer, angles); //double xv2 = particles[i].xv[2]; //particles[i].xv[0] += Vn*dt*tscheb_cos(Gn + xv2); //particles[i].xv[1] += Vn*dt*tscheb_sin(Gn + xv2); for (int j = 0; j<4; j++) { particles[i+j].xv[2] = pi_to_pi_base(angle_buffer[j]); } //particles[i].xv[2] = pi_to_pi_base(xv2 + Vn*dt*tscheb_sin(Gn)/WHEELBASE); } } #endif #ifdef __AVX2__ void predict_update_fast_scalar_pipi(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering_base(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true_base(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2] __attribute__ ((aligned(32))); add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step double Vn, Gn, Vn1, Gn1, Vn2, Gn2, Vn3, Gn3; __m256d Vns, VndtWB, Vndt; __m256d Gns, Gn_theta, Gnsin; __m256d angles; __m256d dtv = _mm256_set1_pd(dt); __m256d WBv = _mm256_set1_pd(WHEELBASE); __m256d dtWBv = _mm256_div_pd(dtv, WBv); __m256i load_mask = _mm256_set_epi64x(9,6,3,0); __m256d thetas, xs, ys, xv1, xv2, xv3, xv, Gn_theta_sin, Gn_theta_cos; Vns = _mm256_set1_pd(VnGn[0]); Gns = _mm256_set1_pd(VnGn[1]); double angle_buffer[4] __attribute__ ((aligned(32))); double S[4] __attribute__ ((aligned(32))); llt_2x2(Q,S); __m256d SMat = _mm256_load_pd(S); __m256d VG = _mm256_set_pd(VnGn[1], VnGn[0], VnGn[1], VnGn[0]); for (size_t i = 0; i < N; i+=4) { if (SWITCH_PREDICT_NOISE == 1) { //Vector2d noise; //multivariate_gauss_base(VnGn,Q,noise); __m256d rand_vec1 = fill_rand_avx(-1.0,1.0); __m256d rand_vec2 = fill_rand_avx(-1.0,1.0); __m256d mul_gauss1 = _mmTadd_2x2_avx_v2(rand_vec1, SMat, VG); __m256d mul_gauss2 = _mmTadd_2x2_avx_v2(rand_vec2, SMat, VG); // S*rand + VnGn Vns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b0000); Gns = _mm256_shuffle_pd(mul_gauss1, mul_gauss2,0b1111); } xs = _mm256_i64gather_pd(particles[i].xv, load_mask, 8); ys = _mm256_i64gather_pd(particles[i].xv + 1, load_mask, 8); thetas = _mm256_i64gather_pd(particles[i].xv +2, load_mask, 8); Vndt = _mm256_mul_pd(Vns, dtv); VndtWB = _mm256_mul_pd(Vns, dtWBv); Gn_theta = _mm256_add_pd(Gns, thetas); Gn_theta_cos = tscheb_cos_avx(Gn_theta); Gn_theta_sin = tscheb_sin_avx(Gn_theta); Gnsin = tscheb_sin_avx(Gns); #ifdef __FMA__ xs = _mm256_fmadd_pd(Vndt, Gn_theta_cos, xs); #else xs = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_cos), xs); #endif #ifdef __FMA__ ys = _mm256_fmadd_pd(Vndt, Gn_theta_sin, ys); #else ys = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_sin), ys); #endif #ifdef __FMA__ angles = _mm256_fmadd_pd(VndtWB, Gnsin, thetas); #else angles = _mm256_add_pd( _mm256_mul_pd(VndtWB, Gnsin), thetas); #endif xv1 = _mm256_shuffle_pd(xs,ys,0b0000); // x1, y1, x3, y3 xv2 = _mm256_shuffle_pd(xs,ys,0b1111); // x2, y2, x4, y4 _mm256_store2_m128d(particles[i+2].xv, particles[i].xv, xv1); _mm256_store2_m128d(particles[i+3].xv, particles[i+1].xv, xv2); _mm256_store_pd(angle_buffer, angles); //double xv2 = particles[i].xv[2]; //particles[i].xv[0] += Vn*dt*tscheb_cos(Gn + xv2); //particles[i].xv[1] += Vn*dt*tscheb_sin(Gn + xv2); for (int j = 0; j<4; j++) { particles[i+j].xv[2] = pi_to_pi_base(angle_buffer[j]); } //particles[i].xv[2] = pi_to_pi_base(xv2 + Vn*dt*tscheb_sin(Gn)/WHEELBASE); } } #endif #ifdef __AVX2__ void predict_update_simd(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering_base(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true_base(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2] __attribute__ ((aligned(32))); add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step double Vn, Gn, Vn1, Gn1, Vn2, Gn2, Vn3, Gn3; __m256d Vns, VndtWB, Vndt; __m256d Gns, Gn_theta, Gnsin; __m256d angles; __m256d dtv = _mm256_set1_pd(dt); __m256d WBv = _mm256_set1_pd(WHEELBASE); __m256d dtWBv = _mm256_div_pd(dtv, WBv); __m256i load_mask = _mm256_set_epi64x(9,6,3,0); __m256d thetas, xs, ys, xv1, xv2, xv3, xv, Gn_theta_sin, Gn_theta_cos; Vns = _mm256_set1_pd(VnGn[0]); Gns = _mm256_set1_pd(VnGn[1]); double angle_buffer[4] __attribute__ ((aligned(32))); for (size_t i = 0; i < N; i+=4) { if (SWITCH_PREDICT_NOISE == 1) { Vector2d noise; multivariate_gauss_base(VnGn,Q,noise); Vn = noise[0]; Gn = noise[1]; Vector2d noise1; multivariate_gauss_base(VnGn,Q,noise1); Vn1 = noise1[0]; Gn1 = noise1[1]; Vector2d noise2; multivariate_gauss_base(VnGn,Q,noise2); Vn2 = noise2[0]; Gn2 = noise2[1]; Vector2d noise3; multivariate_gauss_base(VnGn,Q,noise3); Vn3 = noise3[0]; Gn3 = noise3[1]; Vns = _mm256_set_pd(Vn3, Vn2, Vn1, Vn); Gns = _mm256_set_pd(Gn3, Gn2, Gn1, Gn); } xs = _mm256_i64gather_pd(particles[i].xv, load_mask, 8); ys = _mm256_i64gather_pd(particles[i].xv + 1, load_mask, 8); thetas = _mm256_i64gather_pd(particles[i].xv +2, load_mask, 8); Vndt = _mm256_mul_pd(Vns, dtv); VndtWB = _mm256_mul_pd(Vns, dtWBv); Gn_theta = _mm256_add_pd(Gns, thetas); Gn_theta_cos = tscheb_cos_avx(Gn_theta); Gn_theta_sin = tscheb_sin_avx(Gn_theta); Gnsin = tscheb_sin_avx(Gns); #ifdef __FMA__ xs = _mm256_fmadd_pd(Vndt, Gn_theta_cos, xs); #else xs = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_cos), xs); #endif #ifdef __FMA__ ys = _mm256_fmadd_pd(Vndt, Gn_theta_sin, ys); #else ys = _mm256_add_pd( _mm256_mul_pd(Vndt, Gn_theta_sin), ys); #endif #ifdef __FMA__ angles = _mm256_fmadd_pd(VndtWB, Gnsin, thetas); #else angles = _mm256_add_pd( _mm256_mul_pd(VndtWB, Gnsin), thetas); #endif xv1 = _mm256_shuffle_pd(xs,ys,0b0000); // x1, y1, x3, y3 xv2 = _mm256_shuffle_pd(xs,ys,0b1111); // x2, y2, x4, y4 _mm256_store2_m128d(particles[i+2].xv, particles[i].xv, xv1); _mm256_store2_m128d(particles[i+3].xv, particles[i+1].xv, xv2); _mm256_store_pd(angle_buffer, angles); //double xv2 = particles[i].xv[2]; //particles[i].xv[0] += Vn*dt*tscheb_cos(Gn + xv2); //particles[i].xv[1] += Vn*dt*tscheb_sin(Gn + xv2); for (int j = 0; j<4; j++) { particles[i+j].xv[2] = pi_to_pi_base(angle_buffer[j]); } //particles[i].xv[2] = pi_to_pi_base(xv2 + Vn*dt*tscheb_sin(Gn)/WHEELBASE); } } #endif void predict_update_sine(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering_base(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true_base(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2]; add_control_noise_base(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step double Vn = V; double Gn = *G; for (size_t i = 0; i < N; i++) { if (SWITCH_PREDICT_NOISE == 1) { Vector2d noise; multivariate_gauss_base(VnGn,Q,noise); Vn = noise[0]; Gn = noise[1]; } double xv2 = particles[i].xv[2]; particles[i].xv[0] += Vn*dt*tscheb_cos(Gn + xv2); particles[i].xv[1] += Vn*dt*tscheb_sin(Gn + xv2); particles[i].xv[2] = pi_to_pi_base(xv2 + Vn*dt*tscheb_sin(Gn)/WHEELBASE); } } void predict_update_old(double* wp, size_t N_waypoints, double V, double* Q, double dt, size_t N, Vector3d xtrue, int* iwp, double* G, Particle* particles) { compute_steering(xtrue, wp, N_waypoints, AT_WAYPOINT, RATEG, MAXG, dt, iwp, G); if ( *iwp == -1 && NUMBER_LOOPS > 1 ) { *iwp = 0; NUMBER_LOOPS--; } predict_true(V, *G, WHEELBASE, dt, xtrue); // add process noise double VnGn[2]; add_control_noise(V, *G, Q, SWITCH_CONTROL_NOISE, VnGn); // TODO // Predict step double Vn = V; double Gn = *G; for (size_t i = 0; i < N; i++) { if (SWITCH_PREDICT_NOISE == 1) { Vector2d noise; multivariate_gauss_base(VnGn,Q,noise); Vn = noise[0]; Gn = noise[1]; } double xv2 = particles[i].xv[2]; particles[i].xv[0] += Vn*dt*cos(Gn + xv2); particles[i].xv[1] += Vn*dt*sin(Gn + xv2); particles[i].xv[2] = pi_to_pi_base(xv2 + Vn*dt*sin(Gn)/WHEELBASE); } }
// // chat_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff 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) // #include <cstdlib> #include <deque> #include <iostream> #include <thread> #include <string> #include "asio.hpp" #include "chat_message2.hpp" using asio::ip::tcp; int num1 = 0; int r_value = 0; typedef std::deque<chat_message> chat_message_queue; class chat_client { public: chat_client(asio::io_context& io_context, const tcp::resolver::results_type& endpoints) : io_context_(io_context), socket_(io_context) { do_connect(endpoints); } void write(const chat_message& msg) { asio::post(io_context_, [this, msg]() { bool write_in_progress = !write_msgs_.empty(); write_msgs_.push_back(msg); if (!write_in_progress) { do_write(); } }); } void close() { asio::post(io_context_, [this]() { socket_.close(); }); } private: void do_connect(const tcp::resolver::results_type& endpoints) { asio::async_connect(socket_, endpoints, [this](std::error_code ec, tcp::endpoint) { if (!ec) { do_read_header(); } }); } void do_read_header() { asio::async_read(socket_, asio::buffer(read_msg_.data(), chat_message::header_length), [this](std::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { if(read_msg_.ca.stand != true){ if(read_msg_.ca.track_num ==0){ std::cout << "-----------------------------------" << '\n'; std::cout << "Your first card " << read_msg_.ca.c1_face << " of "<< read_msg_.ca.c1_suit<< std::endl; std::cout << "Your second card " << read_msg_.ca.c2_face << " of "<< read_msg_.ca.c2_suit<< std::endl; std::cout << "Dealer first card " << read_msg_.ca.d1_face << " of "<< read_msg_.ca.d1_suit<< std::endl; std::cout << "----------------------------------------" << '\n'; } else if(read_msg_.ca.r_value == 1){ r_value++; std::cout << "-----------------------------------" << '\n'; std::cout << "Your first card " << read_msg_.ca.c1_face << " of "<< read_msg_.ca.c1_suit<< std::endl; std::cout << "Your second card " << read_msg_.ca.c2_face << " of "<< read_msg_.ca.c2_suit<< std::endl; std::cout << "Dealer first card " << read_msg_.ca.d1_face << " of "<< read_msg_.ca.d1_suit<< std::endl; std::cout << "----------------------------------------" << '\n'; } else{ std::cout << "-------------------------------------------" << '\n'; std::cout << "Your card " << read_msg_.ca.c1_face << " of "<< read_msg_.ca.c1_suit<< std::endl; std::cout << "-------------------------------------------" << '\n'; } } else{ std::cout << "Hello" << '\n'; } do_read_body(); } else { socket_.close(); } }); } void do_read_body() { asio::async_read(socket_, asio::buffer(read_msg_.body(), read_msg_.body_length()), [this](std::error_code ec, std::size_t /*length*/) { if (!ec) { if (read_msg_.gs.valid && read_msg_.ca.stand != true){ std::cout << "/* -------------------------------- */" << '\n'; std::cout << "/* What you like to do? */" << '\n'; std::cout << "Enter Hit for Hit" << '\n'; std::cout << "Enter Stand for Stand" << '\n'; std::cout << "Enter Split for Split" << '\n'; std::cout << "Enter Insurance for Insurance" << '\n'; std::cout << "Enter New to start the new game. *Game should be over*" << '\n'; std::cout << "/* -------------------------------- */" << '\n'; } else{ std::cout << "You have now $" << read_msg_.gs.players_credit << '\n'; int cre = read_msg_.gs.players_credit - 100; if(cre < 0){ int dd = -1 * cre; std::cout << "Sorry, You are Losing by $"<< dd << '\n'; } else if(cre > 0){ std::cout << "Congrtz, You winning by $" << cre << '\n'; } else{ std::cout << "Currently, you are even out." << '\n'; } } //std::cout.write(read_msg_.body(), read_msg_.body_length()); //std::cout << "\n"; do_read_header(); } else { socket_.close(); } }); } void do_write() { asio::async_write(socket_, asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()), [this](std::error_code ec, std::size_t /*length*/) { if (!ec) { write_msgs_.pop_front(); if (!write_msgs_.empty()) { do_write(); } } else { socket_.close(); } }); } private: asio::io_context& io_context_; tcp::socket socket_; chat_message read_msg_; chat_message_queue write_msgs_; }; float send_betamount(){ char dollar[chat_message::max_body_length + 1]; std::cout << "/-----------------------------/" << '\n'; std::cout << "Enter the bet amount: $"; std::cin.getline(dollar, chat_message::max_body_length + 1); std::string fs(dollar); float dol =std::stof(fs); return dol; } int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: chat_client <host> <port>\n"; return 1; } asio::io_context io_context; tcp::resolver resolver(io_context); auto endpoints = resolver.resolve(argv[1], argv[2]); chat_client c(io_context, endpoints); std::thread t([&io_context](){ io_context.run(); }); char ans[chat_message::max_body_length + 1]; char nam[chat_message::max_body_length + 1]; chat_message msg; std::cout << "Welcome to the BlackJack Game" << '\n'; std::cout << "Do you like to start the game? "; std::cin.getline(ans, chat_message::max_body_length + 1); int result = strcmp(ans, "yes"); if(result==0){ msg.ca.start_game = true; } else{ msg.ca.start_game = false; } std::cout << "Enter your name: "; //char line[chat_message::max_body_length + 1]; while (std::cin.getline(nam, chat_message::max_body_length + 1)) { msg.ca.bet = true; msg.ca.track_num = num1; msg.ca.r_value = r_value; if(num1 == 0 ){ msg.ca.name_valid = true; strcpy(msg.ca.name, nam); num1++; }else{ if(strcmp(nam, "Hit")==0){ msg.ca.hit = true; msg.ca.stand = false; msg.ca.insurance = false; msg.ca.split = false; msg.ca.bet = false; msg.ca.new_round = false; } else if(strcmp(nam, "Stand")==0){ char an[chat_message::max_body_length + 1]; std::cout << " Are you sure you want to stand? "; std::cin.getline(an, chat_message::max_body_length + 1); if(strcmp(an, "yes") == 0){ msg.ca.hit = false; msg.ca.stand = true; msg.ca.insurance =false; msg.ca.split =false; msg.ca.bet = false; msg.ca.new_round = false; } } else if(strcmp(nam, "Split")==0){ // std::cout << " I am to Split" << '\n'; msg.ca.hit = false; msg.ca.stand =false; msg.ca.insurance =false; msg.ca.split = true; msg.ca.bet = false; msg.ca.new_round = false; } else if(strcmp(nam, "Insurance")==0){ // std::cout << " I am to Insurance" << '\n'; msg.ca.hit = false; msg.ca.stand =false; msg.ca.insurance = true; msg.ca.split =false; msg.ca.bet = false; msg.ca.new_round = false; } else if(strcmp(nam, "New")==0){ // std::cout << " I am to Insurance" << '\n'; msg.ca.hit = false; msg.ca.stand =false; msg.ca.insurance = false; msg.ca.split =false; msg.ca.bet = false; msg.ca.new_round = true; } else{ msg.ca.hit = false; msg.ca.stand =false; msg.ca.insurance = false; msg.ca.split =false; msg.ca.bet = false; msg.ca.new_round = false; } } if(msg.ca.bet){ float d = send_betamount(); msg.ca.bet_amo_ = d; if(msg.ca.stand){ msg.ca.stand = false; std::cout << "/*-------Starting the new round-------*/" << '\n'; std::cout << '\n'; } } //get the line from command and encode it. msg.body_length(std::strlen(nam)); std::memcpy(msg.body(), nam, msg.body_length()); msg.encode_header(); c.write(msg); } c.close(); t.join(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <shader.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/string_cast.hpp> #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> using namespace std; //设置窗口大小 const unsigned int WindowSize = 600; //控制点的向量,以及当前的点的迭代器 vector<glm::vec3> control_points; vector<glm::vec3>::iterator current_point; //初始情况下默认没有按下左键以及不在画图的过程中 bool left_button_flag = false; bool drawing_flag = false; unsigned int point_VAO, point_VBO; //当用户修改窗口时的回调函数,用于实时修改窗口大小 void windowSizeCallback(GLFWwindow* current_window, int width, int height) { glViewport(0, 0, width, height); } //处理用户输入的函数,这里主要是按TAB键后切换到动态呈现曲线生成过程的bonus模式 void processInput(GLFWwindow* current_window) { if (glfwGetKey(current_window, GLFW_KEY_TAB) == GLFW_PRESS) { drawing_flag = !drawing_flag; } } //寻找距离点击时距离光标最近的控制点的函数 vector<glm::vec3>::iterator GetNearestControlPoint(const float current_x, const float current_y, const float threshold) { //默认值为空 auto result = control_points.end(); //定义一个匿名函数,用来计算当前光标与一个给定点的欧式距离的平方 //这里可以不需要平方,因为只用比较距离的大小 auto getDist = [&current_x, &current_y](const vector<glm::vec3>::iterator iter) -> float { return pow((current_x - iter->x), 2) + pow((current_y - iter->y), 2); }; //遍历所有的控制点,计算是否有在距离在阈值内的控制点 for (auto iter = control_points.begin(); iter != control_points.end(); iter++) { auto temp_dist = getDist(iter); if (temp_dist < threshold) { result = (result == control_points.end()) ? iter : ((getDist(result) < temp_dist) ? result : iter); } } return result; } //将控制点的坐标转换成浮点数的向量 vector<float> Control2Float(vector<glm::vec3> input) { //首先将控制点的坐标放入一个向量中 vector<float> result; result.clear(); for (auto iter = input.begin(); iter != input.end(); iter++) { result.push_back(iter->x); result.push_back(iter->y); result.push_back(iter->z); } //再将坐标标准化到[-1,1]的范围中 for (unsigned int i = 0; i < result.size(); i += 3) { result[i] = (2 * result[i]) / WindowSize - 1; result[i + 1] = 1 - (2 * result[i + 1]) / WindowSize; } return result; } //将GLFW下的坐标转换成标准化设备坐标 glm::vec3 Glfw2Ndc(const glm::vec3 point) { return glm::vec3((2 * point.x) / WindowSize - 1, 1 - (2 * point.y) / WindowSize, 0.0f); } /* 渲染Beizer曲线相关的线段,输入参数为: * shader 线段使用的着色器 * nodeData 控制点的坐标的向量 * pointSize 每个点的大小 */ void RenderLines(Shader& shader, const vector<float>& nodeData, float pointSize) { shader.use(); glBindVertexArray(point_VAO); glBindBuffer(GL_ARRAY_BUFFER, point_VBO); glBufferData(GL_ARRAY_BUFFER, nodeData.size() * sizeof(float), nodeData.data(), GL_STATIC_DRAW); //这里只需要绑定位置信息 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); //先设置点的大小,然后渲染每一个控制点 glPointSize(pointSize); glDrawArrays(GL_POINTS, 0, int(nodeData.size() / 3)); //然后渲染点之间的线段 glLineWidth(1.0f); glDrawArrays(GL_LINE_STRIP, 0, int(nodeData.size() / 3)); glBindVertexArray(0); } /* 动态呈现Beizer生成过程的函数,输入参数为: * shader 渲染用的着色器 * points 上一轮迭代使用的控制点 * t 新生成的点在线段中的比例 */ void DynamicRender(Shader& shader, vector<glm::vec3> points, float t) { //如果只有一个/没有控制点,那么无法动态生成Beizer曲线 //递归的终止条件 if (points.size() < 2) { return; } //计算此次迭代的控制点的坐标 vector<glm::vec3> next_nodes; for (int i = 0; i < points.size() - 1; ++i) { next_nodes.push_back(glm::vec3((1 - t) * points[i].x + t * points[i + 1].x, (1 - t) * points[i].y + t * points[i + 1].y, 0.0f)); } //将点转换成float的向量 auto nodeData = Control2Float(next_nodes); //渲染控制点&之间的线段 RenderLines(shader, nodeData, 3.5f); //递归渲染曲线 DynamicRender(shader, next_nodes, t); } /* 鼠标按钮的回调函数,输入参数有: * current_window 当前窗口 * button 按下的按钮 * action 按下的动作, * mods 模式,在这里不需要使用 */ void ButtonCallback(GLFWwindow* current_window, int button, int action, int mods) { //获得按下鼠标按钮时的光标坐标 double x = 0, y = 0; glfwGetCursorPos(current_window, &x, &y); //当按下的按钮为左键时 if (button == GLFW_MOUSE_BUTTON_LEFT) { //按下按钮时 if (action == GLFW_PRESS) { left_button_flag = true; //寻找附近的控制点,若找不到附近有控制点,则添加一个新的控制点 if (GetNearestControlPoint(x, y, 100) == control_points.end()) { control_points.push_back(glm::vec3(x, y, 0.0f)); } } //释放按钮,将当前点的迭代器容器置空,并且恢复flag if (action == GLFW_RELEASE) { current_point = control_points.end(); left_button_flag = false; } } //当按下右键时,若控制点向量不为空,删除最后一个控制点 if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) { if (!control_points.empty()) { control_points.pop_back(); } } } int main() { //实例化GLFW窗口 glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //创建窗口对象 GLFWwindow* current_window = glfwCreateWindow(WindowSize, WindowSize, "HW8 16340253", NULL, NULL); if (current_window == NULL) { cout << ">Failed at function: glfwCreateWindow()." << endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(current_window); glfwSetFramebufferSizeCallback(current_window, windowSizeCallback); glfwSwapInterval(1); //读取GLAD包中符合本地版本的的OpenGL的所有函数指针 if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { cout << ">Failed at function: gladLoadGLLoader()." << endl; return -1; } //初始化各种数据 float step = 0.001f, current_t = 0.0f; //装所有的顶点的向量 vector<float> vertex_buff; vertex_buff.resize(int(1 / step)); for (int i = 0; i < vertex_buff.size(); i++) { vertex_buff[i] = i * step; } //声明顶点数组对象、顶点缓冲对象,并且绑定到缓冲上 unsigned int VAO, VBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenVertexArrays(1, &point_VAO); glGenBuffers(1, &point_VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, vertex_buff.size() * sizeof(float), vertex_buff.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 1 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); //初始化点和曲线的着色器 Shader point_shader("point/shader.vs", "point/shader.fs"), curve_shader("curve/shader.vs", "curve/shader.fs"); //渲染循环 while (!glfwWindowShouldClose(current_window)) { //创建ImGui glfwPollEvents(); processInput(current_window); //渲染窗口颜色 glClearColor(0.46f, 0.53f, 0.6f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(0); //若点击了左键 if (left_button_flag) { //获得当前的光标的坐标 double current_x = 0, current_y = 0; glfwGetCursorPos(current_window, &current_x, &current_y); //获得最近的控制点 current_point = GetNearestControlPoint(current_x, current_y, 100); //如果最近的控制点不为空,修改此点的位置信息,来达到动态修改控制点的效果 if (current_point != control_points.end()) { current_point->x = current_x; current_point->y = current_y; } } //将控制点转换成浮点数的向量,并且渲染控制线之间的线段 auto pointdata = Control2Float(control_points); RenderLines(point_shader, pointdata, 5.0f); //渲染曲线 //激活曲线着色器 curve_shader.use(); //传输控制点的向量的长度 curve_shader.setInt("size", int(control_points.size())); //遍历控制点的向量,对每一个控制点分别传输数组中的一个元素 for (auto index = 0; index < control_points.size(); index++) { curve_shader.setFloat3(("points[" + std::to_string(index) + "]").c_str(), glm::value_ptr(Glfw2Ndc(control_points[index]))); } //当控制点不为空时 if (!control_points.empty()) { //设置点的大小,画出每一个控制点 glBindVertexArray(VAO); glPointSize(2.0f); glDrawArrays(GL_POINTS, 0, int(vertex_buff.size())); glBindVertexArray(0); } //动态呈现生成曲线的过程 if (drawing_flag) { //此时需要取消鼠标的回调函数 glfwSetMouseButtonCallback(current_window, NULL); //每一次迭代更新一次比例参数,调用动态渲染的函数 current_t = (current_t + 0.001 <= 1) ? current_t + 0.001 : 0; DynamicRender(point_shader, control_points, current_t); } else { //不动态的时候,置零比例参数并且注册鼠标按钮的回调函数 current_t = 0.0; glfwSetMouseButtonCallback(current_window, ButtonCallback); } glfwSwapBuffers(current_window); } //清除所有申请的glfw资源 glfwTerminate(); return 0; }
#include "StringHelpers.h" namespace IRCOptotron { namespace MiscStringHelpers { // trim from start std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } // trim from end std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // trim from both ends std::string &trim(std::string &s) { return ltrim(rtrim(s)); } std::vector<std::string> tokenizeString(const std::string& s, const char& delimiter) { std::string token = ""; std::vector<std::string> tokens; for(unsigned i = 0; i < s.length(); i++) { if(s.at(i) == delimiter) { if(token.length() > 0){ tokens.push_back(token); token = ""; } } else { token += s.at(i); } } if(token.length() > 0) tokens.push_back(token); return tokens; } std::string detokenizeString(const std::vector<std::string>& tokens, const char& combiner, unsigned start) { if(tokens.size() == 0 || tokens.size() < start+1) return ""; std::string combined = tokens[start]; for(unsigned i = start+1; i < tokens.size(); i++) { combined += combiner + tokens[i]; } return combined; } bool stringContainsAllTokens(const std::string& haystack, const std::vector<std::string>& tokens) { for(size_t i = 0; i < tokens.size(); i++) { if(haystack.find(tokens[i]) == std::string::npos) return false; } return true; } } }
#include <bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0) #define rep(i, a, b) for(int i=int(a);i<int(b);i++) #define pb push_back #define mp make_pair #define st first #define nd second #define MAX 100010 using namespace std; typedef vector<int> vi; typedef long long int lld; int solve(vector<stack<int>>& ps, int l, int r, bool dir){ int ans = 0; size_t sizes[ps.size()] = {0}; rep(i, l, r) sizes[i] = ps[i].size(); if(!dir){ for(int i=r-1;i>=l;i--){ if(i == r-1){ while(ps[i].size() >= ps[r].size()){ ps[i].pop(); ans++; if(ps[i].empty()) break; } }else{ if(sizes[i+1] != ps[i+1].size()){ while(ps[i].size() > ps[i+1].size()){ ps[i].pop(); ans++; if(ps[i].empty()) break; } } } } }else{ for(int i=l;i<r;i++){ if(i == l){ while(ps[i].size() >= ps[i-1].size()){ ps[i].pop(); ans++; if(ps[i].empty()) break; } }else{ if(sizes[i-1] != ps[i-1].size()){ while(ps[i].size() > ps[i-1].size()){ ps[i].pop(); ans++; if(ps[i].empty()) break; } } } } } return ans; } int main() { fastio; int n, p; while(cin >> n >> p){ if(n == 0 && p == 0) break; vector<stack<int>> ps(p); int pos = 0; rep(i, 0, p){ int q; cin >> q; rep(j, 0, q){ int x; cin >> x; ps[i].push(x); if(x == 1) pos = i; } } int ans =0; while(ps[pos].top()!=1){ ps[pos].pop(); ans++; } int left, right; left = solve(ps, 0, pos, false); right = solve(ps, pos+1, p, true); cout << min(ans+left, ans+right) << '\n'; } return 0; }
// // Created by jerry on 2/17/2021. // #ifndef COMP345_WINTER2021_MAPLOADERMAIN_H #define COMP345_WINTER2021_MAPLOADERMAIN_H namespace mapLoader{ int main(); } #endif //COMP345_WINTER2021_MAPLOADERMAIN_H
#pragma once namespace ecs { struct Ent; } struct Rect; ecs::Ent* make_workroom(const Rect&);
/******************************************************************************* Copyright (c) 2010, Steve Lesser Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2)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. 3) The name of contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STEVE LESSER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ /** @file Bitmap.cpp @brief Implements the Bitmap class which can write out values to a bitmap */ #include "Bitmap.h" BitmapWriter::BitmapWriter(int width, int height) : m_width(width),m_height(height),m_data(0) { int imagebytes=width*height*3; m_fileHeader.bfSize = 2+sizeof(BMPFileHeader)+sizeof(BMPInfoHeader)+imagebytes; m_fileHeader.bfReserved1 = 0; m_fileHeader.bfReserved2 = 0; m_fileHeader.bfOffBits = 2+sizeof(BMPFileHeader)+sizeof(BMPInfoHeader); m_fileInfoHeader.biSize = sizeof(BMPInfoHeader); m_fileInfoHeader.biWidth = width; m_fileInfoHeader.biHeight = height; m_fileInfoHeader.biPlanes = 1; m_fileInfoHeader.biBitCount = 24; // 24 bits/pixel m_fileInfoHeader.biCompression = 0; // Zero is the defaut Bitmap m_fileInfoHeader.biSizeImage = imagebytes; m_fileInfoHeader.biXPelsPerMeter = 2835; // 72 pixels/inch = 2834.64567 pixels per meter m_fileInfoHeader.biYPelsPerMeter = 2835; m_fileInfoHeader.biClrUsed = 0; m_fileInfoHeader.biClrImportant = 0; m_data =(char*) malloc(imagebytes); // Now to write the file // Open the file in "write binary" mode } void BitmapWriter::flush(const char* fileName) { FILE *f = 0; fopen_s(&f, fileName,"wb"); if (f == 0) return; char magic[2]={'B','M'}; fwrite(magic, 2, 1, f); fwrite((void*)&m_fileHeader, sizeof(BMPFileHeader), 1, f); fwrite((void*)&m_fileInfoHeader, sizeof(BMPInfoHeader), 1, f); fwrite(m_data, m_fileInfoHeader.biSizeImage, 1, f); fclose(f); } void BitmapWriter::setValue(int x, int y, char red, char green, char blue) { if (x < 0 || x >= m_width || y < 0 || y >= m_height) return; m_data[((y*m_width)+x)*3] = red; m_data[((y*m_width)+x)*3+1] = green; m_data[((y*m_width)+x)*3+2] = blue; } //void BitmapWriter::setFloat4Data(float4* data) //{ // int x,y; // for(x=0;x<width;++x) // { // for(y=0;y<height;++y) // { // // R component // m_data[((y*width)+x)*3] = char(data[y*width+x].x); // // G component // m_data[((y*width)+x)*3+1] = char(data[y*width+x].y); // // B component // m_data[((y*width)+x)*3+2] = char(data[y*width+x].z); // } // } //}
/* * Context.h * * Created on: Jun 11, 2017 * Author: root */ #ifndef NETWORK_CONTEXT_H_ #define NETWORK_CONTEXT_H_ #include <vector> #include "NetWorkConfig.h" #include "../Thread/Task.h" #include "../Memory/MemAllocator.h" using namespace std; namespace CommBaseOut { class Message_Service_Handler; class CAcceptorMgr; class CConnMgr; class CEpollMain; class DispatchMgr; class HandlerManager; class GroupSession; class Context #ifdef USE_MEMORY_POOL : public MemoryBase #endif { public: Context(); ~Context(); int Init(Message_Service_Handler *mh, int blockThread, int ioThread); void AddAcceptor(AcceptorConfig &conf); void AddConnector(ConnectionConfig &conf); int Start(); int Stop(); void SystemErr(int fd, int lid, int ltype, int rid, int rtype, int err, string ip, int port); CAcceptorMgr * GetAccMgr() { return m_accMgr; } CConnMgr * GetConnMgr() { return m_connMgr; } HandlerManager *GetHandlerMgr() { return m_handlerMgr; } GroupSession *GetGroupSession() { return m_groupSession; } CEpollMain * GetEpollMgr() { return m_epoll; } Message_Service_Handler * GetServiceHandler() { return m_connHandler; } AcceptorConfig * GetAccConfig(int index) { return &m_acceptAdded[index]; } vector<ConnectionConfig> &GetAllConnConfig() { return m_connAdded; } ConnectionConfig * GetConnConfig(int index) { return &m_connAdded[index]; } DispatchMgr * GetDispatch() { return m_dispatchMgr; } ChannelConfig * GetConfig() { if(m_connAdded.size() == 0) { return static_cast<ChannelConfig *>(&m_acceptAdded[0]); } return static_cast<ChannelConfig *>(&m_connAdded[0]); } ChannelConfig * GetConfig(unsigned char index, unsigned char type) { if(type == eConnEpoll) { return static_cast<ChannelConfig *>(&m_connAdded[index]); } return static_cast<ChannelConfig *>(&m_acceptAdded[index]); } private: vector<ConnectionConfig> m_connAdded; vector<AcceptorConfig> m_acceptAdded; CAcceptorMgr *m_accMgr; CConnMgr *m_connMgr; CEpollMain *m_epoll; Message_Service_Handler *m_connHandler; DispatchMgr * m_dispatchMgr; HandlerManager *m_handlerMgr; GroupSession * m_groupSession; int m_blockThread; int m_ioThread; }; } #endif /* NETWORK_CONTEXT_H_ */
#ifndef BOSS_H #define BOSS_H class Boss { private: byte x, y; byte w, h; byte cx; bool alive; byte timerPriv; byte framePriv; bool moveEnd; byte wait; bool muki; void appearance(); void attack(); public: bool getMoveEnd() const { return moveEnd; } bool getalive() const { return alive; } byte getx() const { return cx; } byte gety() const { return y; } byte getw() const { return w; } byte geth() const { return h; } void initialize(); void init(); void update(); void dead(); }; class BossU { private: byte x, y; byte w, h; public: byte getx() const { return x + 4; } byte gety() const { return y; } byte getw() const { return w; } byte geth() const { return h; } void update(); }; class BossD { private: byte x, y; byte w, h; public: byte getx() const { return x + 4; } byte gety() const { return y; } byte getw() const { return w; } byte geth() const { return h; } void update(); }; class BossCore { private: byte x, y; byte w, h; byte cx; bool hit; bool alive; byte counter; byte life; byte lifed; public: bool getalive() const { return alive; } void sethit() { hit = true; } byte getx() const { return cx; } byte gety() const { return y; } byte getw() const { return w; } byte geth() const { return h; } void initialize(); void init(); void update(); void dead(); }; class BossExplosion { private: byte x, y; bool alive; byte timerPriv; byte framePriv; public: bool getalive() const { return alive; } void clear(); void init(byte, byte); void update(); }; #endif
#pragma once #include "EverydayTools/Bitset/EnumBitset.h" namespace keng::graphics { enum class DeviceBufferBindFlags { None = 0, VertexBuffer = (1 << 0), IndexBuffer = (1 << 1), ConstantBuffer = (1 << 2), ShaderResource = (1 << 3), RenderTarget = (1 << 5), DepthStencil = (1 << 6), UnorderedAccess = (1 << 7), Last }; } namespace edt { template<> struct enable_enum_bitset<keng::graphics::DeviceBufferBindFlags> { static constexpr bool value = true; }; }
#include<bits/stdc++.h> using namespace std; int main() { int n, i, j=0, k=0; cin>>n; int a[n]; int odd[n], even[n]; for(i=0; i<n; i++) { cin>>a[i]; if(a[i]%2==0) { even[j] = a[i]; j++; } else { odd[k] = a[i]; k++; } } sort(even, even+j); sort(odd, odd+k); for(i=0; i<j; i++) { cout<<even[i]<<"\n"; } for(i=k-1; i>=0; i--) { cout<<odd[i]<<"\n"; } return 0; }
#pragma once #include "net/conn.hpp" #include "net/client.hpp" #include "net/stream.hpp" #include "proto/ss_base.pb.h" #include "proto/data_yunying.pb.h" #include <memory> #include <boost/core/noncopyable.hpp> #include "proto/processor.hpp" #include "utils/server_process_base.hpp" using namespace std; namespace ps = proto::ss; namespace pd = proto::data; namespace nora { class service_thread; namespace gm { class login : public enable_shared_from_this<login>, public server_process_base, public proto::processor<login, ps::base> { public: login(const string& conn_name); static string base_name(); static void static_init(); friend ostream& operator<<(ostream& os, const login& lg); private: void process_gonggao_rsp(const ps::base *msg); void process_add_to_white_list_rsp(const ps::base *msg); void process_remove_from_white_list_rsp(const ps::base *msg); void process_fetch_white_list_rsp(const ps::base *msg); void process_fetch_gonggao_list_rsp(const ps::base *msg); string name_; }; } }
#pragma once #include "Vector4.h" #include "BasicLogicDefinitions.h" class AvatarModel { public: typedef struct { float left,top, right,bottom; } Rect; enum AvatarState { AVATAR_STATE_IDLE, AVATAR_STATE_MOVE_UP, AVATAR_STATE_MOVE_DOWN, AVATAR_STATE_MOVE_RIGHT, AVATAR_STATE_MOVE_LEFT, AVATAR_STATE_MOVE_UP_RIGHT, AVATAR_STATE_MOVE_UP_LEFT, AVATAR_STATE_MOVE_DOWN_RIGHT, AVATAR_STATE_MOVE_DOWN_LEFT, AVATAR_STATE_ATTACK_UP, AVATAR_STATE_ATTACK_DOWN, AVATAR_STATE_ATTACK_RIGHT, AVATAR_STATE_ATTACK_LEFT, AVATAR_STATE_ATTACK_UP_RIGHT, AVATAR_STATE_ATTACK_UP_LEFT, AVATAR_STATE_ATTACK_DOWN_RIGHT, AVATAR_STATE_ATTACK_DOWN_LEFT, AVATAR_STATE_DIE, AVATAR_STATE_DEAD }; enum AvatarAction { AVATAR_ACTION_IDLE, AVATAR_ACTION_MOVE_UP, AVATAR_ACTION_MOVE_DOWN, AVATAR_ACTION_MOVE_RIGHT, AVATAR_ACTION_MOVE_LEFT, AVATAR_ACTION_MOVE_UP_RIGHT, AVATAR_ACTION_MOVE_UP_LEFT, AVATAR_ACTION_MOVE_DOWN_RIGHT, AVATAR_ACTION_MOVE_DOWN_LEFT, AVATAR_ACTION_ATTACK_UP, AVATAR_ACTION_ATTACK_DOWN, AVATAR_ACTION_ATTACK_RIGHT, AVATAR_ACTION_ATTACK_LEFT, AVATAR_ACTION_ATTACK_UP_RIGHT, AVATAR_ACTION_ATTACK_UP_LEFT, AVATAR_ACTION_ATTACK_DOWN_RIGHT, AVATAR_ACTION_ATTACK_DOWN_LEFT, AVATAR_ACTION_DIE }; public: AvatarModel(); virtual ~AvatarModel(); public: const float getLifePoints(){ return m_lifePoints;} void setLifePoints(float lifePoints){ m_lifePoints = lifePoints;} virtual AvatarState getState(){return m_state;} virtual void setState(AvatarState state){m_state = state;} virtual AvatarAction getAction(){return m_action;} virtual void setAction(AvatarAction action){m_action = action; } const float getTimeout(){ return m_timeout;}; void setTimeout(float timeout){m_timeout = timeout;} void setTerrainPosition(const Vector4& terrainPosition) { m_terrainPosition = terrainPosition; } const Vector4& getTerrainPosition() const { return m_terrainPosition; } const Vector4 getScreenPosition() const { return m_terrainPosition*PIXELS_PER_METER; } void setScreenPosition(const Vector4& screenPosition) { m_terrainPosition = screenPosition * (float)(1/ (float)PIXELS_PER_METER); } void setStep(const float &stepX, const float &stepY){ m_stepX = stepX; m_stepY = stepY; } void getStep(float *stepX, float *stepY){ *stepX = m_stepX; *stepY = m_stepY; } void setPixelWidth(int width){ m_pixelWidth = width; } const int getPixelWidth(){return m_pixelWidth;} void setPixelHeight(int height){ m_pixelHeight = height; } const int getPixelHeight(){return m_pixelHeight;} void setRect(const Rect rect){ m_rect = rect; } const Rect getRect(){return m_rect;} virtual float getCelerity() = 0; protected: AvatarState m_state; AvatarAction m_action; Vector4 m_terrainPosition; Vector4 m_screenPosition; float m_timeout; float m_stepX; float m_stepY; float m_lifePoints; int m_pixelWidth; int m_pixelHeight; Rect m_rect; };
// // rvHeapArena.h - Heap arena object that manages a set of heaps // Date: 12/13/04 // Created by: Dwight Luetscher // #ifndef __RV_HEAP_ARENA_H__ #define __RV_HEAP_ARENA_H__ class rvHeap; // Define some limits used by a heap arena static const int maxNumHeapsPerArena = 16; // maximum number of heaps that can be simultaneously initialized with the same arena static const int maxHeapStackDepth = maxNumHeapsPerArena*2; // maximum depth of each arena's heap stack class rvHeapArena { public: rvHeapArena(); // constructor ~rvHeapArena(); // destructor void Init( ); // initializes this heap arena for use void Shutdown( ); // releases this heap arena from use (shutting down all associated heaps) ID_INLINE bool IsInitialized( ) const; // returns true if this rvHeapArena object is currently initialized and not released, false otherwise // Push the current heap through the heap object itself (you can Pop() there as well) void Pop( ); // pops the top of the stack, restoring the previous heap as the active heap for this arena ID_INLINE bool IsStackFull( ); // returns true if the heap arena stack is full, false otherwise ID_INLINE rvHeap *GetActiveHeap( ); // returns the active heap for this arena (from the top of the stack, NULL if stack is empty) ID_INLINE void EnterArenaCriticalSection(); // enters this heap arena's critical section ID_INLINE void ExitArenaCriticalSection(); // exits this heap arena's critical section void *Allocate( unsigned int sizeBytes, int debugTag = 0); // allocates the given amount of memory from this arena void *Allocate16( unsigned int sizeBytes, int debugTag = 0); // allocates the given amount of memory from this arena, aligned on a 16-byte boundary void Free( void *p ); // free memory back to this arena int Msize( void *p ); // returns the size, in bytes, of the allocation at the given address (including header, alignment bytes, etc). rvHeap *GetHeap( void *p ); // returns the heap that the given allocation was made from, NULL for none ID_INLINE rvHeap *GetFirstHeap( ); // returns the first heap associated with this arena, NULL for none rvHeap *GetNextHeap( rvHeap &rfPrevHeap ); // returns that follows the given one (associated with this arena), NULL for none void GetTagStats(int tag, int &num, int &size, int &peak); // returns the total stats for a particular tag type (across all heaps managed by this arena) protected: // NOTE: we cannot use idList here - dynamic memory is not yet available. rvHeap *m_heapStack[maxHeapStackDepth]; // stack of heap object pointers CRITICAL_SECTION m_criticalSection; // critical section associated with this heap int m_tos; // top of stack rvHeap *m_heapList; // linked-list of all the heaps that are actively associated with this arena bool m_isInitialized; // set to true if this rvHeapArena object is currently initialized and not released void ResetValues( ); // resets the data members to their pre-initialized state friend class rvHeap; // give the rvHeap class access to the following methods // { void Push( rvHeap &newActiveHeap ); // pushes the given heap onto the top of the stack making it the active one for this arena void InitHeap( rvHeap &newActiveHeap ); // initializes the given heap to be under the care of this arena void ShutdownHeap( rvHeap &newActiveHeap ); // releases the given heap from the care of this arena // } }; // IsInitialized // // returns: true if this rvHeapArena object is currently initialized and not released, false otherwise ID_INLINE bool rvHeapArena::IsInitialized( ) const { return m_isInitialized; } // EnterArenaCriticalSection // // enters this heap arena's critical section ID_INLINE void rvHeapArena::EnterArenaCriticalSection() { ::EnterCriticalSection( &m_criticalSection ); } // ExitArenaCriticalSection // // exits this heap arena's critical section ID_INLINE void rvHeapArena::ExitArenaCriticalSection() { ::LeaveCriticalSection( &m_criticalSection ); } // IsStackFull // // returns: true if the heap arena stack is full, false otherwise ID_INLINE bool rvHeapArena::IsStackFull( ) { bool full; EnterArenaCriticalSection(); full = m_tos >= (maxHeapStackDepth - 1); ExitArenaCriticalSection(); return full; } // GetActiveHeap // // returns: the active heap for this arean (from the top of the stack, NULL if stack is empty) ID_INLINE rvHeap *rvHeapArena::GetActiveHeap( ) { rvHeap *tos; EnterArenaCriticalSection(); if ( m_tos < 0 ) { ExitArenaCriticalSection(); return NULL; } tos = m_heapStack[ m_tos ]; ExitArenaCriticalSection(); return tos; } // GetFirstHeap // // returns: the first heap associated with this arena, NULL for none ID_INLINE rvHeap *rvHeapArena::GetFirstHeap( ) { rvHeap *firstHeap; EnterArenaCriticalSection(); firstHeap = m_heapList; ExitArenaCriticalSection(); return firstHeap; } #endif // #ifndef __RV_HEAP_MANAGER_H__
//renderworld.hpp //Contains quasi-real world objects needed for rendering //Created by Lewis Hosie //17-11-11 //This class is a little tricky to define, but I'll basically leave it at "it contains lights, // occluders, particles and other things that have a graphical manifestation in the world but // do not interact with it." They do not go in world because they don't physically exist. They // do not go in renderer because that's just a GL interface. They do not go in worldrenderer // because that's just an even more complex GL interface. #ifndef E_RENDERWORLD #define E_RENDERWORLD #include "fvec2.hpp" #include "light.hpp" #include "occluder.hpp" #include <vector> #include <list> #define CAMSPEED 10.0f typedef std::list<occluder> occluderlist; typedef std::list<light> lightlist; class camera{ fvec3 position; fvec3 orientation; public: void setposition(fvec3 newpos){ position=newpos; } void setorientation(fvec3 newor){ orientation=newor; } const fvec3 getposition() const{ return position; } const fvec3 getorientation() const{ return orientation; } void tick(world& theworld){ position =((position*(CAMSPEED-1.0f))+(theworld.gettheplayer().getragdollinstance().getpos()+fvec3(0.0f,7.5f,3.5f)))/CAMSPEED; } }; class renderworld{ camera thecamera; lightlist thelights; occluderlist theoccluders; public: renderworld(){ /*light n; n.worldstart=fvec3(-4.0f,0.0f,5.0f); n.worldend=fvec3(0.0f,0.0f,5.0f); n.color=fvec3(1.0f,0.0f,0.0f); n.size=6.0f; n.brightness=1.0f; thelights.push_back(n);*/ //FIXME: Load these from a level format of some kind light g; g.worldstart=fvec3(-10.0f,0.0f,-10.0f); g.worldend=fvec3(-10.0f,0.0f,10.0f); g.color=fvec3(1.0f,1.0f,0.0f); g.size=15.0f; g.brightness=1.0f; thelights.push_back(g); g.worldstart=fvec3(-6.0f,0.0f,-5.0f); g.worldend=fvec3(-3.0f,0.0f,-5.0f); g.color=fvec3(0.0f,0.0f,1.0f); g.size=10.0f; g.brightness=1.0f; thelights.push_back(g); /*occluder b; b.worldstart=fvec3(-6.0f,0.0f,-5.0f); b.worldend=fvec3(-6.0,0.0f,3.0f); b.type=occtype_quad; theoccluders.push_back(b);*/ thecamera.setposition(fvec3(0.0f,-5.0f,0.0f)); thecamera.setorientation(fvec3(60.0f,0.0f,0.0f)); } occluder& addoccluder(fvec3 start, fvec3 end, int type){ occluder b; b.worldorigin=start; b.worldstart=start; b.worldend=end; b.type=type; b.radius=0.3f; theoccluders.push_back(b); occluderlist::iterator m = theoccluders.end(); m--; return *m; } const lightlist& getlights() const { return thelights; } const occluderlist& getoccluders() const { return theoccluders; } const camera& getthecamera() const{ return thecamera; } void calculatelighteyelocations(renderer &therenderer){ for(lightlist::iterator m = thelights.begin(); m!=thelights.end(); ++m) m->calculateeyelocation(therenderer); } void calculateocceyelocations(renderer &therenderer, const light& thelight, const fvec3& upvec){ for(occluderlist::iterator n = theoccluders.begin(); n!=theoccluders.end(); ++n) n->calculateeyelocation(therenderer, thelight, upvec); } int numlights(){ return static_cast<int>(thelights.size()); } int numoccluders(){ return static_cast<int>(theoccluders.size()); } const light& getlight(int lightno) const { lightlist::const_iterator it = thelights.begin(); for(int i=0; i<lightno; i++) it++; return *it; //FIXME: Throw an exception if it doesn't exist } const occluder& getoccluder(int occno) const { occluderlist::const_iterator it = theoccluders.begin(); for(int i=0; i<occno; i++) it++; return *it; //FIXME: Throw an exception if it doesn't exist } void tick(world& theworld){ thecamera.tick(theworld); } }; #endif
// FairMOT.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include "tracker.h" void draw_tracks(cv::Mat&img, std::vector<std::shared_ptr<STrack>>& tracks) { for (auto& tr:tracks) { cv::Rect_<float> loc = tr->to_tlwh_rect(); int color_idx = (tr->track_id) % kColorNum * 4; cv::Scalar_<int> color = cv::Scalar_<int>(kColorArray[color_idx], kColorArray[color_idx + 1], kColorArray[color_idx + 2], kColorArray[color_idx + 3]); cv::rectangle(img, loc, color, 3, cv::LINE_AA, 0); int fontCalibration = cv::FONT_HERSHEY_COMPLEX; float fontScale = 1; int fontThickness = 2; char text[15]; sprintf(text, "%d", tr->track_id); std::string buff = text; putText(img, buff, cv::Point(loc.x, loc.y), fontCalibration, fontScale, color, fontThickness);/**/ } } int main() { DetectorConfig detconfig; detconfig.method = DetectorMethod::FromFile; detconfig.fd.det_list_name = "list.txt"; auto det = std::unique_ptr<Detection>(DetectorFactory::create_object(detconfig)); det->init(); JDETrackerConfig config; config.conf_thres = 0.4f; config.K = 500; config.track_buffer = 30; int frame_rate = 20; JDETracker jde(config, frame_rate); cv::VideoCapture capture; capture.open("test.avi"); cv::Mat frame; std::vector<DetectionBox> vec_db; std::vector<cv::Mat> vec_features; int frame_index = 0; while (true) { capture >> frame; if (frame.empty()) break; det->get_detection(frame, vec_db, vec_features); std::vector<std::shared_ptr<STrack>> tracks = jde.update(vec_db, vec_features); int a = 10; draw_tracks(frame, tracks); // char tmp[100] = { '\0'}; // sprintf(tmp, "tmp/%03d.jpg", frame_index); // std::string save_name = tmp; // cv::imwrite(save_name, frame); cv::imshow("tracking", frame); cv::waitKey(1); frame_index++; } }
#include <GL/glew.h> #include <GL/glut.h> #include <cuda_runtime_api.h> #include <cuda_gl_interop.h> #include <vector_types.h> #include <vector_functions.h> #include <iostream> #include <fstream> #include <vector> #include <string> #include <cmath> #include <AntTweakBar.h> #include "utils.h" #include "cutil_math.h" using namespace std; // Globals --------------------------------------- unsigned int window_width = 800; unsigned int window_height = 600; unsigned int image_width = 800; unsigned int image_height = 600; float delta_t = 0; GLuint pbo; // this pbo is used to connect CUDA and openGL GLuint result_texture; // the ray-tracing result is copied to this openGL texture TriangleMesh mesh; TriangleMesh ground; TriangleMesh sphere; TriangleMesh object; int total_number_of_triangles = 0; float *dev_triangle_p; // the cuda device pointer that points to the uploaded triangles // Camera parameters ----------------------------- float3 a; float3 b; float3 c; float3 campos; float camera_rotation = 0; float camera_distance = 75; float camera_height = 25; bool animate = true; // Scene bounding box ---------------------------- float3 scene_aabbox_min; float3 scene_aabbox_max; float light_x = -23; float light_y = 25; float light_z = 3; float light_color[3] = {1,1,1}; // mouse controls -------------------------------- int mouse_old_x, mouse_old_y; int mouse_buttons = 0; bool left_down = false; bool right_down = false; bool initGL(); bool initCUDA( int argc, char **argv); void initCUDAmemory(); void Terminate(void); void initTweakMenus(); void display(); void reshape(int width, int height); void keyboard(unsigned char key, int x, int y); void KeyboardUpCallback(unsigned char key, int x, int y); void SpecialKey(int key, int x, int y); void mouse(int button, int state, int x, int y); void motion(int x, int y); void rayTrace(); TwBar *bar; // Pointer to the tweak bar void initTweakMenus() { if( !TwInit(TW_OPENGL, NULL) ) { // A fatal error occurred fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError()); exit(0); } bar = TwNewBar("Parameters"); TwAddVarRW(bar, "camera rotation", TW_TYPE_FLOAT, &camera_rotation, " min=-5.0 max=5.0 step=0.01 group='Camera'"); TwAddVarRW(bar, "camera distance", TW_TYPE_FLOAT, &camera_distance, " min= 1.0 max=125.0 step=0.1 group='Camera'"); TwAddVarRW(bar, "camera height", TW_TYPE_FLOAT, &camera_height, " min= -35.0 max= 100.0 step=0.1 group='Camera'"); TwAddVarRW(bar, "light_pos_x", TW_TYPE_FLOAT, &light_x, " min= -100.0 max= 100.0 step=0.1 group='Light_source'"); TwAddVarRW(bar, "light_pos_y", TW_TYPE_FLOAT, &light_y, " min= -100.0 max= 100.0 step=0.1 group='Light_source'"); TwAddVarRW(bar, "light_pos_z", TW_TYPE_FLOAT, &light_z, " min= -100.0 max= 100.0 step=0.1 group='Light_source'"); TwAddVarRW(bar,"light_color",TW_TYPE_COLOR3F, &light_color, " group='Light_source' "); } void Terminate(void) { TwTerminate(); } bool initGL() { glewInit(); if (! glewIsSupported ( "GL_VERSION_4_1 " "GL_ARB_pixel_buffer_object " "GL_EXT_framebuffer_object " )) { fprintf(stderr, "ERROR: Support for necessary OpenGL extensions missing."); fflush(stderr); //return CUTFalse; return false; } // init openGL state glClearColor(0, 0, 0, 1.0); glDisable(GL_DEPTH_TEST); // view-port glViewport(0, 0, window_width, window_height); initTweakMenus(); return true; } bool initCUDA( int argc, char **argv) { cudaGLSetGLDevice(0); return true; } void initCUDAmemory() { // initialize the PBO for transferring data from CUDA to openGL unsigned int num_texels = image_width * image_height; unsigned int size_tex_data = sizeof(GLubyte) * num_texels * 4; void *data = malloc(size_tex_data); // create buffer object glGenBuffers(1, &pbo); glBindBuffer(GL_ARRAY_BUFFER, pbo); glBufferData(GL_ARRAY_BUFFER, size_tex_data, data, GL_DYNAMIC_DRAW); free(data); glBindBuffer(GL_ARRAY_BUFFER, 0); // register this buffer object with CUDA cudaGLRegisterBufferObject(pbo); //CUT_CHECK_ERROR_GL(); // create the texture that we use to visualize the ray-tracing result glGenTextures(1, &result_texture); glBindTexture(GL_TEXTURE_2D, result_texture); // set basic parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // buffer data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); // next we load a simple obj file and upload the triangles to an 1D texture. loadObj("data/cube.obj",mesh,1); loadObj("data/sphere.obj",sphere,1); vector<float4> triangles; for (unsigned int i = 0; i < mesh.faces.size(); i++) { float3 v0 = mesh.verts[mesh.faces[i].v[0]-1]; float3 v1 = mesh.verts[mesh.faces[i].v[1]-1]; float3 v2 = mesh.verts[mesh.faces[i].v[2]-1]; v0.y -= 10.0; v1.y -= 10.0; v2.y -= 10.0; triangles.push_back(make_float4(v0.x,v0.y,v0.z,0)); triangles.push_back(make_float4(v1.x-v0.x, v1.y-v0.y, v1.z-v0.z,0)); // notice we store the edges instead of vertex points, to save some calculations in the triangles.push_back(make_float4(v2.x-v0.x, v2.y-v0.y, v2.z-v0.z,0)); // ray triangle intersection test. } for (unsigned int i = 0; i < sphere.faces.size(); i++) { float3 v0 = sphere.verts[sphere.faces[i].v[0]-1]; float3 v1 = sphere.verts[sphere.faces[i].v[1]-1]; float3 v2 = sphere.verts[sphere.faces[i].v[2]-1]; triangles.push_back(make_float4(v0.x,v0.y,v0.z,0)); triangles.push_back(make_float4(v1.x-v0.x, v1.y-v0.y, v1.z-v0.z,1)); // notice we store the edges instead of vertex points, to save some calculations in the triangles.push_back(make_float4(v2.x-v0.x, v2.y-v0.y, v2.z-v0.z,0)); // ray triangle intersection test. } cout << "total number of triangles check:" << mesh.faces.size() + sphere.faces.size() << " == " << triangles.size()/3 << endl; size_t triangle_size = triangles.size() * sizeof(float4); total_number_of_triangles = triangles.size()/3; if(triangle_size > 0) { cudaMalloc((void **)&dev_triangle_p, triangle_size); cudaMemcpy(dev_triangle_p,&triangles[0],triangle_size,cudaMemcpyHostToDevice); bindTriangles(dev_triangle_p, total_number_of_triangles); } scene_aabbox_min = mesh.bounding_box[0]; scene_aabbox_max = mesh.bounding_box[1]; scene_aabbox_min.x = min(scene_aabbox_min.x,sphere.bounding_box[0].x); scene_aabbox_min.y = min(scene_aabbox_min.y,sphere.bounding_box[0].y); scene_aabbox_min.z = min(scene_aabbox_min.z,sphere.bounding_box[0].z); scene_aabbox_max.x = max(scene_aabbox_max.x,sphere.bounding_box[1].x); scene_aabbox_max.y = max(scene_aabbox_max.y,sphere.bounding_box[1].y); scene_aabbox_max.z = max(scene_aabbox_max.z,sphere.bounding_box[1].z); } void reshape(int width, int height) { // Set OpenGL view port and camera glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (double)width/height, 0.1, 100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Send the new window size to AntTweakBar TwWindowSize(width, height); } void SpecialKey(int key, int x, int y) { switch(key) { case GLUT_KEY_F1: break; }; } void updateCamera() { campos = make_float3(cos(camera_rotation)*camera_distance,camera_height,-sin(camera_rotation)*camera_distance); float3 cam_dir = -1*campos; cam_dir = normalize(cam_dir); float3 cam_up = make_float3(0,1,0); float3 cam_right = cross(cam_dir,cam_up); cam_right = normalize(cam_right); cam_up = -1*cross(cam_dir,cam_right); cam_up = normalize(cam_up); float FOV = 60.0f; float theta = (FOV*3.1415*0.5) / 180.0f; float half_width = tanf(theta); float aspect = (float)image_width / (float)image_height; float u0 = (-1*half_width) * aspect; float v0 = -1*half_width; float u1 = half_width * aspect; float v1 = half_width; float dist_to_image = 1; a = (u1-u0)*cam_right; b = (v1-v0)*cam_up; c = campos + u0*cam_right + v0*cam_up + dist_to_image*cam_dir; if(animate) camera_rotation += 0.25 * delta_t; } void rayTrace() { unsigned int* out_data; cudaGLMapBufferObject( (void**)&out_data, pbo); RayTraceImage(out_data, image_width, image_height, total_number_of_triangles, a, b, c, campos, make_float3(light_x,light_y,light_z), make_float3(light_color[0],light_color[1],light_color[2]), scene_aabbox_min , scene_aabbox_max); cudaGLUnmapBufferObject( pbo); // download texture from destination PBO glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo); glBindTexture(GL_TEXTURE_2D, result_texture); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, image_width, image_height, GL_BGRA, GL_UNSIGNED_BYTE, NULL); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } void displayTexture() { // render a screen sized quad glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); //glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glDepthMask(GL_TRUE); glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0, 0, window_width, window_height); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, 0.5); glTexCoord2f(1.0, 0.0); glVertex3f(1.0, -1.0, 0.5); glTexCoord2f(1.0, 1.0); glVertex3f(1.0, 1.0, 0.5); glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, 0.5); glEnd(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glDisable(GL_TEXTURE_2D); //CUT_CHECK_ERROR_GL(); } void display() { //update the delta time for animation static int lastFrameTime = 0; if (lastFrameTime == 0) { lastFrameTime = glutGet(GLUT_ELAPSED_TIME); } int now = glutGet(GLUT_ELAPSED_TIME); int elapsedMilliseconds = now - lastFrameTime; delta_t = elapsedMilliseconds / 1000.0f; lastFrameTime = now; updateCamera(); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); rayTrace(); displayTexture(); TwDraw(); glutSwapBuffers(); glutPostRedisplay(); } void keyboard(unsigned char key, int /*x*/, int /*y*/) { switch(key) { case ' ': animate = !animate; break; case(27) : Terminate(); exit(0); } } void KeyboardUpCallback(unsigned char key, int x, int y) { if(TwEventKeyboardGLUT(key,x, y)) { return; } } int main(int argc, char** argv) { // Create GL context glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize(window_width,window_height); glutCreateWindow("Parallel Group Raytracer"); // initialize GL if (!initGL()) return 0; // initialize CUDA if (!initCUDA(argc, argv)) return 0; initCUDAmemory(); // register callbacks glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutKeyboardUpFunc(KeyboardUpCallback); glutSpecialUpFunc(SpecialKey); glutReshapeFunc(reshape); // - Directly redirect GLUT mouse button events to AntTweakBar glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT); // - Directly redirect GLUT mouse motion events to AntTweakBar glutMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT); // - Directly redirect GLUT mouse "passive" motion events to AntTweakBar (same as MouseMotion) glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT); // start rendering main-loop glutMainLoop(); cudaThreadExit(); return 0; }
#include "mainwindow.h" #include "./ui_mainwindow.h" #include <QApplication> #include <QLabel> #include <QScreen> #include <QFileDialog> #include <QMenuBar> #include <QStatusBar> #include <QDebug> #include <QToolBar> #include <QHBoxLayout> #include <QStandardPaths> #include <QMimeDatabase> // following include the packages needed for image // transformation #include "itkImage.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) // , ui(new Ui::MainWindow) { cw = new QWidget(); frame = new QVBoxLayout(); pictures = new QHBoxLayout(); haventModifiedPics = new QVBoxLayout(); modifiedPics = new QVBoxLayout(); pictures->addLayout(haventModifiedPics); pictures->addLayout(modifiedPics); pictures->addStretch(); frame->addLayout(pictures); frame->addStretch(); cw->setLayout(frame); setCentralWidget(cw); fileMenu = menuBar()->addMenu(tr("File")); fileToolBar = addToolBar(tr("File")); const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(":resources/images/open.png")); openingAct = new QAction(openIcon,tr("Open..."),this); connect(openingAct,&QAction::triggered,this,&MainWindow::open); openingAct->setShortcut((QKeySequence::Open)); fileMenu->addAction(openingAct); fileToolBar->addAction(openingAct); // const QIcon saveIcon = QIcon::fromTheme("document-save",QIcon(":resources/images/save.png")); // saveAsAct = fileMenu->addAction(tr("Save As..."),this, &MainWindow::saveAs); // saveAsAct->setEnabled(false); fileMenu->addSeparator(); const QIcon exitIcon = QIcon::fromTheme("application-exit"); exitAct = fileMenu->addAction(exitIcon, tr("Exit"), this, &QWidget::close); exitAct->setShortcut(tr("Ctrl+W")); fileToolBar->addAction(exitAct); processMenu = menuBar()->addMenu(tr("Process...")); processAct = new QAction(tr("Process"),this); connect(processAct,&QAction::triggered,this,&MainWindow::process); processMenu->addAction(processAct); FPGAMenu = menuBar()->addMenu(tr("FPGA...")); toFPGAAct = new QAction(tr("To FPGA"),this); connect(toFPGAAct,&QAction::triggered,this,&MainWindow::toFPGA); resize(QGuiApplication::primaryScreen()->availableSize()); FPGAMenu->addAction(toFPGAAct); } void MainWindow::process() { // image = imageToSet; // if (image.colorSpace().isValid()) // image.convertToColorSpace(QColorSpace::SRgb); // xRayImageLabel->setPixmap(QPixmap::fromImage(image)); // xRayScrollArea->setVisible(true); QString folderOfImages = QFileDialog::getExistingDirectory(this, tr("Select Folder of images"), QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); QString save = QFileDialog::getExistingDirectory(this, tr("Select location to save folder of images"), QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); QDir imagesDir(folderOfImages); QDir savedDir(save); // qDebug() << save; // qDebug() << folderOfImages; QList <QFileInfo> fileInfo = imagesDir.entryInfoList(); for (auto info: fileInfo) { // check if its base folder, like /home or / // base folder's baseName is empty // so if not empty, it should be the "real" files/folders if (!info.baseName().isEmpty()) { QMimeDatabase db; QMimeType mime = db.mimeTypeForFile(info,QMimeDatabase::MatchContent); // check if preferredsuffix is the file type we want // can also use suffixes, but will return QStringList // a list of QString if (mime.preferredSuffix() != "mp3") { qDebug() << info.absoluteFilePath(); } } // we can now exclude the files with file format that we dont want // what if have folders inside also } } void MainWindow::open() { const int imageLength = 900; const int imageHeight = 400; QString file = QFileDialog::getOpenFileName(this, tr("Select Images"), QStandardPaths::writableLocation(QStandardPaths::PicturesLocation), "*.jpg *.png"); bool selected = false; if (!file.isEmpty()) { selected = true; } if (selected) { qDebug() << file; QLabel *imageLabel = new QLabel; imageLabel->setFixedSize(imageLength,imageHeight); imageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); QImage image(file); QImage scaled = image.scaled(QSize(imageLength, imageHeight), Qt::KeepAspectRatio, Qt::SmoothTransformation); imageLabel->setPixmap(QPixmap::fromImage(scaled)); haventModifiedPics->addWidget(imageLabel); labels.append(imageLabel); //limit 2 if (labels.length() > 2) { haventModifiedPics->removeWidget(labels.front()); labels.front()->setParent(NULL); labels.pop_front(); } } haventModifiedPics->addStretch(100); } void MainWindow::toFPGA() { // QFileDialog dialog(this,tr("Save File As")); // initializeImageFileDialog(dialog, QFileDialog::AcceptSave); // while (dialog.exec() == QDialog::Accepted && !savingImage(dialog.selectedFiles().first())) {} }
//mnozenie_tablicy.hh #ifndef TABX2_HH #define TABX2_HH /*! * \file * \brief Definicja klasy Tabx2 * * Klasa Tabx2 jest klasa pochodna od klasy Program. * Definiuje metode podawajajaca kazda liczbe znajdujaca sie w tablicy danych * wskazywanej przez zmienna tab klasy Program. */ #include <iostream> #include "program.hh" class Tabx2: public Program{ public: /*! * \brief Metoda wirtualna wykonaj_program. * * Dokonuje przemnozenia przez 2 wszystkich danych znajdujacych sie * w tablicy wskazywanej przez tab. * * \retval TRUE Poprawnie dokonano mnozenia wszystkich liczb * \retval FALSE Rozmiar tablicy danych wynosi 0 */ virtual bool wykonaj_program(); }; #endif
#include <cstdlib> #include <Windows.h> #include <pthread.h> #include <semaphore.h> #include "SaleItem.h" //Function Prototypes void *ProducerFunction (void *); void *ConsumerFunction (void *); void DisplayLocalConsumerData(); void DisplayGlobalStatistics(); //Shared Values const int NUM_ITEMS=100; //This can actually stay constant after program is running const int NUM_PRODUCERS=5; //Represents user input, will change to dynamic const int NUM_CONSUMERS=5; //Represents user input, will change to dynamic const int BSIZE=10; //Represents user input, will change to dynamic int TotalProduced=0, TotalConsumed=0; //global values to track the number produced/consumed int ReadPosition=0, WritePosition=0; //the read/right position in the buffer double StoreTotals[NUM_PRODUCERS]; //Store-wide total sales (Store held in respective index) double MonthTotals[13]; //Month-wide total sales (Month held in respective index) SalesRecord Buffer[BSIZE]; //Used to hold StoreItems Produced Until Consumed /*Problems to overcome with making the above values dynamic: Buffer size is needed to track location of read/write - can make a SaleItem pointer and update size after user input Producer size is needed - Used to create threads(already done dynamically) and consumer must track producer data Consumer size is needed - USed to create threads(already done dynamically) and ConsumerData structs needs number */ sem_t MakeItem, TakeItem; //Semaphore to indicate if buffer is full or has space sem_t ProducedMutex, ConsumedMutex; //Semaphore to ensure mutex on TotalProduced, TotalConsumed sem_t ReadMutex, WriteMutex; //Semaphore to ensure mutex on ReadPosition, WritePosition struct ConsumerData { int ID; //consumer thread ID double ConMonthTotals[13]; //monthly totals for each consumer (index based on month 1-12 used) double ConStoreTotals[NUM_PRODUCERS]; //store totals for each consumer (index based on producer number) }; ConsumerData CData[NUM_CONSUMERS]; //array to hold ConsumeData structs //Pointers to arrays for producerThreads, ConsumerThreads pthread_t * ProducerThreads; pthread_t * ConsumerThreads; int main() { clock_t t1, t2; //time variables for start time and end time t1=clock(); //starting time int rc1, rc2; //return codes if threads fail to create //Create the arrays to hold the producers and consumer threads ProducerThreads=new pthread_t[NUM_PRODUCERS]; ConsumerThreads=new pthread_t[NUM_CONSUMERS]; //initialize the semaphores //parameters for sem_init(pointer to the semaphore, level of sharing, initial value) sem_init(&MakeItem, 0, BSIZE); sem_init(&TakeItem, 0, 0); sem_init(&ReadMutex, 0, 1); sem_init(&WriteMutex, 0, 1); sem_init(&ProducedMutex, 0, 1); sem_init(&ConsumedMutex, 0, 1); //create the consumers for (int t=0; t<NUM_CONSUMERS; t++) { cout<<"Creating consumer thread: "<<t<<endl; rc1=pthread_create(&ConsumerThreads[t], NULL, ConsumerFunction, (void*) t); if (rc1) { cout<<"Error, return code from pthread_create is: "<<rc1<<endl; return 1; } } //create the producers for (int t=0; t<NUM_PRODUCERS; t++) { cout<<"Creating producer thread: "<<t<<endl; rc2=pthread_create(&ProducerThreads[t], NULL, ProducerFunction, (void*) t); if (rc2) { cout<<"Error, return code from pthread_create is: "<<rc2<<endl; return 1; } } //wait for threads to finish for (int i = 0; i < NUM_CONSUMERS; i++) pthread_join(ConsumerThreads[i], NULL); for (int i = 0; i < NUM_PRODUCERS; i++) pthread_join(ProducerThreads[i], NULL); //print the buffer for debugging cout<<"The current buffer (last "<<BSIZE<<" produced):"<<endl; for(int i = 0; i < BSIZE; i++) { Buffer[i].display(); cout <<endl; } cout<<"Total Produced: "<<TotalProduced<<endl; //Display the Local Consumer Data DisplayLocalConsumerData(); //Display the Global Statistics DisplayGlobalStatistics(); //perform cleanup of any dynamically allocated items sem_destroy(&MakeItem); sem_destroy(&TakeItem); sem_destroy(&ReadMutex); sem_destroy(&WriteMutex); sem_destroy(&ProducedMutex); sem_destroy(&ConsumedMutex); t2=clock(); //ending time float diff ((float)t2-(float)t1); cout<<"The Total Run Time Was: "<<diff/CLOCKS_PER_SEC<<" Seconds."<<endl; system("pause"); return 0; } void *ProducerFunction (void *t) { int ProducerID=(long)t; cout<<"Producer: "<<ProducerID<<" started"<<endl; //pick a new random seed for each thread srand((int)time(NULL)^(int)ProducerID); //infinate loop until treads complete while(1) { sem_wait(&ProducedMutex); //All producers wait while checking the number produced if (TotalProduced==NUM_ITEMS) //Check NUM_ITEMS has been produced yet { sem_post(&ProducedMutex); //Remove wait after answer is known cout<<"Producer: "<<ProducerID<<" done"<<endl; pthread_exit(NULL); //Exit thread if true } TotalProduced++; //Increment since an item will be produced when thread has opportunity sem_post(&ProducedMutex); //Remove wait after TotalProduced is updated sem_wait(&MakeItem); //Do Nothing - wait for signal from consumers to make an item //No longer waiting - there is now free buffer space sem_wait(&WriteMutex); //Other producers wait while the buffer is written to and WritePostion is changed Buffer[WritePosition]=SalesRecord(ProducerID); WritePosition=(WritePosition+1)%BSIZE; sem_post(&WriteMutex); //Remove wait on buffer and WritePosition sem_post(&TakeItem); //Signal waiting consumers it's ok to take an item Sleep(int(rand()%36)+5); //randomly sleep for 5-40 milliseconds } return 0; } void *ConsumerFunction (void *t) { int ConsumerID=(long)t; cout<<"Consumer: "<<ConsumerID<<" started"<<endl; //infinate loop until threads complete while(1) { sem_wait(&ConsumedMutex); //All consumers wait while checking the number consumed if(TotalConsumed==NUM_ITEMS) { sem_post(&ConsumedMutex); //Remove wait after answer is known cout<<"Consumer: "<<ConsumerID<<" done"<<endl; pthread_exit(NULL); //Exit thread if true } TotalConsumed++; //Increment since an item will be consumed when thread has opportunity sem_post(&ConsumedMutex); //Remove wait after TotalConsumed is updated this_thread:sleep:(10); sem_wait(&TakeItem); //Do Nothing - wait for signal from producer that an item is available //No longer waiting on item to be made sem_wait(&ReadMutex); //Other consumers wait while the item is being read and ReadPosition is changed CData[ConsumerID].ID=ConsumerID; CData[ConsumerID].ConMonthTotals[Buffer[ReadPosition].getMonth()]+=Buffer[ReadPosition].getSaleAmount(); CData[ConsumerID].ConStoreTotals[Buffer[ReadPosition].getStoreID()]+=Buffer[ReadPosition].getSaleAmount(); ReadPosition=(ReadPosition+1)%BSIZE; sem_post(&ReadMutex); //Remove wait on buffer and ReadPosition sem_post(&MakeItem); //Signal Producers that it's ok to make an item } return 0; } void DisplayLocalConsumerData() { for (int i=0; i<NUM_CONSUMERS; i++) { cout<<"========================================================"<<endl; cout<<"Local Consumer Data Report - Consumer: "<<CData[i].ID<<endl; cout<<"========================================================"<<endl; cout<<"Monthly Totals:"<<endl; cout<<"========================================================"<<endl; cout<<"Jan = $"<<CData[i].ConMonthTotals[1]<<endl; cout<<"Feb = $"<<CData[i].ConMonthTotals[2]<<endl; cout<<"Mar = $"<<CData[i].ConMonthTotals[3]<<endl; cout<<"Apr = $"<<CData[i].ConMonthTotals[4]<<endl; cout<<"May = $"<<CData[i].ConMonthTotals[5]<<endl; cout<<"Jun = $"<<CData[i].ConMonthTotals[6]<<endl; cout<<"Jul = $"<<CData[i].ConMonthTotals[7]<<endl; cout<<"Aug = $"<<CData[i].ConMonthTotals[8]<<endl; cout<<"Sep = $"<<CData[i].ConMonthTotals[9]<<endl; cout<<"Oct = $"<<CData[i].ConMonthTotals[10]<<endl; cout<<"Nov = $"<<CData[i].ConMonthTotals[11]<<endl; cout<<"Dec = $"<<CData[i].ConMonthTotals[12]<<endl<<endl; cout<<"========================================================"<<endl; cout<<"Store Totals:"<<endl; cout<<"========================================================"<<endl; for (int j=0; j<NUM_PRODUCERS; j++) { cout<<"Store "<<j<<" = $"<<CData[i].ConStoreTotals[j]<<endl; } cout<<endl<<endl; } } void DisplayGlobalStatistics() { //store totals for (int i=0; i<NUM_PRODUCERS; i++) { for (int j=0; j<NUM_CONSUMERS; j++) { StoreTotals[i]+=CData[j].ConStoreTotals[i]; } } cout<<"========================================================"<<endl; cout<<"Global Store Statistics: "<<endl; cout<<"========================================================"<<endl; for (int i=0; i<NUM_PRODUCERS; i++) { cout<<"Store "<<i<<" = $"<<StoreTotals[i]<<endl; } //month Totals for (int i=0; i<13; i++) { for (int j=0; j<NUM_CONSUMERS; j++) { MonthTotals[i]+=CData[j].ConMonthTotals[i]; } } cout<<"========================================================"<<endl; cout<<"Global Monthly Statistics: "<<endl; cout<<"========================================================"<<endl; cout<<"Jan = $"<<MonthTotals[1]<<endl; cout<<"Feb = $"<<MonthTotals[2]<<endl; cout<<"Mar = $"<<MonthTotals[3]<<endl; cout<<"Apr = $"<<MonthTotals[4]<<endl; cout<<"May = $"<<MonthTotals[5]<<endl; cout<<"Jun = $"<<MonthTotals[6]<<endl; cout<<"Jul = $"<<MonthTotals[7]<<endl; cout<<"Aug = $"<<MonthTotals[8]<<endl; cout<<"Sep = $"<<MonthTotals[9]<<endl; cout<<"Oct = $"<<MonthTotals[10]<<endl; cout<<"Nov = $"<<MonthTotals[11]<<endl; cout<<"Dec = $"<<MonthTotals[12]<<endl<<endl; }
// Copyright 2020 Fuji-Iot authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FUJI_AC_UNIT_SIM_H_ #define FUJI_AC_UNIT_SIM_H_ #include <bits/stdint-uintn.h> #include <gtest/gtest_prod.h> #include <array> #include <memory> #include "protocol/fuji_frame.h" namespace fuji_iot { namespace sim { // Simulates real AC unit. // May be used in server application to verify code correctness and create // integration tests. class FujiAcUnitSim { public: FujiAcUnitSim(); const FujiMasterFrame GetNextMasterFrame(); void PushControllerFrame(const FujiControllerFrame &frame); // Methods below are intended to real AC unit side state of the universe. // Changing values is simulated as if IR controller was used. bool Enabled() const; void SetEnabled(bool enabled); mode_t Mode() const; void SetMode(mode_t mode); fan_t Fan() const; void SetFan(fan_t fan); uint8_t Temperature() const; void SetTemperature(uint8_t temp); bool Economy() const; void SetEconomy(bool economy); bool Swing() const; void SetSwing(bool swing); bool SwingStep() const; void SetSwingStep(bool swing); bool ControllerPresent() const; protected: FRIEND_TEST(FujiAcUnitSimTest, TestReconnect); FRIEND_TEST(FujiAcUnitSimTest, RemoteTurnOnTurnOff); FRIEND_TEST(FujiAcUnitSimTest, TestGolden); FRIEND_TEST(FujiAcUnitSimTest, TurnOn); FRIEND_TEST(FujiAcUnitSimTest, WiredControlGolden); std::unique_ptr<FujiStatusRegister> status_; private: void Update(); std::array<uint8_t, 8> status_register_; std::array<uint8_t, 8> error_register_; std::array<uint8_t, 8> login_register_; RegisterType next_query_register_; }; } // namespace sim } // namespace fuji_iot #endif
#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 int seven_ans = 56; struct point { int t,step,la; }; bool vis[20001000]; int bit(int k) { return (k-1)*3; } bool pass(int nloc,int nk,int t) { for (int k = 1;k < nk; k++) { int loc = (t >> bit(k))%8; if (nloc == loc) return false; } return true; } map<int,int> dic; int a[10],b[10]; point Q[10000000]; int main() { int t; scanf("%d",&t); while (t--) { memset(vis,0,sizeof(vis)); int n,k,ed = 0,ans = -1; scanf("%d",&n); dic.clear(); for (int i = 0;i < n; i++) {scanf("%d",&a[i]);b[i] = a[i];} sort(a,a+n); for (int i = 0;i < n; i++) dic[a[i]] = i+1; point p; p.t = 0;p.step = 0,p.la = -1; for (int i = 0;i < n; i++) { k = dic[b[i]]; p.t += i << bit(k); ed += i << bit(i+1); } printf("%d\n",p.t); if (p.t == ed) ans = 0; else { Q[0] = p;vis[p.t] = true; int ps = 0,pd = 1; while (ps < pd) { point p = Q[ps++]; //printf("%o %d\n",p.t,p.step); int visloc = (1 << n) - 1; for (int k = 1;k <= n; k++) { int loc = (p.t >> bit(k))%8; if (visloc & (1 << loc)) { visloc -= (1 << loc); int nt; if (loc > 0) { nt = p.t - (1 << bit(k)); if (!vis[nt] && pass(loc-1,k,nt)) { Q[pd++] = (point){nt,p.step+1,ps-1};vis[nt] = true; if (nt == ed) {ans = p.step+1;goto lambel;} } } if (loc < n-1) { nt = p.t + (1 << bit(k)); if (!vis[nt] && pass(loc+1,k,nt)) { Q[pd++] = (point){nt,p.step+1,ps-1};vis[nt] = true; if (nt == ed) {ans = p.step+1;goto lambel;} } } } } } } lambel: printf("%d\n",ans); } return 0; }
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/ml/ml.hpp> #include <opencv2/opencv.hpp> using namespace cv; #include <algorithm> #include <errno.h> #include <fcntl.h> /* File control definitions */ #include <iostream> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/ioctl.h> #include <sys/time.h> #include <termios.h> /* POSIX terminal control definitions */ #include <unistd.h> #include <vector> #include <cv_bridge/cv_bridge.h> #include <image_transport/image_transport.h> #include <ros/ros.h> #include <std_msgs/Bool.h> #include <std_msgs/Int16MultiArray.h> #define PC 0 #define MANIFOLD 1 //#define VIDEO_FILE 0 //#define VIDEO_CAMERA 1 #define NO_SHOW 0 #define SHOW_ALL 1 #define RECORD_OFF 0 #define RECORD_ON 1 #define OPENMP_STOP 0 #define OPENMP_RUN 1 #define PI 3.14159265358979323 #if defined __arm__ # define PLATFORM MANIFOLD #else # define PLATFORM PC #endif #define DRAW SHOW_ALL #define RECORD RECORD_ON #define OPENMP_SWITCH OPENMP_STOP using std::copy; using std::cout; using std::endl; using std::sort; using std::string; using std::vector; bool compareRect(const Rect& r1, const Rect& r2); bool compareRectX(const Rect& r1, const Rect& r2);
#include<iostream> #include<fstream> #include<sstream> #include<string> #include<list> #include<rapidxml.hpp> #include<rapidxml_print.hpp> bool openXML(std::string path, rapidxml::xml_document<> &xml); std::string openHTML(std::string path); std::string get_resources(rapidxml::xml_document<> &xml); std::string get_text(rapidxml::xml_document<> &xml); int main() { rapidxml::xml_document<> xml; rapidxml::xml_document<> resource_file; rapidxml::xml_document<>contain_file; openXML("./container.xml", xml); std::string resource_file_name = get_resources(xml); if(resource_file_name.compare("") == 0) { // return -1; } else{ openXML(resource_file_name, resource_file); print(std::cout, resource_file, 0); } std::cout<<"-------------------------------------------------------------------"<<std::endl; std::cout<<"-------------------------------------------------------------------"<<std::endl; std::cout<<"-------------------------------------------------------------------"<<std::endl; std::string contain_file_name = get_text(resource_file); //openXML(contain_file_name,contain_file); //print(std::cout,contain_file,0); return 0; } bool openXML(std::string path, rapidxml::xml_document<> &xml) { std::ifstream file(path); std::stringstream buffer; if(file){ buffer << file.rdbuf(); file.close(); std::string content = buffer.str(); xml.parse<0>((char*)&content[0]); return true; } return false; } std::string get_resources(rapidxml::xml_document<> &xml) { rapidxml::xml_node<> * root_node = xml.first_node("container"); if(root_node == 0) return ""; rapidxml::xml_node<> * rootfiles_node = root_node->first_node("rootfiles"); rapidxml::xml_node<> * rootfile_node = rootfiles_node->first_node("rootfile"); rapidxml::xml_attribute<> * path_attribute = rootfile_node->first_attribute("full-path"); if(path_attribute != 0) return path_attribute->value(); else return ""; } std::string get_text(rapidxml::xml_document<> &xml) { rapidxml::xml_node<> * package_node = xml.first_node("package"); rapidxml::xml_node<> * manifest_node =package_node->first_node("manifest"); for(rapidxml::xml_node<> * items_node = manifest_node->first_node("item"); items_node; items_node = items_node->next_sibling()) { // if (items_node != 0) { rapidxml::xml_attribute<> * path_attribute = items_node->first_attribute("href"); rapidxml::xml_document<>contain_file; std::string name; name = path_attribute->value(); if((path_attribute != 0) && !(name.empty())) { std::cout<<name <<std::endl; std::cout<<openHTML(name); // } //if(path_attribute != 0) // return path_attribute->value(); // else return ""; } } return ""; } std::string openHTML(std::string path) { std::ifstream file(path); std::stringstream buffer; if(file){ buffer << file.rdbuf(); file.close(); std::string content = buffer.str(); return content; } return ""; }
// BloomFilter.cpp : Defines the entry point for the console application. // #include "stdafx.h" /* http://blog.michaelschmatz.com/2016/04/11/how-to-write-a-bloom-filter-cpp/ Data structures which can efficiently determine whether an element is possible a member of a set or definitely not a member of a set. Two parameters used to construct the Bloom filter: filter size (in bits), number of hash functions to use. */ // Structure contains a constructor, a function to add an // item to the bloom filter, and a function to query for an item struct BloomFilter { BloomFilter(uint64_t size, uint8_t numHashes); void add(const uint8_t *data, std::size_t len); bool possiblyContains(const uint8_t *data, std::size_t len); private: uint64_t m_size; // filter size in bits uint8_t m_numHashes; // number of hash functions to use std::vector<bool> m_bits; // space efficient (one bit per element) }; // constructor, records parameters and resizes bit array BloomFilter::BloomFilter(uint64_t size, uint8_t numHashes) : m_size(size), m_numHashes(numHashes) { m_bits.resize(size); } // 128 hash calculation function declaration std::array<uint64_t, 2> hash(const uint8_t *data, std::size_t len) { std::array<uint64_t, 2> hashValue; MurmurHash3_x64_128(data, len, 0, hashValue.data()); return hashValue; } // function to return output to the n^th hash function inline uint64_t nthHash(uint8_t n, uint64_t hashA, uint64_t hashB, uint64_t filterSize) { return (hashA + n * hashB) % filterSize; } // set bits for item void BloomFilter::add(const uint8_t *data, std::size_t len) { auto hashValues = hash(data, len); for (int n = 0; n < m_numHashes; n++) { m_bits[nthHash(n, hashValues[0], hashValues[1], m_size)] = true; } } // check bits for item bool BloomFilter::possiblyContains(const uint8_t *data, std::size_t len) { auto hashValues = hash(data, len); for (int n = 0; n < m_numHashes; n++) { if (!m_bits[nthHash(n, hashValues[0], hashValues[1], m_size)]) { return false; } } return true; } int _tmain(int argc, _TCHAR* argv[]) { BloomFilter filter(((uint64_t)256), ((uint8_t)13)); filter.add(((const uint8_t*)64), ((size_t)64)); filter.possiblyContains(((const uint8_t*)64), ((size_t)64)); return 0; }
#pragma once namespace func_math { // 범위제한 template <typename type> static type Clamp(type src, type min, type max) { if (min > max) swap(min, max); if (min > src) return min; if (max < src) return max; return src; } } namespace func_dir { static bool CheckDirectory(wstring path) { DWORD result = GetFileAttributes(path.c_str()); // 경로가 잘못됨 if (result == INVALID_FILE_ATTRIBUTES) return false; // 디렉토리 if (result & FILE_ATTRIBUTE_DIRECTORY) return true; // 디렉토리는 아님 return false; } } namespace func_shader { // Buffer static void CreateBuffer(ID3D11Device* device, D3D11_BIND_FLAG flag, UINT byteWidth, D3D11_USAGE usage, void* data, ID3D11Buffer** buffer) { D3D11_BUFFER_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(D3D11_BUFFER_DESC)); bufferDesc.BindFlags = flag; bufferDesc.ByteWidth = byteWidth; bufferDesc.Usage = usage; if (usage == D3D11_USAGE_DYNAMIC) bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; else bufferDesc.CPUAccessFlags = 0; if (data != NULL) { D3D11_SUBRESOURCE_DATA bufferData; ZeroMemory(&bufferData, sizeof(D3D11_SUBRESOURCE_DATA)); bufferData.pSysMem = data; HRESULT hr = device->CreateBuffer(&bufferDesc, &bufferData, buffer); assert(SUCCEEDED(hr)); } else { HRESULT hr = device->CreateBuffer(&bufferDesc, NULL, buffer); assert(SUCCEEDED(hr)); } } static void SetConstantBuffer(ID3D11DeviceContext* context, ID3D11Buffer* buffer, const void* data, UINT dataSize, UINT startSlot) { D3D11_MAPPED_SUBRESOURCE mapped; HRESULT hr = context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); assert(SUCCEEDED(hr)); memcpy(mapped.pData, data, (size_t)dataSize); // 공용버퍼 (Pcb.fx) // 0 - World // 1 - Camera // 2 - Light context->Unmap(buffer, 0); context->VSSetConstantBuffers(startSlot, 1, &buffer); context->HSSetConstantBuffers(startSlot, 1, &buffer); context->DSSetConstantBuffers(startSlot, 1, &buffer); context->PSSetConstantBuffers(startSlot, 1, &buffer); } static void UpdateVertexBuffer(ID3D11DeviceContext* context, ID3D11Buffer* buffer, const void* data, UINT dataSize) { D3D11_MAPPED_SUBRESOURCE mapped; HRESULT hr = context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); assert(SUCCEEDED(hr)); memcpy(mapped.pData, data, (size_t)dataSize); context->Unmap(buffer, 0); } // Texture static void LoadImageInfo(D3DX11_IMAGE_LOAD_INFO* loadInfo, bool grayscaled, bool textureArray) { // 미리설정한 이미지로드시 desc DXGI_FORMAT format; if (gCFTexture.CompressedFormat) { /* DXGI_FORMAT_BC1_UNORM 세가지 색상, 1비트 알파 DXGI_FORMAT_BC2_UNORM 세가지 색상, 4비트 알파 DXGI_FORMAT_BC3_UNORM 세가지 색상, 8비트 알파 DXGI_FORMAT_BC4_UNORM 하나의 색상 (그레이스케일) DXGI_FORMAT_BC5_UNORM 두가지 색상 DXGI_FORMAT_BC6H_UF16 압축된 HDR이미지 자료 DXGI_FORMAT_BC7_UNORM 고품질 RGBA압축 (노멀맵의 압축에 의한 오차가 줄어듬) */ if (grayscaled) format = DXGI_FORMAT_BC4_UNORM; else format = DXGI_FORMAT_BC3_UNORM; } else format = DXGI_FORMAT_FROM_FILE; // 기본설정으로 File원본로드 (추가적으로 format의 설정값을 통해 압축형식을 지정할 수 있으며, 이는 gpu메모리 요구량을 줄일 수 있다.) loadInfo->Width = D3DX11_FROM_FILE; loadInfo->Height = D3DX11_FROM_FILE; loadInfo->Depth = D3DX11_FROM_FILE; loadInfo->FirstMipLevel = 0; loadInfo->MipLevels = D3DX11_FROM_FILE; loadInfo->Format = format; loadInfo->Filter = D3DX11_FILTER_NONE; loadInfo->MipFilter = D3DX11_FILTER_LINEAR; loadInfo->pSrcInfo = 0; // 배열로 설정시, 추가 업데이트를 위해 다음 플래그에 대해 추가설정값을 적용 if (textureArray) { loadInfo->Usage = D3D11_USAGE_STAGING; loadInfo->BindFlags = 0; loadInfo->CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; loadInfo->MiscFlags = 0; } } static void CreateShaderResourceView(ID3D11Device* device, wstring textureName, wstring extensionName, ID3D11ShaderResourceView** srv, bool grayscaled = false) { wstring path = L"Data\\Texture\\" + textureName + L"." + extensionName; D3DX11_IMAGE_LOAD_INFO loadInfo; LoadImageInfo(&loadInfo, grayscaled, false); HRESULT hr = D3DX11CreateShaderResourceViewFromFile(device, path.c_str(), &loadInfo, NULL, srv, NULL); assert(SUCCEEDED(hr)); //// 실제로 설정한 format이 적용됬는지 확인 //ID3D11Texture2D* texture = NULL; //(*srv)->GetResource((ID3D11Resource**)&texture); //D3D11_TEXTURE2D_DESC textureDesc; //ZeroMemory(&textureDesc, sizeof(D3D11_TEXTURE2D_DESC)); //texture->GetDesc(&textureDesc); } static void CreateShaderResourceViewArray(ID3D11Device* device, ID3D11DeviceContext* context, vector<wstring> textureNames, wstring extensionName, ID3D11ShaderResourceView** srvArray, bool grayscaled = false) { // extensionName 사용은 안되지만 명시적 확인용으로 남겨둠 size_t size = textureNames.size(); D3DX11_IMAGE_LOAD_INFO loadInfo; LoadImageInfo(&loadInfo, grayscaled, true); // Texture2D 생성 vector<ID3D11Texture2D*> source; source.resize(size); HRESULT hr; for(UINT i = 0; i < size; ++i) { hr = D3DX11CreateTextureFromFile(device, textureNames[i].c_str(), &loadInfo, NULL, (ID3D11Resource**)&source[i], NULL); assert(SUCCEEDED(hr)); } // 이미지의 desc D3D11_TEXTURE2D_DESC sourceDesc; source[0]->GetDesc(&sourceDesc); // 이미지배열의 desc D3D11_TEXTURE2D_DESC destDesc; ZeroMemory(&destDesc, sizeof(D3D11_TEXTURE2D_DESC)); destDesc.Width = sourceDesc.Width; destDesc.Height = sourceDesc.Height; destDesc.MipLevels = sourceDesc.MipLevels; destDesc.ArraySize = (UINT)size; destDesc.Format = sourceDesc.Format; destDesc.SampleDesc.Count = 1; destDesc.SampleDesc.Quality = 0; destDesc.Usage = D3D11_USAGE_DEFAULT; destDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; destDesc.CPUAccessFlags = 0; destDesc.MiscFlags = 0; // 배열생성 ID3D11Texture2D* textureArray = NULL; hr = device->CreateTexture2D(&destDesc, 0, &textureArray); assert(SUCCEEDED(hr)); // ** 해상도가 다른 파일끼리는 배열로 묶이지 않음 for(UINT element = 0; element < (UINT)size; element++) { for(UINT mipLevel = 0; mipLevel < sourceDesc.MipLevels; mipLevel++) { D3D11_MAPPED_SUBRESOURCE mapped; hr = context->Map(source[element], mipLevel, D3D11_MAP_READ, 0, &mapped); assert(SUCCEEDED(hr)); context->UpdateSubresource ( textureArray, D3D11CalcSubresource(mipLevel, element, sourceDesc.MipLevels), NULL, mapped.pData, mapped.RowPitch, mapped.DepthPitch ); context->Unmap(source[element], mipLevel); } } // SRV desc설정 D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = destDesc.Format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; srvDesc.Texture2DArray.MostDetailedMip = 0; srvDesc.Texture2DArray.MipLevels = destDesc.MipLevels; srvDesc.Texture2DArray.FirstArraySlice = 0; srvDesc.Texture2DArray.ArraySize = (UINT)size; device->CreateShaderResourceView(textureArray, &srvDesc, srvArray); SafeReleaseCom(textureArray); for (UINT i = 0; i < size; ++i) { SafeReleaseCom(source[i]); } } static void CreateShaderResourceViewFromData(ID3D11Device* device, D3D11_TEXTURE2D_DESC desc, const void* data, ID3D11ShaderResourceView** srv) { D3D11_SUBRESOURCE_DATA texData; ZeroMemory(&texData, sizeof(D3D11_SUBRESOURCE_DATA)); texData.pSysMem = data; texData.SysMemPitch = sizeof(FLOAT) * desc.Width; texData.SysMemSlicePitch = 0; ID3D11Texture2D* texture = NULL; device->CreateTexture2D(&desc, &texData, &texture); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = DXGI_FORMAT_R32_FLOAT; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = -1; device->CreateShaderResourceView(texture, &srvDesc, srv); SafeReleaseCom(texture); } } namespace func_data { static void GetBYTEFromFile(wstring path, size_t size, vector<BYTE>* data) { vector<BYTE> temp; temp.resize(size); ifstream file; file.open(path.c_str(), ios_base::binary); assert(!file.fail()); file.read((char*)&temp[0], (streamsize)temp.size()); file.close(); *data = temp; } }
// // Created by YCJ on 2020/7/6. // #ifndef COMPLIER_GRAMMARACTION_H #define COMPLIER_GRAMMARACTION_H #include "..\type\quatName.h" #include "..\XTable\FunSheet.h" #include <bits/stdc++.h> using namespace std; //语义动作,纯函数接口 //四元式的格式(operator,object,object,object) //空:_ static const string fileAddr=R"(..\Files\quat.txt)"; class GrammarAction { const string begin="( "; const string end=" )"; const string separator=" , "; const string empty="_"; ;//中间代码所在文件地址 int tmpIndex=0;//临时变量的标号 ofstream fin; stack<FunSheet::iterator> funStack;//函数栈 stack<string>object;//运算对象栈 stack<string>ope;//运算符栈 stack<string>funCall;//函数调用栈 void genetQuat(const string& a,const string& b,const string& c,const string& d);//生成四元式 string getTmpName(string Cat=""); public: GrammarAction(const string &fileName=fileAddr); void pushFunStack(FunSheet::iterator pushIterator);//将函数迭代器压入函数栈 void beginProgram();//生成函数定义四元式 void beginFunction();//生成代码段开始四元式 void endFunction();//函数定义结束四元式 void Assign();//赋值四元式 void pushObjectStack(const string&objectName);//运算对象压栈 void getAddress();//生成获取数组地址的四元式 void getSonAddress();//生成获取结构体元素的四元式 void assignResult();//生成返回值赋值四元式 void beginIf();//生成beginIf语句 void Else();//生成Else对应的四元式 void endIf();//生成endIf对应的四元式 void pushOpeStack(const string&opeName);//压入算符 void Relation();//生成关系运算四元式,关系运算加入的临时变量为bool型 void beginWhile();//生成beginWhile四元式 void Do();//生成Do对应的四元式 void endWhile();//生成endWhile对应的四元式 void popObjectStack();//运算对象弹栈 void pushFunCallStack(const string&funName);//将函数标识符压栈 void moveParameter();//生成参数传递四元式 void Call();//生成函数调用四元式 void getResult();//生成获取函数返回值的四元式 void popFunCallStack();//函数表示符弹栈 void Arithmetic();//生成算数运算四元式 void Input();//生成输入四元式 void OutPut();//生成输出四元式 }; #endif //COMPLIER_GRAMMARACTION_H
#ifndef _CBankFindPasswd_h_ #define _CBankFindPasswd_h_ #include "CHttpRequestHandler.h" class CBankFindPasswd : public CHttpRequestHandler { public: CBankFindPasswd(){} ~CBankFindPasswd(){} virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out); private: int getCacheIdCode(std::string codeKey); bool setUserBackPassword(int mid); }; #endif
#pragma once class BossComp : public hg::IComponent { public: void Start(); virtual int GetTypeID() const override { return s_TypeID; } void LoadFromXML(tinyxml2::XMLElement* data) {} virtual hg::IComponent* MakeCopyDerived() const { return hg::IComponent::Create(SID(BossComp)); } static uint32_t s_TypeID; void OnMessage(hg::Message* msg)override; private: static hg::Entity* s_agent; };
// Calculate level crossings for the hermitian index staggered operator. // Uses inverse power iterations to get the eigenvalues of the operator squared, // then figure out if the proper eigenvalue is +/- sqrt(eigen). #include <iostream> #include <iomanip> // to set output precision. #include <cmath> #include <string> #include <sstream> #include <complex> #include <random> #include <cstring> // should be replaced by using sstream #include "generic_inverters.h" #include "generic_inverters_precond.h" #include "generic_vector.h" #include "verbosity.h" #include "u1_utils.h" #include "operators.h" using namespace std; // Define pi. #define PI 3.141592653589793 // Custom routine to load gauge field. void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA); // Form the index operator squared. void staggered_index_operator_sq(complex<double>* lhs, complex<double>* rhs, void* extra_data); // A shifted versions of the index op for rayleigh quotients. void shift_op(complex<double>* lhs, complex<double>* rhs, void* extra_data); struct shift_struct { void* extra_data; void (*op)(complex<double>* a, complex<double>* b, void* extra_data); complex<double> shift; int length; }; int main(int argc, char** argv) { // Declare some variables. cout << setiosflags(ios::scientific) << setprecision(6); int i, j, x, y; complex<double> *lattice; // Holds the gauge field. complex<double> *lhs, *rhs, *check; // For some Kinetic terms. complex<double> *evals, *index_evals, **evecs; // Hold eigenvalues, eigenvectors. complex<double> tmp; double explicit_resid = 0.0; double p_bnorm = 0.0; double m_bnorm = 0.0; double relnorm = 0.0; std::mt19937 generator (1337u); // RNG, 1337u is the seed. inversion_info invif; staggered_u1_op stagif; // Set parameters. // L_x = L_y = Dimension for a square lattice. int square_size = 32; // Can be set on command line with --square_size. // Describe the staggered fermions. double MASS = 1e-2; // for Rayleigh Quotient. // Outer Inverter information. double outer_precision = 5e-13; int outer_restart = 256; // Gauge field information. double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta). // For heatbath gauge field, corresponds to non-compact beta. // Can be set on command line with --beta. // Number of eigenvalues to get. int n_evals = 1; // Load an external cfg? char* load_cfg = NULL; bool do_load = false; ///////////////////////////////////////////// // Get a few parameters from command line. // ///////////////////////////////////////////// for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0) { cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n"; cout << "--mass (default 1e-2)\n"; cout << "--square_size [32, 64, 128] (default 32)\n"; cout << "--n-evals [#] (default 1)\n"; cout << "--load-cfg [path] (default do not load, overrides beta)\n"; return 0; } if (i+1 != argc) { if (strcmp(argv[i], "--beta") == 0) { BETA = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--mass") == 0) { MASS = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--square_size") == 0) { square_size = atoi(argv[i+1]); i++; } else if (strcmp(argv[i], "--n-evals") == 0) { n_evals = atoi(argv[i+1]); i++; } else if (strcmp(argv[i], "--load-cfg") == 0) { load_cfg = argv[i+1]; do_load = true; i++; } else { cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n"; cout << "--mass (default 1e-2)\n"; cout << "--square_size [32, 64, 128] (default 32)\n"; cout << "--n-evals [#] (default 1)\n"; cout << "--load-cfg [path] (default do not load, overrides beta)\n"; return 0; } } } //printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector); //return 0; /////////////////////////////////////// // End of human-readable parameters! // /////////////////////////////////////// string op_name; op_name = "Squared staggered index operator."; cout << "[OP]: Operator " << op_name << " Mass " << MASS << "\n"; // Only relevant for free laplace test. int Nc = 1; // Only value that matters for staggered // Describe the fine lattice. int x_fine = square_size; int y_fine = square_size; int fine_size = x_fine*y_fine*Nc; cout << "[VOL]: X " << x_fine << " Y " << y_fine << " Volume " << x_fine*y_fine; cout << "\n"; // Do some allocation. // Initialize the lattice. Indexing: index = y*N + x. lattice = new complex<double>[2*fine_size]; lhs = new complex<double>[fine_size]; rhs = new complex<double>[fine_size]; check = new complex<double>[fine_size]; // Zero it out. zero<double>(lattice, 2*fine_size); zero<double>(rhs, fine_size); zero<double>(lhs, fine_size); zero<double>(check, fine_size); // // Allocate space for eigenvalues, eigenvectors. if (n_evals > 0) { evals = new complex<double>[n_evals]; index_evals = new complex<double>[n_evals]; evecs = new complex<double>*[n_evals]; for (i = 0; i < n_evals; i++) { evecs[i] = new complex<double>[fine_size]; zero<double>(evecs[i], fine_size); // Generate some initial vectors. } } else { cout << "ERROR! Negative number of eigenvalues requested.\n"; return 0; } cout << "[EVAL]: NEval " << n_evals << "\n"; // Fill stagif. stagif.lattice = lattice; stagif.mass = MASS; stagif.x_fine = x_fine; stagif.y_fine = y_fine; stagif.Nc = Nc; // Only relevant for laplace test only. // Create the verbosity structure. inversion_verbose_struct verb; verb.verbosity = VERB_SUMMARY; verb.verb_prefix = "[L1]: "; verb.precond_verbosity = VERB_DETAIL; verb.precond_verb_prefix = "Prec "; // Describe the gauge field. cout << "[GAUGE]: Creating a gauge field.\n"; unit_gauge_u1(lattice, x_fine, y_fine); // Load the gauge field. if (do_load) { read_gauge_u1(lattice, x_fine, y_fine, load_cfg); cout << "[GAUGE]: Loaded a U(1) gauge field from " << load_cfg << "\n"; } else // various predefined cfgs. { internal_load_gauge_u1(lattice, x_fine, y_fine, BETA); } cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(lattice, x_fine, y_fine) << ".\n"; // Begin iterating. for (i = 0; i < n_evals; i++) { // Create a new vector. gaussian<double>(rhs, fine_size, generator); // Orthogonalize it against previous vectors. if (i > 0) { for (j = 0; j < i; j++) { orthogonal<double>(rhs, evecs[j], fine_size); } } // Print norm. cout << "[NORM]: " << norm2sq<double>(rhs, fine_size) << "\n"; // Normalize. normalize<double>(rhs, fine_size); // Zero out lhs. zero<double>(lhs, fine_size); // Seed some initial guesses for the eigenvectors. complex<double> curr, prev; curr = 1.0; prev = 0.5; int counter = 0; while ((relnorm = abs(1.0/curr - 1.0/prev)/abs(1.0/prev)) > 1e-10) { prev = curr; // Switch over to rayleigh quotients at some point. if (counter < 10 || relnorm > 1e-4 || counter > 100) // inverse iterations. { // Perform inverse iteration. invif = minv_vector_cg(lhs, rhs, fine_size, 500, outer_precision, staggered_index_operator_sq, (void*)&stagif, &verb); //invif = minv_vector_gcr(lhs, rhs, fine_size, 500, outer_precision, op, (void*)&stagif, &verb); curr = dot<double>(rhs, lhs, fine_size)/norm2sq<double>(rhs, fine_size); } else // rayleigh { shift_struct sif; sif.extra_data = (void*)&stagif; sif.op = staggered_index_operator_sq; sif.length = fine_size; sif.shift = 1.0/curr; invif = minv_vector_cg(lhs, rhs, fine_size, 500, outer_precision, shift_op, (void*)&sif, &verb); normalize<double>(lhs, fine_size); staggered_index_operator_sq(check, lhs, (void*)&stagif); curr = 1.0/(dot<double>(lhs, check, fine_size)/norm2sq<double>(lhs, fine_size)); } // Reorthogonalize against previous vectors to avoid spurious re-introduction of eigenvalues. if (i > 0) { for (j = 0; j < i; j++) { orthogonal<double>(lhs, evecs[j], fine_size); } } normalize<double>(lhs, fine_size); copy<double>(rhs, lhs, fine_size); zero<double>(lhs, fine_size); // Print cout << "[EVAL]: Val " << i << " Iteration " << counter++ << " Guess " << 1.0/curr << " RelResid " << abs(1.0/curr - 1.0/prev)/abs(1.0/prev) << "\n"; } // Copy vector back into eigenvectors array, save eigenvalue. copy<double>(evecs[i], rhs, fine_size); evals[i] = 1.0/curr; // Okay, moment of truth: find if + or - is the right eigenvalue of the original unsquared op. // First, try plus. zero<double>(lhs, fine_size); staggered_index_operator(lhs, evecs[i], (void*)&stagif); p_bnorm = 0.0; for (j = 0; j < fine_size; j++) { p_bnorm += real(conj(lhs[j] - sqrt(evals[i])*evecs[i][j])*(lhs[j] - sqrt(evals[i])*evecs[i][j])); } cout << "[EVAL]: Plus " << p_bnorm << " Minus "; // Next, try minus. m_bnorm = 0.0; for (j = 0; j < fine_size; j++) { m_bnorm += real(conj(lhs[j] + sqrt(evals[i])*evecs[i][j])*(lhs[j] + sqrt(evals[i])*evecs[i][j])); } cout << m_bnorm << "\n"; index_evals[i] = (p_bnorm < m_bnorm) ? sqrt(evals[i]) : (-sqrt(evals[i])); } // Sort and print eigenvalues. for (i = 0; i < n_evals; i++) { for (j = 0; j < n_evals; j++) { if (real(index_evals[i]) < real(index_evals[j])) { tmp = evals[i]; evals[i] = evals[j]; evals[j] = tmp; tmp = index_evals[i]; index_evals[i] = index_evals[j]; index_evals[j] = tmp; } } } cout << "\n\nAll eigenvalues:\n"; for (i = 0; i < n_evals; i++) { cout << "[FINEVAL]: Mass " << MASS << " Num " << i << " SquareEval " << real(evals[i]) << " IndexEval " << real(index_evals[i]) << "\n"; } // Free the lattice. delete[] lattice; delete[] lhs; delete[] rhs; delete[] check; for (i = 0; i < n_evals; i++) { delete[] evecs[i]; } delete[] evecs; delete[] evals; delete[] index_evals; return 0; } // Hermitian index operator squared. void staggered_index_operator_sq(complex<double>* lhs, complex<double>* rhs, void* extra_data) { staggered_u1_op* stagif = (staggered_u1_op*)extra_data; complex<double>* tmp = new complex<double>[stagif->x_fine*stagif->y_fine]; staggered_index_operator(tmp, rhs, extra_data); staggered_index_operator(lhs, tmp, extra_data); delete[] tmp; } // A shifted versions of the index op for rayleigh quotients. void shift_op(complex<double>* lhs, complex<double>* rhs, void* extra_data) { shift_struct* sop = (shift_struct*)extra_data; (*sop->op)(lhs, rhs, sop->extra_data); for (int i = 0; i < sop->length; i++) { lhs[i] -= sop->shift*rhs[i]; } } // Custom routine to load gauge field. void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA) { if (x_fine == 32 && y_fine == 32) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 64 && y_fine == 64) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 128 && y_fine == 128) { if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l128t128b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l128t128b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l128t128bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } }
// addrspace.cc // Routines to manage address spaces (executing user programs). // // In order to run a user program, you must: // // 1. link with the -N -T 0 option // 2. run coff2noff to convert the object file to Nachos format // (Nachos object code format is essentially just a simpler // version of the UNIX executable object code format) // 3. load the NOFF file into the Nachos file system // (if you haven't implemented the file system yet, you // don't need to do this last step) // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "addrspace.h" #include "noff.h" #ifdef VM #include <cmath> #endif #ifdef HOST_SPARC #include <strings.h> #endif extern void PageFaultHandler(int vaddr); //---------------------------------------------------------------------- // SwapHeader // Do little endian to big endian conversion on the bytes in the // object file header, in case the file was generated on a little // endian machine, and we're now running on a big endian machine. //---------------------------------------------------------------------- static void SwapHeader (NoffHeader *noffH) { noffH->noffMagic = WordToHost(noffH->noffMagic); noffH->code.size = WordToHost(noffH->code.size); noffH->code.virtualAddr = WordToHost(noffH->code.virtualAddr); noffH->code.inFileAddr = WordToHost(noffH->code.inFileAddr); noffH->initData.size = WordToHost(noffH->initData.size); noffH->initData.virtualAddr = WordToHost(noffH->initData.virtualAddr); noffH->initData.inFileAddr = WordToHost(noffH->initData.inFileAddr); noffH->uninitData.size = WordToHost(noffH->uninitData.size); noffH->uninitData.virtualAddr = WordToHost(noffH->uninitData.virtualAddr); noffH->uninitData.inFileAddr = WordToHost(noffH->uninitData.inFileAddr); } //---------------------------------------------------------------------- // AddrSpace::AddrSpace // Create an address space to run a user program. // Load the program from a file "executable", and set everything // up so that we can start executing user instructions. // // Assumes that the object code file is in NOFF format. // // First, set up the translation from program memory to physical // memory. For now, this is really simple (1:1), since we are // only uniprogramming, and we have a single unsegmented page table // // "executable" is the file containing the object code to load into memory //---------------------------------------------------------------------- AddrSpace::AddrSpace(OpenFile *executable) { NoffHeader noffH; unsigned int i, size; int read; pcb = new PCB(procManager->getPID(), -1, NULL, -1); // not even sure if pcb has this constr procManager->insertProcess(pcb, pcb->pid); executable->ReadAt((char *)&noffH, sizeof(noffH), 0); if ((noffH.noffMagic != NOFFMAGIC) && (WordToHost(noffH.noffMagic) == NOFFMAGIC)) SwapHeader(&noffH); ASSERT(noffH.noffMagic == NOFFMAGIC); // how big is address space? // we need to increase the size // to leave room for the stack size = noffH.code.size + noffH.initData.size + noffH.uninitData.size + UserStackSize; numPages = divRoundUp(size, PageSize); size = numPages * PageSize; #ifndef VM ASSERT(numPages <= NumPhysPages); // check we're not trying // to run anything too big -- // at least until we have // virtual memory if(numPages > memManager->getAvailable()) { printf("Not enough memory\n"); procManager->clearPID(pcb->pid); // clearPID() ?? numPages = -1; return; } // ^^^ is this a good error catcher ^^^ #endif DEBUG('a', "Initializing address space, num pages %d, size %d\n", numPages, size); // first, set up the translation pageTable = new TranslationEntry[numPages]; for (i = 0; i < numPages; i++) { pageTable[i].virtualPage = i; // for now, virtual page # = phys page # #ifdef VM // initialize process with no pages in memory pageTable[i].physicalPage = -1; pageTable[i].valid = FALSE; #else pageTable[i].physicalPage = memManager->getPage(); // memManager defined in system.cc pageTable[i].valid = TRUE; #endif pageTable[i].use = FALSE; pageTable[i].dirty = FALSE; pageTable[i].readOnly = FALSE; // if the code segment was entirely on // a separate page, we could set its // pages to be read-only } // zero out the entire address space, to zero the unitialized data segment // and the stack segment // bzero(machine->mainMemory, size); // needed or not?? // then, copy in the code and data segments into memory if (noffH.code.size > 0) { DEBUG('a', "Initializing code segment, at 0x%x, size %d\n",noffH.code.virtualAddr, noffH.code.size);// //executable->ReadAt(&(machine->mainMemory[noffH.code.virtualAddr]),noffH.code.size, noffH.code.inFileAddr); read = ReadFile(noffH.code.virtualAddr,executable,noffH.code.size,noffH.code.inFileAddr); } if (noffH.initData.size > 0) { DEBUG('a', "Initializing data segment, at 0x%x, size %d\n",noffH.initData.virtualAddr, noffH.initData.size); //executable->ReadAt(&(machine->mainMemory[noffH.initData.virtualAddr]),noffH.initData.size, noffH.initData.inFileAddr); read = ReadFile(noffH.initData.virtualAddr,executable,noffH.initData.size,noffH.initData.inFileAddr); } #ifdef VM char* buffer = new char[PageSize + 1]; memset(buffer, '\0', PageSize); int page = ceil((float)(noffH.code.size + noffH.initData.size)/PageSize); DEBUG('q', "Adding %d pages\n",(numPages - page)); for (int v = page; v < numPages; v++) vm->AddPage(&pageTable[v], pcb->pid, PageSize); //vm-> delete buffer; #endif printf("Loaded Program: %d code | %d data | %d bss\n",noffH.code.size,noffH.initData.size,noffH.uninitData.size); } AddrSpace::AddrSpace() { } AddrSpace::AddrSpace(TranslationEntry* table, int page_count, int oldPID) { pageTable = table; numPages = page_count; pcb = new PCB(procManager->getPID(), -1, NULL, -1); procManager->insertProcess(pcb, pcb->pid); #ifdef VM for (int i = 0; i < numPages; i++) { if (pageTable[i].valid) vm->AddPage(&pageTable[i], pcb->pid, machine->mainMemory + (pageTable[i].physicalPage * PageSize), PageSize); else vm->CopyPage(&pageTable[i], oldPID, pcb->pid); pageTable[i].valid = FALSE; pageTable[i].physicalPage = -1; } #endif } //---------------------------------------------------------------------- // AddrSpace::~AddrSpace // Dealloate an address space. Nothing for now! //---------------------------------------------------------------------- //AddrSpace::~AddrSpace() //{ // delete pageTable; // delete pcb; //} #ifdef VM AddrSpace::~AddrSpace() { int i; // Delete any pages in physical memory for (i = 0; i < numPages; i++) { if (pageTable[i].valid) memManager->clearPage(pageTable[i].physicalPage); } delete pageTable; } #else AddrSpace::~AddrSpace() { for (int i = 0; i < numPages; i++) memManager->clearPage(pageTable[i].physicalPage); delete pageTable; } #endif //---------------------------------------------------------------------- // AddrSpace::InitRegisters // Set the initial values for the user-level register set. // // We write these directly into the "machine" registers, so // that we can immediately jump to user code. Note that these // will be saved/restored into the currentThread->userRegisters // when this thread is context switched out. //---------------------------------------------------------------------- void AddrSpace::InitRegisters() { int i; for (i = 0; i < NumTotalRegs; i++) machine->WriteRegister(i, 0); // Initial program counter -- must be location of "Start" machine->WriteRegister(PCReg, 0); // Need to also tell MIPS where next instruction is, because // of branch delay possibility machine->WriteRegister(NextPCReg, 4); // Set the stack register to the end of the address space, where we // allocated the stack; but subtract off a bit, to make sure we don't // accidentally reference off the end! machine->WriteRegister(StackReg, numPages * PageSize - 16); DEBUG('a', "Initializing stack register to %d\n", numPages * PageSize - 16); } //---------------------------------------------------------------------- // AddrSpace::SaveState // On a context switch, save any machine state, specific // to this address space, that needs saving. // // For now, nothing! //---------------------------------------------------------------------- void AddrSpace::SaveState() { //@@@ MIGHT NEED TO TAKE OUT /*for(int i = 0; i<NumTotalRegs; i++){ progRegisters[i] = machine->ReadRegister(i); }*/ } //---------------------------------------------------------------------- // AddrSpace::RestoreState // On a context switch, restore the machine state so that // this address space can run. // // For now, tell the machine where to find the page table. //---------------------------------------------------------------------- void AddrSpace::RestoreState() { machine->pageTable = pageTable; machine->pageTableSize = numPages; //@@@ MIGHT NEED TO TAKE OUT /*for(int i = 0; i < NumTotalRegs; i++){ machine->WriteRegister(i, progRegisters[i]); }*/ } //--------------------------------------------------------------------- // AddrSpace::Translate() // takes a virtual address and tranlates it into a physical // address // // return true if virtual address was valid, false otherwise // // "vAddr" : virtual address to be translated // "physAddr" : the physical address to be stored //--------------------------------------------------------------------- bool AddrSpace::Translate(int vAddr, int *physAddr, bool writing) { if(vAddr < 0) { return false; } int vpn = vAddr / PageSize; // PageSize defined in machine.h if(vpn > numPages) // > or >= ??? return false; else if(!pageTable[vpn].valid) { #ifdef VM DEBUG('3', "PageFaultHandler, vAddr: %i\n", vAddr); PageFaultHandler(vAddr); #else return false; #endif } int offset = vAddr % PageSize; *physAddr = pageTable[vpn].physicalPage * PageSize + offset; // should it be ".physicalPage" ??? if(writing) pageTable[vpn].dirty = TRUE; // ^^^ add this?? ^^^ #ifdef VM pageTable[vpn].use = TRUE; #endif return true; } #ifdef VM // Return Value ??? some int // vaddr = virtual address // file = file to read into memory // size = size of data to read // fileAddr = location in file to start at int AddrSpace::ReadFile(int vaddr, OpenFile* file, int size, int fileAddr) { int bytes_read = 0; int bytes_wrote; int phys_addr; int write_size; char* mem_buffer; char* buffer = new char[PageSize]; char* out_buffer; DEBUG('q', "Start vaddr: %d end vaddr: %d\n", vaddr, vaddr + size); while (bytes_read < size) { int read = file->ReadAt(diskBuffer, PageSize - (vaddr % PageSize), fileAddr); fileAddr += read; DEBUG('q', "Bytes read: %d\n", read); bytes_read += read; DEBUG('q', "We have vaddr: %d, and PageSize: %d, VPN: %d\n", vaddr, PageSize, vaddr/PageSize); out_buffer = diskBuffer; if (vm->GetPage(&pageTable[vaddr/PageSize], pcb->pid, buffer, PageSize)) { DEBUG('7', "Starting at %d, we should be able to write %d bytes\n", vaddr, PageSize - (vaddr % PageSize)); memcpy(buffer + (vaddr % PageSize), diskBuffer, PageSize - (vaddr % PageSize)); out_buffer = buffer; } vm->AddPage(&pageTable[vaddr/PageSize], pcb->pid, out_buffer, PageSize); vaddr += read; } delete buffer; } #else //--------------------------------------------------------------------- // AddrSpace::ReadFile() // loads the code and data segments into the translated memory // instead at positon 0 like the constructor already does // // return the number of bytes actually read // // "virtAddr" : beginning virtual address of the bytes to be read // "file" : file where bytes are from // "size" : amount of bytes to be read // "fileAddr" : the file address //--------------------------------------------------------------------- AddrSpace::ReadFile(int virtAddr, OpenFile* file, int size, int fileAddr) { char diskBuffer[size]; // stores the bytes read int availBytes; // num bytes available to read int physAddr; // get the number of bytes that are actually there int actualSize = file->ReadAt(diskBuffer, size, fileAddr); // @@@ what if actual size > size ??? int bytesLeft = actualSize; int bytesCopied = 0; // read the bytes in the file while(bytesLeft > 0) { bool valid = Translate(virtAddr, &physAddr); if(valid < 0) { DEBUG('a',"virtual address could not be translated\n"); return -1; // could not translate virtAddr... there is an issue } availBytes = PageSize - (physAddr % PageSize); // Be sure not to under or over flow the buffer during copy // Be sure no to write too much of the file into memory int bytesToRead = 0; if(bytesLeft < availBytes) bytesToRead = bytesLeft; else bytesToRead = availBytes; bcopy(diskBuffer+bytesCopied, &machine->mainMemory[physAddr], bytesToRead); // decrement the number of bytes left to read bytesLeft -= bytesToRead; // increment the number of bytes already read bytesCopied += bytesToRead; // increment to the next virtual address to write to virtAddr += bytesToRead; } return actualSize; } #endif #ifdef VM //@@@ don't know if this for sure does the same thing??? AddrSpace* AddrSpace::Duplicate() { AddrSpace* dup = new AddrSpace(); dup->numPages = this->numPages; dup->pageTable = new TranslationEntry[numPages]; for (int i = 0; i < numPages; i++) { //@@@ORIG dup->pageTable[i].virtualPage = i; dup->pageTable[i].virtualPage = this->pageTable[i].virtualPage; dup->pageTable[i].physicalPage = memManager->getPage(); dup->pageTable[i].valid = this->pageTable[i].valid; dup->pageTable[i].use = this->pageTable[i].use; dup->pageTable[i].dirty = this->pageTable[i].dirty; dup->pageTable[i].readOnly = this->pageTable[i].readOnly; } return dup; } #else //Function to make a copy of an address space AddrSpace* AddrSpace::Duplicate(){ if(numPages > memManager->getAvailable()){ *copySpace = NULL; return NULL; } AddrSpace* dup = new AddrSpace(); dup->numPages = this->numPages; dup->pageTable = new TranslationEntry[numPages]; for (int i = 0; i < numPages; i++) { //@@@ORIG dup->pageTable[i].virtualPage = i; dup->pageTable[i].virtualPage = this->pageTable[i].virtualPage; dup->pageTable[i].physicalPage = memManager->getPage(); dup->pageTable[i].valid = this->pageTable[i].valid; dup->pageTable[i].use = this->pageTable[i].use; dup->pageTable[i].dirty = this->pageTable[i].dirty; dup->pageTable[i].readOnly = this->pageTable[i].readOnly; bcopy(machine->mainMemory + this->pageTable[i].physicalPage * PageSize, machine->mainMemory + dup->pageTable[i].physicalPage * PageSize, PageSize); } return dup; } #endif int AddrSpace::getNumPages(){ return numPages; } void AddrSpace::CleanupSysCall(){ for(int i = 0; i < numPages; i++) pageTable[i].use = FALSE; }
#include <iostream> #include <vector> using namespace std; /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ #define int long long int #define ld long double #define F first #define S second #define P pair<int,int> #define pb push_back #define endl '\n' /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ const int N = 3e2 + 5; int dis[N][N]; vector <pair<P, int>> add; int n, q; int ans[N]; const int inf = 1e9; void floyd_warshall() { for (int k = 1; k <= q; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { dis[i][j] = min(dis[i][j], min(dis[i][add[k].F.F] + add[k].S + dis[add[k].F.S][j],//i->a->b->j; dis[i][add[k].F.S] + add[k].S + dis[add[k].F.F][j]));//i->b->a->j; } } for (int ii = 1; ii <= n; ii++) { for (int jj = 1; jj <= n; jj++) { ans[k] += dis[ii][jj]; } } } } void solve() { cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> dis[i][j]; } } cin >> q; add.pb({{0, 0}, 0}); for (int i = 1; i <= q; i++) { int u, v, w; cin >> u >> v >> w; add.pb({{u, v}, w}); } floyd_warshall(); // for (int i = 1; i <= n; i++) { // for (int j = 1; j <= n; j++) { // cout << dis[i][j] << " "; // } // cout << endl; // } for (int i = 1; i <= q; i++) { cout << ans[i] / 2 << " "; } return ; } int32_t main() { /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ //int t;cin>>t;while(t--) solve(); return 0; }
#include "Window.h" Window::Window() { WinMain(SW_SHOWNORMAL); } BOOL CALLBACK Window::DlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_COMMAND: switch (HIWORD(wParam)) { case BN_CLICKED: switch (LOWORD(wParam)) { case (IDOK): { HWND g_handle = GetDlgItem(hwnd, IDC_COMBO1); HWND p_handle = GetDlgItem(hwnd, IDC_COMBO2); HWND c_handle = GetDlgItem(hwnd, IDC_EDIT1); if (SendMessage(g_handle, CB_GETCURSEL, 0, 0) == 0 || SendMessage(g_handle, CB_GETCURSEL, 0, 0) == 7) return false; if (SendMessage(p_handle, CB_GETCURSEL, 0, 0) == 0) return false; char* t = new char[GetWindowTextLength(c_handle) + 1]; GetWindowText(c_handle, t, GetWindowTextLength(c_handle) + 1); if (strlen(t) == 0) { delete[] t; return false; } data.NewCourse(SendMessage(g_handle, CB_GETCURSEL, 0, 0), SendMessage(p_handle, CB_GETCURSEL, 0, 0), t); delete[] t; return EndDialog(hwnd, 1); } break; case (IDCANCEL): return EndDialog(hwnd, 0); break; default: break; } break; default: break; } break; case WM_INITDIALOG: //std::cout << "[CC][DLG] Created Dialog successfully!" << std::endl; //init the dropdowns: { HWND g_handle = GetDlgItem(hwnd, IDC_COMBO1); HWND p_handle = GetDlgItem(hwnd, IDC_COMBO2); if (SendMessage(p_handle, CB_GETCOUNT, 0, 0) == 0) { SendMessage(p_handle, CB_ADDSTRING, 0, (LPARAM)"---"); SendMessage(p_handle, CB_ADDSTRING, 0, (LPARAM)"50"); SendMessage(p_handle, CB_ADDSTRING, 0, (LPARAM)"100"); SendMessage(p_handle, CB_ADDSTRING, 0, (LPARAM)"150"); SendMessage(p_handle, CB_ADDSTRING, 0, (LPARAM)"200"); SendMessage(p_handle, CB_SETCURSEL, 0, (LPARAM)0); } if (SendMessage(g_handle, CB_GETCOUNT, 0, 0) == 0) { SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"---"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"A"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"B"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"C"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"D"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"E"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"F"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"---"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"MVG"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"VG"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"G"); SendMessage(g_handle, CB_ADDSTRING, 0, (LPARAM)"IG"); SendMessage(g_handle, CB_SETCURSEL, 0, (LPARAM)0); } } return 1; default: //return DefDlgProc(hwnd, msg, wParam, lParam); break; } return 0; } bool Window::InsertListViewItems(int amount) { InsertListViewItems(GetDlgItem(hwnd, LST_COURSES), amount); return true; } LRESULT CALLBACK Window::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_TIMER: return DefWindowProc(hwnd, msg, wParam, lParam); break; case WM_COMMAND: switch (HIWORD(wParam)) { case BN_CLICKED: switch (LOWORD(wParam)) { case (BTN_ADDCOURSE): std::cout << "Button" << std::endl; if (DialogBox(NULL, MAKEINTRESOURCE(IDD_DIALOG1), hwnd, DlgProc)) { InsertListViewItems(GetDlgItem(hwnd, LST_COURSES), 1); HWND ed = GetDlgItem(hwnd, EDIT_CREDIT); if (SendMessage(ed, WM_SETTEXT, 0, (LPARAM)std::to_string(data.cred).substr(0, 5).c_str())) return true; } else { std::cout << "[CC][DLG] Pressed Cancel" << std::endl; } break; case (BTN_SAVE): OnFileSaveAs(); break; case (BTN_OPEN): OnFileOpen(); break; default: break; } break; default: break; } break; case WM_NOTIFY: if (lParam) { switch (((LPNMHDR)lParam)->code) { case LVN_GETDISPINFO: { NMLVDISPINFO* plvdi = (NMLVDISPINFO*)lParam; switch (plvdi->item.iSubItem) { case 0: plvdi->item.pszText = (LPSTR)data.GetCourse(plvdi->item.iItem)->name.c_str(); break; case 1: plvdi->item.pszText = (LPSTR)std::to_string(data.GetCourse(plvdi->item.iItem)->points).c_str(); break; case 2: plvdi->item.pszText = (LPSTR)data.GetCourse(plvdi->item.iItem)->gradeName.c_str(); break; default: break; } break; } default: break; } } break; case WM_CREATE: { //std::cout << "[CC-WIN] Window Created Successfully!" << std::endl; HWND addButton = CreateWindowEx( NULL, "BUTTON", "Lägg till Kurs", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 470, 325, 80, 25, hwnd, (HMENU)BTN_ADDCOURSE, (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL); if (addButton == NULL) { std::cout << "[CC][WIN] " << "Button initialization failed!" << std::endl; return false; } SendMessage(addButton, WM_SETFONT, (WPARAM)(HFONT)GetStockObject(ANSI_VAR_FONT), MAKELPARAM(FALSE, 0)); HWND saveButton = CreateWindowEx( NULL, "BUTTON", "Spara", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 470, 10, 50, 25, hwnd, (HMENU)BTN_SAVE, (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL); if (saveButton == NULL) { std::cout << "[CC][WIN] " << "Button initialization failed!" << std::endl; return false; } SendMessage(saveButton, WM_SETFONT, (WPARAM)(HFONT)GetStockObject(ANSI_VAR_FONT), MAKELPARAM(FALSE, 0)); HWND openButton = CreateWindowEx( NULL, "BUTTON", "Öppna", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 525, 10, 50, 25, hwnd, (HMENU)BTN_OPEN, (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL); if (openButton == NULL) { std::cout << "[CC][WIN] " << "Button initialization failed!" << std::endl; return false; } SendMessage(openButton, WM_SETFONT, (WPARAM)(HFONT)GetStockObject(ANSI_VAR_FONT), MAKELPARAM(FALSE, 0)); if (CreateListView(hwnd) == NULL) { std::cout << "[CC][WIN] " << "Listview initialization failed!" << std::endl; return false; } HWND creditLabel = CreateWindowEx( NULL, "STATIC", "Merit", WS_CHILD | WS_VISIBLE | WS_TABSTOP , 497, 45, 40, 25, hwnd, NULL, (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL); SendMessage(creditLabel, WM_SETFONT, (WPARAM)(HFONT)GetStockObject(ANSI_VAR_FONT), MAKELPARAM(FALSE, 0)); HWND creditEdit = CreateWindowEx( WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_READONLY | ES_CENTER, 497, 60, 50, 25, hwnd, (HMENU)EDIT_CREDIT, (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL); if (creditEdit == NULL) { std::cout << "[CC][WIN] " << "Edit initialization failed!" << std::endl; return false; } SendMessage(creditEdit, WM_SETFONT, (WPARAM)(HFONT)GetStockObject(ANSI_VAR_FONT), MAKELPARAM(FALSE, 0)); } break; case WM_SETTEXT: std::cout << "IS TEXT" << std::endl; break; case WM_CHILDACTIVATE: std::cout << "AM CHILD :/" << std::endl; break; case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } Window::~Window() { } int WINAPI Window::WinMain(int nCmdShow) { //Step 1: Register the window wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = NULL;// hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if (!RegisterClassEx(&wc)) { std::cout << "[FORM] Window Registration Failed!" << std::endl; return 0; } DWORD style = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX); //Step 2: Create the window hwnd = CreateWindowEx( 0, g_szClassName, "Gymnasiemeritkalkylator", style, CW_USEDEFAULT, CW_USEDEFAULT, 600, 400, NULL, NULL, NULL, NULL ); if (hwnd == NULL) { std::cout << "[FORM] Window Creation Failed!" << std::endl; return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); while (GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; } CourseData Window::data; LRESULT CALLBACK Window::ListViewProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) { switch (Msg) { case LVM_DELETECOLUMN: return true; break; case WM_KEYDOWN: if (wParam == 46) { std::cout << SendMessage(hwnd, LVM_GETSELECTIONMARK, 0, 0) << std::endl; int selIndex = SendMessage(hwnd, LVM_GETSELECTIONMARK, 0, 0); if (SendMessage(hwnd, LVM_DELETEITEM, selIndex, 0)) { data.DeleteCourse(selIndex); HWND ed = GetDlgItem(GetParent(hwnd), EDIT_CREDIT); if (SendMessage(ed, WM_SETTEXT, 0, (LPARAM)std::to_string(data.cred).substr(0, 5).c_str())) return true; } else std::cout << SendMessage(hwnd, LVM_GETSELECTIONMARK, 0, 0) << std::endl; return TRUE; } break; } return DefSubclassProc(hwnd, Msg, wParam, lParam); } HWND Window::CreateListView(HWND hwndParent) { INITCOMMONCONTROLSEX icex; icex.dwICC = ICC_LISTVIEW_CLASSES; InitCommonControlsEx(&icex); RECT rcClient; GetClientRect(hwndParent, &rcClient); HWND hWndListView = CreateWindowEx(NULL, WC_LISTVIEW, "", WS_CHILD | LVS_REPORT | LVS_EDITLABELS | WS_VISIBLE, 10,10, 450, 340, hwndParent, (HMENU)LST_COURSES, (HINSTANCE)GetWindowLong(hwndParent, GWL_HINSTANCE), NULL); LVCOLUMN lvc; lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; for (int iCol = 0; iCol < 3; iCol++) { lvc.iSubItem = iCol; lvc.cx = iCol == 0 ? 300 : 75; if (iCol == 0) lvc.pszText = (LPSTR)"Kurs"; if (iCol == 1) lvc.pszText = (LPSTR)"Poäng"; if (iCol == 2) lvc.pszText = (LPSTR)"Betyg"; if (ListView_InsertColumn(hWndListView, iCol, &lvc) == -1) return false; } SetWindowSubclass(hWndListView, ListViewProc, 0, 0); return hWndListView; } BOOL Window::InsertListViewItems(HWND hWndListView, int cItems) { LVITEM lvI; lvI.pszText = LPSTR_TEXTCALLBACK; lvI.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE; lvI.stateMask = 0; lvI.iSubItem = 0; lvI.state = 0; for (int i = 0; i < cItems; i++) { lvI.iItem = i; lvI.iImage = i; if (ListView_InsertItem(hWndListView, &lvI) == -1) return false; } return true; } HRESULT Window::_WriteDataToFile(HANDLE hFile, PCWSTR pszDataIn) { DWORD cbData = WideCharToMultiByte(CP_ACP, 0, pszDataIn, -1, NULL, 0, NULL, NULL); HRESULT hr = (cbData == 0) ? HRESULT_FROM_WIN32(GetLastError()) : S_OK; if (SUCCEEDED(hr)) { char *pszData = new (std::nothrow) CHAR[cbData]; hr = pszData ? S_OK : E_OUTOFMEMORY; if (SUCCEEDED(hr)) { hr = WideCharToMultiByte(CP_ACP, 0, pszDataIn, -1, pszData, cbData, NULL, NULL) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); if (SUCCEEDED(hr)) { DWORD dwBytesWritten = 0; hr = WriteFile(hFile, pszData, cbData - 1, &dwBytesWritten, NULL) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } } delete[] pszData; } return hr; } HRESULT Window::_WritePropertyToCustomFile(PCWSTR pszFileName, PCWSTR pszPropertyName, PCWSTR pszValue) { HANDLE hFile = CreateFileW(pszFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); HRESULT hr = (hFile == INVALID_HANDLE_VALUE) ? HRESULT_FROM_WIN32(GetLastError()) : S_OK; if (SUCCEEDED(hr)) { const WCHAR wszPropertyStartTag[] = L"[PROPERTY]"; const WCHAR wszPropertyEndTag[] = L"[ENDPROPERTY]\r\n"; const DWORD cchPropertyStartTag = (DWORD)wcslen(wszPropertyStartTag); const static DWORD cchPropertyEndTag = (DWORD)wcslen(wszPropertyEndTag); DWORD const cchPropertyLine = cchPropertyStartTag + cchPropertyEndTag + (DWORD)wcslen(pszPropertyName) + (DWORD)wcslen(pszValue) + 2; PWSTR pszPropertyLine = new (std::nothrow) WCHAR[cchPropertyLine]; hr = pszPropertyLine ? S_OK : E_OUTOFMEMORY; if (SUCCEEDED(hr)) { hr = StringCchPrintfW(pszPropertyLine, cchPropertyLine, L"%s%s=%s%s", wszPropertyStartTag, pszPropertyName, pszValue, wszPropertyEndTag); if (SUCCEEDED(hr)) { hr = SetFilePointer(hFile, 0, NULL, FILE_END) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); if (SUCCEEDED(hr)) { hr = _WriteDataToFile(hFile, pszPropertyLine); } } } delete[] pszPropertyLine; CloseHandle(hFile); } return hr; } HRESULT Window::_WriteDataToCustomFile(PCWSTR pszFileName) { HANDLE hFile = CreateFileW(pszFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); HRESULT hr = (hFile == INVALID_HANDLE_VALUE) ? HRESULT_FROM_WIN32(GetLastError()) : S_OK; if (SUCCEEDED(hr)) { char* c = data.GetAsSaveData(); int n = MultiByteToWideChar(CP_ACP, 0, c, -1, NULL, 0); WCHAR* wszContent = new WCHAR[n]; MultiByteToWideChar(CP_ACP, 0, c, -1, (LPWSTR)wszContent, n); hr = _WriteDataToFile(hFile, wszContent); CloseHandle(hFile); //delete[] c; delete[] wszContent; } return hr; } HRESULT Window::OnFileSaveAs() { IFileSaveDialog *pfsd; HRESULT hr = CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfsd)); if (SUCCEEDED(hr)) { const COMDLG_FILTERSPEC rgSaveTypes[] = { {L"MeritCalc File (*.mkf)", L"*.mkf"} }; hr = pfsd->SetFileTypes(ARRAYSIZE(rgSaveTypes), rgSaveTypes); if (SUCCEEDED(hr)) { hr = pfsd->SetFileTypeIndex(0); if (SUCCEEDED(hr)) { hr = pfsd->SetDefaultExtension(L"mkf"); if (SUCCEEDED(hr)) { DWORD dwFlags; hr = pfsd->GetOptions(&dwFlags); if (SUCCEEDED(hr)) { hr = pfsd->SetOptions(dwFlags | FOS_FORCEFILESYSTEM); if (SUCCEEDED(hr)) { IPropertyDescriptionList *pd1; hr = PSGetPropertyDescriptionListFromString(L"prop:System.Keywords", IID_PPV_ARGS(&pd1)); if (SUCCEEDED(hr)) { hr = pfsd->SetCollectedProperties(pd1, TRUE); pd1->Release(); } } } } } } if (SUCCEEDED(hr)) { hr = pfsd->Show(NULL); if (SUCCEEDED(hr)) { IShellItem *psiResult; hr = pfsd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszNewFileName; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszNewFileName); if (SUCCEEDED(hr)) { hr = _WriteDataToCustomFile(pszNewFileName); if (SUCCEEDED(hr)) { IPropertyStore *pps; hr = pfsd->GetProperties(&pps); if (SUCCEEDED(hr)) { DWORD cProps = 0; hr = pps->GetCount(&cProps); for (DWORD i = 0; i < cProps && SUCCEEDED(hr); i++) { PROPERTYKEY key; hr = pps->GetAt(i, &key); if (SUCCEEDED(hr)) { PWSTR pszPropertyName; hr = PSGetNameFromPropertyKey(key, &pszPropertyName); if (SUCCEEDED(hr)) { PROPVARIANT propvarValue; PropVariantInit(&propvarValue); hr = pps->GetValue(key, &propvarValue); if (SUCCEEDED(hr)) { WCHAR wszValue[MAX_PATH]; hr = PropVariantToString(propvarValue, wszValue, ARRAYSIZE(wszValue)); if (SUCCEEDED(hr)) { hr = _WritePropertyToCustomFile(pszNewFileName, pszPropertyName, wszValue); } } PropVariantClear(&propvarValue); CoTaskMemFree(pszPropertyName); } } } pps->Release(); } } CoTaskMemFree(pszNewFileName); } psiResult->Release(); } } } pfsd->Release(); } return hr; } HRESULT Window::OnFileOpen() { //DO THE THING HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (SUCCEEDED(hr)) { IFileOpenDialog *pFileOpen; hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen)); if (SUCCEEDED(hr)) { const COMDLG_FILTERSPEC rgSaveTypes[] = { {L"MeritCalc File (*.mkf)", L"*.mkf"} }; hr = pFileOpen->SetFileTypes(ARRAYSIZE(rgSaveTypes), rgSaveTypes); if (SUCCEEDED(hr)) { hr = pFileOpen->Show(NULL); if (SUCCEEDED(hr)) { IShellItem *pItem; hr = pFileOpen->GetResult(&pItem); if (SUCCEEDED(hr)) { PWSTR pszFilePath; hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); if (SUCCEEDED(hr)) { _GetDataFromFile(pszFilePath); CoTaskMemFree(pszFilePath); } pItem->Release(); } } pFileOpen->Release(); } } CoUninitialize(); } return hr; } bool Window::_GetDataFromFile(PCWSTR pszFileName) { char* path = 0; int bytesRequired = WideCharToMultiByte(CP_ACP, 0, pszFileName, -1, 0, 0, 0, 0); if (bytesRequired > 0) { path = new char[bytesRequired]; int rc = WideCharToMultiByte(CP_ACP, 0, pszFileName, -1, path, bytesRequired, 0, 0); if (rc != 0) { path[bytesRequired - 1] = 0; } } std::ifstream file(path); if (file.is_open()) { file.seekg(0, std::ios::end); size_t size = file.tellg(); std::string buffer(size, ' '); file.seekg(0); file.read(&buffer[0], size); file.close(); delete[] path; data.FromSaveData(buffer); InsertListViewItems(data.GetAmount()); HWND ed = GetDlgItem(hwnd, EDIT_CREDIT); SendMessage(ed, WM_SETTEXT, 0, (LPARAM)std::to_string(data.cred).substr(0, 5).c_str()); return 1; } delete[] path; return 0; } HWND Window::hwnd;
#pragma once #include<vector> #include<set> #include<memory> #include <map> #include <cgraph.h> class Transition; class PredicateVehicle; /** * A Situation consists of Objects and all outgoing Transitions. */ class Situation { public: /** * Constructs a Situation object with the given VUT and PredicateVehicles and an 'initial' flag. * @param vut Pointer to the PredicateVehicle representing the VUT. * @param otherVehicles Vector of pointers to PredicateVehicle representing all vehicles but the VUT. * @param initial. Flag signalling if this Situation is the initial situation of a sequence. */ Situation(std::shared_ptr<PredicateVehicle> vut, std::vector<std::shared_ptr<PredicateVehicle>> otherVehicles, bool initial); /** * Delete Copy constructor */ Situation(const Situation&) = delete; /** * Standard Deconstructor. */ ~Situation(); /** * Adds a Transition to the vector of transitions. Checks if this situation is actually the starting situation in the Transition. * @param transition Pointer to the new transition. */ void addTransition(std::shared_ptr<Transition> transition); /** * Getter for the vector of outgoing transitions. * @returns A vector of all outgoing transitions. */ std::set<std::shared_ptr<Transition>> const& getTransitions(); /** * Override operator == * @return true if both Situations have the same stable value, the same isInitial value, contain an equal VUT and equal other vehicles, else false */ bool operator==(const Situation &other) const; /** * Override operator != * @return true iff == returns false */ bool operator!=(const Situation &other) const; /** * The Situation is stable iff the VUT is stable. * @return True iff the Situation is stable. */ bool isStable() const; /** * Getter for the other vehicles * @return vector of vehicles in the Situation excluding the VUT */ std::vector<std::shared_ptr<PredicateVehicle>> const& getOtherVehicles() const; /** * Getter for the VUT * @return const reference to the VUT. */ PredicateVehicle const& getVUT() const; /** * Getter for the initial flag. * @return value of the initial flag. */ bool isInitial() const; /** * Marks this Situation as initial. */ void markInitial(); /** * transforms this Situation to a string representation. * @return string representation of the Situation. */ std::string toString() const; /** * transforms this Situation to a wstring representation. * @return wstring representation of the Situation. */ std::wstring toWString() const; /** * Adds a node representing this Situation to the Graph if it wasn't added already. * @param graph Pointer to the graph the node should be added to. * @param id Unique ID for the resulting node struct in the graph. * @return The node representation of this Situation. */ Agnode_t * addAsNode(Agraph_t *graph, int id); private: std::set<std::shared_ptr<Transition>> transitions; std::shared_ptr<PredicateVehicle> vut; std::vector<std::shared_ptr<PredicateVehicle>> otherVehicles; bool initial; Agnode_t *node; std::string toHTML(); };
#define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_PNG #include "stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" GLuint LoadTexture(const char *file) { int x, y, n; unsigned char *image = stbi_load(file, &x, &y, &n, 0); if (image == nullptr) { LOG_ERROR("Failed to load texture '%s'", file); return 0; } if (n != 3) { stbi_image_free(image); return 0; } GLuint texture = CreateTexture2D(x, y, GL_RGB, GL_UNSIGNED_BYTE, image); stbi_image_free(image); return texture; } bool SaveScreenshot(const char *file, int w, int h) { unsigned char *image = (unsigned char*)malloc(w*h*3); glReadBuffer(GL_BACK); glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, image); stbi_flip_vertically_on_write(1); int rv = stbi_write_png(file, w, h, 3, image, w*3); free(image); return (rv != 0); }
#pragma once #include "stdafx.h" #include "DataTypes\vec.h" #include <map> #include "skeleton.h" #include "boneAbstract.h" #include "octreeSolid.h" #include "bvhVoxel.h" #include "cutSurfTreeMngr2.h" #include "boneTransform.h" //#include "coordAssignManager.h" extern class coordAssignManager; enum errorCompareFlag { COMPARE_VOLUME = 0x0001, COMPARE_ASPECT = 0x0010, COMPARE_FILL = 0x0100, }; class detailSwapManager { public: detailSwapManager(void); ~detailSwapManager(void); void draw(); void draw2(BOOL displayMode[10]); void updateDisplay(int idx1, int idx2); // 1. Load void initFromCutTree2(cutSurfTreeMngr2* m_cutSurface); // Quick swap void initFromAssignCoord(coordAssignManager * m_coordAssign); void swapVoxel2(); void swapVoxelTotal(); // 1.1. Mesh box void loadMeshBox(char *filePath); void loadMeshBoxFromCutTreeWithPose2(cutSurfTreeMngr2* testCut); void loadMeshBoxFromCoordAssign(coordAssignManager * coordAssign); // 1.2. Construct hash table of all voxel void constructVolxeHash(); void constructVolxeHashFromCutTree2(cutSurfTreeMngr2* testCut = nullptr); // 1.3. BVH of voxel of object // But it is actually low performance. Does not use in new code void constructBVHOfMeshBoxesAndHashVoxel(); // 1.4. Assign coordinate manually by user void computeAspectRatio(); // 2. swap one voxel // 2.1 void swapPossibleLayer(); void swapOneVoxel(); // 2.1.a With group bone, which does not have aspect ratio bool swapPossibleLayerWithVolume(); // Only consider volume ratio bool swapPossibleLayerWithVolumeAndAspect(); void cutCenterMeshByHalf(); void restoreCenterMesh(); void growSwap(); //2.2 void swapOneBestVoxel(); void swapOnePossibleVoxel2(); //3.1 Save information for group cutting void saveMeshBox(char* filePath); void initFromSaveFile(); public: std::vector<voxelBox> boxes; // all voxel pixel box hashVoxel hashTable; Vec3f leftDownVoxel, rightUpVoxel; float voxelSize; Vec3i NumXYZ; // Skeleton skeleton m_skeleton; octreeSolid m_octree;// Octree of the total object std::vector<bone*> boneArray; // Sorted by order from cutTree std::vector<bvhVoxel*> meshBox; // box to cut the mesh; sorted by correct order of bone std::vector<std::vector<int>> meshNeighbor; std::vector<Vec3i> coords;// map x-y-z bone on world coord // direct neighbor std::vector<arrayInt> neighborVoxel; int *tempMark; int *voxelOccupy; int m_idx1, m_idx2; // Group bone cut SurfaceObj *s_obj; skeleton *s_skeleton; voxelObject *s_voxelObj; octreeSolid *s_octree; std::vector<voxelBox>* s_boxes; // all voxel pixel box hashVoxel *s_hashTable; std::vector<arrayInt>* s_boxShareFaceWithBox; bool m_bStopThread; private: void setVoxelArray(); float errorReduceAssumeWrap(AABBNode* voxelAABB, int boneSourceIdx, int boneDestIdx); void wrapVoxel(AABBNode* node, int sourceBoneIdx, int desBoneIdx); std::vector<float> getMeshBoxPerimeter(); float getPerimeterError(std::vector<float> perimeter); bool isObjectIfRemove(int boneIndex, int boxIdxToRemove); bool isObjectIfRemove(int boneIndex, arrayInt boxIdxsToRemove); bool isObjectIfRemoveVoxel(int boneIndex, arrayInt boxIdxsToRemove); bool isNeighborMaintainIfRemoveBox(int meshBoxIndex, int ABNodeIdx); bool shouldSwap(AABBNode* voxelAABB, int boneSourceIdx, int boneDestIdx); bool shouldSwap(std::vector<AABBNode*> voxelAABBs, int boneSourceIdx, int boneDestIdx); bool swapBoxLayer(int meshBoxIdx1, int meshBoxIdx2); bool swapBoxLayer2(int meshBoxIdx1, int meshBoxIdx2); bool swapBoxLayerVolume(int meshBoxIdx1, int meshBoxIdx2); bool swapBoxLayerVolumeAndRatio(int meshBoxIdx1, int meshBoxIdx2); bool isBoxInContact(Box b1, Box b2); void getSwapableVoxel(int xyzDirect, float cPos, int meshBoxIdx1, int meshBoxIdx2, arrayInt &swapableIdx1, arrayInt &swapableIdx2, arrayInt &remainIdx1, arrayInt &remainIdx2); void getSwapableVoxel2(int xyzDirect, float cPos, int meshBoxIdx1, int meshBoxIdx2, arrayInt &swapableIdx1, arrayInt &swapableIdx2, arrayInt &remainIdx1, arrayInt &remainIdx2); void getTwoOtherIndex(int xyzDirect, int &xyz1, int &xyz2); bool swapVoxel(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource, arrayInt voxelRemainInLayer, int xyzDirect); bool swapVoxel2(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource, arrayInt voxelRemainInLayer, int xyzDirect); bool swapVoxelVolume(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource, arrayInt voxelRemainInLayer, int xyzDirect); bool swapVoxelVolumeAndRatio(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource, arrayInt voxelRemainInLayer, int xyzDirect); AABBNode* swapNode; // We don't need BVH of the mesh piece public: bool shouldSwap(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdx); bool shouldSwapVolume(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdx); bool shouldSwapVolumeProgress(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdx, arrayFloat &errorSource, arrayFloat &errorDesh); bool shouldSwapVolumeAndRatio(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdx); bool shouldSwapVolumeAndRatioProgress(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdx, arrayFloat &errorSource, arrayFloat &errorDesh); bool shouldSwap2(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdx); bool shouldSwap(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxRemoveFromSource, arrayInt voxelIdxAddToDest); void swapLayer(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource); void getTheVoxelWeShouldSwap(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource, arrayInt &sourceIdx, arrayInt &destIdx); void swapVoxels(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource, arrayInt voxelAddToDest); void getSwapVoxelList(int sourceMeshIdx, int destMeshIdx, arrayInt voxelIdxsInSource, arrayInt &voxelToRemove, arrayInt &voxelToAdd); bool swapBetweenBox(int sourceIdx, int destIdx); bool swapBetweenBox1by1(int sourceIdx, int destIdx); int findPossibleSwapVoxel(int sourceIdx, int destIdx); bool canSwap(int sourceIdx, int destIdx, const arrayInt &temp); arrayFloat getTotalError(float ws, float wd, arrayFloat & eSource, arrayFloat & eDest); float getErrorSum(arrayFloat weight, arrayFloat eOrigin); arrayInt getIdxsShoudSwap(int sourceIdx, int destIdx, arrayInt temp1); std::vector<arrayInt> getIndependentGroup(std::vector<voxelBox>* boxes, arrayInt idxs); bool swap1Voxel(int meshIdx, int sourceIdx); float getBenefit(arrayFloat weight, arrayFloat before, arrayFloat after); bool isBenefitVolume(int sourceIdx, int destIdx); float benefitWithoutVolume(int sourceIdx, int destIdx, arrayInt idxs); void initGroupVoxelFromSaveFile(char* filePath); };
#ifndef SIMULATION_H_INCLUDED #define SIMULATION_H_INCLUDED #include <string> #include <vector> #include <iostream> #include "Grid.h" #include "utilities.h" #include <cmath> #include "Resample.h" #include "Classify.h" #include <sstream> class GOSIM { public: std::vector<Grid *> Reals; // a vector of realizations Grid *TI; // training image Grid *Real; // realization Grid *ConData; // conditioning data GOSIM(); GOSIM(int varnum, int patx, int paty, int patz, int searchiter, int scale_num, std::vector<int> emiters, bool categorical, bool threeDimension, bool conditionalsim, bool histmatch, int categorynum, std::vector<float> w, std::string varianame, std::string outprefix, int factorx, int factory, int factorz, int simgridx, int simgridy, int simgridz, string ti_filename, string con_filename, float low, float high); //construct function //initialize realization grid from grid size and variable numbers(only 1 variable is supported now) Grid *CreateGrid(int length, int width, int height, int varnum, float low, float high); //E-step: search the most similar patterns Grid *PatternSearch(Grid *ti, Grid *real, Grid *condata); //M-step: update the realization grid void GridUpdate(Grid *ti, Grid *real, Grid *errmap); //run GOSIM void GOSIM_run(Grid *ti, Grid *real, int scale, int real_num); Grid *LoadData(std::string filename);//load data to a Grid, support specific format only void SaveData(Grid *grid, std::string filename, std::string variable_name);//save data to a csv file, the same format as input void SaveData2(Grid *grid, std::string filename, std::string variable_name);//save hard data for displaying Grid *Etype(); Grid *SampleData(int dimension, int samplenum); private: bool IsCategorical; // is the data categorical? bool Is3D; //is it 3D data? bool HistMatch; // need to match histogram? bool IsConditional; //conditional simulation? int VarNum; //how many variables used for calculation? std::string variable_name; std::string output_prefix; int category_num; int scales; //Multi-scale. How many scales? int currentscale; //store current scale int resizefactorx; int resizefactory; int resizefactorz; int Search_iterations;//the iteration number for pattern search process std::vector<int> EM_iterations;//the iteration number for EM-iterations std::vector<float> w;//conditioning data weight int patternSizex; int halfPatSizex;//half of the pattern size x int patternSizey; int halfPatSizey;//half of the pattern size y int patternSizez; int halfPatSizez;//half of the pattern size z //relocation of conditioning data Grid *Relocation(Grid *condata, int resizex, int resizey, int resizez); //Calculate the histogram Grid *HistCalc(Grid *grid, int buckets, float minVal, float maxVal); float calc_distance(Grid *ti, Grid *real, Grid *condata, int ti_x, int ti_y, int ti_z, int real_x, int real_y, int real_z, int halfPatSizex, int halfPatSizey, int halfPatSizez, float threshold);// calculate the distance, used for pattern search float find_min(Grid *grid); float find_max(Grid *grid); float minvalue_ti; float maxvalue_ti; float minvalue_real; float maxvalue_real; void Classify(Grid *grid, int category_num, int varnum); }; #endif // SIMULATION_H_INCLUDED
// Name: Zehua Liu // ID: 001086969 /* When testing the wrong input detection, re-enter the current name and score and DON'T re-enter the WHOLE form */ #include<iostream> using namespace std; void insert(int A[], string B[], int n) // Define the insertion sort function { for (int j = 1; j < n; j++) { /* Name and score binding operations: Every time when there's an integer assignment, a corresponding string assignment follows */ int key = A[j]; // Store the number to be compared from the second one string namekey = B[j]; int i = j - 1; while ((i >= 0) && (A[i] <= key)) { // Compare the number with every other number before it // and put it right after the largest one of them A[i + 1] = A[i]; B[i + 1] = B[i]; i--; } A[i + 1] = key; // Fill the blank with the pre-stored number B[i + 1] = namekey; } } int main() { cout << "Please input the size of your class: "; int n; cin >> n; // Get the size of the class cout << "\n"; string* name = new string[n]; // Create the arry for the names int* score = new int[n]; // Create the arry for the scores cout << "Please input the names and the scores: \n"; cout << "(Only enter students' last names as one word \n"; cout << "All grades are integers that have to be in the range from 0 to 100(inclusive)\n"; cout << "Enter one name first, then one score)\n\n"; for (int i = 0; i < n; i++) { cin >> name[i]; // Get the names and the scores and store them cin >> score[i]; if (score[i] > 100 || score[i] < 0) // Detect the wrong score input { cout << "Wrong input! Please re-enter the name and the score\n\n"; i--; continue; // If there's wrong input, re-run THIS loop } } insert(score, name, n); // Call the insertion sort function cout << "\nThe form of students' info: \n"; for (int i = 0; i < n; i++) { cout << name[i] << "\t"; cout << score[i] << "\n"; } // Output the sorted form delete[] name; delete[] score; return 0; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { //基本思想:数学 int overlap_area = 0; int x1, y1, x2, y2; //计算重叠部分的左下角(x1, y1)和右上角(x2, y2) x1 = max(A, E); y1 = max(B, F); x2 = min(C, G); y2 = min(D, H); //两个矩形没有重合部分 if (x2 < x1 || y2 < y1) return (G - E) * (H - F) + (C - A) * (D - B); overlap_area = (x2 - x1) * (y2 - y1); return (G - E) * (H - F) - overlap_area + (C - A) * (D - B); } }; int main() { Solution solute; int a = -3, b = 0, c = 3, d = 4, e = 0, f = -1, g = 9, h = 2; cout << solute.computeArea(a, b, c, d, e, f, g, h) << endl; return 0; }
#include "buffer.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include "error.h" namespace { GLenum toGl(Buffer::Type type) { switch (type) { case Buffer::Type::ARRAY: return GL_ARRAY_BUFFER; case Buffer::Type::COPY_READ: return GL_COPY_READ_BUFFER; case Buffer::Type::COPY_WRITE: return GL_COPY_WRITE_BUFFER; case Buffer::Type::ELEMENT_ARRAY: return GL_ELEMENT_ARRAY_BUFFER; case Buffer::Type::PIXEL_PACK: return GL_PIXEL_PACK_BUFFER; case Buffer::Type::PIXEL_UNPACK: return GL_PIXEL_UNPACK_BUFFER; case Buffer::Type::TEXTURE: return GL_TEXTURE_BUFFER; case Buffer::Type::TRANSFORM_FEEDBACK: return GL_TRANSFORM_FEEDBACK_BUFFER; case Buffer::Type::UNIFORM: return GL_UNIFORM_BUFFER; default: throw std::runtime_error("Unsupported type."); } } GLenum toGl(Buffer::Usage usage) { switch (usage) { case Buffer::Usage::STREAM_DRAW: return GL_STREAM_DRAW; case Buffer::Usage::STREAM_READ: return GL_STREAM_READ; case Buffer::Usage::STREAM_COPY: return GL_STREAM_COPY; case Buffer::Usage::STATIC_DRAW: return GL_STATIC_DRAW; case Buffer::Usage::STATIC_READ: return GL_STATIC_READ; case Buffer::Usage::STATIC_COPY: return GL_STATIC_COPY; case Buffer::Usage::DYNAMIC_DRAW: return GL_DYNAMIC_DRAW; case Buffer::Usage::DYNAMIC_READ: return GL_DYNAMIC_READ; case Buffer::Usage::DYNAMIC_COPY: return GL_DYNAMIC_COPY; default: throw std::runtime_error("Unsupported usage."); } } } Buffer::Buffer(Type type, Usage usage) :_type(type), _usage(usage) { glGenBuffers(1, &_id); gl_error_check(); } Buffer::~Buffer() { if (_id) { glDeleteBuffers(1, &_id); gl_error_check(); } } void Buffer::bind() const { glBindBuffer(toGl(_type), _id); gl_error_check(); } void Buffer::unbind() const { glBindBuffer(toGl(_type), 0); gl_error_check(); } void Buffer::glBufferDataForwarder(Type type, size_t size, const void* data, Usage usage) { glBufferData(toGl(type), size, data, toGl(usage)); gl_error_check(); }
#ifndef WALI_UTIL_CONFIGURATION_VAR_HPP #define WALI_UTIL_CONFIGURATION_VAR_HPP #include <iostream> #include <cstdlib> #include <string> #include <map> #include <boost/any.hpp> namespace wali { namespace util { template<typename BackingType> class ConfigurationVar { std::map<std::string, BackingType> options_; BackingType default_; std::string env_var_name_; public: ConfigurationVar(std::string env_var_name, BackingType const & default_val) : default_(default_val) , env_var_name_(env_var_name) {} void setDefault(BackingType const & val) { default_ = val; } ConfigurationVar & operator() (std::string const & name, BackingType const & val) { assert(options_.count(name) == 0u); options_[name] = val; return *this; } BackingType const & getDefault() const { return default_; } std::string const & getEnvVarName() const { return env_var_name_; } BackingType const & getValueOf(std::string const & name) const { typename std::map<std::string, BackingType>::const_iterator iter = options_.find(name); if(iter != options_.end()) { return iter->second; } else { std::cerr << "Warning: Invalid value for environment variable " << getEnvVarName() << ": " << name << "\n" << "Warning: possible values:\n"; for (typename std::map<std::string, BackingType>::const_iterator iter = options_.begin(); iter != options_.end(); ++iter) { std::cerr << "Warning: " << iter->first << "\n"; } return getDefault(); } } operator BackingType() const { std::string env_var_name = getEnvVarName(); char * env_var_value = std::getenv(env_var_name.c_str()); if (env_var_value != NULL) { return getValueOf(env_var_value); } else { return getDefault(); } } }; } } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Manuela Hutter (manuelah) */ #ifndef FEATURE_CONTROLLER_H #define FEATURE_CONTROLLER_H #include "modules/util/adt/oplisteners.h" class FeatureSettingsContext; /*********************************************************************************** ** @class FeatureControllerListener ** @brief Listener for UI elements to listen to feature settings changes success/failure. ************************************************************************************/ class FeatureControllerListener { public: virtual ~FeatureControllerListener() {} virtual void OnFeatureEnablingSucceeded() = 0; virtual void OnFeatureSettingsChangeSucceeded() = 0; }; /*********************************************************************************** ** @class FeatureController ** @brief Facade, access point for feature UI (sync, webserver) to account ** and feature setup/settings related functions. Must be sub-classed ** per feature. ************************************************************************************/ class FeatureController { public: virtual ~FeatureController() {} // Listener functions for this classes internal listener OP_STATUS AddListener(FeatureControllerListener* listener) { return m_listeners.Add(listener); } OP_STATUS RemoveListener(FeatureControllerListener* listener) { return m_listeners.Remove(listener); } virtual BOOL IsFeatureEnabled() const = 0; virtual void EnableFeature(const FeatureSettingsContext* settings) = 0; virtual void DisableFeature() = 0; virtual void SetFeatureSettings(const FeatureSettingsContext* settings) = 0; // forward common messages to the appropriate place virtual void InvokeMessage(OpMessage msg, MH_PARAM_1 param_1, MH_PARAM_2 param_2) = 0; protected: OpListeners<FeatureControllerListener>& GetListeners() { return m_listeners; } // helper functions to broadcast to UI void BroadcastOnFeatureEnablingSucceeded(); void BroadcastOnFeatureSettingsChangeSucceeded(); private: OpListeners<FeatureControllerListener> m_listeners; }; #endif // FEATURE_CONTROLLER_H
#include "btb.h" #define MAX_TCM_BUNDLE 16 // A TCM entry typedef struct { // Metadata for hit/miss determination and replacement. bool valid; uint64_t tag; uint64_t lru; uint64_t br_flags; uint64_t br_mask; uint64_t ends_in_br; // Payload. uint64_t tcm_bundle_length; //length of the trace cache bundle btb_output_t tcm_fetch_bundle[MAX_TCM_BUNDLE]; // TCM's output for the fetch bundle. uint64_t fall_thru_pc; //equal to pc incremented by fetch bundle width BUG_FIX } tcm_entry_t; class tcm_t { private: // The trace cache has 2 dimensions: number of sets and number of ways per set (associativity) tcm_entry_t **tcm; uint64_t cond_branch_per_cycle; uint64_t num_instr_per_cycle; uint64_t sets; uint64_t assoc; uint64_t log2sets; // number of pc bits that selects the set within a bank uint64_t pc_line_fill; uint64_t cb_predictions_line_fill; uint64_t br_cntr_line_fill; uint64_t cond_branch_line_fill; // "m": maximum number of conditional branches in the line fill. uint64_t br_mask_line_fill; uint64_t valid_line_fill; //line fill buffer has a valid entry in it uint64_t index_line_fill; uint64_t tag_line_fill; uint64_t line_fill_full; // assert when m branches or max instructions present in line fill, deassert when commit or rollback tcm_entry_t line_fill_buffer_entry; //line fill buffer checkpoint uint64_t valid; uint64_t cond_branch; uint64_t br_mask; uint64_t br_cntr; tcm_entry_t checkpoint_line; //////////////////////////////////// // Private utility functions. // Comments are in tcm.cc. //////////////////////////////////// bool search(uint64_t pc, uint64_t cb_predictions, uint64_t &set, uint64_t &way); void update_lru(uint64_t set, uint64_t way); //void checkpoint_line_fill(); public: tcm_t(uint64_t num_entries, uint64_t assoc, uint64_t num_instr_per_cycle, uint64_t cond_branch_per_cycle); ~tcm_t(); // Search the TCM for a hit // Inputs: pc: PC for the first instruction of the bundle // cb_predictions: "m" predictions from branch predictor // Outputs:returns true if TCM hit else returns false // tcm_bundle_length: length of the bundle // tcm_detch_bundle: the non sequential fetch bundle // next_pc: used as fall through pc for call direct and jump, call indirect and return bool lookup(uint64_t pc, uint64_t cb_predictions, uint64_t &tcm_bundle_length, btb_output_t tcm_fetch_bundle[], uint64_t &tcm_next_pc); // Called after btb is hit and fetch bundle is formed void line_fill_buffer(uint64_t pc, uint64_t cb_predictions, uint64_t fetch_bundle_length, btb_output_t btb_fetch_bundle[], uint64_t next_pc);//TODO assert while filling line, last_pc == next_pc // At btb_miss, clear the last entry pushed in line fill buffer //void rollback_line_fill(); // At the end of a properly formed fetch bundle, // commit the last entry pushed in line fill buffer void commit_line_fill(); void clear_line_fill(); };
// // Created by seafood on 2020-09-28 // #ifndef _STATE_CLASSIFYING_TARGET_H_ #define _STATE_CLASSIFYING_TARGET_H_ #include "ArmorBox.h" #include "GetFeature.h" class StateClassifyingTarget{ public: ArmorBox run(cv::Mat &g_srcImage,cv::Mat &g_processImage, armorBoxes armorboxes); //运行函数 private: ArmorBox numberClassifyRoi(cv::Mat &g_srcImage,cv::Mat &g_processImage, armorBoxes armorboxes); //数字分类器 double getarmorPixelS(); // 获取灯条长度和间距的比例 //double getBlobsDistance(); // 获取两个灯条中心点的间距 }; #endif
// // Created by wind on 2023/3/28. // #ifndef NDK_OPENGLES_ASSET_PNG_DECODER_H #define NDK_OPENGLES_ASSET_PNG_DECODER_H #include "../libpng/png_decoder.h" #include <android/asset_manager.h> #include "../log.h" class AssetPngDecoder: public PngDecoder{ public: AssetPngDecoder(AAssetManager* mgr ,char *fName); virtual ~AssetPngDecoder(); virtual void pngReadCallback(png_bytep data, png_size_t length); protected: virtual void fClose(); virtual png_bytep readHead(); private: AAsset* asset; }; #endif //NDK_OPENGLES_ASSET_PNG_DECODER_H
// detail/sp_convertible.hpp // // Copyright 2008 Peter Dimov // // SPDX-License-Identifier: BSL-1.0 // 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 #pragma once #include <pika/config.hpp> #include <cstddef> namespace pika::memory::detail { template <typename Y, typename T> struct sp_convertible { using yes = char (&)[1]; using no = char (&)[2]; static yes f(T*); static no f(...); static constexpr bool value = sizeof((f) (static_cast<Y*>(nullptr))) == sizeof(yes); }; template <typename Y, typename T> struct sp_convertible<Y, T[]> { static constexpr bool value = false; }; template <typename Y, typename T> struct sp_convertible<Y[], T[]> { static constexpr bool value = sp_convertible<Y[1], T[1]>::value; }; template <typename Y, std::size_t N, typename T> struct sp_convertible<Y[N], T[]> { static constexpr bool value = sp_convertible<Y[1], T[1]>::value; }; template <typename Y, typename T> inline constexpr bool sp_convertible_v = sp_convertible<Y, T>::value; } // namespace pika::memory::detail
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> using namespace std; struct point{ double x,y; point(double x=0,double y=0):x(x),y(y) {} }; point a[110]; const int r = 6730; const double pi = 3.1415926; double dis(point i,point j) { double t = r*acos(sin(i.y)*sin(j.y)*cos(i.x-j.x)+cos(i.y)*cos(i.y)); cout << t << endl; return r*acos(sin(i.y)*sin(j.y)*cos(i.x-j.x)+cos(i.y)*cos(i.y)); } int main() {int n; while (cin >> n) {double ans = 10*r; for (int i = 1;i <= n; i++) {cin >> a[i].x >> a[i].y; a[i].x = a[i].x/180*pi; a[i].y = a[i].y/180*pi; } for (int i = 1;i < n; i++) for (int j = i+1;j <= n; j++) ans = min(ans,dis(a[i],a[j])); printf("%.2lf\n",ans); } return 0; }
#include "gwmessage/GWDeviceListRequest.h" #include "gwmessage/GWDeviceListResponse.h" using namespace std; using namespace Poco; using namespace BeeeOn; GWDeviceListRequest::GWDeviceListRequest(): GWRequest(GWMessageType::DEVICE_LIST_REQUEST) { } GWDeviceListRequest::GWDeviceListRequest(const JSON::Object::Ptr object) : GWRequest(object) { } void GWDeviceListRequest::setDevicePrefix(const DevicePrefix &prefix) { json()->set("device_prefix", prefix.toString()); } DevicePrefix GWDeviceListRequest::devicePrefix() const { return DevicePrefix::parse(json()->getValue<string>("device_prefix")); } GWResponse::Ptr GWDeviceListRequest::deriveResponse() const { GWDeviceListResponse::Ptr response(new GWDeviceListResponse); return deriveGenericResponse(response); }
/* Name: Adrian Dy SID: 861118847 Date: 5/14/2015 */ #include "selectionsort.h" using namespace std; int main() { list<int> list0; list0.push_back(2); list0.push_back(4); list0.push_back(5); list0.push_back(1); list0.push_back(8); list0.push_back(9); cout << "pre: "; displaySingle(list0); selectionsort(list0); cout << "post: "; displaySingle(list0); //----next list with pair------------- typedef pair<int,int> Pair; list<Pair> list1; list1.push_back( make_pair(1,2) ); list1.push_back( make_pair(3,-1) ); list1.push_back( make_pair(-1,3) ); list1.push_back( make_pair(0,0) ); list1.push_back( make_pair(2,3) ); list1.push_back( make_pair(1,2) ); list1.push_back( make_pair(1,-2) ); list1.push_back( make_pair(8,10) ); cout << endl; cout << "pre: "; displayPair(list1); selectionsort(list1); cout << "post: "; displayPair(list1); //----next vector with pair------------- vector<Pair> vect0; vect0.push_back( make_pair(10,2) ); vect0.push_back( make_pair(-3,-1) ); vect0.push_back( make_pair(-8,0) ); vect0.push_back( make_pair(1,1) ); vect0.push_back( make_pair(1,1) ); vect0.push_back( make_pair(0,0) ); vect0.push_back( make_pair(10,2) ); vect0.push_back( make_pair(5,5) ); vect0.push_back( make_pair(5,-5) ); vect0.push_back( make_pair(0,0) ); vect0.push_back( make_pair(10,2) ); cout << endl; cout << "pre: "; displayPair(vect0); selectionsort(vect0); cout << "post: "; displayPair(vect0); //----next list with pair------------- typedef pair<int,int> Pair; list<Pair> list2; list2.push_back( make_pair(-1,3) ); list2.push_back( make_pair(0,0) ); list2.push_back( make_pair(1,-2) ); list2.push_back( make_pair(1,2) ); list2.push_back( make_pair(1,2) ); list2.push_back( make_pair(2,3) ); list2.push_back( make_pair(3,-1) ); list2.push_back( make_pair(8,10) ); cout << endl; cout << "pre: "; displayPair(list2); selectionsort(list2); cout << "post: "; displayPair(list1); //------------------- cout << endl << endl; cout << "Question 2: " << endl; cout << "part a: selection sort is not stable due to the swap(), bigger value swaps with the min value"; cout << " which displaces the values initial position " << endl; cout << "part b: In the 3rd example (5, 5) (5, -5) became (5, -5) (5, 5), confirming that "; cout << "the algorithm is unstable " << endl; return 0; }
#include "CombatStates.h" #include "States/StateThings_incl.h" State create_grounded_attack_state() { State ret = State("Grounded attack"); ret.Position_state = PositionState::Grounded; ret.Action_state = ActionState::Attacking; ret.enter = [](Player& p) { }; ret.exit = [](Player& p) { }; ret.update = [](Player& p, float dt) { combat_perform_attack(p, dt); }; return ret; } State create_airborne_attack_state() { State ret = State("Airborne attack"); ret.Position_state = PositionState::Airborne; ret.Action_state = ActionState::Attacking; ret.enter = [](Player& p) { }; ret.exit = [](Player& p) { }; ret.update = [](Player& p, float dt) { combat_perform_attack(p, dt); }; return ret; } void combat_perform_attack(Player& p, float dt) { ActionStateComponent& state = p.ActionState; CombatComponent& combat = p.Combat; AnimationComponent& anim = p.Animation; InputComponent input = p.Input; combat.Current_timer += dt; if (anim.Current_Sprite_Index >= combat.Current_attack->Hitbox_start_frame && anim.Current_Sprite_Index <= combat.Current_attack->Hitbox_stop_frame && !combat.Is_current_attack_resolved) { CollisionTestRequest request = CollisionTestRequest(); AnimationComponent anim = p.Animation; request.Instigator = &p; request.Target = p.Opponent; ColliderComponent col_comp = p.Combat.Current_attack->Hitbox; request.Collider = col_comp; request.Collider.Position = p.Transform.Position; request.Collider.Offset.x = col_comp.Offset.x * (p.Animation.Is_flipped ? -1 : 1); queue_collision(request); } if (anim.Has_full_anim_played) { combat.Current_timer = 0.0f; anim.Has_full_anim_played = false; anim.Anim_state = Loop; combat.Allow_attacking_movement = false; if (state.Position_state == PositionState::Grounded) { if (p.Locomotion.Ledge_balance_queued && input.Left_stick_x == 0.0f) { //set_player_state(p, ActionState::LedgeBalance); //change_player_animation(p, get_anim(10), Loop); p.Locomotion.Ledge_balance_queued = false; } else { //set_player_state(p, ActionState::Idle); p.Locomotion.Ledge_balance_queued = false; } } else { //set_player_state(p, ActionState::Falling); } } }
#include <iostream> #include <NeuralRealisation.h> using namespace std; using namespace ANN; int main() { cout << "hello ANN!" << endl; cout << GetTestString().c_str() << endl; std::vector<size_t> l; l.push_back(3); l.push_back(3); l.push_back(3); auto ann = CreateNeuralNetwork(l, ANN::ANeuralNetwork::ActivationType::POSITIVE_SYGMOID, 1); ann->Load("ann.txt"); return 0; }
//////////////////////////////////////////////////////////////////////////////// // // (C) Andy Thomason 2012-2014 // // Modular Framework for OpenGLES2 rendering on multiple platforms. // namespace octet { /// Scene containing a box with octet. class example_compute : public app { // scene for drawing box ref<visual_scene> app_scene; // a computer shader to generate geometry. ref<compute_shader> compute; // the mesh for our geometry ref<mesh> helix; // resolution of our geometry size_t num_steps; // the format of our vertex struct my_vertex { vec4 pos; vec4 color; }; public: /// this is called when we construct the class before everything is initialised. example_compute(int argc, char **argv) : app(argc, argv) { } /// this is called once OpenGL is initialized void app_init() { app_scene = new visual_scene(); app_scene->create_default_camera_and_lights(); compute = new compute_shader("shaders/helix.cs"); // use a shader that just outputs the color_ attribute. param_shader *shader = new param_shader("shaders/default.vs", "shaders/simple_color.fs"); material *red = new material(vec4(1, 0, 0, 1), shader); // create a new mesh. helix = new mesh(); // number of steps in helix. Increase this to make it smoother num_steps = 320; // allocate vertices and indices into OpenGL buffers size_t num_vertices = num_steps * 2 + 2; size_t num_indices = num_steps * 6; helix->allocate(sizeof(my_vertex)* num_vertices, sizeof(uint32_t)* num_indices); helix->set_params(sizeof(my_vertex), num_indices, num_vertices, GL_TRIANGLES, GL_UNSIGNED_INT); { // this step seems to be necessary on AMD drivers gl_resource::wolock vl(helix->get_vertices()); memset(vl.u8(), 0xff, helix->get_vertices()->get_size()); } // describe the structure of my_vertex to OpenGL helix->add_attribute(attribute_pos, 3, GL_FLOAT, 0); helix->add_attribute(attribute_color, 4, GL_FLOAT, 16); { // make the index buffer gl_resource::wolock il(helix->get_indices()); uint32_t *idx = il.u32(); // make the triangles: note we could have just used a tristrip here... uint32_t vn = 0; for (size_t i = 0; i != num_steps; ++i) { idx[0] = vn + 0; idx[1] = vn + 3; idx[2] = vn + 1; idx += 3; idx[0] = vn + 0; idx[1] = vn + 2; idx[2] = vn + 3; idx += 3; vn += 2; } } // add a scene node with this new mesh. scene_node *node = new scene_node(); app_scene->add_child(node); app_scene->add_mesh_instance(new mesh_instance(node, helix, red)); } /// this is called to draw the world void draw_world(int x, int y, int w, int h) { int vx = 0, vy = 0; get_viewport_size(vx, vy); app_scene->begin_render(vx, vy); // update matrices. assume 30 fps. app_scene->update(1.0f/30); // animate the radii int frame = get_frame_number(); float radius1 = cosf(frame * 3.14159265f / 100) * 10.0f; float radius2 = sinf(frame * 3.14159265f / 100) * 10.0f; // run the compute shader to generate dynamic geometry compute->use(); // copy variables to the program GLuint prog = compute->get_program(); glUniform1i(glGetUniformLocation(prog, "num_steps"), (int)num_steps); glUniform1f(glGetUniformLocation(prog, "radius1"), radius1); glUniform1f(glGetUniformLocation(prog, "radius2"), radius2); // bind the vertex buffer to out_buf glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, helix->get_vertices()->get_buffer()); // kick the shader. compute->dispatch((num_steps + 63) / 64); // unbind the vertex buffer glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0); // make sure the memory writes happen before reading the vertices. // this is needed because the computer shader and vertex shader run asyncronously. glMemoryBarrier(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT); // draw the scene app_scene->render((float)vx / vy); // spin the helix scene_node *node = app_scene->get_mesh_instance(0)->get_node(); node->rotate(5, vec3(0, 1, 0)); } }; }
#include <fstream> #include <math.h> #include <stdlib.h> #include <stdio.h> //#include <vector.h> #include <iostream> #include <string> #include <string.h> #include <iomanip> #include <sstream> #include "TH2D.h" #include "TF1.h" #include "TH1D.h" #include "TCanvas.h" #include "TStyle.h" #include "TRandom3.h" #include "TVirtualFitter.h" #include "TList.h" #include "TStopwatch.h" #include "TMinuit.h" #include "TMath.h" #include "TGraph.h" #include "TFile.h" #include "TBranch.h" #include "TH2F.h" #include "TLine.h" #include "TMarker.h" #include "TTree.h" #include <stdlib.h> #include "TAxis.h" #include "TEventList.h" using namespace::std; int main(int argc, const char* argv[]) { string SM=(string)argv[1]; string date=(string)argv[2]; ///////////////////////////////////////////////////////// // Open and read file with LVR data FILE *inAPDcurrFile; // input file with APD temperatures char * dcuhome = getenv("DCU_HOME"); string dcuHome=dcuhome; string inputFile = date; string dcuWeb = "/data/ecalod-disk01/dcu-data/plots"; //inputFile=dcuHome+inputFile; inAPDcurrFile = fopen(inputFile.c_str(),"r"); if(!inAPDcurrFile) { cout<<"can not open file "<< inputFile.c_str() <<endl; return 0; } int ii=0; // TT counter 0-67 int TT; double f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15; double f16,f17,f18,f19,f20,f21,f22,f23,f24,f25; Double_t IdTT[68]; // Trig Tower counter 1-68 for root file // 25 variables for the 5 values read by each one of the 5 DCUs // DCU on VFE1 Double_t Vfe1c1[68]; // Vfe1 current of crystal 1 Double_t Vfe1c2[68]; Double_t Vfe1c3[68]; Double_t Vfe1c4[68]; Double_t Vfe1c5[68]; // DCU on VFE2 Double_t Vfe2c1[68]; // Vfe2 current of crystal 1 Double_t Vfe2c2[68]; Double_t Vfe2c3[68]; Double_t Vfe2c4[68]; Double_t Vfe2c5[68]; // DCU on VFE3 Double_t Vfe3c1[68]; // Vfe3 current of crystal 1 Double_t Vfe3c2[68]; Double_t Vfe3c3[68]; Double_t Vfe3c4[68]; Double_t Vfe3c5[68]; // DCU on VFE4 Double_t Vfe4c1[68]; // Vfe4 current of crystal 1 Double_t Vfe4c2[68]; Double_t Vfe4c3[68]; Double_t Vfe4c4[68]; Double_t Vfe4c5[68]; // DCU on VFE5 Double_t Vfe5c1[68]; // Vfe5 current of crystal 1 Double_t Vfe5c2[68]; Double_t Vfe5c3[68]; Double_t Vfe5c4[68]; Double_t Vfe5c5[68]; bool Flag=true; bool flag=true; int BLcurrtrend=0; //open Blacklisted values cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; cout<<"~ APD curr test ~"<<endl; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; cout<<""<<endl; //open Balcklist string APDcurrfile=dcuHome+"/root/Known_error/APDcurrKnown.txt"; // cout<<APDcurrfile<<endl; ifstream in(APDcurrfile.c_str()); string a1; int b3; Int_t BLCurr[1700]; int j=0; while (in>> a1>> b3){ if ((a1== SM) ){ // cout<<"Crystal "<<b3<<" for SM "<<SM<<" has been blacklisted "<<endl; BLCurr[j]=b3; j++; } } string dummy1,dummy2,dummy3,dummy4,dummy5,dummy6; ifstream apdcurr(inputFile.c_str()); while(apdcurr >> dummy1 >> dummy2){ break; } while(apdcurr >> dummy1 >> dummy2){ break; } while(apdcurr >> dummy1 >> dummy2){ break; } while(apdcurr >> dummy1 >> dummy2 >> dummy3 >>dummy4 >>dummy5){ break; } while(apdcurr >> dummy1 >> dummy2 >> dummy3 >>dummy4 >>dummy5 >>dummy6){ break; } Double_t APDCurrData[68][25]; Double_t minC ; minC = 200.; Double_t maxC ; maxC = -200.; // fgets(line1,255,inAPDcurrFile); // skip 5 header lines //fgets(line1,255,inAPDcurrFile); // //fgets(line1,255,inAPDcurrFile); // //fgets(line1,255,inAPDcurrFile); // //fgets(line1,255,inAPDcurrFile); // while(apdcurr >> TT >> f1 >> f2 >> f3 >> f4 >> f5 >>f6 >> f7 >> f8 >> f9 >> f10 >> f11 >> f12 >> f13 >> f14 >> f15 >> f16 >> f17 >> f18 >> f19 >> f20 >> f21 >> f22 >> f23 >> f24 >> f25) { //cout << "TT="<<TT<< " f1-25= "<< " "<<f1 << " "<<f2<< "... "<<f23<< " "<<f24<< " "<<f25<<endl; IdTT[ii]=TT; Vfe1c1[ii] =f1; Vfe1c2[ii] =f2; Vfe1c3[ii] =f3; Vfe1c4[ii] =f4; Vfe1c5[ii] =f5; // DCU on VFE2 Vfe2c1[ii] =f6; Vfe2c2[ii] =f7; Vfe2c3[ii] =f8; Vfe2c4[ii] =f9; Vfe2c5[ii] =f10; // DCU on VFE3 Vfe3c1[ii] =f11; Vfe3c2[ii] =f12; Vfe3c3[ii] =f13; Vfe3c4[ii] =f14; Vfe3c5[ii] =f15; // DCU on VFE4 Vfe4c1[ii] =f16; Vfe4c2[ii] =f17; Vfe4c3[ii] =f18; Vfe4c4[ii] =f19; Vfe4c5[ii] =f20; // DCU on VFE5 Vfe5c1[ii] =f21; Vfe5c2[ii] =f22; Vfe5c3[ii] =f23; Vfe5c4[ii] =f24; Vfe5c5[ii] =f25; ii++; //find min current to be used for axis of plots if(f1 < minC ) minC = f1 ; if(f2 < minC ) minC = f2 ; if(f3 < minC ) minC = f3 ; if(f4 < minC ) minC = f4 ; if(f5 < minC ) minC = f5 ; if(f6 < minC ) minC = f6 ; if(f7 < minC ) minC = f7 ; if(f8 < minC ) minC = f8 ; if(f9 < minC ) minC = f9 ; if(f10 < minC ) minC = f10 ; if(f11 < minC ) minC = f11 ; if(f12 < minC ) minC = f12 ; if(f13 < minC ) minC = f13 ; if(f14 < minC ) minC = f14 ; if(f15 < minC ) minC = f15 ; if(f16 < minC ) minC = f16 ; if(f17 < minC ) minC = f17 ; if(f18 < minC ) minC = f18 ; if(f19 < minC ) minC = f19 ; if(f20 < minC ) minC = f20 ; if(f21 < minC ) minC = f21 ; if(f22 < minC ) minC = f22 ; if(f23 < minC ) minC = f23 ; if(f24 < minC ) minC = f24 ; if(f25 < minC ) minC = f25 ; //find max current if(f1 > maxC ) maxC = f1 ; if(f2 > maxC ) maxC = f2 ; if(f3 > maxC ) maxC = f3 ; if(f4 > maxC ) maxC = f4 ; if(f5 > maxC ) maxC = f5 ; if(f6 > maxC ) maxC = f6 ; if(f7 > maxC ) maxC = f7 ; if(f8 > maxC ) maxC = f8 ; if(f9 > maxC ) maxC = f9 ; if(f10 > maxC ) maxC = f10 ; if(f11 > maxC ) maxC = f11 ; if(f12 > maxC ) maxC = f12 ; if(f13 > maxC ) maxC = f13 ; if(f14 > maxC ) maxC = f14 ; if(f15 > maxC ) maxC = f15 ; if(f16 > maxC ) maxC = f16 ; if(f17 > maxC ) maxC = f17 ; if(f18 > maxC ) maxC = f18 ; if(f19 > maxC ) maxC = f19 ; if(f20 > maxC ) maxC = f20 ; if(f21 > maxC ) maxC = f21 ; if(f22 > maxC ) maxC = f22 ; if(f23 > maxC ) maxC = f23 ; if(f24 > maxC ) maxC = f24 ; if(f25 > maxC ) maxC = f25 ; //try to put the data into a vector APDCurrData[TT-1][0]=f1; APDCurrData[TT-1][1]=f2; APDCurrData[TT-1][2]=f3; APDCurrData[TT-1][3]=f4; APDCurrData[TT-1][4]=f5; APDCurrData[TT-1][5]=f6; APDCurrData[TT-1][6]=f7; APDCurrData[TT-1][7]=f8; APDCurrData[TT-1][8]=f9; APDCurrData[TT-1][9]=f10; APDCurrData[TT-1][10]=f11; APDCurrData[TT-1][11]=f12; APDCurrData[TT-1][12]=f13; APDCurrData[TT-1][13]=f14; APDCurrData[TT-1][14]=f15; APDCurrData[TT-1][15]=f16; APDCurrData[TT-1][16]=f17; APDCurrData[TT-1][17]=f18; APDCurrData[TT-1][18]=f19; APDCurrData[TT-1][19]=f20; APDCurrData[TT-1][20]=f21; APDCurrData[TT-1][21]=f22; APDCurrData[TT-1][22]=f23; APDCurrData[TT-1][23]=f24; APDCurrData[TT-1][24]=f25; for (int y=0;y<25;y++){ if ((APDCurrData[TT-1][y]>=15) ){ Flag=false; for(int k=0;k<=j;k++){ if(BLCurr[k]==((TT-1)*25)+y-1){ cout<<"APD current in TT "<<TT<<" for Crystal(electronic crystal number!) "<<((TT-1)*25)+y-1 <<" in SM "<<SM<<" has problem (APDcurr="<<APDCurrData[TT-1][y]<<") - Known Error"<<endl; Flag=true; BLcurrtrend--; } } if(Flag==false){ cout<<"APD current in TT "<<TT<<" for Crystal(electronic crystal number!!) "<<((TT-1)*25)+y-1 <<" in SM "<<SM<<" has problem (APDcurr="<<APDCurrData[TT-1][y]<<")"<<endl; flag=false; } } } } // fclose(inAPDcurrFile); //Blacklisted conservation int token=1; if(BLcurrtrend+j != 0){ cout<<" "<<endl; cout<<" ----------WARNING---------"<<endl; cout<<j<<" APD lekeage current in "<<SM<<" were masked out, while only "<<BLcurrtrend<<" have been discovered"<<endl; cout<<"please check the blacklist:"<<endl; for (int counter=0;counter<j;counter++){ cout<<counter+1<<") APD curr for xtal "<<BLCurr[counter]<<" has been blacklisted "<<endl; } token=3; flag=false; } //check data ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // Open a root file and make plots string label=SM+" APD Currents pedestal subtracted"; string TFileStr1 = dcuWeb+"/Barrel/APDcurrent/Histogram/Histogram_"+SM+".gif"; // histogram for all 2Barrel/APDcurrent/Histogram/Histogram_"+SM+".gif"; // TFileStr=TFileStr; // TFile rootAPDcurr(TFileStr.c_str(), "RECREATE", "APD currents"); // APD Current histogram TCanvas *c14 = new TCanvas("c14","APD Currents",70,70,500,400); minC = minC -1 ; maxC = maxC +2 ; //minC=0; //maxC=15.110; // to be used with a 47-channel histo TH1D * T1Histo = new TH1D("APD Currents",label.c_str(),30,minC,maxC); for(Int_t i=0; i<68; i++){ if(Vfe1c1[i]>minC && Vfe1c1[i]<maxC) T1Histo->Fill(Vfe1c1[i]); if(Vfe1c2[i]>minC && Vfe1c2[i]<maxC) T1Histo->Fill(Vfe1c2[i]); if(Vfe1c3[i]>minC && Vfe1c3[i]<maxC) T1Histo->Fill(Vfe1c3[i]); if(Vfe1c4[i]>minC && Vfe1c4[i]<maxC) T1Histo->Fill(Vfe1c4[i]); if(Vfe1c5[i]>minC && Vfe1c5[i]<maxC) T1Histo->Fill(Vfe1c5[i]); if(Vfe2c1[i]>minC && Vfe2c1[i]<maxC) T1Histo->Fill(Vfe2c1[i]); if(Vfe2c2[i]>minC && Vfe2c2[i]<maxC) T1Histo->Fill(Vfe2c2[i]); if(Vfe2c3[i]>minC && Vfe2c3[i]<maxC) T1Histo->Fill(Vfe2c3[i]); if(Vfe2c4[i]>minC && Vfe2c4[i]<maxC) T1Histo->Fill(Vfe2c4[i]); if(Vfe2c5[i]>minC && Vfe2c5[i]<maxC) T1Histo->Fill(Vfe2c5[i]); if(Vfe3c1[i]>minC && Vfe3c1[i]<maxC) T1Histo->Fill(Vfe3c1[i]); if(Vfe3c2[i]>minC && Vfe3c2[i]<maxC) T1Histo->Fill(Vfe3c2[i]); if(Vfe3c3[i]>minC && Vfe3c3[i]<maxC) T1Histo->Fill(Vfe3c3[i]); if(Vfe3c4[i]>minC && Vfe3c4[i]<maxC) T1Histo->Fill(Vfe3c4[i]); if(Vfe3c5[i]>minC && Vfe3c5[i]<maxC) T1Histo->Fill(Vfe3c5[i]); if(Vfe4c1[i]>minC && Vfe4c1[i]<maxC) T1Histo->Fill(Vfe4c1[i]); if(Vfe4c2[i]>minC && Vfe4c2[i]<maxC) T1Histo->Fill(Vfe4c2[i]); if(Vfe4c3[i]>minC && Vfe4c3[i]<maxC) T1Histo->Fill(Vfe4c3[i]); if(Vfe4c4[i]>minC && Vfe4c4[i]<maxC) T1Histo->Fill(Vfe4c4[i]); if(Vfe4c5[i]>minC && Vfe4c5[i]<maxC) T1Histo->Fill(Vfe4c5[i]); if(Vfe5c1[i]>minC && Vfe5c1[i]<maxC) T1Histo->Fill(Vfe5c1[i]); if(Vfe5c2[i]>minC && Vfe5c2[i]<maxC) T1Histo->Fill(Vfe5c2[i]); if(Vfe5c3[i]>minC && Vfe5c3[i]<maxC) T1Histo->Fill(Vfe5c3[i]); if(Vfe5c4[i]>minC && Vfe5c4[i]<maxC) T1Histo->Fill(Vfe5c4[i]); if(Vfe5c5[i]>minC && Vfe5c5[i]<maxC) T1Histo->Fill(Vfe5c5[i]); } T1Histo -> GetXaxis() -> SetTitle("I (#muA)"); T1Histo -> SetLineColor(1); c14->SetLogy(); T1Histo -> Draw(); Double_t y_max; y_max = T1Histo->GetBinContent(T1Histo->GetMaximumBin()); TLine *line_m = new TLine(0 ,0.0, 0 ,y_max + 10); TLine *line_M = new TLine(15 ,0.0,15 ,y_max + 10); line_m->SetLineColor(2); line_m->Draw(); line_M->SetLineColor(2); line_M->Draw(); T1Histo->Draw(); c14->Print(TFileStr1.c_str(),"gif"); //old sting string TFileStr2 = "/localdata/dcu-data/plots/Barrel/APDcurrent/CurrVsTT/CurrVFE123_"+SM+".gif"; string TFileStr2 =dcuWeb+"/Barrel/APDcurrent/CurrVsTT/CurrVFE123_"+SM+".gif"; // // APD Currents Temperature Vs Trig Tower TCanvas *c12 = new TCanvas("c12","APD CurrentsVFE123",150,150,1000,700); // Vfe1c1 TGraph *Vfe1c1VsTT = new TGraph(68,IdTT,Vfe1c1); Vfe1c1VsTT-> SetTitle(label.c_str()) ; Vfe1c1VsTT->SetMarkerStyle(24); Vfe1c1VsTT-> SetMinimum(minC); Vfe1c1VsTT-> SetMaximum(maxC); Vfe1c1VsTT-> GetXaxis() -> SetTitle("Counter 1 to 68 for Trigger Towers"); Vfe1c1VsTT-> GetYaxis() -> SetTitle("I (#muA)"); Vfe1c1VsTT->Draw("AP"); // all other 24 Vfe#c# TGraph *Vfe1c2VsTT = new TGraph(68,IdTT,Vfe1c2); TGraph *Vfe1c3VsTT = new TGraph(68,IdTT,Vfe1c3); TGraph *Vfe1c4VsTT = new TGraph(68,IdTT,Vfe1c4); TGraph *Vfe1c5VsTT = new TGraph(68,IdTT,Vfe1c5); TGraph *Vfe2c1VsTT = new TGraph(68,IdTT,Vfe2c1); TGraph *Vfe2c2VsTT = new TGraph(68,IdTT,Vfe2c2); TGraph *Vfe2c3VsTT = new TGraph(68,IdTT,Vfe2c3); TGraph *Vfe2c4VsTT = new TGraph(68,IdTT,Vfe2c4); TGraph *Vfe2c5VsTT = new TGraph(68,IdTT,Vfe2c5); TGraph *Vfe3c1VsTT = new TGraph(68,IdTT,Vfe3c1); TGraph *Vfe3c2VsTT = new TGraph(68,IdTT,Vfe3c2); TGraph *Vfe3c3VsTT = new TGraph(68,IdTT,Vfe3c3); TGraph *Vfe3c4VsTT = new TGraph(68,IdTT,Vfe3c4); TGraph *Vfe3c5VsTT = new TGraph(68,IdTT,Vfe3c5); TGraph *Vfe4c1VsTT = new TGraph(68,IdTT,Vfe4c1); TGraph *Vfe4c2VsTT = new TGraph(68,IdTT,Vfe4c2); TGraph *Vfe4c3VsTT = new TGraph(68,IdTT,Vfe4c3); TGraph *Vfe4c4VsTT = new TGraph(68,IdTT,Vfe4c4); TGraph *Vfe4c5VsTT = new TGraph(68,IdTT,Vfe4c5); TGraph *Vfe5c1VsTT = new TGraph(68,IdTT,Vfe5c1); TGraph *Vfe5c2VsTT = new TGraph(68,IdTT,Vfe5c2); TGraph *Vfe5c3VsTT = new TGraph(68,IdTT,Vfe5c3); TGraph *Vfe5c4VsTT = new TGraph(68,IdTT,Vfe5c4); TGraph *Vfe5c5VsTT = new TGraph(68,IdTT,Vfe5c5); Vfe1c2VsTT->SetMarkerStyle(24); Vfe1c3VsTT->SetMarkerStyle(24); Vfe1c4VsTT->SetMarkerStyle(24); Vfe1c5VsTT->SetMarkerStyle(24); Vfe2c1VsTT->SetMarkerStyle(24); Vfe2c2VsTT->SetMarkerStyle(24); Vfe2c3VsTT->SetMarkerStyle(24); Vfe2c4VsTT->SetMarkerStyle(24); Vfe2c5VsTT->SetMarkerStyle(24); Vfe3c1VsTT->SetMarkerStyle(24); Vfe3c2VsTT->SetMarkerStyle(24); Vfe3c3VsTT->SetMarkerStyle(24); Vfe3c4VsTT->SetMarkerStyle(24); Vfe3c5VsTT->SetMarkerStyle(24); Vfe4c1VsTT->SetMarkerStyle(24); Vfe4c2VsTT->SetMarkerStyle(24); Vfe4c3VsTT->SetMarkerStyle(24); Vfe4c4VsTT->SetMarkerStyle(24); Vfe4c5VsTT->SetMarkerStyle(24); Vfe5c1VsTT->SetMarkerStyle(24); Vfe5c2VsTT->SetMarkerStyle(24); Vfe5c3VsTT->SetMarkerStyle(24); Vfe5c4VsTT->SetMarkerStyle(24); Vfe5c5VsTT->SetMarkerStyle(24); Vfe1c2VsTT->Draw("P"); Vfe1c3VsTT->Draw("P"); Vfe1c4VsTT->Draw("P"); Vfe1c5VsTT->Draw("P"); Vfe2c1VsTT->Draw("P"); Vfe2c2VsTT->Draw("P"); Vfe2c3VsTT->Draw("P"); Vfe2c4VsTT->Draw("P"); Vfe2c5VsTT->Draw("P"); Vfe3c1VsTT->Draw("P"); Vfe3c2VsTT->Draw("P"); Vfe3c3VsTT->Draw("P"); Vfe3c4VsTT->Draw("P"); Vfe3c5VsTT->Draw("P"); c12->Print(TFileStr2.c_str(),"png"); if (flag == false){ cout<<"Test NOT OK"<<endl; return token; } cout<<"Test OK"<<endl; return token-1; }
#include "SCERunAction.hh" #include "SCEAnalysis.hh" #include "G4Run.hh" #include "G4RunManager.hh" #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... SCERunAction::SCERunAction(int nenergy, int nlayers, G4String fabsmaterial, double fthick) : G4UserRunAction() { nEnergy = nenergy; nLayers = nlayers; fAbsMaterial = fabsmaterial; fThick = fthick; // set printing event number per each event G4RunManager::GetRunManager()->SetPrintProgress(1); // Create analysis manager // The choice of analysis technology is done via selectin of a namespace // in SCEAnalysis.hh auto analysisManager = G4AnalysisManager::Instance(); G4cout << "Using " << analysisManager->GetType() << G4endl; // Create directories //analysisManager->SetHistoDirectoryName("histograms"); //analysisManager->SetNtupleDirectoryName("ntuple"); analysisManager->SetVerboseLevel(1); analysisManager->SetNtupleMerging(true); // Note: merging ntuples is available only with Root output // Book histograms, ntuple // for (int i=0; i<nLayers; i++) { // Creating histograms analysisManager->CreateH1("Eabs" + std::to_string(i),"Edep in absorber", 100, 0., nEnergy*GeV); analysisManager->CreateH1("Egap" + std::to_string(i),"Edep in gap", 100, 0., nEnergy*GeV); analysisManager->CreateH1("Labs" + std::to_string(i),"trackL in absorber", 100, 0., nEnergy*m); analysisManager->CreateH1("Lgap" + std::to_string(i),"trackL in gap", 100, 0., nEnergy*m); analysisManager->CreateH1("Pgap" + std::to_string(i),"Transverse position in gap", 100, 0., 4*m); analysisManager->CreateH2("Pgap2D" + std::to_string(i),"X and Y position", 100, -2.5*m, 2.5*m, 100, -2.5*m, 2.5*m); // Creating ntuple // analysisManager->CreateNtuple("SCE" + std::to_string(i), "Edep and TrackL"); analysisManager->CreateNtupleDColumn("Eabs"); analysisManager->CreateNtupleDColumn("Egap"); analysisManager->CreateNtupleDColumn("Labs"); analysisManager->CreateNtupleDColumn("Lgap"); analysisManager->CreateNtupleDColumn("Pgap"); analysisManager->FinishNtuple(); } // Creating histograms for tot analysisManager->CreateH1("Eabs_tot","Edep in absorber", 100, 0., nEnergy*GeV); analysisManager->CreateH1("Egap_tot","Edep in gap", 100, 0., nEnergy*GeV); analysisManager->CreateH1("Labs_tot","trackL in absorber", 100, 0., nEnergy*m); analysisManager->CreateH1("Lgap_tot","trackL in gap", 100, 0., nEnergy*m); analysisManager->CreateH1("Pgap_tot","Transverse position in gap", 100, 0., 4.*m); analysisManager->CreateH2("Pgap2D_tot","X and Y position", 100, -2.5*m, 2.5*m, 100, -2.5*m, 2.5*m); // Creating ntuple for tot // analysisManager->CreateNtuple("SCE_tot", "Edep and TrackL"); analysisManager->CreateNtupleDColumn("Eabs"); analysisManager->CreateNtupleDColumn("Egap"); analysisManager->CreateNtupleDColumn("Labs"); analysisManager->CreateNtupleDColumn("Lgap"); analysisManager->CreateNtupleDColumn("Pgap"); analysisManager->FinishNtuple(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... SCERunAction::~SCERunAction() { delete G4AnalysisManager::Instance(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void SCERunAction::BeginOfRunAction(const G4Run* /*run*/) { //inform the runManager to save random number seed //G4RunManager::GetRunManager()->SetRandomNumberStore(true); // Get analysis manager auto analysisManager = G4AnalysisManager::Instance(); // Open an output file // G4String fileName = "rootfiles/SCExam" + std::to_string(nEnergy) + "GeV" + fAbsMaterial + std::to_string((int)fThick) + "cm" + std::to_string(nLayers) + "layers"; analysisManager->OpenFile(fileName); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void SCERunAction::EndOfRunAction(const G4Run* /*run*/) { // print histogram statistics // auto analysisManager = G4AnalysisManager::Instance(); if ( analysisManager->GetH1(nLayers*4+1) ) { G4cout << G4endl << " ----> print histograms statistic "; if(isMaster) { G4cout << "for the entire run " << G4endl << G4endl; } else { G4cout << "for the local thread " << G4endl << G4endl; } G4cout << " EAbs : mean = " << G4BestUnit(analysisManager->GetH1(nLayers*4)->mean(), "Energy") << " rms = " << G4BestUnit(analysisManager->GetH1(nLayers*4)->rms(), "Energy") << G4endl; G4cout << " EGap : mean = " << G4BestUnit(analysisManager->GetH1(nLayers*4+1)->mean(), "Energy") << " rms = " << G4BestUnit(analysisManager->GetH1(nLayers*4+1)->rms(), "Energy") << G4endl; G4cout << "Total mean energy deposited: " << G4BestUnit(analysisManager->GetH1(nLayers*4)->mean() + analysisManager->GetH1(nLayers*4+1)->mean(), "Energy") << G4endl; G4cout << "Energy resolution: " << G4BestUnit(analysisManager->GetH1(nLayers*4+1)->rms() / analysisManager->GetH1(nLayers*4+1)->mean(), "Energy") << G4endl; G4cout << "corresponding to: " << (analysisManager->GetH1(nLayers*4+1)->rms()/analysisManager->GetH1(nLayers*4+1)->mean())*100 << "%" << G4endl; G4cout << " LAbs : mean = " << G4BestUnit(analysisManager->GetH1(nLayers*4+2)->mean(), "Length") << " rms = " << G4BestUnit(analysisManager->GetH1(nLayers*4+2)->rms(), "Length") << G4endl; G4cout << " LGap : mean = " << G4BestUnit(analysisManager->GetH1(nLayers*4+3)->mean(), "Length") << " rms = " << G4BestUnit(analysisManager->GetH1(nLayers*4+3)->rms(), "Length") << G4endl; } // Open text file fo write means for later analysis std::ofstream txtfile; G4String fileName = "txtfiles/SCExam" + std::to_string(nEnergy) + "GeV" + fAbsMaterial + std::to_string((int)fThick) + "cm" + std::to_string(nLayers) + "layers" + ".txt"; txtfile.open(fileName); // write to .txt file for (int i=0; i<nLayers; i++) { txtfile << i << "\t" << analysisManager->GetH1(i*4+3)->mean() << "\t" << analysisManager->GetH1(i*4+1)->mean() << "\n"; } txtfile.close(); // save histograms & ntuple // analysisManager->Write(); analysisManager->CloseFile(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
// Created on: 2005-12-19 // Created by: Julia GERASIMOVA // Copyright (c) 2005-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 _math_ComputeGaussPointsAndWeights_HeaderFile #define _math_ComputeGaussPointsAndWeights_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TColStd_HArray1OfReal.hxx> #include <Standard_Integer.hxx> #include <math_Vector.hxx> class math_ComputeGaussPointsAndWeights { public: DEFINE_STANDARD_ALLOC Standard_EXPORT math_ComputeGaussPointsAndWeights(const Standard_Integer Number); Standard_EXPORT Standard_Boolean IsDone() const; Standard_EXPORT math_Vector Points() const; Standard_EXPORT math_Vector Weights() const; protected: private: Handle(TColStd_HArray1OfReal) myPoints; Handle(TColStd_HArray1OfReal) myWeights; Standard_Boolean myIsDone; }; #endif // _math_ComputeGaussPointsAndWeights_HeaderFile
#include "precompiled.h" #include "component/jsrendercomponent.h" #include "component/jscomponent.h" #include "entity/entitymanager.h" using namespace component; REGISTER_COMPONENT_TYPE(JSRenderComponent, JSRENDERCOMPONENT); #pragma warning(disable: 4355) // disable warning for using 'this' as an initializer JSRenderComponent::JSRenderComponent(entity::Entity* entity, const string& name, const desc_type& desc) : Component(entity, name, desc), transform(this) { transform = desc.transformComponent; } JSRenderComponent::~JSRenderComponent() { if(m_acquired) release(); if(m_scriptObject) destroyScriptObject(); } void JSRenderComponent::acquire() { if(m_acquired) return; if(!transform) { INFO("WARNING: unable to acquire transform for \"%s.%s\"", m_entity->getName().c_str(), m_name.c_str()); return; } m_entity->getManager()->getScene()->addRenderable(this); Component::acquire(); } void JSRenderComponent::release() { Component::release(); transform.release(); m_entity->getManager()->getScene()->removeRenderable(this); } D3DXVECTOR3 JSRenderComponent::getRenderOrigin() const { ASSERT(transform); return transform->getPos(); } void JSRenderComponent::render(texture::Material* lighting) { ASSERT(m_acquired); ASSERT(transform); } JSObject* JSRenderComponent::createScriptObject() { return jscomponent::createComponentScriptObject(this); } void JSRenderComponent::destroyScriptObject() { jscomponent::destroyComponentScriptObject(this); m_scriptObject = NULL; }
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <map> #include <cstdio> #include <vector> #include <set> #include <algorithm> #include <sstream> #include <queue> #include <cctype> #include <cmath> #include <fstream> #include <iomanip> #include <set> #include <map> using namespace std; int main(int argc, char const *argv[]) { long long int Arr[100000], sum = 0; int n; cin >> n; for (int i = 0; i < n; ++i) { cin >> Arr[i]; sum += Arr[i]; } std::cout << sum <<std::endl; return 0; }