text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: slotadd.cxx,v $ * * $Revision: 1.27 $ * * last change: $Author: kz $ $Date: 2007-09-06 14:08:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include "hintids.hxx" #include "uiitems.hxx" #include "cmdid.h" #include <svtools/globalnameitem.hxx> #ifndef _SVT_IMAGEITM_HXX #include <svtools/imageitm.hxx> #endif #ifndef _AEITEM_HXX //autogen #include <svtools/aeitem.hxx> #endif #ifndef _SFXRECTITEM_HXX //autogen #include <svtools/rectitem.hxx> #endif #ifndef _SFX_OBJITEM_HXX //autogen #include <sfx2/objitem.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef _SVX_RULRITEM_HXX //autogen #include <svx/rulritem.hxx> #endif #ifndef _SVX_ZOOMITEM_HXX //autogen #include <svx/zoomitem.hxx> #endif #ifndef _SVX_HLNKITEM_HXX //autogen #include <svx/hlnkitem.hxx> #endif #ifndef _SVX_SMARTTAGITEM_HXX #include <svx/SmartTagItem.hxx> #endif #ifndef _SFXPTITEM_HXX //autogen #include <svtools/ptitem.hxx> #endif #ifndef _SVX_PAGEITEM_HXX //autogen #include <svx/pageitem.hxx> #endif #ifndef _SVX_SRCHITEM_HXX //autogen #include <svx/srchitem.hxx> #endif #ifndef _SFX_TPLPITEM_HXX //autogen #include <sfx2/tplpitem.hxx> #endif #ifndef _SVX_WRLMITEM_HXX //autogen #include <svx/wrlmitem.hxx> #endif #ifndef _SVX_PROTITEM_HXX //autogen #include <svx/protitem.hxx> #endif #ifndef _SVX_OPAQITEM_HXX //autogen #include <svx/opaqitem.hxx> #endif #ifndef _SVX_TSTPITEM_HXX //autogen #include <svx/tstpitem.hxx> #endif #ifndef _SVX_AKRNITEM_HXX //autogen #include <svx/akrnitem.hxx> #endif #ifndef _SVX_KEEPITEM_HXX //autogen #include <svx/keepitem.hxx> #endif #ifndef _SVX_KERNITEM_HXX //autogen #include <svx/kernitem.hxx> #endif #ifndef _SVX_SPLTITEM_HXX //autogen #include <svx/spltitem.hxx> #endif #ifndef _SVX_BRSHITEM_HXX //autogen #include <svx/brshitem.hxx> #endif #ifndef _SVX_WGHTITEM_HXX //autogen #include <svx/wghtitem.hxx> #endif #ifndef _SVX_SHADITEM_HXX //autogen #include <svx/shaditem.hxx> #endif #ifndef _SVX_PBINITEM_HXX //autogen #include <svx/pbinitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX //autogen #include <svx/ulspitem.hxx> #endif #ifndef _SVX_PRNTITEM_HXX //autogen #include <svx/prntitem.hxx> #endif #ifndef _SVX_ORPHITEM_HXX //autogen #include <svx/orphitem.hxx> #endif #ifndef _SVX_WIDWITEM_HXX //autogen #include <svx/widwitem.hxx> #endif #ifndef _SVX_BOLNITEM_HXX //autogen #include <svx/bolnitem.hxx> #endif #ifndef _SVX_PMDLITEM_HXX //autogen #include <svx/pmdlitem.hxx> #endif #ifndef _SVX_CMAPITEM_HXX //autogen #include <svx/cmapitem.hxx> #endif #ifndef _SVX_LANGITEM_HXX //autogen #include <svx/langitem.hxx> #endif #ifndef _SVX_BRKITEM_HXX //autogen #include <svx/brkitem.hxx> #endif #ifndef _SVX_HYZNITEM_HXX //autogen #include <svx/hyznitem.hxx> #endif #ifndef _SVX_ESCPITEM_HXX //autogen #include <svx/escpitem.hxx> #endif #ifndef _SVX_LSPCITEM_HXX //autogen #include <svx/lspcitem.hxx> #endif #ifndef _SVX_ADJITEM_HXX //autogen #include <svx/adjitem.hxx> #endif #ifndef _SVX_CRSDITEM_HXX //autogen #include <svx/crsditem.hxx> #endif #ifndef _SVX_FONTITEM_HXX //autogen #include <svx/fontitem.hxx> #endif #ifndef _SVX_SHDDITEM_HXX //autogen #include <svx/shdditem.hxx> #endif #ifndef _SVX_UDLNITEM_HXX //autogen #include <svx/udlnitem.hxx> #endif #ifndef _SVX_POSTITEM_HXX //autogen #include <svx/postitem.hxx> #endif #ifndef _SVX_FHGTITEM_HXX //autogen #include <svx/fhgtitem.hxx> #endif #ifndef _SVX_CNTRITEM_HXX //autogen #include <svx/cntritem.hxx> #endif #ifndef _SVX_COLRITEM_HXX //autogen #include <svx/colritem.hxx> #endif #ifndef _SVX_BOXITEM_HXX //autogen #include <svx/boxitem.hxx> #endif #ifndef _SVX_SIZEITEM_HXX //autogen #include <svx/sizeitem.hxx> #endif #ifndef _SVX_LRSPITEM_HXX //autogen #include <svx/lrspitem.hxx> #endif #ifndef _SVX__XGRADIENT_HXX //autogen #include <svx/xgrad.hxx> #endif #ifndef _SVX_XLNSTIT_HXX //autogen #include <svx/xlnstit.hxx> #endif #ifndef _SVX_XLNEDIT_HXX //autogen #include <svx/xlnedit.hxx> #endif #ifndef SVX_XFILLIT0_HXX //autogen #include <svx/xfillit0.hxx> #endif #ifndef _SVX_XFLCLIT_HXX //autogen #include <svx/xflclit.hxx> #endif #ifndef _SVX_XFLGRIT_HXX //autogen #include <svx/xflgrit.hxx> #endif #ifndef _SVX_XFLHTIT_HXX //autogen #include <svx/xflhtit.hxx> #endif #ifndef _SVX_XBTMPIT_HXX //autogen #include <svx/xbtmpit.hxx> #endif #ifndef _SVX_XLINEIT0_HXX //autogen #include <svx/xlineit0.hxx> #endif #ifndef _SVX_XLNWTIT_HXX //autogen #include <svx/xlnwtit.hxx> #endif #ifndef _SVX_XLNDSIT_HXX //autogen #include <svx/xlndsit.hxx> #endif #ifndef _SVX_XLNCLIT_HXX //autogen #include <svx/xlnclit.hxx> #endif #ifndef _SVX_TEXTIT0_HXX //autogen #include <svx/xtextit0.hxx> #endif #ifndef _SVX_XFTADIT_HXX //autogen #include <svx/xftadit.hxx> #endif #ifndef _SVX_XFTDIIT_HXX //autogen #include <svx/xftdiit.hxx> #endif #ifndef _SVX_XFTSTIT_HXX //autogen #include <svx/xftstit.hxx> #endif #ifndef _SVX_XFTMRIT_HXX //autogen #include <svx/xftmrit.hxx> #endif #ifndef _SVX_XFTOUIT_HXX //autogen #include <svx/xftouit.hxx> #endif #ifndef _SVX_XFTSHIT_HXX //autogen #include <svx/xftshit.hxx> #endif #ifndef _SVX_XFTSHCLIT_HXX //autogen #include <svx/xftshcit.hxx> #endif #ifndef _SVX_XFTSHXY_HXX //autogen #include <svx/xftshxy.hxx> #endif #ifndef _SVX_XFTSFIT_HXX //autogen #include <svx/xftsfit.hxx> #endif #ifndef _SVX_GRAFCTRL_HXX #include <svx/grafctrl.hxx> #endif #ifndef _FMTORNT_HXX //autogen #include <fmtornt.hxx> #endif #ifndef _PARATR_HXX //autogen #include <paratr.hxx> #endif #ifndef _FMTINFMT_HXX //autogen #include <fmtinfmt.hxx> #endif #ifndef _FMTFSIZE_HXX //autogen #include <fmtfsize.hxx> #endif #ifndef _FMTSRND_HXX //autogen #include <fmtsrnd.hxx> #endif #include "envimg.hxx" #include "frmatr.hxx" #include "cfgitems.hxx" #include "grfatr.hxx" #include "fmtline.hxx" #include <svx/clipfmtitem.hxx> #include <svx/blnkitem.hxx> #include <svtools/slstitm.hxx> #include <svx/paravertalignitem.hxx> #include <svx/charreliefitem.hxx> #include <svx/charrotateitem.hxx> #include <svx/charscaleitem.hxx> #include <svx/postattr.hxx> #include <sfx2/frame.hxx> #include <svx/chrtitem.hxx> #ifndef PROFILE // Code zum Initialisieren von Statics im eigenen Code-Segment #ifdef _MSC_VER #pragma code_seg( "SWSTATICS" ) #endif #endif #ifndef _SVX_DRAWITEM_HXX #include <svx/drawitem.hxx> #endif #ifndef _AVMEDIA_MEDIAITEM_HXX #include <avmedia/mediaitem.hxx> #endif #define SvxDrawToolItem SfxAllEnumItem #define SvxDrawAlignItem SfxAllEnumItem #define SvxDrawBezierItem SfxAllEnumItem #define avmedia_MediaItem ::avmedia::MediaItem #define SFX_TYPEMAP #include "itemdef.hxx" #include "swslots.hxx" #ifndef PROFILE #ifdef _MSC_VER #pragma code_seg() #endif #endif <commit_msg>INTEGRATION: CWS swwarnings (1.24.222); FILE MERGED 2007/09/24 07:12:35 os 1.24.222.4: RESYNC: (1.26-1.27); FILE MERGED 2007/08/20 16:01:21 tl 1.24.222.3: RESYNC: (1.25-1.26); FILE MERGED 2007/05/29 14:06:37 os 1.24.222.2: RESYNC: (1.24-1.25); FILE MERGED 2007/03/05 12:45:54 tl 1.24.222.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: slotadd.cxx,v $ * * $Revision: 1.28 $ * * last change: $Author: hr $ $Date: 2007-09-27 12:29:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include "hintids.hxx" #include "uiitems.hxx" #include "cmdid.h" #include <svtools/globalnameitem.hxx> #ifndef _SVT_IMAGEITM_HXX #include <svtools/imageitm.hxx> #endif #ifndef _AEITEM_HXX //autogen #include <svtools/aeitem.hxx> #endif #ifndef _SFXRECTITEM_HXX //autogen #include <svtools/rectitem.hxx> #endif #ifndef _SFX_OBJITEM_HXX //autogen #include <sfx2/objitem.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef _SVX_RULRITEM_HXX //autogen #include <svx/rulritem.hxx> #endif #ifndef _SVX_ZOOMITEM_HXX //autogen #include <svx/zoomitem.hxx> #endif #ifndef _SVX_HLNKITEM_HXX //autogen #include <svx/hlnkitem.hxx> #endif #ifndef _SVX_SMARTTAGITEM_HXX #include <svx/SmartTagItem.hxx> #endif #ifndef _SFXPTITEM_HXX //autogen #include <svtools/ptitem.hxx> #endif #ifndef _SVX_PAGEITEM_HXX //autogen #include <svx/pageitem.hxx> #endif #ifndef _SVX_SRCHITEM_HXX //autogen #include <svx/srchitem.hxx> #endif #ifndef _SFX_TPLPITEM_HXX //autogen #include <sfx2/tplpitem.hxx> #endif #ifndef _SVX_WRLMITEM_HXX //autogen #include <svx/wrlmitem.hxx> #endif #ifndef _SVX_PROTITEM_HXX //autogen #include <svx/protitem.hxx> #endif #ifndef _SVX_OPAQITEM_HXX //autogen #include <svx/opaqitem.hxx> #endif #ifndef _SVX_TSTPITEM_HXX //autogen #include <svx/tstpitem.hxx> #endif #ifndef _SVX_AKRNITEM_HXX //autogen #include <svx/akrnitem.hxx> #endif #ifndef _SVX_KEEPITEM_HXX //autogen #include <svx/keepitem.hxx> #endif #ifndef _SVX_KERNITEM_HXX //autogen #include <svx/kernitem.hxx> #endif #ifndef _SVX_SPLTITEM_HXX //autogen #include <svx/spltitem.hxx> #endif #ifndef _SVX_BRSHITEM_HXX //autogen #include <svx/brshitem.hxx> #endif #ifndef _SVX_WGHTITEM_HXX //autogen #include <svx/wghtitem.hxx> #endif #ifndef _SVX_SHADITEM_HXX //autogen #include <svx/shaditem.hxx> #endif #ifndef _SVX_PBINITEM_HXX //autogen #include <svx/pbinitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX //autogen #include <svx/ulspitem.hxx> #endif #ifndef _SVX_PRNTITEM_HXX //autogen #include <svx/prntitem.hxx> #endif #ifndef _SVX_ORPHITEM_HXX //autogen #include <svx/orphitem.hxx> #endif #ifndef _SVX_WIDWITEM_HXX //autogen #include <svx/widwitem.hxx> #endif #ifndef _SVX_BOLNITEM_HXX //autogen #include <svx/bolnitem.hxx> #endif #ifndef _SVX_PMDLITEM_HXX //autogen #include <svx/pmdlitem.hxx> #endif #ifndef _SVX_CMAPITEM_HXX //autogen #include <svx/cmapitem.hxx> #endif #ifndef _SVX_LANGITEM_HXX //autogen #include <svx/langitem.hxx> #endif #ifndef _SVX_BRKITEM_HXX //autogen #include <svx/brkitem.hxx> #endif #ifndef _SVX_HYZNITEM_HXX //autogen #include <svx/hyznitem.hxx> #endif #ifndef _SVX_ESCPITEM_HXX //autogen #include <svx/escpitem.hxx> #endif #ifndef _SVX_LSPCITEM_HXX //autogen #include <svx/lspcitem.hxx> #endif #ifndef _SVX_ADJITEM_HXX //autogen #include <svx/adjitem.hxx> #endif #ifndef _SVX_CRSDITEM_HXX //autogen #include <svx/crsditem.hxx> #endif #ifndef _SVX_FONTITEM_HXX //autogen #include <svx/fontitem.hxx> #endif #ifndef _SVX_SHDDITEM_HXX //autogen #include <svx/shdditem.hxx> #endif #ifndef _SVX_UDLNITEM_HXX //autogen #include <svx/udlnitem.hxx> #endif #ifndef _SVX_POSTITEM_HXX //autogen #include <svx/postitem.hxx> #endif #ifndef _SVX_FHGTITEM_HXX //autogen #include <svx/fhgtitem.hxx> #endif #ifndef _SVX_CNTRITEM_HXX //autogen #include <svx/cntritem.hxx> #endif #ifndef _SVX_COLRITEM_HXX //autogen #include <svx/colritem.hxx> #endif #ifndef _SVX_BOXITEM_HXX //autogen #include <svx/boxitem.hxx> #endif #ifndef _SVX_SIZEITEM_HXX //autogen #include <svx/sizeitem.hxx> #endif #ifndef _SVX_LRSPITEM_HXX //autogen #include <svx/lrspitem.hxx> #endif #ifndef _SVX__XGRADIENT_HXX //autogen #include <svx/xgrad.hxx> #endif #ifndef _SVX_XLNSTIT_HXX //autogen #include <svx/xlnstit.hxx> #endif #ifndef _SVX_XLNEDIT_HXX //autogen #include <svx/xlnedit.hxx> #endif #ifndef SVX_XFILLIT0_HXX //autogen #include <svx/xfillit0.hxx> #endif #ifndef _SVX_XFLCLIT_HXX //autogen #include <svx/xflclit.hxx> #endif #ifndef _SVX_XFLGRIT_HXX //autogen #include <svx/xflgrit.hxx> #endif #ifndef _SVX_XFLHTIT_HXX //autogen #include <svx/xflhtit.hxx> #endif #ifndef _SVX_XBTMPIT_HXX //autogen #include <svx/xbtmpit.hxx> #endif #ifndef _SVX_XLINEIT0_HXX //autogen #include <svx/xlineit0.hxx> #endif #ifndef _SVX_XLNWTIT_HXX //autogen #include <svx/xlnwtit.hxx> #endif #ifndef _SVX_XLNDSIT_HXX //autogen #include <svx/xlndsit.hxx> #endif #ifndef _SVX_XLNCLIT_HXX //autogen #include <svx/xlnclit.hxx> #endif #ifndef _SVX_TEXTIT0_HXX //autogen #include <svx/xtextit0.hxx> #endif #ifndef _SVX_XFTADIT_HXX //autogen #include <svx/xftadit.hxx> #endif #ifndef _SVX_XFTDIIT_HXX //autogen #include <svx/xftdiit.hxx> #endif #ifndef _SVX_XFTSTIT_HXX //autogen #include <svx/xftstit.hxx> #endif #ifndef _SVX_XFTMRIT_HXX //autogen #include <svx/xftmrit.hxx> #endif #ifndef _SVX_XFTOUIT_HXX //autogen #include <svx/xftouit.hxx> #endif #ifndef _SVX_XFTSHIT_HXX //autogen #include <svx/xftshit.hxx> #endif #ifndef _SVX_XFTSHCLIT_HXX //autogen #include <svx/xftshcit.hxx> #endif #ifndef _SVX_XFTSHXY_HXX //autogen #include <svx/xftshxy.hxx> #endif #ifndef _SVX_XFTSFIT_HXX //autogen #include <svx/xftsfit.hxx> #endif #ifndef _SVX_GRAFCTRL_HXX #include <svx/grafctrl.hxx> #endif #ifndef _FMTORNT_HXX //autogen #include <fmtornt.hxx> #endif #ifndef _PARATR_HXX //autogen #include <paratr.hxx> #endif #ifndef _FMTINFMT_HXX //autogen #include <fmtinfmt.hxx> #endif #ifndef _FMTFSIZE_HXX //autogen #include <fmtfsize.hxx> #endif #ifndef _FMTSRND_HXX //autogen #include <fmtsrnd.hxx> #endif #include "envimg.hxx" #include "frmatr.hxx" #include "cfgitems.hxx" #include "grfatr.hxx" #include "fmtline.hxx" #include <svx/clipfmtitem.hxx> #include <svx/blnkitem.hxx> #include <svtools/slstitm.hxx> #include <svx/paravertalignitem.hxx> #include <svx/charreliefitem.hxx> #include <svx/charrotateitem.hxx> #include <svx/charscaleitem.hxx> #include <svx/postattr.hxx> #include <sfx2/frame.hxx> #include <svx/chrtitem.hxx> #ifndef _SVX_DRAWITEM_HXX #include <svx/drawitem.hxx> #endif #ifndef _AVMEDIA_MEDIAITEM_HXX #include <avmedia/mediaitem.hxx> #endif #define SvxDrawToolItem SfxAllEnumItem #define SvxDrawAlignItem SfxAllEnumItem #define SvxDrawBezierItem SfxAllEnumItem #define avmedia_MediaItem ::avmedia::MediaItem #define SFX_TYPEMAP #include "itemdef.hxx" #include "swslots.hxx" <|endoftext|>
<commit_before>#include <sdl_renderer.h> #include <cstring> void draw_naive(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; SDL_LockTexture(tex, nullptr, &pixels, &pitch); ppu.nametable_img((byte_t*)pixels, pitch, 0); SDL_UnlockTexture(tex); } void draw_nam(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; SDL_Rect rects[] = { {0 , 0 , 256, 240}, {257, 0 , 512, 240}, {0 , 241, 256, 480}, {257, 241, 512, 480} }; for (int i = 0; i < 4; ++i) { SDL_LockTexture(tex, &rects[i], &pixels, &pitch); ppu.nametable_img((byte_t*)pixels, pitch, i); SDL_UnlockTexture(tex); } } void draw_pat(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; // PAT 0000 SDL_Rect rect = {0, 0, 128, 128}; SDL_LockTexture(tex, &rect, &pixels, &pitch); ppu.patterntable_img((byte_t*)pixels, pitch, 0); SDL_UnlockTexture(tex); // PAT 1000 rect.y += 128 + 10; SDL_LockTexture(tex, &rect, &pixels, &pitch); ppu.patterntable_img((byte_t*)pixels, pitch, 1); SDL_UnlockTexture(tex); } void draw_oam(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; SDL_LockTexture(tex, nullptr, &pixels, &pitch); ppu.sprite_img((byte_t*)pixels, pitch); SDL_UnlockTexture(tex); } Viewport::Viewport(SDL_Window* window) { if ((renderer_ = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == nullptr) throw std::runtime_error("Can't initialize SDL renderer."); } Viewport::~Viewport() { if (tex_ != nullptr) { SDL_DestroyTexture(tex_); } SDL_DestroyRenderer(renderer_); } void Viewport::init_texture(int width, int height) { if (tex_ != nullptr) { SDL_DestroyTexture(tex_); } tex_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGB24, SDL_TEXTUREACCESS_STREAMING, width, height); } void Viewport::flip() { SDL_SetRenderDrawColor(renderer_, 0x0, 0x0, 0x0, 0xFF); SDL_RenderClear(renderer_); SDL_RenderCopy(renderer_, tex_, nullptr, nullptr); SDL_RenderPresent(renderer_); } SDLRenderer::SDLRenderer() : lastUpdate_(0ul) { if (SDL_Init(SDL_INIT_VIDEO) < 0) throw std::runtime_error("Can't initialize SDL."); Viewport *v; // Main game v = init_window("NESEMUL", 256*2, 240*2); v->init_texture(256, 240); resources_.emplace_back(std::make_pair(draw_naive, v->get_texture())); // Name table (debug) //v = init_window("Nametables", 512, 480); //v->init_texture(512, 480); //resources_.emplace_back(std::make_pair(draw_nam, v->get_texture())); // Pattern table (debug) //v = init_window("Pattern tables", 128*2, (128*2+10)*2); //v->init_texture(128, 128*2+10); //resources_.emplace_back(std::make_pair(draw_pat, v->get_texture())); } SDLRenderer::~SDLRenderer() { for(auto & v : viewports_) { delete v.second; SDL_DestroyWindow(v.first); } SDL_Quit(); } bool SDLRenderer::update(const PPU& ppu) { static SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: return false; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_CLOSE) return false; } } draw(ppu); lastUpdate_ = SDL_GetTicks(); SDL_Delay((1000 / CLOCKS_PER_SEC) / 30); return true; } void SDLRenderer::draw(const PPU& ppu) { for (auto & r : resources_) { r.first(r.second, ppu); } for(auto & v : viewports_) { v.second->flip(); } } Viewport* SDLRenderer::init_window(const char* name, int width, int height) { SDL_Window* window; if ((window = SDL_CreateWindow(name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width , height, SDL_WINDOW_RESIZABLE)) == nullptr) throw std::runtime_error("Can't initialize SDL window."); return viewports_.emplace_back(std::make_pair(window, new Viewport{window})).second; } bool SDLRenderer::timeout() { return (SDL_GetTicks() - lastUpdate_ >= 1000 / 30); } <commit_msg>Nametables debug window now draws correctly all four nametables<commit_after>#include <sdl_renderer.h> #include <cstring> void draw_naive(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; SDL_LockTexture(tex, nullptr, &pixels, &pitch); ppu.nametable_img((byte_t*)pixels, pitch, 0); SDL_UnlockTexture(tex); } void draw_nam(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; SDL_Rect rects[] = { {0 , 0 , 256, 240}, {256, 0 , 256, 240}, {0 , 240, 256, 240}, {256, 240, 256, 240} }; for (int i = 0; i < 4; ++i) { SDL_LockTexture(tex, &rects[i], &pixels, &pitch); ppu.nametable_img((byte_t*)pixels, pitch, i); SDL_UnlockTexture(tex); } } void draw_pat(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; // PAT 0000 SDL_Rect rect = {0, 0, 128, 128}; SDL_LockTexture(tex, &rect, &pixels, &pitch); ppu.patterntable_img((byte_t*)pixels, pitch, 0); SDL_UnlockTexture(tex); // PAT 1000 rect.y += 128 + 10; SDL_LockTexture(tex, &rect, &pixels, &pitch); ppu.patterntable_img((byte_t*)pixels, pitch, 1); SDL_UnlockTexture(tex); } void draw_oam(SDL_Texture* tex, const PPU & ppu) { void* pixels; int pitch = 0; SDL_LockTexture(tex, nullptr, &pixels, &pitch); ppu.sprite_img((byte_t*)pixels, pitch); SDL_UnlockTexture(tex); } Viewport::Viewport(SDL_Window* window) { if ((renderer_ = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == nullptr) throw std::runtime_error("Can't initialize SDL renderer."); } Viewport::~Viewport() { if (tex_ != nullptr) { SDL_DestroyTexture(tex_); } SDL_DestroyRenderer(renderer_); } void Viewport::init_texture(int width, int height) { if (tex_ != nullptr) { SDL_DestroyTexture(tex_); } tex_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGB24, SDL_TEXTUREACCESS_STREAMING, width, height); } void Viewport::flip() { SDL_SetRenderDrawColor(renderer_, 0x0, 0x0, 0x0, 0xFF); SDL_RenderClear(renderer_); SDL_RenderCopy(renderer_, tex_, nullptr, nullptr); SDL_RenderPresent(renderer_); } SDLRenderer::SDLRenderer() : lastUpdate_(0ul) { if (SDL_Init(SDL_INIT_VIDEO) < 0) throw std::runtime_error("Can't initialize SDL."); Viewport *v; // Main game v = init_window("NESEMUL", 256*2, 240*2); v->init_texture(256, 240); resources_.emplace_back(std::make_pair(draw_naive, v->get_texture())); // Name table (debug) //v = init_window("Nametables", 512, 480); //v->init_texture(512, 480); //resources_.emplace_back(std::make_pair(draw_nam, v->get_texture())); // Pattern table (debug) //v = init_window("Pattern tables", 128*2, (128*2+10)*2); //v->init_texture(128, 128*2+10); //resources_.emplace_back(std::make_pair(draw_pat, v->get_texture())); } SDLRenderer::~SDLRenderer() { for(auto & v : viewports_) { delete v.second; SDL_DestroyWindow(v.first); } SDL_Quit(); } bool SDLRenderer::update(const PPU& ppu) { static SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: return false; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_CLOSE) return false; } } draw(ppu); lastUpdate_ = SDL_GetTicks(); SDL_Delay((1000 / CLOCKS_PER_SEC) / 30); return true; } void SDLRenderer::draw(const PPU& ppu) { for (auto & r : resources_) { r.first(r.second, ppu); } for(auto & v : viewports_) { v.second->flip(); } } Viewport* SDLRenderer::init_window(const char* name, int width, int height) { SDL_Window* window; if ((window = SDL_CreateWindow(name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width , height, SDL_WINDOW_RESIZABLE)) == nullptr) throw std::runtime_error("Can't initialize SDL window."); return viewports_.emplace_back(std::make_pair(window, new Viewport{window})).second; } bool SDLRenderer::timeout() { return (SDL_GetTicks() - lastUpdate_ >= 1000 / 30); } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 ROUTER_HPP #define ROUTER_HPP #include <functional> #include <regex> #include <stdexcept> #include "request.hpp" #include "response.hpp" #include "../route/path_to_regex.hpp" // TODO: Not relative path? #include "params.hpp" namespace server { //------------------------------- // This class is used to provide // route resolution //------------------------------- class Router { private: //------------------------------- // Internal class type aliases //------------------------------- using Route_expr = std::regex; using Callback = std::function<void(Request_ptr, Response_ptr)>; struct Route { Route_expr expr; Callback callback; std::vector<route::Token> keys; Route(const char* ex, Callback c) : callback{c} { expr = route::PathToRegex::path_to_regex(ex, keys); // also sets the keys attribute } }; using Route_table = std::unordered_map< http::Method, std::vector<Route> >; using Span = gsl::span<char>; public: /** * @brief Returned in match-method. * Contains both the Callback and the route parameters so that both can be returned. */ struct ParsedRoute { Callback job; Params parsed_values; }; //------------------------------- // Default constructor to set up // default routes //------------------------------- explicit Router() = default; //------------------------------- // Default destructor //------------------------------- ~Router() noexcept = default; //------------------------------- // Default move constructor //------------------------------- Router(Router&&) = default; //------------------------------- // Default move assignment operator //------------------------------- Router& operator = (Router&&) = default; //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_options(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_get(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_head(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_post(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_put(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_delete(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_trace(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_connect(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_patch(Routee&& route, Callback result); //------------------------------- // Install a new route table for // route resolutions // // @tparam (http::Router) new_routes - The new route table // to install // // @return - The object that invoked this method //------------------------------- template <typename Routee_Table> Router& install_new_configuration(Routee_Table&& new_routes); /** * Get the route callback where Route_expr matched a given path * * @param path : the route path * @note : not const becuase it uses index operator to a map **/ inline ParsedRoute match(http::Method, const std::string&); private: Router(const Router&) = delete; Router& operator = (const Router&) = delete; Route_table route_table_; }; //< class Router class Router_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Routee> inline Router& Router::on_options(Routee&& route, Callback result) { route_table_[http::OPTIONS].emplace_back({std::forward<Routee>(route), result}); return *this; } template <typename Routee> inline Router& Router::on_get(Routee&& route, Callback result) { route_table_[http::GET].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_head(Routee&& route, Callback result) { route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_post(Routee&& route, Callback result) { route_table_[http::POST].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_put(Routee&& route, Callback result) { route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_delete(Routee&& route, Callback result) { route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_trace(Routee&& route, Callback result) { route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_connect(Routee&& route, Callback result) { route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_patch(Routee&& route, Callback result) { route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee_Table> inline Router& Router::install_new_configuration(Routee_Table&& new_routes) { route_table_ = std::forward<Routee_Table>(new_routes).route_table_; return *this; } inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) { auto routes = route_table_[method]; if (routes.empty()) throw Router_error("No routes for method " + http::method::str(method)); for (auto& route : routes) { if (std::regex_match(path, route.expr)) { // Set the pairs in params: Params params; std::smatch res; for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr}; i != std::sregex_iterator{}; ++i) { res = *i; } // First parameter/value is in res[1], second in res[2], and so on for (size_t i = 0; i < route.keys.size(); i++) params.insert(route.keys[i].name, res[i + 1]); ParsedRoute parsed_route; parsed_route.job = route.callback; parsed_route.parsed_values = params; return parsed_route; } } throw Router_error("No matching route for " + http::method::str(method) + " " + path); } /**--^----------- Implementation Details -----------^--**/ } //< namespace server #endif //< ROUTER_HPP <commit_msg>Router: made include-paths relative<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 ROUTER_HPP #define ROUTER_HPP #include <functional> #include <regex> #include <stdexcept> #include <request.hpp> #include <response.hpp> #include <route/path_to_regex.hpp> #include <params.hpp> namespace server { //------------------------------- // This class is used to provide // route resolution //------------------------------- class Router { private: //------------------------------- // Internal class type aliases //------------------------------- using Route_expr = std::regex; using Callback = std::function<void(Request_ptr, Response_ptr)>; struct Route { Route_expr expr; Callback callback; std::vector<route::Token> keys; Route(const char* ex, Callback c) : callback{c} { expr = route::PathToRegex::path_to_regex(ex, keys); // also sets the keys attribute } }; using Route_table = std::unordered_map< http::Method, std::vector<Route> >; using Span = gsl::span<char>; public: /** * @brief Returned in match-method. * Contains both the Callback and the route parameters so that both can be returned. */ struct ParsedRoute { Callback job; Params parsed_values; }; //------------------------------- // Default constructor to set up // default routes //------------------------------- explicit Router() = default; //------------------------------- // Default destructor //------------------------------- ~Router() noexcept = default; //------------------------------- // Default move constructor //------------------------------- Router(Router&&) = default; //------------------------------- // Default move assignment operator //------------------------------- Router& operator = (Router&&) = default; //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_options(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_get(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_head(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_post(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_put(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_delete(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_trace(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_connect(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_patch(Routee&& route, Callback result); //------------------------------- // Install a new route table for // route resolutions // // @tparam (http::Router) new_routes - The new route table // to install // // @return - The object that invoked this method //------------------------------- template <typename Routee_Table> Router& install_new_configuration(Routee_Table&& new_routes); /** * Get the route callback where Route_expr matched a given path * * @param path : the route path * @note : not const becuase it uses index operator to a map **/ inline ParsedRoute match(http::Method, const std::string&); private: Router(const Router&) = delete; Router& operator = (const Router&) = delete; Route_table route_table_; }; //< class Router class Router_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Routee> inline Router& Router::on_options(Routee&& route, Callback result) { route_table_[http::OPTIONS].emplace_back({std::forward<Routee>(route), result}); return *this; } template <typename Routee> inline Router& Router::on_get(Routee&& route, Callback result) { route_table_[http::GET].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_head(Routee&& route, Callback result) { route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_post(Routee&& route, Callback result) { route_table_[http::POST].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_put(Routee&& route, Callback result) { route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_delete(Routee&& route, Callback result) { route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_trace(Routee&& route, Callback result) { route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_connect(Routee&& route, Callback result) { route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_patch(Routee&& route, Callback result) { route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee_Table> inline Router& Router::install_new_configuration(Routee_Table&& new_routes) { route_table_ = std::forward<Routee_Table>(new_routes).route_table_; return *this; } inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) { auto routes = route_table_[method]; if (routes.empty()) throw Router_error("No routes for method " + http::method::str(method)); for (auto& route : routes) { if (std::regex_match(path, route.expr)) { // Set the pairs in params: Params params; std::smatch res; for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr}; i != std::sregex_iterator{}; ++i) { res = *i; } // First parameter/value is in res[1], second in res[2], and so on for (size_t i = 0; i < route.keys.size(); i++) params.insert(route.keys[i].name, res[i + 1]); ParsedRoute parsed_route; parsed_route.job = route.callback; parsed_route.parsed_values = params; return parsed_route; } } throw Router_error("No matching route for " + http::method::str(method) + " " + path); } /**--^----------- Implementation Details -----------^--**/ } //< namespace server #endif //< ROUTER_HPP <|endoftext|>
<commit_before>/** * @file response_base.hpp * @author Herbert Jones * @brief Base class for the JSON API request return object. * * @copyright Copyright 2014 Mediafire */ #pragma once #include <string> #include <system_error> #include "boost/optional.hpp" #include "boost/property_tree/ptree.hpp" #include "mediafire_sdk/http/headers.hpp" namespace mf { namespace api { /** * @interface ResponseBase * @brief Base class for API Response objects. */ class ResponseBase { public: /** Any error that occured in the process. */ std::error_code error_code; /** Set if error occurred and had extra description. */ boost::optional<std::string> error_string; /** Set if API error occurred and had API error message. */ boost::optional<std::string> api_error_string; /** The HTTP content. For debugging. */ std::string plaintext; /** * Property tree extracted from JSON. * * @warning: property_tree doesn't correctly parse unicode when using * std::string as a base. Wstring used to be able to parse unicode * characters. */ boost::property_tree::wptree pt; /** The url used to make the request. */ std::string url; /** Useful debug information */ std::string debug; /** * @brief Initializer when content was received from the server with no * errors. * * @param[in] request_url Request url * @param[in] debug Debug data to pass to debug member variable * @param[in] headers Http response headers * @param[in] content JSON encoded data from the remote server. * * The error_code will be set if an error occurred while parsing the * content. */ virtual void InitializeWithContent( const std::string & request_url, const std::string & debug, const mf::http::Headers & headers, const std::string & content ); /** * @brief Initialized when HTTP request failed. * * @param[in] request_url Request url * @param[in] debug Debug data to pass to debug member variable * @param[in] ec Error code passed from the HTTP request object. * @param[in] error_str Error text passed from the HTTP request object. */ virtual void InitializeWithError( const std::string & request_url, const std::string & debug, std::error_code ec, const std::string & error_str ); /** * @brief Default constructor. Don't use outside unit testing. */ ResponseBase(); virtual ~ResponseBase(); }; } // namespace api } // namespace mf <commit_msg>STYLE 26420 Remove unnecessary virtual<commit_after>/** * @file response_base.hpp * @author Herbert Jones * @brief Base class for the JSON API request return object. * * @copyright Copyright 2014 Mediafire */ #pragma once #include <string> #include <system_error> #include "boost/optional.hpp" #include "boost/property_tree/ptree.hpp" #include "mediafire_sdk/http/headers.hpp" namespace mf { namespace api { /** * @interface ResponseBase * @brief Base class for API Response objects. */ class ResponseBase { public: /** Any error that occured in the process. */ std::error_code error_code; /** Set if error occurred and had extra description. */ boost::optional<std::string> error_string; /** Set if API error occurred and had API error message. */ boost::optional<std::string> api_error_string; /** The HTTP content. For debugging. */ std::string plaintext; /** * Property tree extracted from JSON. * * @warning: property_tree doesn't correctly parse unicode when using * std::string as a base. Wstring used to be able to parse unicode * characters. */ boost::property_tree::wptree pt; /** The url used to make the request. */ std::string url; /** Useful debug information */ std::string debug; /** * @brief Initializer when content was received from the server with no * errors. * * @param[in] request_url Request url * @param[in] debug Debug data to pass to debug member variable * @param[in] headers Http response headers * @param[in] content JSON encoded data from the remote server. * * The error_code will be set if an error occurred while parsing the * content. */ void InitializeWithContent( const std::string & request_url, const std::string & debug, const mf::http::Headers & headers, const std::string & content ); /** * @brief Initialized when HTTP request failed. * * @param[in] request_url Request url * @param[in] debug Debug data to pass to debug member variable * @param[in] ec Error code passed from the HTTP request object. * @param[in] error_str Error text passed from the HTTP request object. */ void InitializeWithError( const std::string & request_url, const std::string & debug, std::error_code ec, const std::string & error_str ); /** * @brief Default constructor. Don't use outside unit testing. */ ResponseBase(); virtual ~ResponseBase(); }; } // namespace api } // namespace mf <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <service> extern "C" __attribute__((noreturn)) void panic(const char* reason); __attribute__((noreturn)) extern "C" void abort(){ panic("Abort called"); } const char* service_name__ = SERVICE_NAME; const char* service_binary_name__ = SERVICE; <commit_msg>Fix compile error when using test_ukvm.sh<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <service> extern "C" __attribute__((noreturn)) void panic(const char* reason); extern "C" __attribute__((noreturn)) void abort(){ panic("Abort called"); } const char* service_name__ = SERVICE_NAME; const char* service_binary_name__ = SERVICE; <|endoftext|>
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/projection.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/numeric/numeric.h" namespace openMVG { // HZ 12.2 p.312 void TriangulateDLT ( const Mat34 &P1, const Vec3 &x1, const Mat34 &P2, const Vec3 &x2, Vec4 *X_homogeneous ) { // Solve: // [cross(x0,P0) X = 0] // [cross(x1,P1) X = 0] Mat4 design; design.row(0) = x1[0] * P1.row(2) - x1[2] * P1.row(0); design.row(1) = x1[1] * P1.row(2) - x1[2] * P1.row(1); design.row(2) = x2[0] * P2.row(2) - x2[2] * P2.row(0); design.row(3) = x2[1] * P2.row(2) - x2[2] * P2.row(1); const Eigen::JacobiSVD<Mat4> svd( design, Eigen::ComputeFullV ); ( *X_homogeneous ) = svd.matrixV().col( 3 ); } void TriangulateDLT ( const Mat34 &P1, const Vec3 &x1, const Mat34 &P2, const Vec3 &x2, Vec3 *X_euclidean ) { Vec4 X_homogeneous; TriangulateDLT(P1, x1, P2, x2, &X_homogeneous); (*X_euclidean) = X_homogeneous.hnormalized(); } bool TriangulateDLT ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X ) { Mat34 P0, P1; P0.block<3,3>(0,0) = R0; P1.block<3,3>(0,0) = R1; P0.block<3,1>(0,3) = t0; P1.block<3,1>(0,3) = t1; TriangulateDLT(P0, x0, P1, x1, X); return x0.dot(R0 * (*X + R0.transpose() * t0)) > 0.0 && x1.dot(R1 * (*X + R1.transpose() * t1)) > 0.0; } // Helper function // Compute Relative motion between two absolute poses parameterized by Rt // Rotate one bearing vector according to the relative motion inline void AbsoluteToRelative( const Mat3 &R0, const Vec3 &t0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x0, Mat3 &R, Vec3 &t, Vec3 &Rx0 ) { R = R1 * R0.transpose(); t = t1 - R * t0; Rx0 = R * x0; } // Helper function // Compute the 3D point from the outcome of an angular triangulation solver // Return true if the point pass the cheirality test, false otherwise // Lee & Civera Eq. (11) and Table 1 - 4) inline bool Compute3DPoint( const Vec3 &mprime0, const Vec3 &mprime1, const Vec3 &t, const Mat3 &R1, const Vec3 &t1, Vec3 *X) { const Vec3 z = mprime1.cross(mprime0); const double z_squared = z.squaredNorm(); const double lambda0 = z.dot(t.cross(mprime1)) / z_squared; const double lambda1 = z.dot(t.cross(mprime0)) / z_squared; const Vec3 xprime1 = t + lambda0 * mprime0; // x'1 is into the frame of camera1 convert it into the world frame in order to obtain the 3D point *X = R1.transpose() * (xprime1 - t1); // make and return the result of the cheirality test return lambda0 > 0.0 && lambda1 > 0.0; } bool TriangulateL1Angular ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X_euclidean ) { // Table 1 - 1) we compute m0 (Rx0) and m1 (x1) Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); // Table 1 - 2) obtain m'0 and m'1 // allocate the two vectors Vec3 mprime0; Vec3 mprime1; // pre compute n0 and n1 cf. 5. Lemma 2 const Vec3 n0 = Rx0.cross(t).normalized(); const Vec3 n1 = x1.cross(t).normalized(); if(Rx0.normalized().cross(t).squaredNorm() <= x1.normalized().cross(t).squaredNorm()) { // Eq. (12) mprime0 = Rx0 - Rx0.dot(n1) * n1; mprime1 = x1; } else { // Eq. (13) mprime0 = Rx0; mprime1 = x1 - x1.dot(n0) * n0; } return Compute3DPoint(mprime0, mprime1, t, R1, t1, X_euclidean); } bool TriangulateLInfinityAngular ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X_euclidean ) { // Table 1 - 1) we compute m0 (Rx0) and m1 (x1) Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); // cf. 7. Lemma 2 const Vec3 Rx0_norm = Rx0.normalized(); const Vec3 x1_norm = x1.normalized(); const Vec3 na = (Rx0_norm + x1_norm).cross(t); const Vec3 nb = (Rx0_norm - x1_norm).cross(t); const Vec3 nprime = na.squaredNorm() >= nb.squaredNorm() ? na.normalized() : nb.normalized(); const Vec3 mprime0 = Rx0 - (Rx0.dot(nprime)) * nprime; const Vec3 mprime1 = x1 - (x1.dot(nprime)) * nprime; return Compute3DPoint(mprime0, mprime1, t, R1, t1, X_euclidean); } bool TriangulateIDWMidpoint( const Mat3 & R0, const Vec3 & t0, const Vec3 & x0, const Mat3 & R1, const Vec3 & t1, const Vec3 & x1, Vec3* X_euclidean ) { // absolute to relative Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); const double p_norm = Rx0.cross(x1).norm(); const double q_norm = Rx0.cross(t).norm(); const double r_norm = x1.cross(t).norm(); // Eq. (10) const auto xprime1 = ( q_norm / (q_norm + r_norm) ) * ( t + (r_norm / p_norm) * (Rx0 + x1) ); // relative to absolute *X_euclidean = R1.transpose() * (xprime1 - t1); // Eq. (7) const Vec3 lambda0_Rx0 = (r_norm / p_norm) * Rx0; const Vec3 lambda1_x1 = (q_norm / p_norm) * x1; // Eq. (9) - test adequation return (t + lambda0_Rx0 - lambda1_x1).squaredNorm() < std::min(std::min( (t + lambda0_Rx0 + lambda1_x1).squaredNorm(), (t - lambda0_Rx0 - lambda1_x1).squaredNorm()), (t - lambda0_Rx0 + lambda1_x1).squaredNorm()); } bool Triangulate2View ( const Mat3 &R0, const Vec3 &t0, const Vec3 &bearing0, const Mat3 &R1, const Vec3 &t1, const Vec3 &bearing1, Vec3 &X, ETriangulationMethod etri_method ) { switch (etri_method) { case ETriangulationMethod::DIRECT_LINEAR_TRANSFORM: return TriangulateDLT(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::L1_ANGULAR: return TriangulateL1Angular(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::LINFINITY_ANGULAR: return TriangulateLInfinityAngular(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::INVERSE_DEPTH_WEIGHTED_MIDPOINT: return TriangulateIDWMidpoint(R0, t0, bearing0, R1, t1, bearing1, &X); break; default: return false; } return false; } } // namespace openMVG <commit_msg>[multiview] 2 View triangulation #1623 - Enhance the L1 solver. It's less naive and take less time<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/projection.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/numeric/numeric.h" namespace openMVG { // HZ 12.2 p.312 void TriangulateDLT ( const Mat34 &P1, const Vec3 &x1, const Mat34 &P2, const Vec3 &x2, Vec4 *X_homogeneous ) { // Solve: // [cross(x0,P0) X = 0] // [cross(x1,P1) X = 0] Mat4 design; design.row(0) = x1[0] * P1.row(2) - x1[2] * P1.row(0); design.row(1) = x1[1] * P1.row(2) - x1[2] * P1.row(1); design.row(2) = x2[0] * P2.row(2) - x2[2] * P2.row(0); design.row(3) = x2[1] * P2.row(2) - x2[2] * P2.row(1); const Eigen::JacobiSVD<Mat4> svd( design, Eigen::ComputeFullV ); ( *X_homogeneous ) = svd.matrixV().col( 3 ); } void TriangulateDLT ( const Mat34 &P1, const Vec3 &x1, const Mat34 &P2, const Vec3 &x2, Vec3 *X_euclidean ) { Vec4 X_homogeneous; TriangulateDLT(P1, x1, P2, x2, &X_homogeneous); (*X_euclidean) = X_homogeneous.hnormalized(); } bool TriangulateDLT ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X ) { Mat34 P0, P1; P0.block<3,3>(0,0) = R0; P1.block<3,3>(0,0) = R1; P0.block<3,1>(0,3) = t0; P1.block<3,1>(0,3) = t1; TriangulateDLT(P0, x0, P1, x1, X); return x0.dot(R0 * (*X + R0.transpose() * t0)) > 0.0 && x1.dot(R1 * (*X + R1.transpose() * t1)) > 0.0; } // Helper function // Compute Relative motion between two absolute poses parameterized by Rt // Rotate one bearing vector according to the relative motion inline void AbsoluteToRelative( const Mat3 &R0, const Vec3 &t0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x0, Mat3 &R, Vec3 &t, Vec3 &Rx0 ) { R = R1 * R0.transpose(); t = t1 - R * t0; Rx0 = R * x0; } // Helper function // Compute the 3D point from the outcome of an angular triangulation solver // Return true if the point pass the cheirality test, false otherwise // Lee & Civera Eq. (11) and Table 1 - 4) inline bool Compute3DPoint( const Vec3 &mprime0, const Vec3 &mprime1, const Vec3 &t, const Mat3 &R1, const Vec3 &t1, Vec3 *X) { const Vec3 z = mprime1.cross(mprime0); const double z_squared = z.squaredNorm(); const double lambda0 = z.dot(t.cross(mprime1)) / z_squared; const double lambda1 = z.dot(t.cross(mprime0)) / z_squared; const Vec3 xprime1 = t + lambda0 * mprime0; // x'1 is into the frame of camera1 convert it into the world frame in order to obtain the 3D point *X = R1.transpose() * (xprime1 - t1); // make and return the result of the cheirality test return lambda0 > 0.0 && lambda1 > 0.0; } bool TriangulateL1Angular ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X_euclidean ) { // Table 1 - 1) we compute m0 (Rx0) and m1 (x1) Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); // Table 1 - 2) obtain m'0 and m'1 if(Rx0.normalized().cross(t).squaredNorm() <= x1.normalized().cross(t).squaredNorm()) { const Vec3 n1 = x1.cross(t).normalized(); // Eq. (12) const Vec3 mprime0 = Rx0 - Rx0.dot(n1) * n1; return Compute3DPoint(mprime0, x1, t, R1, t1, X_euclidean); } else { const Vec3 n0 = Rx0.cross(t).normalized(); // Eq. (13) const Vec3 mprime1 = x1 - x1.dot(n0) * n0; return Compute3DPoint(Rx0, mprime1, t, R1, t1, X_euclidean); } } bool TriangulateLInfinityAngular ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X_euclidean ) { // Table 1 - 1) we compute m0 (Rx0) and m1 (x1) Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); // cf. 7. Lemma 2 const Vec3 Rx0_norm = Rx0.normalized(); const Vec3 x1_norm = x1.normalized(); const Vec3 na = (Rx0_norm + x1_norm).cross(t); const Vec3 nb = (Rx0_norm - x1_norm).cross(t); const Vec3 nprime = na.squaredNorm() >= nb.squaredNorm() ? na.normalized() : nb.normalized(); const Vec3 mprime0 = Rx0 - (Rx0.dot(nprime)) * nprime; const Vec3 mprime1 = x1 - (x1.dot(nprime)) * nprime; return Compute3DPoint(mprime0, mprime1, t, R1, t1, X_euclidean); } bool TriangulateIDWMidpoint( const Mat3 & R0, const Vec3 & t0, const Vec3 & x0, const Mat3 & R1, const Vec3 & t1, const Vec3 & x1, Vec3* X_euclidean ) { // absolute to relative Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); const double p_norm = Rx0.cross(x1).norm(); const double q_norm = Rx0.cross(t).norm(); const double r_norm = x1.cross(t).norm(); // Eq. (10) const auto xprime1 = ( q_norm / (q_norm + r_norm) ) * ( t + (r_norm / p_norm) * (Rx0 + x1) ); // relative to absolute *X_euclidean = R1.transpose() * (xprime1 - t1); // Eq. (7) const Vec3 lambda0_Rx0 = (r_norm / p_norm) * Rx0; const Vec3 lambda1_x1 = (q_norm / p_norm) * x1; // Eq. (9) - test adequation return (t + lambda0_Rx0 - lambda1_x1).squaredNorm() < std::min(std::min( (t + lambda0_Rx0 + lambda1_x1).squaredNorm(), (t - lambda0_Rx0 - lambda1_x1).squaredNorm()), (t - lambda0_Rx0 + lambda1_x1).squaredNorm()); } bool Triangulate2View ( const Mat3 &R0, const Vec3 &t0, const Vec3 &bearing0, const Mat3 &R1, const Vec3 &t1, const Vec3 &bearing1, Vec3 &X, ETriangulationMethod etri_method ) { switch (etri_method) { case ETriangulationMethod::DIRECT_LINEAR_TRANSFORM: return TriangulateDLT(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::L1_ANGULAR: return TriangulateL1Angular(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::LINFINITY_ANGULAR: return TriangulateLInfinityAngular(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::INVERSE_DEPTH_WEIGHTED_MIDPOINT: return TriangulateIDWMidpoint(R0, t0, bearing0, R1, t1, bearing1, &X); break; default: return false; } return false; } } // namespace openMVG <|endoftext|>
<commit_before>//! ======================================================================================== //! ExecutionGraph //! Copyright (C) 2014 by Gabriel Nützi <gnuetzi (at) gmail (døt) com> //! //! @date Sat Feb 17 2018 //! @author Gabriel Nützi, gnuetzi (at) gmail (døt) com //! //! This Source Code Form is subject to the terms of the Mozilla Public //! License, v. 2.0. If a copy of the MPL was not distributed with this //! file, You can obtain one at http://mozilla.org/MPL/2.0/. //! ======================================================================================== #include "cefapp/BackendResourceHandler.hpp" #include <array> #include <cef_parser.h> #include <chrono> #include <executionGraph/common/Assert.hpp> #include <thread> #include <wrapper/cef_closure_task.h> #include <wrapper/cef_helpers.h> #include "cefapp/BinaryBuffer.hpp" #include "cefapp/Loggers.hpp" #include "cefapp/RequestCef.hpp" #include "cefapp/ResponseCef.hpp" namespace { const std::array<uint8_t, 10> c_debugResponse = {'e', 'x', 'e', 'c', 'g', 'r', 'a', 'p', 'h', '!'}; // void printPostData2(CefRefPtr<CefRequest> request) // { // CefRefPtr<CefPostData> postData = request->GetPostData(); // if(postData) // { // EXECGRAPHGUI_APPLOG_DEBUG("Received {0} post data elements.", postData->GetElementCount()); // CefPostData::ElementVector elements; // postData->GetElements(elements); // for(CefRefPtr<CefPostDataElement> element : elements) // { // std::vector<uint8_t> buffer(element->GetBytesCount()); // element->GetBytes(buffer.size(), static_cast<void*>(buffer.data())); // std::stringstream ss; // for(auto& byte : buffer) // { // ss << byte << ","; // } // EXECGRAPHGUI_APPLOG_DEBUG("Post Data Binary: bytes: '{0}', data: '{1}'", element->GetBytesCount(), ss.str()); // } // } // else // { // EXECGRAPHGUI_APPLOG_WARN("Received no post data!"); // } // } //! Printing the binary data void printPostData(const BinaryBuffer<BufferPool>& buffer) { std::stringstream ss; for(const uint8_t& byte : buffer) { ss << byte << ","; } EXECGRAPHGUI_APPLOG_DEBUG("PostData received: '{0}'", ss.str()); } //! Wait some time in another other to simulate working. void debugWaitOnOtherThread(CefRefPtr<CefCallback> callback) { using namespace std::chrono_literals; EXECGRAPHGUI_APPLOG_DEBUG("Computing started [2sec] ..."); std::this_thread::sleep_for(1.3s); EXECGRAPHGUI_APPLOG_DEBUG("Computing finished!"); callback->Continue(); // Signal that response headers are here. } //! Read the post data `postData` and store it in the `BinaryBuffer`. template<typename RawAllocator> bool readPostData(CefRefPtr<CefPostData> postData, const std::string& mimeType, std::optional<RequestCef::Payload>& payload, std::shared_ptr<RawAllocator> allocator) { if(mimeType.empty()) { return false; } // Read post data if(postData && postData->GetElementCount() != 0) { CefPostData::ElementVector elements; postData->GetElements(elements); auto& element = elements.back(); // get the last post data element. if(element->GetBytesCount() == 0) { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: Received no bytes!"); return false; // dont continue } // Allocate BinaryBuffer BinaryBuffer<BufferPool> buffer(element->GetBytesCount(), allocator); element->GetBytes(buffer.getSize(), static_cast<void*>(buffer.getData())); EXECGRAPHGUI_APPLOG_DEBUG("BackendResourceHandler: Read last post data element: bytes: {0}.", element->GetBytesCount()); EXECGRAPHGUI_LOGCODE_DEBUG(printPostData(buffer)); payload = RequestCef::Payload{std::move(buffer), mimeType}; return true; // continue } EXECGRAPHGUI_APPLOG_WARN("BackendResourceHandler: Received no post data!"); return false; // dont continue } } // namespace void BackendResourceHandler::Cancel() { CEF_REQUIRE_IO_THREAD(); EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: id: '{0}' : cancelled!", getId().getName()); // if from external this handling can be cancelled // we need to properly wait for pending launched tasks // and after that -> call finish() and leave here! // todo finish(); } void BackendResourceHandler::GetResponseHeaders(CefRefPtr<CefResponse> response, int64& responseLength, CefString& redirectUrl) { CEF_REQUIRE_IO_THREAD(); response->SetMimeType("application/octet-stream"); responseLength = c_debugResponse.size(); // quit the ReadResponse after 10bytes have been read (-1 for manual quitting) } bool BackendResourceHandler::ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> cbResponseHeaderReady) { CEF_REQUIRE_IO_THREAD(); // Initialize the request ///////////////////////// if(!initRequest(request)) { // we dont handle this request or an error occured finish(); return false; } // Read the response into a buffer (if existing) //////////////////////////////////////////////// std::optional<RequestCef::Payload> payload; if(!readPostData(request->GetPostData(), m_mimeType, payload, m_allocator)) { finish(); return false; } // Make a request and response wrapper which we hand // over to the message dispatcher. //////////////////////////////////////////////////// // Make a RequestCef (move the payload into it) RequestCef requestCef(m_requestId, std::move(payload)); // Make a ResponseCef ResponseCef responseCef(cbResponseHeaderReady, m_allocator, false); // Get the future out m_responseFuture = ResponseFuture(responseCef); // Post a task to the UI-Thread to handle the message in the message dispatcher // which serializes the data, processes the request (its possible to launch a new worker thread, to not block UI-Thread), // and then serializes a proper reponse // if an error happens, the returned response contains no payload, but a well defined error message. // todo { // DEBUG ========== m_bytesRead = 0; // FILE Threads does not block UI, CefPostTask(TID_FILE, base::Bind(&debugWaitOnOtherThread, cbResponseHeaderReady)); } // DEBUG ========== return true; } bool BackendResourceHandler::ReadResponse(void* dataOut, int bytesToRead, int& bytesRead, CefRefPtr<CefCallback> callback) { CEF_REQUIRE_IO_THREAD(); // Handle the repsponse // todo { // DEBUG ========== if(m_bytesRead < c_debugResponse.size()) { std::memcpy(dataOut, c_debugResponse.data() + m_bytesRead, 1); m_bytesRead++; bytesRead = 1; // one byte read return true; } else { // Response is finished, we returned all bytes to read, so // finish up and return false. finish(); return false; } } // DEBUG ========== } //! Initilize the request by extracting the requestId and query string. //! @return false if the request cannot be handled. bool BackendResourceHandler::initRequest(CefRefPtr<CefRequest> request) { CefString url = request->GetURL(); CefURLParts urlParts; if(!CefParseURL(url, urlParts)) { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: id: '{0}' : url '{1}': url parse failed!", getId().getName(), url.ToString()); return false; } // Exctract requestId // e.g. m_requestId := "catergory/subcategory/command" m_requestId = executionGraph::splitLeadingSlashes(CefString(urlParts.path.str).ToString()); if(m_requestId.empty()) { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler id: '{0}' : url '{1}': requestId extract failed!", getId().getName(), url.ToString()); return false; } // Extract additional query m_query = CefString(urlParts.query.str).ToString(); // Extract MIME type CefRequest::HeaderMap headerMap; request->GetHeaderMap(headerMap); auto it = headerMap.find("Content-Type"); if(it != headerMap.end()) { m_mimeType = it->second; if(m_mimeType != "application/octet-stream" && m_mimeType != "application/json") { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: id: '{0}' : url '{1}': Content-Type: '{2}' can not be handled!", getId().getName(), url.ToString(), m_mimeType); return false; } } else { EXECGRAPHGUI_APPLOG_WARN("No 'Content-Type' header received -> post data will not be loaded!"); } return true; } //! Finish handling the request: Reset everything and signal callback. void BackendResourceHandler::finish() { m_requestId.clear(); m_query.clear(); m_mimeType.clear(); }<commit_msg>[doc]<commit_after>//! ======================================================================================== //! ExecutionGraph //! Copyright (C) 2014 by Gabriel Nützi <gnuetzi (at) gmail (døt) com> //! //! @date Sat Feb 17 2018 //! @author Gabriel Nützi, gnuetzi (at) gmail (døt) com //! //! This Source Code Form is subject to the terms of the Mozilla Public //! License, v. 2.0. If a copy of the MPL was not distributed with this //! file, You can obtain one at http://mozilla.org/MPL/2.0/. //! ======================================================================================== #include "cefapp/BackendResourceHandler.hpp" #include <array> #include <cef_parser.h> #include <chrono> #include <executionGraph/common/Assert.hpp> #include <thread> #include <wrapper/cef_closure_task.h> #include <wrapper/cef_helpers.h> #include "cefapp/BinaryBuffer.hpp" #include "cefapp/Loggers.hpp" #include "cefapp/RequestCef.hpp" #include "cefapp/ResponseCef.hpp" namespace { const std::array<uint8_t, 10> c_debugResponse = {'e', 'x', 'e', 'c', 'g', 'r', 'a', 'p', 'h', '!'}; // void printPostData2(CefRefPtr<CefRequest> request) // { // CefRefPtr<CefPostData> postData = request->GetPostData(); // if(postData) // { // EXECGRAPHGUI_APPLOG_DEBUG("Received {0} post data elements.", postData->GetElementCount()); // CefPostData::ElementVector elements; // postData->GetElements(elements); // for(CefRefPtr<CefPostDataElement> element : elements) // { // std::vector<uint8_t> buffer(element->GetBytesCount()); // element->GetBytes(buffer.size(), static_cast<void*>(buffer.data())); // std::stringstream ss; // for(auto& byte : buffer) // { // ss << byte << ","; // } // EXECGRAPHGUI_APPLOG_DEBUG("Post Data Binary: bytes: '{0}', data: '{1}'", element->GetBytesCount(), ss.str()); // } // } // else // { // EXECGRAPHGUI_APPLOG_WARN("Received no post data!"); // } // } //! Printing the binary data void printPostData(const BinaryBuffer<BufferPool>& buffer) { std::stringstream ss; for(const uint8_t& byte : buffer) { ss << byte << ","; } EXECGRAPHGUI_APPLOG_DEBUG("PostData received: '{0}'", ss.str()); } //! Wait some time in another other to simulate working. void debugWaitOnOtherThread(CefRefPtr<CefCallback> callback) { using namespace std::chrono_literals; EXECGRAPHGUI_APPLOG_DEBUG("Computing started [2sec] ..."); std::this_thread::sleep_for(1.3s); EXECGRAPHGUI_APPLOG_DEBUG("Computing finished!"); callback->Continue(); // Signal that response headers are here. } //! Read the post data `postData` and store it in the `BinaryBuffer`. template<typename RawAllocator> bool readPostData(CefRefPtr<CefPostData> postData, const std::string& mimeType, std::optional<RequestCef::Payload>& payload, std::shared_ptr<RawAllocator> allocator) { if(mimeType.empty()) { return false; } // Read post data if(postData && postData->GetElementCount() != 0) { CefPostData::ElementVector elements; postData->GetElements(elements); auto& element = elements.back(); // get the last post data element. if(element->GetBytesCount() == 0) { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: Received no bytes!"); return false; // dont continue } // Allocate BinaryBuffer BinaryBuffer<BufferPool> buffer(element->GetBytesCount(), allocator); element->GetBytes(buffer.getSize(), static_cast<void*>(buffer.getData())); EXECGRAPHGUI_APPLOG_DEBUG("BackendResourceHandler: Read last post data element: bytes: {0}.", element->GetBytesCount()); EXECGRAPHGUI_LOGCODE_DEBUG(printPostData(buffer)); payload = RequestCef::Payload{std::move(buffer), mimeType}; return true; // continue } EXECGRAPHGUI_APPLOG_WARN("BackendResourceHandler: Received no post data!"); return false; // dont continue } } // namespace //! Cancel the request (see: http://magpcss.org/ceforum/apidocs3/projects/(default)/CefResourceHandler.html) void BackendResourceHandler::Cancel() { CEF_REQUIRE_IO_THREAD(); EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: id: '{0}' : cancelled!", getId().getName()); // if from external this handling can be cancelled // we need to properly wait for pending launched tasks // and after that -> call finish() and leave here! // todo finish(); } //! Get the response headers (see: http://magpcss.org/ceforum/apidocs3/projects/(default)/CefResourceHandler.html) void BackendResourceHandler::GetResponseHeaders(CefRefPtr<CefResponse> response, int64& responseLength, CefString& redirectUrl) { CEF_REQUIRE_IO_THREAD(); response->SetMimeType("application/octet-stream"); responseLength = c_debugResponse.size(); // quit the ReadResponse after 10bytes have been read (-1 for manual quitting) } //! Process the request (see: http://magpcss.org/ceforum/apidocs3/projects/(default)/CefResourceHandler.html) bool BackendResourceHandler::ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> cbResponseHeaderReady) { CEF_REQUIRE_IO_THREAD(); // Initialize the request ///////////////////////// if(!initRequest(request)) { // we dont handle this request or an error occured finish(); return false; } // Read the response into a buffer (if existing) //////////////////////////////////////////////// std::optional<RequestCef::Payload> payload; if(!readPostData(request->GetPostData(), m_mimeType, payload, m_allocator)) { finish(); return false; } // Make a request and response wrapper which we hand // over to the message dispatcher. //////////////////////////////////////////////////// // Make a RequestCef (move the payload into it) RequestCef requestCef(m_requestId, std::move(payload)); // Make a ResponseCef ResponseCef responseCef(cbResponseHeaderReady, m_allocator, false); // Get the future out m_responseFuture = ResponseFuture(responseCef); // Post a task to the UI-Thread to handle the message in the message dispatcher // which serializes the data, processes the request (its possible to launch a new worker thread, to not block UI-Thread), // and then serializes a proper reponse // if an error happens, the returned response contains no payload, but a well defined error message. // todo { // DEBUG ========== m_bytesRead = 0; // FILE Threads does not block UI, CefPostTask(TID_FILE, base::Bind(&debugWaitOnOtherThread, cbResponseHeaderReady)); } // DEBUG ========== return true; } //! Read the response (see: http://magpcss.org/ceforum/apidocs3/projects/(default)/CefResourceHandler.html) bool BackendResourceHandler::ReadResponse(void* dataOut, int bytesToRead, int& bytesRead, CefRefPtr<CefCallback> callback) { CEF_REQUIRE_IO_THREAD(); // Handle the repsponse // todo { // DEBUG ========== if(m_bytesRead < c_debugResponse.size()) { std::memcpy(dataOut, c_debugResponse.data() + m_bytesRead, 1); m_bytesRead++; bytesRead = 1; // one byte read return true; } else { // Response is finished, we returned all bytes to read, so // finish up and return false. finish(); return false; } } // DEBUG ========== } //! Initilize the request by extracting the requestId and query string. //! @return false if the request cannot be handled. bool BackendResourceHandler::initRequest(CefRefPtr<CefRequest> request) { CefString url = request->GetURL(); CefURLParts urlParts; if(!CefParseURL(url, urlParts)) { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: id: '{0}' : url '{1}': url parse failed!", getId().getName(), url.ToString()); return false; } // Exctract requestId // e.g. m_requestId := "catergory/subcategory/command" m_requestId = executionGraph::splitLeadingSlashes(CefString(urlParts.path.str).ToString()); if(m_requestId.empty()) { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler id: '{0}' : url '{1}': requestId extract failed!", getId().getName(), url.ToString()); return false; } // Extract additional query m_query = CefString(urlParts.query.str).ToString(); // Extract MIME type CefRequest::HeaderMap headerMap; request->GetHeaderMap(headerMap); auto it = headerMap.find("Content-Type"); if(it != headerMap.end()) { m_mimeType = it->second; if(m_mimeType != "application/octet-stream" && m_mimeType != "application/json") { EXECGRAPHGUI_APPLOG_ERROR("BackendResourceHandler: id: '{0}' : url '{1}': Content-Type: '{2}' can not be handled!", getId().getName(), url.ToString(), m_mimeType); return false; } } else { EXECGRAPHGUI_APPLOG_WARN("No 'Content-Type' header received -> post data will not be loaded!"); } return true; } //! Finish handling the request: Reset everything and signal callback. void BackendResourceHandler::finish() { m_requestId.clear(); m_query.clear(); m_mimeType.clear(); }<|endoftext|>
<commit_before>#pragma once #include <atomic> #include <mutex> #include <condition_variable> #include <loom/common.hpp> #ifdef LOOM_ASSUME_X86 # define load_barrier() asm volatile("lfence":::"memory") # define store_barrier() asm volatile("sfence":::"memory") #else // LOOM_ASSUME_X86 # warn "defaulting to full memory barriers" # define load_barrier() __sync_synchronize() # define store_barrier() __sync_synchronize() #endif // LOOM_ASSUME_X86 #if 0 #define LOOM_DEBUG_QUEUE(message) LOOM_DEBUG(pendings() << ' ' << message); #else #define LOOM_DEBUG_QUEUE(message) #endif namespace loom { template<class Message> class SharedQueue { typedef uint_fast64_t count_t; struct Envelope { Message message; std::atomic<count_t> pending; Envelope () : pending(0) {} }; class Guard { std::mutex mutex_; std::condition_variable cond_variable_; public: void producer_wait (const std::atomic<count_t> & pending) { if (pending.load(std::memory_order_acquire) != 0) { std::unique_lock<std::mutex> lock(mutex_); cond_variable_.wait(lock, [&](){ return pending.load(std::memory_order_acquire) == 0; }); } } void consumer_wait (const std::atomic<count_t> & pending) { if (pending.load(std::memory_order_acquire) == 0) { std::unique_lock<std::mutex> lock(mutex_); cond_variable_.wait(lock, [&](){ return pending.load(std::memory_order_acquire) != 0; }); } } void produce ( std::atomic<count_t> & pending, const count_t & consumer_count) { LOOM_ASSERT2(consumer_count, "message sent to no consumers"); pending.store(consumer_count, std::memory_order_release); std::unique_lock<std::mutex> lock(mutex_); cond_variable_.notify_all(); } void consume (std::atomic<count_t> & pending) { if (pending.fetch_sub(1, std::memory_order_acq_rel) == 1) { std::unique_lock<std::mutex> lock(mutex_); cond_variable_.notify_one(); } } }; Envelope * const envelopes_; const size_t size_plus_one_; size_t position_; Guard front_; Guard back_; Envelope & envelopes (size_t position) { return envelopes_[position % size_plus_one_]; // TODO use mask } std::vector<count_t> pendings () const { std::vector<count_t> counts; counts.reserve(size_plus_one_); for (count_t i = 0; i < size_plus_one_; ++i) { counts.push_back(envelopes_[i].pending.load()); } return counts; } public: SharedQueue (size_t size) : envelopes_(new Envelope[size + 1]), size_plus_one_(size + 1), position_(0) { assert_ready(); } ~SharedQueue () { assert_ready(); delete[] envelopes_; } size_t size () const { return size_plus_one_ - 1; } void assert_ready () const { if (LOOM_DEBUG_LEVEL >= 2) { for (size_t i = 0; i < size_plus_one_; ++i) { LOOM_ASSERT_EQ(envelopes_[i].pending.load(), 0); } } } size_t unsafe_position () { assert_ready(); return position_; } void producer_wait () { LOOM_DEBUG_QUEUE("wait at " << (position_ % size_plus_one_)); Envelope & last_to_finish = envelopes(position_ + size_plus_one_ - 1); back_.producer_wait(last_to_finish.pending); assert_ready(); } template<class Producer> void produce (const Producer & producer) { LOOM_DEBUG_QUEUE("produce " << (position_ % size_plus_one_)); LOOM_ASSERT2(size_plus_one_ > 1, "cannot use zero-length queue"); const Envelope & fence = envelopes(position_ + 1); back_.producer_wait(fence.pending); Envelope & envelope = envelopes(position_); position_ += 1; count_t consumer_count = producer(envelope.message); store_barrier(); front_.produce(envelope.pending, consumer_count); } template<class Consumer> void consume (size_t position, const Consumer & consumer) { LOOM_DEBUG_QUEUE("consume " << (position % size_plus_one_)); LOOM_ASSERT2(size_plus_one_ > 1, "cannot use zero-length queue"); Envelope & envelope = envelopes(position); front_.consumer_wait(envelope.pending); load_barrier(); consumer(const_cast<const Message &>(envelope.message)); back_.consume(envelope.pending); } }; } // namespace loom <commit_msg>Implement producer_spin option in SharedQueue (off by default)<commit_after>#pragma once #include <atomic> #include <mutex> #include <condition_variable> #include <loom/common.hpp> #ifdef LOOM_ASSUME_X86 # define load_barrier() asm volatile("lfence":::"memory") # define store_barrier() asm volatile("sfence":::"memory") #else // LOOM_ASSUME_X86 # warn "defaulting to full memory barriers" # define load_barrier() __sync_synchronize() # define store_barrier() __sync_synchronize() #endif // LOOM_ASSUME_X86 #if 0 #define LOOM_DEBUG_QUEUE(message) LOOM_DEBUG(pendings() << ' ' << message); #else #define LOOM_DEBUG_QUEUE(message) #endif namespace loom { template<class Message> class SharedQueue { typedef uint_fast64_t count_t; struct Envelope { Message message; std::atomic<count_t> pending; Envelope () : pending(0) {} }; class Guard { std::mutex mutex_; std::condition_variable cond_variable_; public: enum { producer_spin = false }; void producer_wait (const std::atomic<count_t> & pending) { if (producer_spin) { while (pending.load(std::memory_order_acquire)) { // spin } } else { if (pending.load(std::memory_order_acquire) != 0) { std::unique_lock<std::mutex> lock(mutex_); cond_variable_.wait(lock, [&](){ return pending.load(std::memory_order_acquire) == 0; }); } } } void consumer_wait (const std::atomic<count_t> & pending) { if (pending.load(std::memory_order_acquire) == 0) { std::unique_lock<std::mutex> lock(mutex_); cond_variable_.wait(lock, [&](){ return pending.load(std::memory_order_acquire) != 0; }); } } void produce ( std::atomic<count_t> & pending, const count_t & consumer_count) { LOOM_ASSERT2(consumer_count, "message sent to no consumers"); pending.store(consumer_count, std::memory_order_release); std::unique_lock<std::mutex> lock(mutex_); cond_variable_.notify_all(); } void consume (std::atomic<count_t> & pending) { if (producer_spin) { pending.fetch_sub(1, std::memory_order_acq_rel); } else { if (pending.fetch_sub(1, std::memory_order_acq_rel) == 1) { std::unique_lock<std::mutex> lock(mutex_); cond_variable_.notify_one(); } } } }; Envelope * const envelopes_; const size_t size_plus_one_; size_t position_; Guard front_; Guard back_; Envelope & envelopes (size_t position) { return envelopes_[position % size_plus_one_]; // TODO use mask } std::vector<count_t> pendings () const { std::vector<count_t> counts; counts.reserve(size_plus_one_); for (count_t i = 0; i < size_plus_one_; ++i) { counts.push_back(envelopes_[i].pending.load()); } return counts; } public: SharedQueue (size_t size) : envelopes_(new Envelope[size + 1]), size_plus_one_(size + 1), position_(0) { assert_ready(); } ~SharedQueue () { assert_ready(); delete[] envelopes_; } size_t size () const { return size_plus_one_ - 1; } void assert_ready () const { if (LOOM_DEBUG_LEVEL >= 2) { for (size_t i = 0; i < size_plus_one_; ++i) { LOOM_ASSERT_EQ(envelopes_[i].pending.load(), 0); } } } size_t unsafe_position () { assert_ready(); return position_; } void producer_wait () { LOOM_DEBUG_QUEUE("wait at " << (position_ % size_plus_one_)); Envelope & last_to_finish = envelopes(position_ + size_plus_one_ - 1); back_.producer_wait(last_to_finish.pending); assert_ready(); } template<class Producer> void produce (const Producer & producer) { LOOM_DEBUG_QUEUE("produce " << (position_ % size_plus_one_)); LOOM_ASSERT2(size_plus_one_ > 1, "cannot use zero-length queue"); const Envelope & fence = envelopes(position_ + 1); back_.producer_wait(fence.pending); Envelope & envelope = envelopes(position_); position_ += 1; count_t consumer_count = producer(envelope.message); store_barrier(); front_.produce(envelope.pending, consumer_count); } template<class Consumer> void consume (size_t position, const Consumer & consumer) { LOOM_DEBUG_QUEUE("consume " << (position % size_plus_one_)); LOOM_ASSERT2(size_plus_one_ > 1, "cannot use zero-length queue"); Envelope & envelope = envelopes(position); front_.consumer_wait(envelope.pending); load_barrier(); consumer(const_cast<const Message &>(envelope.message)); back_.consume(envelope.pending); } }; } // namespace loom <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkVTKImageIO.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkVTKImageIO.h" #include "itkByteSwapper.h" #include <itksys/ios/sstream> #include <stdio.h> namespace itk { VTKImageIO::VTKImageIO() { this->SetNumberOfDimensions(2); m_ByteOrder = LittleEndian; m_FileType = Binary; } VTKImageIO::~VTKImageIO() { } bool VTKImageIO::OpenVTKFileForReading(std::ifstream& os, const char* filename) { // Make sure that we have a file to if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // Close file from any previous image if ( os.is_open() ) { os.close(); } // Open the new file for reading itkDebugMacro(<< "Initialize: opening file " << filename); // Actually open the file #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) const int openMode = std::ios::in|std::ios::binary; #elif ( defined(__GNUC__) && __GNUC__ >= 3 ) || defined (__MWERKS__) || defined (__INTEL_COMPILER) || defined (__MINGW32__) || defined(__CYGWIN__) const std::ios_base::openmode openMode = std::ios::in; #else const int openMode = std::ios::in; #endif os.open(filename, openMode); if ( os.fail() ) { itkExceptionMacro(<< "Could not open file for reading: " << filename); return false; } return true; } bool VTKImageIO::OpenVTKFileForWriting(std::ofstream& os, const char* filename) { // Make sure that we have a file to if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // Create the file. This is required on some older sgi's std::ofstream tFile(filename,std::ios::out); tFile.close(); // Close file from any previous image if ( os.is_open() ) { os.close(); } // Open the new file for writing itkDebugMacro(<< "Initialize: opening file " << filename); // Actually open the file #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) const int openMode = std::ios::out|std::ios::binary; #elif (defined(__GNUC__) && __GNUC__ >= 3) || defined (__MWERKS__) || defined (__INTEL_COMPILER) || defined (__MINGW32__) || defined(__CYGWIN__) const std::ios_base::openmode openMode =std::ios::out; #else const int openMode = std::ios::out; #endif os.open(filename, openMode); if ( os.fail() ) { itkExceptionMacro(<< "Could not open file for writing: " << filename); return false; } return true; } bool VTKImageIO::CanReadFile(const char* filename) { std::ifstream file; char buffer[256]; std::string fname(filename); if ( fname.find(".vtk") >= fname.length() ) { return false; } if ( ! this->OpenVTKFileForReading(file, filename) ) { return false; } // Check to see if its a vtk structured points file file.getline(buffer,255); file.getline(buffer,255); file.getline(buffer,255); file.getline(buffer,255); fname = buffer; if ( fname.find("STRUCTURED_POINTS") < fname.length() || fname.find("structured_points") < fname.length() ) { return true; } else { return false; } } void VTKImageIO::InternalReadImageInformation(std::ifstream& file) { char line[255]; std::string text; if ( ! this->OpenVTKFileForReading(file, m_FileName.c_str()) ) { itkExceptionMacro(<< "Cannot read requested file"); } file.getline(line,255); file.getline(line,255); file.getline(line,255); text = line; if ( text.find("ASCII") < text.length() || text.find("ascii") < text.length() ) { this->SetFileTypeToASCII(); } else if ( text.find("BINARY") < text.length() || text.find("binary") < text.length() ) { this->SetFileTypeToBinary(); } else { itkExceptionMacro(<< "Unrecognized type"); } file.getline(line,255); text = line; if ( text.find("STRUCTURED_POINTS") >= text.length() && text.find("structured_points") >= text.length() ) { itkExceptionMacro(<< "Not structured points, can't read"); } //extract dimensions, spacing, origin unsigned int dims[3]; float spacing[3]; float origin[3]; file.getline(line,255); text = line; // set values in case we don't find them this->SetNumberOfDimensions(3); m_Spacing[0] = 1.0; m_Spacing[1] = 1.0; m_Spacing[2] = 1.0; m_Origin[0] = 0.0; m_Origin[1] = 0.0; m_Origin[2] = 0.0; if ( text.find("DIMENSIONS") < text.length() || text.find("dimensions") < text.length() ) { sscanf(line, "%*s %d %d %d", dims, dims+1, dims+2); if ( dims[2] <= 1 ) { this->SetNumberOfDimensions(2); } else { this->SetNumberOfDimensions(3); } for ( unsigned int i=0; i < m_NumberOfDimensions; i++ ) { m_Dimensions[i] = dims[i]; } } else { itkExceptionMacro(<<"No dimensions defined"); } for ( bool readScalars=false; !readScalars; ) { file.getline(line,255); text = line; if ( text.find("SPACING") < text.length() || text.find("spacing") < text.length() ) { sscanf(line, "%*s %f %f %f", spacing, spacing+1, spacing+2); for ( unsigned int i=0; i < m_NumberOfDimensions; i++ ) { m_Spacing[i] = spacing[i]; } } else if ( text.find("ORIGIN") < text.length() || text.find("origin") < text.length() ) { sscanf(line, "%*s %f %f %f", origin, origin+1, origin+2); for ( unsigned int i=0; i < m_NumberOfDimensions; i++ ) { m_Origin[i] = origin[i]; } } else if ( text.find("COLOR_SCALARS") < text.length() || text.find("color_scalars") < text.length() ) { readScalars = true; int numComp = 1; sscanf(line, "%*s %*s %d", &numComp); if (numComp == 1) { SetPixelType(SCALAR); } else { SetPixelType(VECTOR); } if ( this->GetFileType() == ASCII ) { SetNumberOfComponents(numComp); SetComponentType(FLOAT); } else { SetNumberOfComponents(numComp); SetComponentType(UCHAR); } } else if ( text.find("SCALARS") < text.length() || text.find("scalars") < text.length() ) { readScalars = true; char pixelType[256]; int numComp = 1; sscanf(line, "%*s %*s %s %d", pixelType, &numComp); text = pixelType; if (numComp == 1) { SetPixelType(SCALAR); } else { SetPixelType(VECTOR); } if ( text.find("float") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(FLOAT); } else if ( text.find("double") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(DOUBLE); } else if ( text.find("unsigned_char") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(UCHAR); } else if ( text.find("char") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(CHAR); } else if ( text.find("unsigned_short") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(USHORT); } else if ( text.find("short") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(SHORT); } else if ( text.find("unsigned_int") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(UINT); } else if ( text.find("int") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(INT); } else if ( text.find("unsigned_long") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(ULONG); } else if ( text.find("long") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(LONG); } else { itkExceptionMacro(<<"Unrecognized type"); } file.getline(line,255); text = line; }//found scalars } } void VTKImageIO::Read(void* buffer) { std::ifstream file; this->InternalReadImageInformation(file); //We are positioned at the data. The data is read depending on whether //it is ASCII or binary. if ( m_FileType == ASCII ) { this->ReadBufferAsASCII(file, buffer, this->GetComponentType(), this->GetImageSizeInComponents()); } else { file.read(static_cast<char*>(buffer), this->GetImageSizeInBytes()); int size = this->GetComponentSize(); switch( size ) { case 2: ByteSwapper<short>::SwapRangeFromSystemToBigEndian((short *)buffer, this->GetImageSizeInComponents() ); break; case 4: ByteSwapper<float>::SwapRangeFromSystemToBigEndian((float *)buffer, this->GetImageSizeInComponents() ); break; case 8: ByteSwapper<double>::SwapRangeFromSystemToBigEndian((double *)buffer, this->GetImageSizeInComponents() ); break; } } } void VTKImageIO::ReadImageInformation() { std::ifstream file; this->InternalReadImageInformation(file); } bool VTKImageIO::CanWriteFile( const char* name ) { std::string filename = name; if ( filename != "" && filename.find(".vtk") < filename.length() ) { return true; } return false; } void VTKImageIO::Write(const void* buffer) { std::ofstream file; if ( ! this->OpenVTKFileForWriting(file,m_FileName.c_str()) ) { return; } // Check the image region for proper dimensions, etc. unsigned int numDims = this->GetNumberOfDimensions(); if ( numDims < 2 || numDims > 3 ) { itkExceptionMacro(<<"VTK Writer can only write 2 or 3-dimensional images"); return; } ImageIORegion ioRegion = this->GetIORegion(); // Write the VTK header information file << "# vtk DataFile Version 3.0\n"; file << "VTK File Generated by Insight Segmentation and Registration Toolkit (ITK)\n"; if ( this->GetFileType() == ASCII ) { file << "ASCII\n"; } else { file << "BINARY\n"; } // Save original formatting flags const itksys_ios::ios::fmtflags origianlFlags = file.flags(); const itksys_ios::streamsize origianlPrecision = file.precision(); file.setf( itksys_ios::ios::scientific, itksys_ios::ios::floatfield ); file.precision(16); // Write characteristics of the data file << "DATASET STRUCTURED_POINTS\n"; if ( numDims == 2 ) { file << "DIMENSIONS " << this->GetDimensions(0) << " " << this->GetDimensions(1) << " 1\n"; file << "SPACING " << m_Spacing[0] << " " << m_Spacing[1] << " 1.0\n"; file << "ORIGIN " << m_Origin[0] << " " << m_Origin[1] << " 0.0\n"; } else //numDims == 3 { file << "DIMENSIONS " << this->GetDimensions(0) << " " << this->GetDimensions(1) << " " << this->GetDimensions(2) << "\n"; file << "SPACING " << m_Spacing[0] << " " << m_Spacing[1] << " " << m_Spacing[2] << "\n"; file << "ORIGIN " << m_Origin[0] << " " << m_Origin[1] << " " << m_Origin[2] << "\n"; } // Restore the original formatting flags file.flags( origianlFlags ); file.precision( origianlPrecision ); file << "POINT_DATA " << this->GetImageSizeInPixels() << "\n"; file << "SCALARS scalars " << this->GetComponentTypeAsString(m_ComponentType) << " " << this->GetNumberOfComponents() << "\n"; file << "LOOKUP_TABLE default\n"; // Write the actual pixel data if ( m_FileType == ASCII ) { this->WriteBufferAsASCII(file, buffer, this->GetComponentType(), this->GetImageSizeInComponents()); } else //binary { int size = this->GetComponentSize(); const unsigned long int numbytes=this->GetImageSizeInBytes(); char * tempmemory=new char[numbytes]; memcpy(tempmemory,buffer,numbytes); switch( size ) { case 2: { ByteSwapper<short>::SwapRangeFromSystemToBigEndian(reinterpret_cast<short *>(tempmemory), this->GetImageSizeInComponents() ); } break; case 4: { ByteSwapper<float>::SwapRangeFromSystemToBigEndian(reinterpret_cast<float *>(tempmemory), this->GetImageSizeInComponents() ); } break; case 8: { ByteSwapper<double>::SwapRangeFromSystemToBigEndian(reinterpret_cast<double *>(tempmemory), this->GetImageSizeInComponents() ); } break; } file.write(static_cast<const char*>(tempmemory), this->GetImageSizeInBytes()); delete [] tempmemory; } } void VTKImageIO::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace itk <commit_msg>COMP: GCC 2.95 defines precision type differently.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkVTKImageIO.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkVTKImageIO.h" #include "itkByteSwapper.h" #include <itksys/ios/sstream> #include <stdio.h> namespace itk { VTKImageIO::VTKImageIO() { this->SetNumberOfDimensions(2); m_ByteOrder = LittleEndian; m_FileType = Binary; } VTKImageIO::~VTKImageIO() { } bool VTKImageIO::OpenVTKFileForReading(std::ifstream& os, const char* filename) { // Make sure that we have a file to if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // Close file from any previous image if ( os.is_open() ) { os.close(); } // Open the new file for reading itkDebugMacro(<< "Initialize: opening file " << filename); // Actually open the file #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) const int openMode = std::ios::in|std::ios::binary; #elif ( defined(__GNUC__) && __GNUC__ >= 3 ) || defined (__MWERKS__) || defined (__INTEL_COMPILER) || defined (__MINGW32__) || defined(__CYGWIN__) const std::ios_base::openmode openMode = std::ios::in; #else const int openMode = std::ios::in; #endif os.open(filename, openMode); if ( os.fail() ) { itkExceptionMacro(<< "Could not open file for reading: " << filename); return false; } return true; } bool VTKImageIO::OpenVTKFileForWriting(std::ofstream& os, const char* filename) { // Make sure that we have a file to if ( filename == "" ) { itkExceptionMacro(<<"A FileName must be specified."); return false; } // Create the file. This is required on some older sgi's std::ofstream tFile(filename,std::ios::out); tFile.close(); // Close file from any previous image if ( os.is_open() ) { os.close(); } // Open the new file for writing itkDebugMacro(<< "Initialize: opening file " << filename); // Actually open the file #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) const int openMode = std::ios::out|std::ios::binary; #elif (defined(__GNUC__) && __GNUC__ >= 3) || defined (__MWERKS__) || defined (__INTEL_COMPILER) || defined (__MINGW32__) || defined(__CYGWIN__) const std::ios_base::openmode openMode =std::ios::out; #else const int openMode = std::ios::out; #endif os.open(filename, openMode); if ( os.fail() ) { itkExceptionMacro(<< "Could not open file for writing: " << filename); return false; } return true; } bool VTKImageIO::CanReadFile(const char* filename) { std::ifstream file; char buffer[256]; std::string fname(filename); if ( fname.find(".vtk") >= fname.length() ) { return false; } if ( ! this->OpenVTKFileForReading(file, filename) ) { return false; } // Check to see if its a vtk structured points file file.getline(buffer,255); file.getline(buffer,255); file.getline(buffer,255); file.getline(buffer,255); fname = buffer; if ( fname.find("STRUCTURED_POINTS") < fname.length() || fname.find("structured_points") < fname.length() ) { return true; } else { return false; } } void VTKImageIO::InternalReadImageInformation(std::ifstream& file) { char line[255]; std::string text; if ( ! this->OpenVTKFileForReading(file, m_FileName.c_str()) ) { itkExceptionMacro(<< "Cannot read requested file"); } file.getline(line,255); file.getline(line,255); file.getline(line,255); text = line; if ( text.find("ASCII") < text.length() || text.find("ascii") < text.length() ) { this->SetFileTypeToASCII(); } else if ( text.find("BINARY") < text.length() || text.find("binary") < text.length() ) { this->SetFileTypeToBinary(); } else { itkExceptionMacro(<< "Unrecognized type"); } file.getline(line,255); text = line; if ( text.find("STRUCTURED_POINTS") >= text.length() && text.find("structured_points") >= text.length() ) { itkExceptionMacro(<< "Not structured points, can't read"); } //extract dimensions, spacing, origin unsigned int dims[3]; float spacing[3]; float origin[3]; file.getline(line,255); text = line; // set values in case we don't find them this->SetNumberOfDimensions(3); m_Spacing[0] = 1.0; m_Spacing[1] = 1.0; m_Spacing[2] = 1.0; m_Origin[0] = 0.0; m_Origin[1] = 0.0; m_Origin[2] = 0.0; if ( text.find("DIMENSIONS") < text.length() || text.find("dimensions") < text.length() ) { sscanf(line, "%*s %d %d %d", dims, dims+1, dims+2); if ( dims[2] <= 1 ) { this->SetNumberOfDimensions(2); } else { this->SetNumberOfDimensions(3); } for ( unsigned int i=0; i < m_NumberOfDimensions; i++ ) { m_Dimensions[i] = dims[i]; } } else { itkExceptionMacro(<<"No dimensions defined"); } for ( bool readScalars=false; !readScalars; ) { file.getline(line,255); text = line; if ( text.find("SPACING") < text.length() || text.find("spacing") < text.length() ) { sscanf(line, "%*s %f %f %f", spacing, spacing+1, spacing+2); for ( unsigned int i=0; i < m_NumberOfDimensions; i++ ) { m_Spacing[i] = spacing[i]; } } else if ( text.find("ORIGIN") < text.length() || text.find("origin") < text.length() ) { sscanf(line, "%*s %f %f %f", origin, origin+1, origin+2); for ( unsigned int i=0; i < m_NumberOfDimensions; i++ ) { m_Origin[i] = origin[i]; } } else if ( text.find("COLOR_SCALARS") < text.length() || text.find("color_scalars") < text.length() ) { readScalars = true; int numComp = 1; sscanf(line, "%*s %*s %d", &numComp); if (numComp == 1) { SetPixelType(SCALAR); } else { SetPixelType(VECTOR); } if ( this->GetFileType() == ASCII ) { SetNumberOfComponents(numComp); SetComponentType(FLOAT); } else { SetNumberOfComponents(numComp); SetComponentType(UCHAR); } } else if ( text.find("SCALARS") < text.length() || text.find("scalars") < text.length() ) { readScalars = true; char pixelType[256]; int numComp = 1; sscanf(line, "%*s %*s %s %d", pixelType, &numComp); text = pixelType; if (numComp == 1) { SetPixelType(SCALAR); } else { SetPixelType(VECTOR); } if ( text.find("float") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(FLOAT); } else if ( text.find("double") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(DOUBLE); } else if ( text.find("unsigned_char") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(UCHAR); } else if ( text.find("char") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(CHAR); } else if ( text.find("unsigned_short") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(USHORT); } else if ( text.find("short") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(SHORT); } else if ( text.find("unsigned_int") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(UINT); } else if ( text.find("int") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(INT); } else if ( text.find("unsigned_long") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(ULONG); } else if ( text.find("long") < text.length() ) { SetNumberOfComponents(numComp); SetComponentType(LONG); } else { itkExceptionMacro(<<"Unrecognized type"); } file.getline(line,255); text = line; }//found scalars } } void VTKImageIO::Read(void* buffer) { std::ifstream file; this->InternalReadImageInformation(file); //We are positioned at the data. The data is read depending on whether //it is ASCII or binary. if ( m_FileType == ASCII ) { this->ReadBufferAsASCII(file, buffer, this->GetComponentType(), this->GetImageSizeInComponents()); } else { file.read(static_cast<char*>(buffer), this->GetImageSizeInBytes()); int size = this->GetComponentSize(); switch( size ) { case 2: ByteSwapper<short>::SwapRangeFromSystemToBigEndian((short *)buffer, this->GetImageSizeInComponents() ); break; case 4: ByteSwapper<float>::SwapRangeFromSystemToBigEndian((float *)buffer, this->GetImageSizeInComponents() ); break; case 8: ByteSwapper<double>::SwapRangeFromSystemToBigEndian((double *)buffer, this->GetImageSizeInComponents() ); break; } } } void VTKImageIO::ReadImageInformation() { std::ifstream file; this->InternalReadImageInformation(file); } bool VTKImageIO::CanWriteFile( const char* name ) { std::string filename = name; if ( filename != "" && filename.find(".vtk") < filename.length() ) { return true; } return false; } void VTKImageIO::Write(const void* buffer) { std::ofstream file; if ( ! this->OpenVTKFileForWriting(file,m_FileName.c_str()) ) { return; } // Check the image region for proper dimensions, etc. unsigned int numDims = this->GetNumberOfDimensions(); if ( numDims < 2 || numDims > 3 ) { itkExceptionMacro(<<"VTK Writer can only write 2 or 3-dimensional images"); return; } ImageIORegion ioRegion = this->GetIORegion(); // Write the VTK header information file << "# vtk DataFile Version 3.0\n"; file << "VTK File Generated by Insight Segmentation and Registration Toolkit (ITK)\n"; if ( this->GetFileType() == ASCII ) { file << "ASCII\n"; } else { file << "BINARY\n"; } // Save original formatting flags const itksys_ios::ios::fmtflags originalFlags = file.flags(); #if (defined(__GNUC__) && (__GNUC__ <=2)) const itksys_ios::ios::streamsize originalPrecision = file.precision(); #else const itksys_ios::streamsize originalPrecision = file.precision(); #endif file.setf( itksys_ios::ios::scientific, itksys_ios::ios::floatfield ); file.precision(16); // Write characteristics of the data file << "DATASET STRUCTURED_POINTS\n"; if ( numDims == 2 ) { file << "DIMENSIONS " << this->GetDimensions(0) << " " << this->GetDimensions(1) << " 1\n"; file << "SPACING " << m_Spacing[0] << " " << m_Spacing[1] << " 1.0\n"; file << "ORIGIN " << m_Origin[0] << " " << m_Origin[1] << " 0.0\n"; } else //numDims == 3 { file << "DIMENSIONS " << this->GetDimensions(0) << " " << this->GetDimensions(1) << " " << this->GetDimensions(2) << "\n"; file << "SPACING " << m_Spacing[0] << " " << m_Spacing[1] << " " << m_Spacing[2] << "\n"; file << "ORIGIN " << m_Origin[0] << " " << m_Origin[1] << " " << m_Origin[2] << "\n"; } // Restore the original formatting flags file.flags( originalFlags ); file.precision( originalPrecision ); file << "POINT_DATA " << this->GetImageSizeInPixels() << "\n"; file << "SCALARS scalars " << this->GetComponentTypeAsString(m_ComponentType) << " " << this->GetNumberOfComponents() << "\n"; file << "LOOKUP_TABLE default\n"; // Write the actual pixel data if ( m_FileType == ASCII ) { this->WriteBufferAsASCII(file, buffer, this->GetComponentType(), this->GetImageSizeInComponents()); } else //binary { int size = this->GetComponentSize(); const unsigned long int numbytes=this->GetImageSizeInBytes(); char * tempmemory=new char[numbytes]; memcpy(tempmemory,buffer,numbytes); switch( size ) { case 2: { ByteSwapper<short>::SwapRangeFromSystemToBigEndian(reinterpret_cast<short *>(tempmemory), this->GetImageSizeInComponents() ); } break; case 4: { ByteSwapper<float>::SwapRangeFromSystemToBigEndian(reinterpret_cast<float *>(tempmemory), this->GetImageSizeInComponents() ); } break; case 8: { ByteSwapper<double>::SwapRangeFromSystemToBigEndian(reinterpret_cast<double *>(tempmemory), this->GetImageSizeInComponents() ); } break; } file.write(static_cast<const char*>(tempmemory), this->GetImageSizeInBytes()); delete [] tempmemory; } } void VTKImageIO::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace itk <|endoftext|>
<commit_before>#include <iostream> #include <memory> #include <chrono> #include <thread> #include <ctime> #include "opencv2/opencv.hpp" #include "opencv2/highgui.hpp" static const cv::Size frameSize(640,480); static const double cameraFPS = 4; static const cv::Size displaySize(640, 480); static const double displayRatio = double(displaySize.height) / frameSize.height; static const char* detection_window = "Object Detection"; static cv::Mat display; std::string date_now() { std::time_t result = std::time(nullptr); std::string str(std::asctime(std::localtime(&result))); // trim trailing endl size_t endpos = str.find_last_not_of(" \t\n"); if( str.npos != endpos ) { str = str.substr( 0, endpos+1 ); } return str + " "; } int main(int argc, const char** argv) { static int n_file = 1; cv::Mat frame, hsv, filtered, buffer1; static cv::Vec3i BlobLower(50, 80, 50); static cv::Vec3i BlobUpper(94, 255, 255); static int dispMode = 2; // 0: none, 1: bw, 2: color bool is_capture = false; cv::VideoCapture capture; if(argc > 1) { is_capture = false; } else { is_capture = true; for(;;) { capture.open(0); capture.set(cv::CAP_PROP_FRAME_WIDTH, frameSize.width); capture.set(cv::CAP_PROP_FRAME_HEIGHT, frameSize.height); capture.set(cv::CAP_PROP_FPS, cameraFPS); capture.set(cv::CAP_PROP_AUTO_EXPOSURE, 0.25); // Magic! 0.25 means manual exposure, 0.75 = auto capture.set(cv::CAP_PROP_EXPOSURE, 0.001); capture.set(cv::CAP_PROP_BRIGHTNESS, 0.5); capture.set(cv::CAP_PROP_CONTRAST, 0.5); capture.set(cv::CAP_PROP_SATURATION, 0.5); if(capture.isOpened()) break; std::cerr << "Couldn't connect to camera" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); } std::cerr << date_now() << "Camera opened." << " Resolution: " << capture.get(cv::CAP_PROP_FRAME_WIDTH) << "x" << capture.get(cv::CAP_PROP_FRAME_HEIGHT) << " FPS: " << capture.get(cv::CAP_PROP_FPS) << std::endl; } cv::namedWindow(detection_window, cv::WINDOW_NORMAL); cv::createTrackbar("Lo H",detection_window, &BlobLower[0], 255); cv::createTrackbar("Hi H",detection_window, &BlobUpper[0], 255); cv::createTrackbar("Lo S",detection_window, &BlobLower[1], 255); cv::createTrackbar("Hi S",detection_window, &BlobUpper[1], 255); cv::createTrackbar("Lo V",detection_window, &BlobLower[2], 255); cv::createTrackbar("Hi V",detection_window, &BlobUpper[2], 255); for(int n=0;;++n) { if(is_capture) { capture >> frame; if (frame.empty()) { std::cerr << " Error reading from camera, empty frame." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(2)); continue; } } else { frame = cv::imread(argv[n_file]); } std::vector<long int> timer_values; std::vector<std::string> timer_names; timer_names.push_back("start"); timer_values.push_back(cv::getTickCount()); cv::cvtColor(frame, hsv, CV_BGR2HSV); inRange(hsv, BlobLower, BlobUpper, filtered); timer_names.push_back("inRange applied"); timer_values.push_back(cv::getTickCount()); switch(dispMode) { case 1: cv::resize(filtered, display, displaySize); break; case 2: cv::resize(frame, display, displaySize); break; } timer_names.push_back("display resized"); timer_values.push_back(cv::getTickCount()); if (dispMode > 0 and n%int(cameraFPS) == 0) { for(size_t i = 0; i < timer_values.size(); ++i) { long int val; if(i == 0) val = timer_values[timer_values.size()-1] - timer_values[0]; else val = timer_values[i] - timer_values[i-1]; std::ostringstream osst; osst << timer_names[i] << ": " << val / cv::getTickFrequency(); cv::putText(display, osst.str(), cv::Point(20,60+20*i), 0, 0.33, cv::Scalar(10,200,200)); } std::ostringstream ossf; ossf << argv[n_file]; cv::putText(display, ossf.str(), cv::Point(20,160), 0, 0.33, cv::Scalar(10,200,200)); cv::imshow(detection_window, display); } int key = cv::waitKey(2); if ((key & 255) == 27) break; if ((key & 255) == 32) { if(++dispMode > 2) dispMode = 1; } if (is_capture) { if((key & 255) == 's') cv::waitKey(0); if ((key & 255) == 'w') { std::ostringstream filename; filename << "img" << n_file++ << ".png"; imwrite(filename.str(), frame); } } else { if((key & 255) == 'n') n_file = (n_file+1)%(argc-1) + 1; } } return 0; } <commit_msg>Auto exposure mode for takepics utility<commit_after>#include <iostream> #include <memory> #include <chrono> #include <thread> #include <ctime> #include "opencv2/opencv.hpp" #include "opencv2/highgui.hpp" static const cv::Size frameSize(640,480); static const double cameraFPS = 4; static const cv::Size displaySize(640, 480); static const double displayRatio = double(displaySize.height) / frameSize.height; static const char* detection_window = "Object Detection"; static cv::Mat display; std::string date_now() { std::time_t result = std::time(nullptr); std::string str(std::asctime(std::localtime(&result))); // trim trailing endl size_t endpos = str.find_last_not_of(" \t\n"); if( str.npos != endpos ) { str = str.substr( 0, endpos+1 ); } return str + " "; } int main(int argc, const char** argv) { bool autoexp = false; static int n_file = 1; cv::Mat frame, hsv, filtered, buffer1; static cv::Vec3i BlobLower(50, 80, 50); static cv::Vec3i BlobUpper(94, 255, 255); static int dispMode = 2; // 0: none, 1: bw, 2: color bool is_capture = false; cv::VideoCapture capture; if(argc == 2 and std::strcmp(argv[1], "auto") == 0) autoexp = true; if(!autoexp and argc > 1) { is_capture = false; } else { is_capture = true; std::cerr << "Option 'auto' for auto exposure" << std::endl << std::endl; std::cerr << " ESC\tQuit" << std::endl; std::cerr << " w\tSave picture in a sequential file" << std::endl; std::cerr << " s\tPause, freeze the frame" << std::endl; std::cerr << " Space\tChange display mode" << std::endl << std::endl; for(;;) { capture.open(0); capture.set(cv::CAP_PROP_FRAME_WIDTH, frameSize.width); capture.set(cv::CAP_PROP_FRAME_HEIGHT, frameSize.height); capture.set(cv::CAP_PROP_FPS, cameraFPS); if(autoexp) { capture.set(cv::CAP_PROP_AUTO_EXPOSURE, 0.0); // Magic! 0.25 means manual exposure, 0.75 = auto } else { capture.set(cv::CAP_PROP_AUTO_EXPOSURE, 0.25); // Magic! 0.25 means manual exposure, 0.75 = auto capture.set(cv::CAP_PROP_EXPOSURE, 0.001); } capture.set(cv::CAP_PROP_BRIGHTNESS, 0.5); capture.set(cv::CAP_PROP_CONTRAST, 0.5); capture.set(cv::CAP_PROP_SATURATION, 0.5); if(capture.isOpened()) break; std::cerr << "Couldn't connect to camera" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); } std::cerr << date_now() << "Camera opened." << " Resolution: " << capture.get(cv::CAP_PROP_FRAME_WIDTH) << "x" << capture.get(cv::CAP_PROP_FRAME_HEIGHT) << " FPS: " << capture.get(cv::CAP_PROP_FPS) << std::endl; } cv::namedWindow(detection_window, cv::WINDOW_NORMAL); cv::createTrackbar("Lo H",detection_window, &BlobLower[0], 255); cv::createTrackbar("Hi H",detection_window, &BlobUpper[0], 255); cv::createTrackbar("Lo S",detection_window, &BlobLower[1], 255); cv::createTrackbar("Hi S",detection_window, &BlobUpper[1], 255); cv::createTrackbar("Lo V",detection_window, &BlobLower[2], 255); cv::createTrackbar("Hi V",detection_window, &BlobUpper[2], 255); for(int n=0;;++n) { if(is_capture) { capture >> frame; if (frame.empty()) { std::cerr << " Error reading from camera, empty frame." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(2)); continue; } } else { frame = cv::imread(argv[n_file]); } std::vector<long int> timer_values; std::vector<std::string> timer_names; timer_names.push_back("start"); timer_values.push_back(cv::getTickCount()); cv::cvtColor(frame, hsv, CV_BGR2HSV); inRange(hsv, BlobLower, BlobUpper, filtered); timer_names.push_back("inRange applied"); timer_values.push_back(cv::getTickCount()); switch(dispMode) { case 1: cv::resize(filtered, display, displaySize); break; case 2: cv::resize(frame, display, displaySize); break; } timer_names.push_back("display resized"); timer_values.push_back(cv::getTickCount()); if (dispMode > 0 and n%int(cameraFPS) == 0) { for(size_t i = 0; i < timer_values.size(); ++i) { long int val; if(i == 0) val = timer_values[timer_values.size()-1] - timer_values[0]; else val = timer_values[i] - timer_values[i-1]; std::ostringstream osst; osst << timer_names[i] << ": " << val / cv::getTickFrequency(); cv::putText(display, osst.str(), cv::Point(20,60+20*i), 0, 0.33, cv::Scalar(10,200,200)); } std::ostringstream ossf; ossf << argv[n_file]; cv::putText(display, ossf.str(), cv::Point(20,160), 0, 0.33, cv::Scalar(10,200,200)); cv::imshow(detection_window, display); } int key = cv::waitKey(2); if ((key & 255) == 27) break; if ((key & 255) == 32) { if(++dispMode > 2) dispMode = 1; } if (is_capture) { if((key & 255) == 's') cv::waitKey(0); if ((key & 255) == 'w') { std::ostringstream filename; filename << "img" << n_file++ << ".png"; imwrite(filename.str(), frame); } } else { if((key & 255) == 'n') n_file = (n_file+1)%(argc-1) + 1; } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Srijan R Shetty * Author: Srijan R Shetty <srijan.shetty+code@gmail.com> * * 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. */ // The configuration file #include "config.h" // The header file #include "vafile.h" // To get the fileSize #include <sys/stat.h> // File IO #include <fstream> #include <iostream> #include <sstream> // STL #include <string> #include <bitset> #include <vector> // Math #include <math.h> namespace VAFile { /** * Get the size of a file. * @param filename The name of the file to check size for * @return The filesize, or 0 if the file does not exist. */ long long getFileSize(const std::string& filename) { struct stat st; if(stat(filename.c_str(), &st) != 0) { return 0; } return (long long) st.st_size; } /** * Compute the quantization of a given coordinate using binary search * @param coordinate The coordinate * @return an integer quantization value */ int quantize(double coordinate) { int first = 1; int last = ((int) pow(2, BITS)) - 1; double base = pow(2, -1 * BITS); // Base cases if (coordinate <= base) { return 0; } if (coordinate >= base * last) { return last; } // Computation of quantization using binary search int quantization = 0; while (last >= first) { int mid = (first + last) / 2; // Base case, when first and last are equal, we get the quantization if (first == last) { if (coordinate < first * base) { quantization = first - 1; } else if (coordinate > first * base){ quantization = first + 1; } else { quantization = first; } break; } // Update the bounds according to the value of the coordinate if (coordinate < mid * base) { last = mid - 1; } else { first = mid + 1; } } return quantization; } /** * Parse a line from a normal file and return the coordinates * @param line The line to parse * @return A vector representing the point */ std::vector<double> parseNormalLine(std::string line) { // Create a stringstream from the input line std::istringstream inputStream(line); // Read each coordinate from the stream and create a vector double coordinate; std::vector<double> coordinates; for (int i = 0; i < DIMENSIONS; ++i) { inputStream >> coordinate; coordinates.push_back(coordinate); } // Return a pair return coordinates; } /** * Parse a line from a VAFile and return the coordinates and lineCount * @param line The line to parse * @return A pair of the vector as a bitset and the lineCount */ std::pair< std::vector< std::bitset<BITS> >, long long> parseVALine(std::string line) { // Create a stringstream from the input line std::istringstream inputStream(line); // Read each coordinate from the stream and create a vector std::bitset<BITS> coordinate; std::vector< std::bitset<BITS> > coordinates; for (int i = 0; i < DIMENSIONS; ++i) { inputStream >> coordinate; coordinates.push_back(coordinate); } // Get the lineCount from the line long long lineCount; inputStream >> lineCount; // Return a pair of coordinates and lineCount return make_pair(coordinates, lineCount); } /** * Batch build a VAFile from a normal file */ void batchBuild() { std::ifstream ifile(DATAFILE); std::ofstream ofile(VAFILE); // A pointer to the location of the point in the file long long lineCount = 1; // Read the file line by line for (std::string line; std::getline(ifile, line); ++lineCount) { // Parse the input line into coordinates and string std::vector<double> coordinates = parseNormalLine(line); // Encode the line and print it out to the file // Create an outputStream which will be written to the VAfile std::ostringstream outputStream; // Now add the quantized point to the outputStream for (auto coordinate : coordinates) { std::bitset<BITS> quant(quantize(coordinate)); outputStream << quant << " "; } // Now add the lineCount outputStream << lineCount; // Push this line to the file ofile << outputStream.str() << std::endl << std::flush; } // Close open files ifile.close(); ofile.close(); } /** * Perform rangeQuery on the VAFile * @param point A vector representation of the query point * @param radius Query radius */ void rangeQuery(std::vector<double> point, double radius) { // Memory map the file incase it is smaller than memory size long long fileSize = getFileSize(VAFILE); } } <commit_msg>Functions to getQuantizedPoint and minDistance<commit_after>/* * Copyright (c) 2015 Srijan R Shetty * Author: Srijan R Shetty <srijan.shetty+code@gmail.com> * * 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. */ // The configuration file #include "config.h" // The header file #include "vafile.h" // To get the fileSize #include <sys/stat.h> // File IO #include <fstream> #include <iostream> #include <sstream> // STL #include <string> #include <bitset> #include <vector> // Math #include <math.h> namespace VAFile { /** * Get the size of a file. * @param filename The name of the file to check size for * @return The filesize, or 0 if the file does not exist. */ long long getFileSize(const std::string& filename) { struct stat st; if(stat(filename.c_str(), &st) != 0) { return 0; } return (long long) st.st_size; } /** * Compute the quantization of a given coordinate using binary search * @param coordinate The coordinate * @return an integer quantization value */ int quantize(double coordinate) { int first = 1; int last = ((int) pow(2, BITS)) - 1; double base = pow(2, -1 * BITS); // Base cases if (coordinate <= base) { return 0; } if (coordinate >= base * last) { return last; } // Computation of quantization using binary search int quantization = 0; while (last >= first) { int mid = (first + last) / 2; // Base case, when first and last are equal, we get the quantization if (first == last) { if (coordinate < first * base) { quantization = first - 1; } else if (coordinate > first * base){ quantization = first + 1; } else { quantization = first; } break; } // Update the bounds according to the value of the coordinate if (coordinate < mid * base) { last = mid - 1; } else { first = mid + 1; } } return quantization; } /** * Get the minimum distance between a point and grid * @param point The point as a vector<double> * @param grid The grid as a vector<bitset> * @return Minimum distance */ double getMinDistance(std::vector<double> point, std::vector< std::bitset<BITS> > grid) { double base = pow(2, -1 * BITS); double minDistance = 0; for (int i = 0; i < DIMENSIONS; ++i) { double component = fabs(grid[i].to_ulong() * base - point[i]); minDistance += component * component; } return sqrt(minDistance); } /** * Get the quantized grid for a point * @param point The point as a vector<double> * @return grid The grid to which the point belongs as vector<bitset> */ std::vector< std::bitset<BITS> > getQuantizedPoint(std::vector<double> point) { std::vector< std::bitset<BITS> > quantizedPoint; for (int i = 0; i < DIMENSIONS; ++i) { quantizedPoint.push_back(std::bitset<BITS>(quantize(point[i]))); } return quantizedPoint; } /** * Parse a line from a normal file and return the coordinates * @param line The line to parse * @return A vector representing the point */ std::vector<double> parseNormalLine(std::string line) { // Create a stringstream from the input line std::istringstream inputStream(line); // Read each coordinate from the stream and create a vector double coordinate; std::vector<double> coordinates; for (int i = 0; i < DIMENSIONS; ++i) { inputStream >> coordinate; coordinates.push_back(coordinate); } // Return a pair return coordinates; } /** * Parse a line from a VAFile and return the coordinates and lineCount * @param line The line to parse * @return A pair of the vector as a bitset and the lineCount */ std::pair< std::vector< std::bitset<BITS> >, long long> parseVALine(std::string line) { // Create a stringstream from the input line std::istringstream inputStream(line); // Read each coordinate from the stream and create a vector std::bitset<BITS> coordinate; std::vector< std::bitset<BITS> > coordinates; for (int i = 0; i < DIMENSIONS; ++i) { inputStream >> coordinate; coordinates.push_back(coordinate); } // Get the lineCount from the line long long lineCount; inputStream >> lineCount; // Return a pair of coordinates and lineCount return make_pair(coordinates, lineCount); } /** * Batch build a VAFile from a normal file */ void batchBuild() { std::ifstream ifile(DATAFILE); std::ofstream ofile(VAFILE); // A pointer to the location of the point in the file long long lineCount = 1; // Read the file line by line for (std::string line; std::getline(ifile, line); ++lineCount) { // Parse the input line into coordinates and string std::vector<double> coordinates = parseNormalLine(line); // Encode the line and print it out to the file // Create an outputStream which will be written to the VAfile std::ostringstream outputStream; // Now add the quantized point to the outputStream for (auto coordinate : coordinates) { std::bitset<BITS> quant(quantize(coordinate)); outputStream << quant << " "; } // Now add the lineCount outputStream << lineCount; // Push this line to the file ofile << outputStream.str() << std::endl << std::flush; } // Close open files ifile.close(); ofile.close(); } /** * Perform rangeQuery on the VAFile * @param point A vector representation of the query point * @param radius Query radius */ void rangeQuery(std::vector<double> point, double radius) { // Memory map the file incase it is smaller than memory size long long fileSize = getFileSize(VAFILE); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Dionysus Module: mwsRestXMLParser.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Kitware Inc. All rights reserved. See Copyright.txt or http://www.Kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mwsRestXMLParser.h" namespace mws{ /** Constructor */ RestXMLParser::RestXMLParser() { m_ErrorCode = 0; m_ErrorMessage = ""; m_CurrentTag = ""; m_FoundXMLTag = false; m_PreBuffer = ""; } //---------------------------------------------------------------------------- static void itkXMLParserStartElement(void* parser, const char *name, const char **atts) { // Begin element handler that is registered with the XML_Parser. // This just casts the user data to a itkXMLParser and calls // StartElement. static_cast<RestXMLParser*>(parser)->StartElement(name, atts); } //---------------------------------------------------------------------------- static void itkXMLParserEndElement(void* parser, const char *name) { // End element handler that is registered with the XML_Parser. This // just casts the user data to a itkXMLParser and calls EndElement. static_cast<RestXMLParser*>(parser)->EndElement(name); } //-------------------------------------------------------------------------------------------------- static void itkXMLParserCharacterDataHandler(void* parser, const char* data, int length) { // Character data handler that is registered with the XML_Parser. // This just casts the user data to a itkXMLParser and calls // CharacterDataHandler. static_cast<RestXMLParser*>(parser)->CharacterDataHandler(data, length); } /** Initialize **/ void RestXMLParser::Initialize(void) { m_Parser = XML_ParserCreate(0); XML_SetElementHandler(m_Parser, &itkXMLParserStartElement, &itkXMLParserEndElement); XML_SetCharacterDataHandler(m_Parser, &itkXMLParserCharacterDataHandler); XML_SetUserData(m_Parser,this); this->m_ErrorMessage = ""; this->m_CurrentTag = ""; this->m_ErrorCode = 0; } //-------------------------------------------------------------------------------------------------- bool RestXMLParser::Parse(const char* buffer,unsigned long length) { if(!m_Parser) { return false; } if(!m_FoundXMLTag) { m_PreBuffer.append(buffer); size_t pos; if((pos = m_PreBuffer.find("<?xml")) != std::string::npos) { m_FoundXMLTag = true; m_PreBuffer = m_PreBuffer.substr(pos); buffer = m_PreBuffer.c_str(); length = m_PreBuffer.length(); } } if(m_FoundXMLTag) { int result = XML_Parse(m_Parser, buffer, length, false); if(result==0) { m_ErrorCode = 1; m_ErrorMessage = "Cannot parse XML: "; for(int i = 0; i < length; ++i) { m_ErrorMessage += buffer[i]; } return false; } } return true; } // Add a tag to parse void RestXMLParser::AddTag(const char* name,std::string& value) { TagType tag; tag.name = name; tag.value = &value; m_TagsToParse.push_back(tag); } // Clear all the tags void RestXMLParser::ClearTags() { m_TagsToParse.clear(); } /** Finalize **/ void RestXMLParser::Finalize(void) { XML_ParserFree(m_Parser); } // Callback function -- called from XML parser with start-of-element // information. void RestXMLParser::StartElement(const char * name,const char **atts) { m_CurrentTag += "/"; m_CurrentTag += name; // If it's an error message std::string val = ""; if(!m_CurrentTag.compare("/rsp/err")) { for(int i = 0; atts[i] != 0; i++) { if(i%2==0) { val = atts[i]; } else { if(!val.compare("code")) { m_ErrorCode = atoi(atts[i]); } else if(!val.compare("msg")) { m_ErrorMessage = atts[i]; } } } return; } } // Callback function -- called from XML parser when ending tag // encountered void RestXMLParser::EndElement(const char *name) { std::string tag = "/"; tag += name; unsigned int pos = m_CurrentTag.find(tag); if(pos != -1) { m_CurrentTag = m_CurrentTag.substr(0,pos); } } //-------------------------------------------------------------------------------------------------- // Callback function -- called from XML parser with the character data // for an XML element void RestXMLParser::CharacterDataHandler(const char *inData, int inLength) { std::vector<TagType>::iterator it = m_TagsToParse.begin(); while(it!=m_TagsToParse.end()) { if(!(*it).name.compare(m_CurrentTag)) { (*((*it).value)).append(inData,inLength); } it++; } } } // end namespace <commit_msg>ENH: Fix signed/unsigned warning<commit_after>/*========================================================================= Program: Dionysus Module: mwsRestXMLParser.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Kitware Inc. All rights reserved. See Copyright.txt or http://www.Kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mwsRestXMLParser.h" namespace mws{ /** Constructor */ RestXMLParser::RestXMLParser() { m_ErrorCode = 0; m_ErrorMessage = ""; m_CurrentTag = ""; m_FoundXMLTag = false; m_PreBuffer = ""; } //---------------------------------------------------------------------------- static void itkXMLParserStartElement(void* parser, const char *name, const char **atts) { // Begin element handler that is registered with the XML_Parser. // This just casts the user data to a itkXMLParser and calls // StartElement. static_cast<RestXMLParser*>(parser)->StartElement(name, atts); } //---------------------------------------------------------------------------- static void itkXMLParserEndElement(void* parser, const char *name) { // End element handler that is registered with the XML_Parser. This // just casts the user data to a itkXMLParser and calls EndElement. static_cast<RestXMLParser*>(parser)->EndElement(name); } //-------------------------------------------------------------------------------------------------- static void itkXMLParserCharacterDataHandler(void* parser, const char* data, int length) { // Character data handler that is registered with the XML_Parser. // This just casts the user data to a itkXMLParser and calls // CharacterDataHandler. static_cast<RestXMLParser*>(parser)->CharacterDataHandler(data, length); } /** Initialize **/ void RestXMLParser::Initialize(void) { m_Parser = XML_ParserCreate(0); XML_SetElementHandler(m_Parser, &itkXMLParserStartElement, &itkXMLParserEndElement); XML_SetCharacterDataHandler(m_Parser, &itkXMLParserCharacterDataHandler); XML_SetUserData(m_Parser,this); this->m_ErrorMessage = ""; this->m_CurrentTag = ""; this->m_ErrorCode = 0; } //-------------------------------------------------------------------------------------------------- bool RestXMLParser::Parse(const char* buffer,unsigned long length) { if(!m_Parser) { return false; } if(!m_FoundXMLTag) { m_PreBuffer.append(buffer); size_t pos; if((pos = m_PreBuffer.find("<?xml")) != std::string::npos) { m_FoundXMLTag = true; m_PreBuffer = m_PreBuffer.substr(pos); buffer = m_PreBuffer.c_str(); length = m_PreBuffer.length(); } } if(m_FoundXMLTag) { int result = XML_Parse(m_Parser, buffer, length, false); if(result==0) { m_ErrorCode = 1; m_ErrorMessage = "Cannot parse XML: "; for(unsigned long i = 0; i < length; ++i) { m_ErrorMessage += buffer[i]; } return false; } } return true; } // Add a tag to parse void RestXMLParser::AddTag(const char* name,std::string& value) { TagType tag; tag.name = name; tag.value = &value; m_TagsToParse.push_back(tag); } // Clear all the tags void RestXMLParser::ClearTags() { m_TagsToParse.clear(); } /** Finalize **/ void RestXMLParser::Finalize(void) { XML_ParserFree(m_Parser); } // Callback function -- called from XML parser with start-of-element // information. void RestXMLParser::StartElement(const char * name,const char **atts) { m_CurrentTag += "/"; m_CurrentTag += name; // If it's an error message std::string val = ""; if(!m_CurrentTag.compare("/rsp/err")) { for(int i = 0; atts[i] != 0; i++) { if(i%2==0) { val = atts[i]; } else { if(!val.compare("code")) { m_ErrorCode = atoi(atts[i]); } else if(!val.compare("msg")) { m_ErrorMessage = atts[i]; } } } return; } } // Callback function -- called from XML parser when ending tag // encountered void RestXMLParser::EndElement(const char *name) { std::string tag = "/"; tag += name; unsigned int pos = m_CurrentTag.find(tag); if(pos != -1) { m_CurrentTag = m_CurrentTag.substr(0,pos); } } //-------------------------------------------------------------------------------------------------- // Callback function -- called from XML parser with the character data // for an XML element void RestXMLParser::CharacterDataHandler(const char *inData, int inLength) { std::vector<TagType>::iterator it = m_TagsToParse.begin(); while(it!=m_TagsToParse.end()) { if(!(*it).name.compare(m_CurrentTag)) { (*((*it).value)).append(inData,inLength); } it++; } } } // end namespace <|endoftext|>
<commit_before>// This Source Code Form is licensed MPLv2: http://mozilla.org/MPL/2.0 #ifndef __RAPICORN_FORMATTER_HH__ #define __RAPICORN_FORMATTER_HH__ #include <rcore/cxxaux.hh> #include <rcore/aida.hh> #include <sstream> namespace Rapicorn { namespace Lib { // Namespace for implementation internals // == StringFormatter == /** StringFormatter - printf-like string formatting for C++. * * See parse_directive() for supported flags, modifiers and conversions. * Finding strings with size modifiers for possible cleanups: * egrep "\"([^\"]|\\\")*%[0-9$]*[-+#0 \'I]*[*0-9$]*[.*0-9$]*[hlLqjzt]+[nSspmCcdiouXxFfGgEeAa]" */ class StringFormatter { typedef long long signed int LLong; typedef long long unsigned int ULLong; typedef long double LDouble; struct FormatArg { union { LDouble d; double f; signed char i1; short i2; int i4; long i6; LLong i8; void *p; const char *s; }; char kind; // f d i u p s }; inline void assign (FormatArg &farg, bool arg) { farg.kind = '1'; farg.i1 = arg; } inline void assign (FormatArg &farg, char arg) { farg.kind = '1'; farg.i1 = arg; } inline void assign (FormatArg &farg, signed char arg) { farg.kind = '1'; farg.i1 = arg; } inline void assign (FormatArg &farg, unsigned char arg) { farg.kind = '1'; farg.i1 = arg; } #if __SIZEOF_WCHAR_T__ == 1 inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '1'; farg.i1 = arg; } #endif inline void assign (FormatArg &farg, short arg) { farg.kind = '2'; farg.i2 = arg; } inline void assign (FormatArg &farg, unsigned short arg) { farg.kind = '2'; farg.i2 = arg; } #if __SIZEOF_WCHAR_T__ == 2 inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '2'; farg.i2 = arg; } #endif inline void assign (FormatArg &farg, int arg) { farg.kind = '4'; farg.i4 = arg; } inline void assign (FormatArg &farg, unsigned int arg) { farg.kind = '4'; farg.i4 = arg; } #if __SIZEOF_WCHAR_T__ == 4 inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '4'; farg.i4 = arg; } #endif inline void assign (FormatArg &farg, long arg) { farg.kind = '6'; farg.i6 = arg; } inline void assign (FormatArg &farg, unsigned long arg) { farg.kind = '6'; farg.i6 = arg; } inline void assign (FormatArg &farg, long long arg) { farg.kind = '8'; farg.i8 = arg; } inline void assign (FormatArg &farg, unsigned long long arg) { farg.kind = '8'; farg.i8 = arg; } inline void assign (FormatArg &farg, float arg) { farg.kind = 'f'; farg.f = arg; } inline void assign (FormatArg &farg, double arg) { farg.kind = 'f'; farg.f = arg; } inline void assign (FormatArg &farg, long double arg) { farg.kind = 'd'; farg.d = arg; } inline void assign (FormatArg &farg, char *arg) { farg.kind = 's'; farg.s = arg; } inline void assign (FormatArg &farg, const char *arg) { farg.kind = 's'; farg.s = arg; } inline void assign (FormatArg &farg, const std::string &arg) { assign (farg, arg.c_str()); } inline void assign (FormatArg &farg, void *arg) { farg.kind = 'p'; farg.p = arg; } template<class T> inline void assign (FormatArg &farg, T *const &arg) { assign (farg, (void*) arg); } template<class T> typename std::enable_if<std::is_enum<T>::value, void> // eliminated via SFINAE ::type assign (FormatArg &farg, const T &arg) { farg.kind = '8'; farg.i8 = arg; } template<class T> typename std::enable_if<std::is_class<T>::value, void> // eliminated via SFINAE ::type assign (FormatArg &farg, const T &arg) { std::ostringstream os; os << arg; temporaries_.push_back (os.str()); assign (farg, temporaries_[temporaries_.size()-1]); } const FormatArg& format_arg (size_t nth); uint32_t arg_as_width (size_t nth); uint32_t arg_as_precision (size_t nth); LLong arg_as_longlong (size_t nth); LDouble arg_as_ldouble (size_t nth); const char* arg_as_chars (size_t nth); void* arg_as_ptr (size_t nth); struct Directive { char conversion; uint32_t adjust_left : 1, add_sign : 1, use_width : 1, use_precision : 1; uint32_t alternate_form : 1, zero_padding : 1, add_space : 1, locale_grouping : 1; uint32_t field_width, precision, start, end, value_index, width_index, precision_index; Directive() : conversion (0), adjust_left (0), add_sign (0), use_width (0), use_precision (0), alternate_form (0), zero_padding (0), add_space (0), locale_grouping (0), field_width (0), precision (0), start (0), end (0), value_index (0), width_index (0), precision_index (0) {} }; typedef std::function<String (const String&)> ArgTransform; FormatArg *const fargs_; const size_t nargs_; const int locale_context_; const ArgTransform &arg_transform_; vector<std::string> temporaries_; static std::string format_error (const char *err, const char *format, size_t directive); static const char* parse_directive (const char **stringp, size_t *indexp, Directive *dirp); std::string locale_format (size_t last, const char *format); std::string render_format (size_t last, const char *format); std::string render_directive (const Directive &dir); template<class A> std::string render_arg (const Directive &dir, const char *modifier, A arg); template<size_t N> inline std::string intern_format (const char *format) { return locale_format (N, format); } template<size_t N, class A, class ...Args> inline std::string intern_format (const char *format, const A &arg, const Args &...args) { assign (fargs_[N], arg); return intern_format<N+1> (format, args...); } template<size_t N> inline constexpr StringFormatter (const ArgTransform &arg_transform, size_t nargs, FormatArg (&mem)[N], int lc) : fargs_ (mem), nargs_ (nargs), locale_context_ (lc), arg_transform_ (arg_transform) {} public: enum LocaleContext { POSIX_LOCALE, CURRENT_LOCALE, }; template<LocaleContext LC = POSIX_LOCALE, class ...Args> static __attribute__ ((__format__ (printf, 2, 0), noinline)) std::string format (const ArgTransform &arg_transform, const char *format, const Args &...args) { constexpr size_t N = sizeof... (Args); FormatArg mem[N ? N : 1]; StringFormatter formatter (arg_transform, N, mem, LC); return formatter.intern_format<0> (format, args...); } }; } // Lib } // Rapicorn #endif /* __RAPICORN_FORMATTER_HH__ */ <commit_msg>RCORE: update StringFormatter docs<commit_after>// This Source Code Form is licensed MPLv2: http://mozilla.org/MPL/2.0 #ifndef __RAPICORN_FORMATTER_HH__ #define __RAPICORN_FORMATTER_HH__ #include <rcore/cxxaux.hh> #include <rcore/aida.hh> #include <sstream> namespace Rapicorn { namespace Lib { // Namespace for implementation internals // == StringFormatter == /** StringFormatter - sprintf() like string formatting for C++. * * See format() for supported flags, modifiers and conversions. * To find source code strings with size modifiers for possible cleanups, use: * egrep "\"([^\"]|\\\")*%[0-9$]*[-+#0 \'I]*[*0-9$]*[.*0-9$]*[hlLqjzt]+[nSspmCcdiouXxFfGgEeAa]" */ class StringFormatter { typedef long long signed int LLong; typedef long long unsigned int ULLong; typedef long double LDouble; struct FormatArg { union { LDouble d; double f; signed char i1; short i2; int i4; long i6; LLong i8; void *p; const char *s; }; char kind; // f d i u p s }; inline void assign (FormatArg &farg, bool arg) { farg.kind = '1'; farg.i1 = arg; } inline void assign (FormatArg &farg, char arg) { farg.kind = '1'; farg.i1 = arg; } inline void assign (FormatArg &farg, signed char arg) { farg.kind = '1'; farg.i1 = arg; } inline void assign (FormatArg &farg, unsigned char arg) { farg.kind = '1'; farg.i1 = arg; } #if __SIZEOF_WCHAR_T__ == 1 inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '1'; farg.i1 = arg; } #endif inline void assign (FormatArg &farg, short arg) { farg.kind = '2'; farg.i2 = arg; } inline void assign (FormatArg &farg, unsigned short arg) { farg.kind = '2'; farg.i2 = arg; } #if __SIZEOF_WCHAR_T__ == 2 inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '2'; farg.i2 = arg; } #endif inline void assign (FormatArg &farg, int arg) { farg.kind = '4'; farg.i4 = arg; } inline void assign (FormatArg &farg, unsigned int arg) { farg.kind = '4'; farg.i4 = arg; } #if __SIZEOF_WCHAR_T__ == 4 inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '4'; farg.i4 = arg; } #endif inline void assign (FormatArg &farg, long arg) { farg.kind = '6'; farg.i6 = arg; } inline void assign (FormatArg &farg, unsigned long arg) { farg.kind = '6'; farg.i6 = arg; } inline void assign (FormatArg &farg, long long arg) { farg.kind = '8'; farg.i8 = arg; } inline void assign (FormatArg &farg, unsigned long long arg) { farg.kind = '8'; farg.i8 = arg; } inline void assign (FormatArg &farg, float arg) { farg.kind = 'f'; farg.f = arg; } inline void assign (FormatArg &farg, double arg) { farg.kind = 'f'; farg.f = arg; } inline void assign (FormatArg &farg, long double arg) { farg.kind = 'd'; farg.d = arg; } inline void assign (FormatArg &farg, char *arg) { farg.kind = 's'; farg.s = arg; } inline void assign (FormatArg &farg, const char *arg) { farg.kind = 's'; farg.s = arg; } inline void assign (FormatArg &farg, const std::string &arg) { assign (farg, arg.c_str()); } inline void assign (FormatArg &farg, void *arg) { farg.kind = 'p'; farg.p = arg; } template<class T> inline void assign (FormatArg &farg, T *const &arg) { assign (farg, (void*) arg); } template<class T> typename std::enable_if<std::is_enum<T>::value, void> // eliminated via SFINAE ::type assign (FormatArg &farg, const T &arg) { farg.kind = '8'; farg.i8 = arg; } template<class T> typename std::enable_if<std::is_class<T>::value, void> // eliminated via SFINAE ::type assign (FormatArg &farg, const T &arg) { std::ostringstream os; os << arg; temporaries_.push_back (os.str()); assign (farg, temporaries_[temporaries_.size()-1]); } const FormatArg& format_arg (size_t nth); uint32_t arg_as_width (size_t nth); uint32_t arg_as_precision (size_t nth); LLong arg_as_longlong (size_t nth); LDouble arg_as_ldouble (size_t nth); const char* arg_as_chars (size_t nth); void* arg_as_ptr (size_t nth); struct Directive { char conversion; uint32_t adjust_left : 1, add_sign : 1, use_width : 1, use_precision : 1; uint32_t alternate_form : 1, zero_padding : 1, add_space : 1, locale_grouping : 1; uint32_t field_width, precision, start, end, value_index, width_index, precision_index; Directive() : conversion (0), adjust_left (0), add_sign (0), use_width (0), use_precision (0), alternate_form (0), zero_padding (0), add_space (0), locale_grouping (0), field_width (0), precision (0), start (0), end (0), value_index (0), width_index (0), precision_index (0) {} }; typedef std::function<String (const String&)> ArgTransform; FormatArg *const fargs_; const size_t nargs_; const int locale_context_; const ArgTransform &arg_transform_; vector<std::string> temporaries_; static std::string format_error (const char *err, const char *format, size_t directive); static const char* parse_directive (const char **stringp, size_t *indexp, Directive *dirp); std::string locale_format (size_t last, const char *format); std::string render_format (size_t last, const char *format); std::string render_directive (const Directive &dir); template<class A> std::string render_arg (const Directive &dir, const char *modifier, A arg); template<size_t N> inline std::string intern_format (const char *format) { return locale_format (N, format); } template<size_t N, class A, class ...Args> inline std::string intern_format (const char *format, const A &arg, const Args &...args) { assign (fargs_[N], arg); return intern_format<N+1> (format, args...); } template<size_t N> inline constexpr StringFormatter (const ArgTransform &arg_transform, size_t nargs, FormatArg (&mem)[N], int lc) : fargs_ (mem), nargs_ (nargs), locale_context_ (lc), arg_transform_ (arg_transform) {} public: enum LocaleContext { POSIX_LOCALE, CURRENT_LOCALE, }; /** Format a string according to an sprintf() @a format string with @a arguments. * Refer to sprintf() for the format string details, this function is designed to * serve as an sprintf() replacement and mimick its behaviour as close as possible. * Supported format directive features are: * - Formatting flags (sign conversion, padding, alignment), i.e. the flags: [-#0+ '] * - Field width and precision specifications. * - Positional arguments for field width, precision and value. * - Length modifiers are tolerated: i.e. any of [hlLjztqZ]. * - The conversion specifiers [spmcCdiouXxFfGgEeAa]. * * Additionally, arguments can be transformed after conversion by passing a std::string * conversion function as @a arg_transform. This may e.g. be used for XML character * escaping of the format argument values. <br/> * @NOTE Format errors, e.g. missing arguments will produce a warning on stderr and * return the @a format string unmodified. * @returns A formatted string. */ template<LocaleContext LC = POSIX_LOCALE, class ...Args> static __attribute__ ((__format__ (printf, 2, 0), noinline)) std::string format (const ArgTransform &arg_transform, const char *format, const Args &...arguments) { constexpr size_t N = sizeof... (Args); FormatArg mem[N ? N : 1]; StringFormatter formatter (arg_transform, N, mem, LC); return formatter.intern_format<0> (format, arguments...); } }; } // Lib } // Rapicorn #endif /* __RAPICORN_FORMATTER_HH__ */ <|endoftext|>
<commit_before>/* * Renderer.cpp * * Renders the box2d content */ #include <vector> #include <Box2D/Box2D.h> #include <SDL2/SDL.h> #include <SDL2/SDL_main.h> #include <SDL2/SDL2_gfxPrimitives.h> #include "Renderer.h" const float Renderer::NUMERATOR = 7.0f; const float Renderer::DENOMINATOR = 9.0f; const float Renderer::SCALING = NUMERATOR / DENOMINATOR; const float Renderer::PADDING_PERCENT = (DENOMINATOR - NUMERATOR) / DENOMINATOR / 2; int Renderer::metersToPixels(const float &meters){ return round(meters * oneMeterInPX); } b2Vec2 Renderer::toScreenCoords(const b2Vec2 &position){ return b2Vec2 ( round(width * PADDING_PERCENT) + metersToPixels(position.x), round(height * PADDING_PERCENT) + metersToPixels(position.y) ); } Renderer::Renderer(int width, int height) : width(width), height(height){ SDL_Init( /*SDL_INIT_EVERYTHING*/SDL_INIT_VIDEO ); window = SDL_CreateWindow( "PinballBot", // window title SDL_WINDOWPOS_CENTERED, // initial x position SDL_WINDOWPOS_CENTERED, // initial y position this->width, // width, in pixels this->height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI //enables retina support ); if (window == nullptr) { printf("Could not create window: %s\n", SDL_GetError()); SDL_Quit(); return; } //updates the width and height if there's a high DPI and calc other vars afterwards SDL_GL_GetDrawableSize(window, &this->width, &this->height); oneMeterInPX = round(SCALING * this->height); /* one meter is equal to half of the width of the window */ renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); //white background SDL_RenderClear(renderer); } Renderer::~Renderer(){ SDL_DestroyWindow(window); SDL_Quit(); } void Renderer::redraw(){ SDL_RenderPresent(renderer); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); } void Renderer::dPolygon(const b2Vec2* vertices, int32 vertexCount, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ std::vector<short> x(vertexCount); std::vector<short> y(vertexCount); for(int i=0;i<vertexCount;i++){ b2Vec2 vec = toScreenCoords(vertices[i]); x[i] = (short) vec.x; y[i] = (short) vec.y; } if(filled){ filledPolygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); }else{ polygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); } } void Renderer::dCircle(const b2Vec2& center, float32 radius, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ b2Vec2 coords = toScreenCoords(center); if(filled){ filledCircleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); }else{ circleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); } } void Renderer::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { dPolygon(vertices, vertexCount, 0, 0, 0, 255, false); } void Renderer::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { dPolygon(vertices, vertexCount, 0, 0, 0, 255, true); } void Renderer::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) { dCircle(center, radius, 0, 0, 0, 255, false); } void Renderer::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) { dCircle(center, radius, 0, 0, 0, 255, true); } void Renderer::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) { b2Vec2 from = toScreenCoords(p1); b2Vec2 to = toScreenCoords(p2); lineRGBA(renderer, (Sint16) from.x, (Sint16) from.y, (Sint16) to.x, (Sint16) to.y, 0, 0, 0, 255); } void Renderer::DrawTransform(const b2Transform& xf) { } <commit_msg>Corrected wrong description<commit_after>/* * Renderer.cpp * * Renders the box2d content */ #include <vector> #include <Box2D/Box2D.h> #include <SDL2/SDL.h> #include <SDL2/SDL_main.h> #include <SDL2/SDL2_gfxPrimitives.h> #include "Renderer.h" const float Renderer::NUMERATOR = 7.0f; const float Renderer::DENOMINATOR = 9.0f; const float Renderer::SCALING = NUMERATOR / DENOMINATOR; const float Renderer::PADDING_PERCENT = (DENOMINATOR - NUMERATOR) / DENOMINATOR / 2; int Renderer::metersToPixels(const float &meters){ return round(meters * oneMeterInPX); } b2Vec2 Renderer::toScreenCoords(const b2Vec2 &position){ return b2Vec2 ( round(width * PADDING_PERCENT) + metersToPixels(position.x), round(height * PADDING_PERCENT) + metersToPixels(position.y) ); } Renderer::Renderer(int width, int height) : width(width), height(height){ SDL_Init( /*SDL_INIT_EVERYTHING*/SDL_INIT_VIDEO ); window = SDL_CreateWindow( "PinballBot", // window title SDL_WINDOWPOS_CENTERED, // initial x position SDL_WINDOWPOS_CENTERED, // initial y position this->width, // width, in pixels this->height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI //enables retina support ); if (window == nullptr) { printf("Could not create window: %s\n", SDL_GetError()); SDL_Quit(); return; } //updates the width and height if there's a high DPI and calc other vars afterwards SDL_GL_GetDrawableSize(window, &this->width, &this->height); oneMeterInPX = round(SCALING * this->height); /* one meter is equal to the height */ renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); //white background SDL_RenderClear(renderer); } Renderer::~Renderer(){ SDL_DestroyWindow(window); SDL_Quit(); } void Renderer::redraw(){ SDL_RenderPresent(renderer); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); } void Renderer::dPolygon(const b2Vec2* vertices, int32 vertexCount, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ std::vector<short> x(vertexCount); std::vector<short> y(vertexCount); for(int i=0;i<vertexCount;i++){ b2Vec2 vec = toScreenCoords(vertices[i]); x[i] = (short) vec.x; y[i] = (short) vec.y; } if(filled){ filledPolygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); }else{ polygonRGBA(renderer, x.data(), y.data(), vertexCount, red, green, blue, alpha); } } void Renderer::dCircle(const b2Vec2& center, float32 radius, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){ b2Vec2 coords = toScreenCoords(center); if(filled){ filledCircleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); }else{ circleRGBA(renderer, (Sint16) coords.x, (Sint16) coords.y, (Sint16) metersToPixels(radius), red, green, blue, alpha); } } void Renderer::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { dPolygon(vertices, vertexCount, 0, 0, 0, 255, false); } void Renderer::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { dPolygon(vertices, vertexCount, 0, 0, 0, 255, true); } void Renderer::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) { dCircle(center, radius, 0, 0, 0, 255, false); } void Renderer::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) { dCircle(center, radius, 0, 0, 0, 255, true); } void Renderer::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) { b2Vec2 from = toScreenCoords(p1); b2Vec2 to = toScreenCoords(p2); lineRGBA(renderer, (Sint16) from.x, (Sint16) from.y, (Sint16) to.x, (Sint16) to.y, 0, 0, 0, 255); } void Renderer::DrawTransform(const b2Transform& xf) { } <|endoftext|>
<commit_before>//vbSort.cpp //Copyright (c) 2015 mmYYmmdd #include "stdafx.h" #include <algorithm> #include <OleAuto.h>//<OAIdl.h> #include "VBA_NestFunc.hpp" //”äŠrŠÖ” class compareByVBAfunc { VARIANT* begin; std::shared_ptr<functionExpr> comp; public: compareByVBAfunc(VARIANT* pA, VARIANT* f) : begin(pA) { VBCallbackFunc pf(f); if ( pf ) comp.reset(new functionExpr(pf)); } bool valid() const { return static_cast<bool>(comp); } bool operator ()(__int32 i, __int32 j) const { return comp->eval(begin + i, begin + j)->lVal ? true: false; } }; //1ŽŸŒ³¸‡ class compFunctor { VARIANT* begin; public: compFunctor(VARIANT* pA) : begin(pA) { } bool operator ()(__int32 i, __int32 j) const { return VARCMP_LT == VarCmp(begin + i, begin + j, LANG_JAPANESE, 0); } }; //2ŽŸŒ³¸‡ class compDictionaryFunctor { VARIANT* begin; void set(__int32 k, SAFEARRAY*& pArray, SAFEARRAYBOUND& bound) const { if ( 1 == Dimension(begin + k) ) { pArray = ( 0 == (VT_BYREF & begin[k].vt) )? (begin[k].parray): (*begin[k].pparray); safeArrayBounds(pArray, 1, &bound); } else { pArray = nullptr; } } public: compDictionaryFunctor(VARIANT* pA) : begin(pA) { } bool operator ()(__int32 i, __int32 j) const { SAFEARRAY* pArray1, *pArray2; SAFEARRAYBOUND bound1, bound2; set(i, pArray1, bound1); set(j, pArray2, bound2); if ( pArray1 == nullptr || pArray2 == nullptr ) return false; VARIANT Var1, Var2; for ( ULONG k = 0; k < bound1.cElements && k < bound2.cElements; ++k ) { auto index1 = static_cast<LONG>(k + bound1.lLbound); auto index2 = static_cast<LONG>(k + bound2.lLbound); ::SafeArrayGetElement(pArray1, &index1, &Var1); ::SafeArrayGetElement(pArray2, &index2, &Var2); if ( VARCMP_LT == VarCmp(&Var1, &Var2, LANG_JAPANESE, 0) ) return true; if ( VARCMP_LT == VarCmp(&Var2, &Var1, LANG_JAPANESE, 0) ) return false; } return false; } }; VARIANT __stdcall stdsort(VARIANT* array, __int32 defaultFlag, VARIANT* pComp) { VARIANT ret; ::VariantInit(&ret); if ( 1 != Dimension(array) ) return ret; SAFEARRAY* pArray = ( 0 == (VT_BYREF & array->vt) )? (array->parray): (*array->pparray); SAFEARRAYBOUND bound = {1, 0}; //—v‘f”ALBound safeArrayBounds(pArray, 1, &bound); std::unique_ptr<__int32[]> index(new __int32[bound.cElements]); std::unique_ptr<VARIANT[]> VArray(new VARIANT[bound.cElements]); for ( ULONG i = 0; i < bound.cElements; ++i ) { index[i] = static_cast<__int32>(i); auto j = static_cast<LONG>(i + bound.lLbound); ::SafeArrayGetElement(pArray, &j, &VArray[i]); } if ( defaultFlag == 1 ) //1ŽŸŒ³¸‡ { compFunctor functor(VArray.get()); std::sort(index.get(), index.get() + bound.cElements, functor); } else if ( defaultFlag == 2 ) //2ŽŸŒ³¸‡ { compDictionaryFunctor functor(VArray.get()); std::sort(index.get(), index.get() + bound.cElements, functor); } else if ( pComp ) { compareByVBAfunc functor(VArray.get(), pComp); if ( functor.valid() ) std::sort(index.get(), index.get() + bound.cElements, functor); } //------------------------------------------------------- SAFEARRAYBOUND boundRet = { bound.cElements, 0}; //—v‘f”ALBound SAFEARRAY* retArray = ::SafeArrayCreate(VT_VARIANT, 1, &boundRet); VARIANT elem; ::VariantInit(&elem); elem.vt = VT_I4; for ( LONG i = 0; i < static_cast<LONG>(bound.cElements); ++i ) { elem.lVal = index[i] + bound.lLbound; ::SafeArrayPutElement(retArray, &i, &elem); } ret.vt = VT_ARRAY | VT_VARIANT; ret.parray = retArray; return ret; } <commit_msg>VBA_NestFunc.hpp のリファクタリングに対応<commit_after>//vbSort.cpp //Copyright (c) 2015 mmYYmmdd #include "stdafx.h" #include <algorithm> #include <OleAuto.h>//<OAIdl.h> #include "VBA_NestFunc.hpp" //比較関数 class compareByVBAfunc { VARIANT* begin; std::shared_ptr<functionExpr> comp; public: compareByVBAfunc(VARIANT* pA, VARIANT* f) : begin(pA) { VBCallbackFunc pf(f); if ( pf ) comp.reset(new functionExpr(pf)); } bool valid() const { return static_cast<bool>(comp); } bool operator ()(__int32 i, __int32 j) const { return comp->eval(begin + i, begin + j)->lVal ? true: false; } }; //1次元昇順 class compFunctor { VARIANT* begin; public: compFunctor(VARIANT* pA) : begin(pA) { } bool operator ()(__int32 i, __int32 j) const { return VARCMP_LT == VarCmp(begin + i, begin + j, LANG_JAPANESE, 0); } }; //2次元昇順 class compDictionaryFunctor { VARIANT* begin; void set(__int32 k, SAFEARRAY*& pArray, SAFEARRAYBOUND& bound) const { if ( 1 == Dimension(begin + k) ) { pArray = ( 0 == (VT_BYREF & begin[k].vt) )? (begin[k].parray): (*begin[k].pparray); safeArrayBounds(pArray, 1, &bound); } else { pArray = nullptr; } } public: compDictionaryFunctor(VARIANT* pA) : begin(pA) { } bool operator ()(__int32 i, __int32 j) const { SAFEARRAY* pArray1, *pArray2; SAFEARRAYBOUND bound1, bound2; set(i, pArray1, bound1); set(j, pArray2, bound2); if ( pArray1 == nullptr || pArray2 == nullptr ) return false; VARIANT Var1, Var2; for ( ULONG k = 0; k < bound1.cElements && k < bound2.cElements; ++k ) { auto index1 = static_cast<LONG>(k + bound1.lLbound); auto index2 = static_cast<LONG>(k + bound2.lLbound); ::SafeArrayGetElement(pArray1, &index1, &Var1); ::SafeArrayGetElement(pArray2, &index2, &Var2); if ( VARCMP_LT == VarCmp(&Var1, &Var2, LANG_JAPANESE, 0) ) return true; if ( VARCMP_LT == VarCmp(&Var2, &Var1, LANG_JAPANESE, 0) ) return false; } return false; } }; VARIANT __stdcall stdsort(VARIANT* array, __int32 defaultFlag, VARIANT* pComp) { VARIANT ret; ::VariantInit(&ret); if ( 1 != Dimension(array) ) return ret; SAFEARRAY* pArray = ( 0 == (VT_BYREF & array->vt) )? (array->parray): (*array->pparray); SAFEARRAYBOUND bound = {1, 0}; //要素数、LBound safeArrayBounds(pArray, 1, &bound); std::unique_ptr<__int32[]> index(new __int32[bound.cElements]); std::unique_ptr<VARIANT[]> VArray(new VARIANT[bound.cElements]); for ( ULONG i = 0; i < bound.cElements; ++i ) { index[i] = static_cast<__int32>(i); auto j = static_cast<LONG>(i + bound.lLbound); ::SafeArrayGetElement(pArray, &j, &VArray[i]); } if ( defaultFlag == 1 ) //1次元昇順 { compFunctor functor(VArray.get()); std::sort(index.get(), index.get() + bound.cElements, functor); } else if ( defaultFlag == 2 ) //2次元昇順 { compDictionaryFunctor functor(VArray.get()); std::sort(index.get(), index.get() + bound.cElements, functor); } else if ( pComp ) { compareByVBAfunc functor(VArray.get(), pComp); if ( functor.valid() ) std::sort(index.get(), index.get() + bound.cElements, functor); } //------------------------------------------------------- SAFEARRAYBOUND boundRet = { bound.cElements, 0}; //要素数、LBound SAFEARRAY* retArray = ::SafeArrayCreate(VT_VARIANT, 1, &boundRet); VARIANT elem; ::VariantInit(&elem); elem.vt = VT_I4; for ( LONG i = 0; i < static_cast<LONG>(bound.cElements); ++i ) { elem.lVal = index[i] + bound.lLbound; ::SafeArrayPutElement(retArray, &i, &elem); } ret.vt = VT_ARRAY | VT_VARIANT; ret.parray = retArray; return ret; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <glog/logging.h> #include <gflags/gflags.h> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <sstream> #include <llvm/IR/Function.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <remill/Arch/Arch.h> #include <remill/BC/Util.h> #include <remill/BC/Version.h> #include "mcsema/Arch/Arch.h" #include "mcsema/BC/Lift.h" #include "mcsema/BC/Util.h" #ifndef LLVM_VERSION_STRING # define LLVM_VERSION_STRING LLVM_VERSION_MAJOR << "." << LLVM_VERSION_MINOR #endif #ifndef MCSEMA_VERSION_STRING # define MCSEMA_VERSION_STRING "unknown" #endif // MCSEMA_VERSION_STRING #ifndef MCSEMA_BRANCH_NAME # define MCSEMA_BRANCH_NAME "unknown" #endif // MCSEMA_BRANCH_NAME DECLARE_string(arch); DECLARE_string(os); DEFINE_string(cfg, "", "Path to the CFG file containing code to lift."); DEFINE_string(output, "", "Output bitcode file name."); DEFINE_string(library, "", "Path to an LLVM bitcode or IR file that contains " "external library definitions."); DECLARE_bool(version); DECLARE_bool(disable_optimizer); DECLARE_bool(keep_memops); DECLARE_bool(explicit_args); DECLARE_string(pc_annotation); DEFINE_bool(list_supported, false, "List instructions that can be lifted."); DEFINE_bool(legacy_mode, false, "Try to make the output bitcode resemble the original McSema."); namespace { static void PrintVersion(void) { std::cout << "This is mcsema-lift version: " << MCSEMA_VERSION_STRING << std::endl << "Built from branch: " << MCSEMA_BRANCH_NAME << std::endl << "Using LLVM " << LLVM_VERSION_STRING << std::endl; } // Print a list of instructions that Remill can lift. static void PrintSupportedInstructions(void) { remill::ForEachISel(mcsema::gModule, [=](llvm::GlobalVariable *isel, llvm::Function *) { std::cout << isel->getName().str() << std::endl; }); } // Load in a separate bitcode or IR library, and copy function and variable // declarations from that library into our module. We can use this feature // to provide better type information to McSema. static void LoadLibraryIntoModule(void) { std::unique_ptr<llvm::Module> lib( remill::LoadModuleFromFile(mcsema::gContext, FLAGS_library)); // Declare the functions from the library in McSema's target module. for (auto &func : *lib) { auto func_name = func.getName(); if (func_name.startswith("__mcsema") || func_name.startswith("__remill")) { continue; } if (mcsema::gModule->getFunction(func_name)) { continue; } auto dest_func = llvm::Function::Create( func.getFunctionType(), func.getLinkage(), func_name, mcsema::gModule); dest_func->copyAttributesFrom(&func); dest_func->setVisibility(func.getVisibility()); } // Declare the global variables from the library in McSema's target module. for (auto &var : lib->globals()) { auto var_name = var.getName(); if (var_name.startswith("__mcsema") || var_name.startswith("__remill")) { continue; } if (mcsema::gModule->getGlobalVariable(var_name)) { continue; } auto dest_var = new llvm::GlobalVariable( *mcsema::gModule, var.getType()->getElementType(), var.isConstant(), var.getLinkage(), nullptr, var_name, nullptr, var.getThreadLocalMode(), var.getType()->getAddressSpace()); dest_var->copyAttributesFrom(&var); } } } // namespace int main(int argc, char *argv[]) { std::stringstream ss; ss << std::endl << std::endl << " " << argv[0] << " \\" << std::endl << " --output OUTPUT_BC_FILE \\" << std::endl << " --arch ARCH_NAME \\" << std::endl << " --os OS_NAME \\" << std::endl << " --cfg CFG_FILE \\" << std::endl // This option is very useful for debugging McSema-lifted bitcode. It // injects so-called breakpoint functions before every lifted instruction. // For example, the the instruction at PC `0xf00` is lifted, then this // option will inject a call to `breakpoint_f00`. With this feature, we // can add breakpoints in a debugger on these breakpoint functions, and // know that they correspond to locations in the original program. << " [--add_breakpoints] \\" << std::endl // This option injects a function call before every lifted instruction. // This function is implemented in the McSema runtime and it prints the // values of the general purpose registers to `stderr`. << " [--add_reg_tracer] \\" << std::endl // This option tells McSema not to optimize the bitcode. This is useful // for debugging, especially in conjunction with `--add_breakpoints`. << " [--disable_optimizer] \\" << std::endl // This option tells McSema not to lower Remill's memory access intrinsic // functions into LLVM `load` and `store` instructions. << " [--keep_memops] \\" << std::endl // There are roughly two ways of using McSema-lifted bitcode. The default // use case is to compile the bitcode into an executable that behaves like // the original program. The other use case is to do some kind of static // analysis, e.g. with KLEE. In this use case, calls to external functions // are emulated so that we also try to explicitly lift parameter passing. // This mode of passing arguments explicitly is enabled by // `--explicit_args`, and in situations where we have no knowledge of the // argument counts expected by an external function, we fall back on // passing `--explicit_args_count` number of arguments to that function. << " [--explicit_args] \\" << std::endl << " [--explicit_args_count NUM_ARGS_FOR_EXTERNALS] \\" << std::endl // This option is most useful when using `--explicit_args` (or // `--legacy_mode`, which enables `--explicit_args`). In general, McSema // doesn't have type information about externals, and so it assumes all // externals operate on integer-typed arguments, and return integer values. // This is wrong in many ways, but tends to work out about 80% of the time. // To get McSema better information about externals, one should create a // C or C++ file with the declarations of the externals (perhaps by // `#include`ing standard headers). Then, should add to this file something // like: // __attribute__((used)) // void *__mcsema_used_funcs[] = { // (void *) external_func_name_1, // (void *) external_func_name_2, // ... // }; // And compile this file to bitcode using `remill-clang-M.m` (Major.minor). // This bitcode file will then be the source of type information for // McSema. << " [--library BITCODE_FILE] \\" << std::endl // Annotate each LLVM IR instruction with some metadata that includes the // original program counter. The name of the LLVM metadats is // `PC_METADATA_ID`. This is enabled by default with `--legacy_mode`, // which sets `--pc_annotation` to be `mcsema_real_eip`. << " [--pc_annotation PC_METADATA_ID] \\" << std::endl // Try to produce bitcode that looks like McSema version 1. This enables // `--explicit_args` and `--pc_annotation`. << " [--legacy_mode] \\" << std::endl // Print a list of the instructions that can be lifted. << " [--list-supported]" << std::endl // Print the version and exit. << " [--version]" << std::endl << std::endl; google::InitGoogleLogging(argv[0]); google::SetUsageMessage(ss.str()); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_version) { PrintVersion(); return EXIT_SUCCESS; } CHECK(!FLAGS_os.empty()) << "Must specify an operating system name to --os."; CHECK(!FLAGS_arch.empty()) << "Must specify a machine code architecture name to --arch."; CHECK(!FLAGS_cfg.empty()) << "Must specify the path to a CFG file to --cfg."; mcsema::gContext = new llvm::LLVMContext; CHECK(mcsema::InitArch(FLAGS_os, FLAGS_arch)) << "Cannot initialize for arch " << FLAGS_arch << " and OS " << FLAGS_os << std::endl; if (FLAGS_legacy_mode) { LOG_IF(WARNING, FLAGS_keep_memops) << "Disabling --keep_memops in legacy mode."; FLAGS_keep_memops = false; LOG_IF(WARNING, !FLAGS_explicit_args) << "Enabling --explicit_args in legacy mode."; FLAGS_explicit_args = true; LOG_IF(WARNING, !FLAGS_pc_annotation.empty()) << "Changing --pc_annotation to mcsema_real_eip in legacy mode."; FLAGS_pc_annotation = "mcsema_real_eip"; LOG_IF(WARNING, FLAGS_disable_optimizer) << "Re-enabling the optimizer in legacy mode."; FLAGS_disable_optimizer = false; } auto cfg_module = mcsema::ReadProtoBuf( FLAGS_cfg, (mcsema::gArch->address_size / 8)); mcsema::gModule = remill::LoadTargetSemantics(mcsema::gContext); mcsema::gArch->PrepareModule(mcsema::gModule); if (FLAGS_list_supported) { PrintSupportedInstructions(); } if (!FLAGS_library.empty()) { LoadLibraryIntoModule(); } CHECK(mcsema::LiftCodeIntoModule(cfg_module)) << "Unable to lift CFG from " << FLAGS_cfg << " into module " << FLAGS_output; remill::StoreModuleToFile(mcsema::gModule, FLAGS_output); google::ShutDownCommandLineFlags(); google::ShutdownGoogleLogging(); return EXIT_SUCCESS; } <commit_msg>Fixes an issue where we assume that every symbol in the module passed to --library is external, whereas that's false. (#368)<commit_after>/* * Copyright (c) 2017 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <glog/logging.h> #include <gflags/gflags.h> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <sstream> #include <llvm/IR/Function.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <remill/Arch/Arch.h> #include <remill/BC/Util.h> #include <remill/BC/Version.h> #include "mcsema/Arch/Arch.h" #include "mcsema/BC/Lift.h" #include "mcsema/BC/Util.h" #ifndef LLVM_VERSION_STRING # define LLVM_VERSION_STRING LLVM_VERSION_MAJOR << "." << LLVM_VERSION_MINOR #endif #ifndef MCSEMA_VERSION_STRING # define MCSEMA_VERSION_STRING "unknown" #endif // MCSEMA_VERSION_STRING #ifndef MCSEMA_BRANCH_NAME # define MCSEMA_BRANCH_NAME "unknown" #endif // MCSEMA_BRANCH_NAME DECLARE_string(arch); DECLARE_string(os); DEFINE_string(cfg, "", "Path to the CFG file containing code to lift."); DEFINE_string(output, "", "Output bitcode file name."); DEFINE_string(library, "", "Path to an LLVM bitcode or IR file that contains " "external library definitions."); DECLARE_bool(version); DECLARE_bool(disable_optimizer); DECLARE_bool(keep_memops); DECLARE_bool(explicit_args); DECLARE_string(pc_annotation); DEFINE_bool(list_supported, false, "List instructions that can be lifted."); DEFINE_bool(legacy_mode, false, "Try to make the output bitcode resemble the original McSema."); namespace { static void PrintVersion(void) { std::cout << "This is mcsema-lift version: " << MCSEMA_VERSION_STRING << std::endl << "Built from branch: " << MCSEMA_BRANCH_NAME << std::endl << "Using LLVM " << LLVM_VERSION_STRING << std::endl; } // Print a list of instructions that Remill can lift. static void PrintSupportedInstructions(void) { remill::ForEachISel(mcsema::gModule, [=](llvm::GlobalVariable *isel, llvm::Function *) { std::cout << isel->getName().str() << std::endl; }); } // Load in a separate bitcode or IR library, and copy function and variable // declarations from that library into our module. We can use this feature // to provide better type information to McSema. static void LoadLibraryIntoModule(void) { std::unique_ptr<llvm::Module> lib( remill::LoadModuleFromFile(mcsema::gContext, FLAGS_library)); // Declare the functions from the library in McSema's target module. for (auto &func : *lib) { auto func_name = func.getName(); if (func_name.startswith("__mcsema") || func_name.startswith("__remill")) { continue; } if (!func.hasExternalLinkage()) { continue; } if (mcsema::gModule->getFunction(func_name)) { continue; } auto dest_func = llvm::Function::Create( func.getFunctionType(), func.getLinkage(), func_name, mcsema::gModule); dest_func->copyAttributesFrom(&func); dest_func->setVisibility(func.getVisibility()); } // Declare the global variables from the library in McSema's target module. for (auto &var : lib->globals()) { auto var_name = var.getName(); if (var_name.startswith("__mcsema") || var_name.startswith("__remill")) { continue; } if (!var.hasExternalLinkage()) { continue; } if (mcsema::gModule->getGlobalVariable(var_name)) { continue; } auto dest_var = new llvm::GlobalVariable( *mcsema::gModule, var.getType()->getElementType(), var.isConstant(), var.getLinkage(), nullptr, var_name, nullptr, var.getThreadLocalMode(), var.getType()->getAddressSpace()); dest_var->copyAttributesFrom(&var); } } } // namespace int main(int argc, char *argv[]) { std::stringstream ss; ss << std::endl << std::endl << " " << argv[0] << " \\" << std::endl << " --output OUTPUT_BC_FILE \\" << std::endl << " --arch ARCH_NAME \\" << std::endl << " --os OS_NAME \\" << std::endl << " --cfg CFG_FILE \\" << std::endl // This option is very useful for debugging McSema-lifted bitcode. It // injects so-called breakpoint functions before every lifted instruction. // For example, the the instruction at PC `0xf00` is lifted, then this // option will inject a call to `breakpoint_f00`. With this feature, we // can add breakpoints in a debugger on these breakpoint functions, and // know that they correspond to locations in the original program. << " [--add_breakpoints] \\" << std::endl // This option injects a function call before every lifted instruction. // This function is implemented in the McSema runtime and it prints the // values of the general purpose registers to `stderr`. << " [--add_reg_tracer] \\" << std::endl // This option tells McSema not to optimize the bitcode. This is useful // for debugging, especially in conjunction with `--add_breakpoints`. << " [--disable_optimizer] \\" << std::endl // This option tells McSema not to lower Remill's memory access intrinsic // functions into LLVM `load` and `store` instructions. << " [--keep_memops] \\" << std::endl // There are roughly two ways of using McSema-lifted bitcode. The default // use case is to compile the bitcode into an executable that behaves like // the original program. The other use case is to do some kind of static // analysis, e.g. with KLEE. In this use case, calls to external functions // are emulated so that we also try to explicitly lift parameter passing. // This mode of passing arguments explicitly is enabled by // `--explicit_args`, and in situations where we have no knowledge of the // argument counts expected by an external function, we fall back on // passing `--explicit_args_count` number of arguments to that function. << " [--explicit_args] \\" << std::endl << " [--explicit_args_count NUM_ARGS_FOR_EXTERNALS] \\" << std::endl // This option is most useful when using `--explicit_args` (or // `--legacy_mode`, which enables `--explicit_args`). In general, McSema // doesn't have type information about externals, and so it assumes all // externals operate on integer-typed arguments, and return integer values. // This is wrong in many ways, but tends to work out about 80% of the time. // To get McSema better information about externals, one should create a // C or C++ file with the declarations of the externals (perhaps by // `#include`ing standard headers). Then, should add to this file something // like: // __attribute__((used)) // void *__mcsema_used_funcs[] = { // (void *) external_func_name_1, // (void *) external_func_name_2, // ... // }; // And compile this file to bitcode using `remill-clang-M.m` (Major.minor). // This bitcode file will then be the source of type information for // McSema. << " [--library BITCODE_FILE] \\" << std::endl // Annotate each LLVM IR instruction with some metadata that includes the // original program counter. The name of the LLVM metadats is // `PC_METADATA_ID`. This is enabled by default with `--legacy_mode`, // which sets `--pc_annotation` to be `mcsema_real_eip`. << " [--pc_annotation PC_METADATA_ID] \\" << std::endl // Try to produce bitcode that looks like McSema version 1. This enables // `--explicit_args` and `--pc_annotation`. << " [--legacy_mode] \\" << std::endl // Print a list of the instructions that can be lifted. << " [--list-supported]" << std::endl // Print the version and exit. << " [--version]" << std::endl << std::endl; google::InitGoogleLogging(argv[0]); google::SetUsageMessage(ss.str()); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_version) { PrintVersion(); return EXIT_SUCCESS; } CHECK(!FLAGS_os.empty()) << "Must specify an operating system name to --os."; CHECK(!FLAGS_arch.empty()) << "Must specify a machine code architecture name to --arch."; CHECK(!FLAGS_cfg.empty()) << "Must specify the path to a CFG file to --cfg."; mcsema::gContext = new llvm::LLVMContext; CHECK(mcsema::InitArch(FLAGS_os, FLAGS_arch)) << "Cannot initialize for arch " << FLAGS_arch << " and OS " << FLAGS_os << std::endl; if (FLAGS_legacy_mode) { LOG_IF(WARNING, FLAGS_keep_memops) << "Disabling --keep_memops in legacy mode."; FLAGS_keep_memops = false; LOG_IF(WARNING, !FLAGS_explicit_args) << "Enabling --explicit_args in legacy mode."; FLAGS_explicit_args = true; LOG_IF(WARNING, !FLAGS_pc_annotation.empty()) << "Changing --pc_annotation to mcsema_real_eip in legacy mode."; FLAGS_pc_annotation = "mcsema_real_eip"; LOG_IF(WARNING, FLAGS_disable_optimizer) << "Re-enabling the optimizer in legacy mode."; FLAGS_disable_optimizer = false; } auto cfg_module = mcsema::ReadProtoBuf( FLAGS_cfg, (mcsema::gArch->address_size / 8)); mcsema::gModule = remill::LoadTargetSemantics(mcsema::gContext); mcsema::gArch->PrepareModule(mcsema::gModule); if (FLAGS_list_supported) { PrintSupportedInstructions(); } if (!FLAGS_library.empty()) { LoadLibraryIntoModule(); } CHECK(mcsema::LiftCodeIntoModule(cfg_module)) << "Unable to lift CFG from " << FLAGS_cfg << " into module " << FLAGS_output; remill::StoreModuleToFile(mcsema::gModule, FLAGS_output); google::ShutDownCommandLineFlags(); google::ShutdownGoogleLogging(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright 2016 Rodrigo Jose Hernandez Cordoba 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 <iostream> #include <QMessageBox> #include "MainWindow.h" #include "ModelViewer.h" #include "aeongames/AeonEngine.h" int ENTRYPOINT main ( int argc, char *argv[] ) { #ifdef _MSC_VER /* Call _CrtDumpMemoryLeaks on exit, required because Qt does a lot of static allocations, which are detected as false positives. http://msdn.microsoft.com/en-us/library/5at7yxcs%28v=vs.71%29.aspx */ _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // Use _CrtSetBreakAlloc( ) to set breakpoints on allocations. #endif if ( !AeonGames::Initialize() ) { return -1; } int retval = 0; AeonGames::ModelViewer application ( argc, argv ); application.setWindowIcon ( QIcon ( ":/icons/magnifying_glass" ) ); application.setOrganizationName ( "AeonGames" ); application.setOrganizationDomain ( "aeongames.com" ); application.setApplicationName ( "AeonGames Model Viewer" ); AeonGames::MainWindow* mainWindow; mainWindow = new AeonGames::MainWindow(); mainWindow->showNormal(); retval = application.exec(); delete mainWindow; AeonGames::Finalize(); return retval; } <commit_msg>Catch runtime exceptions in model viewer.<commit_after>/* Copyright 2016 Rodrigo Jose Hernandez Cordoba 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 <iostream> #include <QMessageBox> #include "MainWindow.h" #include "ModelViewer.h" #include "aeongames/AeonEngine.h" int ENTRYPOINT main ( int argc, char *argv[] ) { #ifdef _MSC_VER /* Call _CrtDumpMemoryLeaks on exit, required because Qt does a lot of static allocations, which are detected as false positives. http://msdn.microsoft.com/en-us/library/5at7yxcs%28v=vs.71%29.aspx */ _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // Use _CrtSetBreakAlloc( ) to set breakpoints on allocations. #endif if ( !AeonGames::Initialize() ) { return -1; } int retval = 0; AeonGames::ModelViewer application ( argc, argv ); application.setWindowIcon ( QIcon ( ":/icons/magnifying_glass" ) ); application.setOrganizationName ( "AeonGames" ); application.setOrganizationDomain ( "aeongames.com" ); application.setApplicationName ( "AeonGames Model Viewer" ); AeonGames::MainWindow* mainWindow; try { mainWindow = new AeonGames::MainWindow(); } catch ( std::runtime_error& e ) { std::cout << e.what() << std::endl; throw; } mainWindow->showNormal(); retval = application.exec(); delete mainWindow; AeonGames::Finalize(); return retval; } <|endoftext|>
<commit_before>#include "web_output.h" #include <iomanip> #include <iostream> #include <sstream> #include <string> using namespace std; void Web_Output::add_encoding_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"encoding error: "<<error; display_error(out.str()); } encoding_errors = true; } void Web_Output::add_parse_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": parse error: "<<error; display_error(out.str()); } parse_errors = true; } void Web_Output::add_static_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": static error: "<<error; display_error(out.str()); } static_errors = true; } void Web_Output::add_encoding_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"encoding remark: "<<error; display_remark(out.str()); } } void Web_Output::add_parse_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": parse remark: "<<error; display_remark(out.str()); } } void Web_Output::add_static_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": static remark: "<<error; display_remark(out.str()); } } void Web_Output::runtime_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"runtime error: "<<error; display_error(out.str()); } } void Web_Output::runtime_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"runtime remark: "<<error; display_remark(out.str()); } } void Web_Output::display_statement_stopwatch (const string& name, const vector< double >& stopwatches, const vector< uint >& read_counts) { if (log_level != Error_Output::VERBOSE) return; ostringstream out; out<<"Stopwatch "<<name; vector< uint >::const_iterator rit(read_counts.begin()); for (vector< double >::const_iterator it(stopwatches.begin()); it != stopwatches.end(); ++it) { out<<setprecision(3)<<fixed<<'\t'<<*it<<' '<<*rit; ++rit; } display_remark(out.str()); } void Web_Output::enforce_header() { if (header_written == not_yet) write_html_header(); } void Web_Output::write_html_header (const string& timestamp, const string& area_timestamp) { if (header_written != not_yet) return; header_written = html; cout<< "Content-Type: text/html; charset=utf-8\n\n"; cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">" "<head>\n" " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n" " <title>OSM3S Response</title>\n" "</head>\n" "<body>\n\n" "<p>The data included in this document is from www.openstreetmap.org. " "It has there been collected by a large group of contributors. For individual " "attribution of each item please refer to " "http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history </p>\n"; if (timestamp != "") { cout<<"<p>Data included until: "<<timestamp; if (area_timestamp != "") cout<<"<br/>Areas based on data until: "<<area_timestamp; cout<<"</p>\n"; } } void Web_Output::write_xml_header (const string& timestamp, const string& area_timestamp) { if (header_written != not_yet) return; header_written = xml; cout<< "Content-type: application/osm3s\n\n"; cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<osm version=\"0.6\" generator=\"Overpass API\">\n" "<note>The data included in this document is from www.openstreetmap.org. " "It has there been collected by a large group of contributors. For individual " "attribution of each item please refer to " "http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history </note>\n"; cout<<"<meta osm_base=\""<<timestamp<<'\"'; if (area_timestamp != "") cout<<" areas=\""<<area_timestamp<<"\""; cout<<"/>\n\n"; } void Web_Output::write_footer() { if (header_written == xml) cout<<"\n</osm>\n"; else if (header_written == html) cout<<"\n</body>\n</html>\n"; header_written = final; } void Web_Output::display_remark(const string& text) { enforce_header(); if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#00BB00\">Remark</strong>: " <<text<<" </p>\n"; } void Web_Output::display_error(const string& text) { enforce_header(); if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#FF0000\">Error</strong>: " <<text<<" </p>\n"; } <commit_msg>Changed MIME type.<commit_after>#include "web_output.h" #include <iomanip> #include <iostream> #include <sstream> #include <string> using namespace std; void Web_Output::add_encoding_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"encoding error: "<<error; display_error(out.str()); } encoding_errors = true; } void Web_Output::add_parse_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": parse error: "<<error; display_error(out.str()); } parse_errors = true; } void Web_Output::add_static_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": static error: "<<error; display_error(out.str()); } static_errors = true; } void Web_Output::add_encoding_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"encoding remark: "<<error; display_remark(out.str()); } } void Web_Output::add_parse_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": parse remark: "<<error; display_remark(out.str()); } } void Web_Output::add_static_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": static remark: "<<error; display_remark(out.str()); } } void Web_Output::runtime_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"runtime error: "<<error; display_error(out.str()); } } void Web_Output::runtime_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"runtime remark: "<<error; display_remark(out.str()); } } void Web_Output::display_statement_stopwatch (const string& name, const vector< double >& stopwatches, const vector< uint >& read_counts) { if (log_level != Error_Output::VERBOSE) return; ostringstream out; out<<"Stopwatch "<<name; vector< uint >::const_iterator rit(read_counts.begin()); for (vector< double >::const_iterator it(stopwatches.begin()); it != stopwatches.end(); ++it) { out<<setprecision(3)<<fixed<<'\t'<<*it<<' '<<*rit; ++rit; } display_remark(out.str()); } void Web_Output::enforce_header() { if (header_written == not_yet) write_html_header(); } void Web_Output::write_html_header (const string& timestamp, const string& area_timestamp) { if (header_written != not_yet) return; header_written = html; cout<< "Content-Type: text/html; charset=utf-8\n\n"; cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">" "<head>\n" " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n" " <title>OSM3S Response</title>\n" "</head>\n" "<body>\n\n" "<p>The data included in this document is from www.openstreetmap.org. " "It has there been collected by a large group of contributors. For individual " "attribution of each item please refer to " "http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history </p>\n"; if (timestamp != "") { cout<<"<p>Data included until: "<<timestamp; if (area_timestamp != "") cout<<"<br/>Areas based on data until: "<<area_timestamp; cout<<"</p>\n"; } } void Web_Output::write_xml_header (const string& timestamp, const string& area_timestamp) { if (header_written != not_yet) return; header_written = xml; cout<< "Content-type: application/osm3s+xml\n\n"; cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<osm version=\"0.6\" generator=\"Overpass API\">\n" "<note>The data included in this document is from www.openstreetmap.org. " "It has there been collected by a large group of contributors. For individual " "attribution of each item please refer to " "http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history </note>\n"; cout<<"<meta osm_base=\""<<timestamp<<'\"'; if (area_timestamp != "") cout<<" areas=\""<<area_timestamp<<"\""; cout<<"/>\n\n"; } void Web_Output::write_footer() { if (header_written == xml) cout<<"\n</osm>\n"; else if (header_written == html) cout<<"\n</body>\n</html>\n"; header_written = final; } void Web_Output::display_remark(const string& text) { enforce_header(); if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#00BB00\">Remark</strong>: " <<text<<" </p>\n"; } void Web_Output::display_error(const string& text) { enforce_header(); if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#FF0000\">Error</strong>: " <<text<<" </p>\n"; } <|endoftext|>
<commit_before>/* * main.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <mparisdiaz@gmail.com> * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <execinfo.h> #include "MediaServerServiceHandler.hpp" #include <protocol/TBinaryProtocol.h> #include <transport/TServerSocket.h> #include <transport/TBufferTransports.h> #include <server/TNonblockingServer.h> #include <concurrency/PosixThreadFactory.h> #include <concurrency/ThreadManager.h> #include "media_config_loader.hpp" #include <glibmm.h> #include <fstream> #include <gst/gst.h> #include <version.hpp> #include "log.hpp" #define GST_DEFAULT_NAME "media_server" GST_DEBUG_CATEGORY (GST_CAT_DEFAULT); using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::transport; using namespace ::apache::thrift::server; using namespace ::apache::thrift::concurrency; using namespace ::kurento; using boost::shared_ptr; using ::kurento::MediaServerServiceHandler; using ::Glib::KeyFile; using ::Glib::KeyFileFlags; #define DEFAULT_CONFIG_FILE "/etc/kurento/kurento.conf" #define MEDIA_SERVER_ADDRESS_KEY "serverAddress" #define MEDIA_SERVER_SERVICE_PORT_KEY "serverPort" static std::string serverAddress; static gint serverServicePort; static GstSDPMessage *sdp_message; static KeyFile configFile; Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (true); static TNonblockingServer *p_server = NULL; static gchar *conf_file; static GOptionEntry entries[] = { { "conf-file", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, "Configuration file", NULL }, {NULL} }; static void create_media_server_service () { int port; port = MEDIA_SERVER_SERVICE_PORT; shared_ptr < MediaServerServiceHandler > handler (new MediaServerServiceHandler () ); shared_ptr < TProcessor > processor (new MediaServerServiceProcessor (handler) ); shared_ptr < TProtocolFactory > protocolFactory (new TBinaryProtocolFactory () ); shared_ptr < PosixThreadFactory > threadFactory (new PosixThreadFactory () ); shared_ptr < ThreadManager > threadManager = ThreadManager::newSimpleThreadManager (15); threadManager->threadFactory (threadFactory); threadManager->start (); TNonblockingServer server (processor, protocolFactory, port, threadManager); p_server = &server; GST_INFO ("Starting MediaServerService"); kill (getppid(), SIGCONT); server.serve (); GST_INFO ("MediaServerService stopped finishing thread"); throw Glib::Thread::Exit (); } static void check_port (int port) { if (port <= 0 || port > G_MAXUSHORT) throw Glib::KeyFileError (Glib::KeyFileError::PARSE, "Invalid value"); } static void set_default_server_config () { serverAddress = MEDIA_SERVER_ADDRESS; serverServicePort = MEDIA_SERVER_SERVICE_PORT; } static void load_config (const std::string &file_name) { gint port; GST_INFO ("Reading configuration from: %s", file_name.c_str () ); /* Try to open de file */ { std::ifstream file (file_name); if (!file) { GST_INFO ("Config file not found, creating a new one"); std::ofstream of (file_name); } } try { if (!configFile.load_from_file (file_name, KeyFileFlags::KEY_FILE_KEEP_COMMENTS | KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS) ) { GST_WARNING ("Error loading configuration from %s, loading " "default server config, but no " "codecs will be available", file_name.c_str () ); set_default_server_config (); return; } } catch (Glib::Error ex) { GST_WARNING ("Error loading configuration: %s", ex.what ().c_str () ); GST_WARNING ("Error loading configuration from %s, loading " "default server config, but no " "codecs will be available", file_name.c_str () ); set_default_server_config (); return; } try { serverAddress = configFile.get_string (SERVER_GROUP, MEDIA_SERVER_ADDRESS_KEY); } catch (Glib::KeyFileError err) { GST_INFO (err.what ().c_str () ); GST_INFO ("Setting default address"); configFile.set_string (SERVER_GROUP, MEDIA_SERVER_ADDRESS_KEY, MEDIA_SERVER_ADDRESS); serverAddress = MEDIA_SERVER_ADDRESS; } try { port = configFile.get_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY); check_port (port); serverServicePort = port; } catch (Glib::KeyFileError err) { GST_INFO (err.what ().c_str () ); GST_INFO ("Setting default server port"); configFile.set_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY, MEDIA_SERVER_SERVICE_PORT); serverServicePort = MEDIA_SERVER_SERVICE_PORT; } try { sdp_message = load_session_descriptor (configFile); } catch (Glib::KeyFileError err) { GST_WARNING (err.what ().c_str () ); GST_WARNING ("Wrong codec configuration, communication won't be possible"); } std::ofstream f (file_name, std::ios::out | std::ios::trunc); f << configFile.to_data (); f.close (); GST_INFO ("Configuration loaded successfully"); GST_DEBUG ("Final config file:\n%s", configFile.to_data ().c_str () ); } static void initialiseExecutableName (char *exe, int size) { char link[1024]; int len; snprintf (link, sizeof (link), "/proc/%d/exe", getpid () ); len = readlink (link, exe, size); if (len == -1) { fprintf (stderr, "ERROR GETTING NAME\n"); exit (1); } exe[len] = '\0'; } static const char * getExecutableName () { static char *exe = NULL; static char aux[1024]; if (exe == NULL) { initialiseExecutableName (aux, sizeof (aux) ); exe = aux; } return exe; } static bool quit_loop () { loop->quit (); return FALSE; } static void bt_sighandler (int sig, siginfo_t *info, gpointer data) { void *trace[35]; char **messages = (char **) NULL; int i, trace_size = 0; // ucontext_t *uc = (ucontext_t *)data; /* Do something useful with siginfo_t */ if (sig == SIGSEGV) { printf ("Got signal %d, faulty address is %p\n", sig, (gpointer) info->si_addr); } else if (sig == SIGKILL || sig == SIGINT) { /* since we connect to a signal handler, asynchronous management might */ /* might happen so we need to set an idle handler to exit the main loop */ /* in the mainloop context. */ Glib::RefPtr<Glib::IdleSource> idle_source = Glib::IdleSource::create (); idle_source->connect (sigc::ptr_fun (&quit_loop) ); idle_source->attach (loop->get_context() ); return; } else { printf ("Got signal %d\n", sig); } trace_size = backtrace (trace, 35); /* overwrite sigaction with caller's address */ //trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP]; messages = backtrace_symbols (trace, trace_size); /* skip first stack frame (points here) */ g_print ("\t[bt] Execution path:\n"); for (i = 1; i < trace_size; ++i) { g_print ("\t[bt] #%d %s\n", i, messages[i]); char syscom[256]; gchar **strs; const gchar *exe; strs = g_strsplit (messages[i], "(", 2); if (strs[1] == NULL) exe = getExecutableName (); else exe = strs[0]; sprintf (syscom, "echo -n \"\t[bt]\t\t\"; addr2line %p -s -e %s", trace[i], exe); g_strfreev (strs); system (syscom); } if (sig == SIGPIPE) { GST_DEBUG ("Ignore sigpipe"); } else { exit (sig); } } int main (int argc, char **argv) { GError *error = NULL; GOptionContext *context; struct sigaction sa; context = g_option_context_new (""); g_option_context_add_main_entries (context, entries, NULL); g_option_context_add_group (context, gst_init_get_option_group () ); if (!g_option_context_parse (context, &argc, &argv, &error) ) { GST_ERROR ("option parsing failed: %s\n", error->message); exit (1); } g_option_context_free (context); gst_init (&argc, &argv); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); /* Install our signal handler */ sa.sa_sigaction = /*(void (*)(int, siginfo*, gpointer)) */ bt_sighandler; sigemptyset (&sa.sa_mask); sa.sa_flags = SA_RESTART | SA_SIGINFO; sigaction (SIGSEGV, &sa, NULL); sigaction (SIGPIPE, &sa, NULL); sigaction (SIGINT, &sa, NULL); sigaction (SIGKILL, &sa, NULL); Glib::thread_init (); GST_INFO ("Kmsc version: %s", get_version () ); if (!conf_file) load_config (DEFAULT_CONFIG_FILE); else load_config ( (std::string) conf_file); sigc::slot < void >ss = sigc::ptr_fun (&create_media_server_service); Glib::Thread::create (ss, true); /* Created thread not used to join because of a bug in thrift */ loop->run (); return 0; } <commit_msg>Add format when GST log is used<commit_after>/* * main.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <mparisdiaz@gmail.com> * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <execinfo.h> #include "MediaServerServiceHandler.hpp" #include <protocol/TBinaryProtocol.h> #include <transport/TServerSocket.h> #include <transport/TBufferTransports.h> #include <server/TNonblockingServer.h> #include <concurrency/PosixThreadFactory.h> #include <concurrency/ThreadManager.h> #include "media_config_loader.hpp" #include <glibmm.h> #include <fstream> #include <gst/gst.h> #include <version.hpp> #include "log.hpp" #define GST_DEFAULT_NAME "media_server" GST_DEBUG_CATEGORY (GST_CAT_DEFAULT); using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::transport; using namespace ::apache::thrift::server; using namespace ::apache::thrift::concurrency; using namespace ::kurento; using boost::shared_ptr; using ::kurento::MediaServerServiceHandler; using ::Glib::KeyFile; using ::Glib::KeyFileFlags; #define DEFAULT_CONFIG_FILE "/etc/kurento/kurento.conf" #define MEDIA_SERVER_ADDRESS_KEY "serverAddress" #define MEDIA_SERVER_SERVICE_PORT_KEY "serverPort" static std::string serverAddress; static gint serverServicePort; static GstSDPMessage *sdp_message; static KeyFile configFile; Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (true); static TNonblockingServer *p_server = NULL; static gchar *conf_file; static GOptionEntry entries[] = { { "conf-file", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, "Configuration file", NULL }, {NULL} }; static void create_media_server_service () { int port; port = MEDIA_SERVER_SERVICE_PORT; shared_ptr < MediaServerServiceHandler > handler (new MediaServerServiceHandler () ); shared_ptr < TProcessor > processor (new MediaServerServiceProcessor (handler) ); shared_ptr < TProtocolFactory > protocolFactory (new TBinaryProtocolFactory () ); shared_ptr < PosixThreadFactory > threadFactory (new PosixThreadFactory () ); shared_ptr < ThreadManager > threadManager = ThreadManager::newSimpleThreadManager (15); threadManager->threadFactory (threadFactory); threadManager->start (); TNonblockingServer server (processor, protocolFactory, port, threadManager); p_server = &server; GST_INFO ("Starting MediaServerService"); kill (getppid(), SIGCONT); server.serve (); GST_INFO ("MediaServerService stopped finishing thread"); throw Glib::Thread::Exit (); } static void check_port (int port) { if (port <= 0 || port > G_MAXUSHORT) throw Glib::KeyFileError (Glib::KeyFileError::PARSE, "Invalid value"); } static void set_default_server_config () { serverAddress = MEDIA_SERVER_ADDRESS; serverServicePort = MEDIA_SERVER_SERVICE_PORT; } static void load_config (const std::string &file_name) { gint port; GST_INFO ("Reading configuration from: %s", file_name.c_str () ); /* Try to open de file */ { std::ifstream file (file_name); if (!file) { GST_INFO ("Config file not found, creating a new one"); std::ofstream of (file_name); } } try { if (!configFile.load_from_file (file_name, KeyFileFlags::KEY_FILE_KEEP_COMMENTS | KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS) ) { GST_WARNING ("Error loading configuration from %s, loading " "default server config, but no " "codecs will be available", file_name.c_str () ); set_default_server_config (); return; } } catch (Glib::Error ex) { GST_WARNING ("Error loading configuration: %s", ex.what ().c_str () ); GST_WARNING ("Error loading configuration from %s, loading " "default server config, but no " "codecs will be available", file_name.c_str () ); set_default_server_config (); return; } try { serverAddress = configFile.get_string (SERVER_GROUP, MEDIA_SERVER_ADDRESS_KEY); } catch (Glib::KeyFileError err) { GST_INFO ("%s", err.what ().c_str () ); GST_INFO ("Setting default address"); configFile.set_string (SERVER_GROUP, MEDIA_SERVER_ADDRESS_KEY, MEDIA_SERVER_ADDRESS); serverAddress = MEDIA_SERVER_ADDRESS; } try { port = configFile.get_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY); check_port (port); serverServicePort = port; } catch (Glib::KeyFileError err) { GST_INFO ("%s", err.what ().c_str () ); GST_INFO ("Setting default server port"); configFile.set_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY, MEDIA_SERVER_SERVICE_PORT); serverServicePort = MEDIA_SERVER_SERVICE_PORT; } try { sdp_message = load_session_descriptor (configFile); } catch (Glib::KeyFileError err) { GST_WARNING ("%s", err.what ().c_str () ); GST_WARNING ("Wrong codec configuration, communication won't be possible"); } std::ofstream f (file_name, std::ios::out | std::ios::trunc); f << configFile.to_data (); f.close (); GST_INFO ("Configuration loaded successfully"); GST_DEBUG ("Final config file:\n%s", configFile.to_data ().c_str () ); } static void initialiseExecutableName (char *exe, int size) { char link[1024]; int len; snprintf (link, sizeof (link), "/proc/%d/exe", getpid () ); len = readlink (link, exe, size); if (len == -1) { fprintf (stderr, "ERROR GETTING NAME\n"); exit (1); } exe[len] = '\0'; } static const char * getExecutableName () { static char *exe = NULL; static char aux[1024]; if (exe == NULL) { initialiseExecutableName (aux, sizeof (aux) ); exe = aux; } return exe; } static bool quit_loop () { loop->quit (); return FALSE; } static void bt_sighandler (int sig, siginfo_t *info, gpointer data) { void *trace[35]; char **messages = (char **) NULL; int i, trace_size = 0; // ucontext_t *uc = (ucontext_t *)data; /* Do something useful with siginfo_t */ if (sig == SIGSEGV) { printf ("Got signal %d, faulty address is %p\n", sig, (gpointer) info->si_addr); } else if (sig == SIGKILL || sig == SIGINT) { /* since we connect to a signal handler, asynchronous management might */ /* might happen so we need to set an idle handler to exit the main loop */ /* in the mainloop context. */ Glib::RefPtr<Glib::IdleSource> idle_source = Glib::IdleSource::create (); idle_source->connect (sigc::ptr_fun (&quit_loop) ); idle_source->attach (loop->get_context() ); return; } else { printf ("Got signal %d\n", sig); } trace_size = backtrace (trace, 35); /* overwrite sigaction with caller's address */ //trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP]; messages = backtrace_symbols (trace, trace_size); /* skip first stack frame (points here) */ g_print ("\t[bt] Execution path:\n"); for (i = 1; i < trace_size; ++i) { g_print ("\t[bt] #%d %s\n", i, messages[i]); char syscom[256]; gchar **strs; const gchar *exe; strs = g_strsplit (messages[i], "(", 2); if (strs[1] == NULL) exe = getExecutableName (); else exe = strs[0]; sprintf (syscom, "echo -n \"\t[bt]\t\t\"; addr2line %p -s -e %s", trace[i], exe); g_strfreev (strs); system (syscom); } if (sig == SIGPIPE) { GST_DEBUG ("Ignore sigpipe"); } else { exit (sig); } } int main (int argc, char **argv) { GError *error = NULL; GOptionContext *context; struct sigaction sa; context = g_option_context_new (""); g_option_context_add_main_entries (context, entries, NULL); g_option_context_add_group (context, gst_init_get_option_group () ); if (!g_option_context_parse (context, &argc, &argv, &error) ) { GST_ERROR ("option parsing failed: %s\n", error->message); exit (1); } g_option_context_free (context); gst_init (&argc, &argv); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); /* Install our signal handler */ sa.sa_sigaction = /*(void (*)(int, siginfo*, gpointer)) */ bt_sighandler; sigemptyset (&sa.sa_mask); sa.sa_flags = SA_RESTART | SA_SIGINFO; sigaction (SIGSEGV, &sa, NULL); sigaction (SIGPIPE, &sa, NULL); sigaction (SIGINT, &sa, NULL); sigaction (SIGKILL, &sa, NULL); Glib::thread_init (); GST_INFO ("Kmsc version: %s", get_version () ); if (!conf_file) load_config (DEFAULT_CONFIG_FILE); else load_config ( (std::string) conf_file); sigc::slot < void >ss = sigc::ptr_fun (&create_media_server_service); Glib::Thread::create (ss, true); /* Created thread not used to join because of a bug in thrift */ loop->run (); return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cassert> #include <sstream> #include "genome.h" #include "gtf.h" #include "config.h" #include "assembler.h" #include "scallop3.h" #include "sgraph_compare.h" #include "super_graph.h" assembler::assembler() { sfn = sam_open(input_file.c_str(), "r"); hdr = sam_hdr_read(sfn); b1t = bam_init1(); terminate = false; index = -1; qlen = 0; } assembler::~assembler() { bam_destroy1(b1t); bam_hdr_destroy(hdr); sam_close(sfn); } int assembler::assemble() { while(sam_read1(sfn, hdr, b1t) >= 0) { if(terminate == true) return 0; bam1_core_t &p = b1t->core; if((p.flag & 0x4) >= 1) continue; // read is not mapped if((p.flag & 0x100) >= 1) continue; // secondary alignment if(p.n_cigar < 1) continue; // should never happen if(p.n_cigar > MAX_NUM_CIGAR) continue; // ignore hits with more than 7 cigar types if(p.qual < min_mapping_quality) continue; // ignore hits with small quality hit ht(b1t); qlen += ht.qlen; if(ht.strand == '.') continue; // TODO truncate(ht); add_hit(ht); } for(int i = 0; i < vbb.size(); i++) process(vbb[i]); if(output_file == "") return 0; double factor = 1e9 * average_read_length / qlen; gm.assign_RPKM(factor); gm.write(output_file); return 0; } int assembler::add_hit(const hit &ht) { bool b = false; for(int i = 0; i < vbb.size(); i++) { bundle_base &bb = vbb[i]; assert(bb.hits.size() >= 1); assert(bb.strand != '.'); //if(bb.overlap(ht) == false) continue; if(ht.strand != bb.strand) continue; if(ht.tid != bb.tid) continue; if(ht.pos > bb.rpos + min_bundle_gap) continue; bb.add_hit(ht); b = true; break; } if(b == true) return 0; bundle_base bb; bb.add_hit(ht); vbb.push_back(bb); return 0; } int assembler::truncate(const hit &ht) { for(int i = 0; i < vbb.size(); i++) { bundle_base &bb = vbb[i]; if(ht.pos <= bb.rpos + min_bundle_gap && ht.tid == bb.tid) continue; process(bb); vbb.erase(vbb.begin() + i); truncate(ht); } return 0; } int assembler::process(const bundle_base &bb) { printf("hits.size = %lu, min-num = %d\n", bb.hits.size(), min_num_hits_in_bundle); if(bb.hits.size() < min_num_hits_in_bundle) return 0; char buf[1024]; assert(bb.tid >= 0); strcpy(buf, hdr->target_name[bb.tid]); bundle bd(bb); bd.chrm = string(buf); bd.build(); index++; /* bd.print(index); if(ref_file != "") compare(bd.gr, ref_file, "compare.tex"); if(ref_file1 != "" && bd.strand == '+') compare(bd.gr, ref_file1, "compare1.tex"); if(ref_file2 != "" && bd.strand == '-') compare(bd.gr, ref_file2, "compare2.tex"); */ super_graph sg(bd.gr, bd.hs); sg.build(); int maxk = -1; int maxv = 0; for(int k = 0; k < sg.subs.size(); k++) { if(sg.subs[k].num_vertices() < maxv) continue; maxk = k; maxv = sg.subs[k].num_vertices(); } if(ref_file != "") compare(bd.gr, ref_file, "compare.tex"); if(ref_file1 != "" && bd.strand == '+') compare(bd.gr, ref_file1, "compare1.tex"); if(ref_file2 != "" && bd.strand == '-') compare(bd.gr, ref_file2, "compare2.tex"); for(int k = 0; k < sg.subs.size(); k++) { //if(k != maxk) continue; string gid = "bundle." + tostring(index) + "." + tostring(k); if(fixed_gene_name != "" && gid != fixed_gene_name) continue; if(k == 0 || fixed_gene_name != "") bd.print(index); if(k == 0 || fixed_gene_name != "") sg.print(); splice_graph &gr = sg.subs[k]; hyper_set &hs = sg.hss[k]; /* if(ref_file != "") compare(gr, ref_file, "compare.tex"); if(ref_file1 != "" && bd.strand == '+') compare(gr, ref_file1, "compare1.tex"); if(ref_file2 != "" && bd.strand == '-') compare(gr, ref_file2, "compare2.tex"); */ double ss = gr.compute_coverage() / average_read_length; if(ss < min_splice_graph_coverage) continue; scallop3 sc(gid, gr, hs); sc.assemble(); vector<path> pp; for(int i = 0; i < sc.paths.size(); i++) { path p; p.v = sg.get_root_vertices(k, sc.paths[i].v); p.abd = sc.paths[i].abd; p.reads = sc.paths[i].reads; pp.push_back(p); } gene gn; bd.output_transcripts(gn, pp, gid); gm.add_gene(gn); if(fixed_gene_name != "" && gid == fixed_gene_name) terminate = true; if(terminate == true) return 0; } return 0; } int assembler::compare(splice_graph &gr, const string &file, const string &texfile) { if(file == "") return 0; genome g(file); if(g.genes.size() <= 0) return 0; gtf gg(g.genes[0]); splice_graph gt; gg.build_splice_graph(gt); sgraph_compare sgc(gt, gr); sgc.compare(texfile); return 0; } <commit_msg>update<commit_after>#include <cstdio> #include <cassert> #include <sstream> #include "genome.h" #include "gtf.h" #include "config.h" #include "assembler.h" #include "scallop3.h" #include "sgraph_compare.h" #include "super_graph.h" assembler::assembler() { sfn = sam_open(input_file.c_str(), "r"); hdr = sam_hdr_read(sfn); b1t = bam_init1(); terminate = false; index = -1; qlen = 0; } assembler::~assembler() { bam_destroy1(b1t); bam_hdr_destroy(hdr); sam_close(sfn); } int assembler::assemble() { while(sam_read1(sfn, hdr, b1t) >= 0) { if(terminate == true) return 0; bam1_core_t &p = b1t->core; if((p.flag & 0x4) >= 1) continue; // read is not mapped if((p.flag & 0x100) >= 1) continue; // secondary alignment if(p.n_cigar < 1) continue; // should never happen if(p.n_cigar > MAX_NUM_CIGAR) continue; // ignore hits with more than 7 cigar types if(p.qual < min_mapping_quality) continue; // ignore hits with small quality hit ht(b1t); qlen += ht.qlen; if(ht.strand == '.') continue; // TODO truncate(ht); add_hit(ht); } for(int i = 0; i < vbb.size(); i++) process(vbb[i]); if(output_file == "") return 0; double factor = 1e9 * average_read_length / qlen; gm.assign_RPKM(factor); gm.write(output_file); return 0; } int assembler::add_hit(const hit &ht) { bool b = false; for(int i = 0; i < vbb.size(); i++) { bundle_base &bb = vbb[i]; assert(bb.hits.size() >= 1); assert(bb.strand != '.'); //if(bb.overlap(ht) == false) continue; if(ht.strand != bb.strand) continue; if(ht.tid != bb.tid) continue; if(ht.pos > bb.rpos + min_bundle_gap) continue; bb.add_hit(ht); b = true; break; } if(b == true) return 0; bundle_base bb; bb.add_hit(ht); vbb.push_back(bb); return 0; } int assembler::truncate(const hit &ht) { for(int i = 0; i < vbb.size(); i++) { bundle_base &bb = vbb[i]; if(ht.pos <= bb.rpos + min_bundle_gap && ht.tid == bb.tid) continue; process(bb); vbb.erase(vbb.begin() + i); truncate(ht); } return 0; } int assembler::process(const bundle_base &bb) { //printf("hits.size = %lu, min-num = %d\n", bb.hits.size(), min_num_hits_in_bundle); if(bb.hits.size() < min_num_hits_in_bundle) return 0; char buf[1024]; assert(bb.tid >= 0); strcpy(buf, hdr->target_name[bb.tid]); bundle bd(bb); bd.chrm = string(buf); bd.build(); index++; /* bd.print(index); if(ref_file != "") compare(bd.gr, ref_file, "compare.tex"); if(ref_file1 != "" && bd.strand == '+') compare(bd.gr, ref_file1, "compare1.tex"); if(ref_file2 != "" && bd.strand == '-') compare(bd.gr, ref_file2, "compare2.tex"); */ super_graph sg(bd.gr, bd.hs); sg.build(); int maxk = -1; int maxv = 0; for(int k = 0; k < sg.subs.size(); k++) { if(sg.subs[k].num_vertices() < maxv) continue; maxk = k; maxv = sg.subs[k].num_vertices(); } if(ref_file != "") compare(bd.gr, ref_file, "compare.tex"); if(ref_file1 != "" && bd.strand == '+') compare(bd.gr, ref_file1, "compare1.tex"); if(ref_file2 != "" && bd.strand == '-') compare(bd.gr, ref_file2, "compare2.tex"); for(int k = 0; k < sg.subs.size(); k++) { //if(k != maxk) continue; string gid = "bundle." + tostring(index) + "." + tostring(k); if(fixed_gene_name != "" && gid != fixed_gene_name) continue; if(k == 0 || fixed_gene_name != "") bd.print(index); if(k == 0 || fixed_gene_name != "") sg.print(); splice_graph &gr = sg.subs[k]; hyper_set &hs = sg.hss[k]; /* if(ref_file != "") compare(gr, ref_file, "compare.tex"); if(ref_file1 != "" && bd.strand == '+') compare(gr, ref_file1, "compare1.tex"); if(ref_file2 != "" && bd.strand == '-') compare(gr, ref_file2, "compare2.tex"); */ double ss = gr.compute_coverage() / average_read_length; if(ss < min_splice_graph_coverage) continue; scallop3 sc(gid, gr, hs); sc.assemble(); vector<path> pp; for(int i = 0; i < sc.paths.size(); i++) { path p; p.v = sg.get_root_vertices(k, sc.paths[i].v); p.abd = sc.paths[i].abd; p.reads = sc.paths[i].reads; pp.push_back(p); } gene gn; bd.output_transcripts(gn, pp, gid); gm.add_gene(gn); if(fixed_gene_name != "" && gid == fixed_gene_name) terminate = true; if(terminate == true) return 0; } return 0; } int assembler::compare(splice_graph &gr, const string &file, const string &texfile) { if(file == "") return 0; genome g(file); if(g.genes.size() <= 0) return 0; gtf gg(g.genes[0]); splice_graph gt; gg.build_splice_graph(gt); sgraph_compare sgc(gt, gr); sgc.compare(texfile); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkExceptionObject.h" #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkPolyLineParametricPath.h" #include "otbImageFileReader.h" #include "otbPathListSource.h" #include "otbImageToPathListAlignFilter.h" #include "otbDrawPathListFilter.h" #include "otbImageFileWriter.h" int otbDrawPathList( int argc, char * argv[] ) { try { const char * inputFilename = argv[1]; const char * outputFilename = argv[2]; typedef unsigned char InputPixelType; typedef unsigned char OutputPixelType; const unsigned int Dimension = 2; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::PolyLineParametricPath< Dimension > PathType; typedef PathType::Pointer PathPointerType; typedef otb::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; // typedef otb::ImageToPathListAlignFilter<InputImageType,PathType> ListAlignFilterType; // typedef ListAlignFilterType::OutputPathListType ListAlignFilterOutputPathListType; typedef otb::DrawPathListFilter<InputImageType,PathType,OutputImageType> DrawPathListFilterType; typedef otb::ImageToPathListAlignFilter<InputImageType,PathType> PathListType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); // InputImageType::Pointer ImageIn = InputImageType::New(); // OutputImageType::Pointer ImageOut = OutputImageType::New(); DrawPathListFilterType::Pointer DrawPath = DrawPathListFilterType::New(); // typedef itk::PathSource<PathType> TestType; // TestType::Pointer test = TestType::New(); PathListType::Pointer testList = PathListType::New(); reader->SetFileName( inputFilename ); writer->SetFileName( outputFilename ); //OTB-FA-00010-CS testList->SetInput( reader->GetOutput() ); testList->Update(); DrawPath->SetImageInput(reader->GetOutput() ); DrawPath->SetPathInput( testList->GetOutput()); DrawPath->Update(); writer->SetInput(DrawPath->GetImageOutput()); writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "Exception itk::ExceptionObject levee !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } catch( ... ) { std::cout << "Exception levee inconnue !" << std::endl; return EXIT_FAILURE; } // Software Guide : EndCodeSnippet //#endif return EXIT_SUCCESS; } <commit_msg>Remplacement de varaibles itk::Image et itk::ImageFileWriter par otb::.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkExceptionObject.h" #include "itkPolyLineParametricPath.h" #include "otbImage.h" #include "otbPathListSource.h" #include "otbImageToPathListAlignFilter.h" #include "otbDrawPathListFilter.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" int otbDrawPathList( int argc, char * argv[] ) { try { const char * inputFilename = argv[1]; const char * outputFilename = argv[2]; typedef unsigned char InputPixelType; typedef unsigned char OutputPixelType; const unsigned int Dimension = 2; typedef otb::Image< InputPixelType, Dimension > InputImageType; typedef otb::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::PolyLineParametricPath< Dimension > PathType; typedef PathType::Pointer PathPointerType; typedef otb::ImageFileReader< InputImageType > ReaderType; typedef otb::ImageFileWriter< OutputImageType > WriterType; typedef otb::DrawPathListFilter<InputImageType,PathType,OutputImageType> DrawPathListFilterType; typedef otb::ImageToPathListAlignFilter<InputImageType,PathType> PathListType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); DrawPathListFilterType::Pointer DrawPath = DrawPathListFilterType::New(); PathListType::Pointer testList = PathListType::New(); reader->SetFileName( inputFilename ); writer->SetFileName( outputFilename ); //OTB-FA-00010-CS testList->SetInput( reader->GetOutput() ); testList->Update(); DrawPath->SetImageInput(reader->GetOutput() ); DrawPath->SetPathInput( testList->GetOutput()); DrawPath->Update(); writer->SetInput(DrawPath->GetImageOutput()); writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "Exception itk::ExceptionObject levee !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } catch( ... ) { std::cout << "Exception levee inconnue !" << std::endl; return EXIT_FAILURE; } // Software Guide : EndCodeSnippet //#endif return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mmdocselectpage.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2005-03-07 17:36:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _SFXNEW_HXX #include <sfx2/new.hxx> #endif #ifndef _SFX_DOCFILT_HACK_HXX #include <sfx2/docfilt.hxx> #endif #ifndef _SFX_FCONTNR_HXX #include <sfx2/fcontnr.hxx> #endif #ifndef _SFX_OBJFAC_HXX #include <sfx2/docfac.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SWVIEW_HXX #include <view.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _MAILMERGEDOCSELECTPAGE_HXX #include <mmdocselectpage.hxx> #endif #ifndef _MAILMERGEWIZARD_HXX #include <mailmergewizard.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _SW_ABSTDLG_HXX #include <swabstdlg.hxx> #endif #ifndef _MMCONFIGITEM_HXX #include <mmconfigitem.hxx> #endif #include <dbui.hrc> #include <mmdocselectpage.hrc> #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterManager.hpp> #endif using namespace com::sun::star::ui::dialogs; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace svt; /*-- 02.04.2004 09:40:14--------------------------------------------------- -----------------------------------------------------------------------*/ SwMailMergeDocSelectPage::SwMailMergeDocSelectPage( SwMailMergeWizard* _pParent ) : svt::OWizardPage(_pParent, SW_RES(DLG_MM_DOCSELECT_PAGE)), #pragma warning (disable : 4355) m_aHeaderFI(this, ResId( FI_HEADER ) ), m_aHowToFT (this, ResId( FT_HOWTO )), m_aCurrentDocRB (this, ResId( RB_CURRENTDOC )), m_aNewDocRB (this, ResId( RB_NEWDOC )), m_aLoadDocRB (this, ResId( RB_LOADDOC )), m_aBrowseDocPB (this, ResId( PB_LOADDOC )), m_aLoadTemplateRB (this, ResId( RB_LOADTEMPLATE )), m_aBrowseTemplatePB (this, ResId( PB_BROWSETEMPLATE )), m_aRecentDocRB (this, ResId( RB_RECENTDOC )), m_aRecentDocLB (this, ResId( LB_RECENTDOC )), #pragma warning (default : 4355) m_pWizard(_pParent) { FreeResource(); m_aCurrentDocRB.Check(); DocSelectHdl(&m_aNewDocRB); Link aDocSelectLink = LINK(this, SwMailMergeDocSelectPage, DocSelectHdl); m_aCurrentDocRB.SetClickHdl(aDocSelectLink); m_aNewDocRB.SetClickHdl(aDocSelectLink); m_aLoadDocRB.SetClickHdl(aDocSelectLink); m_aLoadTemplateRB.SetClickHdl(aDocSelectLink); m_aRecentDocRB.SetClickHdl(aDocSelectLink); Link aFileSelectHdl = LINK(this, SwMailMergeDocSelectPage, FileSelectHdl); m_aBrowseDocPB.SetClickHdl(aFileSelectHdl); m_aBrowseTemplatePB.SetClickHdl(aFileSelectHdl); const uno::Sequence< ::rtl::OUString >& rDocs = m_pWizard->GetConfigItem().GetSavedDocuments(); for(sal_Int32 nDoc = 0; nDoc < rDocs.getLength(); ++nDoc) { //insert in reverse order m_aRecentDocLB.InsertEntry(rDocs[nDoc], 0); } m_aRecentDocLB.SelectEntryPos(0); if(!rDocs.getLength()) { m_aRecentDocRB.Enable(sal_False); } } /*-- 02.04.2004 09:40:14--------------------------------------------------- -----------------------------------------------------------------------*/ SwMailMergeDocSelectPage::~SwMailMergeDocSelectPage() { } /*-- 05.04.2004 14:21:48--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwMailMergeDocSelectPage, DocSelectHdl, RadioButton*, pButton) { m_aRecentDocLB.Enable(&m_aRecentDocRB == pButton); sal_Bool bEnableNext = m_aNewDocRB.IsChecked() || m_aCurrentDocRB.IsChecked() || (m_sLoadFileName.Len() && (m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked())) || m_aRecentDocLB.GetSelectEntry().Len(); m_pWizard->enableButtons( WZB_NEXT, bEnableNext ); return 0; } /*-- 05.04.2004 14:25:12--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwMailMergeDocSelectPage, FileSelectHdl, PushButton*, pButton) { bool bTemplate = &m_aBrowseTemplatePB == pButton; if(bTemplate) { m_aLoadTemplateRB.Check(); SfxNewFileDialog* pNewFileDlg = new SfxNewFileDialog(this, 0); //pNewFileDlg->SetTemplateFlags(nFlags); USHORT nRet = pNewFileDlg->Execute(); if(RET_TEMPLATE_LOAD == nRet) bTemplate = false; else if(RET_CANCEL != nRet) m_sLoadFileName = pNewFileDlg->GetTemplateFileName(); delete pNewFileDlg; } else m_aLoadDocRB.Check(); if(!bTemplate) { sfx2::FileDialogHelper aDlgHelper( TemplateDescription::FILEOPEN_SIMPLE, 0 ); Reference < XFilePicker > xFP = aDlgHelper.GetFilePicker(); xFP->setDisplayDirectory( SvtPathOptions().GetWorkPath() ); SfxObjectFactory &rFact = m_pWizard->GetSwView()->GetDocShell()->GetFactory(); SfxFilterMatcher aMatcher( String::CreateFromAscii(rFact.GetShortName()) ); SfxFilterMatcherIter aIter( &aMatcher ); Reference<XFilterManager> xFltMgr(xFP, UNO_QUERY); const SfxFilter* pFlt = aIter.First(); while( pFlt ) { if( pFlt && pFlt->IsAllowedAsTemplate() ) { const String sWild = ((WildCard&)pFlt->GetWildcard()).GetWildCard(); xFltMgr->appendFilter( pFlt->GetUIName(), sWild ); // #i40125 if(pFlt->GetFilterFlags() & SFX_FILTER_DEFAULT) xFltMgr->setCurrentFilter( pFlt->GetUIName() ) ; } pFlt = aIter.Next(); } if( ERRCODE_NONE == aDlgHelper.Execute() ) { m_sLoadFileName = xFP->getFiles().getConstArray()[0]; } } m_pWizard->enableButtons( WZB_NEXT, m_sLoadFileName.Len() > 0 ); return 0; } /*-- 06.04.2004 12:52:24--------------------------------------------------- -----------------------------------------------------------------------*/ sal_Bool SwMailMergeDocSelectPage::commitPage(COMMIT_REASON _eReason) { if(_eReason == CR_TRAVEL_NEXT) { sal_Bool bCloseDialog = sal_True; if(m_sLoadFileName.Len() && (m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked())) m_pWizard->SetReloadDocument(m_sLoadFileName); else if(m_aNewDocRB.IsChecked()) m_pWizard->SetReloadDocument(String()); else if(m_aRecentDocRB.IsChecked()) { m_pWizard->SetReloadDocument(m_aRecentDocLB.GetSelectEntry()); } else bCloseDialog = sal_False; if(bCloseDialog) { m_pWizard->SetRestartPage(MM_OUTPUTTYPETPAGE); m_pWizard->EndDialog(RET_LOAD_DOC); } } return sal_True; } <commit_msg>INTEGRATION: CWS ooo19126 (1.5.276); FILE MERGED 2005/09/05 13:43:45 rt 1.5.276.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mmdocselectpage.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 06:58:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _SFXNEW_HXX #include <sfx2/new.hxx> #endif #ifndef _SFX_DOCFILT_HACK_HXX #include <sfx2/docfilt.hxx> #endif #ifndef _SFX_FCONTNR_HXX #include <sfx2/fcontnr.hxx> #endif #ifndef _SFX_OBJFAC_HXX #include <sfx2/docfac.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SWVIEW_HXX #include <view.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _MAILMERGEDOCSELECTPAGE_HXX #include <mmdocselectpage.hxx> #endif #ifndef _MAILMERGEWIZARD_HXX #include <mailmergewizard.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _SW_ABSTDLG_HXX #include <swabstdlg.hxx> #endif #ifndef _MMCONFIGITEM_HXX #include <mmconfigitem.hxx> #endif #include <dbui.hrc> #include <mmdocselectpage.hrc> #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterManager.hpp> #endif using namespace com::sun::star::ui::dialogs; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace svt; /*-- 02.04.2004 09:40:14--------------------------------------------------- -----------------------------------------------------------------------*/ SwMailMergeDocSelectPage::SwMailMergeDocSelectPage( SwMailMergeWizard* _pParent ) : svt::OWizardPage(_pParent, SW_RES(DLG_MM_DOCSELECT_PAGE)), #pragma warning (disable : 4355) m_aHeaderFI(this, ResId( FI_HEADER ) ), m_aHowToFT (this, ResId( FT_HOWTO )), m_aCurrentDocRB (this, ResId( RB_CURRENTDOC )), m_aNewDocRB (this, ResId( RB_NEWDOC )), m_aLoadDocRB (this, ResId( RB_LOADDOC )), m_aBrowseDocPB (this, ResId( PB_LOADDOC )), m_aLoadTemplateRB (this, ResId( RB_LOADTEMPLATE )), m_aBrowseTemplatePB (this, ResId( PB_BROWSETEMPLATE )), m_aRecentDocRB (this, ResId( RB_RECENTDOC )), m_aRecentDocLB (this, ResId( LB_RECENTDOC )), #pragma warning (default : 4355) m_pWizard(_pParent) { FreeResource(); m_aCurrentDocRB.Check(); DocSelectHdl(&m_aNewDocRB); Link aDocSelectLink = LINK(this, SwMailMergeDocSelectPage, DocSelectHdl); m_aCurrentDocRB.SetClickHdl(aDocSelectLink); m_aNewDocRB.SetClickHdl(aDocSelectLink); m_aLoadDocRB.SetClickHdl(aDocSelectLink); m_aLoadTemplateRB.SetClickHdl(aDocSelectLink); m_aRecentDocRB.SetClickHdl(aDocSelectLink); Link aFileSelectHdl = LINK(this, SwMailMergeDocSelectPage, FileSelectHdl); m_aBrowseDocPB.SetClickHdl(aFileSelectHdl); m_aBrowseTemplatePB.SetClickHdl(aFileSelectHdl); const uno::Sequence< ::rtl::OUString >& rDocs = m_pWizard->GetConfigItem().GetSavedDocuments(); for(sal_Int32 nDoc = 0; nDoc < rDocs.getLength(); ++nDoc) { //insert in reverse order m_aRecentDocLB.InsertEntry(rDocs[nDoc], 0); } m_aRecentDocLB.SelectEntryPos(0); if(!rDocs.getLength()) { m_aRecentDocRB.Enable(sal_False); } } /*-- 02.04.2004 09:40:14--------------------------------------------------- -----------------------------------------------------------------------*/ SwMailMergeDocSelectPage::~SwMailMergeDocSelectPage() { } /*-- 05.04.2004 14:21:48--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwMailMergeDocSelectPage, DocSelectHdl, RadioButton*, pButton) { m_aRecentDocLB.Enable(&m_aRecentDocRB == pButton); sal_Bool bEnableNext = m_aNewDocRB.IsChecked() || m_aCurrentDocRB.IsChecked() || (m_sLoadFileName.Len() && (m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked())) || m_aRecentDocLB.GetSelectEntry().Len(); m_pWizard->enableButtons( WZB_NEXT, bEnableNext ); return 0; } /*-- 05.04.2004 14:25:12--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwMailMergeDocSelectPage, FileSelectHdl, PushButton*, pButton) { bool bTemplate = &m_aBrowseTemplatePB == pButton; if(bTemplate) { m_aLoadTemplateRB.Check(); SfxNewFileDialog* pNewFileDlg = new SfxNewFileDialog(this, 0); //pNewFileDlg->SetTemplateFlags(nFlags); USHORT nRet = pNewFileDlg->Execute(); if(RET_TEMPLATE_LOAD == nRet) bTemplate = false; else if(RET_CANCEL != nRet) m_sLoadFileName = pNewFileDlg->GetTemplateFileName(); delete pNewFileDlg; } else m_aLoadDocRB.Check(); if(!bTemplate) { sfx2::FileDialogHelper aDlgHelper( TemplateDescription::FILEOPEN_SIMPLE, 0 ); Reference < XFilePicker > xFP = aDlgHelper.GetFilePicker(); xFP->setDisplayDirectory( SvtPathOptions().GetWorkPath() ); SfxObjectFactory &rFact = m_pWizard->GetSwView()->GetDocShell()->GetFactory(); SfxFilterMatcher aMatcher( String::CreateFromAscii(rFact.GetShortName()) ); SfxFilterMatcherIter aIter( &aMatcher ); Reference<XFilterManager> xFltMgr(xFP, UNO_QUERY); const SfxFilter* pFlt = aIter.First(); while( pFlt ) { if( pFlt && pFlt->IsAllowedAsTemplate() ) { const String sWild = ((WildCard&)pFlt->GetWildcard()).GetWildCard(); xFltMgr->appendFilter( pFlt->GetUIName(), sWild ); // #i40125 if(pFlt->GetFilterFlags() & SFX_FILTER_DEFAULT) xFltMgr->setCurrentFilter( pFlt->GetUIName() ) ; } pFlt = aIter.Next(); } if( ERRCODE_NONE == aDlgHelper.Execute() ) { m_sLoadFileName = xFP->getFiles().getConstArray()[0]; } } m_pWizard->enableButtons( WZB_NEXT, m_sLoadFileName.Len() > 0 ); return 0; } /*-- 06.04.2004 12:52:24--------------------------------------------------- -----------------------------------------------------------------------*/ sal_Bool SwMailMergeDocSelectPage::commitPage(COMMIT_REASON _eReason) { if(_eReason == CR_TRAVEL_NEXT) { sal_Bool bCloseDialog = sal_True; if(m_sLoadFileName.Len() && (m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked())) m_pWizard->SetReloadDocument(m_sLoadFileName); else if(m_aNewDocRB.IsChecked()) m_pWizard->SetReloadDocument(String()); else if(m_aRecentDocRB.IsChecked()) { m_pWizard->SetReloadDocument(m_aRecentDocLB.GetSelectEntry()); } else bCloseDialog = sal_False; if(bCloseDialog) { m_pWizard->SetRestartPage(MM_OUTPUTTYPETPAGE); m_pWizard->EndDialog(RET_LOAD_DOC); } } return sal_True; } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" #include "RawImgFrame.hpp" namespace dai { struct RawImageManipConfig : public RawBuffer { // NNData data is in PoBuf struct CropRect { // Normalized range 0-1 float xmin = 0.0f, ymin = 0.0f, xmax = 0.0f, ymax = 0.0f; NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropRect, xmin, ymin, xmax, ymax); }; struct CropConfig { CropRect cropRect; bool enableCenterCropRectangle = false; // if enableCenterCropRectangle -> automatically calculated crop parameters float cropRatio = 1.0f, widthHeightAspectRatio = 1.0f; NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropConfig, cropRect, enableCenterCropRectangle, cropRatio, widthHeightAspectRatio); }; struct ResizeConfig { int width = 0, height = 0; bool lockAspectRatioFill = false; char bgRed = 0, bgGreen = 0, bgBlue = 0; NLOHMANN_DEFINE_TYPE_INTRUSIVE(ResizeConfig, width, height, lockAspectRatioFill, bgRed, bgGreen, bgBlue); }; struct FormatConfig { RawImgFrame::Type type = RawImgFrame::Type::RGB888p; bool flipHorizontal = false; NLOHMANN_DEFINE_TYPE_INTRUSIVE(FormatConfig, type, flipHorizontal); }; CropConfig cropConfig; ResizeConfig resizeConfig; FormatConfig formatConfig; bool enableCrop = false; bool enableResize = false; bool enableFormat = false; void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::ImageManipConfig; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawImageManipConfig, cropConfig, resizeConfig, formatConfig, enableCrop, enableResize, enableFormat); }; } // namespace dai<commit_msg>ImageManip: add support for rotated/arbitrary cropping<commit_after>#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" #include "RawImgFrame.hpp" namespace dai { struct RawImageManipConfig : public RawBuffer { // NNData data is in PoBuf struct CropRect { // Normalized range 0-1 float xmin = 0.0f, ymin = 0.0f, xmax = 0.0f, ymax = 0.0f; NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropRect, xmin, ymin, xmax, ymax); }; // Point2f, Size2f, RotatedRect are defined similar to OpenCV types struct Point2f { float x; float y; NLOHMANN_DEFINE_TYPE_INTRUSIVE(Point2f, x, y); }; struct Size2f { float width; float height; NLOHMANN_DEFINE_TYPE_INTRUSIVE(Size2f, width, height); }; struct RotatedRect { Point2f center; Size2f size; // degrees, increasing clockwise float angle; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RotatedRect, center, size, angle); }; struct CropQuadrilateral { // pt[0] is mapped to the top-left output corner, clockwise order std::vector<Point2f> pt; Size2f outSize; NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropQuadrilateral, pt, outSize); }; struct CropConfig { CropRect cropRect; RotatedRect cropRotatedRect; CropQuadrilateral cropQuadrilateral; bool enableCenterCropRectangle = false; // if enableCenterCropRectangle -> automatically calculated crop parameters float cropRatio = 1.0f, widthHeightAspectRatio = 1.0f; bool enableRotatedRect = false; bool enableCropQuadrilateral = false; // Range 0..1 by default. Set 'false' to specify in pixels bool normalizedCoords = true; NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropConfig, cropRect, cropRotatedRect, cropQuadrilateral, enableCenterCropRectangle, cropRatio, widthHeightAspectRatio, enableRotatedRect, enableCropQuadrilateral, normalizedCoords); }; struct ResizeConfig { int width = 0, height = 0; bool lockAspectRatioFill = false; char bgRed = 0, bgGreen = 0, bgBlue = 0; NLOHMANN_DEFINE_TYPE_INTRUSIVE(ResizeConfig, width, height, lockAspectRatioFill, bgRed, bgGreen, bgBlue); }; struct FormatConfig { RawImgFrame::Type type = RawImgFrame::Type::RGB888p; bool flipHorizontal = false; NLOHMANN_DEFINE_TYPE_INTRUSIVE(FormatConfig, type, flipHorizontal); }; CropConfig cropConfig; ResizeConfig resizeConfig; FormatConfig formatConfig; bool enableCrop = false; bool enableResize = false; bool enableFormat = false; void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::ImageManipConfig; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawImageManipConfig, cropConfig, resizeConfig, formatConfig, enableCrop, enableResize, enableFormat); }; } // namespace dai<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sync/notifier/registration_manager.h" #include <algorithm> #include <cstddef> #include <iterator> #include <string> #include <utility> #include "base/rand_util.h" #include "base/stl_util.h" #include "google/cacheinvalidation/include/invalidation-client.h" #include "google/cacheinvalidation/include/types.h" #include "sync/notifier/invalidation_util.h" namespace syncer { RegistrationManager::PendingRegistrationInfo::PendingRegistrationInfo() {} RegistrationManager::RegistrationStatus::RegistrationStatus( const invalidation::ObjectId& id, RegistrationManager* manager) : id(id), registration_manager(manager), enabled(true), state(invalidation::InvalidationListener::UNREGISTERED) { DCHECK(registration_manager); } RegistrationManager::RegistrationStatus::~RegistrationStatus() {} void RegistrationManager::RegistrationStatus::DoRegister() { CHECK(enabled); // We might be called explicitly, so stop the timer manually and // reset the delay. registration_timer.Stop(); delay = base::TimeDelta(); registration_manager->DoRegisterId(id); DCHECK(!last_registration_request.is_null()); } void RegistrationManager::RegistrationStatus::Disable() { enabled = false; state = invalidation::InvalidationListener::UNREGISTERED; registration_timer.Stop(); delay = base::TimeDelta(); } const int RegistrationManager::kInitialRegistrationDelaySeconds = 5; const int RegistrationManager::kRegistrationDelayExponent = 2; const double RegistrationManager::kRegistrationDelayMaxJitter = 0.5; const int RegistrationManager::kMinRegistrationDelaySeconds = 1; // 1 hour. const int RegistrationManager::kMaxRegistrationDelaySeconds = 60 * 60; RegistrationManager::RegistrationManager( invalidation::InvalidationClient* invalidation_client) : invalidation_client_(invalidation_client) { DCHECK(invalidation_client_); } RegistrationManager::~RegistrationManager() { DCHECK(CalledOnValidThread()); STLDeleteValues(&registration_statuses_); } ObjectIdSet RegistrationManager::UpdateRegisteredIds(const ObjectIdSet& ids) { DCHECK(CalledOnValidThread()); const ObjectIdSet& old_ids = GetRegisteredIds(); const ObjectIdSet& to_register = ids; ObjectIdSet to_unregister; std::set_difference(old_ids.begin(), old_ids.end(), ids.begin(), ids.end(), std::inserter(to_unregister, to_unregister.begin()), ObjectIdLessThan()); for (ObjectIdSet::const_iterator it = to_unregister.begin(); it != to_unregister.end(); ++it) { UnregisterId(*it); } for (ObjectIdSet::const_iterator it = to_register.begin(); it != to_register.end(); ++it) { if (!ContainsKey(registration_statuses_, *it)) { registration_statuses_.insert( std::make_pair(*it, new RegistrationStatus(*it, this))); } if (!IsIdRegistered(*it)) { TryRegisterId(*it, false /* is-retry */); } } return to_unregister; } void RegistrationManager::MarkRegistrationLost( const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { DLOG(WARNING) << "Attempt to mark non-existent registration for " << ObjectIdToString(id) << " as lost"; return; } if (!it->second->enabled) { return; } it->second->state = invalidation::InvalidationListener::UNREGISTERED; bool is_retry = !it->second->last_registration_request.is_null(); TryRegisterId(id, is_retry); } void RegistrationManager::MarkAllRegistrationsLost() { DCHECK(CalledOnValidThread()); for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { if (IsIdRegistered(it->first)) { MarkRegistrationLost(it->first); } } } void RegistrationManager::DisableId(const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { DLOG(WARNING) << "Attempt to disable non-existent registration for " << ObjectIdToString(id); return; } it->second->Disable(); } // static double RegistrationManager::CalculateBackoff( double retry_interval, double initial_retry_interval, double min_retry_interval, double max_retry_interval, double backoff_exponent, double jitter, double max_jitter) { // scaled_jitter lies in [-max_jitter, max_jitter]. double scaled_jitter = jitter * max_jitter; double new_retry_interval = (retry_interval == 0.0) ? (initial_retry_interval * (1.0 + scaled_jitter)) : (retry_interval * (backoff_exponent + scaled_jitter)); return std::max(min_retry_interval, std::min(max_retry_interval, new_retry_interval)); } ObjectIdSet RegistrationManager::GetRegisteredIdsForTest() const { return GetRegisteredIds(); } RegistrationManager::PendingRegistrationMap RegistrationManager::GetPendingRegistrationsForTest() const { DCHECK(CalledOnValidThread()); PendingRegistrationMap pending_registrations; for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { const invalidation::ObjectId& id = it->first; RegistrationStatus* status = it->second; if (status->registration_timer.IsRunning()) { pending_registrations[id].last_registration_request = status->last_registration_request; pending_registrations[id].registration_attempt = status->last_registration_attempt; pending_registrations[id].delay = status->delay; pending_registrations[id].actual_delay = status->registration_timer.GetCurrentDelay(); } } return pending_registrations; } void RegistrationManager::FirePendingRegistrationsForTest() { DCHECK(CalledOnValidThread()); for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { if (it->second->registration_timer.IsRunning()) { it->second->DoRegister(); } } } double RegistrationManager::GetJitter() { // |jitter| lies in [-1.0, 1.0), which is low-biased, but only // barely. // // TODO(akalin): Fix the bias. return 2.0 * base::RandDouble() - 1.0; } void RegistrationManager::TryRegisterId(const invalidation::ObjectId& id, bool is_retry) { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { DLOG(FATAL) << "TryRegisterId called on " << ObjectIdToString(id) << " which is not in the registration map"; return; } RegistrationStatus* status = it->second; if (!status->enabled) { // Disabled, so do nothing. return; } status->last_registration_attempt = base::Time::Now(); if (is_retry) { // If we're a retry, we must have tried at least once before. DCHECK(!status->last_registration_request.is_null()); // delay = max(0, (now - last request) + next_delay) status->delay = (status->last_registration_request - status->last_registration_attempt) + status->next_delay; base::TimeDelta delay = (status->delay <= base::TimeDelta()) ? base::TimeDelta() : status->delay; DVLOG(2) << "Registering " << ObjectIdToString(id) << " in " << delay.InMilliseconds() << " ms"; status->registration_timer.Stop(); status->registration_timer.Start(FROM_HERE, delay, status, &RegistrationManager::RegistrationStatus::DoRegister); double next_delay_seconds = CalculateBackoff(static_cast<double>(status->next_delay.InSeconds()), kInitialRegistrationDelaySeconds, kMinRegistrationDelaySeconds, kMaxRegistrationDelaySeconds, kRegistrationDelayExponent, GetJitter(), kRegistrationDelayMaxJitter); status->next_delay = base::TimeDelta::FromSeconds(static_cast<int64>(next_delay_seconds)); DVLOG(2) << "New next delay for " << ObjectIdToString(id) << " is " << status->next_delay.InSeconds() << " seconds"; } else { DVLOG(2) << "Not a retry -- registering " << ObjectIdToString(id) << " immediately"; status->delay = base::TimeDelta(); status->next_delay = base::TimeDelta(); status->DoRegister(); } } void RegistrationManager::DoRegisterId(const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); invalidation_client_->Register(id); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { DLOG(FATAL) << "DoRegisterId called on " << ObjectIdToString(id) << " which is not in the registration map"; return; } it->second->state = invalidation::InvalidationListener::REGISTERED; it->second->last_registration_request = base::Time::Now(); } void RegistrationManager::UnregisterId(const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); invalidation_client_->Unregister(id); RegistrationStatusMap::iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { DLOG(FATAL) << "UnregisterId called on " << ObjectIdToString(id) << " which is not in the registration map"; return; } delete it->second; registration_statuses_.erase(it); } ObjectIdSet RegistrationManager::GetRegisteredIds() const { DCHECK(CalledOnValidThread()); ObjectIdSet ids; for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { if (IsIdRegistered(it->first)) { ids.insert(it->first); } } return ids; } bool RegistrationManager::IsIdRegistered( const invalidation::ObjectId& id) const { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); return it != registration_statuses_.end() && it->second->state == invalidation::InvalidationListener::REGISTERED; } } // namespace syncer <commit_msg>Cleanup: Change some DLOG(WARNINGS) to DVLOG(1). Change DLOG(FATAL) to NOTREACHED().<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sync/notifier/registration_manager.h" #include <algorithm> #include <cstddef> #include <iterator> #include <string> #include <utility> #include "base/rand_util.h" #include "base/stl_util.h" #include "google/cacheinvalidation/include/invalidation-client.h" #include "google/cacheinvalidation/include/types.h" #include "sync/notifier/invalidation_util.h" namespace syncer { RegistrationManager::PendingRegistrationInfo::PendingRegistrationInfo() {} RegistrationManager::RegistrationStatus::RegistrationStatus( const invalidation::ObjectId& id, RegistrationManager* manager) : id(id), registration_manager(manager), enabled(true), state(invalidation::InvalidationListener::UNREGISTERED) { DCHECK(registration_manager); } RegistrationManager::RegistrationStatus::~RegistrationStatus() {} void RegistrationManager::RegistrationStatus::DoRegister() { CHECK(enabled); // We might be called explicitly, so stop the timer manually and // reset the delay. registration_timer.Stop(); delay = base::TimeDelta(); registration_manager->DoRegisterId(id); DCHECK(!last_registration_request.is_null()); } void RegistrationManager::RegistrationStatus::Disable() { enabled = false; state = invalidation::InvalidationListener::UNREGISTERED; registration_timer.Stop(); delay = base::TimeDelta(); } const int RegistrationManager::kInitialRegistrationDelaySeconds = 5; const int RegistrationManager::kRegistrationDelayExponent = 2; const double RegistrationManager::kRegistrationDelayMaxJitter = 0.5; const int RegistrationManager::kMinRegistrationDelaySeconds = 1; // 1 hour. const int RegistrationManager::kMaxRegistrationDelaySeconds = 60 * 60; RegistrationManager::RegistrationManager( invalidation::InvalidationClient* invalidation_client) : invalidation_client_(invalidation_client) { DCHECK(invalidation_client_); } RegistrationManager::~RegistrationManager() { DCHECK(CalledOnValidThread()); STLDeleteValues(&registration_statuses_); } ObjectIdSet RegistrationManager::UpdateRegisteredIds(const ObjectIdSet& ids) { DCHECK(CalledOnValidThread()); const ObjectIdSet& old_ids = GetRegisteredIds(); const ObjectIdSet& to_register = ids; ObjectIdSet to_unregister; std::set_difference(old_ids.begin(), old_ids.end(), ids.begin(), ids.end(), std::inserter(to_unregister, to_unregister.begin()), ObjectIdLessThan()); for (ObjectIdSet::const_iterator it = to_unregister.begin(); it != to_unregister.end(); ++it) { UnregisterId(*it); } for (ObjectIdSet::const_iterator it = to_register.begin(); it != to_register.end(); ++it) { if (!ContainsKey(registration_statuses_, *it)) { registration_statuses_.insert( std::make_pair(*it, new RegistrationStatus(*it, this))); } if (!IsIdRegistered(*it)) { TryRegisterId(*it, false /* is-retry */); } } return to_unregister; } void RegistrationManager::MarkRegistrationLost( const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { DVLOG(1) << "Attempt to mark non-existent registration for " << ObjectIdToString(id) << " as lost"; return; } if (!it->second->enabled) { return; } it->second->state = invalidation::InvalidationListener::UNREGISTERED; bool is_retry = !it->second->last_registration_request.is_null(); TryRegisterId(id, is_retry); } void RegistrationManager::MarkAllRegistrationsLost() { DCHECK(CalledOnValidThread()); for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { if (IsIdRegistered(it->first)) { MarkRegistrationLost(it->first); } } } void RegistrationManager::DisableId(const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { DVLOG(1) << "Attempt to disable non-existent registration for " << ObjectIdToString(id); return; } it->second->Disable(); } // static double RegistrationManager::CalculateBackoff( double retry_interval, double initial_retry_interval, double min_retry_interval, double max_retry_interval, double backoff_exponent, double jitter, double max_jitter) { // scaled_jitter lies in [-max_jitter, max_jitter]. double scaled_jitter = jitter * max_jitter; double new_retry_interval = (retry_interval == 0.0) ? (initial_retry_interval * (1.0 + scaled_jitter)) : (retry_interval * (backoff_exponent + scaled_jitter)); return std::max(min_retry_interval, std::min(max_retry_interval, new_retry_interval)); } ObjectIdSet RegistrationManager::GetRegisteredIdsForTest() const { return GetRegisteredIds(); } RegistrationManager::PendingRegistrationMap RegistrationManager::GetPendingRegistrationsForTest() const { DCHECK(CalledOnValidThread()); PendingRegistrationMap pending_registrations; for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { const invalidation::ObjectId& id = it->first; RegistrationStatus* status = it->second; if (status->registration_timer.IsRunning()) { pending_registrations[id].last_registration_request = status->last_registration_request; pending_registrations[id].registration_attempt = status->last_registration_attempt; pending_registrations[id].delay = status->delay; pending_registrations[id].actual_delay = status->registration_timer.GetCurrentDelay(); } } return pending_registrations; } void RegistrationManager::FirePendingRegistrationsForTest() { DCHECK(CalledOnValidThread()); for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { if (it->second->registration_timer.IsRunning()) { it->second->DoRegister(); } } } double RegistrationManager::GetJitter() { // |jitter| lies in [-1.0, 1.0), which is low-biased, but only // barely. // // TODO(akalin): Fix the bias. return 2.0 * base::RandDouble() - 1.0; } void RegistrationManager::TryRegisterId(const invalidation::ObjectId& id, bool is_retry) { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { NOTREACHED() << "TryRegisterId called on " << ObjectIdToString(id) << " which is not in the registration map"; return; } RegistrationStatus* status = it->second; if (!status->enabled) { // Disabled, so do nothing. return; } status->last_registration_attempt = base::Time::Now(); if (is_retry) { // If we're a retry, we must have tried at least once before. DCHECK(!status->last_registration_request.is_null()); // delay = max(0, (now - last request) + next_delay) status->delay = (status->last_registration_request - status->last_registration_attempt) + status->next_delay; base::TimeDelta delay = (status->delay <= base::TimeDelta()) ? base::TimeDelta() : status->delay; DVLOG(2) << "Registering " << ObjectIdToString(id) << " in " << delay.InMilliseconds() << " ms"; status->registration_timer.Stop(); status->registration_timer.Start(FROM_HERE, delay, status, &RegistrationManager::RegistrationStatus::DoRegister); double next_delay_seconds = CalculateBackoff(static_cast<double>(status->next_delay.InSeconds()), kInitialRegistrationDelaySeconds, kMinRegistrationDelaySeconds, kMaxRegistrationDelaySeconds, kRegistrationDelayExponent, GetJitter(), kRegistrationDelayMaxJitter); status->next_delay = base::TimeDelta::FromSeconds(static_cast<int64>(next_delay_seconds)); DVLOG(2) << "New next delay for " << ObjectIdToString(id) << " is " << status->next_delay.InSeconds() << " seconds"; } else { DVLOG(2) << "Not a retry -- registering " << ObjectIdToString(id) << " immediately"; status->delay = base::TimeDelta(); status->next_delay = base::TimeDelta(); status->DoRegister(); } } void RegistrationManager::DoRegisterId(const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); invalidation_client_->Register(id); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { NOTREACHED() << "DoRegisterId called on " << ObjectIdToString(id) << " which is not in the registration map"; return; } it->second->state = invalidation::InvalidationListener::REGISTERED; it->second->last_registration_request = base::Time::Now(); } void RegistrationManager::UnregisterId(const invalidation::ObjectId& id) { DCHECK(CalledOnValidThread()); invalidation_client_->Unregister(id); RegistrationStatusMap::iterator it = registration_statuses_.find(id); if (it == registration_statuses_.end()) { NOTREACHED() << "UnregisterId called on " << ObjectIdToString(id) << " which is not in the registration map"; return; } delete it->second; registration_statuses_.erase(it); } ObjectIdSet RegistrationManager::GetRegisteredIds() const { DCHECK(CalledOnValidThread()); ObjectIdSet ids; for (RegistrationStatusMap::const_iterator it = registration_statuses_.begin(); it != registration_statuses_.end(); ++it) { if (IsIdRegistered(it->first)) { ids.insert(it->first); } } return ids; } bool RegistrationManager::IsIdRegistered( const invalidation::ObjectId& id) const { DCHECK(CalledOnValidThread()); RegistrationStatusMap::const_iterator it = registration_statuses_.find(id); return it != registration_statuses_.end() && it->second->state == invalidation::InvalidationListener::REGISTERED; } } // namespace syncer <|endoftext|>
<commit_before>#include "RobustMatcher.h" // Clear matches for which NN ratio is > than threshold // return the number of removed points // (corresponding entries being cleared, // i.e. size will be 0) int RobustMatcher::ratioTest(vector<vector<DMatch> > &matches) { int removed=0; // for all matches for (vector<vector<DMatch> >::iterator matchIterator = matches.begin(); matchIterator != matches.end(); ++matchIterator) { // if 2 NN has been identified if (matchIterator->size() > 1) { // check distance ratio if ((*matchIterator)[0].distance / (*matchIterator)[1].distance > ratio) { matchIterator->clear(); // remove match removed++; } } else { // does not have 2 neighbors matchIterator->clear(); // remove match removed++; } } return removed; } // Identify good matches using RANSAC // Return fundemental matrix Mat RobustMatcher::ransacTest(const vector<DMatch>& matches, const vector<KeyPoint>& keypoints1, const vector<KeyPoint>& keypoints2, vector<DMatch>& outMatches) { // Convert keypoints into Point2f vector<Point2f> points1, points2; for (vector<DMatch>::const_iterator it = matches.begin(); it != matches.end(); ++it) { // Get the position of left keypoints float x = keypoints1[it->queryIdx].pt.x; float y = keypoints1[it->queryIdx].pt.y; points1.push_back(Point2f(x,y)); // Get the position of right keypoints x = keypoints2[it->trainIdx].pt.x; y = keypoints2[it->trainIdx].pt.y; points2.push_back(Point2f(x,y)); } // Compute F matrix using RANSAC vector<uchar> inliers(points1.size(),0); Mat fundemental= findFundamentalMat( Mat(points1), Mat(points2), // matching points inliers, // match status (inlier or outlier) CV_FM_RANSAC, // RANSAC method distance, // distance to epipolar line confidence); // confidence probability // extract the surviving (inliers) matches vector<uchar>::const_iterator itIn = inliers.begin(); vector<DMatch>::const_iterator itM = matches.begin(); // for all matches for ( ; itIn != inliers.end(); ++itIn, ++itM) { if (*itIn) // it is a valid match { outMatches.push_back(*itM); } } if (refineF) { // The F matrix will be recomputed with // all accepted matches // Convert keypoints into Point2f // for final F computation points1.clear(); points2.clear(); for (vector<DMatch>::const_iterator it = outMatches.begin(); it != outMatches.end(); ++it) { // Get the position of left keypoints float x = keypoints1[it->queryIdx].pt.x; float y = keypoints1[it->queryIdx].pt.y; points1.push_back(Point2f(x,y)); // Get the position of right keypoints x = keypoints2[it->trainIdx].pt.x; y = keypoints2[it->trainIdx].pt.y; points2.push_back(Point2f(x,y)); } // Compute 8-point F from all accepted matches fundemental = findFundamentalMat(Mat(points1),Mat(points2), CV_FM_8POINT); } return fundemental; } // Insert symmetrical matches in symMatches vector void RobustMatcher::symmetryTest(const vector<vector<DMatch> >& matches1, const vector<vector<DMatch> >& matches2, vector<DMatch>& symMatches) { // for all matches image 1 -> image 2 for (vector<vector<DMatch> >::const_iterator matchIterator1 = matches1.begin(); matchIterator1 != matches1.end(); ++matchIterator1) { // ignore deleted matches if (matchIterator1->size() < 2) { continue; } // for all matches image 2 -> image 1 for (vector<vector<DMatch> >::const_iterator matchIterator2 = matches2.begin(); matchIterator2 != matches2.end(); ++matchIterator2) { // ignore deleted matches if (matchIterator2->size() < 2) { continue; } // Match symmetry test if ((*matchIterator1)[0].queryIdx == (*matchIterator2)[0].trainIdx && (*matchIterator2)[0].queryIdx == (*matchIterator1)[0].trainIdx) { // add symmetrical match symMatches.push_back( DMatch((*matchIterator1)[0].queryIdx, (*matchIterator1)[0].trainIdx, (*matchIterator1)[0].distance)); break; // next match in image 1 -> image 2 } } } } // Match feature points using symmetry test and RANSAC // returns fundemental matrix Mat RobustMatcher::match(vector<KeyPoint>& keypoints1, vector<KeyPoint>& keypoints2, Mat& descriptors1, Mat& descriptors2, vector<DMatch>& matches) { // Construction of the matcher FlannBasedMatcher matcher; // from image 1 to image 2 // based on k nearest neighbors (with k=2) vector<vector<DMatch> > matches1; // return 2 nearest neighbours matcher.knnMatch(descriptors1,descriptors2, matches1, 2); // from image 2 to image 1 // based on k nearest neighbours (with k=2) vector<vector<DMatch> > matches2; // return 2 nearest neighbours matcher.knnMatch(descriptors2,descriptors1, matches2, 2); // 3. Remove matches for which NN ratio is > than threshold // clean image 1 -> image 2 matches int removed = ratioTest(matches1); // clean image 2 -> image 1 matches removed = ratioTest(matches2); // 4. Remove non-symmetrical matches vector<DMatch> symMatches; symmetryTest(matches1,matches2,symMatches); // 5. Validate matches using RANSAC Mat fundemental= ransacTest(symMatches, keypoints1, keypoints2, matches); // return the found fundemental matrix return fundemental; } <commit_msg>Sometimes too many matches were removed. This lead to a failed assertion within opencv when calculating a fundamental matrix.<commit_after>#include "RobustMatcher.h" // Clear matches for which NN ratio is > than threshold // return the number of removed points // (corresponding entries being cleared, // i.e. size will be 0) int RobustMatcher::ratioTest(vector<vector<DMatch> > &matches) { int removed=0; // for all matches for (vector<vector<DMatch> >::iterator matchIterator = matches.begin(); matchIterator != matches.end(); ++matchIterator) { // if 2 NN has been identified if (matchIterator->size() > 1) { // check distance ratio if ((*matchIterator)[0].distance / (*matchIterator)[1].distance > ratio) { matchIterator->clear(); // remove match removed++; } } else { // does not have 2 neighbors matchIterator->clear(); // remove match removed++; } } return removed; } // Identify good matches using RANSAC // Return fundemental matrix Mat RobustMatcher::ransacTest(const vector<DMatch>& matches, const vector<KeyPoint>& keypoints1, const vector<KeyPoint>& keypoints2, vector<DMatch>& outMatches) { // Convert keypoints into Point2f vector<Point2f> points1, points2; for (vector<DMatch>::const_iterator it = matches.begin(); it != matches.end(); ++it) { // Get the position of left keypoints float x = keypoints1[it->queryIdx].pt.x; float y = keypoints1[it->queryIdx].pt.y; points1.push_back(Point2f(x,y)); // Get the position of right keypoints x = keypoints2[it->trainIdx].pt.x; y = keypoints2[it->trainIdx].pt.y; points2.push_back(Point2f(x,y)); } // Compute F matrix using RANSAC vector<uchar> inliers(points1.size(),0); Mat fundemental= findFundamentalMat( Mat(points1), Mat(points2), // matching points inliers, // match status (inlier or outlier) CV_FM_RANSAC, // RANSAC method distance, // distance to epipolar line confidence); // confidence probability // extract the surviving (inliers) matches vector<uchar>::const_iterator itIn = inliers.begin(); vector<DMatch>::const_iterator itM = matches.begin(); // for all matches for ( ; itIn != inliers.end(); ++itIn, ++itM) { if (*itIn) // it is a valid match { outMatches.push_back(*itM); } } if (refineF) { // The F matrix will be recomputed with // all accepted matches // Convert keypoints into Point2f // for final F computation points1.clear(); points2.clear(); for (vector<DMatch>::const_iterator it = outMatches.begin(); it != outMatches.end(); ++it) { // Get the position of left keypoints float x = keypoints1[it->queryIdx].pt.x; float y = keypoints1[it->queryIdx].pt.y; points1.push_back(Point2f(x,y)); // Get the position of right keypoints x = keypoints2[it->trainIdx].pt.x; y = keypoints2[it->trainIdx].pt.y; points2.push_back(Point2f(x,y)); } // Compute 8-point F from all accepted matches fundemental = findFundamentalMat(Mat(points1),Mat(points2), CV_FM_8POINT); } return fundemental; } // Insert symmetrical matches in symMatches vector void RobustMatcher::symmetryTest(const vector<vector<DMatch> >& matches1, const vector<vector<DMatch> >& matches2, vector<DMatch>& symMatches) { // for all matches image 1 -> image 2 for (vector<vector<DMatch> >::const_iterator matchIterator1 = matches1.begin(); matchIterator1 != matches1.end(); ++matchIterator1) { // ignore deleted matches if (matchIterator1->size() < 2) { continue; } // for all matches image 2 -> image 1 for (vector<vector<DMatch> >::const_iterator matchIterator2 = matches2.begin(); matchIterator2 != matches2.end(); ++matchIterator2) { // ignore deleted matches if (matchIterator2->size() < 2) { continue; } // Match symmetry test if ((*matchIterator1)[0].queryIdx == (*matchIterator2)[0].trainIdx && (*matchIterator2)[0].queryIdx == (*matchIterator1)[0].trainIdx) { // add symmetrical match symMatches.push_back( DMatch((*matchIterator1)[0].queryIdx, (*matchIterator1)[0].trainIdx, (*matchIterator1)[0].distance)); break; // next match in image 1 -> image 2 } } } } // Match feature points using symmetry test and RANSAC // returns fundemental matrix Mat RobustMatcher::match(vector<KeyPoint>& keypoints1, vector<KeyPoint>& keypoints2, Mat& descriptors1, Mat& descriptors2, vector<DMatch>& matches) { // Construction of the matcher FlannBasedMatcher matcher; vector<DMatch> symMatches; bool findMatches = true; while(findMatches) { symMatches.clear(); // from image 1 to image 2 // based on k nearest neighbors (with k=2) vector<vector<DMatch> > matches1; // return 2 nearest neighbours matcher.knnMatch(descriptors1,descriptors2, matches1, 2); // from image 2 to image 1 // based on k nearest neighbours (with k=2) vector<vector<DMatch> > matches2; // return 2 nearest neighbours matcher.knnMatch(descriptors2,descriptors1, matches2, 2); // 3. Remove matches for which NN ratio is > than threshold // clean image 1 -> image 2 matches int removed = ratioTest(matches1); // clean image 2 -> image 1 matches removed = ratioTest(matches2); // 4. Remove non-symmetrical matches symmetryTest(matches1,matches2,symMatches); if (symMatches.size() > 6) { findMatches = false; } else { if (ratio > 1) { throw runtime_error("RobustMatcher cannot find enough matches to create fundamental matrix"); } ratio += 0.01f; } } // 5. Validate matches using RANSAC Mat fundemental= ransacTest(symMatches, keypoints1, keypoints2, matches); // return the found fundemental matrix return fundemental; } <|endoftext|>
<commit_before>#include "CollimationTrackingAction.h" #include <iostream> #include "G4VProcess.hh" #include "G4ThreeVector.hh" #include "G4ParticleDefinition.hh" #include "G4Proton.hh" CollimationTrackingAction::CollimationTrackingAction() {} void CollimationTrackingAction::PreUserTrackingAction(const G4Track* Track) { /* const G4ParticleDefinition* particle = Track->GetParticleDefinition(); if(particle == G4Proton::ProtonDefinition()) { const G4VProcess* pr = Track->GetCreatorProcess(); if(pr) { if(pr->GetProcessName() == "protonInelastic") { double KE = Track->GetKineticEnergy()/CLHEP::GeV; if(KE > 1000) { std::cout << "PROTON INELASTIC: " << KE << std::endl; std::cout << Track->GetTrackID() << "\t" << Track->GetParentID() << std::endl; //const G4ThreeVector& pos = Track->GetPreStepPoint(); //std::cout << pos / CLHEP::m << std::endl; } } } } else { //Track->SetTrackStatus(fStopAndKill); } */ //G4StepStatus Tstatus = Track->GetStep()->GetPreStepPoint()->GetStepStatus(); //if(Tstatus == fGeomBoundary) //Record initial impact point /* if(Track->GetParticleDefinition()->GetAtomicMass() > 1) { std::cout << "GetCharge() - pre: " << Track->GetDynamicParticle()->GetCharge() << std::endl; } */ } void CollimationTrackingAction::PostUserTrackingAction(const G4Track* Track) { /* //Check if we have impacted G4StepPoint* point_in = Track->GetStep()->GetPreStepPoint(); G4TouchableHandle touch_in = point_in->GetTouchableHandle(); G4VPhysicalVolume* volume = touch_in->GetVolume(); if(volume->GetName().substr(0,3) == "jaw") { // std::cout << "PARTICLE INTERACTED" << std::endl; EventAction->OutputParticle->interacted = 1; } */ G4StepStatus Tstatus = Track->GetStep()->GetPostStepPoint()->GetStepStatus(); // if (Tstatus == fWorldBoundary && Track->GetParticleDefinition() == G4Proton::ProtonDefinition()) if (Tstatus == fWorldBoundary && Track->GetParticleDefinition()->GetPDGCharge() != 0) { // std::cout << "AT EXIT PLANE" << std::endl; if(Track->GetKineticEnergy() > ReferenceEnergy*RelativeEnergyCut && Track->GetKineticEnergy() > AbsoluteEnergyCut) { G4Stuff exit_particle; exit_particle.x = Track->GetPosition().x() / CLHEP::m; exit_particle.y = Track->GetPosition().y() / CLHEP::m; exit_particle.px = Track->GetMomentum().x() / CLHEP::GeV; exit_particle.py = Track->GetMomentum().y() / CLHEP::GeV; double p2 = pow(Track->GetMomentum().x()/CLHEP::GeV,2) + pow(Track->GetMomentum().y()/CLHEP::GeV,2) + pow(Track->GetMomentum().z()/CLHEP::GeV,2); exit_particle.p = sqrt(pow(p2 + pow(Track->GetParticleDefinition()->GetPDGMass()/CLHEP::GeV,2)); exit_particle.pdgid = Track->GetParticleDefinition()->GetPDGEncoding(); exit_particle.z = Track->GetParticleDefinition()->GetAtomicNumber(); exit_particle.a = Track->GetParticleDefinition()->GetAtomicMass(); exit_particle.m = Track->GetParticleDefinition()->GetPDGMass()/CLHEP::GeV; exit_particle.q = Track->GetDynamicParticle()->GetCharge(); EventAction->AddOutputParticle(exit_particle); // std::cout << "TrackEnd: " << Track->GetParticleDefinition()->GetParticleName() << "\t" << Track->GetKineticEnergy() /CLHEP::GeV << "\t" << Track->GetMomentum().z()/CLHEP::GeV << std::endl; /* if(exit_particle.z > 1 && exit_particle.a > 1) { std::cout << "GetCharge() - post: " << Track->GetDynamicParticle()->GetCharge() << std::endl; } */ //double p = Track->GetKineticEnergy(); // std::cout << "KEEPING: ";// << std::endl; // std::cout << x / CLHEP::m << "\t" << px << "\t" << y << "\t" << py << "\t" << p << std::endl; // EventAction->AddOutputParticle(x,px,y,py,p); // G4double energy = aStep->GetTrack()->GetKineticEnergy(); // EventAction->IncrementProtonCount(); } } } void CollimationTrackingAction::SetEventAction(CollimationEventAction* ev) { EventAction = ev; } void CollimationTrackingAction::SetReferenceEnergy(double e0) { ReferenceEnergy = e0; } void CollimationTrackingAction::SetAbsoluteEnergyCut(double cut) { AbsoluteEnergyCut = cut; } void CollimationTrackingAction::SetRigidityCut(double cut) { RigidityCut = cut; } void CollimationTrackingAction::SetRelativeEnergyCut(double cut) { RelativeEnergyCut = cut; } <commit_msg>Learn to type..<commit_after>#include "CollimationTrackingAction.h" #include <iostream> #include "G4VProcess.hh" #include "G4ThreeVector.hh" #include "G4ParticleDefinition.hh" #include "G4Proton.hh" CollimationTrackingAction::CollimationTrackingAction() {} void CollimationTrackingAction::PreUserTrackingAction(const G4Track* Track) { /* const G4ParticleDefinition* particle = Track->GetParticleDefinition(); if(particle == G4Proton::ProtonDefinition()) { const G4VProcess* pr = Track->GetCreatorProcess(); if(pr) { if(pr->GetProcessName() == "protonInelastic") { double KE = Track->GetKineticEnergy()/CLHEP::GeV; if(KE > 1000) { std::cout << "PROTON INELASTIC: " << KE << std::endl; std::cout << Track->GetTrackID() << "\t" << Track->GetParentID() << std::endl; //const G4ThreeVector& pos = Track->GetPreStepPoint(); //std::cout << pos / CLHEP::m << std::endl; } } } } else { //Track->SetTrackStatus(fStopAndKill); } */ //G4StepStatus Tstatus = Track->GetStep()->GetPreStepPoint()->GetStepStatus(); //if(Tstatus == fGeomBoundary) //Record initial impact point /* if(Track->GetParticleDefinition()->GetAtomicMass() > 1) { std::cout << "GetCharge() - pre: " << Track->GetDynamicParticle()->GetCharge() << std::endl; } */ } void CollimationTrackingAction::PostUserTrackingAction(const G4Track* Track) { /* //Check if we have impacted G4StepPoint* point_in = Track->GetStep()->GetPreStepPoint(); G4TouchableHandle touch_in = point_in->GetTouchableHandle(); G4VPhysicalVolume* volume = touch_in->GetVolume(); if(volume->GetName().substr(0,3) == "jaw") { // std::cout << "PARTICLE INTERACTED" << std::endl; EventAction->OutputParticle->interacted = 1; } */ G4StepStatus Tstatus = Track->GetStep()->GetPostStepPoint()->GetStepStatus(); // if (Tstatus == fWorldBoundary && Track->GetParticleDefinition() == G4Proton::ProtonDefinition()) if (Tstatus == fWorldBoundary && Track->GetParticleDefinition()->GetPDGCharge() != 0) { // std::cout << "AT EXIT PLANE" << std::endl; if(Track->GetKineticEnergy() > ReferenceEnergy*RelativeEnergyCut && Track->GetKineticEnergy() > AbsoluteEnergyCut) { G4Stuff exit_particle; exit_particle.x = Track->GetPosition().x() / CLHEP::m; exit_particle.y = Track->GetPosition().y() / CLHEP::m; exit_particle.px = Track->GetMomentum().x() / CLHEP::GeV; exit_particle.py = Track->GetMomentum().y() / CLHEP::GeV; double p2 = pow(Track->GetMomentum().x()/CLHEP::GeV,2) + pow(Track->GetMomentum().y()/CLHEP::GeV,2) + pow(Track->GetMomentum().z()/CLHEP::GeV,2); exit_particle.p = sqrt(p2 + pow(Track->GetParticleDefinition()->GetPDGMass()/CLHEP::GeV,2)); exit_particle.pdgid = Track->GetParticleDefinition()->GetPDGEncoding(); exit_particle.z = Track->GetParticleDefinition()->GetAtomicNumber(); exit_particle.a = Track->GetParticleDefinition()->GetAtomicMass(); exit_particle.m = Track->GetParticleDefinition()->GetPDGMass()/CLHEP::GeV; exit_particle.q = Track->GetDynamicParticle()->GetCharge(); EventAction->AddOutputParticle(exit_particle); // std::cout << "TrackEnd: " << Track->GetParticleDefinition()->GetParticleName() << "\t" << Track->GetKineticEnergy() /CLHEP::GeV << "\t" << Track->GetMomentum().z()/CLHEP::GeV << std::endl; /* if(exit_particle.z > 1 && exit_particle.a > 1) { std::cout << "GetCharge() - post: " << Track->GetDynamicParticle()->GetCharge() << std::endl; } */ //double p = Track->GetKineticEnergy(); // std::cout << "KEEPING: ";// << std::endl; // std::cout << x / CLHEP::m << "\t" << px << "\t" << y << "\t" << py << "\t" << p << std::endl; // EventAction->AddOutputParticle(x,px,y,py,p); // G4double energy = aStep->GetTrack()->GetKineticEnergy(); // EventAction->IncrementProtonCount(); } } } void CollimationTrackingAction::SetEventAction(CollimationEventAction* ev) { EventAction = ev; } void CollimationTrackingAction::SetReferenceEnergy(double e0) { ReferenceEnergy = e0; } void CollimationTrackingAction::SetAbsoluteEnergyCut(double cut) { AbsoluteEnergyCut = cut; } void CollimationTrackingAction::SetRigidityCut(double cut) { RigidityCut = cut; } void CollimationTrackingAction::SetRelativeEnergyCut(double cut) { RelativeEnergyCut = cut; } <|endoftext|>
<commit_before>/* * Copyright (C) Lynn Tran * * Implementation of war card game using Queue and OOP */ #include<string> #include<iostream> #include<queue> #define DECKSIZE 52 using namespace std; /* * The deck will start from 0 to 51 where the suits are clubs, diamonds, hearts and spades * respectively. */ class Card { private: int value; public: Card(int thisValue){ value = thisValue; }; int getRank(Card c){ return c.value % 13; }; int getSuit(Card c){ return (c.value % 52) / 13; }; void showCard(Card c){ switch (getRank(c)){ case 0: cout << "Deuce of "; break; case 1: cout << "Three of "; break; case 2: cout << "Four of "; break; case 3: cout << "Five of "; break; case 4: cout << "Six of "; break; case 5: cout << "Seven of "; break; case 6: cout << "Eight of "; break; case 7: cout << "Nine of "; break; case 8: cout << "Ten of "; break; case 9: cout << "Jack of "; break; case 10: cout << "Queen of "; break; case 11: cout << "King of "; break; case 12: cout << "Ace of "; break; } switch (getSuit(c)){ case 0: cout << "Clubs\n"; break; case 1: cout << "Diamonds\n"; break; case 2: cout << "Hearts\n"; break; case 3: cout << "Spades\n"; break; } }; }; class Deck { public: Deck(){ queue<int> A, B; }; void shuffle(); void dealCard(queue<int> Deck){ }; void playCard(); }; class Hand { public: int getCardsCount(); void showHand(Card c); }; int main(){ } <commit_msg>Working on the Deck<commit_after>/* * Copyright (C) Lynn Tran * * Implementation of war card game using Queue and OOP */ #include<string> #include<iostream> #include<queue> #define DECKSIZE 52 using namespace std; /* * The deck will start from 0 to 51 where the suits are clubs, diamonds, hearts and spades * respectively. */ class Card { private: int value; public: Card(int thisValue){ value = thisValue; }; int getRank(Card c){ return c.value % 13; }; int getSuit(Card c){ return (c.value % 52) / 13; }; void showCard(Card c){ switch (getRank(c)){ case 0: cout << "Deuce of "; break; case 1: cout << "Three of "; break; case 2: cout << "Four of "; break; case 3: cout << "Five of "; break; case 4: cout << "Six of "; break; case 5: cout << "Seven of "; break; case 6: cout << "Eight of "; break; case 7: cout << "Nine of "; break; case 8: cout << "Ten of "; break; case 9: cout << "Jack of "; break; case 10: cout << "Queen of "; break; case 11: cout << "King of "; break; case 12: cout << "Ace of "; break; } switch (getSuit(c)){ case 0: cout << "Clubs\n"; break; case 1: cout << "Diamonds\n"; break; case 2: cout << "Hearts\n"; break; case 3: cout << "Spades\n"; break; } }; }; class Deck { public: Deck(queue<int> deck, queue<int> a, queue<int> b){ DeckQ = deck; A = a; B = b; }; void shuffle(); void dealCard(queue<int> deck){ while(!deck.empty()){ A.push(deck.pop()); B.push(deck.pop()); } }; void playCard(queue<int> A, queue<int> B){ }; private: queue<int> DeckQ; queue<int> A; queue<int> B; }; class Hand { public: int getCardsCount(); void showHand(Card c); }; int main(){ } <|endoftext|>
<commit_before>/* This program will add histograms from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hadd targetfile source1 source2 ... if the source files contains histograms and Trees, one can skip the Trees with hadd -T targetfile source1 source2 ... Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch */ #include <string> #include "TChain.h" #include "TFile.h" #include "TH1.h" #include "TKey.h" #include "Riostream.h" TList *FileList; TFile *Target, *Source; Bool_t noTrees; void MergeRootfile( TDirectory *target, TList *sourcelist ); int main( int argc, char **argv ) { if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) { cout << "Usage: " << argv[0] << " [-f] [-T] targetfile source1 source2 [source3 ...]" << endl; cout << "This program will add histograms from a list of root files and write them" << endl; cout << "to a target root file. The target file is newly created and must not " << endl; cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl; cout << "Supply at least two source files for this to make sense... ;-)" << endl; cout << "If the first argument is -T, Trees are not merged" <<endl; return 1; } FileList = new TList(); Bool_t force = (!strcmp(argv[1],"-f") || !strcmp(argv[2],"-f")); noTrees = (!strcmp(argv[1],"-T") || !strcmp(argv[2],"-T")); int ffirst = 2; if (force) ffirst++; if (noTrees) ffirst++; cout << "Target file: " << argv[ffirst-1] << endl; Target = TFile::Open( argv[ffirst-1], (force?"RECREATE":"CREATE") ); if (!Target || Target->IsZombie()) { cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl; cerr << "Pass \"-f\" argument to force re-creation of output file." << endl; exit(1); } // by default hadd can merge Trees in a file that can go up to 100 Gbytes Long64_t maxsize = 10000000000; //100GB TTree::SetMaxTreeSize(maxsize); for ( int i = ffirst; i < argc; i++ ) { cout << "Source file " << i-ffirst+1 << ": " << argv[i] << endl; Source = TFile::Open( argv[i] ); FileList->Add(Source); } MergeRootfile( Target, FileList ); return 0; } void MergeRootfile( TDirectory *target, TList *sourcelist ) { // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory TChain *globChain = 0; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key, *oldkey=0; //gain time, do not add the objects in the list in memory TH1::AddDirectory(kFALSE); while ( (key = (TKey*)nextkey())) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue; // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) { // descendant of TH1 -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; TList listH; // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName()); if (key2) { listH.Add( key2->ReadObj() ); h1->Merge(&listH); listH.Clear(); } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TTree" ) ) { // loop over all source files create a chain of Trees "globChain" if (!noTrees) { TString obj_name; if (path.Length()) { obj_name = path + "/" + obj->GetName(); } else { obj_name = obj->GetName(); } globChain = new TChain(obj_name); globChain->Add(first_source->GetName()); TFile *nextsource = (TFile*)sourcelist->After( first_source ); // const char* file_name = nextsource->GetName(); // cout << "file name " << file_name << endl; while ( nextsource ) { globChain->Add(nextsource->GetName()); nextsource = (TFile*)sourcelist->After( nextsource ); } } } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, sourcelist ); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); //!!if the object is a tree, it is stored in globChain... if(obj->IsA()->InheritsFrom( "TTree" )) { if (!noTrees) globChain->Merge(target->GetFile(),0,"keep"); } else { obj->Write( key->GetName() ); } } oldkey = key; } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->SaveSelf(kTRUE); } <commit_msg>Workaround to define a large constant (100 Gbytes) on some compilers<commit_after>/* This program will add histograms from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hadd targetfile source1 source2 ... if the source files contains histograms and Trees, one can skip the Trees with hadd -T targetfile source1 source2 ... Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch */ #include <string> #include "TChain.h" #include "TFile.h" #include "TH1.h" #include "TKey.h" #include "Riostream.h" TList *FileList; TFile *Target, *Source; Bool_t noTrees; void MergeRootfile( TDirectory *target, TList *sourcelist ); int main( int argc, char **argv ) { if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) { cout << "Usage: " << argv[0] << " [-f] [-T] targetfile source1 source2 [source3 ...]" << endl; cout << "This program will add histograms from a list of root files and write them" << endl; cout << "to a target root file. The target file is newly created and must not " << endl; cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl; cout << "Supply at least two source files for this to make sense... ;-)" << endl; cout << "If the first argument is -T, Trees are not merged" <<endl; return 1; } FileList = new TList(); Bool_t force = (!strcmp(argv[1],"-f") || !strcmp(argv[2],"-f")); noTrees = (!strcmp(argv[1],"-T") || !strcmp(argv[2],"-T")); int ffirst = 2; if (force) ffirst++; if (noTrees) ffirst++; cout << "Target file: " << argv[ffirst-1] << endl; Target = TFile::Open( argv[ffirst-1], (force?"RECREATE":"CREATE") ); if (!Target || Target->IsZombie()) { cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl; cerr << "Pass \"-f\" argument to force re-creation of output file." << endl; exit(1); } // by default hadd can merge Trees in a file that can go up to 100 Gbytes Long64_t maxsize = 100000000; //100GB maxsize *= 100; //to bypass some compiler limitations with big constants TTree::SetMaxTreeSize(maxsize); for ( int i = ffirst; i < argc; i++ ) { cout << "Source file " << i-ffirst+1 << ": " << argv[i] << endl; Source = TFile::Open( argv[i] ); FileList->Add(Source); } MergeRootfile( Target, FileList ); return 0; } void MergeRootfile( TDirectory *target, TList *sourcelist ) { // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory TChain *globChain = 0; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key, *oldkey=0; //gain time, do not add the objects in the list in memory TH1::AddDirectory(kFALSE); while ( (key = (TKey*)nextkey())) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue; // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) { // descendant of TH1 -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; TList listH; // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName()); if (key2) { listH.Add( key2->ReadObj() ); h1->Merge(&listH); listH.Clear(); } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TTree" ) ) { // loop over all source files create a chain of Trees "globChain" if (!noTrees) { TString obj_name; if (path.Length()) { obj_name = path + "/" + obj->GetName(); } else { obj_name = obj->GetName(); } globChain = new TChain(obj_name); globChain->Add(first_source->GetName()); TFile *nextsource = (TFile*)sourcelist->After( first_source ); // const char* file_name = nextsource->GetName(); // cout << "file name " << file_name << endl; while ( nextsource ) { globChain->Add(nextsource->GetName()); nextsource = (TFile*)sourcelist->After( nextsource ); } } } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, sourcelist ); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); //!!if the object is a tree, it is stored in globChain... if(obj->IsA()->InheritsFrom( "TTree" )) { if (!noTrees) globChain->Merge(target->GetFile(),0,"keep"); } else { obj->Write( key->GetName() ); } } oldkey = key; } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->SaveSelf(kTRUE); } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); imshow("webcam", image); // thresholds on dark regions Mat black, blurred_gray, threshold_gray; cvtColor(image, black, CV_BGR2GRAY); blur(black, blurred_gray, Size(width/4.5,height/9)); equalizeHist(blurred_gray, blurred_gray); bitwise_not(blurred_gray, blurred_gray); threshold(blurred_gray, threshold_gray, 220, 255, THRESH_BINARY); imshow("threshold", threshold_gray); Mat topHat; Mat kernel = Mat::ones(15,15,CV_8UC1); morphologyEx(black, topHat, MORPH_TOPHAT, kernel); imshow("tophat", topHat); /* split(image, channel); channel[0] = channel[0].mul(black); channel[1] = channel[1].mul(black); channel[2] = channel[2].mul(black); merge(channel, 3, image); */ // imshow("yox", image); //do some weird morphological closing thing // Mat channel[3]; /* Mat canny; Canny(image, canny, 0, 50); imshow("canny", canny); */ /* Mat fill = image.clone(); Point seed(rand()%width, rand()%height); floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25)); imshow("fill", fill); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); imshow("webcam", image); // thresholds on dark regions Mat gray, blurred_gray, threshold_gray; cvtColor(image, gray, CV_BGR2GRAY); blur(gray, blurred_gray, Size(width/4.5,height/9)); equalizeHist(blurred_gray, blurred_gray); bitwise_not(blurred_gray, blurred_gray); threshold(blurred_gray, threshold_gray, 220, 255, THRESH_BINARY); imshow("threshold", threshold_gray); Mat topHat; Mat kernel = Mat::ones(15,15,CV_8UC1); morphologyEx(blurred_gray, topHat, MORPH_TOPHAT, kernel); imshow("tophat", topHat); /* split(image, channel); channel[0] = channel[0].mul(black); channel[1] = channel[1].mul(black); channel[2] = channel[2].mul(black); merge(channel, 3, image); */ // imshow("yox", image); //do some weird morphological closing thing // Mat channel[3]; /* Mat canny; Canny(image, canny, 0, 50); imshow("canny", canny); */ /* Mat fill = image.clone(); Point seed(rand()%width, rand()%height); floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25)); imshow("fill", fill); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow 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 "tensorflow/compiler/xla/pjrt/utils.h" #include "absl/container/flat_hash_set.h" #include "tensorflow/compiler/xla/client/executable_build_options.h" #include "tensorflow/compiler/xla/client/xla_computation.h" #include "tensorflow/compiler/xla/service/hlo.pb.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/hlo_sharding.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace xla { namespace { StatusOr<Shape> GetShardedShape(const Shape& shape, const OpSharding& sharding) { if (sharding.type() == OpSharding::TUPLE) { if (!shape.IsTuple()) { return InvalidArgument( "Got tuple OpSharding (%s) for non-tuple shape (%s)", sharding.DebugString(), shape.ToString()); } if (sharding.tuple_shardings_size() != shape.tuple_shapes_size()) { return InvalidArgument( "Got mismatched OpSharding tuple size (%d) and shape tuple size (%d)." " (OpSharding: %s, shape: %s)", sharding.tuple_shardings_size(), shape.tuple_shapes_size(), sharding.DebugString(), shape.ToString()); } std::vector<Shape> sharded_subshapes; for (int i = 0; i < shape.tuple_shapes_size(); ++i) { TF_ASSIGN_OR_RETURN( Shape sharded_subshape, GetShardedShape(shape.tuple_shapes(i), sharding.tuple_shardings(i))); sharded_subshapes.emplace_back(std::move(sharded_subshape)); } return ShapeUtil::MakeTupleShape(sharded_subshapes); } TF_ASSIGN_OR_RETURN(HloSharding hlo_sharding, HloSharding::FromProto(sharding)); return hlo_sharding.TileShape(shape); } StatusOr<Shape> GetShardedShape(const HloInstructionProto& instr) { const Shape unsharded_shape(instr.shape()); Shape sharded_shape; if (instr.has_sharding()) { TF_ASSIGN_OR_RETURN(sharded_shape, GetShardedShape(unsharded_shape, instr.sharding())); } else { sharded_shape = unsharded_shape; } LayoutUtil::ClearLayout(&sharded_shape); return sharded_shape; } // Returns sharded (argument shapes, result shape) without layouts. StatusOr<std::pair<std::vector<Shape>, Shape>> GetShardedProgramShapes( const XlaComputation& computation, const ProgramShape& program_shape) { std::vector<Shape> arg_shapes; arg_shapes.resize(program_shape.parameters_size()); Shape result_shape; for (const HloComputationProto& comp : computation.proto().computations()) { if (comp.id() != computation.proto().entry_computation_id()) { continue; } for (const HloInstructionProto& instr : comp.instructions()) { if (instr.opcode() == HloOpcodeString(HloOpcode::kParameter)) { if (instr.parameter_number() >= program_shape.parameters_size()) { return InvalidArgument( "Got invalid parameter number %d, expected %d parameters", instr.parameter_number(), program_shape.parameters_size()); } TF_ASSIGN_OR_RETURN(arg_shapes[instr.parameter_number()], GetShardedShape(instr)); } if (instr.id() == comp.root_id()) { if (result_shape.element_type() != PRIMITIVE_TYPE_INVALID) { return InvalidArgument("Found multiple root instructions"); } TF_ASSIGN_OR_RETURN(result_shape, GetShardedShape(instr)); } } } for (int i = 0; i < arg_shapes.size(); ++i) { if (arg_shapes[i].element_type() == PRIMITIVE_TYPE_INVALID) { return InvalidArgument("Couldn't find parameter %d", i); } } if (result_shape.element_type() == PRIMITIVE_TYPE_INVALID) { return InvalidArgument("Couldn't find root instruction"); } return std::make_pair(arg_shapes, result_shape); } } // namespace Status ParseDeviceAssignmentCompileOptions( bool compile_portable_executable, ExecutableBuildOptions* build_options, std::function<StatusOr<DeviceAssignment>(int, int)> GetDefaultDeviceAssignmentFunction, int* num_replicas, int* num_partitions, std::shared_ptr<DeviceAssignment>* device_assignment) { if (compile_portable_executable) { if (build_options->has_device_assignment()) { return InvalidArgument( "CompileOptions requests portable executable but " "ExecutableBuildOptions includes a device assignment"); } *num_replicas = 1; *num_partitions = 1; } else { if (!build_options->has_device_assignment()) { VLOG(2) << "Compile using default device_assignment."; TF_ASSIGN_OR_RETURN( DeviceAssignment device_assignment, GetDefaultDeviceAssignmentFunction(build_options->num_replicas(), build_options->num_partitions())); build_options->set_device_assignment(device_assignment); } VLOG(2) << "Compile device_assignment:\n" << build_options->device_assignment().ToString(); *num_replicas = build_options->device_assignment().replica_count(); *num_partitions = build_options->device_assignment().computation_count(); *device_assignment = std::make_shared<DeviceAssignment>(build_options->device_assignment()); } return Status::OK(); } Status DetermineArgumentLayoutsFromCompileOptions( const XlaComputation& computation, std::function<StatusOr<Shape>(Shape)> choose_compact_layout_for_shape_function, absl::optional<std::vector<Shape>>& argument_layouts, ExecutableBuildOptions* build_options, std::vector<const Shape*>* argument_layout_pointers) { TF_ASSIGN_OR_RETURN(ProgramShape program_shape, computation.GetProgramShape()); if (!argument_layouts) { argument_layouts.emplace(program_shape.parameters()); for (Shape& shape : *argument_layouts) { LayoutUtil::ClearLayout(&shape); } } else if (argument_layouts->size() != program_shape.parameters_size()) { return InvalidArgument( "CompileOptions specify %d argument layouts, but computation has %d " "arguments", argument_layouts->size(), program_shape.parameters_size()); } argument_layout_pointers->reserve(argument_layouts->size()); // Assign a default layout based on `sharded_shape` to any array subshapes in // `dst_shape` that are missing layouts. auto assign_layouts = [&choose_compact_layout_for_shape_function]( const Shape& sharded_shape, Shape* dst_shape) { return ShapeUtil::ForEachMutableSubshapeWithStatus( dst_shape, [&](Shape* subshape, const ShapeIndex& idx) { if (subshape->IsArray() && !subshape->has_layout()) { CHECK(ShapeUtil::IndexIsValid(sharded_shape, idx)); const Shape& sharded_subshape = ShapeUtil::GetSubshape(sharded_shape, idx); LayoutUtil::SetToDefaultLayout(subshape); TF_ASSIGN_OR_RETURN( Shape layout, choose_compact_layout_for_shape_function(sharded_subshape)); *subshape->mutable_layout() = layout.layout(); } return Status::OK(); }); }; TF_ASSIGN_OR_RETURN(auto sharded_shapes, GetShardedProgramShapes(computation, program_shape)); CHECK_EQ(sharded_shapes.first.size(), argument_layouts->size()); for (int i = 0; i < argument_layouts->size(); ++i) { Shape* layout = &(*argument_layouts)[i]; argument_layout_pointers->push_back(layout); TF_RETURN_IF_ERROR(assign_layouts(sharded_shapes.first[i], layout)); } Shape result_layout; if (build_options->result_layout()) { result_layout = *build_options->result_layout(); } else { result_layout = program_shape.result(); LayoutUtil::ClearLayout(&result_layout); } TF_RETURN_IF_ERROR(assign_layouts(sharded_shapes.second, &result_layout)); build_options->set_result_layout(result_layout); return Status::OK(); } StatusOr<std::vector<int>> ComputeParametersThatMustBeDonated( const HloModule& module, bool tuple_inputs) { HloComputation* computation = module.entry_computation(); int number_of_parameters = [&]() -> int { if (tuple_inputs) { CHECK_EQ(computation->num_parameters(), 1); const Shape& input_tuple_shape = computation->parameter_instruction(0)->shape(); CHECK(input_tuple_shape.IsTuple()); return input_tuple_shape.tuple_shapes_size(); } else { return computation->num_parameters(); } }(); // If any buffer in a parameter is aliased we will donate the entire input // parameter. std::vector<int> parameters_to_donate; parameters_to_donate.reserve(computation->num_parameters()); const HloInputOutputAliasConfig& config = module.input_output_alias_config(); TF_RETURN_IF_ERROR(config.ForEachAliasWithStatus( [&](const ShapeIndex& output_index, const HloInputOutputAliasConfig::Alias& alias) { if (tuple_inputs) { if (alias.parameter_number != 0) { return InvalidArgument( "Unexpected parameter number %d in alias config with tupled " "inputs", alias.parameter_number); } const ShapeIndex& index = alias.parameter_index; if (!index.empty()) { int this_parameter = index.data()[0]; if (this_parameter >= number_of_parameters) { return InvalidArgument( "Unexpected parameter index %s in alias config with tupled " "inputs and %d parameters", index.ToString(), number_of_parameters); } parameters_to_donate.push_back(this_parameter); } } else { int this_parameter = alias.parameter_number; if (this_parameter >= number_of_parameters) { return InvalidArgument( "Unexpected parameter number %d in alias config without tupled " "inputs and %d parameters", this_parameter, number_of_parameters); } parameters_to_donate.push_back(this_parameter); } return Status::OK(); })); absl::c_sort(parameters_to_donate); return parameters_to_donate; } int DefaultThreadPoolSize() { // Google's CI system exposes an environment variable NPROC that describes // a CPU reservation for tests. // TODO(phawkins): expose a better thought-out set of knobs to control // parallelism. const char* nproc_str = std::getenv("NPROC"); int nproc = 0; if (nproc_str && absl::SimpleAtoi(nproc_str, &nproc)) { return std::max(0, nproc); } return tensorflow::port::MaxParallelism(); } bool HasMajorToMinorLayout(PrimitiveType type, absl::Span<int64_t const> dims, absl::Span<int64_t const> byte_strides) { CHECK_EQ(dims.size(), byte_strides.size()); // If the array is size 0, the strides are irrelevant. if (absl::c_find(dims, 0) != dims.end()) { return true; } int64_t stride = primitive_util::ByteWidth(type); for (int i = static_cast<int>(dims.size()) - 1; i >= 0; --i) { // If a dimension is of size 1, its stride is irrelevant. if (dims[i] != 1) { if (byte_strides[i] != stride) { return false; } stride *= dims[i]; } } return true; } } // namespace xla <commit_msg>[tensorflow/compiler/xla/pjrt/utils.cc] Add calls to `reserve()` before populating vectors<commit_after>/* Copyright 2020 The TensorFlow 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 "tensorflow/compiler/xla/pjrt/utils.h" #include "absl/container/flat_hash_set.h" #include "tensorflow/compiler/xla/client/executable_build_options.h" #include "tensorflow/compiler/xla/client/xla_computation.h" #include "tensorflow/compiler/xla/service/hlo.pb.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/hlo_sharding.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace xla { namespace { StatusOr<Shape> GetShardedShape(const Shape& shape, const OpSharding& sharding) { if (sharding.type() == OpSharding::TUPLE) { if (!shape.IsTuple()) { return InvalidArgument( "Got tuple OpSharding (%s) for non-tuple shape (%s)", sharding.DebugString(), shape.ToString()); } if (sharding.tuple_shardings_size() != shape.tuple_shapes_size()) { return InvalidArgument( "Got mismatched OpSharding tuple size (%d) and shape tuple size (%d)." " (OpSharding: %s, shape: %s)", sharding.tuple_shardings_size(), shape.tuple_shapes_size(), sharding.DebugString(), shape.ToString()); } std::vector<Shape> sharded_subshapes; const auto tuple_shapes_size = shape.tuple_shapes_size(); for (int i = 0; i < tuple_shapes_size; ++i) { TF_ASSIGN_OR_RETURN( Shape sharded_subshape, GetShardedShape(shape.tuple_shapes(i), sharding.tuple_shardings(i))); sharded_subshapes.emplace_back(std::move(sharded_subshape)); } return ShapeUtil::MakeTupleShape(sharded_subshapes); } TF_ASSIGN_OR_RETURN(HloSharding hlo_sharding, HloSharding::FromProto(sharding)); return hlo_sharding.TileShape(shape); } StatusOr<Shape> GetShardedShape(const HloInstructionProto& instr) { const Shape unsharded_shape(instr.shape()); Shape sharded_shape; if (instr.has_sharding()) { TF_ASSIGN_OR_RETURN(sharded_shape, GetShardedShape(unsharded_shape, instr.sharding())); } else { sharded_shape = unsharded_shape; } LayoutUtil::ClearLayout(&sharded_shape); return sharded_shape; } // Returns sharded (argument shapes, result shape) without layouts. StatusOr<std::pair<std::vector<Shape>, Shape>> GetShardedProgramShapes( const XlaComputation& computation, const ProgramShape& program_shape) { std::vector<Shape> arg_shapes; arg_shapes.resize(program_shape.parameters_size()); Shape result_shape; for (const HloComputationProto& comp : computation.proto().computations()) { if (comp.id() != computation.proto().entry_computation_id()) { continue; } for (const HloInstructionProto& instr : comp.instructions()) { if (instr.opcode() == HloOpcodeString(HloOpcode::kParameter)) { if (instr.parameter_number() >= program_shape.parameters_size()) { return InvalidArgument( "Got invalid parameter number %d, expected %d parameters", instr.parameter_number(), program_shape.parameters_size()); } TF_ASSIGN_OR_RETURN(arg_shapes[instr.parameter_number()], GetShardedShape(instr)); } if (instr.id() == comp.root_id()) { if (result_shape.element_type() != PRIMITIVE_TYPE_INVALID) { return InvalidArgument("Found multiple root instructions"); } TF_ASSIGN_OR_RETURN(result_shape, GetShardedShape(instr)); } } } for (int i = 0; i < arg_shapes.size(); ++i) { if (arg_shapes[i].element_type() == PRIMITIVE_TYPE_INVALID) { return InvalidArgument("Couldn't find parameter %d", i); } } if (result_shape.element_type() == PRIMITIVE_TYPE_INVALID) { return InvalidArgument("Couldn't find root instruction"); } return std::make_pair(arg_shapes, result_shape); } } // namespace Status ParseDeviceAssignmentCompileOptions( bool compile_portable_executable, ExecutableBuildOptions* build_options, std::function<StatusOr<DeviceAssignment>(int, int)> GetDefaultDeviceAssignmentFunction, int* num_replicas, int* num_partitions, std::shared_ptr<DeviceAssignment>* device_assignment) { if (compile_portable_executable) { if (build_options->has_device_assignment()) { return InvalidArgument( "CompileOptions requests portable executable but " "ExecutableBuildOptions includes a device assignment"); } *num_replicas = 1; *num_partitions = 1; } else { if (!build_options->has_device_assignment()) { VLOG(2) << "Compile using default device_assignment."; TF_ASSIGN_OR_RETURN( DeviceAssignment device_assignment, GetDefaultDeviceAssignmentFunction(build_options->num_replicas(), build_options->num_partitions())); build_options->set_device_assignment(device_assignment); } VLOG(2) << "Compile device_assignment:\n" << build_options->device_assignment().ToString(); *num_replicas = build_options->device_assignment().replica_count(); *num_partitions = build_options->device_assignment().computation_count(); *device_assignment = std::make_shared<DeviceAssignment>(build_options->device_assignment()); } return Status::OK(); } Status DetermineArgumentLayoutsFromCompileOptions( const XlaComputation& computation, std::function<StatusOr<Shape>(Shape)> choose_compact_layout_for_shape_function, absl::optional<std::vector<Shape>>& argument_layouts, ExecutableBuildOptions* build_options, std::vector<const Shape*>* argument_layout_pointers) { TF_ASSIGN_OR_RETURN(ProgramShape program_shape, computation.GetProgramShape()); if (!argument_layouts) { argument_layouts.emplace(program_shape.parameters()); for (Shape& shape : *argument_layouts) { LayoutUtil::ClearLayout(&shape); } } else if (argument_layouts->size() != program_shape.parameters_size()) { return InvalidArgument( "CompileOptions specify %d argument layouts, but computation has %d " "arguments", argument_layouts->size(), program_shape.parameters_size()); } argument_layout_pointers->reserve(argument_layouts->size()); // Assign a default layout based on `sharded_shape` to any array subshapes in // `dst_shape` that are missing layouts. auto assign_layouts = [&choose_compact_layout_for_shape_function]( const Shape& sharded_shape, Shape* dst_shape) { return ShapeUtil::ForEachMutableSubshapeWithStatus( dst_shape, [&](Shape* subshape, const ShapeIndex& idx) { if (subshape->IsArray() && !subshape->has_layout()) { CHECK(ShapeUtil::IndexIsValid(sharded_shape, idx)); const Shape& sharded_subshape = ShapeUtil::GetSubshape(sharded_shape, idx); LayoutUtil::SetToDefaultLayout(subshape); TF_ASSIGN_OR_RETURN( Shape layout, choose_compact_layout_for_shape_function(sharded_subshape)); *subshape->mutable_layout() = layout.layout(); } return Status::OK(); }); }; TF_ASSIGN_OR_RETURN(auto sharded_shapes, GetShardedProgramShapes(computation, program_shape)); CHECK_EQ(sharded_shapes.first.size(), argument_layouts->size()); for (int i = 0; i < argument_layouts->size(); ++i) { Shape* layout = &(*argument_layouts)[i]; argument_layout_pointers->push_back(layout); TF_RETURN_IF_ERROR(assign_layouts(sharded_shapes.first[i], layout)); } Shape result_layout; if (build_options->result_layout()) { result_layout = *build_options->result_layout(); } else { result_layout = program_shape.result(); LayoutUtil::ClearLayout(&result_layout); } TF_RETURN_IF_ERROR(assign_layouts(sharded_shapes.second, &result_layout)); build_options->set_result_layout(result_layout); return Status::OK(); } StatusOr<std::vector<int>> ComputeParametersThatMustBeDonated( const HloModule& module, bool tuple_inputs) { HloComputation* computation = module.entry_computation(); int number_of_parameters = [&]() -> int { if (tuple_inputs) { CHECK_EQ(computation->num_parameters(), 1); const Shape& input_tuple_shape = computation->parameter_instruction(0)->shape(); CHECK(input_tuple_shape.IsTuple()); return input_tuple_shape.tuple_shapes_size(); } else { return computation->num_parameters(); } }(); // If any buffer in a parameter is aliased we will donate the entire input // parameter. std::vector<int> parameters_to_donate; parameters_to_donate.reserve(computation->num_parameters()); const HloInputOutputAliasConfig& config = module.input_output_alias_config(); TF_RETURN_IF_ERROR(config.ForEachAliasWithStatus( [&](const ShapeIndex& output_index, const HloInputOutputAliasConfig::Alias& alias) { if (tuple_inputs) { if (alias.parameter_number != 0) { return InvalidArgument( "Unexpected parameter number %d in alias config with tupled " "inputs", alias.parameter_number); } const ShapeIndex& index = alias.parameter_index; if (!index.empty()) { int this_parameter = index.data()[0]; if (this_parameter >= number_of_parameters) { return InvalidArgument( "Unexpected parameter index %s in alias config with tupled " "inputs and %d parameters", index.ToString(), number_of_parameters); } parameters_to_donate.push_back(this_parameter); } } else { int this_parameter = alias.parameter_number; if (this_parameter >= number_of_parameters) { return InvalidArgument( "Unexpected parameter number %d in alias config without tupled " "inputs and %d parameters", this_parameter, number_of_parameters); } parameters_to_donate.push_back(this_parameter); } return Status::OK(); })); absl::c_sort(parameters_to_donate); return parameters_to_donate; } int DefaultThreadPoolSize() { // Google's CI system exposes an environment variable NPROC that describes // a CPU reservation for tests. // TODO(phawkins): expose a better thought-out set of knobs to control // parallelism. const char* nproc_str = std::getenv("NPROC"); int nproc = 0; if (nproc_str && absl::SimpleAtoi(nproc_str, &nproc)) { return std::max(0, nproc); } return tensorflow::port::MaxParallelism(); } bool HasMajorToMinorLayout(PrimitiveType type, absl::Span<int64_t const> dims, absl::Span<int64_t const> byte_strides) { CHECK_EQ(dims.size(), byte_strides.size()); // If the array is size 0, the strides are irrelevant. if (absl::c_find(dims, 0) != dims.end()) { return true; } int64_t stride = primitive_util::ByteWidth(type); for (int i = static_cast<int>(dims.size()) - 1; i >= 0; --i) { // If a dimension is of size 1, its stride is irrelevant. if (dims[i] != 1) { if (byte_strides[i] != stride) { return false; } stride *= dims[i]; } } return true; } } // namespace xla <|endoftext|>
<commit_before>#include "Test.h" #include <arpa/inet.h> using namespace XNet; #ifdef __LITTLE_ENDIAN__ #define LOCALHOST 0x0100007F #else #define LOCALHOST 0x7F000001 #endif int main() { BSDSocketProvider* provider = new BSDSocketProvider(); Socket* sender = provider->NewSocket(1025); Socket* receiver = provider->NewSocket(1026); uint32_t localhost = provider->ResolveHost("localhost"); ASSERT_EQUAL(localhost, LOCALHOST, "failed to look up localhost"); sender->Send(localhost, 1026, (const void*)"blah", 4); uint32_t receiveHost; uint16_t receivePort; size_t receiveLength; void* receiveData = NULL; for (int i = 0; i < 40 && !receiveData; ++i) { receiveData = receiver->Receive(receiveHost, receivePort, receiveLength); usleep(10000); } ASSERT_NOT_NULL(receiveData, "failed to receive message"); ASSERT_EQUAL(0, memcmp(receiveData, (const void*)"blah", 4), "got wrong data"); ASSERT_EQUAL(receiveHost, localhost, "got message from wrong host"); ASSERT_EQUAL(receivePort, 1025, "got message on wrong port (expected 1025, got " << receivePort << ")"); free(receiveData); delete receiver; delete sender; delete provider; return 0; } <commit_msg>Fixed the test to properly swap the bytes in port numbers.<commit_after>#include "Test.h" #include <arpa/inet.h> using namespace XNet; #ifdef __LITTLE_ENDIAN__ #define LOCALHOST 0x0100007F #else #define LOCALHOST 0x7F000001 #endif int main() { BSDSocketProvider* provider = new BSDSocketProvider(); Socket* sender = provider->NewSocket(htons(1025)); Socket* receiver = provider->NewSocket(htons(1026)); uint32_t localhost = provider->ResolveHost("localhost"); ASSERT_EQUAL(localhost, LOCALHOST, "failed to look up localhost"); sender->Send(localhost, htons(1026), (const void*)"blah", 4); uint32_t receiveHost; uint16_t receivePort; size_t receiveLength; void* receiveData = NULL; for (int i = 0; i < 40 && !receiveData; ++i) { receiveData = receiver->Receive(receiveHost, receivePort, receiveLength); usleep(10000); } char* rd = (char*)receiveData; ASSERT_NOT_NULL(receiveData, "failed to receive message"); ASSERT_EQUAL(0, memcmp(receiveData, (const void*)"blah", 4), "got wrong data: expected 'blah', got '" << rd[0] << rd[1] << rd[2] << rd[3] << "'"); ASSERT_EQUAL(receiveHost, localhost, "got message from wrong host"); ASSERT_EQUAL(receivePort, htons(1025), "got message on wrong port (expected 1025, got " << receivePort << ")"); free(receiveData); delete receiver; delete sender; delete provider; return 0; } <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2016 Adrian Dobrică, Ștefan-Gabriel Mirea * * 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 "e_ident_container.hpp" #include <iostream> #include <sstream> using namespace elf; EIdentContainer::EIdentContainer(ELFFile *file) : Container(file, true, std::make_pair(0, EI_NIDENT)) { setName("e_ident"); } std::vector<Container *> &EIdentContainer::getInnerContainers() { if (innerContainers.empty()) { Container *container; ELFFile *efile = dynamic_cast<ELFFile *>(getFile()); ELFIO::elfio *elfio = efile->getELFIO(); int offset = 0x00; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag0 = elfio->get_elfmag0(); std::string elfmag0_string = ""; if (elfmag0 == ELFMAG0) elfmag0_string = "ELFMAG0"; else { std::stringstream ss; ss << std::hex << std::showbase << elfmag0; elfmag0_string = ss.str(); } container->setName("e_ident[EI_MAG0]: " + elfmag0_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag1 = elfio->get_elfmag1(); std::string elfmag1_string = ""; if (elfmag1 == ELFMAG1) elfmag1_string = "ELFMAG1"; else { std::stringstream ss; ss << std::hex << std::showbase << elfmag1; elfmag1_string = ss.str(); } container->setName("e_ident[EI_MAG1]: " + elfmag1_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag2 = elfio->get_elfmag2(); std::string elfmag2_string = ""; if (elfmag2 == ELFMAG2) elfmag2_string = "ELFMAG2"; else { std::stringstream ss; ss << std::hex << std::showbase << elfmag2; elfmag2_string = ss.str(); } container->setName("e_ident[EI_MAG2]: " + elfmag2_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag3 = elfio->get_elfmag3(); std::string elfmag3_string = ""; if (elfmag3 == ELFMAG3) elfmag3_string = "ELFMAG3"; else { std::stringstream ss; ss << std::hex << std::showbase << elfmag3; elfmag3_string = ss.str(); } container->setName("e_ident[EI_MAG3]: " + elfmag3_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_class = elfio->get_class(); std::string ei_class_string = ""; switch(ei_class) { case ELFCLASSNONE: ei_class_string = "ELFCLASSNONE"; break; case ELFCLASS32: ei_class_string = "ELFCLASS32"; break; case ELFCLASS64 : ei_class_string = "ELFCLASS64"; break; default: ei_class_string = std::to_string(ei_class); break; } container->setName("e_ident[EI_CLASS]: " + ei_class_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_data = elfio->get_encoding(); std::string ei_data_string = ""; switch(ei_data) { case ELFDATANONE: ei_data_string = "ELFDATANONE"; break; case ELFDATA2LSB: ei_data_string = "ELFDATA2LSB"; break; case ELFDATA2MSB: ei_data_string = "ELFDATA2MSB"; break; default: ei_data_string = std::to_string(ei_data); break; } container->setName("e_ident[EI_DATA]: " + ei_data_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_version = elfio->get_elf_version(); std::string ei_version_string = ""; switch(ei_version) { case EV_NONE: ei_version_string = "EV_NONE"; break; case EV_CURRENT: ei_version_string = "EV_CURRENT"; break; default: ei_version_string = std::to_string(ei_version); break; } container->setName("e_ident[EI_VERSION]: " + ei_version_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_osabi = elfio->get_os_abi(); std::string ei_osabi_string = ""; switch(ei_osabi) { case ELFOSABI_NONE: ei_osabi_string = "ELFOSABI_NONE"; break; case ELFOSABI_HPUX: ei_osabi_string = "ELFOSABI_HPUX"; break; case ELFOSABI_NETBSD: ei_osabi_string = "ELFOSABI_NETBSD"; break; case ELFOSABI_LINUX: ei_osabi_string = "ELFOSABI_LINUX"; break; case ELFOSABI_SOLARIS: ei_osabi_string = "ELFOSABI_SOLARIS"; break; case ELFOSABI_AIX: ei_osabi_string = "ELFOSABI_AIX"; break; case ELFOSABI_IRIX: ei_osabi_string = "ELFOSABI_IRIX"; break; case ELFOSABI_FREEBSD: ei_osabi_string = "ELFOSABI_FREEBSD"; break; case ELFOSABI_TRU64: ei_osabi_string = "ELFOSABI_TRU64"; break; case ELFOSABI_MODESTO: ei_osabi_string = "ELFOSABI_MODESTO"; break; case ELFOSABI_OPENBSD: ei_osabi_string = "ELFOSABI_OPENBSD"; break; case ELFOSABI_OPENVMS: ei_osabi_string = "ELFOSABI_OPENVMS"; break; case ELFOSABI_NSK: ei_osabi_string = "ELFOSABI_NSK"; break; case ELFOSABI_AROS: ei_osabi_string = "ELFOSABI_AROS"; break; case ELFOSABI_FENIXOS: ei_osabi_string = "ELFOSABI_FENIXOS"; break; default: ei_osabi_string = std::to_string(ei_class); break; } container->setName("e_ident[EI_OSABI]: " + ei_osabi_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); container->setName("e_ident[EI_ABIVERSION]: " + std::to_string(elfio->get_abi_version())); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 7)); container->setName("e_ident[EI_PAD]"); addInnerContainer(container); offset += 7; } return innerContainers; } EIdentContainer::~EIdentContainer() {} <commit_msg>Use printHex function for e_ident container<commit_after>/* The MIT License (MIT) * * Copyright (c) 2016 Adrian Dobrică, Ștefan-Gabriel Mirea * * 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 "e_ident_container.hpp" #include "util.hpp" #include <iostream> using namespace elf; EIdentContainer::EIdentContainer(ELFFile *file) : Container(file, true, std::make_pair(0, EI_NIDENT)) { setName("e_ident"); } std::vector<Container *> &EIdentContainer::getInnerContainers() { if (innerContainers.empty()) { Container *container; ELFFile *efile = dynamic_cast<ELFFile *>(getFile()); ELFIO::elfio *elfio = efile->getELFIO(); int offset = 0x00; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag0 = elfio->get_elfmag0(); std::string elfmag0_string = ""; if (elfmag0 == ELFMAG0) elfmag0_string = "ELFMAG0"; else { elfmag0_string = printHex(elfmag0); } container->setName("e_ident[EI_MAG0]: " + elfmag0_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag1 = elfio->get_elfmag1(); std::string elfmag1_string = ""; if (elfmag1 == ELFMAG1) elfmag1_string = "ELFMAG1"; else { elfmag1_string = printHex(elfmag1); } container->setName("e_ident[EI_MAG1]: " + elfmag1_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag2 = elfio->get_elfmag2(); std::string elfmag2_string = ""; if (elfmag2 == ELFMAG2) elfmag2_string = "ELFMAG2"; else { elfmag2_string = printHex(elfmag2); } container->setName("e_ident[EI_MAG2]: " + elfmag2_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int elfmag3 = elfio->get_elfmag3(); std::string elfmag3_string = ""; if (elfmag3 == ELFMAG3) elfmag3_string = "ELFMAG3"; else { elfmag3_string = printHex(elfmag3); } container->setName("e_ident[EI_MAG3]: " + elfmag3_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_class = elfio->get_class(); std::string ei_class_string = ""; switch(ei_class) { case ELFCLASSNONE: ei_class_string = "ELFCLASSNONE"; break; case ELFCLASS32: ei_class_string = "ELFCLASS32"; break; case ELFCLASS64 : ei_class_string = "ELFCLASS64"; break; default: ei_class_string = printHex(ei_class); break; } container->setName("e_ident[EI_CLASS]: " + ei_class_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_data = elfio->get_encoding(); std::string ei_data_string = ""; switch(ei_data) { case ELFDATANONE: ei_data_string = "ELFDATANONE"; break; case ELFDATA2LSB: ei_data_string = "ELFDATA2LSB"; break; case ELFDATA2MSB: ei_data_string = "ELFDATA2MSB"; break; default: ei_data_string = printHex(ei_data); break; } container->setName("e_ident[EI_DATA]: " + ei_data_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_version = elfio->get_elf_version(); std::string ei_version_string = ""; switch(ei_version) { case EV_NONE: ei_version_string = "EV_NONE"; break; case EV_CURRENT: ei_version_string = "EV_CURRENT"; break; default: ei_version_string = printHex(ei_version); break; } container->setName("e_ident[EI_VERSION]: " + ei_version_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); int ei_osabi = elfio->get_os_abi(); std::string ei_osabi_string = ""; switch(ei_osabi) { case ELFOSABI_NONE: ei_osabi_string = "ELFOSABI_NONE"; break; case ELFOSABI_HPUX: ei_osabi_string = "ELFOSABI_HPUX"; break; case ELFOSABI_NETBSD: ei_osabi_string = "ELFOSABI_NETBSD"; break; case ELFOSABI_LINUX: ei_osabi_string = "ELFOSABI_LINUX"; break; case ELFOSABI_SOLARIS: ei_osabi_string = "ELFOSABI_SOLARIS"; break; case ELFOSABI_AIX: ei_osabi_string = "ELFOSABI_AIX"; break; case ELFOSABI_IRIX: ei_osabi_string = "ELFOSABI_IRIX"; break; case ELFOSABI_FREEBSD: ei_osabi_string = "ELFOSABI_FREEBSD"; break; case ELFOSABI_TRU64: ei_osabi_string = "ELFOSABI_TRU64"; break; case ELFOSABI_MODESTO: ei_osabi_string = "ELFOSABI_MODESTO"; break; case ELFOSABI_OPENBSD: ei_osabi_string = "ELFOSABI_OPENBSD"; break; case ELFOSABI_OPENVMS: ei_osabi_string = "ELFOSABI_OPENVMS"; break; case ELFOSABI_NSK: ei_osabi_string = "ELFOSABI_NSK"; break; case ELFOSABI_AROS: ei_osabi_string = "ELFOSABI_AROS"; break; case ELFOSABI_FENIXOS: ei_osabi_string = "ELFOSABI_FENIXOS"; break; default: ei_osabi_string = printHex(ei_class); break; } container->setName("e_ident[EI_OSABI]: " + ei_osabi_string); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 1)); container->setName("e_ident[EI_ABIVERSION]: " + printHex(elfio->get_abi_version())); addInnerContainer(container); offset++; container = new Container(getFile(), false, std::make_pair(offset, offset + 7)); container->setName("e_ident[EI_PAD]"); addInnerContainer(container); offset += 7; } return innerContainers; } EIdentContainer::~EIdentContainer() {} <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file transactionqueue.cpp * @author Christoph Jentzsch <cj@ethdev.com> * @date 2015 * TransactionQueue test functions. */ #include <libethereum/TransactionQueue.h> #include "../TestHelper.h" using namespace std; using namespace dev; using namespace dev::eth; BOOST_AUTO_TEST_SUITE(TransactionQueue) BOOST_AUTO_TEST_CASE(maxNonce) { dev::eth::TransactionQueue txq; // from a94f5374fce5edbc8e2a8697c15331677e6ebf0b const u256 gasCost = 10 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Address to = Address("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"); Secret sec = Secret("0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"); Transaction tx0(0, gasCost, gas, dest, bytes(), 0, sec ); Transaction tx0_1(1, gasCost, gas, dest, bytes(), 0, sec ); Transaction tx1(0, gasCost, gas, dest, bytes(), 1, sec ); Transaction tx2(0, gasCost, gas, dest, bytes(), 2, sec ); Transaction tx9(0, gasCost, gas, dest, bytes(), 9, sec ); txq.import(tx0); BOOST_CHECK(1 == txq.maxNonce(to)); txq.import(tx0); BOOST_CHECK(1 == txq.maxNonce(to)); txq.import(tx0_1); BOOST_CHECK(1 == txq.maxNonce(to)); txq.import(tx1); BOOST_CHECK(2 == txq.maxNonce(to)); txq.import(tx9); BOOST_CHECK(10 == txq.maxNonce(to)); txq.import(tx2); BOOST_CHECK(10 == txq.maxNonce(to)); } BOOST_AUTO_TEST_CASE(priority) { dev::eth::TransactionQueue txq; const u256 gasCostCheap = 10 * szabo; const u256 gasCostMed = 20 * szabo; const u256 gasCostHigh = 30 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Secret sender1 = Secret("0x3333333333333333333333333333333333333333333333333333333333333333"); Secret sender2 = Secret("0x4444444444444444444444444444444444444444444444444444444444444444"); Transaction tx0(0, gasCostCheap, gas, dest, bytes(), 0, sender1 ); Transaction tx0_1(1, gasCostMed, gas, dest, bytes(), 0, sender1 ); Transaction tx1(0, gasCostCheap, gas, dest, bytes(), 1, sender1 ); Transaction tx2(0, gasCostHigh, gas, dest, bytes(), 0, sender2 ); Transaction tx3(0, gasCostCheap + 1, gas, dest, bytes(), 1, sender2 ); Transaction tx4(0, gasCostHigh, gas, dest, bytes(), 2, sender1 ); Transaction tx5(0, gasCostMed, gas, dest, bytes(), 2, sender2 ); txq.import(tx0); BOOST_CHECK(Transactions { tx0 } == txq.topTransactions(256)); txq.import(tx0); BOOST_CHECK(Transactions { tx0 } == txq.topTransactions(256)); txq.import(tx0_1); BOOST_CHECK(Transactions { tx0_1 } == txq.topTransactions(256)); txq.import(tx1); BOOST_CHECK((Transactions { tx0_1, tx1 }) == txq.topTransactions(256)); txq.import(tx2); BOOST_CHECK((Transactions { tx2, tx0_1, tx1 }) == txq.topTransactions(256)); txq.import(tx3); BOOST_CHECK((Transactions { tx2, tx0_1, tx1, tx3 }) == txq.topTransactions(256)); txq.import(tx4); BOOST_CHECK((Transactions { tx2, tx0_1, tx1, tx3, tx4 }) == txq.topTransactions(256)); txq.import(tx5); BOOST_CHECK((Transactions { tx2, tx0_1, tx1, tx3, tx5, tx4 }) == txq.topTransactions(256)); txq.drop(tx0_1.sha3()); BOOST_CHECK((Transactions { tx2, tx1, tx3, tx5, tx4 }) == txq.topTransactions(256)); txq.drop(tx1.sha3()); BOOST_CHECK((Transactions { tx2, tx3, tx5, tx4 }) == txq.topTransactions(256)); txq.drop(tx5.sha3()); BOOST_CHECK((Transactions { tx2, tx3, tx4 }) == txq.topTransactions(256)); Transaction tx6(0, gasCostMed, gas, dest, bytes(), 20, sender1 ); txq.import(tx6); BOOST_CHECK((Transactions { tx2, tx3, tx4, tx6 }) == txq.topTransactions(256)); Transaction tx7(0, gasCostMed, gas, dest, bytes(), 2, sender2 ); txq.import(tx7); BOOST_CHECK((Transactions { tx2, tx3, tx4, tx6, tx7 }) == txq.topTransactions(256)); } BOOST_AUTO_TEST_CASE(future) { dev::eth::TransactionQueue txq; // from a94f5374fce5edbc8e2a8697c15331677e6ebf0b const u256 gasCostMed = 20 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Secret sender = Secret("0x3333333333333333333333333333333333333333333333333333333333333333"); Transaction tx0(0, gasCostMed, gas, dest, bytes(), 0, sender ); Transaction tx1(0, gasCostMed, gas, dest, bytes(), 1, sender ); Transaction tx2(0, gasCostMed, gas, dest, bytes(), 2, sender ); Transaction tx3(0, gasCostMed, gas, dest, bytes(), 3, sender ); Transaction tx4(0, gasCostMed, gas, dest, bytes(), 4, sender ); txq.import(tx0); txq.import(tx1); txq.import(tx2); txq.import(tx3); txq.import(tx4); BOOST_CHECK((Transactions { tx0, tx1, tx2, tx3, tx4 }) == txq.topTransactions(256)); txq.setFuture(tx2.sha3()); BOOST_CHECK((Transactions { tx0, tx1 }) == txq.topTransactions(256)); Transaction tx2_2(1, gasCostMed, gas, dest, bytes(), 2, sender ); txq.import(tx2_2); BOOST_CHECK((Transactions { tx0, tx1, tx2_2, tx3, tx4 }) == txq.topTransactions(256)); } BOOST_AUTO_TEST_CASE(lmits) { dev::eth::TransactionQueue txq(3, 3); const u256 gasCostMed = 20 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Secret sender = Secret("0x3333333333333333333333333333333333333333333333333333333333333333"); Secret sender2 = Secret("0x4444444444444444444444444444444444444444444444444444444444444444"); Transaction tx0(0, gasCostMed, gas, dest, bytes(), 0, sender ); Transaction tx1(0, gasCostMed, gas, dest, bytes(), 1, sender ); Transaction tx2(0, gasCostMed, gas, dest, bytes(), 2, sender ); Transaction tx3(0, gasCostMed, gas, dest, bytes(), 3, sender ); Transaction tx4(0, gasCostMed, gas, dest, bytes(), 4, sender ); Transaction tx5(0, gasCostMed + 1, gas, dest, bytes(), 0, sender2 ); txq.import(tx0); txq.import(tx1); txq.import(tx2); txq.import(tx3); txq.import(tx4); txq.import(tx5); BOOST_CHECK((Transactions { tx5, tx0, tx1 }) == txq.topTransactions(256)); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Update txq test for deterministic signature output of updated secp256k1.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file transactionqueue.cpp * @author Christoph Jentzsch <cj@ethdev.com> * @date 2015 * TransactionQueue test functions. */ #include <libethereum/TransactionQueue.h> #include "../TestHelper.h" using namespace std; using namespace dev; using namespace dev::eth; BOOST_AUTO_TEST_SUITE(TransactionQueue) BOOST_AUTO_TEST_CASE(maxNonce) { dev::eth::TransactionQueue txq; // from a94f5374fce5edbc8e2a8697c15331677e6ebf0b const u256 gasCost = 10 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Address to = Address("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"); Secret sec = Secret("0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"); Transaction tx0(0, gasCost, gas, dest, bytes(), 0, sec ); Transaction tx0_1(1, gasCost, gas, dest, bytes(), 0, sec ); Transaction tx1(0, gasCost, gas, dest, bytes(), 1, sec ); Transaction tx2(0, gasCost, gas, dest, bytes(), 2, sec ); Transaction tx9(0, gasCost, gas, dest, bytes(), 9, sec ); txq.import(tx0); BOOST_CHECK(1 == txq.maxNonce(to)); txq.import(tx0); BOOST_CHECK(1 == txq.maxNonce(to)); txq.import(tx0_1); BOOST_CHECK(1 == txq.maxNonce(to)); txq.import(tx1); BOOST_CHECK(2 == txq.maxNonce(to)); txq.import(tx9); BOOST_CHECK(10 == txq.maxNonce(to)); txq.import(tx2); BOOST_CHECK(10 == txq.maxNonce(to)); } BOOST_AUTO_TEST_CASE(priority) { dev::eth::TransactionQueue txq; const u256 gasCostCheap = 10 * szabo; const u256 gasCostMed = 20 * szabo; const u256 gasCostHigh = 30 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Secret sender1 = Secret("0x3333333333333333333333333333333333333333333333333333333333333333"); Secret sender2 = Secret("0x4444444444444444444444444444444444444444444444444444444444444444"); Transaction tx0(0, gasCostCheap, gas, dest, bytes(), 0, sender1 ); Transaction tx0_1(1, gasCostMed, gas, dest, bytes(), 0, sender1 ); Transaction tx1(0, gasCostCheap, gas, dest, bytes(), 1, sender1 ); Transaction tx2(0, gasCostHigh, gas, dest, bytes(), 0, sender2 ); Transaction tx3(0, gasCostCheap + 1, gas, dest, bytes(), 1, sender2 ); Transaction tx4(0, gasCostHigh, gas, dest, bytes(), 2, sender1 ); Transaction tx5(0, gasCostMed, gas, dest, bytes(), 2, sender2 ); txq.import(tx0); BOOST_CHECK(Transactions { tx0 } == txq.topTransactions(256)); txq.import(tx0); BOOST_CHECK(Transactions { tx0 } == txq.topTransactions(256)); txq.import(tx0_1); BOOST_CHECK(Transactions { tx0_1 } == txq.topTransactions(256)); txq.import(tx1); BOOST_CHECK((Transactions { tx0_1, tx1 }) == txq.topTransactions(256)); txq.import(tx2); BOOST_CHECK((Transactions { tx2, tx0_1, tx1 }) == txq.topTransactions(256)); txq.import(tx3); BOOST_CHECK((Transactions { tx2, tx0_1, tx1, tx3 }) == txq.topTransactions(256)); txq.import(tx4); BOOST_CHECK((Transactions { tx2, tx0_1, tx1, tx3, tx4 }) == txq.topTransactions(256)); txq.import(tx5); BOOST_CHECK((Transactions { tx2, tx0_1, tx1, tx3, tx5, tx4 }) == txq.topTransactions(256)); txq.drop(tx0_1.sha3()); BOOST_CHECK((Transactions { tx2, tx1, tx3, tx5, tx4 }) == txq.topTransactions(256)); txq.drop(tx1.sha3()); BOOST_CHECK((Transactions { tx2, tx3, tx5, tx4 }) == txq.topTransactions(256)); txq.drop(tx5.sha3()); BOOST_CHECK((Transactions { tx2, tx3, tx4 }) == txq.topTransactions(256)); Transaction tx6(0, gasCostMed, gas, dest, bytes(), 20, sender1 ); txq.import(tx6); BOOST_CHECK((Transactions { tx2, tx3, tx4, tx6 }) == txq.topTransactions(256)); Transaction tx7(0, gasCostMed, gas, dest, bytes(), 2, sender2 ); txq.import(tx7); #ifdef ETH_HAVE_SECP256K1 // deterministic signature: hash of tx5 and tx7 will be same BOOST_CHECK((Transactions { tx2, tx3, tx4, tx6 }) == txq.topTransactions(256)); #else BOOST_CHECK((Transactions { tx2, tx3, tx4, tx6, tx7 }) == txq.topTransactions(256)); #endif } BOOST_AUTO_TEST_CASE(future) { dev::eth::TransactionQueue txq; // from a94f5374fce5edbc8e2a8697c15331677e6ebf0b const u256 gasCostMed = 20 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Secret sender = Secret("0x3333333333333333333333333333333333333333333333333333333333333333"); Transaction tx0(0, gasCostMed, gas, dest, bytes(), 0, sender ); Transaction tx1(0, gasCostMed, gas, dest, bytes(), 1, sender ); Transaction tx2(0, gasCostMed, gas, dest, bytes(), 2, sender ); Transaction tx3(0, gasCostMed, gas, dest, bytes(), 3, sender ); Transaction tx4(0, gasCostMed, gas, dest, bytes(), 4, sender ); txq.import(tx0); txq.import(tx1); txq.import(tx2); txq.import(tx3); txq.import(tx4); BOOST_CHECK((Transactions { tx0, tx1, tx2, tx3, tx4 }) == txq.topTransactions(256)); txq.setFuture(tx2.sha3()); BOOST_CHECK((Transactions { tx0, tx1 }) == txq.topTransactions(256)); Transaction tx2_2(1, gasCostMed, gas, dest, bytes(), 2, sender ); txq.import(tx2_2); BOOST_CHECK((Transactions { tx0, tx1, tx2_2, tx3, tx4 }) == txq.topTransactions(256)); } BOOST_AUTO_TEST_CASE(lmits) { dev::eth::TransactionQueue txq(3, 3); const u256 gasCostMed = 20 * szabo; const u256 gas = 25000; Address dest = Address("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"); Secret sender = Secret("0x3333333333333333333333333333333333333333333333333333333333333333"); Secret sender2 = Secret("0x4444444444444444444444444444444444444444444444444444444444444444"); Transaction tx0(0, gasCostMed, gas, dest, bytes(), 0, sender ); Transaction tx1(0, gasCostMed, gas, dest, bytes(), 1, sender ); Transaction tx2(0, gasCostMed, gas, dest, bytes(), 2, sender ); Transaction tx3(0, gasCostMed, gas, dest, bytes(), 3, sender ); Transaction tx4(0, gasCostMed, gas, dest, bytes(), 4, sender ); Transaction tx5(0, gasCostMed + 1, gas, dest, bytes(), 0, sender2 ); txq.import(tx0); txq.import(tx1); txq.import(tx2); txq.import(tx3); txq.import(tx4); txq.import(tx5); BOOST_CHECK((Transactions { tx5, tx0, tx1 }) == txq.topTransactions(256)); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5pp. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Author: Jan Kotanski <jan.kotanski@desy.de> // Created on: Nov 12, 2018 // #include <gtest/gtest.h> #include <h5cpp/file/functions.hpp> #include <h5cpp/node/group.hpp> #include <h5cpp/dataspace/hyperslab.hpp> #include <sys/time.h> using namespace hdf5; namespace fs = boost::filesystem; class DatasetReadSpeedTest : public testing::Test { protected: virtual void SetUp() { #if H5_VERSION_GE(1, 10, 0) property::FileCreationList fcpl; property::FileAccessList fapl; property::DatasetCreationList dcpl; property::LinkCreationList lcpl; property::DatasetAccessList dapl; fapl.library_version_bounds(property::LibVersion::LATEST, property::LibVersion::LATEST); file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl); #else file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE); #endif node::Group root = f.root(); long long unsigned int xdim = 867; long long unsigned int ydim = 700; long long unsigned int nframe = 33; dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED}}; dcpl.layout(property::DatasetLayout::CHUNKED); dcpl.chunk({1, xdim, ydim}); node::Dataset data = node::Dataset(root, "data", datatype::create<unsigned short int>(), space,lcpl,dcpl,dapl); std::vector<unsigned short int> frame(xdim*ydim); dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}}; for(long long unsigned int i = 0; i != nframe; i++){ data.extent(0, 1); framespace.offset({i, 0, 0}); data.write(frame, framespace); } } }; #ifndef _MSC_VER TEST_F(DatasetReadSpeedTest, read) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(dims[0]*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{0, 0, 0}; hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(8*time1, time0); EXPECT_GT(8*time0, time1); } TEST_F(DatasetReadSpeedTest, read_hyperslab) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(11*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{10, 0, 0}; hdf5::Dimensions frameblock{11, dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]})); // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace0, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer, selected_frames); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(8*time1, time0); EXPECT_GT(8*time0, time1); } #endif <commit_msg>comment sys/time.h<commit_after>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5pp. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Author: Jan Kotanski <jan.kotanski@desy.de> // Created on: Nov 12, 2018 // #include <gtest/gtest.h> #include <h5cpp/file/functions.hpp> #include <h5cpp/node/group.hpp> #include <h5cpp/dataspace/hyperslab.hpp> #ifndef _MSC_VER #include <sys/time.h> #endif using namespace hdf5; namespace fs = boost::filesystem; class DatasetReadSpeedTest : public testing::Test { protected: virtual void SetUp() { #if H5_VERSION_GE(1, 10, 0) property::FileCreationList fcpl; property::FileAccessList fapl; property::DatasetCreationList dcpl; property::LinkCreationList lcpl; property::DatasetAccessList dapl; fapl.library_version_bounds(property::LibVersion::LATEST, property::LibVersion::LATEST); file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl); #else file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE); #endif node::Group root = f.root(); long long unsigned int xdim = 867; long long unsigned int ydim = 700; long long unsigned int nframe = 33; dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED}}; dcpl.layout(property::DatasetLayout::CHUNKED); dcpl.chunk({1, xdim, ydim}); node::Dataset data = node::Dataset(root, "data", datatype::create<unsigned short int>(), space,lcpl,dcpl,dapl); std::vector<unsigned short int> frame(xdim*ydim); dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}}; for(long long unsigned int i = 0; i != nframe; i++){ data.extent(0, 1); framespace.offset({i, 0, 0}); data.write(frame, framespace); } } }; #ifndef _MSC_VER TEST_F(DatasetReadSpeedTest, read) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(dims[0]*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{0, 0, 0}; hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(8*time1, time0); EXPECT_GT(8*time0, time1); } TEST_F(DatasetReadSpeedTest, read_hyperslab) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(11*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{10, 0, 0}; hdf5::Dimensions frameblock{11, dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]})); // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace0, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer, selected_frames); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(8*time1, time0); EXPECT_GT(8*time0, time1); } #endif <|endoftext|>
<commit_before>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5pp. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Author: Jan Kotanski <jan.kotanski@desy.de> // Created on: Nov 12, 2018 // #include <gtest/gtest.h> #include <h5cpp/file/functions.hpp> #include <h5cpp/node/group.hpp> #include <h5cpp/dataspace/hyperslab.hpp> #include <boost/filesystem.hpp> #ifndef _MSC_VER #include <sys/time.h> #endif using namespace hdf5; namespace fs = boost::filesystem; class DatasetReadSpeedTest : public testing::Test { protected: virtual void SetUp() { #if H5_VERSION_GE(1, 10, 0) property::FileCreationList fcpl; property::FileAccessList fapl; property::DatasetCreationList dcpl; property::LinkCreationList lcpl; property::DatasetAccessList dapl; fapl.library_version_bounds(property::LibVersion::LATEST, property::LibVersion::LATEST); file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl); #else file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE); #endif node::Group root = f.root(); long long unsigned int xdim = 867; long long unsigned int ydim = 700; long long unsigned int nframe = 33; dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED}}; dcpl.layout(property::DatasetLayout::CHUNKED); dcpl.chunk({1, xdim, ydim}); node::Dataset data = node::Dataset(root, "data", datatype::create<unsigned short int>(), space,lcpl,dcpl,dapl); std::vector<unsigned short int> frame(xdim*ydim); dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}}; for(long long unsigned int i = 0; i != nframe; i++){ data.extent(0, 1); framespace.offset({i, 0, 0}); data.write(frame, framespace); } virtual void TearDown() { fs::remove("dataset_read_speed.h5"); } } }; #ifndef _MSC_VER TEST_F(DatasetReadSpeedTest, read) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(dims[0]*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{0, 0, 0}; hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(14 * time1, time0); EXPECT_GT(14 * time0, time1); } TEST_F(DatasetReadSpeedTest, read_hyperslab) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(11*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{10, 0, 0}; hdf5::Dimensions frameblock{11, dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]})); // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace0, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer, selected_frames); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(14 * time1, time0); EXPECT_GT(14 * time0, time1); } #endif <commit_msg>fix brackets<commit_after>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5pp. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Author: Jan Kotanski <jan.kotanski@desy.de> // Created on: Nov 12, 2018 // #include <gtest/gtest.h> #include <h5cpp/file/functions.hpp> #include <h5cpp/node/group.hpp> #include <h5cpp/dataspace/hyperslab.hpp> #include <boost/filesystem.hpp> #ifndef _MSC_VER #include <sys/time.h> #endif using namespace hdf5; namespace fs = boost::filesystem; class DatasetReadSpeedTest : public testing::Test { protected: virtual void SetUp() { #if H5_VERSION_GE(1, 10, 0) property::FileCreationList fcpl; property::FileAccessList fapl; property::DatasetCreationList dcpl; property::LinkCreationList lcpl; property::DatasetAccessList dapl; fapl.library_version_bounds(property::LibVersion::LATEST, property::LibVersion::LATEST); file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl); #else file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE); #endif node::Group root = f.root(); long long unsigned int xdim = 867; long long unsigned int ydim = 700; long long unsigned int nframe = 33; dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED, dataspace::Simple::UNLIMITED}}; dcpl.layout(property::DatasetLayout::CHUNKED); dcpl.chunk({1, xdim, ydim}); node::Dataset data = node::Dataset(root, "data", datatype::create<unsigned short int>(), space,lcpl,dcpl,dapl); std::vector<unsigned short int> frame(xdim*ydim); dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}}; for(long long unsigned int i = 0; i != nframe; i++){ data.extent(0, 1); framespace.offset({i, 0, 0}); data.write(frame, framespace); } } virtual void TearDown() { fs::remove("dataset_read_speed.h5"); } }; #ifndef _MSC_VER TEST_F(DatasetReadSpeedTest, read) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(dims[0]*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{0, 0, 0}; hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(14 * time1, time0); EXPECT_GT(14 * time0, time1); } TEST_F(DatasetReadSpeedTest, read_hyperslab) { struct timeval stime1; struct timeval etime1; struct timeval stime0; struct timeval etime0; file::File f0 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root0 = f0.root(); auto dataset0 = root0.get_dataset("/data"); hdf5::dataspace::Simple dataspace(dataset0.dataspace()); const auto dims = dataspace.current_dimensions(); std::vector<unsigned short int> buffer(11*dims[1]*dims[2]); auto datatype = dataset0.datatype(); hdf5::Dimensions frameoffset{10, 0, 0}; hdf5::Dimensions frameblock{11, dims[1], dims[2]}; hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock}; dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]})); // time0 gettimeofday(&stime0, NULL); dataset0.read(buffer, datatype, dataspace0, selected_frames); gettimeofday(&etime0, NULL); f0.close(); file::File f1 = file::open("dataset_read_speed.h5", file::AccessFlags::READONLY); auto root1 = f1.root(); auto dataset1 = root1.get_dataset("/data"); // time1 gettimeofday(&stime1, NULL); dataset1.read(buffer, selected_frames); gettimeofday(&etime1, NULL); f1.close(); double time0 = (double)(etime0.tv_sec - stime0.tv_sec) + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001; double time1 = (double)(etime1.tv_sec - stime1.tv_sec) + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001; EXPECT_GT(14 * time1, time0); EXPECT_GT(14 * time0, time1); } #endif <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * 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 "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SynthXilinxPass : public ScriptPass { SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -arch {xcup|xcu|xc7|xc6s}\n"); log(" run synthesis for the specified Xilinx architecture\n"); log(" default: xc7\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nocarry\n"); log(" disable inference of carry chains\n"); log("\n"); log(" -nobram\n"); log(" disable inference of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable inference of distributed rams\n"); log("\n"); log(" -nosrl\n"); log(" disable inference of shift registers\n"); log("\n"); log(" -nomux\n"); log(" disable inference of wide multiplexers\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use abc9 instead of abc\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } std::string top_opt, edif_file, blif_file, abc, arch; bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux; void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; edif_file.clear(); blif_file.clear(); abc = "abc"; flatten = false; retime = false; vpr = false; nocarry = false; nobram = false; nodram = false; nosrl = false; nomux = false; arch = "xc7"; } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-arch" && argidx+1 < args.size()) { arch = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-nosrl") { nosrl = true; continue; } if (args[argidx] == "-nomux") { nomux = true; continue; } if (args[argidx] == "-abc9") { abc = "abc9"; continue; } break; } extra_args(args, argidx, design); if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s") log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str()); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("begin")) { if (vpr) run("read_verilog -lib -D_ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); else run("read_verilog -lib -D_ABC +/xilinx/cells_sim.v"); run("read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram || help_mode) run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')"); run(stringf("hierarchy -check %s", top_opt.c_str())); } if (check_label("flatten", "(with '-flatten' only)")) { if (flatten || help_mode) { run("proc"); run("flatten"); } } if (check_label("coarse")) { run("synth -run coarse"); // shregmap -tech xilinx can cope with $shiftx and $mux // cells for identifying variable-length shift registers, // so attempt to convert $pmux-es to the former // Also: wide multiplexer inference benefits from this too if (!(nosrl && nomux) || help_mode) run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')"); // Run a number of peephole optimisations, including one // that optimises $mul cells driving $shiftx's B input // and that aids wide mux analysis run("peepopt"); } if (check_label("bram", "(skip if '-nobram')")) { if (!nobram || help_mode) { run("memory_bram -rules +/xilinx/brams.txt"); run("techmap -map +/xilinx/brams_map.v"); } } if (check_label("dram", "(skip if '-nodram')")) { if (!nodram || help_mode) { run("memory_bram -rules +/xilinx/drams.txt"); run("techmap -map +/xilinx/drams_map.v"); } } if (check_label("fine")) { run("opt -fast -full"); run("memory_map"); run("dffsr2dff"); run("dff2dffe"); run("opt -full"); if (!nosrl || help_mode) { // shregmap operates on bit-level flops, not word-level, // so break those down here run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')"); // shregmap with '-tech xilinx' infers variable length shift regs run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')"); } std::string techmap_files = " -map +/techmap.v"; if (help_mode) techmap_files += " [-map +/xilinx/mux_map.v]"; else if (!nomux) techmap_files += " -map +/xilinx/mux_map.v"; if (help_mode) techmap_files += " [-map +/xilinx/arith_map.v]"; else if (!nocarry) { techmap_files += " -map +/xilinx/arith_map.v"; if (vpr) techmap_files += " -D _EXPLICIT_CARRY"; else if (abc == "abc9") techmap_files += " -D _CLB_CARRY"; } run("techmap " + techmap_files); run("opt -fast"); } if (check_label("map_cells")) { run("techmap -map +/techmap.v -map +/xilinx/cells_map.v"); run("clean"); } if (check_label("map_luts")) { if (abc == "abc9") run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : "")); else if (help_mode) run(abc + " -luts 2:2,3,6:5,10,20 [-dff]"); else run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : "")); run("clean"); // This shregmap call infers fixed length shift registers after abc // has performed any necessary retiming if (!nosrl || help_mode) run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')"); run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v"); run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat -tech xilinx"); run("check -noinit"); } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) run(stringf("write_blif %s", edif_file.c_str())); } } } SynthXilinxPass; PRIVATE_NAMESPACE_END <commit_msg>Add space between -D and _ABC<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * 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 "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SynthXilinxPass : public ScriptPass { SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -arch {xcup|xcu|xc7|xc6s}\n"); log(" run synthesis for the specified Xilinx architecture\n"); log(" default: xc7\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nocarry\n"); log(" disable inference of carry chains\n"); log("\n"); log(" -nobram\n"); log(" disable inference of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable inference of distributed rams\n"); log("\n"); log(" -nosrl\n"); log(" disable inference of shift registers\n"); log("\n"); log(" -nomux\n"); log(" disable inference of wide multiplexers\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use abc9 instead of abc\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } std::string top_opt, edif_file, blif_file, abc, arch; bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux; void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; edif_file.clear(); blif_file.clear(); abc = "abc"; flatten = false; retime = false; vpr = false; nocarry = false; nobram = false; nodram = false; nosrl = false; nomux = false; arch = "xc7"; } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-arch" && argidx+1 < args.size()) { arch = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-nosrl") { nosrl = true; continue; } if (args[argidx] == "-nomux") { nomux = true; continue; } if (args[argidx] == "-abc9") { abc = "abc9"; continue; } break; } extra_args(args, argidx, design); if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s") log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str()); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("begin")) { if (vpr) run("read_verilog -lib -D _ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); else run("read_verilog -lib -D _ABC +/xilinx/cells_sim.v"); run("read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram || help_mode) run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')"); run(stringf("hierarchy -check %s", top_opt.c_str())); } if (check_label("flatten", "(with '-flatten' only)")) { if (flatten || help_mode) { run("proc"); run("flatten"); } } if (check_label("coarse")) { run("synth -run coarse"); // shregmap -tech xilinx can cope with $shiftx and $mux // cells for identifying variable-length shift registers, // so attempt to convert $pmux-es to the former // Also: wide multiplexer inference benefits from this too if (!(nosrl && nomux) || help_mode) run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')"); // Run a number of peephole optimisations, including one // that optimises $mul cells driving $shiftx's B input // and that aids wide mux analysis run("peepopt"); } if (check_label("bram", "(skip if '-nobram')")) { if (!nobram || help_mode) { run("memory_bram -rules +/xilinx/brams.txt"); run("techmap -map +/xilinx/brams_map.v"); } } if (check_label("dram", "(skip if '-nodram')")) { if (!nodram || help_mode) { run("memory_bram -rules +/xilinx/drams.txt"); run("techmap -map +/xilinx/drams_map.v"); } } if (check_label("fine")) { run("opt -fast -full"); run("memory_map"); run("dffsr2dff"); run("dff2dffe"); run("opt -full"); if (!nosrl || help_mode) { // shregmap operates on bit-level flops, not word-level, // so break those down here run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')"); // shregmap with '-tech xilinx' infers variable length shift regs run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')"); } std::string techmap_files = " -map +/techmap.v"; if (help_mode) techmap_files += " [-map +/xilinx/mux_map.v]"; else if (!nomux) techmap_files += " -map +/xilinx/mux_map.v"; if (help_mode) techmap_files += " [-map +/xilinx/arith_map.v]"; else if (!nocarry) { techmap_files += " -map +/xilinx/arith_map.v"; if (vpr) techmap_files += " -D _EXPLICIT_CARRY"; else if (abc == "abc9") techmap_files += " -D _CLB_CARRY"; } run("techmap " + techmap_files); run("opt -fast"); } if (check_label("map_cells")) { run("techmap -map +/techmap.v -map +/xilinx/cells_map.v"); run("clean"); } if (check_label("map_luts")) { if (abc == "abc9") run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : "")); else if (help_mode) run(abc + " -luts 2:2,3,6:5,10,20 [-dff]"); else run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : "")); run("clean"); // This shregmap call infers fixed length shift registers after abc // has performed any necessary retiming if (!nosrl || help_mode) run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')"); run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v"); run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat -tech xilinx"); run("check -noinit"); } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) run(stringf("write_blif %s", edif_file.c_str())); } } } SynthXilinxPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <string> #include <map> #include <iostream> // TODO: remove me! #include "../../cvmfs/catalog_traversal.h" #include "../../cvmfs/manifest.h" #include "../../cvmfs/hash.h" using namespace swissknife; static const std::string rhs = "f9d87ae2cc46be52b324335ff05fae4c1a7c4dd4"; static const shash::Any root_hash = shash::Any(shash::kSha1, shash::HexPtr(rhs)); /** * This is a mock of an ObjectFetcher that does essentially nothing. */ class MockObjectFetcher { public: MockObjectFetcher(const CatalogTraversalParams &params) {} public: manifest::Manifest* FetchManifest() { return new manifest::Manifest(root_hash, 0, ""); } inline bool Fetch(const shash::Any &catalog_hash, std::string *catalog_file) { return true; } inline bool Exists(const std::string &file) { return false; } }; /** * This is a minimal mock of a Catalog class. */ class MockCatalog { public: typedef std::map<shash::Any, MockCatalog*> AvailableCatalogs; static AvailableCatalogs available_catalogs; static void RegisterCatalog(MockCatalog *catalog) { ASSERT_EQ (MockCatalog::available_catalogs.end(), MockCatalog::available_catalogs.find(catalog->catalog_hash())); MockCatalog::available_catalogs[catalog->catalog_hash()] = catalog; } static void UnregisterCatalogs() { MockCatalog::AvailableCatalogs::const_iterator i, iend; for (i = MockCatalog::available_catalogs.begin(), iend = MockCatalog::available_catalogs.end(); i != iend; ++i) { delete i->second; } MockCatalog::available_catalogs.clear(); } static MockCatalog* GetCatalog(const shash::Any &catalog_hash) { AvailableCatalogs::const_iterator clg_itr = MockCatalog::available_catalogs.find(catalog_hash); return (MockCatalog::available_catalogs.end() != clg_itr) ? clg_itr->second : NULL; } public: struct NestedCatalog { PathString path; shash::Any hash; MockCatalog *child; uint64_t size; }; typedef std::vector<NestedCatalog> NestedCatalogList; public: MockCatalog(const std::string &root_path, const shash::Any &catalog_hash, const uint64_t catalog_size, MockCatalog *parent = NULL, MockCatalog *previous = NULL) : parent_(parent), previous_(previous), root_path_(root_path), catalog_hash_(catalog_hash), catalog_size_(catalog_size) { if (parent != NULL) { parent->RegisterChild(this); } } public: /* API in this 'public block' is used by CatalogTraversal * (see catalog.h - catalog::Catalog for details) */ static MockCatalog* AttachFreely(const std::string &root_path, const std::string &file, const shash::Any &catalog_hash, MockCatalog *parent = NULL) { const MockCatalog *catalog = MockCatalog::GetCatalog(catalog_hash); if (catalog == NULL) { return NULL; } else { return catalog->Clone(); } } bool IsRoot() const { return (parent_ == NULL); } NestedCatalogList *ListNestedCatalogs() const { return const_cast<NestedCatalogList*>(&children_); } shash::Any GetPreviousRevision() const { return (previous_ != NULL) ? previous_->catalog_hash() : shash::Any(); } public: const std::string& root_path() const { return root_path_; } const shash::Any& catalog_hash() const { return catalog_hash_; } uint64_t catalog_size() const { return catalog_size_; } protected: void RegisterChild(MockCatalog *child) { NestedCatalog nested; nested.path = PathString(child->root_path()); nested.hash = child->catalog_hash(); nested.child = child; nested.size = child->catalog_size(); children_.push_back(nested); } MockCatalog* Clone() const { MockCatalog *new_catalog = new MockCatalog(root_path_, catalog_hash_, catalog_size_, parent_, previous_); new_catalog->children_ = children_; return new_catalog; } private: MockCatalog *parent_; MockCatalog *previous_; const std::string root_path_; const shash::Any catalog_hash_; const uint64_t catalog_size_; NestedCatalogList children_; }; MockCatalog::AvailableCatalogs MockCatalog::available_catalogs; // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // typedef CatalogTraversal<MockCatalog, MockObjectFetcher> MockedCatalogTraversal; class T_CatalogTraversal : public ::testing::Test { public: MockCatalog *dummy_catalog_hierarchy; protected: void SetUp() { SetupDummyCatalogs(); } void TearDown() { MockCatalog::UnregisterCatalogs(); } void SetupDummyCatalogs() { /** * Dummy catalog hierarchy: * * 0-0 HEAD * | * +-------------------+---------------+---------------+ * | | | | * 1-0 1-1 1-2 1-3 * | | | | * +-------------+ +----+----+ +----+----+ +----+ * | | | | | | | | | | * 2-0 2-1 2-2 2-3 2-4 2-5 2-6 2-7 2-8 2-9 * | | | * +----+----+ +-----+ +-----+-----+-----+ * | | | | | | | | | * 3-0 3-1 3-2 3-3 3-4 3-5 3-6 3-7 3-8 * | | * | +-----+-----+ * | | | | * 4-0 4-1 4-2 4-3 * * Parts of the hierarchy are created multiple times in order to get some * historic catalogs. To simplify the creation the history looks like so: * Revision 1: - only the root catalog (0-0) * Revision 2: - adds branch 1-0 * Revision 3: - adds branch 1-1 * Revision 4: - adds branch 1-2 and branch 1-1 is recreated * Revision 5: - adds branch 1-3 * */ MockCatalog *head = CreateAndRegisterCatalog("", root_hash, 42); Make_10_Branch(head); Make_11_Branch(head); Make_12_Branch(head); Make_13_Branch(head); } void Make_10_Branch(MockCatalog *parent) { MockCatalog *_10 = CreateAndRegisterCatalog("/00/10", GetRandomHash(), 13124, parent); MockCatalog *_20 = CreateAndRegisterCatalog("/00/10/20", GetRandomHash(), 23524, _10); MockCatalog *_21 = CreateAndRegisterCatalog("/00/10/21", GetRandomHash(), 74546, _10); MockCatalog *_30 = CreateAndRegisterCatalog("/00/10/20/30", GetRandomHash(), 66234, _20); MockCatalog *_31 = CreateAndRegisterCatalog("/00/10/20/31", GetRandomHash(), 87365, _20); MockCatalog *_32 = CreateAndRegisterCatalog("/00/10/20/32", GetRandomHash(), 93405, _20); MockCatalog *_40 = CreateAndRegisterCatalog("/00/10/20/30/40", GetRandomHash(), 85617, _30); } void Make_11_Branch(MockCatalog *parent) { MockCatalog *_11 = CreateAndRegisterCatalog("/00/11", GetRandomHash(), 87648, parent); MockCatalog *_22 = CreateAndRegisterCatalog("/00/11/22", GetRandomHash(), 86546, _11); MockCatalog *_23 = CreateAndRegisterCatalog("/00/11/23", GetRandomHash(), 98565, _11); MockCatalog *_24 = CreateAndRegisterCatalog("/00/11/24", GetRandomHash(), 45271, _11); MockCatalog *_33 = CreateAndRegisterCatalog("/00/11/22/33", GetRandomHash(), 17412, _22); MockCatalog *_34 = CreateAndRegisterCatalog("/00/11/22/34", GetRandomHash(), 89127, _22); MockCatalog *_41 = CreateAndRegisterCatalog("/00/11/22/34/41", GetRandomHash(), 10987, _34); MockCatalog *_42 = CreateAndRegisterCatalog("/00/11/22/34/42", GetRandomHash(), 40987, _34); MockCatalog *_43 = CreateAndRegisterCatalog("/00/11/22/34/43", GetRandomHash(), 12234, _34); } void Make_12_Branch(MockCatalog *parent) { MockCatalog *_12 = CreateAndRegisterCatalog("/00/12", GetRandomHash(), 39272, parent); MockCatalog *_25 = CreateAndRegisterCatalog("/00/12/25", GetRandomHash(), 91999, _12); MockCatalog *_26 = CreateAndRegisterCatalog("/00/12/26", GetRandomHash(), 11111, _12); MockCatalog *_27 = CreateAndRegisterCatalog("/00/12/27", GetRandomHash(), 12344, _12); MockCatalog *_35 = CreateAndRegisterCatalog("/00/12/26/35", GetRandomHash(), 99992, _26); MockCatalog *_36 = CreateAndRegisterCatalog("/00/12/26/36", GetRandomHash(), 12333, _26); MockCatalog *_37 = CreateAndRegisterCatalog("/00/12/26/37", GetRandomHash(), 23442, _26); MockCatalog *_38 = CreateAndRegisterCatalog("/00/12/26/38", GetRandomHash(), 14112, _26); } void Make_13_Branch(MockCatalog *parent) { MockCatalog *_13 = CreateAndRegisterCatalog("/00/13", GetRandomHash(), 14120, parent); MockCatalog *_28 = CreateAndRegisterCatalog("/00/13/28", GetRandomHash(), 92370, _13); MockCatalog *_29 = CreateAndRegisterCatalog("/00/13/29", GetRandomHash(), 14122, _13); } private: MockCatalog* CreateAndRegisterCatalog(const std::string &root_path, const shash::Any &catalog_hash, const uint64_t catalog_size, MockCatalog *parent = NULL, MockCatalog *previous = NULL) { MockCatalog *catalog = new MockCatalog(root_path, catalog_hash, catalog_size, parent, previous); MockCatalog::RegisterCatalog(catalog); return catalog; } shash::Any GetRandomHash() const { shash::Any hash(shash::kSha1); hash.Randomize(); return hash; } }; // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_CatalogTraversal, Initialize) { CatalogTraversalParams params; MockedCatalogTraversal traverse(params); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // CatalogTraversal<MockCatalog, MockObjectFetcher> traverse(params); traverse.Traverse(); } <commit_msg>add revision to MockCatalog<commit_after>#include <gtest/gtest.h> #include <string> #include <map> #include <cassert> #include <iostream> // TODO: remove me! #include "../../cvmfs/prng.h" #include "../../cvmfs/catalog_traversal.h" #include "../../cvmfs/manifest.h" #include "../../cvmfs/hash.h" using namespace swissknife; static const std::string rhs = "f9d87ae2cc46be52b324335ff05fae4c1a7c4dd4"; static const shash::Any root_hash = shash::Any(shash::kSha1, shash::HexPtr(rhs)); /** * This is a mock of an ObjectFetcher that does essentially nothing. */ class MockObjectFetcher { public: MockObjectFetcher(const CatalogTraversalParams &params) {} public: manifest::Manifest* FetchManifest() { return new manifest::Manifest(root_hash, 0, ""); } inline bool Fetch(const shash::Any &catalog_hash, std::string *catalog_file) { return true; } inline bool Exists(const std::string &file) { return false; } }; /** * This is a minimal mock of a Catalog class. */ class MockCatalog { public: typedef std::map<shash::Any, MockCatalog*> AvailableCatalogs; static AvailableCatalogs available_catalogs; static void RegisterCatalog(MockCatalog *catalog) { ASSERT_EQ (MockCatalog::available_catalogs.end(), MockCatalog::available_catalogs.find(catalog->catalog_hash())); MockCatalog::available_catalogs[catalog->catalog_hash()] = catalog; } static void UnregisterCatalogs() { MockCatalog::AvailableCatalogs::const_iterator i, iend; for (i = MockCatalog::available_catalogs.begin(), iend = MockCatalog::available_catalogs.end(); i != iend; ++i) { delete i->second; } MockCatalog::available_catalogs.clear(); } static MockCatalog* GetCatalog(const shash::Any &catalog_hash) { AvailableCatalogs::const_iterator clg_itr = MockCatalog::available_catalogs.find(catalog_hash); return (MockCatalog::available_catalogs.end() != clg_itr) ? clg_itr->second : NULL; } public: struct NestedCatalog { PathString path; shash::Any hash; MockCatalog *child; uint64_t size; }; typedef std::vector<NestedCatalog> NestedCatalogList; public: MockCatalog(const std::string &root_path, const shash::Any &catalog_hash, const uint64_t catalog_size, const unsigned int revision, MockCatalog *parent = NULL, MockCatalog *previous = NULL) : parent_(parent), previous_(previous), root_path_(root_path), catalog_hash_(catalog_hash), catalog_size_(catalog_size), revision_(revision) { if (parent != NULL) { parent->RegisterChild(this); } } public: /* API in this 'public block' is used by CatalogTraversal * (see catalog.h - catalog::Catalog for details) */ static MockCatalog* AttachFreely(const std::string &root_path, const std::string &file, const shash::Any &catalog_hash, MockCatalog *parent = NULL) { const MockCatalog *catalog = MockCatalog::GetCatalog(catalog_hash); if (catalog == NULL) { return NULL; } else { return catalog->Clone(); } } bool IsRoot() const { return (parent_ == NULL); } NestedCatalogList *ListNestedCatalogs() const { return const_cast<NestedCatalogList*>(&children_); } shash::Any GetPreviousRevision() const { return (previous_ != NULL) ? previous_->catalog_hash() : shash::Any(); } public: const std::string& root_path() const { return root_path_; } const shash::Any& catalog_hash() const { return catalog_hash_; } uint64_t catalog_size() const { return catalog_size_; } unsigned int revision() const { return revision_; } MockCatalog* parent() const { return parent_; } MockCatalog* previous() const { return previous_; } public: void RegisterChild(MockCatalog *child) { NestedCatalog nested; nested.path = PathString(child->root_path()); nested.hash = child->catalog_hash(); nested.child = child; nested.size = child->catalog_size(); children_.push_back(nested); } protected: MockCatalog* Clone() const { MockCatalog *new_catalog = new MockCatalog(root_path_, catalog_hash_, catalog_size_, revision_, parent_, previous_); new_catalog->children_ = children_; return new_catalog; } private: MockCatalog *parent_; MockCatalog *previous_; const std::string root_path_; const shash::Any catalog_hash_; const uint64_t catalog_size_; const unsigned int revision_; NestedCatalogList children_; }; MockCatalog::AvailableCatalogs MockCatalog::available_catalogs; // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // typedef CatalogTraversal<MockCatalog, MockObjectFetcher> MockedCatalogTraversal; class T_CatalogTraversal : public ::testing::Test { public: MockCatalog *dummy_catalog_hierarchy; protected: void SetUp() { SetupDummyCatalogs(); } void TearDown() { MockCatalog::UnregisterCatalogs(); } void SetupDummyCatalogs() { /** * Dummy catalog hierarchy: * * 0-0 HEAD * | * +-------------------+---------------+---------------+ * | | | | * 1-0 1-1 1-2 1-3 * | | | | * +-------------+ +----+----+ +----+----+ +----+ * | | | | | | | | | | * 2-0 2-1 2-2 2-3 2-4 2-5 2-6 2-7 2-8 2-9 * | | | * +----+----+ +-----+ +-----+-----+-----+ * | | | | | | | | | * 3-0 3-1 3-2 3-3 3-4 3-5 3-6 3-7 3-8 * | | * | +-----+-----+ * | | | | * 4-0 4-1 4-2 4-3 * * Parts of the hierarchy are created multiple times in order to get some * historic catalogs. To simplify the creation the history looks like so: * Revision 1: - only the root catalog (0-0) * Revision 2: - adds branch 1-0 * Revision 3: - adds branch 1-1 * Revision 4: - adds branch 1-2 and branch 1-1 is recreated * Revision 5: - adds branch 1-3 * */ MockCatalog *head = CreateAndRegisterCatalog("", root_hash, 42); Make_10_Branch(head); Make_11_Branch(head); Make_12_Branch(head); Make_13_Branch(head); } void Make_10_Branch(MockCatalog *parent) { MockCatalog *_10 = CreateAndRegisterCatalog("/00/10", GetRandomHash(), 13124, parent); MockCatalog *_20 = CreateAndRegisterCatalog("/00/10/20", GetRandomHash(), 23524, _10); MockCatalog *_21 = CreateAndRegisterCatalog("/00/10/21", GetRandomHash(), 74546, _10); MockCatalog *_30 = CreateAndRegisterCatalog("/00/10/20/30", GetRandomHash(), 66234, _20); MockCatalog *_31 = CreateAndRegisterCatalog("/00/10/20/31", GetRandomHash(), 87365, _20); MockCatalog *_32 = CreateAndRegisterCatalog("/00/10/20/32", GetRandomHash(), 93405, _20); MockCatalog *_40 = CreateAndRegisterCatalog("/00/10/20/30/40", GetRandomHash(), 85617, _30); } void Make_11_Branch(MockCatalog *parent) { MockCatalog *_11 = CreateAndRegisterCatalog("/00/11", GetRandomHash(), 87648, parent); MockCatalog *_22 = CreateAndRegisterCatalog("/00/11/22", GetRandomHash(), 86546, _11); MockCatalog *_23 = CreateAndRegisterCatalog("/00/11/23", GetRandomHash(), 98565, _11); MockCatalog *_24 = CreateAndRegisterCatalog("/00/11/24", GetRandomHash(), 45271, _11); MockCatalog *_33 = CreateAndRegisterCatalog("/00/11/22/33", GetRandomHash(), 17412, _22); MockCatalog *_34 = CreateAndRegisterCatalog("/00/11/22/34", GetRandomHash(), 89127, _22); MockCatalog *_41 = CreateAndRegisterCatalog("/00/11/22/34/41", GetRandomHash(), 10987, _34); MockCatalog *_42 = CreateAndRegisterCatalog("/00/11/22/34/42", GetRandomHash(), 40987, _34); MockCatalog *_43 = CreateAndRegisterCatalog("/00/11/22/34/43", GetRandomHash(), 12234, _34); } void Make_12_Branch(MockCatalog *parent) { MockCatalog *_12 = CreateAndRegisterCatalog("/00/12", GetRandomHash(), 39272, parent); MockCatalog *_25 = CreateAndRegisterCatalog("/00/12/25", GetRandomHash(), 91999, _12); MockCatalog *_26 = CreateAndRegisterCatalog("/00/12/26", GetRandomHash(), 11111, _12); MockCatalog *_27 = CreateAndRegisterCatalog("/00/12/27", GetRandomHash(), 12344, _12); MockCatalog *_35 = CreateAndRegisterCatalog("/00/12/26/35", GetRandomHash(), 99992, _26); MockCatalog *_36 = CreateAndRegisterCatalog("/00/12/26/36", GetRandomHash(), 12333, _26); MockCatalog *_37 = CreateAndRegisterCatalog("/00/12/26/37", GetRandomHash(), 23442, _26); MockCatalog *_38 = CreateAndRegisterCatalog("/00/12/26/38", GetRandomHash(), 14112, _26); } void Make_13_Branch(MockCatalog *parent) { MockCatalog *_13 = CreateAndRegisterCatalog("/00/13", GetRandomHash(), 14120, parent); MockCatalog *_28 = CreateAndRegisterCatalog("/00/13/28", GetRandomHash(), 92370, _13); MockCatalog *_29 = CreateAndRegisterCatalog("/00/13/29", GetRandomHash(), 14122, _13); } private: MockCatalog* CreateAndRegisterCatalog(const std::string &root_path, const shash::Any &catalog_hash, const uint64_t catalog_size, MockCatalog *parent = NULL, MockCatalog *previous = NULL) { MockCatalog *catalog = new MockCatalog(root_path, catalog_hash, catalog_size, parent, previous); MockCatalog::RegisterCatalog(catalog); return catalog; } shash::Any GetRandomHash() const { shash::Any hash(shash::kSha1); hash.Randomize(); return hash; } }; // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_CatalogTraversal, Initialize) { CatalogTraversalParams params; MockedCatalogTraversal traverse(params); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // CatalogTraversal<MockCatalog, MockObjectFetcher> traverse(params); traverse.Traverse(); } <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: sligocki@google.com (Shawn Ligocki) #include "net/instaweb/rewriter/public/association_transformer.h" #include "net/instaweb/http/public/request_context.h" #include "net/instaweb/rewriter/public/css_url_counter.h" #include "net/instaweb/rewriter/public/resource.h" #include "net/instaweb/rewriter/public/resource_slot.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/util/public/google_url.h" #include "net/instaweb/util/public/gtest.h" #include "net/instaweb/util/public/null_message_handler.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" #include "net/instaweb/util/public/string_writer.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/thread_system.h" #include "pagespeed/kernel/util/platform.h" namespace net_instaweb { namespace { class DummyResource : public Resource { public: DummyResource() : Resource(NULL, NULL) {} virtual ~DummyResource() {} void set_url(const StringPiece& url) { url_ = url.as_string(); } virtual GoogleString url() const { return url_; } virtual const RewriteOptions* rewrite_options() const { return NULL; } virtual void LoadAndCallback(NotCacheablePolicy not_cacheable_policy, const RequestContextPtr& request_context, AsyncCallback* callback) { callback->Done(false, false); } virtual bool UseHttpCache() const { return false; } private: GoogleString url_; DISALLOW_COPY_AND_ASSIGN(DummyResource); }; class DummyTransformer : public CssTagScanner::Transformer { public: DummyTransformer() {} virtual ~DummyTransformer() {} virtual TransformStatus Transform(const StringPiece& in, GoogleString* out) { *out = StrCat("Dummy:", in); return kSuccess; } private: DISALLOW_COPY_AND_ASSIGN(DummyTransformer); }; } // namespace class AssociationTransformerTest : public ::testing::Test { protected: AssociationTransformerTest() : thread_system_(Platform::CreateThreadSystem()) { RewriteOptions::Initialize(); options_.reset(new RewriteOptions(thread_system_.get())); options_->set_preserve_url_relativity(true); } template <class T> void ExpectValue(const std::map<GoogleString, T>& map, const StringPiece& key, const T& expected_value) { typename std::map<GoogleString, T>::const_iterator iter = map.find(key.as_string()); ASSERT_NE(map.end(), iter) << "map does not have key " << key; EXPECT_EQ(expected_value, iter->second) << "map[\"" << key << "\"] not as expected"; } scoped_ptr<ThreadSystem> thread_system_; scoped_ptr<RewriteOptions> options_; }; TEST_F(AssociationTransformerTest, TransformsCorrectly) { const char css_template[] = "blah fwe.fwei ofe w {{{ " "url('%s') fafwe" "@import '%s';829hqbr23b" "url()" // Empty URLs are left alone. "url(%s)" "url(%s)" "url(%s)"; const GoogleString css_before = StringPrintf( css_template, "image.gif", "before.css", "http://example.com/before.css", "http://other.org/foo.ttf", "data:text/plain,Foobar"); GoogleUrl base_url("http://example.com/"); NullMessageHandler handler; CssUrlCounter url_counter(&base_url, &handler); DummyTransformer backup_trans; AssociationTransformer trans(&base_url, options_.get(), &backup_trans, &handler); // Run first pass. EXPECT_TRUE(url_counter.Count(css_before)); // Check that 1 URL was discovered and absolutified correctly. EXPECT_EQ(4, url_counter.url_counts().size()); ExpectValue(url_counter.url_counts(), "http://example.com/image.gif", 1); ExpectValue(url_counter.url_counts(), "http://example.com/before.css", 2); ExpectValue(url_counter.url_counts(), "http://other.org/foo.ttf", 1); ExpectValue(url_counter.url_counts(), "data:text/plain,Foobar", 1); // Provide URL association. DummyResource* resource = new DummyResource; ResourcePtr resource_ptr(resource); ResourceSlotPtr slot(new AssociationSlot( resource_ptr, trans.map(), "http://example.com/before.css")); resource->set_url("http://example.com/after.css"); slot->Render(); // Check that the association was registered. EXPECT_EQ(1, trans.map()->size()); ExpectValue<GoogleString>(*trans.map(), "http://example.com/before.css", "http://example.com/after.css"); // Run second pass. GoogleString out; StringWriter out_writer(&out); EXPECT_TRUE(CssTagScanner::TransformUrls(css_before, &out_writer, &trans, &handler)); // Check that contents was rewritten correctly. const GoogleString css_after = StringPrintf( css_template, // image.gif did not have an association set, so it was passed to // DummyTransformer. "Dummy:image.gif", // before.css was rewritten in both places to after.css. // The first one stays relative and the second stays absolute. "after.css", "http://example.com/after.css", // Passed through DummyTransformer. "Dummy:http://other.org/foo.ttf", "Dummy:data:text/plain,Foobar"); EXPECT_EQ(css_after, out); } TEST_F(AssociationTransformerTest, FailsOnInvalidUrl) { const char css_before[] = "url(////)"; GoogleUrl base_url("http://example.com/"); DummyTransformer backup_trans; NullMessageHandler handler; AssociationTransformer trans(&base_url, options_.get(), &backup_trans, &handler); // Transform fails because there is an invalid URL. GoogleString out; StringWriter out_writer(&out); EXPECT_FALSE(CssTagScanner::TransformUrls(css_before, &out_writer, &trans, &handler)); } } // namespace net_instaweb <commit_msg>Fix leak in test (spotted as "possibly lost" by vg)<commit_after>/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: sligocki@google.com (Shawn Ligocki) #include "net/instaweb/rewriter/public/association_transformer.h" #include "net/instaweb/http/public/request_context.h" #include "net/instaweb/rewriter/public/css_url_counter.h" #include "net/instaweb/rewriter/public/resource.h" #include "net/instaweb/rewriter/public/resource_slot.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/util/public/google_url.h" #include "net/instaweb/util/public/gtest.h" #include "net/instaweb/util/public/null_message_handler.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" #include "net/instaweb/util/public/string_writer.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/thread_system.h" #include "pagespeed/kernel/util/platform.h" namespace net_instaweb { namespace { class DummyResource : public Resource { public: DummyResource() : Resource(NULL, NULL) {} virtual ~DummyResource() {} void set_url(const StringPiece& url) { url_ = url.as_string(); } virtual GoogleString url() const { return url_; } virtual const RewriteOptions* rewrite_options() const { return NULL; } virtual void LoadAndCallback(NotCacheablePolicy not_cacheable_policy, const RequestContextPtr& request_context, AsyncCallback* callback) { callback->Done(false, false); } virtual bool UseHttpCache() const { return false; } private: GoogleString url_; DISALLOW_COPY_AND_ASSIGN(DummyResource); }; class DummyTransformer : public CssTagScanner::Transformer { public: DummyTransformer() {} virtual ~DummyTransformer() {} virtual TransformStatus Transform(const StringPiece& in, GoogleString* out) { *out = StrCat("Dummy:", in); return kSuccess; } private: DISALLOW_COPY_AND_ASSIGN(DummyTransformer); }; } // namespace class AssociationTransformerTest : public ::testing::Test { protected: AssociationTransformerTest() : thread_system_(Platform::CreateThreadSystem()) { RewriteOptions::Initialize(); options_.reset(new RewriteOptions(thread_system_.get())); options_->set_preserve_url_relativity(true); } ~AssociationTransformerTest() { RewriteOptions::Terminate(); } template <class T> void ExpectValue(const std::map<GoogleString, T>& map, const StringPiece& key, const T& expected_value) { typename std::map<GoogleString, T>::const_iterator iter = map.find(key.as_string()); ASSERT_NE(map.end(), iter) << "map does not have key " << key; EXPECT_EQ(expected_value, iter->second) << "map[\"" << key << "\"] not as expected"; } scoped_ptr<ThreadSystem> thread_system_; scoped_ptr<RewriteOptions> options_; }; TEST_F(AssociationTransformerTest, TransformsCorrectly) { const char css_template[] = "blah fwe.fwei ofe w {{{ " "url('%s') fafwe" "@import '%s';829hqbr23b" "url()" // Empty URLs are left alone. "url(%s)" "url(%s)" "url(%s)"; const GoogleString css_before = StringPrintf( css_template, "image.gif", "before.css", "http://example.com/before.css", "http://other.org/foo.ttf", "data:text/plain,Foobar"); GoogleUrl base_url("http://example.com/"); NullMessageHandler handler; CssUrlCounter url_counter(&base_url, &handler); DummyTransformer backup_trans; AssociationTransformer trans(&base_url, options_.get(), &backup_trans, &handler); // Run first pass. EXPECT_TRUE(url_counter.Count(css_before)); // Check that 1 URL was discovered and absolutified correctly. EXPECT_EQ(4, url_counter.url_counts().size()); ExpectValue(url_counter.url_counts(), "http://example.com/image.gif", 1); ExpectValue(url_counter.url_counts(), "http://example.com/before.css", 2); ExpectValue(url_counter.url_counts(), "http://other.org/foo.ttf", 1); ExpectValue(url_counter.url_counts(), "data:text/plain,Foobar", 1); // Provide URL association. DummyResource* resource = new DummyResource; ResourcePtr resource_ptr(resource); ResourceSlotPtr slot(new AssociationSlot( resource_ptr, trans.map(), "http://example.com/before.css")); resource->set_url("http://example.com/after.css"); slot->Render(); // Check that the association was registered. EXPECT_EQ(1, trans.map()->size()); ExpectValue<GoogleString>(*trans.map(), "http://example.com/before.css", "http://example.com/after.css"); // Run second pass. GoogleString out; StringWriter out_writer(&out); EXPECT_TRUE(CssTagScanner::TransformUrls(css_before, &out_writer, &trans, &handler)); // Check that contents was rewritten correctly. const GoogleString css_after = StringPrintf( css_template, // image.gif did not have an association set, so it was passed to // DummyTransformer. "Dummy:image.gif", // before.css was rewritten in both places to after.css. // The first one stays relative and the second stays absolute. "after.css", "http://example.com/after.css", // Passed through DummyTransformer. "Dummy:http://other.org/foo.ttf", "Dummy:data:text/plain,Foobar"); EXPECT_EQ(css_after, out); } TEST_F(AssociationTransformerTest, FailsOnInvalidUrl) { const char css_before[] = "url(////)"; GoogleUrl base_url("http://example.com/"); DummyTransformer backup_trans; NullMessageHandler handler; AssociationTransformer trans(&base_url, options_.get(), &backup_trans, &handler); // Transform fails because there is an invalid URL. GoogleString out; StringWriter out_writer(&out); EXPECT_FALSE(CssTagScanner::TransformUrls(css_before, &out_writer, &trans, &handler)); } } // namespace net_instaweb <|endoftext|>
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #ifndef OUZEL_NETWORK_SOCKET_HPP #define OUZEL_NETWORK_SOCKET_HPP #include <stdexcept> #include <system_error> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <winsock2.h> # include <ws2tcpip.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__unix__) || defined(__APPLE__) # include <sys/socket.h> # include <netinet/in.h> # include <netdb.h> # include <unistd.h> # include <errno.h> #endif namespace ouzel { namespace network { inline int getLastError() noexcept { #if defined(_WIN32) return WSAGetLastError(); #elif defined(__unix__) || defined(__APPLE__) return errno; #endif } enum class InternetProtocol: uint8_t { V4, V6 }; constexpr int getAddressFamily(InternetProtocol internetProtocol) { return (internetProtocol == InternetProtocol::V4) ? AF_INET : (internetProtocol == InternetProtocol::V6) ? AF_INET6 : throw std::runtime_error("Unsupported protocol"); } class Socket final { public: #if defined(_WIN32) using Type = SOCKET; static constexpr Type Invalid = INVALID_SOCKET; #elif defined(__unix__) || defined(__APPLE__) using Type = int; static constexpr Type Invalid = -1; #endif explicit Socket(InternetProtocol internetProtocol = InternetProtocol::V4): endpoint(socket(getAddressFamily(internetProtocol), SOCK_STREAM, IPPROTO_TCP)) { if (endpoint == Invalid) throw std::system_error(getLastError(), std::system_category(), "Failed to create socket"); } explicit constexpr Socket(Type s) noexcept: endpoint(s) { } ~Socket() { if (endpoint != Invalid) #if defined(_WIN32) closesocket(endpoint); #elif defined(__unix__) || defined(__APPLE__) close(endpoint); #endif } Socket(const Socket&) = delete; Socket& operator=(const Socket&) = delete; Socket(Socket&& other) noexcept: endpoint(other.endpoint) { other.endpoint = Invalid; } Socket& operator=(Socket&& other) noexcept { if (&other == this) return *this; if (endpoint != Invalid) #if defined(_WIN32) closesocket(endpoint); #elif defined(__unix__) || defined(__APPLE__) close(endpoint); #endif endpoint = other.endpoint; other.endpoint = Invalid; return *this; } inline operator Type() const noexcept { return endpoint; } private: Type endpoint = Invalid; }; } // namespace network } // namespace ouzel #endif // OUZEL_NETWORK_SOCKET_HPP <commit_msg>Rename Invalid to invalid<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #ifndef OUZEL_NETWORK_SOCKET_HPP #define OUZEL_NETWORK_SOCKET_HPP #include <stdexcept> #include <system_error> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <winsock2.h> # include <ws2tcpip.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__unix__) || defined(__APPLE__) # include <sys/socket.h> # include <netinet/in.h> # include <netdb.h> # include <unistd.h> # include <errno.h> #endif namespace ouzel { namespace network { inline int getLastError() noexcept { #if defined(_WIN32) return WSAGetLastError(); #elif defined(__unix__) || defined(__APPLE__) return errno; #endif } enum class InternetProtocol: uint8_t { V4, V6 }; constexpr int getAddressFamily(InternetProtocol internetProtocol) { return (internetProtocol == InternetProtocol::V4) ? AF_INET : (internetProtocol == InternetProtocol::V6) ? AF_INET6 : throw std::runtime_error("Unsupported protocol"); } class Socket final { public: #if defined(_WIN32) using Type = SOCKET; static constexpr Type invalid = INVALID_SOCKET; #elif defined(__unix__) || defined(__APPLE__) using Type = int; static constexpr Type invalid = -1; #endif explicit Socket(InternetProtocol internetProtocol = InternetProtocol::V4): endpoint(socket(getAddressFamily(internetProtocol), SOCK_STREAM, IPPROTO_TCP)) { if (endpoint == invalid) throw std::system_error(getLastError(), std::system_category(), "Failed to create socket"); } explicit constexpr Socket(Type s) noexcept: endpoint(s) { } ~Socket() { if (endpoint != invalid) #if defined(_WIN32) closesocket(endpoint); #elif defined(__unix__) || defined(__APPLE__) close(endpoint); #endif } Socket(const Socket&) = delete; Socket& operator=(const Socket&) = delete; Socket(Socket&& other) noexcept: endpoint(other.endpoint) { other.endpoint = invalid; } Socket& operator=(Socket&& other) noexcept { if (&other == this) return *this; if (endpoint != invalid) #if defined(_WIN32) closesocket(endpoint); #elif defined(__unix__) || defined(__APPLE__) close(endpoint); #endif endpoint = other.endpoint; other.endpoint = invalid; return *this; } inline operator Type() const noexcept { return endpoint; } private: Type endpoint = invalid; }; } // namespace network } // namespace ouzel #endif // OUZEL_NETWORK_SOCKET_HPP <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "websearch_api_compat.h" #include "cgi.h" #include "urlmatch.h" #include "mrf.h" #ifdef FEATURE_IMG_WEBSEARCH_PLUGIN #include "img_websearch.h" #endif using namespace sp; using lsh::mrf; namespace seeks_plugins { websearch_api_compat::websearch_api_compat() : plugin() { _name = "websearch-api-compat"; _version_major = "0"; _version_minor = "3"; // cgi_dispatchers. cgi_dispatcher *cgid_wb_search = new cgi_dispatcher("search", &websearch_api_compat::cgi_search_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_search); cgi_dispatcher *cgid_wb_search_cache = new cgi_dispatcher("search_cache", &websearch_api_compat::cgi_search_cache_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_search_cache); cgi_dispatcher *cgid_wb_qc_redir = new cgi_dispatcher("qc_redir",&websearch_api_compat::cgi_qc_redir_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_qc_redir); cgi_dispatcher *cgid_wb_tbd = new cgi_dispatcher("tbd",&websearch_api_compat::cgi_tbd_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_tbd); #ifdef FEATURE_IMG_WEBSEARCH_PLUGIN cgi_dispatcher *cgid_iwb_search = new cgi_dispatcher("search_img",&websearch_api_compat::cgi_img_search_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_iwb_search); #endif } websearch_api_compat::~websearch_api_compat() { } sp_err websearch_api_compat::cgi_search_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for action. const char *action = miscutil::lookup(parameters,"action"); if (!action || strcasecmp(action,"expand")==0 || strcasecmp(action,"page")==0) { // route to /search/txt free(csp->_http._path); std::string path = "/search/txt/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_search(csp,rsp,parameters); } else if (strcasecmp(action,"types")==0) { // route to /cluster/types free(csp->_http._path); std::string path = "/cluster/types/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_clustered_types(csp,rsp,parameters); } else if (strcasecmp(action,"clusterize")==0) { // route to /cluster/auto free(csp->_http._path); std::string path = "/cluster/auto/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_clusterize(csp,rsp,parameters); } else if (strcasecmp(action,"similarity")==0) { // route to /similar/txt free(csp->_http._path); std::string path = "/similar/txt/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_similarity(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } else return SP_ERR_CGI_PARAMS; } sp_err websearch_api_compat::cgi_search_cache_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for url. const char *url_str = miscutil::lookup(parameters,"url"); if (!url_str) return SP_ERR_CGI_PARAMS; std::string url = url_str; std::transform(url.begin(),url.end(),url.begin(),tolower); std::string surl = urlmatch::strip_url(url); uint32_t id = mrf::mrf_single_feature(surl); std::string sid = miscutil::to_string(id); miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); // route to /cache free(csp->_http._path); std::string path = "/cache/txt/" + query + "/" + sid; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_search_cache(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } sp_err websearch_api_compat::cgi_qc_redir_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // redirection. miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>\ (parameters),"redirect",1,"1",1); // check for url. const char *url_str = miscutil::lookup(parameters,"url"); if (!url_str) return SP_ERR_CGI_PARAMS; std::string url = url_str; std::transform(url.begin(),url.end(),url.begin(),tolower); std::string surl = urlmatch::strip_url(url); uint32_t id = mrf::mrf_single_feature(surl); std::string sid = miscutil::to_string(id); miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); // route to POST /search/txt free(csp->_http._path); std::string path = "/search/txt/" + query + "/" + sid; csp->_http._path = strdup(path.c_str()); free(csp->_http._gpc); csp->_http._gpc = strdup("post"); return websearch::cgi_websearch_search(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } sp_err websearch_api_compat::cgi_tbd_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for url. const char *url_str = miscutil::lookup(parameters,"url"); if (!url_str) return SP_ERR_CGI_PARAMS; std::string url = url_str; std::transform(url.begin(),url.end(),url.begin(),tolower); std::string surl = urlmatch::strip_url(url); uint32_t id = mrf::mrf_single_feature(surl); std::string sid = miscutil::to_string(id); miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); // route to DELETE /search/txt free(csp->_http._path); std::string path = "/search/txt/" + query + "/" + sid; csp->_http._path = strdup(path.c_str()); free(csp->_http._gpc); csp->_http._gpc = strdup("delete"); sp_err err = websearch::cgi_websearch_search(csp,rsp,parameters); if (err != SP_ERR_OK) return err; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"action",1,"expand",1); miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"output",1,"html",1); //return websearch_api_compat::cgi_search_compat(csp,rsp,parameters); free(csp->_http._gpc); csp->_http._gpc = strdup("get"); free(csp->_http._path); path = "/search/txt/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_search(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } #ifdef FEATURE_IMG_WEBSEARCH_PLUGIN sp_err websearch_api_compat::cgi_img_search_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for action. const char *action = miscutil::lookup(parameters,"action"); if (!action || strcasecmp(action,"expand")==0 || strcasecmp(action,"page")==0) { // route to /search/img free(csp->_http._path); std::string path = "/search/img/" + query; csp->_http._path = strdup(path.c_str()); return img_websearch::cgi_img_websearch_search(csp,rsp,parameters); } #ifdef FEATURE_OPENCV2 else if (strcasecmp(action,"similarity")==0) { // route to /similar/img free(csp->_http._path); std::string path = "/similar/img/" + query; csp->_http._path = strdup(path.c_str()); return img_websearch::cgi_img_websearch_similarity(csp,rsp,parameters); } #endif else return SP_ERR_CGI_PARAMS; } else return SP_ERR_CGI_PARAMS; } #endif /* plugin registration */ extern "C" { plugin* maker() { return new websearch_api_compat; } } } /* end of namespace. */ <commit_msg>fixed double url decoding of query when using websearch API compatibility plugin. (refs #584)<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "websearch_api_compat.h" #include "cgi.h" #include "urlmatch.h" #include "encode.h" #include "mrf.h" #ifdef FEATURE_IMG_WEBSEARCH_PLUGIN #include "img_websearch.h" #endif using namespace sp; using lsh::mrf; namespace seeks_plugins { websearch_api_compat::websearch_api_compat() : plugin() { _name = "websearch-api-compat"; _version_major = "0"; _version_minor = "3"; // cgi_dispatchers. cgi_dispatcher *cgid_wb_search = new cgi_dispatcher("search", &websearch_api_compat::cgi_search_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_search); cgi_dispatcher *cgid_wb_search_cache = new cgi_dispatcher("search_cache", &websearch_api_compat::cgi_search_cache_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_search_cache); cgi_dispatcher *cgid_wb_qc_redir = new cgi_dispatcher("qc_redir",&websearch_api_compat::cgi_qc_redir_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_qc_redir); cgi_dispatcher *cgid_wb_tbd = new cgi_dispatcher("tbd",&websearch_api_compat::cgi_tbd_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_tbd); #ifdef FEATURE_IMG_WEBSEARCH_PLUGIN cgi_dispatcher *cgid_iwb_search = new cgi_dispatcher("search_img",&websearch_api_compat::cgi_img_search_compat, NULL, TRUE); _cgi_dispatchers.push_back(cgid_iwb_search); #endif } websearch_api_compat::~websearch_api_compat() { } sp_err websearch_api_compat::cgi_search_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; char *enc_query = encode::url_encode(query_str); std::string query = enc_query; free(enc_query); miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for action. const char *action = miscutil::lookup(parameters,"action"); if (!action || strcasecmp(action,"expand")==0 || strcasecmp(action,"page")==0) { // route to /search/txt free(csp->_http._path); std::string path = "/search/txt/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_search(csp,rsp,parameters); } else if (strcasecmp(action,"types")==0) { // route to /cluster/types free(csp->_http._path); std::string path = "/cluster/types/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_clustered_types(csp,rsp,parameters); } else if (strcasecmp(action,"clusterize")==0) { // route to /cluster/auto free(csp->_http._path); std::string path = "/cluster/auto/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_clusterize(csp,rsp,parameters); } else if (strcasecmp(action,"similarity")==0) { // route to /similar/txt free(csp->_http._path); std::string path = "/similar/txt/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_similarity(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } else return SP_ERR_CGI_PARAMS; } sp_err websearch_api_compat::cgi_search_cache_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for url. const char *url_str = miscutil::lookup(parameters,"url"); if (!url_str) return SP_ERR_CGI_PARAMS; std::string url = url_str; std::transform(url.begin(),url.end(),url.begin(),tolower); std::string surl = urlmatch::strip_url(url); uint32_t id = mrf::mrf_single_feature(surl); std::string sid = miscutil::to_string(id); miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); // route to /cache free(csp->_http._path); std::string path = "/cache/txt/" + query + "/" + sid; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_search_cache(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } sp_err websearch_api_compat::cgi_qc_redir_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // redirection. miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>\ (parameters),"redirect",1,"1",1); // check for url. const char *url_str = miscutil::lookup(parameters,"url"); if (!url_str) return SP_ERR_CGI_PARAMS; std::string url = url_str; std::transform(url.begin(),url.end(),url.begin(),tolower); std::string surl = urlmatch::strip_url(url); uint32_t id = mrf::mrf_single_feature(surl); std::string sid = miscutil::to_string(id); miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); // route to POST /search/txt free(csp->_http._path); std::string path = "/search/txt/" + query + "/" + sid; csp->_http._path = strdup(path.c_str()); free(csp->_http._gpc); csp->_http._gpc = strdup("post"); return websearch::cgi_websearch_search(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } sp_err websearch_api_compat::cgi_tbd_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for url. const char *url_str = miscutil::lookup(parameters,"url"); if (!url_str) return SP_ERR_CGI_PARAMS; std::string url = url_str; std::transform(url.begin(),url.end(),url.begin(),tolower); std::string surl = urlmatch::strip_url(url); uint32_t id = mrf::mrf_single_feature(surl); std::string sid = miscutil::to_string(id); miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); // route to DELETE /search/txt free(csp->_http._path); std::string path = "/search/txt/" + query + "/" + sid; csp->_http._path = strdup(path.c_str()); free(csp->_http._gpc); csp->_http._gpc = strdup("delete"); sp_err err = websearch::cgi_websearch_search(csp,rsp,parameters); if (err != SP_ERR_OK) return err; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url"); miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"action",1,"expand",1); miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"output",1,"html",1); //return websearch_api_compat::cgi_search_compat(csp,rsp,parameters); free(csp->_http._gpc); csp->_http._gpc = strdup("get"); free(csp->_http._path); path = "/search/txt/" + query; csp->_http._path = strdup(path.c_str()); return websearch::cgi_websearch_search(csp,rsp,parameters); } else return SP_ERR_CGI_PARAMS; } #ifdef FEATURE_IMG_WEBSEARCH_PLUGIN sp_err websearch_api_compat::cgi_img_search_compat(client_state *csp, http_response *rsp, const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { if (!parameters->empty()) { // check for query. const char *query_str = miscutil::lookup(parameters,"q"); if (!query_str || strlen(query_str) == 0) return SP_ERR_CGI_PARAMS; std::string query = query_str; miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q"); // check for action. const char *action = miscutil::lookup(parameters,"action"); if (!action || strcasecmp(action,"expand")==0 || strcasecmp(action,"page")==0) { // route to /search/img free(csp->_http._path); std::string path = "/search/img/" + query; csp->_http._path = strdup(path.c_str()); return img_websearch::cgi_img_websearch_search(csp,rsp,parameters); } #ifdef FEATURE_OPENCV2 else if (strcasecmp(action,"similarity")==0) { // route to /similar/img free(csp->_http._path); std::string path = "/similar/img/" + query; csp->_http._path = strdup(path.c_str()); return img_websearch::cgi_img_websearch_similarity(csp,rsp,parameters); } #endif else return SP_ERR_CGI_PARAMS; } else return SP_ERR_CGI_PARAMS; } #endif /* plugin registration */ extern "C" { plugin* maker() { return new websearch_api_compat; } } } /* end of namespace. */ <|endoftext|>
<commit_before>/* Copyright (C) 1998 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "sysdef.h" #include "csengine/polytmap.h" #include "csengine/textrans.h" #include "csgeom/transfrm.h" //--------------------------------------------------------------------------- IMPLEMENT_CSOBJTYPE (csPolyTxtPlane,csObject); csPolyTxtPlane::csPolyTxtPlane () : csObject () { ref_count = 1; } csPolyTxtPlane::~csPolyTxtPlane () { if (ref_count) printf ("csPolyTxtPlane: ref_count=%d\n", ref_count); } void csPolyTxtPlane::SetTextureSpace ( const csPlane& plane_wor, const csVector3& v_orig, const csVector3& v1, float len) { SetTextureSpace (plane_wor, v_orig.x, v_orig.y, v_orig.z, v1.x, v1.y, v1.z, len); } void csPolyTxtPlane::SetTextureSpace ( const csPlane& plane_wor, float xo, float yo, float zo, float x1, float y1, float z1, float len1) { float A = plane_wor.A (); float B = plane_wor.B (); float C = plane_wor.C (); TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, xo, yo, zo, x1, y1, z1, len1, A, B, C); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( const csVector3& v_orig, const csVector3& v1, float len1, const csVector3& v2, float len2) { TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, v_orig, v1, len1, v2, len2); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( const csVector3& v_orig, const csVector3& v_u, const csVector3& v_v) { TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, v_orig, v_u, v_v); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace (float xo, float yo, float zo, float xu, float yu, float zu, float xv, float yv, float zv) { const csVector3 o(xo, yo, zo); const csVector3 u(xu, yu, zu); const csVector3 v(xv, yv, zv); TextureTrans::compute_texture_space (m_obj2tex, v_obj2tex, o, u, v); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( float xo, float yo, float zo, float xu, float yu, float zu, float xv, float yv, float zv, float xw, float yw, float zw) { TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, xo, yo, zo,xu, yu, zu, xv, yv, zv, xw, yw, zw); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( const csMatrix3& tx_matrix, const csVector3& tx_vector) { m_obj2tex = tx_matrix; m_world2tex = tx_matrix; v_obj2tex = tx_vector; v_world2tex = tx_vector; } void csPolyTxtPlane::GetTextureSpace (csMatrix3& tx_matrix, csVector3& tx_vector) { tx_matrix = m_obj2tex; tx_vector = v_obj2tex; } void csPolyTxtPlane::WorldToCamera ( const csReversibleTransform& t, csMatrix3& m_cam2tex, csVector3& v_cam2tex) { // Create the matrix to transform camera space to texture space. // From: T = Mwt * (W - Vwt) // C = Mwc * (W - Vwc) // To: T = Mct * (C - Vct) // Mcw * C + Vwc = W // T = Mwt * (Mcw * C + Mcw * Mwc * (Vwc - Vwt)) // T = Mwt * Mcw * (C - Mwc * (Vwt-Vwc)) // ===> // Mct = Mwt * Mcw // Vct = Mwc * (Vwt - Vwc) (void) vertex1; m_cam2tex = m_world2tex; m_cam2tex *= t.GetT2O (); v_cam2tex = t.Other2This (v_world2tex); } void csPolyTxtPlane::ObjectToWorld ( const csReversibleTransform& obj) { // From: T = Mot * (O - Vot) // W = Mow * O - Vow // To: T = Mwt * (W - Vwt) // Mwo * (W + Vow) = O // T = Mot * (Mwo * (W + Vow) - (Mwo * Mow) * Vot) // T = Mot * Mwo * (W + Vow - Mow * Vot) // ===> // Mwt = Mot * Mwo // Vwt = Mow * Vot - Vow (void) vertex1; m_world2tex = m_obj2tex; m_world2tex *= obj.GetO2T (); v_world2tex = obj.This2Other (v_obj2tex); } //--------------------------------------------------------------------------- <commit_msg>Undefined variable bugfix<commit_after>/* Copyright (C) 1998 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "sysdef.h" #include "csengine/polytmap.h" #include "csengine/textrans.h" #include "csgeom/transfrm.h" //--------------------------------------------------------------------------- IMPLEMENT_CSOBJTYPE (csPolyTxtPlane,csObject); csPolyTxtPlane::csPolyTxtPlane () : csObject () { ref_count = 1; } csPolyTxtPlane::~csPolyTxtPlane () { if (ref_count) printf ("csPolyTxtPlane: ref_count=%d\n", ref_count); } void csPolyTxtPlane::SetTextureSpace ( const csPlane& plane_wor, const csVector3& v_orig, const csVector3& v1, float len) { SetTextureSpace (plane_wor, v_orig.x, v_orig.y, v_orig.z, v1.x, v1.y, v1.z, len); } void csPolyTxtPlane::SetTextureSpace ( const csPlane& plane_wor, float xo, float yo, float zo, float x1, float y1, float z1, float len1) { float A = plane_wor.A (); float B = plane_wor.B (); float C = plane_wor.C (); TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, xo, yo, zo, x1, y1, z1, len1, A, B, C); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( const csVector3& v_orig, const csVector3& v1, float len1, const csVector3& v2, float len2) { TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, v_orig, v1, len1, v2, len2); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( const csVector3& v_orig, const csVector3& v_u, const csVector3& v_v) { TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, v_orig, v_u, v_v); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace (float xo, float yo, float zo, float xu, float yu, float zu, float xv, float yv, float zv) { const csVector3 o(xo, yo, zo); const csVector3 u(xu, yu, zu); const csVector3 v(xv, yv, zv); TextureTrans::compute_texture_space (m_obj2tex, v_obj2tex, o, u, v); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( float xo, float yo, float zo, float xu, float yu, float zu, float xv, float yv, float zv, float xw, float yw, float zw) { TextureTrans::compute_texture_space ( m_obj2tex, v_obj2tex, xo, yo, zo,xu, yu, zu, xv, yv, zv, xw, yw, zw); m_world2tex = m_obj2tex; v_world2tex = v_obj2tex; } void csPolyTxtPlane::SetTextureSpace ( const csMatrix3& tx_matrix, const csVector3& tx_vector) { m_obj2tex = tx_matrix; m_world2tex = tx_matrix; v_obj2tex = tx_vector; v_world2tex = tx_vector; } void csPolyTxtPlane::GetTextureSpace (csMatrix3& tx_matrix, csVector3& tx_vector) { tx_matrix = m_obj2tex; tx_vector = v_obj2tex; } void csPolyTxtPlane::WorldToCamera ( const csReversibleTransform& t, csMatrix3& m_cam2tex, csVector3& v_cam2tex) { // Create the matrix to transform camera space to texture space. // From: T = Mwt * (W - Vwt) // C = Mwc * (W - Vwc) // To: T = Mct * (C - Vct) // Mcw * C + Vwc = W // T = Mwt * (Mcw * C + Mcw * Mwc * (Vwc - Vwt)) // T = Mwt * Mcw * (C - Mwc * (Vwt-Vwc)) // ===> // Mct = Mwt * Mcw // Vct = Mwc * (Vwt - Vwc) //(void) vertex1; m_cam2tex = m_world2tex; m_cam2tex *= t.GetT2O (); v_cam2tex = t.Other2This (v_world2tex); } void csPolyTxtPlane::ObjectToWorld ( const csReversibleTransform& obj) { // From: T = Mot * (O - Vot) // W = Mow * O - Vow // To: T = Mwt * (W - Vwt) // Mwo * (W + Vow) = O // T = Mot * (Mwo * (W + Vow) - (Mwo * Mow) * Vot) // T = Mot * Mwo * (W + Vow - Mow * Vot) // ===> // Mwt = Mot * Mwo // Vwt = Mow * Vot - Vow // (void) vertex1; m_world2tex = m_obj2tex; m_world2tex *= obj.GetO2T (); v_world2tex = obj.This2Other (v_obj2tex); } //--------------------------------------------------------------------------- <|endoftext|>
<commit_before>#pragma once #include <map> #include <ros/console.h> #include "AbstractCameraQueue.hpp" template <class T> class TrackingQueue { public: TrackingQueue(); ~TrackingQueue(); void enqueue(std::vector<CameraData> data); void enqueue(CameraData data); size_t getSize(); std::vector<CameraData> dequeue(); bool dataAvailable(); private: std::map<int, AbstractCameraQueue*> queues; std::vector<int> ids; int rrIndex; size_t size; }; template <class T> TrackingQueue<T>::TrackingQueue() { size = 0; rrIndex = 0; } template <class T> TrackingQueue<T>::~TrackingQueue() { for (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) { delete it->second; } } template <class T> void TrackingQueue<T>::enqueue(std::vector<CameraData> data) { for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) { enqueue(*it); } } template <class T> void TrackingQueue<T>::enqueue(CameraData data) { if (queues.count(data.quadcopterId) == 0) { queues[data.quadcopterId] = new T(3L * 1000 * 1000 * 1000 / 30, 5L * 1000 * 1000 * 1000 / 30, 2L * 1000 * 1000 * 1000 / 30, true); ids.push_back(data.quadcopterId); } size++; queues[data.quadcopterId]->enqueue(data); } template <class T> size_t TrackingQueue<T>::getSize() { return size; } template <class T> std::vector<CameraData> TrackingQueue<T>::dequeue() { if (size == 0) { return std::vector<CameraData>(); } int index = rrIndex; int loopCount = 0; do { index = (index + 1) % ids.size(); loopCount++; if (queues[ids[index]]->dataAvailable()) { break; } } while (index != rrIndex); if (loopCount > ids.size()) { return std::vector<CameraData>(); } else { rrIndex = index; std::vector<CameraData> result = queues[ids[index]]->dequeue(); size -= result.size(); return result; } } template <class T> bool TrackingQueue<T>::dataAvailable() { for (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) { if (it->second->dataAvailable()) { return true; } } return false; } <commit_msg>Reduced waiting time even lower (1.5 frames)<commit_after>#pragma once #include <map> #include <ros/console.h> #include "AbstractCameraQueue.hpp" template <class T> class TrackingQueue { public: TrackingQueue(); ~TrackingQueue(); void enqueue(std::vector<CameraData> data); void enqueue(CameraData data); size_t getSize(); std::vector<CameraData> dequeue(); bool dataAvailable(); private: std::map<int, AbstractCameraQueue*> queues; std::vector<int> ids; int rrIndex; size_t size; }; template <class T> TrackingQueue<T>::TrackingQueue() { size = 0; rrIndex = 0; } template <class T> TrackingQueue<T>::~TrackingQueue() { for (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) { delete it->second; } } template <class T> void TrackingQueue<T>::enqueue(std::vector<CameraData> data) { for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) { enqueue(*it); } } template <class T> void TrackingQueue<T>::enqueue(CameraData data) { if (queues.count(data.quadcopterId) == 0) { queues[data.quadcopterId] = new T(15L * 100 * 1000 * 1000 / 30, 3L * 1000 * 1000 * 1000 / 30, 2L * 1000 * 1000 * 1000 / 30, true); ids.push_back(data.quadcopterId); } size++; queues[data.quadcopterId]->enqueue(data); } template <class T> size_t TrackingQueue<T>::getSize() { return size; } template <class T> std::vector<CameraData> TrackingQueue<T>::dequeue() { if (size == 0) { return std::vector<CameraData>(); } int index = rrIndex; int loopCount = 0; do { index = (index + 1) % ids.size(); loopCount++; if (queues[ids[index]]->dataAvailable()) { break; } } while (index != rrIndex); if (loopCount > ids.size()) { return std::vector<CameraData>(); } else { rrIndex = index; std::vector<CameraData> result = queues[ids[index]]->dequeue(); size -= result.size(); return result; } } template <class T> bool TrackingQueue<T>::dataAvailable() { for (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) { if (it->second->dataAvailable()) { return true; } } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: resary.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2005-01-03 17:08:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #define _TOOLS_RESARY_CXX #ifndef _TOOLS_RESARY_HXX #include <resary.hxx> #endif #ifndef _TOOLS_RCID_H #include <rcid.h> #endif // ======================================================================= ResStringArray::ResStringArray( const ResId& rResId ) : Resource ( rResId.SetRT( RSC_STRINGARRAY ) ), mpAry ( 0 ), mnSize ( ReadLongRes() ) { if ( mnSize ) { mpAry = new ImplResStringItem*[mnSize]; for ( sal_uInt32 i = 0; i < mnSize; i++ ) { // String laden mpAry[i] = new ImplResStringItem( ReadStringRes() ); // Value laden mpAry[i]->mnValue = ReadLongRes(); } } } // ----------------------------------------------------------------------- ResStringArray::~ResStringArray() { for ( sal_uInt32 i = 0; i < mnSize; i++ ) delete mpAry[i]; delete[] mpAry; } // ----------------------------------------------------------------------- sal_uInt32 ResStringArray::FindIndex( long nValue ) const { for ( sal_uInt32 i = 0; i < mnSize; i++ ) { if ( mpAry[i]->mnValue == nValue ) return i; } return RESARRAY_INDEX_NOTFOUND; } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.74); FILE MERGED 2005/09/05 13:59:29 rt 1.3.74.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: resary.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:30:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #define _TOOLS_RESARY_CXX #ifndef _TOOLS_RESARY_HXX #include <resary.hxx> #endif #ifndef _TOOLS_RCID_H #include <rcid.h> #endif // ======================================================================= ResStringArray::ResStringArray( const ResId& rResId ) : Resource ( rResId.SetRT( RSC_STRINGARRAY ) ), mpAry ( 0 ), mnSize ( ReadLongRes() ) { if ( mnSize ) { mpAry = new ImplResStringItem*[mnSize]; for ( sal_uInt32 i = 0; i < mnSize; i++ ) { // String laden mpAry[i] = new ImplResStringItem( ReadStringRes() ); // Value laden mpAry[i]->mnValue = ReadLongRes(); } } } // ----------------------------------------------------------------------- ResStringArray::~ResStringArray() { for ( sal_uInt32 i = 0; i < mnSize; i++ ) delete mpAry[i]; delete[] mpAry; } // ----------------------------------------------------------------------- sal_uInt32 ResStringArray::FindIndex( long nValue ) const { for ( sal_uInt32 i = 0; i < mnSize; i++ ) { if ( mpAry[i]->mnValue == nValue ) return i; } return RESARRAY_INDEX_NOTFOUND; } <|endoftext|>
<commit_before>/* Copyright (C) 2008-2016 The Communi Project You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sharedtimer.h" #include <QTimerEvent> SharedTimer::SharedTimer(QObject* parent) : QObject(parent) { d.interval = 500; } SharedTimer* SharedTimer::instance() { static SharedTimer timer; return &timer; } int SharedTimer::interval() const { return d.interval; } void SharedTimer::setInterval(int interval) { if (d.timer.isActive()) qWarning("SharedTimer::setInterval(): timer active"); d.interval = interval; } void SharedTimer::registerReceiver(QObject* receiver, const QByteArray& member) { if (!receiver || member.isEmpty()) return; QList<QByteArray> members = d.members.values(receiver); if (!members.contains(member)) { if (d.members.isEmpty()) d.timer.start(d.interval, this); if (!d.members.contains(receiver)) connect(receiver, SIGNAL(destroyed(QObject*)), this, SLOT(destroyed(QObject*))); d.members.insertMulti(receiver, member); } } void SharedTimer::unregisterReceiver(QObject* receiver, const QByteArray& member) { if (!receiver) return; if (member.isNull()) d.members.remove(receiver); else d.members.remove(receiver, member); if (!d.members.contains(receiver)) disconnect(receiver, SIGNAL(destroyed(QObject*)), this, SLOT(destroyed(QObject*))); if (d.members.isEmpty()) d.timer.stop(); } void SharedTimer::pause() { if (d.timer.isActive()) d.timer.stop(); } void SharedTimer::resume() { if (!d.members.isEmpty() && !d.timer.isActive()) d.timer.start(d.interval, this); } void SharedTimer::timerEvent(QTimerEvent* event) { if (event->timerId() == d.timer.timerId()) { QHashIterator<QObject*, QByteArray> it(d.members); while (it.hasNext()) { it.next(); QMetaObject::invokeMethod(it.key(), it.value()); } } } void SharedTimer::destroyed(QObject* object) { unregisterReceiver(object); } <commit_msg>SharedTimer: convert to new style connect/disconnect syntax<commit_after>/* Copyright (C) 2008-2016 The Communi Project You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sharedtimer.h" #include <QTimerEvent> SharedTimer::SharedTimer(QObject* parent) : QObject(parent) { d.interval = 500; } SharedTimer* SharedTimer::instance() { static SharedTimer timer; return &timer; } int SharedTimer::interval() const { return d.interval; } void SharedTimer::setInterval(int interval) { if (d.timer.isActive()) qWarning("SharedTimer::setInterval(): timer active"); d.interval = interval; } void SharedTimer::registerReceiver(QObject* receiver, const QByteArray& member) { if (!receiver || member.isEmpty()) return; QList<QByteArray> members = d.members.values(receiver); if (!members.contains(member)) { if (d.members.isEmpty()) d.timer.start(d.interval, this); if (!d.members.contains(receiver)) connect(receiver, &QObject::destroyed, this, &QObject::destroyed); d.members.insertMulti(receiver, member); } } void SharedTimer::unregisterReceiver(QObject* receiver, const QByteArray& member) { if (!receiver) return; if (member.isNull()) d.members.remove(receiver); else d.members.remove(receiver, member); if (!d.members.contains(receiver)) disconnect(receiver, &QObject::destroyed, this, &QObject::destroyed); if (d.members.isEmpty()) d.timer.stop(); } void SharedTimer::pause() { if (d.timer.isActive()) d.timer.stop(); } void SharedTimer::resume() { if (!d.members.isEmpty() && !d.timer.isActive()) d.timer.start(d.interval, this); } void SharedTimer::timerEvent(QTimerEvent* event) { if (event->timerId() == d.timer.timerId()) { QHashIterator<QObject*, QByteArray> it(d.members); while (it.hasNext()) { it.next(); QMetaObject::invokeMethod(it.key(), it.value()); } } } void SharedTimer::destroyed(QObject* object) { unregisterReceiver(object); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (C) 2006-, Akira Okumura * * All rights reserved. * *****************************************************************************/ // An example of a hexagonal Okumura cone #include "AFocalSurface.h" #include "AGeoBezierPgon.h" #include "AGeoWinstonCone2D.h" #include "AGeoWinstonConePoly.h" #include "ALens.h" #include "AMirror.h" #include "AOpticsManager.h" #include "ARayShooter.h" #include "TAxis.h" #include "TCanvas.h" #include "TGeoBBox.h" #include "TGeoCompositeShape.h" #include "TGeoMatrix.h" #include "TLegend.h" // define useful units static const Double_t cm = AOpticsManager::cm(); static const Double_t mm = AOpticsManager::mm(); static const Double_t um = AOpticsManager::um(); static const Double_t nm = AOpticsManager::nm(); static const Double_t m = AOpticsManager::m(); TGraph* ConeTrace(Int_t mode, bool del) { // mode == 0: hex-hex Winston cone built with AGeoWinstonConePoly // mode == 1: hex-hex Okumura cone built with AGeoBezierPgon AOpticsManager* manager = new AOpticsManager("manager", "SC"); // Make the world TGeoBBox* worldbox = new TGeoBBox("worldbox", 10 * cm, 10 * cm, 10 * cm); AOpticalComponent* world = new AOpticalComponent("world", worldbox); manager->SetTopVolume(world); const Double_t kRin = 20 * mm; const Double_t kRout = 10 * mm; TGeoRotation* rot30 = new TGeoRotation("rot30", 30, 0, 0); rot30->RegisterYourself(); TGeoRotation* rot60 = new TGeoRotation("rot60", 60, 0, 0); rot60->RegisterYourself(); TGeoRotation* rot120 = new TGeoRotation("rot120", 120, 0, 0); rot120->RegisterYourself(); AGeoWinstonCone2D* coneV = new AGeoWinstonCone2D("coneV", kRin, kRout, kRin * 1.733); TGeoPgon* pgon = new TGeoPgon("pgon", 0, 360, 6, 4); pgon->DefineSection(0, -coneV->GetDZ() * 0.9999, 0, kRout * 1.1); pgon->DefineSection(1, -coneV->GetDZ() * 0.5, 0, kRin * 0.9); pgon->DefineSection(2, -coneV->GetDZ() * 0., 0, kRin * 1.001); pgon->DefineSection(3, coneV->GetDZ() * 0.9999, 0, kRin * 1.001); AGeoWinstonConePoly* hexV = new AGeoWinstonConePoly("hexV", kRin, kRout, 6); TGeoCompositeShape* coneComp1 = 0; if (mode == 0) { coneComp1 = new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexV"); } else if (mode == 1) { AGeoBezierPgon* hexB = new AGeoBezierPgon("hexB", 0, 360, 6, 100, kRin, kRout, hexV->GetDZ()); hexB->SetControlPoints(0.39, 0.18, 0.87, 0.36); coneComp1 = new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexB:rot30"); } // if AMirror* coneMirror = new AMirror("coneMirror", coneComp1); world->AddNode(coneMirror, 1); TGeoPgon* pgonPMT = new TGeoPgon("pgonPMT", 0, 360, 6, 2); pgonPMT->DefineSection(0, -coneV->GetDZ() - 0.01 * mm, 0, kRout * 1.01); pgonPMT->DefineSection(1, -coneV->GetDZ(), 0, kRout * 1.01); AFocalSurface* pmt = new AFocalSurface("pmt", pgonPMT); world->AddNode(pmt, 1, rot30); manager->CloseGeometry(); if (mode == 1) { TCanvas* can1 = new TCanvas("can1", "can1"); manager->GetTopVolume()->Draw("ogl"); } // if TGraph* graAeff = new TGraph; for (Double_t deg = 0.; deg < 40.; deg += 0.1) { Double_t Aeff = 0.; for (Double_t phi = 0.; phi < 30.; phi += 0.3) { TGeoTranslation* raytr = new TGeoTranslation( "raytr", 50 * mm * TMath::Sin(deg * TMath::DegToRad()), 0, 50 * mm * TMath::Cos(deg * TMath::DegToRad())); TGeoRotation* rayrot = new TGeoRotation("rayrot", 90 - phi, 180 + deg, 0); TVector3 dir(0, 0, 1); Double_t lambda = 400 * nm; // does not affect the results because we have no lens // 1 photon per 1 mm^2 const int kN = 1000; const double kD = 100 * mm; ARayArray* array = ARayShooter::RandomSquare(lambda, kD, kN, rayrot, raytr, &dir); Double_t dA = kD * kD / kN; manager->TraceNonSequential(*array); TObjArray* focused = array->GetFocused(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; if (!ray) continue; // Calculate the effective area from the number of focused photons Aeff += dA; if (mode == 1 and TMath::Abs(deg - 20.) < 0.001 and j < 50 and phi == 0) { TPolyLine3D* pol = ray->MakePolyLine3D(); pol->SetLineColor(3); pol->SetLineWidth(2); pol->Draw(); } // if } // j delete array; } // phi graAeff->SetPoint(graAeff->GetN(), deg, Aeff / (2 * TMath::Sqrt(3) * kRin * kRin) / TMath::Cos(deg * TMath::DegToRad())); } // deg if (del) { delete manager; manager = 0; } // if return graAeff; } void HexOkumuraCone() { TGraph* win = ConeTrace(0, true); // Winston cone TGraph* oku = ConeTrace(1, false); // Okumura cone TGraph* gra[2] = {win, oku}; TCanvas* can2 = new TCanvas("can2", "can2"); for (int i = 0; i < 2; i++) { gra[i]->GetXaxis()->SetTitle("Incident Angle (deg)"); gra[i]->GetYaxis()->SetTitle("Collection Efficiency (%)"); gra[i]->SetMarkerSize(0.3); gra[i]->SetMarkerStyle(21 + 3 * i); gra[i]->Draw(i == 0 ? "ap" : "p same"); gra[i]->GetXaxis()->SetRangeUser(0, 40.); } // i TGraph* ideal = new TGraph; ideal->SetPoint(0, 0, 100); ideal->SetPoint(1, 30, 100); ideal->SetPoint(2, 30, 0); ideal->SetPoint(3, 40, 0); ideal->Draw("l same"); TLegend* leg = new TLegend(0.15, 0.15, 0.7, 0.35); leg->SetFillStyle(0); leg->SetTextFont(132); leg->AddEntry(ideal, "Ideal 2D Winston Cone", "l"); leg->AddEntry(win, "Hexagonal Winston Cone", "p"); leg->AddEntry(oku, "Hexagonal Okumura Cone", "p"); leg->Draw(); } <commit_msg>Make the code more self explanatory<commit_after>/****************************************************************************** * Copyright (C) 2006-, Akira Okumura * * All rights reserved. * *****************************************************************************/ // An example script of a hexagonal Okumura cone // See A. Okumura (2012) Astroparticle Physics 38 18-24 #include "AFocalSurface.h" #include "AGeoBezierPgon.h" #include "AGeoWinstonCone2D.h" #include "AGeoWinstonConePoly.h" #include "ALens.h" #include "AMirror.h" #include "AOpticsManager.h" #include "ARayShooter.h" #include "TAxis.h" #include "TCanvas.h" #include "TGeoBBox.h" #include "TGeoCompositeShape.h" #include "TGeoMatrix.h" #include "TLegend.h" // define useful units static const Double_t cm = AOpticsManager::cm(); static const Double_t mm = AOpticsManager::mm(); static const Double_t um = AOpticsManager::um(); static const Double_t nm = AOpticsManager::nm(); static const Double_t m = AOpticsManager::m(); static const Double_t deg = AOpticsManager::deg(); TGraph* ConeTrace(Int_t mode, bool del) { // mode == 0: hex-hex Winston cone built with AGeoWinstonConePoly // mode == 1: hex-hex Okumura cone built with AGeoBezierPgon AOpticsManager* manager = new AOpticsManager("manager", "manager"); // Make the world TGeoBBox* worldbox = new TGeoBBox("worldbox", 10 * cm, 10 * cm, 10 * cm); AOpticalComponent* world = new AOpticalComponent("world", worldbox); manager->SetTopVolume(world); const Double_t kRin = 20 * mm; const Double_t kRout = 10 * mm; TGeoRotation* rot30 = new TGeoRotation("rot30", 30, 0, 0); rot30->RegisterYourself(); AGeoWinstonConePoly* hexWin = new AGeoWinstonConePoly("hexWin", kRin, kRout, 6); const Double_t kDZ = hexWin->GetDZ(); // Make an outer shape of the cone // The length is intentionally smaller than kDZ to avoid possible rounding errors TGeoPgon* pgon = new TGeoPgon("pgon", 0, 360, 6, 4); pgon->DefineSection(0, -kDZ * 0.9999, 0, kRout * 1.1); pgon->DefineSection(1, -kDZ * 0.5, 0, kRin * 0.9); pgon->DefineSection(2, -kDZ * 0., 0, kRin * 1.001); pgon->DefineSection(3, kDZ * 0.9999, 0, kRin * 1.001); TGeoCompositeShape* coneComp1 = 0; if (mode == 0) { coneComp1 = new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexWin"); } else if (mode == 1) { AGeoBezierPgon* hexBez = new AGeoBezierPgon("hexBez", 0, 360, 6, 100, kRin, kRout, kDZ); hexBez->SetControlPoints(0.39, 0.18, 0.87, 0.36); coneComp1 = new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexBez:rot30"); } AMirror* coneMirror = new AMirror("coneMirror", coneComp1); world->AddNode(coneMirror, 1); // Here we assume a flat hexagonal PMT which is slightly bigger than the exit aperture TGeoPgon* pgonPMT = new TGeoPgon("pgonPMT", 0, 360, 6, 2); pgonPMT->DefineSection(0, - kDZ - 0.01 * mm, 0, kRout * 1.01); pgonPMT->DefineSection(1, - kDZ, 0, kRout * 1.01); AFocalSurface* pmt = new AFocalSurface("pmt", pgonPMT); world->AddNode(pmt, 1, rot30); manager->CloseGeometry(); if (mode == 1) { TCanvas* can1 = new TCanvas("can1", "can1"); manager->GetTopVolume()->Draw("ogl"); } // if TGraph* graAeff = new TGraph; for (Double_t theta = 0.; theta < 40.; theta += 0.1) { Double_t Aeff = 0.; for (Double_t phi = 0.; phi < 30.; phi += 0.3) { TGeoTranslation* raytr = new TGeoTranslation( "raytr", 50 * mm * TMath::Sin(theta * deg), 0, 50 * mm * TMath::Cos(theta * deg)); TGeoRotation* rayrot = new TGeoRotation("rayrot", 90 - phi, 180 + theta, 0); TVector3 dir(0, 0, 1); // does not affect the results because we have no lenses Double_t lambda = 400 * nm; // 1 photon per 1 mm^2 const int kNph = 1000; const double kD = 100 * mm; ARayArray* array = ARayShooter::RandomSquare(lambda, kD, kNph, rayrot, raytr, &dir); // illuminated small area per input photon // i.e., if 3 photons are detected, the effective area is 3 x dA Double_t dA = kD * kD / kNph; manager->TraceNonSequential(*array); TObjArray* focused = array->GetFocused(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; if (!ray) continue; // Calculate the effective area from the number of focused photons Aeff += dA; if (mode == 1 and TMath::Abs(theta - 20.) < 0.001 and j < 50 and phi == 0) { TPolyLine3D* pol = ray->MakePolyLine3D(); pol->SetLineColor(3); pol->SetLineWidth(2); pol->Draw(); } } delete array; } // phi Double_t hexA = 2 * TMath::Sqrt(3) * kRin * kRin; // Area of the inputer aperture Double_t eff = Aeff / hexA / TMath::Cos(theta * TMath::DegToRad()); graAeff->SetPoint(graAeff->GetN(), theta, eff); } // theta if (del) { delete manager; manager = 0; } // if return graAeff; } void HexOkumuraCone() { TGraph* win = ConeTrace(0, true); // Winston cone TGraph* oku = ConeTrace(1, false); // Okumura cone TGraph* gra[2] = {win, oku}; TCanvas* can2 = new TCanvas("can2", "can2"); for (int i = 0; i < 2; i++) { gra[i]->GetXaxis()->SetTitle("Incident Angle (deg)"); gra[i]->GetYaxis()->SetTitle("Collection Efficiency (%)"); gra[i]->SetMarkerSize(0.3); gra[i]->SetMarkerStyle(21 + 3 * i); gra[i]->Draw(i == 0 ? "ap" : "p same"); gra[i]->GetXaxis()->SetRangeUser(0, 40.); } // i TGraph* ideal = new TGraph; ideal->SetPoint(0, 0, 100); ideal->SetPoint(1, 30, 100); ideal->SetPoint(2, 30, 0); ideal->SetPoint(3, 40, 0); ideal->Draw("l same"); TLegend* leg = new TLegend(0.15, 0.15, 0.7, 0.35); leg->SetFillStyle(0); leg->SetTextFont(132); leg->AddEntry(ideal, "Ideal 2D Winston Cone", "l"); leg->AddEntry(win, "Hexagonal Winston Cone", "p"); leg->AddEntry(oku, "Hexagonal Okumura Cone", "p"); leg->Draw(); } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_hist /// \notebook /// Display the various 2-d drawing options /// /// \macro_code /// /// \author Rene Brun void draw2dopt() { gStyle->SetOptStat(0); gStyle->SetCanvasColor(33); gStyle->SetFrameFillColor(18); TF2 *f2 = new TF2("f2","xygaus + xygaus(5) + xylandau(10)",-4,4,-4,4); Double_t params[] = {130,-1.4,1.8,1.5,1, 150,2,0.5,-2,0.5, 3600,-2,0.7,-3,0.3}; f2->SetParameters(params); TH2F h2("h2","xygaus + xygaus(5) + xylandau(10)",20,-4,4,20,-4,4); h2.SetFillColor(46); h2.FillRandom("f2",40000); TPaveLabel pl; //basic 2-d options Float_t xMin=0.67, yMin=0.875, xMax=0.85, yMax=0.95; Int_t cancolor = 17; TCanvas c2h("c2h","2-d options",10,10,800,600); c2h.Divide(2,2); c2h.SetFillColor(cancolor); c2h.cd(1); h2.Draw(); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"SCAT","brNDC"); c2h.cd(2); h2.Draw("box"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"BOX","brNDC"); c2h.cd(3); h2.Draw("arr"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"ARR","brNDC"); c2h.cd(4); h2.Draw("colz"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"COLZ","brNDC"); c2h.Update(); //text option TCanvas ctext("ctext","text option",50,50,800,600); gPad->SetGrid(); ctext.SetFillColor(cancolor); ctext.SetGrid(); h2.Draw("text"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"TEXT","brNDC"); ctext.Update(); //contour options TCanvas cont("contours","contours",100,100,800,600); cont.Divide(2,2); gPad->SetGrid(); cont.SetFillColor(cancolor); cont.cd(1); h2.Draw("contz"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"CONTZ","brNDC"); cont.cd(2); gPad->SetGrid(); h2.Draw("cont1"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"CONT1","brNDC"); cont.cd(3); gPad->SetGrid(); h2.Draw("cont2"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"CONT2","brNDC"); cont.cd(4); gPad->SetGrid(); h2.Draw("cont3"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"CONT3","brNDC"); cont.Update(); //lego options TCanvas lego("lego","lego options",150,150,800,600); lego.Divide(2,2); lego.SetFillColor(cancolor); lego.cd(1); h2.Draw("lego"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"LEGO","brNDC"); lego.cd(2); h2.Draw("lego1"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"LEGO1","brNDC"); lego.cd(3); gPad->SetTheta(61); gPad->SetPhi(-82); h2.Draw("surf1pol"); pl.DrawPaveLabel(xMin,yMin,xMax+0.05,yMax,"SURF1POL","brNDC"); lego.cd(4); gPad->SetTheta(21); gPad->SetPhi(-90); h2.Draw("surf1cyl"); pl.DrawPaveLabel(xMin,yMin,xMax+0.05,yMax,"SURF1CYL","brNDC"); lego.Update(); //surface options TCanvas surf("surfopt","surface options",200,200,800,600); surf.Divide(2,2); surf.SetFillColor(cancolor); surf.cd(1); h2.Draw("surf1"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF1","brNDC"); surf.cd(2); h2.Draw("surf2z"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF2Z","brNDC"); surf.cd(3); h2.Draw("surf3"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF3","brNDC"); surf.cd(4); h2.Draw("surf4"); pl.DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF4","brNDC"); surf.Update(); } <commit_msg>Make it work with ROOT 6. Include the pictures in the ref guide.<commit_after>/// \file /// \ingroup tutorial_hist /// \notebook /// Display the various 2-d drawing options /// /// \macro_image /// \macro_code /// /// \author Rene Brun void draw2dopt() { gStyle->SetOptStat(0); gStyle->SetCanvasColor(33); gStyle->SetFrameFillColor(18); TF2 *f2 = new TF2("f2","xygaus + xygaus(5) + xylandau(10)",-4,4,-4,4); Double_t params[] = {130,-1.4,1.8,1.5,1, 150,2,0.5,-2,0.5, 3600,-2,0.7,-3,0.3}; f2->SetParameters(params); auto h2 = new TH2F("h2","xygaus + xygaus(5) + xylandau(10)",20,-4,4,20,-4,4); h2->SetFillColor(46); h2->FillRandom("f2",40000); auto pl = new TPaveLabel(); //basic 2-d options Float_t xMin=0.67, yMin=0.875, xMax=0.85, yMax=0.95; Int_t cancolor = 17; auto c2h = new TCanvas("c2h","2-d options",10,10,800,600); c2h->Divide(2,2); c2h->SetFillColor(cancolor); c2h->cd(1); h2->Draw(); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"SCAT","brNDC"); c2h->cd(2); h2->Draw("box"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"BOX","brNDC"); c2h->cd(3); h2->Draw("arr"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"ARR","brNDC"); c2h->cd(4); h2->Draw("colz"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"COLZ","brNDC"); c2h->Update(); //text option auto ctext = new TCanvas("ctext","text option",50,50,800,600); gPad->SetGrid(); ctext->SetFillColor(cancolor); ctext->SetGrid(); h2->Draw("text"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"TEXT","brNDC"); ctext->Update(); //contour options auto cont = new TCanvas("contours","contours",100,100,800,600); cont->Divide(2,2); gPad->SetGrid(); cont->SetFillColor(cancolor); cont->cd(1); h2->Draw("contz"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"CONTZ","brNDC"); cont->cd(2); gPad->SetGrid(); h2->Draw("cont1"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"CONT1","brNDC"); cont->cd(3); gPad->SetGrid(); h2->Draw("cont2"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"CONT2","brNDC"); cont->cd(4); gPad->SetGrid(); h2->Draw("cont3"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"CONT3","brNDC"); cont->Update(); //lego options auto lego = new TCanvas("lego","lego options",150,150,800,600); lego->Divide(2,2); lego->SetFillColor(cancolor); lego->cd(1); h2->Draw("lego"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"LEGO","brNDC"); lego->cd(2); h2->Draw("lego1"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"LEGO1","brNDC"); lego->cd(3); gPad->SetTheta(61); gPad->SetPhi(-82); h2->Draw("surf1pol"); pl->DrawPaveLabel(xMin,yMin,xMax+0.05,yMax,"SURF1POL","brNDC"); lego->cd(4); gPad->SetTheta(21); gPad->SetPhi(-90); h2->Draw("surf1cyl"); pl->DrawPaveLabel(xMin,yMin,xMax+0.05,yMax,"SURF1CYL","brNDC"); lego->Update(); //surface options auto surf = new TCanvas("surfopt","surface options",200,200,800,600); surf->Divide(2,2); surf->SetFillColor(cancolor); surf->cd(1); h2->Draw("surf1"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF1","brNDC"); surf->cd(2); h2->Draw("surf2z"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF2Z","brNDC"); surf->cd(3); h2->Draw("surf3"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF3","brNDC"); surf->cd(4); h2->Draw("surf4"); pl->DrawPaveLabel(xMin,yMin,xMax,yMax,"SURF4","brNDC"); surf->Update(); } <|endoftext|>
<commit_before>// Read data (CERN staff) from an ascii file and create a root file with a Tree. // see also a variant in staff.C // Author: Rene Brun TFile *cernbuild(Int_t get=0) { Int_t Category; UInt_t Flag; Int_t Age; Int_t Service; Int_t Children; Int_t Grade; Int_t Step; Int_t Hrweek; Int_t Cost; Char_t Division[4]; Char_t Nation[3]; //The input file cern.dat is a copy of the CERN staff data base //from 1988 TString filename = "cernstaff.root"; TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName()); dir.ReplaceAll("cernbuild.C",""); dir.ReplaceAll("/./","/"); FILE *fp = fopen(Form("%scernstaff.dat",dir.Data()),"r"); TFile *hfile = 0; if (get) { // if the argument get =1 return the file "cernstaff.root" // if the file does not exist, it is created if (!gSystem->AccessPathName(dir+"cernstaff.root",kFileExists)) { hfile = TFile::Open(dir+"cernstaff.root"); //in $ROOTSYS/tutorials/tree if (hfile) return hfile; } //otherwise try $PWD/cernstaff.root if (!gSystem->AccessPathName("cernstaff.root",kFileExists)) { hfile = TFile::Open("cernstaff.root"); //in current dir if (hfile) return hfile; } } //no cernstaff.root file found. Must generate it ! //generate cernstaff.root in $ROOTSYS/tutorials/tree if we have write access if (!gSystem->AccessPathName(dir,kWritePermission)) { filename = dir+"cernstaff.root"; } else if (!gSystem->AccessPathName(".",kWritePermission)) { //otherwise generate cernstaff.root in the current directory } else { printf("you must run the script in a directory with write access\n"); return 0; } hfile = TFile::Open(filename,"RECREATE"); TTree *tree = new TTree("T","CERN 1988 staff data"); tree->Branch("Category",&Category,"Category/I"); tree->Branch("Flag",&Flag,"Flag/i"); tree->Branch("Age",&Age,"Age/I"); tree->Branch("Service",&Service,"Service/I"); tree->Branch("Children",&Children,"Children/I"); tree->Branch("Grade",&Grade,"Grade/I"); tree->Branch("Step",&Step,"Step/I"); tree->Branch("Hrweek",&Hrweek,"Hrweek/I"); tree->Branch("Cost",&Cost,"Cost/I"); tree->Branch("Division",Division,"Division/C"); tree->Branch("Nation",Nation,"Nation/C"); char line[80]; while (fgets(&line,80,fp)) { sscanf(&line[0],"%d %d %d %d %d",&Category,&Flag,&Age,&Service,&Children); sscanf(&line[32],"%d %d %d %d %s %s",&Grade,&Step,&Hrweek,&Cost,Division,Nation); tree->Fill(); } tree->Print(); tree->Write(); fclose(fp); delete hfile; if (get) { //we come here when the script is executed outside $ROOTSYS/tutorials/tree hfile = TFile::Open(filename); return hfile; } return 0; } <commit_msg>Add a new optional parameter to turn off the printout. It is needed is order to call this macro from stressGraphics<commit_after>// Read data (CERN staff) from an ascii file and create a root file with a Tree. // see also a variant in staff.C // Author: Rene Brun TFile *cernbuild(Int_t get=0, Int_t print=1) { Int_t Category; UInt_t Flag; Int_t Age; Int_t Service; Int_t Children; Int_t Grade; Int_t Step; Int_t Hrweek; Int_t Cost; Char_t Division[4]; Char_t Nation[3]; //The input file cern.dat is a copy of the CERN staff data base //from 1988 TString filename = "cernstaff.root"; TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName()); dir.ReplaceAll("cernbuild.C",""); dir.ReplaceAll("/./","/"); FILE *fp = fopen(Form("%scernstaff.dat",dir.Data()),"r"); TFile *hfile = 0; if (get) { // if the argument get =1 return the file "cernstaff.root" // if the file does not exist, it is created if (!gSystem->AccessPathName(dir+"cernstaff.root",kFileExists)) { hfile = TFile::Open(dir+"cernstaff.root"); //in $ROOTSYS/tutorials/tree if (hfile) return hfile; } //otherwise try $PWD/cernstaff.root if (!gSystem->AccessPathName("cernstaff.root",kFileExists)) { hfile = TFile::Open("cernstaff.root"); //in current dir if (hfile) return hfile; } } //no cernstaff.root file found. Must generate it ! //generate cernstaff.root in $ROOTSYS/tutorials/tree if we have write access if (!gSystem->AccessPathName(dir,kWritePermission)) { filename = dir+"cernstaff.root"; } else if (!gSystem->AccessPathName(".",kWritePermission)) { //otherwise generate cernstaff.root in the current directory } else { printf("you must run the script in a directory with write access\n"); return 0; } hfile = TFile::Open(filename,"RECREATE"); TTree *tree = new TTree("T","CERN 1988 staff data"); tree->Branch("Category",&Category,"Category/I"); tree->Branch("Flag",&Flag,"Flag/i"); tree->Branch("Age",&Age,"Age/I"); tree->Branch("Service",&Service,"Service/I"); tree->Branch("Children",&Children,"Children/I"); tree->Branch("Grade",&Grade,"Grade/I"); tree->Branch("Step",&Step,"Step/I"); tree->Branch("Hrweek",&Hrweek,"Hrweek/I"); tree->Branch("Cost",&Cost,"Cost/I"); tree->Branch("Division",Division,"Division/C"); tree->Branch("Nation",Nation,"Nation/C"); char line[80]; while (fgets(&line,80,fp)) { sscanf(&line[0],"%d %d %d %d %d",&Category,&Flag,&Age,&Service,&Children); sscanf(&line[32],"%d %d %d %d %s %s",&Grade,&Step,&Hrweek,&Cost,Division,Nation); tree->Fill(); } if (print) tree->Print(); tree->Write(); fclose(fp); delete hfile; if (get) { //we come here when the script is executed outside $ROOTSYS/tutorials/tree hfile = TFile::Open(filename); return hfile; } return 0; } <|endoftext|>
<commit_before>//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // This checker flags misuses of KeyChainAPI. In particular, the password data // allocated/returned by SecKeychainItemCopyContent, // SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has // to be freed using a call to SecKeychainItemFreeContent. //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h" using namespace clang; using namespace ento; namespace { class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>, check::PreStmt<ReturnStmt>, check::PostStmt<CallExpr>, check::EndPath > { mutable llvm::OwningPtr<BugType> BT; public: void checkPreStmt(const CallExpr *S, CheckerContext &C) const; void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; void checkPostStmt(const CallExpr *S, CheckerContext &C) const; void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const; private: /// Stores the information about the allocator and deallocator functions - /// these are the functions the checker is tracking. struct ADFunctionInfo { const char* Name; unsigned int Param; unsigned int DeallocatorIdx; }; static const unsigned InvalidIdx = 100000; static const unsigned FunctionsToTrackSize = 6; static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize]; /// Given the function name, returns the index of the allocator/deallocator /// function. unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const; inline void initBugType() const { if (!BT) BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API")); } }; } /// AllocationState is a part of the checker specific state together with the /// MemRegion corresponding to the allocated data. struct AllocationState { const Expr *Address; /// The index of the allocator function. unsigned int AllocatorIdx; AllocationState(const Expr *E, unsigned int Idx) : Address(E), AllocatorIdx(Idx) {} bool operator==(const AllocationState &X) const { return Address == X.Address; } void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddPointer(Address); ID.AddInteger(AllocatorIdx); } }; /// GRState traits to store the currently allocated (and not yet freed) symbols. typedef llvm::ImmutableMap<const MemRegion*, AllocationState> AllocatedSetTy; namespace { struct AllocatedData {}; } namespace clang { namespace ento { template<> struct GRStateTrait<AllocatedData> : public GRStatePartialTrait<AllocatedSetTy > { static void *GDMIndex() { static int index = 0; return &index; } }; }} static bool isEnclosingFunctionParam(const Expr *E) { E = E->IgnoreParenCasts(); if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { const ValueDecl *VD = DRE->getDecl(); if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD)) return true; } return false; } const MacOSKeychainAPIChecker::ADFunctionInfo MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = { {"SecKeychainItemCopyContent", 4, 3}, // 0 {"SecKeychainFindGenericPassword", 6, 3}, // 1 {"SecKeychainFindInternetPassword", 13, 3}, // 2 {"SecKeychainItemFreeContent", 1, InvalidIdx}, // 3 {"SecKeychainItemCopyAttributesAndData", 5, 5}, // 4 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx}, // 5 }; unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const { for (unsigned I = 0; I < FunctionsToTrackSize; ++I) { ADFunctionInfo FI = FunctionsToTrack[I]; if (FI.Name != Name) continue; // Make sure the function is of the right type (allocator vs deallocator). if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx)) return InvalidIdx; if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx)) return InvalidIdx; return I; } // The function is not tracked. return InvalidIdx; } /// Given the address expression, retrieve the value it's pointing to. Assume /// that value is itself an address, and return the corresponding MemRegion. static const MemRegion *getAsPointeeMemoryRegion(const Expr *Expr, CheckerContext &C) { const GRState *State = C.getState(); SVal ArgV = State->getSVal(Expr); if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) { StoreManager& SM = C.getStoreManager(); const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion(); return V; } return 0; } void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { const GRState *State = C.getState(); const Expr *Callee = CE->getCallee(); SVal L = State->getSVal(Callee); unsigned idx = InvalidIdx; const FunctionDecl *funDecl = L.getAsFunctionDecl(); if (!funDecl) return; IdentifierInfo *funI = funDecl->getIdentifier(); if (!funI) return; StringRef funName = funI->getName(); // If it is a call to an allocator function, it could be a double allocation. idx = getTrackedFunctionIndex(funName, true); if (idx != InvalidIdx) { const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param); if (const MemRegion *V = getAsPointeeMemoryRegion(ArgExpr, C)) if (const AllocationState *AS = State->get<AllocatedData>(V)) { ExplodedNode *N = C.generateSink(State); if (!N) return; initBugType(); std::string sbuf; llvm::raw_string_ostream os(sbuf); unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx; os << "Allocated data should be released before another call to " << "the allocator: missing a call to '" << FunctionsToTrack[DIdx].Name << "'."; RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N); Report->addRange(ArgExpr->getSourceRange()); C.EmitReport(Report); } return; } // Is it a call to one of deallocator functions? idx = getTrackedFunctionIndex(funName, false); if (idx == InvalidIdx) return; const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param); const MemRegion *Arg = State->getSVal(ArgExpr).getAsRegion(); if (!Arg) return; // If trying to free data which has not been allocated yet, report as bug. const AllocationState *AS = State->get<AllocatedData>(Arg); if (!AS) { // It is possible that this is a false positive - the argument might // have entered as an enclosing function parameter. if (isEnclosingFunctionParam(ArgExpr)) return; ExplodedNode *N = C.generateNode(State); if (!N) return; initBugType(); RangedBugReport *Report = new RangedBugReport(*BT, "Trying to free data which has not been allocated.", N); Report->addRange(ArgExpr->getSourceRange()); C.EmitReport(Report); return; } // Check if the proper deallocator is used. unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx; if (PDeallocIdx != idx) { ExplodedNode *N = C.generateSink(State); if (!N) return; initBugType(); std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Allocator doesn't match the deallocator: '" << FunctionsToTrack[PDeallocIdx].Name << "' should be used."; RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N); Report->addRange(ArgExpr->getSourceRange()); C.EmitReport(Report); return; } // If a value has been freed, remove it from the list and continue exploring // from the new state. State = State->remove<AllocatedData>(Arg); C.addTransition(State); } void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { const GRState *State = C.getState(); const Expr *Callee = CE->getCallee(); SVal L = State->getSVal(Callee); const FunctionDecl *funDecl = L.getAsFunctionDecl(); if (!funDecl) return; IdentifierInfo *funI = funDecl->getIdentifier(); if (!funI) return; StringRef funName = funI->getName(); // If a value has been allocated, add it to the set for tracking. unsigned idx = getTrackedFunctionIndex(funName, true); if (idx == InvalidIdx) return; const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param); if (const MemRegion *V = getAsPointeeMemoryRegion(ArgExpr, C)) { // If the argument points to something that's not a region, it can be: // - unknown (cannot reason about it) // - undefined (already reported by other checker) // - constant (null - should not be tracked, // other constant will generate a compiler warning) // - goto (should be reported by other checker) // We only need to track the value if the function returned noErr(0), so // bind the return value of the function to 0 and proceed from the no error // state. SValBuilder &Builder = C.getSValBuilder(); SVal ZeroVal = Builder.makeIntVal(0, CE->getCallReturnType()); const GRState *NoErr = State->BindExpr(CE, ZeroVal); // Add the symbolic value V, which represents the location of the allocated // data, to the set. NoErr = NoErr->set<AllocatedData>(V, AllocationState(ArgExpr, idx)); assert(NoErr); C.addTransition(NoErr); // Generate a transition to explore the state space when there is an error. // In this case, we do not track the allocated data. SVal ReturnedError = Builder.evalBinOpNN(State, BO_NE, cast<NonLoc>(ZeroVal), cast<NonLoc>(State->getSVal(CE)), CE->getCallReturnType()); const GRState *Err = State->assume(cast<NonLoc>(ReturnedError), true); assert(Err); C.addTransition(Err); } } void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const { const Expr *retExpr = S->getRetValue(); if (!retExpr) return; // Check if the value is escaping through the return. const GRState *state = C.getState(); const MemRegion *V = state->getSVal(retExpr).getAsRegion(); if (!V) return; state = state->remove<AllocatedData>(V); // Proceed from the new state. C.addTransition(state); } void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const { const GRState *state = B.getState(); AllocatedSetTy AS = state->get<AllocatedData>(); ExplodedNode *N = B.generateNode(state); if (!N) return; initBugType(); // Anything which has been allocated but not freed (nor escaped) will be // found here, so report it. for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) { const ADFunctionInfo &FI = FunctionsToTrack[I->second.AllocatorIdx]; std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Allocated data is not released: missing a call to '" << FunctionsToTrack[FI.DeallocatorIdx].Name << "'."; RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N); // TODO: The report has to mention the expression which contains the // allocated content as well as the point at which it has been allocated. // Currently, the next line is useless. Report->addRange(I->second.Address->getSourceRange()); Eng.getBugReporter().EmitReport(Report); } } void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) { mgr.registerChecker<MacOSKeychainAPIChecker>(); } <commit_msg>KeychainAPI checker: Track SymbolMetadata instead of MemRegion in checker state so that we could clear the state on evalDeadSymbols; also track the return value.<commit_after>//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // This checker flags misuses of KeyChainAPI. In particular, the password data // allocated/returned by SecKeychainItemCopyContent, // SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has // to be freed using a call to SecKeychainItemFreeContent. //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h" using namespace clang; using namespace ento; namespace { class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>, check::PreStmt<ReturnStmt>, check::PostStmt<CallExpr>, check::EndPath > { mutable llvm::OwningPtr<BugType> BT; public: void checkPreStmt(const CallExpr *S, CheckerContext &C) const; void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; void checkPostStmt(const CallExpr *S, CheckerContext &C) const; void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const; private: /// Stores the information about the allocator and deallocator functions - /// these are the functions the checker is tracking. struct ADFunctionInfo { const char* Name; unsigned int Param; unsigned int DeallocatorIdx; }; static const unsigned InvalidIdx = 100000; static const unsigned FunctionsToTrackSize = 6; static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize]; /// The value, which represents no error return value for allocator functions. static const unsigned NoErr = 0; /// Given the function name, returns the index of the allocator/deallocator /// function. unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const; inline void initBugType() const { if (!BT) BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API")); } }; } /// AllocationState is a part of the checker specific state together with the /// MemRegion corresponding to the allocated data. struct AllocationState { const Expr *Address; /// The index of the allocator function. unsigned int AllocatorIdx; SymbolRef RetValue; AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) : Address(E), AllocatorIdx(Idx), RetValue(R) {} bool operator==(const AllocationState &X) const { return Address == X.Address; } void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddPointer(Address); ID.AddInteger(AllocatorIdx); } }; /// GRState traits to store the currently allocated (and not yet freed) symbols. typedef llvm::ImmutableMap<const SymbolMetadata *, AllocationState> AllocatedSetTy; namespace { struct AllocatedData {}; } namespace clang { namespace ento { template<> struct GRStateTrait<AllocatedData> : public GRStatePartialTrait<AllocatedSetTy > { static void *GDMIndex() { static int index = 0; return &index; } }; }} static bool isEnclosingFunctionParam(const Expr *E) { E = E->IgnoreParenCasts(); if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { const ValueDecl *VD = DRE->getDecl(); if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD)) return true; } return false; } const MacOSKeychainAPIChecker::ADFunctionInfo MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = { {"SecKeychainItemCopyContent", 4, 3}, // 0 {"SecKeychainFindGenericPassword", 6, 3}, // 1 {"SecKeychainFindInternetPassword", 13, 3}, // 2 {"SecKeychainItemFreeContent", 1, InvalidIdx}, // 3 {"SecKeychainItemCopyAttributesAndData", 5, 5}, // 4 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx}, // 5 }; unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const { for (unsigned I = 0; I < FunctionsToTrackSize; ++I) { ADFunctionInfo FI = FunctionsToTrack[I]; if (FI.Name != Name) continue; // Make sure the function is of the right type (allocator vs deallocator). if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx)) return InvalidIdx; if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx)) return InvalidIdx; return I; } // The function is not tracked. return InvalidIdx; } static const SymbolMetadata *getSymbolMetadata(CheckerContext &C, const MemRegion *R) { QualType sizeTy = C.getSValBuilder().getContext().getSizeType(); return C.getSymbolManager().getMetadataSymbol(R, 0, sizeTy, 0); } /// Given the address expression, retrieve the value it's pointing to. Assume /// that value is itself an address, and return the corresponding MemRegion. static const SymbolMetadata *getAsPointeeMemoryRegion(const Expr *Expr, CheckerContext &C) { const GRState *State = C.getState(); SVal ArgV = State->getSVal(Expr); if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) { StoreManager& SM = C.getStoreManager(); const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion(); if (V) return getSymbolMetadata(C, V); } return 0; } void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { const GRState *State = C.getState(); const Expr *Callee = CE->getCallee(); SVal L = State->getSVal(Callee); unsigned idx = InvalidIdx; const FunctionDecl *funDecl = L.getAsFunctionDecl(); if (!funDecl) return; IdentifierInfo *funI = funDecl->getIdentifier(); if (!funI) return; StringRef funName = funI->getName(); // If it is a call to an allocator function, it could be a double allocation. idx = getTrackedFunctionIndex(funName, true); if (idx != InvalidIdx) { const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param); if (const SymbolMetadata *V = getAsPointeeMemoryRegion(ArgExpr, C)) if (const AllocationState *AS = State->get<AllocatedData>(V)) { ExplodedNode *N = C.generateSink(State); if (!N) return; initBugType(); std::string sbuf; llvm::raw_string_ostream os(sbuf); unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx; os << "Allocated data should be released before another call to " << "the allocator: missing a call to '" << FunctionsToTrack[DIdx].Name << "'."; RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N); Report->addRange(ArgExpr->getSourceRange()); C.EmitReport(Report); } return; } // Is it a call to one of deallocator functions? idx = getTrackedFunctionIndex(funName, false); if (idx == InvalidIdx) return; const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param); const MemRegion *Arg = State->getSVal(ArgExpr).getAsRegion(); if (!Arg) return; const SymbolMetadata *ArgSM = getSymbolMetadata(C, Arg); // If trying to free data which has not been allocated yet, report as bug. const AllocationState *AS = State->get<AllocatedData>(ArgSM); if (!AS) { // It is possible that this is a false positive - the argument might // have entered as an enclosing function parameter. if (isEnclosingFunctionParam(ArgExpr)) return; ExplodedNode *N = C.generateNode(State); if (!N) return; initBugType(); RangedBugReport *Report = new RangedBugReport(*BT, "Trying to free data which has not been allocated.", N); Report->addRange(ArgExpr->getSourceRange()); C.EmitReport(Report); return; } // Check if the proper deallocator is used. unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx; if (PDeallocIdx != idx) { ExplodedNode *N = C.generateSink(State); if (!N) return; initBugType(); std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Allocator doesn't match the deallocator: '" << FunctionsToTrack[PDeallocIdx].Name << "' should be used."; RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N); Report->addRange(ArgExpr->getSourceRange()); C.EmitReport(Report); return; } // If a value has been freed, remove it from the list and continue exploring // from the new state. State = State->remove<AllocatedData>(ArgSM); C.addTransition(State); } void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { const GRState *State = C.getState(); const Expr *Callee = CE->getCallee(); SVal L = State->getSVal(Callee); const FunctionDecl *funDecl = L.getAsFunctionDecl(); if (!funDecl) return; IdentifierInfo *funI = funDecl->getIdentifier(); if (!funI) return; StringRef funName = funI->getName(); // If a value has been allocated, add it to the set for tracking. unsigned idx = getTrackedFunctionIndex(funName, true); if (idx == InvalidIdx) return; const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param); if (const SymbolMetadata *V = getAsPointeeMemoryRegion(ArgExpr, C)) { // If the argument points to something that's not a region, it can be: // - unknown (cannot reason about it) // - undefined (already reported by other checker) // - constant (null - should not be tracked, // other constant will generate a compiler warning) // - goto (should be reported by other checker) // We only need to track the value if the function returned noErr(0), so // bind the return value of the function to 0 and proceed from the no error // state. SValBuilder &Builder = C.getSValBuilder(); SVal NoErrVal = Builder.makeIntVal(NoErr, CE->getCallReturnType()); const GRState *NoErr = State->BindExpr(CE, NoErrVal); // Add the symbolic value V, which represents the location of the allocated // data, to the set. NoErr = NoErr->set<AllocatedData>(V, AllocationState(ArgExpr, idx, State->getSVal(CE).getAsSymbol())); assert(NoErr); C.addTransition(NoErr); // Generate a transition to explore the state space when there is an error. // In this case, we do not track the allocated data. SVal ReturnedError = Builder.evalBinOpNN(State, BO_NE, cast<NonLoc>(NoErrVal), cast<NonLoc>(State->getSVal(CE)), CE->getCallReturnType()); const GRState *Err = State->assume(cast<NonLoc>(ReturnedError), true); assert(Err); C.addTransition(Err); } } void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const { const Expr *retExpr = S->getRetValue(); if (!retExpr) return; // Check if the value is escaping through the return. const GRState *state = C.getState(); const MemRegion *V = state->getSVal(retExpr).getAsRegion(); if (!V) return; state = state->remove<AllocatedData>(getSymbolMetadata(C, V)); // Proceed from the new state. C.addTransition(state); } void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const { const GRState *state = B.getState(); AllocatedSetTy AS = state->get<AllocatedData>(); ExplodedNode *N = B.generateNode(state); if (!N) return; initBugType(); // Anything which has been allocated but not freed (nor escaped) will be // found here, so report it. for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) { const ADFunctionInfo &FI = FunctionsToTrack[I->second.AllocatorIdx]; std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Allocated data is not released: missing a call to '" << FunctionsToTrack[FI.DeallocatorIdx].Name << "'."; RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N); // TODO: The report has to mention the expression which contains the // allocated content as well as the point at which it has been allocated. // Currently, the next line is useless. Report->addRange(I->second.Address->getSourceRange()); Eng.getBugReporter().EmitReport(Report); } } void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) { mgr.registerChecker<MacOSKeychainAPIChecker>(); } <|endoftext|>
<commit_before>#include "solarsystem.h" SolarSystem::SolarSystem() { } CelestialBody& SolarSystem::createCelestialBody(vec3 position, vec3 velocity, double mass) { m_bodies.push_back( CelestialBody(position, velocity, mass) ); return m_bodies.back(); // Return reference to the newest added celstial body } void SolarSystem::calculateForcesAndEnergy() { m_kineticEnergy = 0; m_potentialEnergy = 0; m_angularMomentum.zeros(); for(int i=0; i<numberOfBodies(); i++) { CelestialBody &body1 = m_bodies[i]; for(int j=i+1; j<numberOfBodies(); j++) { CelestialBody &body2 = m_bodies[j]; vec3 deltaRVector = body1.position - body2.position; double dr = deltaRVector.length(); // Calculate the force and potential energy here } m_kineticEnergy += 0.5*body1.mass*body1.velocity.lengthSquared(); } } int SolarSystem::numberOfBodies() { return m_bodies.size(); } double SolarSystem::totalEnergy() const { return m_kineticEnergy + m_potentialEnergy; } double SolarSystem::potentialEnergy() const { return m_potentialEnergy; } double SolarSystem::kineticEnergy() const { return m_kineticEnergy; } vec3 SolarSystem::angularMomentum() const { return m_angularMomentum; } std::vector<CelestialBody> &SolarSystem::bodies() { return m_bodies; } <commit_msg>Resetting forces in calculateForcesAndEnergy.<commit_after>#include "solarsystem.h" SolarSystem::SolarSystem() { } CelestialBody& SolarSystem::createCelestialBody(vec3 position, vec3 velocity, double mass) { m_bodies.push_back( CelestialBody(position, velocity, mass) ); return m_bodies.back(); // Return reference to the newest added celstial body } void SolarSystem::calculateForcesAndEnergy() { m_kineticEnergy = 0; m_potentialEnergy = 0; m_angularMomentum.zeros(); for(CelestialBody &body : m_bodies) { body.resetForce(); } for(int i=0; i<numberOfBodies(); i++) { CelestialBody &body1 = m_bodies[i]; for(int j=i+1; j<numberOfBodies(); j++) { CelestialBody &body2 = m_bodies[j]; vec3 deltaRVector = body1.position - body2.position; double dr = deltaRVector.length(); // Calculate the force and potential energy here } m_kineticEnergy += 0.5*body1.mass*body1.velocity.lengthSquared(); } } int SolarSystem::numberOfBodies() { return m_bodies.size(); } double SolarSystem::totalEnergy() const { return m_kineticEnergy + m_potentialEnergy; } double SolarSystem::potentialEnergy() const { return m_potentialEnergy; } double SolarSystem::kineticEnergy() const { return m_kineticEnergy; } vec3 SolarSystem::angularMomentum() const { return m_angularMomentum; } std::vector<CelestialBody> &SolarSystem::bodies() { return m_bodies; } <|endoftext|>
<commit_before>/** * @file ada_delta.hpp * @author Marcus Edel * * Implmentation of the RmsProp optimizer. Adadelta is an optimizer that uses * the magnitude of recent gradients and steps to obtain an adaptive step rate. */ #ifndef __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #define __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #include <mlpack/core.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * Adadelta is an optimizer that uses the magnitude of recent gradients and * steps to obtain an adaptive step rate. In its basic form, given a step rate * \f$ \gamma \f$ and a decay term \f$ \alpha \f$ we perform the following * updates: * * \f{eqnarray*}{ * g_t &=& (1 - \gamma)f'(\Delta_t)^2 + \gamma g_{t - 1} \\ * \vec{\Delta} \Delta_t &=& \alpha \frac{\sqrt(s_{t-1} + * \epsilon)}{\sqrt{g_t + \epsilon}} f'(\Delta_t) \\ * \Delta_{t + 1} &=& \Delta_t - \vec{\Delta} \Delta_t \\ * s_t &=& (1 - \gamma) \vec{\Delta} \Delta_t^2 + \gamma s_{t - 1} * \f} * * For more information, see the following. * * @code * @article{Zeiler2012, * author = {Matthew D. Zeiler}, * title = {{ADADELTA:} An Adaptive Learning Rate Method}, * journal = {CoRR}, * year = {2012} * } * @endcode */ template<typename DecomposableFunctionType, typename DataType> class AdaDelta { public: /** * Construct the AdaDelta optimizer with the given function and parameters. * * @param function Function to be optimized (minimized). * @param rho Constant similar to that used in AdaDelta and Momentum methods. * @param eps The eps coefficient to avoid division by zero. */ AdaDelta(DecomposableFunctionType& function, const double rho = 0.95, const double eps = 1e-6) : function(function), rho(rho), eps(eps), iteration(0) { // Nothing to do here. } /** * Optimize the given function using RmsProp. */ void Optimize() { if (meanSquaredGradient.n_elem == 0) { meanSquaredGradient = function.Weights(); meanSquaredGradient.zeros(); meanSquaredGradientDx = meanSquaredGradient; } if (iteration > 1) gradient /= iteration; Optimize(function.Weights(), gradient, meanSquaredGradient, meanSquaredGradientDx); } /* * Sum up all gradients and store the results in the gradients storage. */ void Update() { iteration++; if (gradient.n_elem != 0) { DataType outputGradient; function.Gradient(outputGradient); gradient += outputGradient; } else { function.Gradient(gradient); } } /* * Reset the gradient storage. */ void Reset() { iteration = 0; gradient.zeros(); } //! Get the gradient. DataType& Gradient() const { return gradient; } //! Modify the gradient. DataType& Gradient() { return gradient; } private: /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Cube<eT>& weights, arma::Cube<eT>& gradient, arma::Cube<eT>& meanSquaredGradient, arma::Cube<eT>& meanSquaredGradientDx) { for (size_t s = 0; s < weights.n_slices; s++) { Optimize(weights.slice(s), gradient.slice(s), meanSquaredGradient.slice(s), meanSquaredGradientDx.slice(s)); } } /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Mat<eT>& weights, arma::Mat<eT>& gradient, arma::Mat<eT>& meanSquaredGradient, arma::Mat<eT>& meanSquaredGradientDx) { // Accumulate gradient. meanSquaredGradient *= rho; meanSquaredGradient += (1 - rho) * (gradient % gradient); arma::Mat<eT> dx = arma::sqrt((meanSquaredGradientDx + eps) / (meanSquaredGradient + eps)) % gradient; // Accumulate updates. meanSquaredGradientDx *= rho; meanSquaredGradientDx += (1 - rho) * (dx % dx); // Apply update. weights -= dx; } //! The instantiated function. DecomposableFunctionType& function; //! The value used as learning rate. const double rho; //! The value used as eps. const double eps; //! The current gradient. DataType gradient; //! The current mean squared gradient. DataType meanSquaredGradient; //! The current mean squared gradient Dx DataType meanSquaredGradientDx; //! The locally stored number of iterations. size_t iteration; }; // class AdaDelta }; // namespace ann }; // namespace mlpack #endif <commit_msg>Refactor optimizer for new network API.<commit_after>/** * @file ada_delta.hpp * @author Marcus Edel * * Implmentation of the RmsProp optimizer. Adadelta is an optimizer that uses * the magnitude of recent gradients and steps to obtain an adaptive step rate. */ #ifndef __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #define __MLPACK_METHODS_ANN_OPTIMIZER_ADA_DELTA_HPP #include <mlpack/core.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * Adadelta is an optimizer that uses the magnitude of recent gradients and * steps to obtain an adaptive step rate. In its basic form, given a step rate * \f$ \gamma \f$ and a decay term \f$ \alpha \f$ we perform the following * updates: * * \f{eqnarray*}{ * g_t &=& (1 - \gamma)f'(\Delta_t)^2 + \gamma g_{t - 1} \\ * \vec{\Delta} \Delta_t &=& \alpha \frac{\sqrt(s_{t-1} + * \epsilon)}{\sqrt{g_t + \epsilon}} f'(\Delta_t) \\ * \Delta_{t + 1} &=& \Delta_t - \vec{\Delta} \Delta_t \\ * s_t &=& (1 - \gamma) \vec{\Delta} \Delta_t^2 + \gamma s_{t - 1} * \f} * * For more information, see the following. * * @code * @article{Zeiler2012, * author = {Matthew D. Zeiler}, * title = {{ADADELTA:} An Adaptive Learning Rate Method}, * journal = {CoRR}, * year = {2012} * } * @endcode */ template<typename DecomposableFunctionType, typename DataType> class AdaDelta { public: /** * Construct the AdaDelta optimizer with the given function and parameters. * * @param function Function to be optimized (minimized). * @param rho Constant similar to that used in AdaDelta and Momentum methods. * @param eps The eps coefficient to avoid division by zero. */ AdaDelta(DecomposableFunctionType& function, const double rho = 0.95, const double eps = 1e-6) : function(function), rho(rho), eps(eps) { // Nothing to do here. } /** * Optimize the given function using RmsProp. */ void Optimize() { if (meanSquaredGradient.n_elem == 0) { meanSquaredGradient = function.Weights(); meanSquaredGradient.zeros(); meanSquaredGradientDx = meanSquaredGradient; } Optimize(function.Weights(), gradient, meanSquaredGradient, meanSquaredGradientDx); } /* * Sum up all gradients and store the results in the gradients storage. */ void Update() { if (gradient.n_elem != 0) { gradient += function.Gradient(); } else { gradient = function.Gradient(); } } /* * Reset the gradient storage. */ void Reset() { gradient.zeros(); } //! Get the gradient. DataType& Gradient() const { return gradient; } //! Modify the gradient. DataType& Gradient() { return gradient; } private: /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Cube<eT>& weights, arma::Cube<eT>& gradient, arma::Cube<eT>& meanSquaredGradient, arma::Cube<eT>& meanSquaredGradientDx) { for (size_t s = 0; s < weights.n_slices; s++) { Optimize(weights.slice(s), gradient.slice(s), meanSquaredGradient.slice(s), meanSquaredGradientDx.slice(s)); } } /** * Optimize the given function using AdaDelta. * * @param weights The weights that should be updated. * @param gradient The gradient used to update the weights. * @param meanSquaredGradient The current mean squared gradient Dx * @param meanSquaredGradientDx The current mean squared gradient. */ template<typename eT> void Optimize(arma::Mat<eT>& weights, arma::Mat<eT>& gradient, arma::Mat<eT>& meanSquaredGradient, arma::Mat<eT>& meanSquaredGradientDx) { // Accumulate gradient. meanSquaredGradient *= rho; meanSquaredGradient += (1 - rho) * (gradient % gradient); arma::Mat<eT> dx = arma::sqrt((meanSquaredGradientDx + eps) / (meanSquaredGradient + eps)) % gradient; // Accumulate updates. meanSquaredGradientDx *= rho; meanSquaredGradientDx += (1 - rho) * (dx % dx); // Apply update. weights -= dx; } //! The instantiated function. DecomposableFunctionType& function; //! The value used as learning rate. const double rho; //! The value used as eps. const double eps; //! The current gradient. DataType gradient; //! The current mean squared gradient. DataType meanSquaredGradient; //! The current mean squared gradient Dx DataType meanSquaredGradientDx; }; // class AdaDelta }; // namespace ann }; // namespace mlpack #endif <|endoftext|>
<commit_before>/** * @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file SinogramCreatorMC.cpp */ #include "SinogramCreatorMC.h" #include <TH1F.h> #include <TH2I.h> using namespace jpet_options_tools; SinogramCreatorMC::SinogramCreatorMC(const char* name) : SinogramCreator(name) {} SinogramCreatorMC::~SinogramCreatorMC() {} bool SinogramCreatorMC::init() { SinogramCreatorMC::setUpOptions(); fOutputEvents = new JPetTimeWindow("JPetEvent"); getStatistics().createHistogram(new TH2I("reconstruction_histogram", "reconstruction_histogram histogram", std::ceil(fMaxReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1, 0.f, fMaxReconstructionLayerRadius, kReconstructionMaxAngle, 0, kReconstructionMaxAngle)); getStatistics().createHistogram( new TH1F("pos_dis", "Position distance real data", (fMaxReconstructionLayerRadius)*10 * 5, 0.f, fMaxReconstructionLayerRadius)); getStatistics().createHistogram(new TH1F("angle", "Position angle real data", kReconstructionMaxAngle, 0, kReconstructionMaxAngle)); #if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0) getStatistics().getObject<TH2I>("reconstruction_histogram")->SetBit(TH2::kCanRebin); getStatistics().getObject<TH1F>("angle")->SetBit(TH1::kCanRebin); getStatistics().getObject<TH1F>("pos_dis")->SetBit(TH1::kCanRebin); #else getStatistics().getObject<TH2I>("reconstruction_histogram")->SetCanExtend(TH1::kAllAxes); getStatistics().getObject<TH1F>("angle")->SetCanExtend(TH1::kAllAxes); getStatistics().getObject<TH1F>("pos_dis")->SetCanExtend(TH1::kAllAxes); #endif generateSinogram(); return true; } void SinogramCreatorMC::generateSinogram() { float firstX = 0.f; float firstY = 0.f; float secondX = 0.f; float secondY = 0.f; float firstZ = 0.f; float secondZ = 0.f; float firstT = 0.f; float secondT = 0.f; float skip = 0.f; int coincidence = 0; int numberOfCorrectHits = 0; int totalHits = 1; // to make sure that we do not divide by 0 if (fSinogram == nullptr) { fSinogram = new JPetRecoImageTools::Matrix2DProj*[fZSplitNumber]; for (int i = 0; i < fZSplitNumber; i++) { fSinogram[i] = new JPetRecoImageTools::Matrix2DProj(fMaxDistanceNumber, (std::vector<double>(kReconstructionMaxAngle, 0))); } } for (const auto& inputPath : fInputData) { std::ifstream in(inputPath); while (in.peek() != EOF) { in >> firstX >> firstY >> firstZ >> firstT >> secondX >> secondY >> secondZ >> secondT >> skip >> skip >> skip >> skip >> coincidence >> skip >> skip >> skip; // in >> firstX >> firstY >> firstZ >> firstT >> secondX >> secondY >> secondZ >> secondT; if (coincidence != 1) // 1 == true event continue; if (analyzeHits(firstX, firstY, firstZ, firstT, secondX, secondY, secondZ, secondT)) { numberOfCorrectHits++; } totalHits++; } } std::cout << "Correct hits: " << numberOfCorrectHits << " total hits: " << totalHits << " (correct percentage: " << (((float)numberOfCorrectHits * 100.f) / (float)totalHits) << "%)" << std::endl; } bool SinogramCreatorMC::exec() { return true; } bool SinogramCreatorMC::terminate() { JPetFilterRamLak filter(0.7); JPetRecoImageTools::FourierTransformFunction f = JPetRecoImageTools::doFFTW; for (int i = 0; i < fZSplitNumber; i++) { int sliceNumber = i - (fZSplitNumber / 2); if (std::find(fReconstructSliceNumbers.begin(), fReconstructSliceNumbers.end(), sliceNumber) == fReconstructSliceNumbers.end()) continue; // save sinogram saveResult((*fSinogram[i]), fOutFileName + "sinogram_" + std::to_string(sliceNumber) + "_" + std::to_string(fZSplitRange[i].first) + "_" + std::to_string(fZSplitRange[i].second) + ".ppm"); // calculate KDE JPetRecoImageTools::Matrix2DProj result = JPetRecoImageTools::backProjectWithKDE((*fSinogram[i]), fTOFInformation[i], (*fSinogram[i])[0].size(), JPetRecoImageTools::nonRescale, 0, 255); // save KDE saveResult(result, fOutFileName + "reconstruction_with_KDE_" + std::to_string(sliceNumber) + ".ppm"); // filter sinogram JPetRecoImageTools::Matrix2DProj filteredSinogram = JPetRecoImageTools::FilterSinogram(f, filter, (*fSinogram[i])); // backproject JPetRecoImageTools::Matrix2DProj resultBP = JPetRecoImageTools::backProject(filteredSinogram, (*fSinogram[i])[0].size(), JPetRecoImageTools::nonRescale, 0, 255); // save FBP saveResult(resultBP, fOutFileName + "reconstruction_with_FBP" + std::to_string(sliceNumber) + ".ppm"); } delete[] fSinogram; delete[] fMaxValueInSinogram; return true; } void SinogramCreatorMC::setUpOptions() { auto opts = getOptions(); if (isOptionSet(opts, kOutFileNameKey)) { fOutFileName = getOptionAsString(opts, kOutFileNameKey); } if (isOptionSet(opts, kReconstructionDistanceAccuracy)) { fReconstructionDistanceAccuracy = getOptionAsFloat(opts, kReconstructionDistanceAccuracy); } if (isOptionSet(opts, kZSplitNumber)) { fZSplitNumber = getOptionAsInt(opts, kZSplitNumber); } if (isOptionSet(opts, kScintillatorLenght)) { fScintillatorLenght = getOptionAsFloat(opts, kScintillatorLenght); } if (isOptionSet(opts, kMaxReconstructionRadius)) { fMaxReconstructionLayerRadius = getOptionAsFloat(opts, kMaxReconstructionRadius); } if (isOptionSet(opts, kInputDataKey)) { fInputData = getOptionAsVectorOfStrings(opts, kInputDataKey); } if (isOptionSet(opts, kEnableObliqueLORRemapping)) { fEnableObliqueLORRemapping = getOptionAsBool(opts, kEnableObliqueLORRemapping); } if (isOptionSet(opts, kEnableTOFReconstruction)) { fEnableKDEReconstruction = getOptionAsBool(opts, kEnableTOFReconstruction); } fTOFInformation = new JPetRecoImageTools::Matrix2DTOF[fZSplitNumber]; fMaxValueInSinogram = new int[fZSplitNumber]; fCurrentValueInSinogram = new int[fZSplitNumber]; const float maxZRange = fScintillatorLenght / 2.f; float range = (2.f * maxZRange) / fZSplitNumber; for (int i = 0; i < fZSplitNumber; i++) { float rangeStart = (i * range) - maxZRange; float rangeEnd = ((i + 1) * range) - maxZRange; fZSplitRange.push_back(std::make_pair(rangeStart, rangeEnd)); fCurrentValueInSinogram[i] = 0; fMaxValueInSinogram[i] = 0; } fMaxDistanceNumber = std::ceil(fMaxReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1; if (isOptionSet(opts, kReconstructSliceNumbers)) { fReconstructSliceNumbers = boost::any_cast<std::vector<int>>(getOptionValue(opts, kReconstructSliceNumbers)); } else { for (int i = 0; i < fZSplitNumber; i++) { fReconstructSliceNumbers.push_back(i); } } }<commit_msg>Reforamt<commit_after>/** * @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file SinogramCreatorMC.cpp */ #include "SinogramCreatorMC.h" #include <TH1F.h> #include <TH2I.h> using namespace jpet_options_tools; SinogramCreatorMC::SinogramCreatorMC(const char* name) : SinogramCreator(name) {} SinogramCreatorMC::~SinogramCreatorMC() {} bool SinogramCreatorMC::init() { SinogramCreatorMC::setUpOptions(); fOutputEvents = new JPetTimeWindow("JPetEvent"); getStatistics().createHistogram(new TH2I("reconstruction_histogram", "reconstruction_histogram histogram", std::ceil(fMaxReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1, 0.f, fMaxReconstructionLayerRadius, kReconstructionMaxAngle, 0, kReconstructionMaxAngle)); getStatistics().createHistogram( new TH1F("pos_dis", "Position distance real data", (fMaxReconstructionLayerRadius)*10 * 5, 0.f, fMaxReconstructionLayerRadius)); getStatistics().createHistogram(new TH1F("angle", "Position angle real data", kReconstructionMaxAngle, 0, kReconstructionMaxAngle)); #if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0) getStatistics().getObject<TH2I>("reconstruction_histogram")->SetBit(TH2::kCanRebin); getStatistics().getObject<TH1F>("angle")->SetBit(TH1::kCanRebin); getStatistics().getObject<TH1F>("pos_dis")->SetBit(TH1::kCanRebin); #else getStatistics().getObject<TH2I>("reconstruction_histogram")->SetCanExtend(TH1::kAllAxes); getStatistics().getObject<TH1F>("angle")->SetCanExtend(TH1::kAllAxes); getStatistics().getObject<TH1F>("pos_dis")->SetCanExtend(TH1::kAllAxes); #endif generateSinogram(); return true; } void SinogramCreatorMC::generateSinogram() { float firstX = 0.f; float firstY = 0.f; float secondX = 0.f; float secondY = 0.f; float firstZ = 0.f; float secondZ = 0.f; float firstT = 0.f; float secondT = 0.f; float skip = 0.f; int coincidence = 0; int numberOfCorrectHits = 0; int totalHits = 1; // to make sure that we do not divide by 0 if (fSinogram == nullptr) { fSinogram = new JPetRecoImageTools::Matrix2DProj*[fZSplitNumber]; for (int i = 0; i < fZSplitNumber; i++) { fSinogram[i] = new JPetRecoImageTools::Matrix2DProj(fMaxDistanceNumber, (std::vector<double>(kReconstructionMaxAngle, 0))); } } for (const auto& inputPath : fInputData) { std::ifstream in(inputPath); while (in.peek() != EOF) { in >> firstX >> firstY >> firstZ >> firstT >> secondX >> secondY >> secondZ >> secondT >> skip >> skip >> skip >> skip >> coincidence >> skip >> skip >> skip; // in >> firstX >> firstY >> firstZ >> firstT >> secondX >> secondY >> secondZ >> secondT; if (coincidence != 1) // 1 == true event continue; if (analyzeHits(firstX, firstY, firstZ, firstT, secondX, secondY, secondZ, secondT)) { numberOfCorrectHits++; } totalHits++; } } std::cout << "Correct hits: " << numberOfCorrectHits << " total hits: " << totalHits << " (correct percentage: " << (((float)numberOfCorrectHits * 100.f) / (float)totalHits) << "%)" << std::endl; } bool SinogramCreatorMC::exec() { return true; } bool SinogramCreatorMC::terminate() { JPetFilterRamLak filter(0.7); JPetRecoImageTools::FourierTransformFunction f = JPetRecoImageTools::doFFTW; for (int i = 0; i < fZSplitNumber; i++) { int sliceNumber = i - (fZSplitNumber / 2); if (std::find(fReconstructSliceNumbers.begin(), fReconstructSliceNumbers.end(), sliceNumber) == fReconstructSliceNumbers.end()) continue; // save sinogram saveResult((*fSinogram[i]), fOutFileName + "sinogram_" + std::to_string(sliceNumber) + "_" + std::to_string(fZSplitRange[i].first) + "_" + std::to_string(fZSplitRange[i].second) + ".ppm"); // calculate KDE JPetRecoImageTools::Matrix2DProj result = JPetRecoImageTools::backProjectWithKDE((*fSinogram[i]), fTOFInformation[i], (*fSinogram[i])[0].size(), JPetRecoImageTools::nonRescale, 0, 255); // save KDE saveResult(result, fOutFileName + "reconstruction_with_KDE_" + std::to_string(sliceNumber) + ".ppm"); // filter sinogram // JPetRecoImageTools::Matrix2DProj filteredSinogram = JPetRecoImageTools::FilterSinogram(f, filter, (*fSinogram[i])); // backproject // JPetRecoImageTools::Matrix2DProj resultBP = // JPetRecoImageTools::backProject(filteredSinogram, (*fSinogram[i])[0].size(), JPetRecoImageTools::nonRescale, 0, 255); // save FBP // saveResult(resultBP, fOutFileName + "reconstruction_with_FBP" + std::to_string(sliceNumber) + ".ppm"); } delete[] fSinogram; delete[] fMaxValueInSinogram; return true; } void SinogramCreatorMC::setUpOptions() { auto opts = getOptions(); if (isOptionSet(opts, kOutFileNameKey)) { fOutFileName = getOptionAsString(opts, kOutFileNameKey); } if (isOptionSet(opts, kReconstructionDistanceAccuracy)) { fReconstructionDistanceAccuracy = getOptionAsFloat(opts, kReconstructionDistanceAccuracy); } if (isOptionSet(opts, kZSplitNumber)) { fZSplitNumber = getOptionAsInt(opts, kZSplitNumber); } if (isOptionSet(opts, kScintillatorLenght)) { fScintillatorLenght = getOptionAsFloat(opts, kScintillatorLenght); } if (isOptionSet(opts, kMaxReconstructionRadius)) { fMaxReconstructionLayerRadius = getOptionAsFloat(opts, kMaxReconstructionRadius); } if (isOptionSet(opts, kInputDataKey)) { fInputData = getOptionAsVectorOfStrings(opts, kInputDataKey); } if (isOptionSet(opts, kEnableObliqueLORRemapping)) { fEnableObliqueLORRemapping = getOptionAsBool(opts, kEnableObliqueLORRemapping); } if (isOptionSet(opts, kEnableTOFReconstruction)) { fEnableKDEReconstruction = getOptionAsBool(opts, kEnableTOFReconstruction); } fTOFInformation = new JPetRecoImageTools::Matrix2DTOF[fZSplitNumber]; fMaxValueInSinogram = new int[fZSplitNumber]; fCurrentValueInSinogram = new int[fZSplitNumber]; const float maxZRange = fScintillatorLenght / 2.f; float range = (2.f * maxZRange) / fZSplitNumber; for (int i = 0; i < fZSplitNumber; i++) { float rangeStart = (i * range) - maxZRange; float rangeEnd = ((i + 1) * range) - maxZRange; fZSplitRange.push_back(std::make_pair(rangeStart, rangeEnd)); fCurrentValueInSinogram[i] = 0; fMaxValueInSinogram[i] = 0; } fMaxDistanceNumber = std::ceil(fMaxReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1; if (isOptionSet(opts, kReconstructSliceNumbers)) { fReconstructSliceNumbers = boost::any_cast<std::vector<int>>(getOptionValue(opts, kReconstructSliceNumbers)); } else { for (int i = 0; i < fZSplitNumber; i++) { fReconstructSliceNumbers.push_back(i); } } }<|endoftext|>
<commit_before>/* * producer_glaxnimate.cpp -- a Glaxnimate/Qt based producer for MLT * Copyright (C) 2022 Meltytech, LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <framework/mlt.h> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include "io/io_registry.hpp" using namespace glaxnimate; class Glaxnimate { private: mlt_producer m_producer = nullptr; std::unique_ptr<model::Document> m_document; public: mlt_profile m_profile = nullptr; void setProducer( mlt_producer producer ) { m_producer = producer; } mlt_producer producer() const { return m_producer; } mlt_service service() const { return MLT_PRODUCER_SERVICE(m_producer); } mlt_properties properties() const { return MLT_PRODUCER_PROPERTIES(m_producer); } QSize size() const { return m_document->size(); } int duration() const { return qRound(m_document->main()->animation->last_frame.get() - m_document->main()->animation->first_frame.get() + 1.f); } Glaxnimate() { } ~Glaxnimate() { } int getImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable) { int error = 0; auto pos = mlt_frame_original_position(frame); if (mlt_properties_get(properties(), "eof") && !::strcmp("loop", mlt_properties_get(properties(), "eof"))) { pos %= duration(); } auto bg = mlt_properties_get_color(properties(), "background"); auto background = QColor(bg.r, bg.g, bg.r, bg.a); auto image = m_document->render_image(m_document->main()->animation->first_frame.get() + pos, {*width, *height}, background); *format = mlt_image_rgba; int size = mlt_image_format_size(*format, *width, *height, NULL); *buffer = static_cast<uint8_t*>(mlt_pool_alloc(size)); memcpy(*buffer, image.constBits(), size); error = mlt_frame_set_image(frame, *buffer, size, mlt_pool_release); return error; } bool open(const char* fileName) { auto filename = QString::fromUtf8(fileName); auto importer = io::IoRegistry::instance().from_filename(filename, io::ImportExport::Import); if (!importer || !importer->can_open()) { mlt_log_error(service(), "Unknown importer\n"); return false; } QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { mlt_log_error(service(), "Could not open input file for reading\n"); return false; } m_document.reset(new model::Document(filename)); QVariantMap settings; if ( !importer->open(file, filename, m_document.get(), settings) ) { mlt_log_error(service(), "Error loading input file\n"); return false; } return true; } }; extern "C" { static int get_image(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable) { auto producer = static_cast<mlt_producer>(mlt_frame_pop_service(frame)); auto glax = static_cast<Glaxnimate*>(producer->child); return glax->getImage(frame, buffer, format, width, height, writable); } static int get_frame(mlt_producer producer, mlt_frame_ptr frame, int index) { *frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer)); mlt_properties frame_properties = MLT_FRAME_PROPERTIES( *frame ); // Set frame properties mlt_properties_set_int(frame_properties, "progressive", 1); double force_ratio = mlt_properties_get_double(MLT_PRODUCER_PROPERTIES(producer), "force_aspect_ratio"); if (force_ratio > 0.0) mlt_properties_set_double(frame_properties, "aspect_ratio", force_ratio); else mlt_properties_set_double(frame_properties, "aspect_ratio", 1.0); mlt_frame_set_position(*frame, mlt_producer_position(producer)); mlt_frame_push_service(*frame, producer); mlt_frame_push_get_image(*frame, get_image); mlt_producer_prepare_next(producer); return 0; } static void producer_close(mlt_producer producer) { delete static_cast<Glaxnimate*>(producer->child); producer->close = nullptr; mlt_producer_close(producer); } mlt_producer producer_glaxnimate_init(mlt_profile profile, mlt_service_type type, const char *id, char *arg) { // Allocate the producer Glaxnimate* glax = new Glaxnimate(); mlt_producer producer = (mlt_producer) calloc(1, sizeof( *producer )); // If allocated and initializes if (glax && !mlt_producer_init(producer, glax) && glax->open(arg)) { glax->setProducer(producer); producer->close = (mlt_destructor) producer_close; producer->get_frame = get_frame; auto properties = glax->properties(); mlt_properties_set(properties, "resource", arg); mlt_properties_set(properties, "background", "#00000000"); mlt_properties_set_int(properties, "aspect_ratio", 1); mlt_properties_set_int(properties, "progressive", 1); mlt_properties_set_int(properties, "seekable", 1); mlt_properties_set_int(properties, "meta.media.width", glax->size().width()); mlt_properties_set_int(properties, "meta.media.height", glax->size().height()); mlt_properties_set_int(properties, "meta.media.sample_aspect_num", 1); mlt_properties_set_int(properties, "meta.media.sample_aspect_den", 1); mlt_properties_set_int(properties, "out", glax->duration() - 1); mlt_properties_set_int(properties, "length", glax->duration()); } return producer; } static mlt_properties metadata(mlt_service_type type, const char *id, void *data) { char file[PATH_MAX]; const char *service_type = NULL; switch (type) { case mlt_service_producer_type: service_type = "producer"; break; default: return NULL; } snprintf(file, PATH_MAX, "%s/glaxnimate/%s_%s.yml", mlt_environment("MLT_DATA"), service_type, id); return mlt_properties_parse_yaml(file); } MLT_REPOSITORY { MLT_REGISTER(mlt_service_producer_type, "glaxnimate", producer_glaxnimate_init); MLT_REGISTER_METADATA(mlt_service_producer_type, "glaxnimate", metadata, NULL); } } // extern C <commit_msg>fix glaxnimate background color<commit_after>/* * producer_glaxnimate.cpp -- a Glaxnimate/Qt based producer for MLT * Copyright (C) 2022 Meltytech, LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <framework/mlt.h> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include "io/io_registry.hpp" using namespace glaxnimate; class Glaxnimate { private: mlt_producer m_producer = nullptr; std::unique_ptr<model::Document> m_document; public: mlt_profile m_profile = nullptr; void setProducer( mlt_producer producer ) { m_producer = producer; } mlt_producer producer() const { return m_producer; } mlt_service service() const { return MLT_PRODUCER_SERVICE(m_producer); } mlt_properties properties() const { return MLT_PRODUCER_PROPERTIES(m_producer); } QSize size() const { return m_document->size(); } int duration() const { return qRound(m_document->main()->animation->last_frame.get() - m_document->main()->animation->first_frame.get() + 1.f); } Glaxnimate() { } ~Glaxnimate() { } int getImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable) { int error = 0; auto pos = mlt_frame_original_position(frame); if (mlt_properties_get(properties(), "eof") && !::strcmp("loop", mlt_properties_get(properties(), "eof"))) { pos %= duration(); } auto bg = mlt_properties_get_color(properties(), "background"); auto background = QColor(bg.r, bg.g, bg.b, bg.a); auto image = m_document->render_image(m_document->main()->animation->first_frame.get() + pos, {*width, *height}, background); *format = mlt_image_rgba; int size = mlt_image_format_size(*format, *width, *height, NULL); *buffer = static_cast<uint8_t*>(mlt_pool_alloc(size)); memcpy(*buffer, image.constBits(), size); error = mlt_frame_set_image(frame, *buffer, size, mlt_pool_release); return error; } bool open(const char* fileName) { auto filename = QString::fromUtf8(fileName); auto importer = io::IoRegistry::instance().from_filename(filename, io::ImportExport::Import); if (!importer || !importer->can_open()) { mlt_log_error(service(), "Unknown importer\n"); return false; } QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { mlt_log_error(service(), "Could not open input file for reading\n"); return false; } m_document.reset(new model::Document(filename)); QVariantMap settings; if ( !importer->open(file, filename, m_document.get(), settings) ) { mlt_log_error(service(), "Error loading input file\n"); return false; } return true; } }; extern "C" { static int get_image(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable) { auto producer = static_cast<mlt_producer>(mlt_frame_pop_service(frame)); auto glax = static_cast<Glaxnimate*>(producer->child); return glax->getImage(frame, buffer, format, width, height, writable); } static int get_frame(mlt_producer producer, mlt_frame_ptr frame, int index) { *frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer)); mlt_properties frame_properties = MLT_FRAME_PROPERTIES( *frame ); // Set frame properties mlt_properties_set_int(frame_properties, "progressive", 1); double force_ratio = mlt_properties_get_double(MLT_PRODUCER_PROPERTIES(producer), "force_aspect_ratio"); if (force_ratio > 0.0) mlt_properties_set_double(frame_properties, "aspect_ratio", force_ratio); else mlt_properties_set_double(frame_properties, "aspect_ratio", 1.0); mlt_frame_set_position(*frame, mlt_producer_position(producer)); mlt_frame_push_service(*frame, producer); mlt_frame_push_get_image(*frame, get_image); mlt_producer_prepare_next(producer); return 0; } static void producer_close(mlt_producer producer) { delete static_cast<Glaxnimate*>(producer->child); producer->close = nullptr; mlt_producer_close(producer); } mlt_producer producer_glaxnimate_init(mlt_profile profile, mlt_service_type type, const char *id, char *arg) { // Allocate the producer Glaxnimate* glax = new Glaxnimate(); mlt_producer producer = (mlt_producer) calloc(1, sizeof( *producer )); // If allocated and initializes if (glax && !mlt_producer_init(producer, glax) && glax->open(arg)) { glax->setProducer(producer); producer->close = (mlt_destructor) producer_close; producer->get_frame = get_frame; auto properties = glax->properties(); mlt_properties_set(properties, "resource", arg); mlt_properties_set(properties, "background", "#00000000"); mlt_properties_set_int(properties, "aspect_ratio", 1); mlt_properties_set_int(properties, "progressive", 1); mlt_properties_set_int(properties, "seekable", 1); mlt_properties_set_int(properties, "meta.media.width", glax->size().width()); mlt_properties_set_int(properties, "meta.media.height", glax->size().height()); mlt_properties_set_int(properties, "meta.media.sample_aspect_num", 1); mlt_properties_set_int(properties, "meta.media.sample_aspect_den", 1); mlt_properties_set_int(properties, "out", glax->duration() - 1); mlt_properties_set_int(properties, "length", glax->duration()); } return producer; } static mlt_properties metadata(mlt_service_type type, const char *id, void *data) { char file[PATH_MAX]; const char *service_type = NULL; switch (type) { case mlt_service_producer_type: service_type = "producer"; break; default: return NULL; } snprintf(file, PATH_MAX, "%s/glaxnimate/%s_%s.yml", mlt_environment("MLT_DATA"), service_type, id); return mlt_properties_parse_yaml(file); } MLT_REPOSITORY { MLT_REGISTER(mlt_service_producer_type, "glaxnimate", producer_glaxnimate_init); MLT_REGISTER_METADATA(mlt_service_producer_type, "glaxnimate", metadata, NULL); } } // extern C <|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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 "proposal.hpp" #include "ngraph/op/constant.hpp" using namespace std; using namespace ngraph; const string op::Proposal::type_name{"Proposal"}; op::Proposal::Proposal(const Output<Node>& class_probs, const Output<Node>& class_logits, const Output<Node>& image_shape, const ProposalAttrs& attrs) : Op({class_probs, class_logits, image_shape}) , m_attrs(attrs) { constructor_validate_and_infer_types(); } void op::Proposal::validate_and_infer_types() { set_input_is_relevant_to_shape(2); const auto& class_probs_pshape = get_input_partial_shape(0); const auto& class_logits_pshape = get_input_partial_shape(1); const auto& image_shape_pshape = get_input_partial_shape(2); if (class_probs_pshape.is_static() && class_logits_pshape.is_static() && image_shape_pshape.is_static()) { const Shape class_probs_shape{class_probs_pshape.to_shape()}; const Shape class_logits_shape{class_logits_pshape.to_shape()}; const Shape image_shape_shape{image_shape_pshape.to_shape()}; NODE_VALIDATION_CHECK( this, class_probs_shape.size() == 4, "Proposal layer shape class_probs input must have rank 4 (class_probs_shape: ", class_probs_shape, ")."); NODE_VALIDATION_CHECK( this, class_logits_shape.size() == 4, "Proposal layer shape class_logits_shape input must have rank 4 (class_logits_shape: ", class_logits_shape, ")."); NODE_VALIDATION_CHECK( this, image_shape_shape.size() == 1, "Proposal layer image_shape input must have rank 1 (image_shape_shape: ", image_shape_shape, ")."); NODE_VALIDATION_CHECK( this, image_shape_shape[0] >= 3 && image_shape_shape[0] <= 4, "Image_shape 1D tensor must have => 3 and <= 4 elements (image_shape_shape[0]", image_shape_shape[0], ")."); auto batch_size = class_probs_shape[0]; set_output_type(0, element::f32, Shape{batch_size * m_attrs.post_nms_topn, 5}); } else { set_output_type(0, element::f32, PartialShape::dynamic()); } } shared_ptr<Node> op::Proposal::copy_with_new_args(const NodeVector& new_args) const { check_new_args_count(this, new_args); return make_shared<Proposal>(new_args.at(0), new_args.at(1), new_args.at(2), m_attrs); } <commit_msg>Fixed Proposal output type infer (#3538)<commit_after>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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 "proposal.hpp" #include "ngraph/op/constant.hpp" using namespace std; using namespace ngraph; const string op::Proposal::type_name{"Proposal"}; op::Proposal::Proposal(const Output<Node>& class_probs, const Output<Node>& class_logits, const Output<Node>& image_shape, const ProposalAttrs& attrs) : Op({class_probs, class_logits, image_shape}) , m_attrs(attrs) { constructor_validate_and_infer_types(); } void op::Proposal::validate_and_infer_types() { set_input_is_relevant_to_shape(2); const auto& class_probs_pshape = get_input_partial_shape(0); const auto& class_logits_pshape = get_input_partial_shape(1); const auto& image_shape_pshape = get_input_partial_shape(2); if (class_probs_pshape.is_static() && class_logits_pshape.is_static() && image_shape_pshape.is_static()) { const Shape class_probs_shape{class_probs_pshape.to_shape()}; const Shape class_logits_shape{class_logits_pshape.to_shape()}; const Shape image_shape_shape{image_shape_pshape.to_shape()}; NODE_VALIDATION_CHECK( this, class_probs_shape.size() == 4, "Proposal layer shape class_probs input must have rank 4 (class_probs_shape: ", class_probs_shape, ")."); NODE_VALIDATION_CHECK( this, class_logits_shape.size() == 4, "Proposal layer shape class_logits_shape input must have rank 4 (class_logits_shape: ", class_logits_shape, ")."); NODE_VALIDATION_CHECK( this, image_shape_shape.size() == 1, "Proposal layer image_shape input must have rank 1 (image_shape_shape: ", image_shape_shape, ")."); NODE_VALIDATION_CHECK( this, image_shape_shape[0] >= 3 && image_shape_shape[0] <= 4, "Image_shape 1D tensor must have => 3 and <= 4 elements (image_shape_shape[0]", image_shape_shape[0], ")."); auto batch_size = class_probs_shape[0]; set_output_type(0, get_input_element_type(0), Shape{batch_size * m_attrs.post_nms_topn, 5}); } else { set_output_type(0, get_input_element_type(0), PartialShape::dynamic()); } } shared_ptr<Node> op::Proposal::copy_with_new_args(const NodeVector& new_args) const { check_new_args_count(this, new_args); return make_shared<Proposal>(new_args.at(0), new_args.at(1), new_args.at(2), m_attrs); } <|endoftext|>
<commit_before>#include "GolfBall.hpp" #include "../Resources.hpp" #include "Default3D.vert.hpp" #include "Default3D.geom.hpp" #include "Default3D.frag.hpp" #include "glm/gtc/constants.hpp" #include "../Util/Log.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/quaternion.hpp> GolfBall::GolfBall(BallType ballType, TerrainObject* terrain, Water* water) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"), "Resources/Models/GolfBall/Diffuse.png", "Resources/Models/GolfBall/Normal.png", "Resources/Models/GolfBall/Specular.png") { state = GolfBall::INITIAL; restitution = ballType == TWOPIECE ? 0.78f : 0.68f; this->terrain = terrain; this->water = water; origin = glm::vec3(1.f, 0.f, 1.f); mass = 0.0459f; this->ballType = ballType; sphere.position = Position(); SetRadius(0.0214f); } GolfBall::~GolfBall() { Resources().FreeOBJModel(modelGeometry); } void GolfBall::Reset(){ state = GolfBall::INITIAL; velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); SetPosition(origin); sphere.position = Position(); orientation = glm::quat(); } void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) { if (state == GolfBall::ACTIVE) { Move(static_cast<float>(time)* velocity); sphere.position = Position(); if (glm::length(angularVelocity) > 0.0001f) { glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity)); orientation = deltaQuat * orientation; } glm::vec3 dragForce, magnusForce, acceleration = glm::vec3(0.f, 0.f, 0.f); float groundLevel = terrain->GetY(Position().x, Position().z); float waterLevel = water->Position().y; // Check if in water. if ((sphere.position.y - sphere.radius < groundLevel && groundLevel + sphere.radius < waterLevel) || sphere.position.y + sphere.radius < waterLevel) { state = GolfBall::OUT; return; } // Check for collision if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){ float vCritical = 0.3f; float e = 0.35f; float muSliding = 0.51f; float muRolling = 0.096f; SetPosition(Position().x, groundLevel + sphere.radius, Position().z); sphere.position = Position(); //glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f)); glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().z); glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh; glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f); if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f){ eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity); } float vRoh = glm::dot(velocity, eRoh); float deltaU = -(e + 1.f) * vRoh; glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity)); float w = glm::dot(angularVelocity, angularDirection); if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) { glm::vec3 mg = (9.82f)*glm::vec3(0.f, -1.f, 0.f); glm::vec3 tangentialGravityAcceleration = mg - glm::dot(mg, eRoh)*eRoh; glm::vec3 tangentialSlidingFrictionDeceleration = muSliding*eFriction; glm::vec3 tangentialRollingFrictionDeceleration = muRolling*eFriction; glm::vec3 tangentialDelta = tangentialVelocity + (tangentialGravityAcceleration - tangentialSlidingFrictionDeceleration)*static_cast<float>(time); if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) { //Rolling if (glm::length(tangentialGravityAcceleration) < glm::length(tangentialRollingFrictionDeceleration)) tangentialRollingFrictionDeceleration = glm::length(tangentialGravityAcceleration)*eFriction; velocity = tangentialVelocity + (tangentialGravityAcceleration + tangentialRollingFrictionDeceleration)*static_cast<float>(time); angularVelocity = (glm::length(velocity) / sphere.radius) * cross(eRoh,eFriction); } else { //Sliding velocity = tangentialVelocity + (tangentialGravityAcceleration + tangentialSlidingFrictionDeceleration)*static_cast<float>(time); angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * cross(eRoh, eFriction); } } else { float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f; float velocityRoh = glm::dot(velocity, eRoh); float velocityNormal = glm::dot(velocity, eFriction); float uRoh = -e*velocityRoh; float deltauRoh = uRoh - (velocityRoh); float deltaUn = muSliding*deltauRoh; float rollUn = (5.f / 7.f)*velocityNormal; float slideUn = velocityNormal - deltaUn; if (velocityNormal > rollUn){ velocity = uRoh*eRoh + rollUn*eFriction; angularVelocity += muRolling * (deltaU + 9.82f*eRoh.y * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } else { velocity = uRoh*eRoh + slideUn*eFriction; angularVelocity += muSliding * (deltaU + 9.82f *eRoh.y* deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } } } else { // Calculate magnus force. float v = glm::length(velocity); float u = glm::length(velocity - wind); float w = glm::length(angularVelocity); glm::vec3 eU = (velocity - wind) / u; magnusForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f && v > 0.f && w > 0.f) { float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f; float Fm = 0.5f * Cm * 1.23f * area * u * u; magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity)); } // Calculate drag force. float cD; if (ballType == TWOPIECE) cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f; else cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f; dragForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f) dragForce = -0.5f * 1.23f * area * cD * u * u * eU; // Calculate gravitational force. glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f); // Get acceleration from total force. acceleration = (dragForce + magnusForce + gravitationForce) / mass; } velocity += acceleration * static_cast<float>(time); } } void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{ if (state != GolfBall::EXPLODED && state != GolfBall::OUT) ModelObject::Render(camera, screenSize, clippingPlane); } void GolfBall::Explode(std::vector<PlayerObject>& players){ //@TODO: Set mass equivalent depending on material used. float equivalenceFactor = 1.0f; float massEquivalent = mass*equivalenceFactor; for (auto &player : players){ glm::vec3 distanceV = (Position() - player.Position()); float distance = glm::length(distanceV); //pow(meq, 1.f/3.f) => cube root of meq float z = distance / (pow(massEquivalent, 1.f / 3.f)); float alpha = 1 + pow((z / 4.5f), 2.f); float beta = 1 + pow((z / 0.048f), 2.f); float gamma = 1 + pow((z / 1.35f), 2.f); float delta = 1 + pow((z / 0.32f), 2.f); //float Pf = 8.08f*pow(10.f, 7.f)*alpha; float Pf = ((8.08e7)*alpha) / sqrt(beta*gamma*delta); player.TakeDamage(Pf); } state = GolfBall::EXPLODED; } void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) { state = GolfBall::ACTIVE; // Club velocity in strike plane. float v = glm::length(clubVelocity); if (v > 0.f) { float sinLoft = sin(club.loft); float cosLoft = cos(club.loft); // Ball velocity. float massCoefficient = club.mass / (club.mass + mass); float Up = (1.f + restitution) * massCoefficient * v * cosLoft; float Un = (2.f / 7.f) * massCoefficient * v * sinLoft; // Go back from strike plane to 3D. glm::vec3 forward = clubVelocity / v; glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward)); glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up); glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up); // Total velocity. velocity = Up * ep + Un * en; angularVelocity = -Un / sphere.radius * glm::cross(ep, en); } else { velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); } } float GolfBall::Radius() const { return sphere.radius; } void GolfBall::SetRadius(float radius) { sphere.radius = radius; SetScale(glm::vec3(radius, radius, radius)); area = glm::pi<float>() * radius * radius; } glm::mat4 GolfBall::Orientation() const { return glm::toMat4(orientation); } GolfBall::State GolfBall::GetState() const { return state; } <commit_msg>More work on acceleration<commit_after>#include "GolfBall.hpp" #include "../Resources.hpp" #include "Default3D.vert.hpp" #include "Default3D.geom.hpp" #include "Default3D.frag.hpp" #include "glm/gtc/constants.hpp" #include "../Util/Log.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/quaternion.hpp> GolfBall::GolfBall(BallType ballType, TerrainObject* terrain, Water* water) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"), "Resources/Models/GolfBall/Diffuse.png", "Resources/Models/GolfBall/Normal.png", "Resources/Models/GolfBall/Specular.png") { state = GolfBall::INITIAL; restitution = ballType == TWOPIECE ? 0.78f : 0.68f; this->terrain = terrain; this->water = water; origin = glm::vec3(1.f, 0.f, 1.f); mass = 0.0459f; this->ballType = ballType; sphere.position = Position(); SetRadius(0.0214f); } GolfBall::~GolfBall() { Resources().FreeOBJModel(modelGeometry); } void GolfBall::Reset(){ state = GolfBall::INITIAL; velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); SetPosition(origin); sphere.position = Position(); orientation = glm::quat(); } void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) { if (state == GolfBall::ACTIVE) { Move(static_cast<float>(time)* velocity); sphere.position = Position(); if (glm::length(angularVelocity) > 0.0001f) { glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity)); orientation = deltaQuat * orientation; } glm::vec3 dragForce, magnusForce, acceleration = glm::vec3(0.f, 0.f, 0.f); float groundLevel = terrain->GetY(Position().x, Position().z); float waterLevel = water->Position().y; // Check if in water. if ((sphere.position.y - sphere.radius < groundLevel && groundLevel + sphere.radius < waterLevel) || sphere.position.y + sphere.radius < waterLevel) { state = GolfBall::OUT; return; } // Check for collision if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){ float vCritical = 0.3f; float e = 0.35f; float muSliding = 0.51f; float muRolling = 0.096f; SetPosition(Position().x, groundLevel + sphere.radius, Position().z); sphere.position = Position(); //glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f)); glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().z); glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh; glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f); if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f){ eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity); } float vRoh = glm::dot(velocity, eRoh); float deltaU = -(e + 1.f) * vRoh; glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity)); float w = glm::dot(angularVelocity, angularDirection); if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) { glm::vec3 mg = (9.82f)*glm::vec3(0.f, -1.f, 0.f); glm::vec3 tangentialGravityAcceleration = mg - glm::dot(mg, eRoh)*eRoh; glm::vec3 tangentialSlidingFrictionDeceleration = muSliding*eFriction; glm::vec3 tangentialRollingFrictionDeceleration = muRolling*eFriction; glm::vec3 tangentialDelta = tangentialVelocity + (tangentialGravityAcceleration - tangentialSlidingFrictionDeceleration)*static_cast<float>(time); if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) { //Rolling if (glm::length(tangentialGravityAcceleration)*muRolling < glm::length(tangentialRollingFrictionDeceleration)) tangentialRollingFrictionDeceleration = glm::length(tangentialGravityAcceleration)*eFriction; velocity = tangentialVelocity + (tangentialGravityAcceleration + tangentialRollingFrictionDeceleration)*static_cast<float>(time); angularVelocity = (glm::length(velocity) / sphere.radius) * cross(eRoh,eFriction); } else { //Sliding velocity = tangentialVelocity + (tangentialGravityAcceleration + tangentialSlidingFrictionDeceleration)*static_cast<float>(time); angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * cross(eRoh, eFriction); } } else { float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f; float velocityRoh = glm::dot(velocity, eRoh); float velocityNormal = glm::dot(velocity, eFriction); float uRoh = -e*velocityRoh; float deltauRoh = uRoh - (velocityRoh); float deltaUn = muSliding*deltauRoh; float rollUn = (5.f / 7.f)*velocityNormal; float slideUn = velocityNormal - deltaUn; if (velocityNormal > rollUn){ velocity = uRoh*eRoh + rollUn*eFriction; angularVelocity += muRolling * (deltaU + 9.82f*eRoh.y * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } else { velocity = uRoh*eRoh + slideUn*eFriction; angularVelocity += muSliding * (deltaU + 9.82f *eRoh.y* deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } } } else { // Calculate magnus force. float v = glm::length(velocity); float u = glm::length(velocity - wind); float w = glm::length(angularVelocity); glm::vec3 eU = (velocity - wind) / u; magnusForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f && v > 0.f && w > 0.f) { float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f; float Fm = 0.5f * Cm * 1.23f * area * u * u; magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity)); } // Calculate drag force. float cD; if (ballType == TWOPIECE) cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f; else cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f; dragForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f) dragForce = -0.5f * 1.23f * area * cD * u * u * eU; // Calculate gravitational force. glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f); // Get acceleration from total force. acceleration = (dragForce + magnusForce + gravitationForce) / mass; } velocity += acceleration * static_cast<float>(time); } } void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{ if (state != GolfBall::EXPLODED && state != GolfBall::OUT) ModelObject::Render(camera, screenSize, clippingPlane); } void GolfBall::Explode(std::vector<PlayerObject>& players){ //@TODO: Set mass equivalent depending on material used. float equivalenceFactor = 1.0f; float massEquivalent = mass*equivalenceFactor; for (auto &player : players){ glm::vec3 distanceV = (Position() - player.Position()); float distance = glm::length(distanceV); //pow(meq, 1.f/3.f) => cube root of meq float z = distance / (pow(massEquivalent, 1.f / 3.f)); float alpha = 1 + pow((z / 4.5f), 2.f); float beta = 1 + pow((z / 0.048f), 2.f); float gamma = 1 + pow((z / 1.35f), 2.f); float delta = 1 + pow((z / 0.32f), 2.f); //float Pf = 8.08f*pow(10.f, 7.f)*alpha; float Pf = ((8.08e7)*alpha) / sqrt(beta*gamma*delta); player.TakeDamage(Pf); } state = GolfBall::EXPLODED; } void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) { state = GolfBall::ACTIVE; // Club velocity in strike plane. float v = glm::length(clubVelocity); if (v > 0.f) { float sinLoft = sin(club.loft); float cosLoft = cos(club.loft); // Ball velocity. float massCoefficient = club.mass / (club.mass + mass); float Up = (1.f + restitution) * massCoefficient * v * cosLoft; float Un = (2.f / 7.f) * massCoefficient * v * sinLoft; // Go back from strike plane to 3D. glm::vec3 forward = clubVelocity / v; glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward)); glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up); glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up); // Total velocity. velocity = Up * ep + Un * en; angularVelocity = -Un / sphere.radius * glm::cross(ep, en); } else { velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); } } float GolfBall::Radius() const { return sphere.radius; } void GolfBall::SetRadius(float radius) { sphere.radius = radius; SetScale(glm::vec3(radius, radius, radius)); area = glm::pi<float>() * radius * radius; } glm::mat4 GolfBall::Orientation() const { return glm::toMat4(orientation); } GolfBall::State GolfBall::GetState() const { return state; } <|endoftext|>
<commit_before><?hh // strict namespace Dust\Evaluate; use Dust\Ast\Identifier; class Context { /** * @var \Dust\Evaluate\Evaluator */ public Evaluator $evaluator; /** * @var \Dust\Evaluate\Context */ public Context $parent; /** * @var \Dust\Evaluate\State */ public State $head; /** * @var string */ public string $currentFilePath; /** * @constructor * @param \Dust\Evaluate\Evaluator $evaluator * @param \Dust\Evaluate\Context $parent * @param \Dust\Evaluate\State $head */ public function __construct(Evaluator $evaluator, ?Context $parent = NULL, ?State $head = NULL): void { $this->evaluator = $evaluator; $this->parent = $parent; $this->head = $head; if ($parent != NULL) $this->currentFilePath = $parent->currentFilePath; } /** * @return string */ public function current(): string { if($this->head->forcedParent != NULL) return $this->head->forcedParent; return $this->head->value; } /** * @param string $key * @param $value * @return string */ public function findInArrayAccess(string $key, $value): ?string { if((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$key])) return $value[$key]; else return NULL; } /** * @param string $key * @param $parent */ public function findInObject(string $key, $parent) { if (is_object($parent) && !is_numeric($key)) { // Prop or method if (array_key_exists($key, $parent)) return $parent->{$key}; else if (method_exists($parent, $key)) return (new \ReflectionMethod($parent, $key))->getClosure($parent); else if (is_callable([ $parent, "get" . ucfirst($key) ])) { $getter = "get" . ucfirst($key); return $parent->$getter(); } } else { return NULL; } } /** * @param string $str */ public function get(string $str) { $ident = new Identifier(-1); $ident->key = $str; $resolved = $this->resolve($ident); $resolved = $this->evaluator->normalizeResolved($this, $resolved, new Chunk($this->evaluator)); if ($resolved instanceof Chunk) return $resolved->getOut(); return $resolved; } /** * @param \Dust\Evaluate\State $head * @param string $index * @param int $length * @param int iterationCount * @return \Dust\Evaluate\Context */ public function push(State $head, ?string $index = NULL, ?int $length = NULL, ?int $iterationCount = NULL): Context { $state = new State($head); if ($index !== NULL) $state->params["$idx"] = $index; if ($length !== NULL) $state->params["$len"] = $length; if ($iterationCount !== NULL) $state->params["$iter"] = $iterationCount; return $this->pushState($state); } /** * @param \Dust\Evaluate\State $head * @return \Dust\Evaluate\Context */ public function pushState(State $head): Context { return new Context($this->evaluator, $this, $head); } /** * @param string $head * @return \Dust\Evaluate\Context */ public function rebase(string $head): Context { return $this->rebaseState(new State($head)); } /** * @param \Dust\Evaluate\State $head * @return \Dust\Evaluate\Context */ public function rebaseState(State $head): Context { // Gotta get top parent $topParent = $this; while ($topParent->parent != NULL) $topParent = $topParent->parent; // Now create return new Context($this->evaluator, $topParent, $head); } /** * @param \Dust\Ast\Identifier $identifier * @param bool $forceArrayLookup * @param string $mainValue */ public function resolve(Identifier $identifier, $forceArrayLookup = false, ?string $mainValue = NULL) { if ($mainValue === NULL) $mainValue = $this->head->value; // Try local $resolved = $this->resolveLocal($identifier, $mainValue, $forceArrayLookup); // Forced local? if ($identifier->preDot) return $resolved; // If it's not there, we can try the forced parent if ($resolved === NULL && $this->head->forcedParent) $resolved = $this->resolveLocal($identifier, $this->head->forcedParent, $forceArrayLookup); // If it's still not there, we can try parameters if ($resolved === NULL && count($this->head->params) > 0) $resolved = $this->resolveLocal($identifier, $this->head->params, true); // Not there and not forced parent? walk up if($resolved === NULL && $this->head->forcedParent === NULL && $this->parent != NULL) $resolved = $this->parent->resolve($identifier, $forceArrayLookup); return $resolved; } /** * @param \Dust\Ast\Identifier $identifier * @param $parantObject * @param bool $forceArrayLookup */ public function resolveLocal(Identifier $identifier, $parentObject, $forceArrayLookup = false) { $key = NULL; if ($identifier->key != NULL) $key = $identifier->key; else if ($identifier->number != NULL) { $key = intval($identifier->number); // If this isn't an array lookup, just return the number if (!$forceArrayLookup) return $key; } $result = NULL; // No key, no array, but predot means result is just the parent if ($key === NULL && $identifier->preDot && $identifier->arrayAccess == NULL) $result = $parentObject; // Try to find on object (if we aren't forcing array lookup) if (!$forceArrayLookup && $key !== NULL) $result = $this->findInObject($key, $parentObject); // Now, try to find in array if ($result === NULL && $key !== NULL) $result = $this->findInArrayAccess($key, $parentObject); // If it's there (or has predot) and has array access, try to get array child if ($identifier->arrayAccess != NULL) { // Find the key $arrayKey = $this->resolve($identifier->arrayAccess, false, $parentObject); if ($arrayKey !== NULL) { $keyIdent = new Identifier(-1); if (is_numeric($arrayKey)) $keyIdent->number = strval($arrayKey); else $keyIdent->key = (string) $arrayKey; // Lookup by array key if ($result !== NULL) $result = $this->resolveLocal($keyIdent, $result, true); else if ($identifier->preDot) $result = $this->resolveLocal($keyIdent, $parentObject, true); } } // If it's there and has next, use it if ($result !== NULL && $identifier->next && !is_callable($result)) $result = $this->resolveLocal($identifier->next, $result); return $result; } }<commit_msg>Mixed value<commit_after><?hh // strict namespace Dust\Evaluate; use Dust\Ast\Identifier; class Context { /** * @var \Dust\Evaluate\Evaluator */ public Evaluator $evaluator; /** * @var \Dust\Evaluate\Context */ public Context $parent; /** * @var \Dust\Evaluate\State */ public State $head; /** * @var string */ public string $currentFilePath; /** * @constructor * @param \Dust\Evaluate\Evaluator $evaluator * @param \Dust\Evaluate\Context $parent * @param \Dust\Evaluate\State $head */ public function __construct(Evaluator $evaluator, ?Context $parent = NULL, ?State $head = NULL): void { $this->evaluator = $evaluator; $this->parent = $parent; $this->head = $head; if ($parent != NULL) $this->currentFilePath = $parent->currentFilePath; } /** * @return string */ public function current(): string { if($this->head->forcedParent != NULL) return $this->head->forcedParent; return $this->head->value; } /** * @param string $key * @param $value * @return mixed */ public function findInArrayAccess(string $key, $value) { if((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$key])) return $value[$key]; else return NULL; } /** * @param string $key * @param $parent */ public function findInObject(string $key, $parent) { if (is_object($parent) && !is_numeric($key)) { // Prop or method if (array_key_exists($key, $parent)) return $parent->{$key}; else if (method_exists($parent, $key)) return (new \ReflectionMethod($parent, $key))->getClosure($parent); else if (is_callable([ $parent, "get" . ucfirst($key) ])) { $getter = "get" . ucfirst($key); return $parent->$getter(); } } else { return NULL; } } /** * @param string $str */ public function get(string $str) { $ident = new Identifier(-1); $ident->key = $str; $resolved = $this->resolve($ident); $resolved = $this->evaluator->normalizeResolved($this, $resolved, new Chunk($this->evaluator)); if ($resolved instanceof Chunk) return $resolved->getOut(); return $resolved; } /** * @param \Dust\Evaluate\State $head * @param string $index * @param int $length * @param int iterationCount * @return \Dust\Evaluate\Context */ public function push(State $head, ?string $index = NULL, ?int $length = NULL, ?int $iterationCount = NULL): Context { $state = new State($head); if ($index !== NULL) $state->params["$idx"] = $index; if ($length !== NULL) $state->params["$len"] = $length; if ($iterationCount !== NULL) $state->params["$iter"] = $iterationCount; return $this->pushState($state); } /** * @param \Dust\Evaluate\State $head * @return \Dust\Evaluate\Context */ public function pushState(State $head): Context { return new Context($this->evaluator, $this, $head); } /** * @param string $head * @return \Dust\Evaluate\Context */ public function rebase(string $head): Context { return $this->rebaseState(new State($head)); } /** * @param \Dust\Evaluate\State $head * @return \Dust\Evaluate\Context */ public function rebaseState(State $head): Context { // Gotta get top parent $topParent = $this; while ($topParent->parent != NULL) $topParent = $topParent->parent; // Now create return new Context($this->evaluator, $topParent, $head); } /** * @param \Dust\Ast\Identifier $identifier * @param bool $forceArrayLookup * @param string $mainValue */ public function resolve(Identifier $identifier, $forceArrayLookup = false, ?string $mainValue = NULL) { if ($mainValue === NULL) $mainValue = $this->head->value; // Try local $resolved = $this->resolveLocal($identifier, $mainValue, $forceArrayLookup); // Forced local? if ($identifier->preDot) return $resolved; // If it's not there, we can try the forced parent if ($resolved === NULL && $this->head->forcedParent) $resolved = $this->resolveLocal($identifier, $this->head->forcedParent, $forceArrayLookup); // If it's still not there, we can try parameters if ($resolved === NULL && count($this->head->params) > 0) $resolved = $this->resolveLocal($identifier, $this->head->params, true); // Not there and not forced parent? walk up if($resolved === NULL && $this->head->forcedParent === NULL && $this->parent != NULL) $resolved = $this->parent->resolve($identifier, $forceArrayLookup); return $resolved; } /** * @param \Dust\Ast\Identifier $identifier * @param $parantObject * @param bool $forceArrayLookup */ public function resolveLocal(Identifier $identifier, $parentObject, $forceArrayLookup = false) { $key = NULL; if ($identifier->key != NULL) $key = $identifier->key; else if ($identifier->number != NULL) { $key = intval($identifier->number); // If this isn't an array lookup, just return the number if (!$forceArrayLookup) return $key; } $result = NULL; // No key, no array, but predot means result is just the parent if ($key === NULL && $identifier->preDot && $identifier->arrayAccess == NULL) $result = $parentObject; // Try to find on object (if we aren't forcing array lookup) if (!$forceArrayLookup && $key !== NULL) $result = $this->findInObject($key, $parentObject); // Now, try to find in array if ($result === NULL && $key !== NULL) $result = $this->findInArrayAccess($key, $parentObject); // If it's there (or has predot) and has array access, try to get array child if ($identifier->arrayAccess != NULL) { // Find the key $arrayKey = $this->resolve($identifier->arrayAccess, false, $parentObject); if ($arrayKey !== NULL) { $keyIdent = new Identifier(-1); if (is_numeric($arrayKey)) $keyIdent->number = strval($arrayKey); else $keyIdent->key = (string) $arrayKey; // Lookup by array key if ($result !== NULL) $result = $this->resolveLocal($keyIdent, $result, true); else if ($identifier->preDot) $result = $this->resolveLocal($keyIdent, $parentObject, true); } } // If it's there and has next, use it if ($result !== NULL && $identifier->next && !is_callable($result)) $result = $this->resolveLocal($identifier->next, $result); return $result; } }<|endoftext|>
<commit_before>#include <QtWidgets> #include "LatticeFittingWindow.hpp" #include "PointDetector.hpp" #include "ImageProcessor.hpp" #include "LatticeFittingDockWidget.hpp" LatticeFittingWindow::LatticeFittingWindow() : _imageLabel(new QLabel(this)), _scrollArea(new QScrollArea(this)), _dockWidget(new LatticeFittingDockWidget(this)), _imageProcessor(new ImageProcessor(this)), _pointDetector(new PointDetector(*_dockWidget->_pointDetectorWidget, this)) { _imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); _imageLabel->setScaledContents(true); _scrollArea->setBackgroundRole(QPalette::Dark); _scrollArea->setWidget(_imageLabel); auto layout = new QHBoxLayout; layout->addWidget(_scrollArea); auto centralWidget = new QWidget(this); centralWidget->setLayout(layout); setCentralWidget(centralWidget); createActions(); createMenus(); // dialog -------------------------------------------------------------------- const auto picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation); _openDialog = new QFileDialog( this, tr("Open File"), picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last() ); _openDialog->setAcceptMode(QFileDialog::AcceptOpen); _openDialog->selectMimeTypeFilter("image/jpeg"); setStatusBar(new QStatusBar); addDockWidget(Qt::RightDockWidgetArea, _dockWidget); resize(QGuiApplication::primaryScreen()->availableSize() / 1.5); } bool LatticeFittingWindow::loadFile(const QString& fileName) { _cvImage = cv::imread(fileName.toStdString()); if (!_cvImage.data) { QMessageBox::information( this, QGuiApplication::applicationDisplayName(), tr("Cannot load %1.").arg(QDir::toNativeSeparators(fileName))); setWindowFilePath(QString()); _imageLabel->setPixmap(QPixmap()); _imageLabel->adjustSize(); return false; } resetImage(); cv::cvtColor(_cvImage, _cvGray, cv::COLOR_BGR2GRAY); setWindowFilePath(fileName); statusBar()->showMessage(QStringLiteral("Image Loaded successfully."), 10000); return true; } void LatticeFittingWindow::open() { while (_openDialog->exec() && !loadFile(_openDialog->selectedFiles().first())); if (!_openDialog->selectedFiles().isEmpty()) _openDialog->setDirectory( QFileInfo(_openDialog->selectedFiles().first()).path()); } void LatticeFittingWindow::detect() { if (_dockWidget->_thresholdWidget->isChecked()) { _pointDetector->detect(_cvThresh, _cvThresh); _imageLabel->setPixmap( _imageProcessor->mat2QPixmapGray(_pointDetector->_points_image) ); } else { _pointDetector->detect(_cvImage, _cvGray); _imageLabel->setPixmap( _imageProcessor->mat2QPixmap(_pointDetector->_points_image) ); } _imageLabel->adjustSize(); } void LatticeFittingWindow::toggleDetect(bool toggle) { if (toggle) { detect(); } else { resetImage(); if (_dockWidget->_thresholdWidget->isChecked()) threshold(_dockWidget->_thresholdWidget->level()); } } void LatticeFittingWindow::threshold(int value) { _imageProcessor->threshold(_cvGray, _cvThresh, static_cast<double>(value)); _imageLabel->setPixmap(_imageProcessor->mat2QPixmapGray(_cvThresh)); _imageLabel->adjustSize(); } void LatticeFittingWindow::toggleThreshold(bool toggle) { if (toggle) { threshold(_dockWidget->_thresholdWidget->level()); } else { resetImage(); } if (_dockWidget->_pointDetectorWidget->isChecked()) detect(); } void LatticeFittingWindow::createActions() { _openAct = new QAction(tr("&Open Image..."), this); _openAct->setShortcut(tr("Ctrl+O")); connect(_openAct, &QAction::triggered, this, &LatticeFittingWindow::open); _exitAct = new QAction(tr("E&xit"), this); _exitAct->setShortcut(tr("Ctrl+Q")); connect(_exitAct, &QAction::triggered, this, &LatticeFittingWindow::close); _detectAct = new QAction(tr("Detect Grid &Points"), this); _detectAct->setShortcut(tr("Ctrl+P")); connect(_detectAct, &QAction::triggered, this, &LatticeFittingWindow::detect); connect(_dockWidget->_pointDetectorWidget, SIGNAL(parameterChanged()), this, SLOT(detect())); connect(_dockWidget->_pointDetectorWidget, SIGNAL(toggled(bool)), this, SLOT(toggleDetect(bool))); connect(_dockWidget->_thresholdWidget, SIGNAL(levelChanged(int)), this, SLOT(threshold(int))); connect(_dockWidget->_thresholdWidget, SIGNAL(toggled(bool)), this, SLOT(toggleThreshold(bool))); } void LatticeFittingWindow::createMenus() { _fileMenu = new QMenu(tr("&File"), this); _fileMenu->addAction(_openAct); _fileMenu->addSeparator(); _fileMenu->addAction(_exitAct); _detectMenu = new QMenu(tr("&Detection"), this); _detectMenu->addAction(_detectAct); menuBar()->addMenu(_fileMenu); menuBar()->addMenu(_detectMenu); } void LatticeFittingWindow::resetImage() { _imageLabel->setPixmap(_imageProcessor->mat2QPixmap(_cvImage)); _imageLabel->adjustSize(); } <commit_msg>Applied changes from removal of ImageProcessor<commit_after>#include <QtWidgets> #include "LatticeFittingWindow.hpp" #include "PointDetector.hpp" #include "functions.hpp" #include "LatticeFittingDockWidget.hpp" LatticeFittingWindow::LatticeFittingWindow() : _imageLabel(new QLabel(this)), _scrollArea(new QScrollArea(this)), _dockWidget(new LatticeFittingDockWidget(this)), _pointDetector(new PointDetector(*_dockWidget->_pointDetectorWidget, this)) { _imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); _imageLabel->setScaledContents(true); _scrollArea->setBackgroundRole(QPalette::Dark); _scrollArea->setWidget(_imageLabel); auto layout = new QHBoxLayout; layout->addWidget(_scrollArea); auto centralWidget = new QWidget(this); centralWidget->setLayout(layout); setCentralWidget(centralWidget); createActions(); createMenus(); // dialog -------------------------------------------------------------------- const auto picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation); _openDialog = new QFileDialog( this, tr("Open File"), picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last() ); _openDialog->setAcceptMode(QFileDialog::AcceptOpen); _openDialog->selectMimeTypeFilter("image/jpeg"); setStatusBar(new QStatusBar); addDockWidget(Qt::RightDockWidgetArea, _dockWidget); resize(QGuiApplication::primaryScreen()->availableSize() / 1.5); } bool LatticeFittingWindow::loadFile(const QString& fileName) { _cvImage = cv::imread(fileName.toStdString()); if (!_cvImage.data) { QMessageBox::information( this, QGuiApplication::applicationDisplayName(), tr("Cannot load %1.").arg(QDir::toNativeSeparators(fileName))); setWindowFilePath(QString()); _imageLabel->setPixmap(QPixmap()); _imageLabel->adjustSize(); return false; } resetImage(); cv::cvtColor(_cvImage, _cvGray, cv::COLOR_BGR2GRAY); setWindowFilePath(fileName); statusBar()->showMessage(QStringLiteral("Image Loaded successfully."), 10000); return true; } void LatticeFittingWindow::open() { while (_openDialog->exec() && !loadFile(_openDialog->selectedFiles().first())); if (!_openDialog->selectedFiles().isEmpty()) _openDialog->setDirectory( QFileInfo(_openDialog->selectedFiles().first()).path()); } void LatticeFittingWindow::detect() { if (_dockWidget->_thresholdWidget->isChecked()) { _pointDetector->detect(_cvThresh, _cvThresh); _imageLabel->setPixmap( mat2QPixmapGray(_pointDetector->_points_image) ); } else { _pointDetector->detect(_cvImage, _cvGray); _imageLabel->setPixmap( mat2QPixmap(_pointDetector->_points_image) ); } _imageLabel->adjustSize(); } void LatticeFittingWindow::toggleDetect(bool toggle) { if (toggle) { detect(); } else { resetImage(); if (_dockWidget->_thresholdWidget->isChecked()) threshold(_dockWidget->_thresholdWidget->level()); } } void LatticeFittingWindow::threshold(int value) { applyThreshold(_cvGray, _cvThresh, static_cast<double>(value)); _imageLabel->setPixmap(mat2QPixmapGray(_cvThresh)); _imageLabel->adjustSize(); } void LatticeFittingWindow::toggleThreshold(bool toggle) { if (toggle) { threshold(_dockWidget->_thresholdWidget->level()); } else { resetImage(); } if (_dockWidget->_pointDetectorWidget->isChecked()) detect(); } void LatticeFittingWindow::createActions() { _openAct = new QAction(tr("&Open Image..."), this); _openAct->setShortcut(tr("Ctrl+O")); connect(_openAct, &QAction::triggered, this, &LatticeFittingWindow::open); _exitAct = new QAction(tr("E&xit"), this); _exitAct->setShortcut(tr("Ctrl+Q")); connect(_exitAct, &QAction::triggered, this, &LatticeFittingWindow::close); _detectAct = new QAction(tr("Detect Grid &Points"), this); _detectAct->setShortcut(tr("Ctrl+P")); connect(_detectAct, &QAction::triggered, this, &LatticeFittingWindow::detect); connect(_dockWidget->_pointDetectorWidget, SIGNAL(parameterChanged()), this, SLOT(detect())); connect(_dockWidget->_pointDetectorWidget, SIGNAL(toggled(bool)), this, SLOT(toggleDetect(bool))); connect(_dockWidget->_thresholdWidget, SIGNAL(levelChanged(int)), this, SLOT(threshold(int))); connect(_dockWidget->_thresholdWidget, SIGNAL(toggled(bool)), this, SLOT(toggleThreshold(bool))); } void LatticeFittingWindow::createMenus() { _fileMenu = new QMenu(tr("&File"), this); _fileMenu->addAction(_openAct); _fileMenu->addSeparator(); _fileMenu->addAction(_exitAct); _detectMenu = new QMenu(tr("&Detection"), this); _detectMenu->addAction(_detectAct); menuBar()->addMenu(_fileMenu); menuBar()->addMenu(_detectMenu); } void LatticeFittingWindow::resetImage() { _imageLabel->setPixmap(mat2QPixmap(_cvImage)); _imageLabel->adjustSize(); } <|endoftext|>
<commit_before>/* * File: LuaHeader.hpp * Author: frex * * Created on August 9, 2014, 6:35 PM */ #ifndef LUAHEADER_HPP #define LUAHEADER_HPP #include <lua.hpp> #include <cstddef> #include <cstring> //this header is to allow both lua jit (based on 5.1), 5.1 and 5.2 be //used with the console by defining some very minor things //NOTE: //since we define things that might be defined (ie. equal, which is deprecated, //do missing by default but may be present) we prepend bla_ to them //this also lets code of model know which functions are 'common' between 51 and //52 and 53 and which are 'patchwork' to allow this code sharing, //incompleteChunkError is exempt from that, since it's in our lua namespace, //it's not a symbol from either of Lua versions and it ended up here just //because it depends on the version of lua as well //---------------------------------------------------------------------- //LUA 5.2 AND LUA 5.3 -------------------------------------------------- #if ((LUA_VERSION_NUM == 502) || (LUA_VERSION_NUM == 503)) namespace blua { inline bool incompleteChunkError(const char * err, std::size_t len) { return 0 == std::strcmp(err + len - 5u, "<eof>"); } } //blua //5.2 deprecated lua_equal so we use lua_compare to reimplement it: inline int bla_lua_equal(lua_State * L, int index1, int index2) { return lua_compare(L, index1, index2, LUA_OPEQ); } #define bla_lua_pushglobaltable lua_pushglobaltable #define BLA_LUA_OK LUA_OK #endif //LUA 5.2 or LUA 5.3 //---------------------------------------------------------------------- //LUA JIT AND 5.1 ------------------------------------------------------ #if (LUA_VERSION_NUM == 501) namespace blua { inline bool incompleteChunkError(const char * err, std::size_t len) { return 0 == std::strcmp(err + len - 7u, "'<eof>'"); } } //blua #define bla_lua_equal lua_equal //pushglobaltable is missing but easy to fake via old method of getting globals: #define bla_lua_pushglobaltable(L) (lua_pushvalue((L), LUA_GLOBALSINDEX)) //LUA_OK is missing but 0 is assumed to be 'success' value in comments, so: #define BLA_LUA_OK 0 #endif //LUA 5.1 #endif /* LUAHEADER_HPP */ <commit_msg>Fix for two rare potential bad memory accesses. 1. Check for null err str - possible on error called with non str. 2. Check for length to not look for eof str in short messages.<commit_after>/* * File: LuaHeader.hpp * Author: frex * * Created on August 9, 2014, 6:35 PM */ #ifndef LUAHEADER_HPP #define LUAHEADER_HPP #include <lua.hpp> #include <cstddef> #include <cstring> //this header is to allow both lua jit (based on 5.1), 5.1 and 5.2 be //used with the console by defining some very minor things //NOTE: //since we define things that might be defined (ie. equal, which is deprecated, //do missing by default but may be present) we prepend bla_ to them //this also lets code of model know which functions are 'common' between 51 and //52 and 53 and which are 'patchwork' to allow this code sharing, //incompleteChunkError is exempt from that, since it's in our lua namespace, //it's not a symbol from either of Lua versions and it ended up here just //because it depends on the version of lua as well //---------------------------------------------------------------------- //LUA 5.2 AND LUA 5.3 -------------------------------------------------- #if ((LUA_VERSION_NUM == 502) || (LUA_VERSION_NUM == 503)) namespace blua { inline bool incompleteChunkError(const char * err, std::size_t len) { return err && (std::strlen(err) >= 5u) && (0 == std::strcmp(err + len - 5u, "<eof>")); } } //blua //5.2 deprecated lua_equal so we use lua_compare to reimplement it: inline int bla_lua_equal(lua_State * L, int index1, int index2) { return lua_compare(L, index1, index2, LUA_OPEQ); } #define bla_lua_pushglobaltable lua_pushglobaltable #define BLA_LUA_OK LUA_OK #endif //LUA 5.2 or LUA 5.3 //---------------------------------------------------------------------- //LUA JIT AND 5.1 ------------------------------------------------------ #if (LUA_VERSION_NUM == 501) namespace blua { inline bool incompleteChunkError(const char * err, std::size_t len) { return err && (std::strlen(err) >= 7u) && (0 == std::strcmp(err + len - 7u, "'<eof>'")); } } //blua #define bla_lua_equal lua_equal //pushglobaltable is missing but easy to fake via old method of getting globals: #define bla_lua_pushglobaltable(L) (lua_pushvalue((L), LUA_GLOBALSINDEX)) //LUA_OK is missing but 0 is assumed to be 'success' value in comments, so: #define BLA_LUA_OK 0 #endif //LUA 5.1 #endif /* LUAHEADER_HPP */ <|endoftext|>
<commit_before>/* * OSPRaySphereGeometry.cpp * Copyright (C) 2009-2017 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "OSPRaySphereGeometry.h" #include "vislib/forceinline.h" #include "mmcore/moldyn/MultiParticleDataCall.h" #include "mmcore/param/FloatParam.h" #include "mmcore/param/IntParam.h" #include "mmcore/param/Vector3fParam.h" #include "mmcore/param/EnumParam.h" #include "vislib/sys/Log.h" #include "mmcore/Call.h" #include "mmcore/view/CallGetTransferFunction.h" #include "mmcore/view/CallClipPlane.h" using namespace megamol::ospray; VISLIB_FORCEINLINE float floatFromVoidArray(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index) { //const float* parts = static_cast<const float*>(p.GetVertexData()); //return parts[index * stride + offset]; return static_cast<const float*>(p.GetVertexData())[index]; } VISLIB_FORCEINLINE unsigned char byteFromVoidArray(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index) { return static_cast<const unsigned char*>(p.GetVertexData())[index]; } typedef float(*floatFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); typedef unsigned char(*byteFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); OSPRaySphereGeometry::OSPRaySphereGeometry(void) : AbstractOSPRayStructure(), getDataSlot("getdata", "Connects to the data source"), getTFSlot("gettransferfunction", "Connects to the transfer function module"), getClipPlaneSlot("getclipplane", "Connects to a clipping plane module"), particleList("ParticleList", "Switches between particle lists") { this->getDataSlot.SetCompatibleCall<core::moldyn::MultiParticleDataCallDescription>(); this->MakeSlotAvailable(&this->getDataSlot); this->getTFSlot.SetCompatibleCall<core::view::CallGetTransferFunctionDescription>(); this->MakeSlotAvailable(&this->getTFSlot); this->getClipPlaneSlot.SetCompatibleCall<core::view::CallClipPlaneDescription>(); this->MakeSlotAvailable(&this->getClipPlaneSlot); this->particleList << new core::param::IntParam(0); this->MakeSlotAvailable(&this->particleList); } bool OSPRaySphereGeometry::readData(megamol::core::Call &call) { // read Data, calculate shape parameters, fill data vectors CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); this->structureContainer.dataChanged = false; if (cd == NULL) return false; if (cd->FrameCount() <= 1) { cd->SetFrameID(0.0f, true); // isTimeForced flag set to true } else { cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true } if (this->datahash != cd->DataHash() || this->time != os->getTime() || this->InterfaceIsDirty()) { this->datahash = cd->DataHash(); this->time = os->getTime(); this->structureContainer.dataChanged = true; } else { return true; } if (this->particleList.Param<core::param::IntParam>()->Value() >(cd->GetParticleListCount() - 1)) { this->particleList.Param<core::param::IntParam>()->SetValue(0); } if (!(*cd)(1)) return false; if (!(*cd)(0)) return false; core::moldyn::MultiParticleDataCall::Particles &parts = cd->AccessParticles(this->particleList.Param<core::param::IntParam>()->Value()); unsigned int partCount = parts.GetCount(); float globalRadius = parts.GetGlobalRadius(); size_t vertexLength; size_t colorLength; // Vertex data type check if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ) { vertexLength = 3; } else if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR) { vertexLength = 4; } // reserve space for vertex data object vd.reserve(parts.GetCount() * vertexLength); // Color data type check if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGBA) { colorLength = 4; //convertedColorType = OSP_FLOAT4; cd_rgba.reserve(parts.GetCount() * colorLength); floatFromArrayFunc ffaf; ffaf = floatFromVoidArray; for (size_t loop = 0; loop < (parts.GetCount() * parts.GetVertexDataStride() / sizeof(float)); loop++) { if (loop % (vertexLength + colorLength) >= vertexLength) { cd_rgba.push_back(ffaf(parts, loop)); } else { vd.push_back(ffaf(parts, loop)); } } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_I) { // this colorType will be transformed to: //convertedColorType = OSP_FLOAT4; colorLength = 4; cd_rgba.reserve(parts.GetCount() * colorLength); floatFromArrayFunc ffaf; ffaf = floatFromVoidArray; std::vector<float> cd; for (size_t loop = 0; loop < (parts.GetCount() * parts.GetVertexDataStride() / sizeof(float)); loop++) { if (loop % (vertexLength + 1) >= vertexLength) { cd.push_back(ffaf(parts, loop)); } else { vd.push_back(ffaf(parts, loop)); } } // Color transfer call and calculation core::view::CallGetTransferFunction *cgtf = this->getTFSlot.CallAs<core::view::CallGetTransferFunction>(); if (cgtf != NULL && ((*cgtf)())) { float const* tf_tex = cgtf->GetTextureData(); tex_size = cgtf->TextureSize(); this->colorTransferGray(cd, tf_tex, tex_size, cd_rgba); } else { this->colorTransferGray(cd, NULL, 0, cd_rgba); } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGB) { colorLength = 3; //convertedColorType = OSP_FLOAT3; cd_rgba.reserve(parts.GetCount() * colorLength); floatFromArrayFunc ffaf; ffaf = floatFromVoidArray; for (size_t loop = 0; loop < (parts.GetCount() * parts.GetVertexDataStride() / sizeof(float)); loop++) { if (loop % (vertexLength + colorLength) >= vertexLength) { cd_rgba.push_back(ffaf(parts, loop)); } else { vd.push_back(ffaf(parts, loop)); } } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_UINT8_RGBA) { colorLength = 4; //convertedColorType = OSP_FLOAT4; cd_rgba.reserve(parts.GetCount() * colorLength); float alpha = 1.0f; byteFromArrayFunc bfaf; bfaf = byteFromVoidArray; vd.resize(parts.GetCount() * vertexLength); auto data = static_cast<const float*>(parts.GetVertexData()); for (size_t i = 0; i < parts.GetCount(); i++) { std::copy_n(data + (i * parts.GetVertexDataStride() / sizeof(float)), vertexLength, vd.begin() + (i * vertexLength)); for (size_t j = 0; j < colorLength; j++) { cd_rgba.push_back((float)bfaf(parts, i * parts.GetVertexDataStride() + vertexLength * sizeof(float) + j) / 255.0f); } } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_UINT8_RGB) { vislib::sys::Log::DefaultLog.WriteError("File format deprecated. Convert your data."); } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_NONE) { colorLength = 4; cd_rgba.reserve(parts.GetCount() * colorLength); auto pdata = (float*)parts.GetVertexData(); vd.assign(pdata, pdata + parts.GetCount() * vertexLength); auto globalColor = parts.GetGlobalColour(); for (size_t i = 0; i < parts.GetCount(); i++) { for (size_t j = 0; j < colorLength; j++) { cd_rgba.push_back((float)globalColor[j]/255.0f); } } } // Write stuff into the structureContainer CallOSPRayMaterial *cm = this->getMaterialSlot.CallAs<CallOSPRayMaterial>(); if (cm != NULL) { auto gmp = cm->getMaterialParameter(); if (gmp->isValid) { this->structureContainer.materialContainer = cm->getMaterialParameter(); } } else { this->structureContainer.materialContainer = NULL; } this->structureContainer.type = structureTypeEnum::GEOMETRY; this->structureContainer.geometryType = geometryTypeEnum::SPHERES; this->structureContainer.vertexData = std::make_shared<std::vector<float>>(std::move(vd)); this->structureContainer.colorData = std::make_shared<std::vector<float>>(std::move(cd_rgba)); this->structureContainer.vertexLength = vertexLength; this->structureContainer.colorLength = colorLength; this->structureContainer.partCount = partCount; this->structureContainer.globalRadius = globalRadius; return true; } void OSPRaySphereGeometry::colorTransferGray(std::vector<float> &grayArray, float const* transferTable, unsigned int tableSize, std::vector<float> &rgbaArray) { float gray_max = *std::max_element(grayArray.begin(), grayArray.end()); float gray_min = *std::min_element(grayArray.begin(), grayArray.end()); for (auto &gray : grayArray) { float scaled_gray; if ((gray_max - gray_min) <= 1e-4f) { scaled_gray = 0; } else { scaled_gray = (gray - gray_min) / (gray_max - gray_min); } if (transferTable == NULL && tableSize == 0) { for (int i = 0; i < 3; i++) { rgbaArray.push_back((0.3f + scaled_gray) / 1.3f); } rgbaArray.push_back(1.0f); } else { float exact_tf = (tableSize - 1) * scaled_gray; int floor = std::floor(exact_tf); float tail = exact_tf - (float)floor; floor *= 4; for (int i = 0; i < 4; i++) { float colorFloor = transferTable[floor + i]; float colorCeil = transferTable[floor + i + 4]; float finalColor = colorFloor + (colorCeil - colorFloor)*(tail); rgbaArray.push_back(finalColor); } } } } OSPRaySphereGeometry::~OSPRaySphereGeometry() { // } bool OSPRaySphereGeometry::create() { return true; } void OSPRaySphereGeometry::release() { } /* ospray::OSPRaySphereGeometry::InterfaceIsDirty() */ bool OSPRaySphereGeometry::InterfaceIsDirty() { CallOSPRayMaterial *cm = this->getMaterialSlot.CallAs<CallOSPRayMaterial>(); cm->getMaterialParameter(); if ( cm->InterfaceIsDirty() || this->particleList.IsDirty() ) { this->particleList.ResetDirty(); return true; } else { return false; } } /* * ospray::OSPRaySphereGeometry::getClipData */ void OSPRaySphereGeometry::getClipData(float *clipDat, float *clipCol) { megamol::core::view::CallClipPlane *ccp = this->getClipPlaneSlot.CallAs<megamol::core::view::CallClipPlane>(); if ((ccp != NULL) && (*ccp)()) { clipDat[0] = ccp->GetPlane().Normal().X(); clipDat[1] = ccp->GetPlane().Normal().Y(); clipDat[2] = ccp->GetPlane().Normal().Z(); vislib::math::Vector<float, 3> grr(ccp->GetPlane().Point().PeekCoordinates()); clipDat[3] = grr.Dot(ccp->GetPlane().Normal()); clipCol[0] = static_cast<float>(ccp->GetColour()[0]) / 255.0f; clipCol[1] = static_cast<float>(ccp->GetColour()[1]) / 255.0f; clipCol[2] = static_cast<float>(ccp->GetColour()[2]) / 255.0f; clipCol[3] = static_cast<float>(ccp->GetColour()[3]) / 255.0f; } else { clipDat[0] = clipDat[1] = clipDat[2] = clipDat[3] = 0.0f; clipCol[0] = clipCol[1] = clipCol[2] = 0.75f; clipCol[3] = 1.0f; } } bool OSPRaySphereGeometry::getExtends(megamol::core::Call &call) { CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); if (cd == NULL) return false; if (cd->FrameCount() <= 1) { cd->SetFrameID(0.0f, true); // isTimeForced flag set to true } else { cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true } if (!(*cd)(1)) return false; this->extendContainer.boundingBox = std::make_shared<megamol::core::BoundingBoxes>(cd->AccessBoundingBoxes()); this->extendContainer.timeFramesCount = cd->FrameCount(); this->extendContainer.isValid = true; return true; }<commit_msg>if a dataset dosn't provide the required time, it is not read again<commit_after>/* * OSPRaySphereGeometry.cpp * Copyright (C) 2009-2017 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "OSPRaySphereGeometry.h" #include "vislib/forceinline.h" #include "mmcore/moldyn/MultiParticleDataCall.h" #include "mmcore/param/FloatParam.h" #include "mmcore/param/IntParam.h" #include "mmcore/param/Vector3fParam.h" #include "mmcore/param/EnumParam.h" #include "vislib/sys/Log.h" #include "mmcore/Call.h" #include "mmcore/view/CallGetTransferFunction.h" #include "mmcore/view/CallClipPlane.h" using namespace megamol::ospray; VISLIB_FORCEINLINE float floatFromVoidArray(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index) { //const float* parts = static_cast<const float*>(p.GetVertexData()); //return parts[index * stride + offset]; return static_cast<const float*>(p.GetVertexData())[index]; } VISLIB_FORCEINLINE unsigned char byteFromVoidArray(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index) { return static_cast<const unsigned char*>(p.GetVertexData())[index]; } typedef float(*floatFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); typedef unsigned char(*byteFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); OSPRaySphereGeometry::OSPRaySphereGeometry(void) : AbstractOSPRayStructure(), getDataSlot("getdata", "Connects to the data source"), getTFSlot("gettransferfunction", "Connects to the transfer function module"), getClipPlaneSlot("getclipplane", "Connects to a clipping plane module"), particleList("ParticleList", "Switches between particle lists") { this->getDataSlot.SetCompatibleCall<core::moldyn::MultiParticleDataCallDescription>(); this->MakeSlotAvailable(&this->getDataSlot); this->getTFSlot.SetCompatibleCall<core::view::CallGetTransferFunctionDescription>(); this->MakeSlotAvailable(&this->getTFSlot); this->getClipPlaneSlot.SetCompatibleCall<core::view::CallClipPlaneDescription>(); this->MakeSlotAvailable(&this->getClipPlaneSlot); this->particleList << new core::param::IntParam(0); this->MakeSlotAvailable(&this->particleList); } bool OSPRaySphereGeometry::readData(megamol::core::Call &call) { // read Data, calculate shape parameters, fill data vectors CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); this->structureContainer.dataChanged = false; if (cd == NULL) return false; cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true if (this->datahash != cd->DataHash() || this->time != os->getTime() || this->InterfaceIsDirty()) { this->datahash = cd->DataHash(); this->time = os->getTime(); this->structureContainer.dataChanged = true; } else { return true; } if (this->particleList.Param<core::param::IntParam>()->Value() >(cd->GetParticleListCount() - 1)) { this->particleList.Param<core::param::IntParam>()->SetValue(0); } if (!(*cd)(1)) return false; if ((*cd)(0)) { core::moldyn::MultiParticleDataCall::Particles &parts = cd->AccessParticles(this->particleList.Param<core::param::IntParam>()->Value()); unsigned int partCount = parts.GetCount(); float globalRadius = parts.GetGlobalRadius(); size_t vertexLength; size_t colorLength; // Vertex data type check if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ) { vertexLength = 3; } else if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR) { vertexLength = 4; } // reserve space for vertex data object vd.reserve(parts.GetCount() * vertexLength); // Color data type check if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGBA) { colorLength = 4; //convertedColorType = OSP_FLOAT4; cd_rgba.reserve(parts.GetCount() * colorLength); floatFromArrayFunc ffaf; ffaf = floatFromVoidArray; for (size_t loop = 0; loop < (parts.GetCount() * parts.GetVertexDataStride() / sizeof(float)); loop++) { if (loop % (vertexLength + colorLength) >= vertexLength) { cd_rgba.push_back(ffaf(parts, loop)); } else { vd.push_back(ffaf(parts, loop)); } } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_I) { // this colorType will be transformed to: //convertedColorType = OSP_FLOAT4; colorLength = 4; cd_rgba.reserve(parts.GetCount() * colorLength); floatFromArrayFunc ffaf; ffaf = floatFromVoidArray; std::vector<float> cd; for (size_t loop = 0; loop < (parts.GetCount() * parts.GetVertexDataStride() / sizeof(float)); loop++) { if (loop % (vertexLength + 1) >= vertexLength) { cd.push_back(ffaf(parts, loop)); } else { vd.push_back(ffaf(parts, loop)); } } // Color transfer call and calculation core::view::CallGetTransferFunction *cgtf = this->getTFSlot.CallAs<core::view::CallGetTransferFunction>(); if (cgtf != NULL && ((*cgtf)())) { float const* tf_tex = cgtf->GetTextureData(); tex_size = cgtf->TextureSize(); this->colorTransferGray(cd, tf_tex, tex_size, cd_rgba); } else { this->colorTransferGray(cd, NULL, 0, cd_rgba); } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGB) { colorLength = 3; //convertedColorType = OSP_FLOAT3; cd_rgba.reserve(parts.GetCount() * colorLength); floatFromArrayFunc ffaf; ffaf = floatFromVoidArray; for (size_t loop = 0; loop < (parts.GetCount() * parts.GetVertexDataStride() / sizeof(float)); loop++) { if (loop % (vertexLength + colorLength) >= vertexLength) { cd_rgba.push_back(ffaf(parts, loop)); } else { vd.push_back(ffaf(parts, loop)); } } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_UINT8_RGBA) { colorLength = 4; //convertedColorType = OSP_FLOAT4; cd_rgba.reserve(parts.GetCount() * colorLength); float alpha = 1.0f; byteFromArrayFunc bfaf; bfaf = byteFromVoidArray; vd.resize(parts.GetCount() * vertexLength); auto data = static_cast<const float*>(parts.GetVertexData()); for (size_t i = 0; i < parts.GetCount(); i++) { std::copy_n(data + (i * parts.GetVertexDataStride() / sizeof(float)), vertexLength, vd.begin() + (i * vertexLength)); for (size_t j = 0; j < colorLength; j++) { cd_rgba.push_back((float)bfaf(parts, i * parts.GetVertexDataStride() + vertexLength * sizeof(float) + j) / 255.0f); } } } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_UINT8_RGB) { vislib::sys::Log::DefaultLog.WriteError("File format deprecated. Convert your data."); } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_NONE) { colorLength = 4; cd_rgba.reserve(parts.GetCount() * colorLength); auto pdata = (float*)parts.GetVertexData(); vd.assign(pdata, pdata + parts.GetCount() * vertexLength); auto globalColor = parts.GetGlobalColour(); for (size_t i = 0; i < parts.GetCount(); i++) { for (size_t j = 0; j < colorLength; j++) { cd_rgba.push_back((float)globalColor[j] / 255.0f); } } } // Write stuff into the structureContainer this->structureContainer.type = structureTypeEnum::GEOMETRY; this->structureContainer.geometryType = geometryTypeEnum::SPHERES; this->structureContainer.vertexData = std::make_shared<std::vector<float>>(std::move(vd)); this->structureContainer.colorData = std::make_shared<std::vector<float>>(std::move(cd_rgba)); this->structureContainer.vertexLength = vertexLength; this->structureContainer.colorLength = colorLength; this->structureContainer.partCount = partCount; this->structureContainer.globalRadius = globalRadius; } // material container CallOSPRayMaterial *cm = this->getMaterialSlot.CallAs<CallOSPRayMaterial>(); if (cm != NULL) { auto gmp = cm->getMaterialParameter(); if (gmp->isValid) { this->structureContainer.materialContainer = cm->getMaterialParameter(); } } else { this->structureContainer.materialContainer = NULL; } return true; } void OSPRaySphereGeometry::colorTransferGray(std::vector<float> &grayArray, float const* transferTable, unsigned int tableSize, std::vector<float> &rgbaArray) { float gray_max = *std::max_element(grayArray.begin(), grayArray.end()); float gray_min = *std::min_element(grayArray.begin(), grayArray.end()); for (auto &gray : grayArray) { float scaled_gray; if ((gray_max - gray_min) <= 1e-4f) { scaled_gray = 0; } else { scaled_gray = (gray - gray_min) / (gray_max - gray_min); } if (transferTable == NULL && tableSize == 0) { for (int i = 0; i < 3; i++) { rgbaArray.push_back((0.3f + scaled_gray) / 1.3f); } rgbaArray.push_back(1.0f); } else { float exact_tf = (tableSize - 1) * scaled_gray; int floor = std::floor(exact_tf); float tail = exact_tf - (float)floor; floor *= 4; for (int i = 0; i < 4; i++) { float colorFloor = transferTable[floor + i]; float colorCeil = transferTable[floor + i + 4]; float finalColor = colorFloor + (colorCeil - colorFloor)*(tail); rgbaArray.push_back(finalColor); } } } } OSPRaySphereGeometry::~OSPRaySphereGeometry() { // } bool OSPRaySphereGeometry::create() { return true; } void OSPRaySphereGeometry::release() { } /* ospray::OSPRaySphereGeometry::InterfaceIsDirty() */ bool OSPRaySphereGeometry::InterfaceIsDirty() { CallOSPRayMaterial *cm = this->getMaterialSlot.CallAs<CallOSPRayMaterial>(); cm->getMaterialParameter(); if ( cm->InterfaceIsDirty() || this->particleList.IsDirty() ) { this->particleList.ResetDirty(); return true; } else { return false; } } /* * ospray::OSPRaySphereGeometry::getClipData */ void OSPRaySphereGeometry::getClipData(float *clipDat, float *clipCol) { megamol::core::view::CallClipPlane *ccp = this->getClipPlaneSlot.CallAs<megamol::core::view::CallClipPlane>(); if ((ccp != NULL) && (*ccp)()) { clipDat[0] = ccp->GetPlane().Normal().X(); clipDat[1] = ccp->GetPlane().Normal().Y(); clipDat[2] = ccp->GetPlane().Normal().Z(); vislib::math::Vector<float, 3> grr(ccp->GetPlane().Point().PeekCoordinates()); clipDat[3] = grr.Dot(ccp->GetPlane().Normal()); clipCol[0] = static_cast<float>(ccp->GetColour()[0]) / 255.0f; clipCol[1] = static_cast<float>(ccp->GetColour()[1]) / 255.0f; clipCol[2] = static_cast<float>(ccp->GetColour()[2]) / 255.0f; clipCol[3] = static_cast<float>(ccp->GetColour()[3]) / 255.0f; } else { clipDat[0] = clipDat[1] = clipDat[2] = clipDat[3] = 0.0f; clipCol[0] = clipCol[1] = clipCol[2] = 0.75f; clipCol[3] = 1.0f; } } bool OSPRaySphereGeometry::getExtends(megamol::core::Call &call) { CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); if (cd == NULL) return false; cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true if (!(*cd)(1)) return false; this->extendContainer.boundingBox = std::make_shared<megamol::core::BoundingBoxes>(cd->AccessBoundingBoxes()); this->extendContainer.timeFramesCount = cd->FrameCount(); this->extendContainer.isValid = true; return true; }<|endoftext|>
<commit_before>#include <cctype> #include <istream> #include <sstream> #include "BitFunnel/TermMatchNode.h" #include "QueryParser.h" namespace BitFunnel { QueryParser::QueryParser(std::istream& input, IAllocator& allocator) : m_input(input), m_allocator(allocator), m_currentPosition(0), m_haveChar(false) { } TermMatchNode const * QueryParser::Parse() { return ParseOr(); } TermMatchNode const * QueryParser::ParseOr() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); auto left = ParseAnd(); builder.AddChild(left); for (;;) { SkipWhite(); if (PeekChar() != '|') { break; } GetChar(); auto child = ParseAnd(); builder.AddChild(child); } return builder.Complete(); } TermMatchNode const * QueryParser::ParseAnd() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); // TODO. return builder.Complete(); } TermMatchNode const * QueryParser::ParseTerm() { std::string streamId = "body"; SkipWhite(); if (PeekChar() == '"') { // TODO: handle streamId. // return ParsePhrase(streamId); return ParsePhrase(); } else { std::string token = ParseToken(); if (PeekChar() == ':') { streamId = token; GetChar(); } if (PeekChar() == '"') { // TODO: add streamId. // return ParsePhrase(streamId); return ParsePhrase(); } else { // TODO: add streamId. // return ParseUnigram(streamId); return ParseUnigram(); } } } TermMatchNode const * QueryParser::ParseSimple() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); // TODO. return builder.Complete(); } TermMatchNode const * QueryParser::ParseUnigram() { // TODO: make sure we've consumed whitespace prior to calling this. std::string token = ParseToken(); TermMatchNode::Builder builder(TermMatchNode::UnigramMatch, m_allocator); // TODO: is position = 0 here ok? // TODO: won't this c_str go away when we go out of scope? // This should get fixed when we allocate with the arena allocator. TermMatchNode::Unigram term(token.c_str(), 0); builder.AddChild(&term); return builder.Complete(); } TermMatchNode const * QueryParser::ParsePhrase() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); // TODO. return builder.Complete(); } void QueryParser::SkipWhite() { while (isspace(PeekChar())) { GetChar(); } } void QueryParser::ExpectDelimeter(char c) { if (PeekChar() != c) { // TODO: REVIEW: Check lifetime of c_str() passed to exception constructor. std::stringstream message; message << "Expected '" << c << "'."; throw ParseError(message.str().c_str(), m_currentPosition); } else { GetChar(); } } char QueryParser::GetChar() { char result = PeekChar(); if (result == '\0') { throw ParseError("Attempting to read past NULL byte", m_currentPosition); } ++m_currentPosition; m_haveChar = false; return result; } char QueryParser::PeekChar() { if (!m_haveChar) { if (!m_input.eof()) { // TODO: when we handle UTF-8 correctly, everything will turn // into int. m_nextChar = static_cast<char>(m_input.get()); } else { m_nextChar = '\0'; } m_haveChar = true; } return m_nextChar; } char QueryParser::GetWithEscape() { char c = PeekChar(); char const * legalEscapes = "&|\\()\":"; if (c == '\\') { GetChar(); c = PeekChar(); if (strchr(legalEscapes, c) != nullptr) { return GetChar(); } else { throw ParseError("Bad escape char", c); } } else { return GetChar(); } } std::string ParseToken() { // TODO. return ""; } QueryParser::ParseError::ParseError(char const * message, size_t position) : std::runtime_error(message), m_position(position) { } std::ostream& operator<< (std::ostream &out, const QueryParser::ParseError &e) { out << std::string(e.m_position, ' ') << '^' << std::endl; out << "Parser error (position = " << e.m_position << "): "; out << e.what(); out << std::endl; return out; } } <commit_msg>WIP: GetToken.<commit_after>#include <cctype> #include <istream> #include <sstream> #include "BitFunnel/TermMatchNode.h" #include "QueryParser.h" namespace BitFunnel { QueryParser::QueryParser(std::istream& input, IAllocator& allocator) : m_input(input), m_allocator(allocator), m_currentPosition(0), m_haveChar(false) { } TermMatchNode const * QueryParser::Parse() { return ParseOr(); } TermMatchNode const * QueryParser::ParseOr() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); auto left = ParseAnd(); builder.AddChild(left); for (;;) { SkipWhite(); if (PeekChar() != '|') { break; } GetChar(); auto child = ParseAnd(); builder.AddChild(child); } return builder.Complete(); } TermMatchNode const * QueryParser::ParseAnd() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); // TODO. return builder.Complete(); } TermMatchNode const * QueryParser::ParseTerm() { std::string streamId = "body"; SkipWhite(); if (PeekChar() == '"') { // TODO: handle streamId. // return ParsePhrase(streamId); return ParsePhrase(); } else { std::string token = ParseToken(); if (PeekChar() == ':') { streamId = token; GetChar(); } if (PeekChar() == '"') { // TODO: add streamId. // return ParsePhrase(streamId); return ParsePhrase(); } else { // TODO: add streamId. // return ParseUnigram(streamId); return ParseUnigram(); } } } TermMatchNode const * QueryParser::ParseSimple() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); // TODO. return builder.Complete(); } TermMatchNode const * QueryParser::ParseUnigram() { // TODO: make sure we've consumed whitespace prior to calling this. std::string token = ParseToken(); TermMatchNode::Builder builder(TermMatchNode::UnigramMatch, m_allocator); // TODO: is position = 0 here ok? // TODO: won't this c_str go away when we go out of scope? // This should get fixed when we allocate with the arena allocator. TermMatchNode::Unigram term(token.c_str(), 0); builder.AddChild(&term); return builder.Complete(); } TermMatchNode const * QueryParser::ParsePhrase() { TermMatchNode::Builder builder(TermMatchNode::OrMatch, m_allocator); // TODO. return builder.Complete(); } void QueryParser::SkipWhite() { while (isspace(PeekChar())) { GetChar(); } } void QueryParser::ExpectDelimeter(char c) { if (PeekChar() != c) { // TODO: REVIEW: Check lifetime of c_str() passed to exception constructor. std::stringstream message; message << "Expected '" << c << "'."; throw ParseError(message.str().c_str(), m_currentPosition); } else { GetChar(); } } char QueryParser::GetChar() { char result = PeekChar(); if (result == '\0') { throw ParseError("Attempting to read past NULL byte", m_currentPosition); } ++m_currentPosition; m_haveChar = false; return result; } char QueryParser::PeekChar() { if (!m_haveChar) { if (!m_input.eof()) { // TODO: when we handle UTF-8 correctly, everything will turn // into int. m_nextChar = static_cast<char>(m_input.get()); } else { m_nextChar = '\0'; } m_haveChar = true; } return m_nextChar; } char QueryParser::GetWithEscape() { char c = PeekChar(); char const * legalEscapes = "&|\\()\":"; if (c == '\\') { GetChar(); c = PeekChar(); if (strchr(legalEscapes, c) != nullptr) { return GetChar(); } else { throw ParseError("Bad escape char", c); } } else { return GetChar(); } } std::string QueryParser::ParseToken() { // TODO: unify with legalEscapes. char const * specialChars = "&|\\()\":"; std::string token; char c = PeekChar(); if (isspace(c) || strchr(specialChars, c) != nullptr) { // TODO: should we throw here or just return the empty string? throw ParseError("Found space or special character at beginning of unigram.", m_currentPosition); } do { token.push_back(GetChar()); c = PeekChar(); } while (!isspace(c) && strchr(specialChars, c) == nullptr); return token; } QueryParser::ParseError::ParseError(char const * message, size_t position) : std::runtime_error(message), m_position(position) { } std::ostream& operator<< (std::ostream &out, const QueryParser::ParseError &e) { out << std::string(e.m_position, ' ') << '^' << std::endl; out << "Parser error (position = " << e.m_position << "): "; out << e.what(); out << std::endl; return out; } } <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Utility/Debug.h> #include <corradeCompatibility.h> #ifdef CORRADE_TARGET_NACL #include <Utility/NaClStreamBuffer.h> #endif #include "Context.h" #ifndef CORRADE_TARGET_NACL #include "Platform/WindowlessGlxApplication.h" #else #include "Platform/WindowlessNaClApplication.h" #endif namespace Magnum { class MagnumInfo: public Platform::WindowlessApplication { public: explicit MagnumInfo(const Arguments& arguments); int exec() override { return 0; } }; MagnumInfo::MagnumInfo(const Arguments& arguments): Platform::WindowlessApplication(arguments) { Context* c = Context::current(); /* Pass debug output as messages to JavaScript */ #ifdef CORRADE_TARGET_NACL Utility::NaClMessageStreamBuffer buffer(this); std::ostream out(&buffer); Debug::setOutput(&out); #endif Debug() << ""; Debug() << " +---------------------------------------------------------+"; Debug() << " | Information about Magnum engine and OpenGL capabilities |"; Debug() << " +---------------------------------------------------------+"; Debug() << ""; Debug() << "Used application: Platform::WindowlessGlxApplication"; Debug() << "Compilation flags:"; #ifdef CORRADE_GCC46_COMPATIBILITY Debug() << " CORRADE_GCC46_COMPATIBILITY"; #endif #ifdef CORRADE_GCC47_COMPATIBILITY Debug() << " CORRADE_GCC47_COMPATIBILITY"; #endif #ifdef CORRADE_BUILD_STATIC Debug() << " CORRADE_BUILD_STATIC"; #endif #ifdef CORRADE_TARGET_NACL Debug() << " CORRADE_TARGET_NACL"; #endif #ifdef CORRADE_TARGET_NACL_NEWLIB Debug() << " CORRADE_TARGET_NACL_NEWLIB"; #endif #ifdef CORRADE_TARGET_NACL_GLIBC Debug() << " CORRADE_TARGET_NACL_GLIBC"; #endif #ifdef CORRADE_TARGET_EMSCRIPTEN Debug() << " CORRADE_TARGET_EMSCRIPTEN"; #endif #ifdef MAGNUM_BUILD_STATIC Debug() << " MAGNUM_BUILD_STATIC"; #endif #ifdef MAGNUM_TARGET_GLES Debug() << " MAGNUM_TARGET_GLES"; #endif #ifdef MAGNUM_TARGET_GLES2 Debug() << " MAGNUM_TARGET_GLES2"; #endif #ifdef MAGNUM_TARGET_DESKTOP_GLES Debug() << " MAGNUM_TARGET_DESKTOP_GLES"; #endif Debug() << ""; Debug() << "Vendor:" << c->vendorString(); Debug() << "Renderer:" << c->rendererString(); Debug() << "OpenGL version:" << c->version() << '(' + c->versionString() + ')'; Debug() << "Supported GLSL versions:"; const std::vector<std::string> shadingLanguageVersions = c->shadingLanguageVersionStrings(); for(const auto& version: shadingLanguageVersions) Debug() << " " << version; Debug() << ""; /* Get first future (not supported) version */ std::vector<Version> versions{ #ifndef MAGNUM_TARGET_GLES Version::GL300, Version::GL310, Version::GL320, Version::GL330, Version::GL400, Version::GL410, Version::GL420, Version::GL430, Version::GL440, #else Version::GLES200, Version::GLES300, #endif Version::None }; std::size_t future = 0; while(versions[future] != Version::None && c->isVersionSupported(versions[future])) ++future; /* Display supported OpenGL extensions from unsupported versions */ for(std::size_t i = future; i != versions.size(); ++i) { if(versions[i] != Version::None) Debug() << versions[i] << "extension support:"; else Debug() << "Vendor extension support:"; for(const auto& extension: Extension::extensions(versions[i])) { std::string extensionName = extension.string(); Debug d; d << " " << extensionName << std::string(60-extensionName.size(), ' '); if(c->isExtensionSupported(extension)) d << "SUPPORTED"; else if(c->isVersionSupported(extension.requiredVersion())) d << " -"; else d << " ---"; } Debug() << ""; } } } MAGNUM_WINDOWLESSAPPLICATION_MAIN(Magnum::MagnumInfo) <commit_msg>Platform: ability to show extensions also for fully supported versions.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Utility/Arguments.h> #include <Utility/Debug.h> #include <corradeCompatibility.h> #ifdef CORRADE_TARGET_NACL #include <Utility/NaClStreamBuffer.h> #endif #include "Context.h" #ifndef CORRADE_TARGET_NACL #include "Platform/WindowlessGlxApplication.h" #else #include "Platform/WindowlessNaClApplication.h" #endif namespace Magnum { class MagnumInfo: public Platform::WindowlessApplication { public: explicit MagnumInfo(const Arguments& arguments); int exec() override { return 0; } }; MagnumInfo::MagnumInfo(const Arguments& arguments): Platform::WindowlessApplication(arguments, nullptr) { Utility::Arguments args; args.addBooleanOption("all-extensions") .setHelp("all-extensions", "show extensions also for fully supported versions") .setHelp("Displays information about Magnum engine and OpenGL capabilities.") .parse(arguments.argc, arguments.argv); /* Create context after parsing arguments, so the help can be displayed without creating context */ createContext({}); Context* c = Context::current(); /* Pass debug output as messages to JavaScript */ #ifdef CORRADE_TARGET_NACL Utility::NaClMessageStreamBuffer buffer(this); std::ostream out(&buffer); Debug::setOutput(&out); #endif Debug() << ""; Debug() << " +---------------------------------------------------------+"; Debug() << " | Information about Magnum engine and OpenGL capabilities |"; Debug() << " +---------------------------------------------------------+"; Debug() << ""; Debug() << "Used application: Platform::WindowlessGlxApplication"; Debug() << "Compilation flags:"; #ifdef CORRADE_GCC46_COMPATIBILITY Debug() << " CORRADE_GCC46_COMPATIBILITY"; #endif #ifdef CORRADE_GCC47_COMPATIBILITY Debug() << " CORRADE_GCC47_COMPATIBILITY"; #endif #ifdef CORRADE_BUILD_STATIC Debug() << " CORRADE_BUILD_STATIC"; #endif #ifdef CORRADE_TARGET_NACL Debug() << " CORRADE_TARGET_NACL"; #endif #ifdef CORRADE_TARGET_NACL_NEWLIB Debug() << " CORRADE_TARGET_NACL_NEWLIB"; #endif #ifdef CORRADE_TARGET_NACL_GLIBC Debug() << " CORRADE_TARGET_NACL_GLIBC"; #endif #ifdef CORRADE_TARGET_EMSCRIPTEN Debug() << " CORRADE_TARGET_EMSCRIPTEN"; #endif #ifdef MAGNUM_BUILD_STATIC Debug() << " MAGNUM_BUILD_STATIC"; #endif #ifdef MAGNUM_TARGET_GLES Debug() << " MAGNUM_TARGET_GLES"; #endif #ifdef MAGNUM_TARGET_GLES2 Debug() << " MAGNUM_TARGET_GLES2"; #endif #ifdef MAGNUM_TARGET_DESKTOP_GLES Debug() << " MAGNUM_TARGET_DESKTOP_GLES"; #endif Debug() << ""; Debug() << "Vendor:" << c->vendorString(); Debug() << "Renderer:" << c->rendererString(); Debug() << "OpenGL version:" << c->version() << '(' + c->versionString() + ')'; Debug() << "Supported GLSL versions:"; const std::vector<std::string> shadingLanguageVersions = c->shadingLanguageVersionStrings(); for(const auto& version: shadingLanguageVersions) Debug() << " " << version; Debug() << ""; /* Get first future (not supported) version */ std::vector<Version> versions{ #ifndef MAGNUM_TARGET_GLES Version::GL300, Version::GL310, Version::GL320, Version::GL330, Version::GL400, Version::GL410, Version::GL420, Version::GL430, Version::GL440, #else Version::GLES200, Version::GLES300, #endif Version::None }; std::size_t future = 0; if(!args.isSet("all-extensions")) while(versions[future] != Version::None && c->isVersionSupported(versions[future])) ++future; /* Display supported OpenGL extensions from unsupported versions */ for(std::size_t i = future; i != versions.size(); ++i) { if(versions[i] != Version::None) Debug() << versions[i] << "extension support:"; else Debug() << "Vendor extension support:"; for(const auto& extension: Extension::extensions(versions[i])) { std::string extensionName = extension.string(); Debug d; d << " " << extensionName << std::string(60-extensionName.size(), ' '); if(c->isExtensionSupported(extension)) d << "SUPPORTED"; else if(c->isVersionSupported(extension.requiredVersion())) d << " -"; else d << " ---"; } Debug() << ""; } } } MAGNUM_WINDOWLESSAPPLICATION_MAIN(Magnum::MagnumInfo) <|endoftext|>
<commit_before> #include "QstCommInt.h" /*****************************************************************************/ /* 普通显示 */ /*****************************************************************************/ /* ======================================= 文本数据显示 ======================================= */ CR_API void_t qst_txt_show ( __CR_IN__ void_t* parm, __CR_IN__ ansi_t cha ) { ansi_t show[2]; sQstComm* ctx = (sQstComm*)parm; CTextOper* opr = (CTextOper*)ctx->oper; /* 过滤无法显示的字符 */ if (cha != CR_AC('\n') && cha != CR_AC('\r') && !is_printA(cha)) show[0] = CR_AC(' '); else show[0] = cha; show[1] = NIL; opr->text(show); } /* ======================================= 16进制数据显示 ======================================= */ CR_API void_t qst_hex_show ( __CR_IN__ void_t* parm, __CR_IN__ ansi_t cha ) { ansi_t show[4]; sQstComm* ctx = (sQstComm*)parm; CTextOper* opr = (CTextOper*)ctx->oper; /* 转换成16进制数显示 */ sprintf(show, "%02X ", cha); opr->text(show); } /*****************************************************************************/ /* 色彩显示 */ /*****************************************************************************/ /* ANSI 转义处理上下文 */ static bool_t s_have; static bool_t s_buffer; static uint_t s_state; static uint_t s_at_idx; static bool_t s_type[6]; /* 高亮 + 下划线 + 上划线 + 中划线 + 反色 + 闪烁 */ static sint_t s_color[2]; /* 前景色 + 背景色 */ static ansi_t s_attr[33]; static iDATOT* s_html = NULL; /* ======================================= 创建 ANSI 上下文 ======================================= */ CR_API bool_t qst_csi_init (void_t) { s_state = 0; s_have = s_buffer = FALSE; s_color[0] = s_color[1] = -1; mem_zero(s_type, sizeof(s_type)); s_html = create_buff_out(512); if (s_html == NULL) return (FALSE); return (TRUE); } /* ======================================= 释放 ANSI 上下文 ======================================= */ CR_API void_t qst_csi_free (void_t) { CR_VCALL(s_html)->release(s_html); } /* ======================================= 清除 ANSI 上下文 ======================================= */ CR_API void_t qst_csi_clear (void_t) { s_state = 0; s_have = s_buffer = FALSE; s_color[0] = s_color[1] = -1; mem_zero(s_type, sizeof(s_type)); CR_VCALL(s_html)->reput(s_html, 0); } /* 颜色常数表 */ static const ansi_t* s_lo_color[] = { "#000000;", "#800000;", "#008000;", "#808000;", "#000080;", "#800080;", "#008080;", "#C0C0C0;", }; static const ansi_t* s_hi_color[] = { "#808080;", "#FF0000;", "#00FF00;", "#FFFF00;", "#0000FF;", "#FF00FF;", "#00FFFF;", "#FFFFFF;", }; /* --------------------------------------- 渲染 ANSI 字符串 --------------------------------------- */ static void_t qst_csi_render ( __CR_IN__ CTextOper* opr, __CR_IN__ const ansi_t* tail ) { ansi_t* str; ansi_t* send; ansi_t* span; const ansi_t* fg = ""; const ansi_t* bk = ""; const ansi_t* fc = ""; const ansi_t* bc = ""; const ansi_t* tx = "text-decoration:none;"; /* 颜色风格 */ if (s_color[0] > 0) { if (s_type[0]) fc = s_hi_color[s_color[0]]; else fc = s_lo_color[s_color[0]]; } if (s_color[1] > 0) { if (s_type[0]) bc = s_hi_color[s_color[1]]; else bc = s_lo_color[s_color[1]]; } /* 下划线|划线风格 */ if (s_type[1]) tx = "text-decoration:underline;"; else if (s_type[2]) tx = "text-decoration:overline;"; else if (s_type[3]) tx = "text-decoration:line-through;"; /* 反色风格 */ if (s_type[4]) { if (s_color[0] > 0) fg = "background-color:"; if (s_color[1] > 0) bk = "color:"; } else { if (s_color[0] > 0) fg = "color:"; if (s_color[1] > 0) bk = "background-color:"; } /* 闪烁风格 - 未实现 */ /*********************/ span = str_fmtA("<span style=\"%s%s%s%s%s\">", tx, fg, fc, bk, bc); if (span != NULL) { if (tail != NULL) { CR_VCALL(s_html)->write(s_html, "</span>", 7); CR_VCALL(s_html)->write(s_html, tail, str_sizeA(tail)); } else { CR_VCALL(s_html)->write(s_html, "</span>", 8); } str = (ansi_t*)(CR_VCALL(s_html)->flush(s_html)); send = str_fmtA("%s%s", span, str); if (send != NULL) { opr->html(send); mem_free(send); } CR_VCALL(s_html)->reput(s_html, 0); s_have = FALSE; mem_free(span); } } /* --------------------------------------- 处理 ANSI 转义属性 --------------------------------------- */ static void_t qst_csi_attrib ( __CR_IN__ CTextOper* opr ) { leng_t idx; uint_t at[8]; leng_t count; ansi_t** attrs; /* 发送上次结果 */ if (s_have) qst_csi_render(opr, NULL); /* 解析转义属性 */ attrs = str_splitA(s_attr, ';', &count); if (attrs == NULL) return; if (count > cntsof(at)) count = cntsof(at); for (idx = 0; idx < count; idx++) { at[idx] = str2intA(attrs[idx]); if (at[idx] == 0) { s_have = s_buffer = FALSE; s_color[0] = s_color[1] = -1; mem_zero(s_type, sizeof(s_type)); mem_free(attrs); return; } } mem_free(attrs); s_buffer = TRUE; for (idx = 0; idx < count; idx++) { switch (at[idx]) { default: /* 颜色 */ if (at[idx] >= 30 && at[idx] <= 37) s_color[0] = at[idx] - 30; else if (at[idx] >= 40 && at[idx] <= 47) s_color[1] = at[idx] - 40; break; case 1: /* 高亮 */ s_type[0] = TRUE; break; case 4: /* 下划线 */ s_type[1] = TRUE; break; case 24: s_type[1] = FALSE; break; case 53: /* 上划线 */ s_type[2] = TRUE; break; case 55: s_type[2] = FALSE; break; case 9: /* 中划线 */ s_type[3] = TRUE; break; case 29: s_type[3] = FALSE; break; case 7: /* 反色 */ s_type[4] = TRUE; break; case 27: s_type[4] = FALSE; break; case 5: /* 闪烁 */ s_type[5] = TRUE; break; case 25: s_type[5] = FALSE; break; } } } /* --------------------------------------- 输出 HTML 转义字符 --------------------------------------- */ static void_t qst_csi_output ( __CR_IN__ CTextOper* opr, __CR_IN__ ansi_t cha ) { if (cha == CR_AC('\"')) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&quot;", 6); } else if (cha == CR_AC('&')) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&amp;", 5); } else if (cha == CR_AC('\'')) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&apos;", 6); } else if (cha == CR_AC('<')) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&lt;", 4); } else if (cha == CR_AC('>')) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&gt;", 4); } else if (cha == CR_AC('\r') || cha == CR_AC('\n')) { qst_csi_render(opr, "<br>"); } else { s_have = TRUE; CR_VCALL(s_html)->putb_no(s_html, cha); } } /* ======================================= ANSI 转义文本显示 ======================================= */ CR_API void_t qst_csi_show ( __CR_IN__ void_t* parm, __CR_IN__ ansi_t cha ) { ansi_t show[4]; sQstComm* ctx = (sQstComm*)parm; CTextOper* opr = (CTextOper*)ctx->oper; switch (s_state) { case 0: /* 查找 ESC 阶段 */ if (cha != 0x1B) { if (cha != CR_AC('\n') && cha != CR_AC('\r') && !is_printA(cha)) show[0] = CR_AC(' '); else show[0] = cha; show[1] = NIL; if (s_buffer) qst_csi_output(opr, show[0]); else opr->text(show); } else { s_state += 1; } break; case 1: /* 查找 '[' 阶段 */ if (cha != CR_AC('[')) { show[0] = CR_AC(' '); if (cha != CR_AC('\n') && cha != CR_AC('\r') && !is_printA(cha)) show[1] = CR_AC(' '); else show[1] = cha; show[2] = NIL; if (s_buffer) { qst_csi_output(opr, show[0]); qst_csi_output(opr, show[1]); } else { opr->text(show); } s_state = 0; } else { s_state += 1; s_at_idx = 0; } break; default: /* case 2: */ /* 查找 'm' 阶段 */ if (cha == CR_AC('m') || s_at_idx >= sizeof(s_attr) - 1) { s_attr[s_at_idx] = NIL; qst_csi_attrib(opr); s_state = 0; } else { s_attr[s_at_idx++] = cha; } break; } } <commit_msg>QstComm: 修正 ANSI 颜色显示不对的问题<commit_after> #include "QstCommInt.h" /*****************************************************************************/ /* 普通显示 */ /*****************************************************************************/ /* ======================================= 文本数据显示 ======================================= */ CR_API void_t qst_txt_show ( __CR_IN__ void_t* parm, __CR_IN__ ansi_t cha ) { ansi_t show[2]; sQstComm* ctx = (sQstComm*)parm; CTextOper* opr = (CTextOper*)ctx->oper; /* 过滤无法显示的字符 */ if (cha != CR_AC('\n') && cha != CR_AC('\r') && !is_printA(cha)) show[0] = CR_AC(' '); else show[0] = cha; show[1] = NIL; opr->text(show); } /* ======================================= 16进制数据显示 ======================================= */ CR_API void_t qst_hex_show ( __CR_IN__ void_t* parm, __CR_IN__ ansi_t cha ) { ansi_t show[4]; sQstComm* ctx = (sQstComm*)parm; CTextOper* opr = (CTextOper*)ctx->oper; /* 转换成16进制数显示 */ sprintf(show, "%02X ", cha); opr->text(show); } /*****************************************************************************/ /* 色彩显示 */ /*****************************************************************************/ /* ANSI 转义处理上下文 */ static bool_t s_have; static bool_t s_buffer; static uint_t s_state; static uint_t s_at_idx; static bool_t s_type[6]; /* 高亮 + 下划线 + 上划线 + 中划线 + 反色 + 闪烁 */ static sint_t s_color[2]; /* 前景色 + 背景色 */ static ansi_t s_attr[33]; static iDATOT* s_html = NULL; /* ======================================= 创建 ANSI 上下文 ======================================= */ CR_API bool_t qst_csi_init (void_t) { s_state = 0; s_have = s_buffer = FALSE; s_color[0] = s_color[1] = -1; mem_zero(s_type, sizeof(s_type)); s_html = create_buff_out(512); if (s_html == NULL) return (FALSE); return (TRUE); } /* ======================================= 释放 ANSI 上下文 ======================================= */ CR_API void_t qst_csi_free (void_t) { CR_VCALL(s_html)->release(s_html); } /* ======================================= 清除 ANSI 上下文 ======================================= */ CR_API void_t qst_csi_clear (void_t) { s_state = 0; s_have = s_buffer = FALSE; s_color[0] = s_color[1] = -1; mem_zero(s_type, sizeof(s_type)); CR_VCALL(s_html)->reput(s_html, 0); } /* 颜色常数表 */ static const ansi_t* s_lo_color[] = { "#000000;", "#800000;", "#008000;", "#808000;", "#000080;", "#800080;", "#008080;", "#C0C0C0;", }; static const ansi_t* s_hi_color[] = { "#808080;", "#FF0000;", "#00FF00;", "#FFFF00;", "#0000FF;", "#FF00FF;", "#00FFFF;", "#FFFFFF;", }; /* --------------------------------------- 渲染 ANSI 字符串 --------------------------------------- */ static void_t qst_csi_render ( __CR_IN__ const sQstComm* parm, __CR_IN__ const ansi_t* tail ) { ansi_t* str; ansi_t* send; ansi_t* span; const ansi_t* fg = "color:"; const ansi_t* bk = "background-color:"; const ansi_t* fc = parm->cfgs.fg; const ansi_t* bc = parm->cfgs.bg; const ansi_t* tx = "text-decoration:none;"; /* 颜色风格 */ if (s_color[0] > 0) { if (s_type[0]) fc = s_hi_color[s_color[0]]; else fc = s_lo_color[s_color[0]]; } if (s_color[1] > 0) { if (s_type[0]) bc = s_hi_color[s_color[1]]; else bc = s_lo_color[s_color[1]]; } /* 下划线|划线风格 */ if (s_type[1]) tx = "text-decoration:underline;"; else if (s_type[2]) tx = "text-decoration:overline;"; else if (s_type[3]) tx = "text-decoration:line-through;"; /* 反色风格 */ if (s_type[4]) { fg = "background-color:"; bk = "color:"; } /* 闪烁风格 - 未实现 */ /*********************/ span = str_fmtA("<span style=\"%s%s%s%s%s\">", tx, fg, fc, bk, bc); if (span != NULL) { if (tail != NULL) { CR_VCALL(s_html)->write(s_html, "</span>", 7); CR_VCALL(s_html)->write(s_html, tail, str_sizeA(tail)); } else { CR_VCALL(s_html)->write(s_html, "</span>", 8); } str = (ansi_t*)(CR_VCALL(s_html)->flush(s_html)); send = str_fmtA("%s%s", span, str); if (send != NULL) { ((CTextOper*)(parm->oper))->html(send); mem_free(send); } CR_VCALL(s_html)->reput(s_html, 0); s_have = FALSE; mem_free(span); } } /* --------------------------------------- 处理 ANSI 转义属性 --------------------------------------- */ static void_t qst_csi_attrib ( __CR_IN__ const sQstComm* parm ) { leng_t idx; uint_t at[8]; leng_t count; ansi_t** attrs; /* 发送上次结果 */ if (s_buffer && s_have) qst_csi_render(parm, NULL); /* 解析转义属性 */ attrs = str_splitA(s_attr, ';', &count); if (attrs == NULL) return; if (count > cntsof(at)) count = cntsof(at); for (idx = 0; idx < count; idx++) { at[idx] = str2intA(attrs[idx]); if (at[idx] == 0) { s_have = s_buffer = FALSE; s_color[0] = s_color[1] = -1; mem_zero(s_type, sizeof(s_type)); mem_free(attrs); return; } } mem_free(attrs); s_buffer = TRUE; for (idx = 0; idx < count; idx++) { switch (at[idx]) { default: /* 颜色 */ if (at[idx] >= 30 && at[idx] <= 37) s_color[0] = at[idx] - 30; else if (at[idx] >= 40 && at[idx] <= 47) s_color[1] = at[idx] - 40; break; case 1: /* 高亮 */ s_type[0] = TRUE; break; case 4: /* 下划线 */ s_type[1] = TRUE; break; case 24: s_type[1] = FALSE; break; case 53: /* 上划线 */ s_type[2] = TRUE; break; case 55: s_type[2] = FALSE; break; case 9: /* 中划线 */ s_type[3] = TRUE; break; case 29: s_type[3] = FALSE; break; case 7: /* 反色 */ s_type[4] = TRUE; break; case 27: s_type[4] = FALSE; break; case 5: /* 闪烁 */ s_type[5] = TRUE; break; case 25: s_type[5] = FALSE; break; } } } /* --------------------------------------- 输出 HTML 转义字符 --------------------------------------- */ static void_t qst_csi_output ( __CR_IN__ const sQstComm* parm, __CR_IN__ ansi_t cha ) { ansi_t show[2]; if (cha == CR_AC('\"')) { if (s_buffer) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&quot;", 6); } else { ((CTextOper*)(parm->oper))->html("&quot;"); } } else if (cha == CR_AC('&')) { if (s_buffer) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&amp;", 5); } else { ((CTextOper*)(parm->oper))->html("&amp;"); } } else if (cha == CR_AC('\'')) { if (s_buffer) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&apos;", 6); } else { ((CTextOper*)(parm->oper))->html("&apos;"); } } else if (cha == CR_AC('<')) { if (s_buffer) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&lt;", 4); } else { ((CTextOper*)(parm->oper))->html("&lt;"); } } else if (cha == CR_AC('>')) { if (s_buffer) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&gt;", 4); } else { ((CTextOper*)(parm->oper))->html("&gt;"); } } else if (cha == CR_AC(' ')) { if (s_buffer) { s_have = TRUE; CR_VCALL(s_html)->write(s_html, "&nbsp;", 6); } else { ((CTextOper*)(parm->oper))->html("&nbsp;"); } } else if (cha == CR_AC('\r') || cha == CR_AC('\n')) { if (s_buffer) { qst_csi_render(parm, "<br>"); } else { ((CTextOper*)(parm->oper))->html("<br>"); } } else { if (s_buffer) { s_have = TRUE; CR_VCALL(s_html)->putb_no(s_html, cha); } else { show[0] = cha; show[1] = NIL; ((CTextOper*)(parm->oper))->html(show); } } } /* ======================================= ANSI 转义文本显示 ======================================= */ CR_API void_t qst_csi_show ( __CR_IN__ void_t* parm, __CR_IN__ ansi_t cha ) { ansi_t show[2]; sQstComm* ctx = (sQstComm*)parm; switch (s_state) { case 0: /* 查找 ESC 阶段 */ if (cha != 0x1B) { if (cha != CR_AC('\n') && cha != CR_AC('\r') && !is_printA(cha)) show[0] = CR_AC(' '); else show[0] = cha; qst_csi_output(ctx, show[0]); } else { s_state += 1; } break; case 1: /* 查找 '[' 阶段 */ if (cha != CR_AC('[')) { show[0] = CR_AC(' '); if (cha != CR_AC('\n') && cha != CR_AC('\r') && !is_printA(cha)) show[1] = CR_AC(' '); else show[1] = cha; qst_csi_output(ctx, show[0]); qst_csi_output(ctx, show[1]); s_state = 0; } else { s_state += 1; s_at_idx = 0; } break; default: /* case 2: */ /* 查找 'm' 阶段 */ if (cha == CR_AC('m') || s_at_idx >= sizeof(s_attr) - 1) { s_attr[s_at_idx] = NIL; qst_csi_attrib(ctx); s_state = 0; } else { s_attr[s_at_idx++] = cha; } break; } } <|endoftext|>
<commit_before>#include <QtWidgets> #include "../event.h" #include "../osd.h" #include "../error.h" #include "../pc6001v.h" #include "../typedef.h" #include "../console.h" #include "../error.h" #include "../osd.h" #include "renderview.h" #include "qtp6vxapplication.h" /////////////////////////////////////////////////////////// // フォントファイルチェック(無ければ作成する) /////////////////////////////////////////////////////////// bool CheckFont( void ) { char FontFile[PATH_MAX]; bool ret = true; sprintf( FontFile, "%s%s/%s", OSD_GetConfigPath(), FONT_DIR, FONTH_FILE ); ret |= ( !OSD_FileExist( FontFile ) && !OSD_CreateFont( FontFile, NULL, FSIZE ) ); sprintf( FontFile, "%s%s/%s", OSD_GetConfigPath(), FONT_DIR, FONTZ_FILE ); ret |= ( !OSD_FileExist( FontFile ) && !OSD_CreateFont( NULL, FontFile, FSIZE ) ); return ret; } /////////////////////////////////////////////////////////// // ROMファイル存在チェック&機種変更 /////////////////////////////////////////////////////////// bool SerchRom( CFG6 *cfg ) { char RomSerch[PATH_MAX]; int IniModel = cfg->GetModel(); sprintf( RomSerch, "%s*.%2d", cfg->GetRomPath(), IniModel ); if( OSD_FileExist( RomSerch ) ){ Error::SetError( Error::NoError ); return true; } int models[] = { 60, 62, 66 }; for( int i=0; i < COUNTOF(models); i++ ){ sprintf( RomSerch, "%s*.%2d", cfg->GetRomPath(), models[i] ); if( OSD_FileExist( RomSerch ) ){ cfg->SetModel( models[i] ); cfg->Write(); Error::SetError( Error::RomChange ); return true; } } Error::SetError( Error::NoRom ); return false; } QtP6VXApplication::QtP6VXApplication(int &argc, char **argv) : QtSingleApplication(argc, argv) , P6Core(NULL) , Restart(EL6::Quit) , Adaptor(new EmulationAdaptor()) { //HWINDOWという型名をシグナルの引数として使えるようにする qRegisterMetaType<HWINDOW>("HWINDOW"); // エミュレーションコア部分用スレッドを生成 QThread* emulationThread = new QThread(this); emulationThread->start(); Adaptor->moveToThread(emulationThread); //ウィンドウを閉じても終了しない。 //終了はEL6::Quitが返ってきた時に行う。 setQuitOnLastWindowClosed (false); connect(this, SIGNAL(initialized()), this, SLOT(executeEmulation())); connect(this, SIGNAL(vmPrepared()), Adaptor, SLOT(doEventLoop())); connect(this, SIGNAL(vmRestart()), this, SLOT(executeEmulation())); connect(Adaptor, SIGNAL(finished()), this, SLOT(postExecuteEmulation())); } QtP6VXApplication::~QtP6VXApplication() { Adaptor->thread()->exit(); Adaptor->deleteLater(); } void QtP6VXApplication::startup() { // 二重起動禁止 if( isRunning() ) { exit(); return; } // 設定ファイルパスを作成 if(!OSD_CreateConfigPath()){ exit(); return; } // OSD関連初期化 if( !OSD_Init() ){ Error::SetError( Error::InitFailed ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); OSD_Quit(); // 終了処理 exit(); return; } // フォントファイルチェック if( !CheckFont() ){ Error::SetError( Error::FontCreateFailed ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); } // コンソール用フォント読込み char FontZ[PATH_MAX], FontH[PATH_MAX]; sprintf( FontZ, ":/res/%s/%s", FONT_DIR, FONTZ_FILE ); sprintf( FontH, ":/res/%s/%s", FONT_DIR, FONTH_FILE ); if( !JFont::OpenFont( FontZ, FontH ) ){ Error::SetError( Error::FontLoadFailed ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); Error::SetError( Error::NoError ); } // INIファイル読込み if( !Cfg.Init() ){ switch( Error::GetError() ){ case Error::IniDefault: OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); break; default: OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); OSD_Quit(); // 終了処理 exit(); return; } } emit initialized(); } void QtP6VXApplication::createWindow(HWINDOW Wh, int bpp, bool fsflag) { RenderView* view = static_cast<RenderView*>(Wh); Q_ASSERT(view); QGraphicsScene* scene = view->scene(); OSD_ClearWindow(Wh); if(fsflag){ view->showFullScreen(); } else { view->showNormal(); //qDebug("scene:%dx%d view:%dx%d", scene->width(), scene->height(), view->width(), view->height()); //Windowsではウィンドウ表示が完了しきらないうちにresize()を呼ぶと //タイトルバーが画面からはみ出るので、適当に左上にマージンを取る。 view->setGeometry(100, 100, scene->width(), scene->height()); } view->fitContent(); } void QtP6VXApplication::layoutBitmap(HWINDOW Wh, int x, int y, double aspect, QImage image) { //QtではSceneRectの幅を返す QGraphicsView* view = static_cast<QGraphicsView*>(Wh); Q_ASSERT(view); QGraphicsScene* scene = view->scene(); // 指定座標に生成済みのQPixmapItemが存在するかチェック // (同一座標にビットマップが重なることはないという前提) QGraphicsItem* item = NULL; QGraphicsPixmapItem* pItem = NULL; foreach(item, scene->items()){ if(item->scenePos() == QPointF(x, y)){ pItem = dynamic_cast<QGraphicsPixmapItem*>(item); break; } } if(pItem == NULL){ // 既存のQPixmapItemが存在しない場合は生成 pItem = new QGraphicsPixmapItem(NULL); scene->addItem(pItem); pItem->setTransformationMode(Qt::SmoothTransformation); QTransform trans; trans.scale(1, aspect); trans.translate(x, y); pItem->setTransform(trans); } pItem->setPixmap(QPixmap::fromImage(image)); } void QtP6VXApplication::clearLayout(HWINDOW Wh) { QGraphicsView* view = static_cast<QGraphicsView*>(Wh); Q_ASSERT(view); Q_ASSERT(view->scene()); QGraphicsScene* scene = view->scene(); scene->clear(); // フルスクリーンでTILTモードが有効になっている場合、背景を描く if(view->isFullScreen() && property("TILTEnabled").toBool()){ QGraphicsPixmapItem* background = new QGraphicsPixmapItem(QPixmap::fromImage(QImage(":/res/background.png"))); background->setTransformationMode(Qt::SmoothTransformation); QTransform trans; //画像の拡大倍率 qreal ratio = qMax(scene->width() / background->sceneBoundingRect().width(), scene->height() / background->sceneBoundingRect().height()); qreal scaleRatio = ratio * 1.15; int scaledWidth = background->sceneBoundingRect().width() * scaleRatio; int scaledHeight = background->sceneBoundingRect().height() * scaleRatio; //画像のオフセットを計算(枠の分だけ左上に移動) trans.translate(-(scaledWidth - scene->width()) / 2, -(scaledHeight - scene->height()) / 2); trans.scale(ratio * 1.15, ratio * 1.15); background->setTransform(trans); scene->addItem(background); } } void QtP6VXApplication::showPopupMenu(int x, int y) { //メニュー表示中に右クリックすると二重にメニューが表示されてしまうため、その対処 static QMutex mutex; if(mutex.tryLock()){ P6Core->Stop(); P6Core->ShowPopupImpl(x, y); P6Core->Start(); mutex.unlock(); } } //仮想マシンを開始させる void QtP6VXApplication::executeEmulation() { // ROMファイル存在チェック&機種変更 if( SerchRom( &Cfg ) ){ if( Error::GetError() != Error::NoError ){ OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDM_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); } }else{ if(OSD_Message( QString("ROMファイルが見つかりません。\n" "ROMフォルダ(%1)にROMファイルをコピーするか、" "別のROMフォルダを指定してください。\n" "別のROMフォルダを指定しますか?").arg(Cfg.GetRomPath()).toUtf8().constData(), MSERR_ERROR, OSDM_YESNO | OSDM_ICONERROR ) == OSDR_YES){ //ROMフォルダ再設定 char folder[PATH_MAX]; strncpy(folder, Cfg.GetRomPath(), PATH_MAX); Delimiter(folder); OSD_FolderDiaog(NULL, folder); UnDelimiter(folder); if(strlen(folder) > 0){ Cfg.SetRomPath(folder); Cfg.Write(); Restart = EL6::Restart; } else { exit(); return; } } else { exit(); return; } emit vmRestart(); return; } // 機種別P6オブジェクト確保 P6Core = new QtEL6; if( !P6Core ){ exit(); return; } // VM初期化 if( !P6Core->Init( &Cfg ) ){ if(Error::GetError() == Error::RomCrcNG){ // CRCが合わない場合 int ret = OSD_Message( "ROMイメージのCRCが不正です。\n" "CRCが一致しないROMを使用すると、予期せぬ不具合を引き起こす可能性があります。\n" "それでも起動しますか?", MSERR_ERROR, OSDM_YESNO | OSDM_ICONWARNING ); if(ret == OSDR_YES) { Cfg.SetCheckCRC(false); Cfg.Write(); Restart = EL6::Restart; } } else { OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); exit(); } } switch( Restart ){ case EL6::Dokoload: // どこでもLOAD? P6Core->DokoDemoLoad( Cfg.GetDokoFile() ); break; case EL6::Replay: // リプレイ再生? { char temp[PATH_MAX]; strncpy( temp, Cfg.GetDokoFile(), PATH_MAX ); P6Core->DokoDemoLoad( temp ); P6Core->REPLAY::StartReplay( temp ); } break; default: break; } // 以降、ウィンドウが閉じたらアプリを終了する connect(this, SIGNAL(lastWindowClosed()), this, SLOT(terminateEmulation())); // VM実行 Adaptor->setEmulationObj(P6Core); emit vmPrepared(); P6Core->Start(); } //仮想マシン終了後の処理 void QtP6VXApplication::postExecuteEmulation() { Restart = Adaptor->getReturnCode(); Adaptor->setEmulationObj(NULL); P6Core->Stop(); P6Core->deleteLater(); // P6オブジェクトを開放 P6Core = NULL; // 再起動ならばINIファイル再読込み if( Restart == EL6::Restart ){ if( !Cfg.Init() ){ Error::SetError( Error::IniDefault ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); } } if( Restart == EL6::Quit ){ // 終了処理 OSD_Quit(); exit(); return; } else { emit vmRestart(); } } void QtP6VXApplication::terminateEmulation() { OSD_PushEvent( EV_QUIT ); } bool QtP6VXApplication::notify ( QObject * receiver, QEvent * event ) { Event ev; ev.type = EV_NOEVENT; switch(event->type()){ case QEvent::KeyPress: case QEvent::KeyRelease: { QKeyEvent* ke = dynamic_cast<QKeyEvent*>(event); Q_ASSERT(ke); int keyCode = ke->key(); // 「ろ」が入力できない対策 quint32 nativeKey = ke->nativeScanCode(); //X11の場合 if (QGuiApplication::platformName() == QLatin1String("xcb")){ if(keyCode == Qt::Key_Backslash){ keyCode = nativeKey == 97 ? Qt::Key_Underscore : Qt::Key_Backslash; } } //Windowsの場合 else if (QGuiApplication::platformName() == QLatin1String("windows")){ if(keyCode == Qt::Key_Backslash){ keyCode = nativeKey == 115 ? Qt::Key_Underscore : Qt::Key_Backslash; } } ev.type = event->type() == QEvent::KeyPress ? EV_KEYDOWN : EV_KEYUP; ev.key.state = event->type() == QEvent::KeyPress ? true : false; ev.key.sym = OSD_ConvertKeyCode( keyCode ); ev.key.mod = (PCKEYmod)( ( ke->modifiers() & Qt::ShiftModifier ? KVM_SHIFT : KVM_NONE ) | ( ke->modifiers() & Qt::ControlModifier ? KVM_CTRL : KVM_NONE ) | ( ke->modifiers() & Qt::AltModifier ? KVM_ALT : KVM_NONE ) | ( ke->modifiers() & Qt::MetaModifier ? KVM_META : KVM_NONE ) | ( ke->modifiers() & Qt::KeypadModifier ? KVM_NUM : KVM_NONE ) //#PENDING CAPSLOCKは検出できない? //| ( ke->modifiers() & Qt::caps ? KVM_NUM : KVM_NONE ) ); ev.key.unicode = ke->text().utf16()[0]; OSD_PushEvent(ev); break; } case QEvent::ContextMenu: { ev.type = EV_CONTEXTMENU; OSD_PushEvent(ev.type); break; } default:; } if(ev.type == EV_NOEVENT){ return QtSingleApplication::notify(receiver, event); } else { return true; } } <commit_msg>TILTモードの背景配置の関係で、OSD_ClearWindowを呼ぶタイミングをずらした<commit_after>#include <QtWidgets> #include "../event.h" #include "../osd.h" #include "../error.h" #include "../pc6001v.h" #include "../typedef.h" #include "../console.h" #include "../error.h" #include "../osd.h" #include "renderview.h" #include "qtp6vxapplication.h" /////////////////////////////////////////////////////////// // フォントファイルチェック(無ければ作成する) /////////////////////////////////////////////////////////// bool CheckFont( void ) { char FontFile[PATH_MAX]; bool ret = true; sprintf( FontFile, "%s%s/%s", OSD_GetConfigPath(), FONT_DIR, FONTH_FILE ); ret |= ( !OSD_FileExist( FontFile ) && !OSD_CreateFont( FontFile, NULL, FSIZE ) ); sprintf( FontFile, "%s%s/%s", OSD_GetConfigPath(), FONT_DIR, FONTZ_FILE ); ret |= ( !OSD_FileExist( FontFile ) && !OSD_CreateFont( NULL, FontFile, FSIZE ) ); return ret; } /////////////////////////////////////////////////////////// // ROMファイル存在チェック&機種変更 /////////////////////////////////////////////////////////// bool SerchRom( CFG6 *cfg ) { char RomSerch[PATH_MAX]; int IniModel = cfg->GetModel(); sprintf( RomSerch, "%s*.%2d", cfg->GetRomPath(), IniModel ); if( OSD_FileExist( RomSerch ) ){ Error::SetError( Error::NoError ); return true; } int models[] = { 60, 62, 66 }; for( int i=0; i < COUNTOF(models); i++ ){ sprintf( RomSerch, "%s*.%2d", cfg->GetRomPath(), models[i] ); if( OSD_FileExist( RomSerch ) ){ cfg->SetModel( models[i] ); cfg->Write(); Error::SetError( Error::RomChange ); return true; } } Error::SetError( Error::NoRom ); return false; } QtP6VXApplication::QtP6VXApplication(int &argc, char **argv) : QtSingleApplication(argc, argv) , P6Core(NULL) , Restart(EL6::Quit) , Adaptor(new EmulationAdaptor()) { //HWINDOWという型名をシグナルの引数として使えるようにする qRegisterMetaType<HWINDOW>("HWINDOW"); // エミュレーションコア部分用スレッドを生成 QThread* emulationThread = new QThread(this); emulationThread->start(); Adaptor->moveToThread(emulationThread); //ウィンドウを閉じても終了しない。 //終了はEL6::Quitが返ってきた時に行う。 setQuitOnLastWindowClosed (false); connect(this, SIGNAL(initialized()), this, SLOT(executeEmulation())); connect(this, SIGNAL(vmPrepared()), Adaptor, SLOT(doEventLoop())); connect(this, SIGNAL(vmRestart()), this, SLOT(executeEmulation())); connect(Adaptor, SIGNAL(finished()), this, SLOT(postExecuteEmulation())); } QtP6VXApplication::~QtP6VXApplication() { Adaptor->thread()->exit(); Adaptor->deleteLater(); } void QtP6VXApplication::startup() { // 二重起動禁止 if( isRunning() ) { exit(); return; } // 設定ファイルパスを作成 if(!OSD_CreateConfigPath()){ exit(); return; } // OSD関連初期化 if( !OSD_Init() ){ Error::SetError( Error::InitFailed ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); OSD_Quit(); // 終了処理 exit(); return; } // フォントファイルチェック if( !CheckFont() ){ Error::SetError( Error::FontCreateFailed ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); } // コンソール用フォント読込み char FontZ[PATH_MAX], FontH[PATH_MAX]; sprintf( FontZ, ":/res/%s/%s", FONT_DIR, FONTZ_FILE ); sprintf( FontH, ":/res/%s/%s", FONT_DIR, FONTH_FILE ); if( !JFont::OpenFont( FontZ, FontH ) ){ Error::SetError( Error::FontLoadFailed ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); Error::SetError( Error::NoError ); } // INIファイル読込み if( !Cfg.Init() ){ switch( Error::GetError() ){ case Error::IniDefault: OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); break; default: OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); OSD_Quit(); // 終了処理 exit(); return; } } emit initialized(); } void QtP6VXApplication::createWindow(HWINDOW Wh, int bpp, bool fsflag) { RenderView* view = static_cast<RenderView*>(Wh); Q_ASSERT(view); QGraphicsScene* scene = view->scene(); if(fsflag){ view->showFullScreen(); } else { view->showNormal(); //qDebug("scene:%dx%d view:%dx%d", scene->width(), scene->height(), view->width(), view->height()); //Windowsではウィンドウ表示が完了しきらないうちにresize()を呼ぶと //タイトルバーが画面からはみ出るので、適当に左上にマージンを取る。 view->setGeometry(100, 100, scene->width(), scene->height()); } view->fitContent(); OSD_ClearWindow(Wh); } void QtP6VXApplication::layoutBitmap(HWINDOW Wh, int x, int y, double aspect, QImage image) { //QtではSceneRectの幅を返す QGraphicsView* view = static_cast<QGraphicsView*>(Wh); Q_ASSERT(view); QGraphicsScene* scene = view->scene(); // 指定座標に生成済みのQPixmapItemが存在するかチェック // (同一座標にビットマップが重なることはないという前提) QGraphicsItem* item = NULL; QGraphicsPixmapItem* pItem = NULL; foreach(item, scene->items()){ if(item->scenePos() == QPointF(x, y)){ pItem = dynamic_cast<QGraphicsPixmapItem*>(item); break; } } if(pItem == NULL){ // 既存のQPixmapItemが存在しない場合は生成 pItem = new QGraphicsPixmapItem(NULL); scene->addItem(pItem); pItem->setTransformationMode(Qt::SmoothTransformation); QTransform trans; trans.scale(1, aspect); trans.translate(x, y); pItem->setTransform(trans); } pItem->setPixmap(QPixmap::fromImage(image)); } void QtP6VXApplication::clearLayout(HWINDOW Wh) { QGraphicsView* view = static_cast<QGraphicsView*>(Wh); Q_ASSERT(view); Q_ASSERT(view->scene()); QGraphicsScene* scene = view->scene(); scene->clear(); // フルスクリーンでTILTモードが有効になっている場合、背景を描く if(view->isFullScreen() && property("TILTEnabled").toBool()){ QGraphicsPixmapItem* background = new QGraphicsPixmapItem(QPixmap::fromImage(QImage(":/res/background.png"))); background->setTransformationMode(Qt::SmoothTransformation); QTransform trans; //画像の拡大倍率 qreal ratio = qMax(scene->width() / background->sceneBoundingRect().width(), scene->height() / background->sceneBoundingRect().height()); qreal scaleRatio = ratio * 1.15; int scaledWidth = background->sceneBoundingRect().width() * scaleRatio; int scaledHeight = background->sceneBoundingRect().height() * scaleRatio; //画像のオフセットを計算(枠の分だけ左上に移動) trans.translate(-(scaledWidth - scene->width()) / 2, -(scaledHeight - scene->height()) / 2); trans.scale(ratio * 1.15, ratio * 1.15); background->setTransform(trans); scene->addItem(background); } } void QtP6VXApplication::showPopupMenu(int x, int y) { //メニュー表示中に右クリックすると二重にメニューが表示されてしまうため、その対処 static QMutex mutex; if(mutex.tryLock()){ P6Core->Stop(); P6Core->ShowPopupImpl(x, y); P6Core->Start(); mutex.unlock(); } } //仮想マシンを開始させる void QtP6VXApplication::executeEmulation() { // ROMファイル存在チェック&機種変更 if( SerchRom( &Cfg ) ){ if( Error::GetError() != Error::NoError ){ OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDM_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); } }else{ if(OSD_Message( QString("ROMファイルが見つかりません。\n" "ROMフォルダ(%1)にROMファイルをコピーするか、" "別のROMフォルダを指定してください。\n" "別のROMフォルダを指定しますか?").arg(Cfg.GetRomPath()).toUtf8().constData(), MSERR_ERROR, OSDM_YESNO | OSDM_ICONERROR ) == OSDR_YES){ //ROMフォルダ再設定 char folder[PATH_MAX]; strncpy(folder, Cfg.GetRomPath(), PATH_MAX); Delimiter(folder); OSD_FolderDiaog(NULL, folder); UnDelimiter(folder); if(strlen(folder) > 0){ Cfg.SetRomPath(folder); Cfg.Write(); Restart = EL6::Restart; } else { exit(); return; } } else { exit(); return; } emit vmRestart(); return; } // 機種別P6オブジェクト確保 P6Core = new QtEL6; if( !P6Core ){ exit(); return; } // VM初期化 if( !P6Core->Init( &Cfg ) ){ if(Error::GetError() == Error::RomCrcNG){ // CRCが合わない場合 int ret = OSD_Message( "ROMイメージのCRCが不正です。\n" "CRCが一致しないROMを使用すると、予期せぬ不具合を引き起こす可能性があります。\n" "それでも起動しますか?", MSERR_ERROR, OSDM_YESNO | OSDM_ICONWARNING ); if(ret == OSDR_YES) { Cfg.SetCheckCRC(false); Cfg.Write(); Restart = EL6::Restart; } } else { OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONERROR ); exit(); } } switch( Restart ){ case EL6::Dokoload: // どこでもLOAD? P6Core->DokoDemoLoad( Cfg.GetDokoFile() ); break; case EL6::Replay: // リプレイ再生? { char temp[PATH_MAX]; strncpy( temp, Cfg.GetDokoFile(), PATH_MAX ); P6Core->DokoDemoLoad( temp ); P6Core->REPLAY::StartReplay( temp ); } break; default: break; } // 以降、ウィンドウが閉じたらアプリを終了する connect(this, SIGNAL(lastWindowClosed()), this, SLOT(terminateEmulation())); // VM実行 Adaptor->setEmulationObj(P6Core); emit vmPrepared(); P6Core->Start(); } //仮想マシン終了後の処理 void QtP6VXApplication::postExecuteEmulation() { Restart = Adaptor->getReturnCode(); Adaptor->setEmulationObj(NULL); P6Core->Stop(); P6Core->deleteLater(); // P6オブジェクトを開放 P6Core = NULL; // 再起動ならばINIファイル再読込み if( Restart == EL6::Restart ){ if( !Cfg.Init() ){ Error::SetError( Error::IniDefault ); OSD_Message( (char *)Error::GetErrorText(), MSERR_ERROR, OSDR_OK | OSDM_ICONWARNING ); Error::SetError( Error::NoError ); } } if( Restart == EL6::Quit ){ // 終了処理 OSD_Quit(); exit(); return; } else { emit vmRestart(); } } void QtP6VXApplication::terminateEmulation() { OSD_PushEvent( EV_QUIT ); } bool QtP6VXApplication::notify ( QObject * receiver, QEvent * event ) { Event ev; ev.type = EV_NOEVENT; switch(event->type()){ case QEvent::KeyPress: case QEvent::KeyRelease: { QKeyEvent* ke = dynamic_cast<QKeyEvent*>(event); Q_ASSERT(ke); int keyCode = ke->key(); // 「ろ」が入力できない対策 quint32 nativeKey = ke->nativeScanCode(); //X11の場合 if (QGuiApplication::platformName() == QLatin1String("xcb")){ if(keyCode == Qt::Key_Backslash){ keyCode = nativeKey == 97 ? Qt::Key_Underscore : Qt::Key_Backslash; } } //Windowsの場合 else if (QGuiApplication::platformName() == QLatin1String("windows")){ if(keyCode == Qt::Key_Backslash){ keyCode = nativeKey == 115 ? Qt::Key_Underscore : Qt::Key_Backslash; } } ev.type = event->type() == QEvent::KeyPress ? EV_KEYDOWN : EV_KEYUP; ev.key.state = event->type() == QEvent::KeyPress ? true : false; ev.key.sym = OSD_ConvertKeyCode( keyCode ); ev.key.mod = (PCKEYmod)( ( ke->modifiers() & Qt::ShiftModifier ? KVM_SHIFT : KVM_NONE ) | ( ke->modifiers() & Qt::ControlModifier ? KVM_CTRL : KVM_NONE ) | ( ke->modifiers() & Qt::AltModifier ? KVM_ALT : KVM_NONE ) | ( ke->modifiers() & Qt::MetaModifier ? KVM_META : KVM_NONE ) | ( ke->modifiers() & Qt::KeypadModifier ? KVM_NUM : KVM_NONE ) //#PENDING CAPSLOCKは検出できない? //| ( ke->modifiers() & Qt::caps ? KVM_NUM : KVM_NONE ) ); ev.key.unicode = ke->text().utf16()[0]; OSD_PushEvent(ev); break; } case QEvent::ContextMenu: { ev.type = EV_CONTEXTMENU; OSD_PushEvent(ev.type); break; } default:; } if(ev.type == EV_NOEVENT){ return QtSingleApplication::notify(receiver, event); } else { return true; } } <|endoftext|>
<commit_before>/* * RemoteSyslogAppender.cpp * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Walter Stroebel. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "log4cpp/Portability.hh" #ifdef LOG4CPP_HAVE_UNISTD_H # include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "log4cpp/RemoteSyslogAppender.hh" #ifdef WIN32 #include <winsock2.h> #endif namespace log4cpp { int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) { static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG }; int result; priority++; priority /= 100; if (priority < 0) { result = LOG_EMERG; } else if (priority > 7) { result = LOG_DEBUG; } else { result = priorities[priority]; } return result; } RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name, const std::string& syslogName, const std::string& relayer, int facility, int portNumber) : AppenderSkeleton(name), _syslogName(syslogName), _relayer(relayer), _facility(facility), _portNumber (portNumber), _socket (0), _ipAddr (0), _cludge (0) { open(); } RemoteSyslogAppender::~RemoteSyslogAppender() { close(); #ifdef WIN32 if (_cludge) { // we started it, we end it. WSACleanup (); } #endif } void RemoteSyslogAppender::open() { if (!_ipAddr) { struct hostent *pent = gethostbyname (_relayer.c_str ()); if (pent == NULL) { #ifdef WIN32 if (WSAGetLastError () == WSANOTINITIALISED) { WSADATA wsaData; int err; err = WSAStartup (0x101, &wsaData ); if (err) abort (); pent = gethostbyname (_relayer.c_str ()); _cludge = 1; } else { abort (); } #endif } if (pent == NULL) { unsigned long ip = (unsigned long) inet_addr (_relayer.c_str ()); pent = gethostbyaddr ((const char *) &ip, 4, AF_INET); } if (pent == NULL) { abort (); } _ipAddr = *((unsigned long *) pent->h_addr); } // Get a datagram socket. if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { abort (); } } void RemoteSyslogAppender::close() { if (_socket) { #if WIN32 closesocket (_socket); #else close (_socket); #endif _socket = 0; } } void RemoteSyslogAppender::_append(const LoggingEvent& event) { if (!_layout) { // XXX help! help! return; } const char* message = _layout->format(event).c_str(); int len = strlen (message) + 16; char *buf = new char [len]; int priority = toSyslogPriority(event.priority); sprintf (buf, "<%d>", priority); memcpy (buf + strlen (buf), message, len - 16); sockaddr_in sain; sain.sin_family = AF_INET; sain.sin_port = htons (_portNumber); sain.sin_addr.s_addr = htonl (_ipAddr); sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain)); delete buf; } bool RemoteSyslogAppender::reopen() { close(); open(); return true; } bool RemoteSyslogAppender::requiresLayout() const { return true; } void RemoteSyslogAppender::setLayout(Layout* layout) { _layout = layout; } } <commit_msg>Debugging<commit_after>/* * RemoteSyslogAppender.cpp * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Walter Stroebel. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "log4cpp/Portability.hh" #ifdef LOG4CPP_HAVE_UNISTD_H # include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "log4cpp/RemoteSyslogAppender.hh" #ifdef WIN32 #include <winsock2.h> #endif namespace log4cpp { int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) { static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG }; int result; priority++; priority /= 100; if (priority < 0) { result = LOG_EMERG; } else if (priority > 7) { result = LOG_DEBUG; } else { result = priorities[priority]; } return result; } RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name, const std::string& syslogName, const std::string& relayer, int facility, int portNumber) : AppenderSkeleton(name), _syslogName(syslogName), _relayer(relayer), _facility(facility), _portNumber (portNumber), _socket (0), _ipAddr (0), _cludge (0) { open(); } RemoteSyslogAppender::~RemoteSyslogAppender() { close(); #ifdef WIN32 if (_cludge) { // we started it, we end it. WSACleanup (); } #endif } void RemoteSyslogAppender::open() { if (!_ipAddr) { struct hostent *pent = gethostbyname (_relayer.c_str ()); if (pent == NULL) { #ifdef WIN32 if (WSAGetLastError () == WSANOTINITIALISED) { WSADATA wsaData; int err; err = WSAStartup (0x101, &wsaData ); if (err) abort (); pent = gethostbyname (_relayer.c_str ()); _cludge = 1; } else { abort (); } #endif } if (pent == NULL) { unsigned long ip = (unsigned long) inet_addr (_relayer.c_str ()); pent = gethostbyaddr ((const char *) &ip, 4, AF_INET); } if (pent == NULL) { abort (); } _ipAddr = *((unsigned long *) pent->h_addr); } // Get a datagram socket. if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { abort (); } else { sockaddr_in sain; sain.sin_family = AF_INET; sain.sin_port = htons (_portNumber); sain.sin_addr.s_addr = htonl (_ipAddr); if (connect (_socket, (struct sockaddr *) &sain, sizeof (sain)) < 0) { abort (); } } } void RemoteSyslogAppender::close() { if (_socket) { #if WIN32 closesocket (_socket); #else close (_socket); #endif _socket = 0; } } void RemoteSyslogAppender::_append(const LoggingEvent& event) { if (!_layout) { // XXX help! help! return; } const char* message = _layout->format(event).c_str(); int len = strlen (message) + 16; char *buf = new char [len]; int priority = toSyslogPriority(event.priority); sprintf (buf, "<%d>", priority); memcpy (buf + strlen (buf), message, len - 16); sockaddr_in sain; sain.sin_family = AF_INET; sain.sin_port = htons (_portNumber); sain.sin_addr.s_addr = htonl (_ipAddr); int r = sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain)); printf ("sendto: %d\n", r); delete buf; } bool RemoteSyslogAppender::reopen() { close(); open(); return true; } bool RemoteSyslogAppender::requiresLayout() const { return true; } void RemoteSyslogAppender::setLayout(Layout* layout) { _layout = layout; } } <|endoftext|>
<commit_before>#ifndef __POINT_3D_H #define __POINT_3D_H template<typename T> struct Point3D { T x, y, z; inline void operator+=(const Point3D& other) { x += other.x; y += other.y; z += other.z; } inline void operator-=(const Point3D& other) { x -= other.x; y -= other.y; z -= other.z; } inline void operator*=(T mul) { x *= mul; y *= mul; z *= mul; } inline void operator/=(T div) { x *= div; y *= div; z *= div; } }; #endif // __POINT_3D_H <commit_msg>Bug fix<commit_after>#ifndef __POINT_3D_H #define __POINT_3D_H template<typename T> struct Point3D { T x, y, z; inline void operator+=(const Point3D& other) { x += other.x; y += other.y; z += other.z; } inline void operator-=(const Point3D& other) { x -= other.x; y -= other.y; z -= other.z; } inline void operator*=(T mul) { x *= mul; y *= mul; z *= mul; } inline void operator/=(T div) { x /= div; y /= div; z /= div; } }; #endif // __POINT_3D_H <|endoftext|>
<commit_before>#ifndef __STAN__VERSION_HPP__ #define __STAN__VERSION_HPP__ #include <string> namespace stan { /** Major version number for Stan package. */ const std::string MAJOR_VERSION = "alpha"; /** Minor version number for Stan package. */ const std::string MINOR_VERSION = "0"; } #endif <commit_msg>added patch level version number<commit_after>#ifndef __STAN__VERSION_HPP__ #define __STAN__VERSION_HPP__ #include <string> namespace stan { /** Major version number for Stan package. */ const std::string MAJOR_VERSION = "1"; /** Minor version number for Stan package. */ const std::string MINOR_VERSION = "0"; /** Patch version for Stan package. */ const std::string PATCH_VERSION = "0"; } #endif <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ElemApplyImport.hpp" #include <xercesc/sax/AttributeList.hpp> #include <XalanDOM/XalanDOMException.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <DOMSupport/DOMServices.hpp> #include "Constants.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetExecutionContext.hpp" XALAN_CPP_NAMESPACE_BEGIN ElemApplyImport::ElemApplyImport( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const AttributeListType& atts, int lineNumber, int columnNumber) : ElemTemplateElement(constructionContext, stylesheetTree, lineNumber, columnNumber, StylesheetConstructionContext::ELEMNAME_APPLY_IMPORTS) { const unsigned int nAttrs = atts.getLength(); for(unsigned int i = 0; i < nAttrs; i++) { const XalanDOMChar* const aname = atts.getName(i); if(isAttrOK(aname, atts, i, constructionContext) == false) { constructionContext.error( "xsl:apply-imports has an illegal attribute", 0, this); } } } const XalanDOMString& ElemApplyImport::getElementName() const { return Constants::ELEMNAME_APPLY_IMPORTS_WITH_PREFIX_STRING; } void ElemApplyImport::execute(StylesheetExecutionContext& executionContext) const { XalanNode* const sourceNode = executionContext.getCurrentNode(); assert(sourceNode != 0); if (executionContext.getCurrentTemplate() == 0) { executionContext.error("There is no current template", sourceNode, getLocator()); } ElemTemplateElement::execute(executionContext); transformChild( executionContext, *this, 0, sourceNode); } ElemTemplateElement* ElemApplyImport::appendChildElem(ElemTemplateElement* /* newChild */) { throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR); return 0; } XALAN_CPP_NAMESPACE_END <commit_msg>Push and pop context marker when executing.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ElemApplyImport.hpp" #include <xercesc/sax/AttributeList.hpp> #include <XalanDOM/XalanDOMException.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <DOMSupport/DOMServices.hpp> #include "Constants.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetExecutionContext.hpp" XALAN_CPP_NAMESPACE_BEGIN ElemApplyImport::ElemApplyImport( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const AttributeListType& atts, int lineNumber, int columnNumber) : ElemTemplateElement(constructionContext, stylesheetTree, lineNumber, columnNumber, StylesheetConstructionContext::ELEMNAME_APPLY_IMPORTS) { const unsigned int nAttrs = atts.getLength(); for(unsigned int i = 0; i < nAttrs; i++) { const XalanDOMChar* const aname = atts.getName(i); if(isAttrOK(aname, atts, i, constructionContext) == false) { constructionContext.error( "xsl:apply-imports has an illegal attribute", 0, this); } } } const XalanDOMString& ElemApplyImport::getElementName() const { return Constants::ELEMNAME_APPLY_IMPORTS_WITH_PREFIX_STRING; } void ElemApplyImport::execute(StylesheetExecutionContext& executionContext) const { XalanNode* const sourceNode = executionContext.getCurrentNode(); assert(sourceNode != 0); if (executionContext.getCurrentTemplate() == 0) { executionContext.error("There is no current template", sourceNode, getLocator()); } ElemTemplateElement::execute(executionContext); const StylesheetExecutionContext::PushAndPopContextMarker thePusPop(executionContext); transformChild( executionContext, *this, 0, sourceNode); } ElemTemplateElement* ElemApplyImport::appendChildElem(ElemTemplateElement* /* newChild */) { throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR); return 0; } XALAN_CPP_NAMESPACE_END <|endoftext|>
<commit_before>/* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_RUBY_SLICC_INTERFACE_NETWORKMESSAGE_HH__ #define __MEM_RUBY_SLICC_INTERFACE_NETWORKMESSAGE_HH__ #include <iostream> #include "base/refcnt.hh" #include "mem/protocol/MessageSizeType.hh" #include "mem/ruby/common/Global.hh" #include "mem/ruby/common/NetDest.hh" #include "mem/ruby/slicc_interface/Message.hh" class Address; class NetworkMessage; typedef RefCountingPtr<NetworkMessage> NetMsgPtr; class NetworkMessage : public Message { public: NetworkMessage() : m_internal_dest_valid(false) { } NetworkMessage(const NetworkMessage &other) : Message(other), m_internal_dest_valid(other.m_internal_dest_valid) { } virtual ~NetworkMessage() { } virtual const NetDest& getDestination() const = 0; virtual NetDest& getDestination() = 0; virtual const MessageSizeType& getMessageSize() const = 0; virtual MessageSizeType& getMessageSize() = 0; const NetDest& getInternalDestination() const { if (m_internal_dest_valid == false) return getDestination(); return m_internal_dest; } NetDest& getInternalDestination() { if (m_internal_dest_valid == false) { m_internal_dest = getDestination(); m_internal_dest_valid = true; } return m_internal_dest; } virtual void print(std::ostream& out) const = 0; private: NetDest m_internal_dest; bool m_internal_dest_valid; }; inline std::ostream& operator<<(std::ostream& out, const NetworkMessage& obj) { obj.print(out); out << std::flush; return out; } #endif // __MEM_RUBY_SLICC_INTERFACE_NETWORKMESSAGE_HH__ <commit_msg>NetworkMessage copy constructor fix<commit_after>/* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_RUBY_SLICC_INTERFACE_NETWORKMESSAGE_HH__ #define __MEM_RUBY_SLICC_INTERFACE_NETWORKMESSAGE_HH__ #include <iostream> #include "base/refcnt.hh" #include "mem/protocol/MessageSizeType.hh" #include "mem/ruby/common/Global.hh" #include "mem/ruby/common/NetDest.hh" #include "mem/ruby/slicc_interface/Message.hh" class Address; class NetworkMessage; typedef RefCountingPtr<NetworkMessage> NetMsgPtr; class NetworkMessage : public Message { public: NetworkMessage() : m_internal_dest_valid(false) { } NetworkMessage(const NetworkMessage &other) : Message(other), m_internal_dest(other.m_internal_dest), m_internal_dest_valid(other.m_internal_dest_valid) { } virtual ~NetworkMessage() { } virtual const NetDest& getDestination() const = 0; virtual NetDest& getDestination() = 0; virtual const MessageSizeType& getMessageSize() const = 0; virtual MessageSizeType& getMessageSize() = 0; const NetDest& getInternalDestination() const { if (m_internal_dest_valid == false) return getDestination(); return m_internal_dest; } NetDest& getInternalDestination() { if (m_internal_dest_valid == false) { m_internal_dest = getDestination(); m_internal_dest_valid = true; } return m_internal_dest; } virtual void print(std::ostream& out) const = 0; private: NetDest m_internal_dest; bool m_internal_dest_valid; }; inline std::ostream& operator<<(std::ostream& out, const NetworkMessage& obj) { obj.print(out); out << std::flush; return out; } #endif // __MEM_RUBY_SLICC_INTERFACE_NETWORKMESSAGE_HH__ <|endoftext|>
<commit_before>#include "endtoendtest.h" using namespace std; using namespace cv; using namespace alpr; EndToEndTest::EndToEndTest(string inputDir, string outputDir) { this->inputDir = inputDir; this->outputDir = outputDir; } void EndToEndTest::runTest(string country, vector<std::string> files) { AlprImpl alpr(country); alpr.config->debugOff(); alpr.setDetectRegion(false); vector<EndToEndBenchmarkResult> benchmarkResults; vector<string> textFiles = filterByExtension(files, ".txt"); for (int i = 0; i< textFiles.size(); i++) { cout << "Benchmarking file " << (i + 1) << " / " << textFiles.size() << " -- " << textFiles[i] << endl; EndToEndBenchmarkResult benchmarkResult; string fulltextpath = inputDir + "/" + textFiles[i]; ifstream inputFile(fulltextpath.c_str()); string line; getline(inputFile, line); istringstream ss(line); string imgfile, plate_number; int x, y, w, h; ss >> imgfile >> x >> y >> w >> h >> plate_number; string fullimgpath = inputDir + "/" + imgfile; benchmarkResult.imageName = imgfile; Mat frame = imread( fullimgpath.c_str() ); Rect actualPlateRect(x, y, w, h); AlprFullDetails recognitionDetails = alpr.recognizeFullDetails(frame); //cv::circle(frame, centerPoint, 2, Scalar(0, 0, 255), 5); //drawAndWait(&frame); benchmarkResult.detectionFalsePositives = 0; for (int z = 0; z < recognitionDetails.plateRegions.size(); z++) { benchmarkResult.detectionFalsePositives += totalRectCount(recognitionDetails.plateRegions[z]); bool rectmatches = rectMatches(actualPlateRect, recognitionDetails.plateRegions[z]); if (rectmatches) { // This region matches our plate_number benchmarkResult.detectedPlate = true; benchmarkResult.detectionFalsePositives--; break; } } benchmarkResult.resultsFalsePositives = recognitionDetails.results.plates.size(); // Determine if the top result and the top N results match the correct value for (int z = 0; z < recognitionDetails.results.plates.size(); z++) { //cout << "Actual: " << plate_number << endl; //cout << "Candidate: " << recognitionDetails.results[z].bestPlate.characters << endl; if (recognitionDetails.results.plates[z].bestPlate.characters == plate_number) { benchmarkResult.topResultCorrect = true; benchmarkResult.top10ResultCorrect = true; benchmarkResult.resultsFalsePositives--; break; } for (int idx = 0; idx < recognitionDetails.results.plates[z].topNPlates.size(); idx++) { if (recognitionDetails.results.plates[z].topNPlates[idx].characters == plate_number) { benchmarkResult.top10ResultCorrect = true; benchmarkResult.resultsFalsePositives--; break; } } if (benchmarkResult.top10ResultCorrect) break; } benchmarkResults.push_back(benchmarkResult); } // Print results data ofstream data; string outputResultsFile = outputDir + "/results.txt"; data.open(outputResultsFile.c_str()); data << "Image name Detected Plate # False Detections Top Result Correct Top 10 Correct # False Results" << endl; for (int i = 0; i < benchmarkResults.size(); i++) { EndToEndBenchmarkResult br = benchmarkResults[i]; data << br.imageName << "\t" << br.detectedPlate << "\t" << br.detectionFalsePositives << "\t" << br.topResultCorrect << "\t" << br.top10ResultCorrect << "\t" << br.resultsFalsePositives << endl; } data.close(); // Print summary data int totalDetections = 0; int totalTopResultCorrect = 0; int totalTop10Correct = 0; int falseDetectionPositives = 0; int falseResults = 0; for (int i = 0; i < benchmarkResults.size(); i++) { if (benchmarkResults[i].detectedPlate) totalDetections++; if (benchmarkResults[i].topResultCorrect) totalTopResultCorrect++; if (benchmarkResults[i].top10ResultCorrect) totalTop10Correct++; falseDetectionPositives += benchmarkResults[i].detectionFalsePositives; falseResults += benchmarkResults[i].resultsFalsePositives; } // Percentage of how many are correct (higher is better) float detectionScore = 100.0 * ((float) totalDetections) / ((float) benchmarkResults.size()); float topResultScore = 100.0 * ((float) totalTopResultCorrect) / ((float) benchmarkResults.size()); float top10ResultScore = 100.0 * ((float) totalTop10Correct) / ((float) benchmarkResults.size()); // How many false positives per image (higher is worse) float falseDetectionPositivesScore = ((float) falseDetectionPositives) / ((float) benchmarkResults.size()); float falseResultsScore = ((float) falseResults) / ((float) benchmarkResults.size()); string outputSummaryFile = outputDir + "/summary.txt"; data.open(outputSummaryFile.c_str()); data << "-------------------" << endl; data << "| SUMMARY |" << endl; data << "-------------------" << endl; data << endl; data << "Accuracy scores (higher is better)" << endl; data << "Percent of plates DETECTED: " << detectionScore << endl; data << "Percent of correct TOP10: " << top10ResultScore << endl; data << "Percent of correct MATCHES: " << topResultScore << endl; data << endl; data << "False Positives Score (lower is better)" << endl; data << "False DETECTIONS per image: " << falseDetectionPositivesScore << endl; data << "False RESULTS per image: " << falseResultsScore << endl; data.close(); // Print the contents of these files now: string line; ifstream resultsFileIn(outputResultsFile.c_str()); while(getline(resultsFileIn, line)) { cout << line << endl; } ifstream summaryFileIn(outputSummaryFile.c_str()); while(getline(summaryFileIn, line)) { cout << line << endl; } } bool EndToEndTest::rectMatches(cv::Rect actualPlate, PlateRegion candidate) { // Determine if this region matches our plate in the image // Do this simply by verifying that the center point of the plate is within the region // And that the plate region is not x% larger or smaller const float MAX_SIZE_PERCENT_LARGER = 0.65; //int plateCenterX = actualPlate.x + (int) (((float) actualPlate.width) / 2.0); //int plateCenterY = actualPlate.y + (int) (((float) actualPlate.height) / 2.0); //Point centerPoint(plateCenterX, plateCenterY); vector<Point> requiredPoints; requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.2), actualPlate.y + (int) (((float) actualPlate.height) * 0.15) )); requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.8), actualPlate.y + (int) (((float) actualPlate.height) * 0.15) )); requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.2), actualPlate.y + (int) (((float) actualPlate.height) * 0.85) )); requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.8), actualPlate.y + (int) (((float) actualPlate.height) * 0.85) )); float sizeDiff = 1.0 - ((float) actualPlate.area()) / ((float) candidate.rect.area()); //cout << "Candidate: " << candidate.rect.x << "," << candidate.rect.y << " " << candidate.rect.width << "-" << candidate.rect.height << endl; //cout << "Actual: " << actualPlate.x << "," << actualPlate.y << " " << actualPlate.width << "-" << actualPlate.height << endl; //cout << "size diff: " << sizeDiff << endl; bool hasAllPoints = true; for (int z = 0; z < requiredPoints.size(); z++) { if (candidate.rect.contains(requiredPoints[z]) == false) hasAllPoints = false; break; } if ( hasAllPoints && (sizeDiff < MAX_SIZE_PERCENT_LARGER) ) { return true; } else { for (int i = 0; i < candidate.children.size(); i++) { if (rectMatches(actualPlate, candidate.children[i])) return true; } } return false; } int EndToEndTest::totalRectCount(PlateRegion rootCandidate) { int childCount = 0; for (int i = 0; i < rootCandidate.children.size(); i++) { childCount += totalRectCount(rootCandidate.children[i]); } return childCount + 1; } <commit_msg>Fixed end-to-end benchmark to work with updated internal API<commit_after>#include "endtoendtest.h" using namespace std; using namespace cv; using namespace alpr; EndToEndTest::EndToEndTest(string inputDir, string outputDir) { this->inputDir = inputDir; this->outputDir = outputDir; } void EndToEndTest::runTest(string country, vector<std::string> files) { AlprImpl alpr(country); alpr.config->debugOff(); alpr.setDetectRegion(false); vector<EndToEndBenchmarkResult> benchmarkResults; vector<string> textFiles = filterByExtension(files, ".txt"); for (int i = 0; i< textFiles.size(); i++) { cout << "Benchmarking file " << (i + 1) << " / " << textFiles.size() << " -- " << textFiles[i] << endl; EndToEndBenchmarkResult benchmarkResult; string fulltextpath = inputDir + "/" + textFiles[i]; ifstream inputFile(fulltextpath.c_str()); string line; getline(inputFile, line); istringstream ss(line); string imgfile, plate_number; int x, y, w, h; ss >> imgfile >> x >> y >> w >> h >> plate_number; string fullimgpath = inputDir + "/" + imgfile; benchmarkResult.imageName = imgfile; Mat frame = imread( fullimgpath.c_str() ); Rect actualPlateRect(x, y, w, h); vector<Rect> rois; rois.push_back(Rect(0,0,frame.cols,frame.rows)); AlprFullDetails recognitionDetails = alpr.recognizeFullDetails(frame, rois); //cv::circle(frame, centerPoint, 2, Scalar(0, 0, 255), 5); //drawAndWait(&frame); benchmarkResult.detectionFalsePositives = 0; for (int z = 0; z < recognitionDetails.plateRegions.size(); z++) { benchmarkResult.detectionFalsePositives += totalRectCount(recognitionDetails.plateRegions[z]); bool rectmatches = rectMatches(actualPlateRect, recognitionDetails.plateRegions[z]); if (rectmatches) { // This region matches our plate_number benchmarkResult.detectedPlate = true; benchmarkResult.detectionFalsePositives--; break; } } benchmarkResult.resultsFalsePositives = recognitionDetails.results.plates.size(); // Determine if the top result and the top N results match the correct value for (int z = 0; z < recognitionDetails.results.plates.size(); z++) { //cout << "Actual: " << plate_number << endl; //cout << "Candidate: " << recognitionDetails.results[z].bestPlate.characters << endl; if (recognitionDetails.results.plates[z].bestPlate.characters == plate_number) { benchmarkResult.topResultCorrect = true; benchmarkResult.top10ResultCorrect = true; benchmarkResult.resultsFalsePositives--; break; } for (int idx = 0; idx < recognitionDetails.results.plates[z].topNPlates.size(); idx++) { if (recognitionDetails.results.plates[z].topNPlates[idx].characters == plate_number) { benchmarkResult.top10ResultCorrect = true; benchmarkResult.resultsFalsePositives--; break; } } if (benchmarkResult.top10ResultCorrect) break; } benchmarkResults.push_back(benchmarkResult); } // Print results data ofstream data; string outputResultsFile = outputDir + "/results.txt"; data.open(outputResultsFile.c_str()); data << "Image name Detected Plate # False Detections Top Result Correct Top 10 Correct # False Results" << endl; for (int i = 0; i < benchmarkResults.size(); i++) { EndToEndBenchmarkResult br = benchmarkResults[i]; data << br.imageName << "\t" << br.detectedPlate << "\t" << br.detectionFalsePositives << "\t" << br.topResultCorrect << "\t" << br.top10ResultCorrect << "\t" << br.resultsFalsePositives << endl; } data.close(); // Print summary data int totalDetections = 0; int totalTopResultCorrect = 0; int totalTop10Correct = 0; int falseDetectionPositives = 0; int falseResults = 0; for (int i = 0; i < benchmarkResults.size(); i++) { if (benchmarkResults[i].detectedPlate) totalDetections++; if (benchmarkResults[i].topResultCorrect) totalTopResultCorrect++; if (benchmarkResults[i].top10ResultCorrect) totalTop10Correct++; falseDetectionPositives += benchmarkResults[i].detectionFalsePositives; falseResults += benchmarkResults[i].resultsFalsePositives; } // Percentage of how many are correct (higher is better) float detectionScore = 100.0 * ((float) totalDetections) / ((float) benchmarkResults.size()); float topResultScore = 100.0 * ((float) totalTopResultCorrect) / ((float) benchmarkResults.size()); float top10ResultScore = 100.0 * ((float) totalTop10Correct) / ((float) benchmarkResults.size()); // How many false positives per image (higher is worse) float falseDetectionPositivesScore = ((float) falseDetectionPositives) / ((float) benchmarkResults.size()); float falseResultsScore = ((float) falseResults) / ((float) benchmarkResults.size()); string outputSummaryFile = outputDir + "/summary.txt"; data.open(outputSummaryFile.c_str()); data << "-------------------" << endl; data << "| SUMMARY |" << endl; data << "-------------------" << endl; data << endl; data << "Accuracy scores (higher is better)" << endl; data << "Percent of plates DETECTED: " << detectionScore << endl; data << "Percent of correct TOP10: " << top10ResultScore << endl; data << "Percent of correct MATCHES: " << topResultScore << endl; data << endl; data << "False Positives Score (lower is better)" << endl; data << "False DETECTIONS per image: " << falseDetectionPositivesScore << endl; data << "False RESULTS per image: " << falseResultsScore << endl; data.close(); // Print the contents of these files now: string line; ifstream resultsFileIn(outputResultsFile.c_str()); while(getline(resultsFileIn, line)) { cout << line << endl; } ifstream summaryFileIn(outputSummaryFile.c_str()); while(getline(summaryFileIn, line)) { cout << line << endl; } } bool EndToEndTest::rectMatches(cv::Rect actualPlate, PlateRegion candidate) { // Determine if this region matches our plate in the image // Do this simply by verifying that the center point of the plate is within the region // And that the plate region is not x% larger or smaller const float MAX_SIZE_PERCENT_LARGER = 0.65; //int plateCenterX = actualPlate.x + (int) (((float) actualPlate.width) / 2.0); //int plateCenterY = actualPlate.y + (int) (((float) actualPlate.height) / 2.0); //Point centerPoint(plateCenterX, plateCenterY); vector<Point> requiredPoints; requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.2), actualPlate.y + (int) (((float) actualPlate.height) * 0.15) )); requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.8), actualPlate.y + (int) (((float) actualPlate.height) * 0.15) )); requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.2), actualPlate.y + (int) (((float) actualPlate.height) * 0.85) )); requiredPoints.push_back(Point( actualPlate.x + (int) (((float) actualPlate.width) * 0.8), actualPlate.y + (int) (((float) actualPlate.height) * 0.85) )); float sizeDiff = 1.0 - ((float) actualPlate.area()) / ((float) candidate.rect.area()); //cout << "Candidate: " << candidate.rect.x << "," << candidate.rect.y << " " << candidate.rect.width << "-" << candidate.rect.height << endl; //cout << "Actual: " << actualPlate.x << "," << actualPlate.y << " " << actualPlate.width << "-" << actualPlate.height << endl; //cout << "size diff: " << sizeDiff << endl; bool hasAllPoints = true; for (int z = 0; z < requiredPoints.size(); z++) { if (candidate.rect.contains(requiredPoints[z]) == false) hasAllPoints = false; break; } if ( hasAllPoints && (sizeDiff < MAX_SIZE_PERCENT_LARGER) ) { return true; } else { for (int i = 0; i < candidate.children.size(); i++) { if (rectMatches(actualPlate, candidate.children[i])) return true; } } return false; } int EndToEndTest::totalRectCount(PlateRegion rootCandidate) { int childCount = 0; for (int i = 0; i < rootCandidate.children.size(); i++) { childCount += totalRectCount(rootCandidate.children[i]); } return childCount + 1; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnetworkconfigmanager_p.h" #include "qbearerplugin.h" #include <QtCore/private/qfactoryloader_p.h> #include <QtCore/qdebug.h> #include <QtCore/qtimer.h> #include <QtCore/qstringlist.h> QT_BEGIN_NAMESPACE Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QBearerEngineFactoryInterface_iid, QLatin1String("/bearer"))) QNetworkConfigurationManagerPrivate::~QNetworkConfigurationManagerPrivate() { while (!sessionEngines.isEmpty()) delete sessionEngines.takeFirst(); } void QNetworkConfigurationManagerPrivate::configurationAdded(QNetworkConfigurationPrivatePointer ptr) { if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationAdded(item); } if (ptr->state == QNetworkConfiguration::Active) { onlineConfigurations.insert(ptr); if (!firstUpdate && onlineConfigurations.count() == 1) emit onlineStateChanged(true); } } void QNetworkConfigurationManagerPrivate::configurationRemoved(QNetworkConfigurationPrivatePointer ptr) { ptr->isValid = false; if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationRemoved(item); } onlineConfigurations.remove(ptr); if (!firstUpdate && onlineConfigurations.isEmpty()) emit onlineStateChanged(false); } void QNetworkConfigurationManagerPrivate::configurationChanged(QNetworkConfigurationPrivatePointer ptr) { if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationChanged(item); } bool previous = !onlineConfigurations.isEmpty(); if (ptr->state == QNetworkConfiguration::Active) onlineConfigurations.insert(ptr); else onlineConfigurations.remove(ptr); bool online = !onlineConfigurations.isEmpty(); if (!firstUpdate && online != previous) emit onlineStateChanged(online); } void QNetworkConfigurationManagerPrivate::updateInternetServiceConfiguration() { #if 0 if (!generic->snapConfigurations.contains(QLatin1String("Internet Service Network"))) { QNetworkConfigurationPrivate *serviceNetwork = new QNetworkConfigurationPrivate; serviceNetwork->name = tr("Internet"); serviceNetwork->isValid = true; serviceNetwork->id = QLatin1String("Internet Service Network"); serviceNetwork->state = QNetworkConfiguration::Defined; serviceNetwork->type = QNetworkConfiguration::ServiceNetwork; QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> ptr(serviceNetwork); generic->snapConfigurations.insert(serviceNetwork->id, ptr); if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationAdded(item); } } QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> ptr = generic->snapConfigurations.value(QLatin1String("Internet Service Network")); QList<QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> > serviceNetworkMembers; QHash<QString, QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> >::const_iterator i = generic->accessPointConfigurations.constBegin(); QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Defined; while (i != generic->accessPointConfigurations.constEnd()) { QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> child = i.value(); if (child.data()->internet && ((child.data()->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined)) { serviceNetworkMembers.append(child); state |= child.data()->state; } ++i; } if (ptr.data()->state != state || ptr.data()->serviceNetworkMembers != serviceNetworkMembers) { ptr.data()->state = state; ptr.data()->serviceNetworkMembers = serviceNetworkMembers; QNetworkConfiguration item; item.d = ptr; emit configurationChanged(item); } #endif } void QNetworkConfigurationManagerPrivate::updateConfigurations() { if (firstUpdate) { updating = false; QFactoryLoader *l = loader(); foreach (const QString &key, l->keys()) { QBearerEnginePlugin *plugin = qobject_cast<QBearerEnginePlugin *>(l->instance(key)); if (plugin) { QBearerEngine *engine = plugin->create(key); if (!engine) continue; sessionEngines.append(engine); connect(engine, SIGNAL(updateCompleted()), this, SLOT(updateConfigurations())); connect(engine, SIGNAL(configurationAdded(QNetworkConfigurationPrivatePointer)), this, SLOT(configurationAdded(QNetworkConfigurationPrivatePointer))); connect(engine, SIGNAL(configurationRemoved(QNetworkConfigurationPrivatePointer)), this, SLOT(configurationRemoved(QNetworkConfigurationPrivatePointer))); connect(engine, SIGNAL(configurationChanged(QNetworkConfigurationPrivatePointer)), this, SLOT(configurationChanged(QNetworkConfigurationPrivatePointer))); capFlags |= engine->capabilities(); } } } QBearerEngine *engine = qobject_cast<QBearerEngine *>(sender()); if (!updatingEngines.isEmpty() && engine) { int index = sessionEngines.indexOf(engine); if (index >= 0) updatingEngines.remove(index); } if (updating && updatingEngines.isEmpty()) { updating = false; emit configurationUpdateComplete(); } if (firstUpdate) firstUpdate = false; } /*! Returns the default configuration of the first plugin, if one exists; otherwise returns an invalid configuration. \internal */ QNetworkConfiguration QNetworkConfigurationManagerPrivate::defaultConfiguration() { foreach (QBearerEngine *engine, sessionEngines) { QNetworkConfigurationPrivatePointer ptr = engine->defaultConfiguration(); if (ptr) { QNetworkConfiguration config; config.d = ptr; return config; } } return QNetworkConfiguration(); } void QNetworkConfigurationManagerPrivate::performAsyncConfigurationUpdate() { updating = true; for (int i = 0; i < sessionEngines.count(); ++i) { updatingEngines.insert(i); sessionEngines.at(i)->requestUpdate(); } } QT_END_NAMESPACE <commit_msg>Calculate default configuration if one is not provided by engines.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnetworkconfigmanager_p.h" #include "qbearerplugin.h" #include <QtCore/private/qfactoryloader_p.h> #include <QtCore/qdebug.h> #include <QtCore/qtimer.h> #include <QtCore/qstringlist.h> QT_BEGIN_NAMESPACE Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QBearerEngineFactoryInterface_iid, QLatin1String("/bearer"))) QNetworkConfigurationManagerPrivate::~QNetworkConfigurationManagerPrivate() { while (!sessionEngines.isEmpty()) delete sessionEngines.takeFirst(); } void QNetworkConfigurationManagerPrivate::configurationAdded(QNetworkConfigurationPrivatePointer ptr) { if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationAdded(item); } if (ptr->state == QNetworkConfiguration::Active) { onlineConfigurations.insert(ptr); if (!firstUpdate && onlineConfigurations.count() == 1) emit onlineStateChanged(true); } } void QNetworkConfigurationManagerPrivate::configurationRemoved(QNetworkConfigurationPrivatePointer ptr) { ptr->isValid = false; if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationRemoved(item); } onlineConfigurations.remove(ptr); if (!firstUpdate && onlineConfigurations.isEmpty()) emit onlineStateChanged(false); } void QNetworkConfigurationManagerPrivate::configurationChanged(QNetworkConfigurationPrivatePointer ptr) { if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationChanged(item); } bool previous = !onlineConfigurations.isEmpty(); if (ptr->state == QNetworkConfiguration::Active) onlineConfigurations.insert(ptr); else onlineConfigurations.remove(ptr); bool online = !onlineConfigurations.isEmpty(); if (!firstUpdate && online != previous) emit onlineStateChanged(online); } void QNetworkConfigurationManagerPrivate::updateInternetServiceConfiguration() { #if 0 if (!generic->snapConfigurations.contains(QLatin1String("Internet Service Network"))) { QNetworkConfigurationPrivate *serviceNetwork = new QNetworkConfigurationPrivate; serviceNetwork->name = tr("Internet"); serviceNetwork->isValid = true; serviceNetwork->id = QLatin1String("Internet Service Network"); serviceNetwork->state = QNetworkConfiguration::Defined; serviceNetwork->type = QNetworkConfiguration::ServiceNetwork; QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> ptr(serviceNetwork); generic->snapConfigurations.insert(serviceNetwork->id, ptr); if (!firstUpdate) { QNetworkConfiguration item; item.d = ptr; emit configurationAdded(item); } } QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> ptr = generic->snapConfigurations.value(QLatin1String("Internet Service Network")); QList<QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> > serviceNetworkMembers; QHash<QString, QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> >::const_iterator i = generic->accessPointConfigurations.constBegin(); QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Defined; while (i != generic->accessPointConfigurations.constEnd()) { QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> child = i.value(); if (child.data()->internet && ((child.data()->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined)) { serviceNetworkMembers.append(child); state |= child.data()->state; } ++i; } if (ptr.data()->state != state || ptr.data()->serviceNetworkMembers != serviceNetworkMembers) { ptr.data()->state = state; ptr.data()->serviceNetworkMembers = serviceNetworkMembers; QNetworkConfiguration item; item.d = ptr; emit configurationChanged(item); } #endif } void QNetworkConfigurationManagerPrivate::updateConfigurations() { if (firstUpdate) { updating = false; QFactoryLoader *l = loader(); QBearerEngine *generic = 0; foreach (const QString &key, l->keys()) { QBearerEnginePlugin *plugin = qobject_cast<QBearerEnginePlugin *>(l->instance(key)); if (plugin) { QBearerEngine *engine = plugin->create(key); if (!engine) continue; if (key == QLatin1String("generic")) generic = engine; else sessionEngines.append(engine); connect(engine, SIGNAL(updateCompleted()), this, SLOT(updateConfigurations())); connect(engine, SIGNAL(configurationAdded(QNetworkConfigurationPrivatePointer)), this, SLOT(configurationAdded(QNetworkConfigurationPrivatePointer))); connect(engine, SIGNAL(configurationRemoved(QNetworkConfigurationPrivatePointer)), this, SLOT(configurationRemoved(QNetworkConfigurationPrivatePointer))); connect(engine, SIGNAL(configurationChanged(QNetworkConfigurationPrivatePointer)), this, SLOT(configurationChanged(QNetworkConfigurationPrivatePointer))); capFlags |= engine->capabilities(); } } sessionEngines.append(generic); } QBearerEngine *engine = qobject_cast<QBearerEngine *>(sender()); if (!updatingEngines.isEmpty() && engine) { int index = sessionEngines.indexOf(engine); if (index >= 0) updatingEngines.remove(index); } if (updating && updatingEngines.isEmpty()) { updating = false; emit configurationUpdateComplete(); } if (firstUpdate) firstUpdate = false; } /*! Returns the default configuration of the first plugin, if one exists; otherwise returns an invalid configuration. \internal */ QNetworkConfiguration QNetworkConfigurationManagerPrivate::defaultConfiguration() { foreach (QBearerEngine *engine, sessionEngines) { QNetworkConfigurationPrivatePointer ptr = engine->defaultConfiguration(); if (ptr) { QNetworkConfiguration config; config.d = ptr; return config; } } // Engines don't have a default configuration. // Return first active snap QNetworkConfigurationPrivatePointer firstDiscovered; foreach (QBearerEngine *engine, sessionEngines) { foreach (const QString &id, engine->snapConfigurations.keys()) { QNetworkConfigurationPrivatePointer ptr = engine->snapConfigurations.value(id); if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { QNetworkConfiguration config; config.d = ptr; return config; } else if ((ptr->state & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) { firstDiscovered = ptr; } } } // No Active SNAPs return first Discovered SNAP. if (firstDiscovered) { QNetworkConfiguration config; config.d = firstDiscovered; return config; } // No Active or Discovered SNAPs, do same for InternetAccessPoints. firstDiscovered.reset(); foreach (QBearerEngine *engine, sessionEngines) { foreach (const QString &id, engine->accessPointConfigurations.keys()) { QNetworkConfigurationPrivatePointer ptr = engine->accessPointConfigurations.value(id); if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { QNetworkConfiguration config; config.d = ptr; return config; } else if ((ptr->state & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) { firstDiscovered = ptr; } } } // No Active InternetAccessPoint return first Discovered InternetAccessPoint. if (firstDiscovered) { QNetworkConfiguration config; config.d = firstDiscovered; return config; } return QNetworkConfiguration(); } void QNetworkConfigurationManagerPrivate::performAsyncConfigurationUpdate() { updating = true; for (int i = 0; i < sessionEngines.count(); ++i) { updatingEngines.insert(i); sessionEngines.at(i)->requestUpdate(); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: yuanyi03@baidu.com #include "curl_downloader.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include "common/logging.h" extern "C" { #include "curl/curl.h" } using namespace common; extern int FLAGS_agent_curl_recv_buffer_size; static pthread_once_t once_control = PTHREAD_ONCE_INIT; // destroy func process level static void GlobalDestroy() { curl_global_cleanup(); } // init func process level static void GlobalInit() { curl_global_init(CURL_GLOBAL_ALL); ::atexit(GlobalDestroy); } namespace galaxy { static int OPEN_FLAGS = O_CREAT | O_WRONLY; static int OPEN_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO; CurlDownloader::CurlDownloader() : recv_buffer_size_(0), used_length_(0), recv_buffer_(NULL), output_fd_(-1) { if (FLAGS_agent_curl_recv_buffer_size <= 16 * 1024) { recv_buffer_size_ = 16 * 1024; } else { recv_buffer_size_ = FLAGS_agent_curl_recv_buffer_size; } recv_buffer_ = new char[recv_buffer_size_]; pthread_once(&once_control, GlobalInit); } CurlDownloader::~CurlDownloader() { if (recv_buffer_) { delete recv_buffer_; recv_buffer_ = NULL; } } size_t CurlDownloader::RecvTrunkData(char* ptr, size_t size, size_t nmemb, void* user_data) { CurlDownloader* downloader = static_cast<CurlDownloader*>(user_data); assert(downloader); if (size * nmemb <= 0) { return size * nmemb; } if (downloader->used_length_ == downloader->recv_buffer_size_ || size * nmemb > static_cast<size_t>(downloader->recv_buffer_size_ - downloader->used_length_)) { // flush to disk if (write(downloader->output_fd_, downloader->recv_buffer_, downloader->used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); return 0; } LOG(INFO, "write file %s", downloader->used_length_); downloader->used_length_ = 0; } memcpy(downloader->recv_buffer_ + downloader->used_length_, ptr, size * nmemb); downloader->used_length_ += size * nmemb; return size * nmemb; } int CurlDownloader::Fetch(const std::string& uri, const std::string& path) { output_fd_ = open(path.c_str(), OPEN_FLAGS, OPEN_MODE); if (output_fd_ == -1) { LOG(WARNING, "open file failed %s err[%d: %s]", path.c_str(), errno, strerror(errno)); return -1; } LOG(INFO, "start to curl data %s", uri.c_str()); CURL* curl = curl_easy_init(); int ret; do { ret = curl_easy_setopt(curl, CURLOPT_URL, uri.c_str()); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_URL", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEDATA", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlDownloader::RecvTrunkData); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEFUNCTION", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_VERBOSE", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_perform(curl); if (ret != CURLE_OK) { LOG(WARNING, "libcurl perform failed [%d: %s]", ret, curl_easy_strerror((CURLcode)ret)); break; } if (used_length_ != 0) { if (write(output_fd_, recv_buffer_, used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); ret = -1; break; } LOG(INFO, "write file %d", used_length_); used_length_ = 0; } } while(0); if (curl != NULL) { curl_easy_cleanup(curl); } if (ret != CURLE_OK) { return -1; } return 0; } } // ending namespace galaxy /* vim: set ts=4 sw=4 sts=4 tw=100 */ <commit_msg>update curl_downloader.cc<commit_after>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: yuanyi03@baidu.com #include "curl_downloader.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include "common/logging.h" extern "C" { #include "curl/curl.h" } using namespace common; extern int FLAGS_agent_curl_recv_buffer_size; static pthread_once_t once_control = PTHREAD_ONCE_INIT; // destroy func process level static void GlobalDestroy() { curl_global_cleanup(); } // init func process level static void GlobalInit() { curl_global_init(CURL_GLOBAL_ALL); ::atexit(GlobalDestroy); } namespace galaxy { static int OPEN_FLAGS = O_CREAT | O_WRONLY; static int OPEN_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO; CurlDownloader::CurlDownloader() : recv_buffer_size_(0), used_length_(0), recv_buffer_(NULL), output_fd_(-1) { if (FLAGS_agent_curl_recv_buffer_size <= 16 * 1024) { recv_buffer_size_ = 16 * 1024; } else { recv_buffer_size_ = FLAGS_agent_curl_recv_buffer_size; } recv_buffer_ = new char[recv_buffer_size_]; pthread_once(&once_control, GlobalInit); } CurlDownloader::~CurlDownloader() { if (recv_buffer_) { delete recv_buffer_; recv_buffer_ = NULL; } } size_t CurlDownloader::RecvTrunkData(char* ptr, size_t size, size_t nmemb, void* user_data) { CurlDownloader* downloader = static_cast<CurlDownloader*>(user_data); assert(downloader); if (size * nmemb <= 0) { return size * nmemb; } if (downloader->used_length_ == downloader->recv_buffer_size_ || size * nmemb > static_cast<size_t>(downloader->recv_buffer_size_ - downloader->used_length_)) { // flush to disk if (write(downloader->output_fd_, downloader->recv_buffer_, downloader->used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); return 0; } LOG(INFO, "write file %d", downloader->used_length_); downloader->used_length_ = 0; } memcpy(downloader->recv_buffer_ + downloader->used_length_, ptr, size * nmemb); downloader->used_length_ += size * nmemb; return size * nmemb; } int CurlDownloader::Fetch(const std::string& uri, const std::string& path) { output_fd_ = open(path.c_str(), OPEN_FLAGS, OPEN_MODE); if (output_fd_ == -1) { LOG(WARNING, "open file failed %s err[%d: %s]", path.c_str(), errno, strerror(errno)); return -1; } LOG(INFO, "start to curl data %s", uri.c_str()); CURL* curl = curl_easy_init(); int ret; do { ret = curl_easy_setopt(curl, CURLOPT_URL, uri.c_str()); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_URL", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEDATA", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlDownloader::RecvTrunkData); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEFUNCTION", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_VERBOSE", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_perform(curl); if (ret != CURLE_OK) { LOG(WARNING, "libcurl perform failed [%d: %s]", ret, curl_easy_strerror((CURLcode)ret)); break; } if (used_length_ != 0) { if (write(output_fd_, recv_buffer_, used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); ret = -1; break; } LOG(INFO, "write file %d", used_length_); used_length_ = 0; } } while(0); if (curl != NULL) { curl_easy_cleanup(curl); } if (ret != CURLE_OK) { return -1; } return 0; } } // ending namespace galaxy /* vim: set ts=4 sw=4 sts=4 tw=100 */ <|endoftext|>
<commit_before>// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_kinematics_hpp__ #define __se3_kinematics_hpp__ #include "pinocchio/multibody/visitor.hpp" #include "pinocchio/multibody/model.hpp" namespace se3 { inline void geometry(const Model & model, Data & data, const Eigen::VectorXd & q); inline void kinematics(const Model & model, Data & data, const Eigen::VectorXd & q, const Eigen::VectorXd & v); } // namespace se3 /* --- Details -------------------------------------------------------------------- */ namespace se3 { struct GeometryStep : public fusion::JointVisitor<GeometryStep> { typedef boost::fusion::vector<const se3::Model &, se3::Data &, const size_t, const Eigen::VectorXd & > ArgsType; JOINT_VISITOR_INIT (GeometryStep); template<typename JointModel> static void algo(const se3::JointModelBase<JointModel> & jmodel, se3::JointDataBase<typename JointModel::JointData> & jdata, const se3::Model & model, se3::Data & data, const size_t i, const Eigen::VectorXd & q) { using namespace se3; jmodel.calc (jdata.derived (), q); const Model::Index & parent = model.parents[i]; data.liMi[i] = model.jointPlacements[i] * jdata.M (); if (parent>0) data.oMi[i] = data.oMi[parent] * data.liMi[i]; else data.oMi[i] = data.liMi[i]; } }; inline void geometry(const Model & model, Data & data, const Eigen::VectorXd & q) { for (size_t i=1; i < (size_t) model.nbody; ++i) { GeometryStep::run(model.joints[i], data.joints[i], GeometryStep::ArgsType (model,data,i,q) ); } } struct KinematicsStep : public fusion::JointVisitor<KinematicsStep> { typedef boost::fusion::vector< const se3::Model&, se3::Data&, const size_t, const Eigen::VectorXd &, const Eigen::VectorXd & > ArgsType; JOINT_VISITOR_INIT(KinematicsStep); template<typename JointModel> static void algo(const se3::JointModelBase<JointModel> & jmodel, se3::JointDataBase<typename JointModel::JointData> & jdata, const se3::Model& model, se3::Data& data, const size_t i, const Eigen::VectorXd & q, const Eigen::VectorXd & v) { using namespace Eigen; using namespace se3; jmodel.calc(jdata.derived(),q,v); const Model::Index & parent = model.parents[i]; data.v[i] = jdata.v(); data.liMi[i] = model.jointPlacements[i]*jdata.M(); if(parent>0) { data.oMi[i] = data.oMi[parent]*data.liMi[i]; data.v[i] += data.liMi[i].actInv(data.v[parent]); } else data.oMi[i] = data.liMi[i]; } }; inline void kinematics(const Model & model, Data& data, const Eigen::VectorXd & q, const Eigen::VectorXd & v) { data.v[0] = Motion::Zero(); for( size_t i=1; i<(size_t) model.nbody; ++i ) { KinematicsStep::run(model.joints[i],data.joints[i], KinematicsStep::ArgsType(model,data,i,q,v)); } } } // namespace se3 #endif // ifndef __se3_kinematics_hpp__ <commit_msg>[Minor] Cosmetic change as Model::Index is a size_t<commit_after>// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_kinematics_hpp__ #define __se3_kinematics_hpp__ #include "pinocchio/multibody/visitor.hpp" #include "pinocchio/multibody/model.hpp" namespace se3 { inline void geometry(const Model & model, Data & data, const Eigen::VectorXd & q); inline void kinematics(const Model & model, Data & data, const Eigen::VectorXd & q, const Eigen::VectorXd & v); } // namespace se3 /* --- Details -------------------------------------------------------------------- */ namespace se3 { struct GeometryStep : public fusion::JointVisitor<GeometryStep> { typedef boost::fusion::vector<const se3::Model &, se3::Data &, const Model::Index, const Eigen::VectorXd & > ArgsType; JOINT_VISITOR_INIT (GeometryStep); template<typename JointModel> static void algo(const se3::JointModelBase<JointModel> & jmodel, se3::JointDataBase<typename JointModel::JointData> & jdata, const se3::Model & model, se3::Data & data, const Model::Index i, const Eigen::VectorXd & q) { using namespace se3; jmodel.calc (jdata.derived (), q); const Model::Index & parent = model.parents[i]; data.liMi[i] = model.jointPlacements[i] * jdata.M (); if (parent>0) data.oMi[i] = data.oMi[parent] * data.liMi[i]; else data.oMi[i] = data.liMi[i]; } }; inline void geometry(const Model & model, Data & data, const Eigen::VectorXd & q) { for (Model::Index i=1; i < (Model::Index) model.nbody; ++i) { GeometryStep::run(model.joints[i], data.joints[i], GeometryStep::ArgsType (model,data,i,q) ); } } struct KinematicsStep : public fusion::JointVisitor<KinematicsStep> { typedef boost::fusion::vector< const se3::Model&, se3::Data&, const Model::Index, const Eigen::VectorXd &, const Eigen::VectorXd & > ArgsType; JOINT_VISITOR_INIT(KinematicsStep); template<typename JointModel> static void algo(const se3::JointModelBase<JointModel> & jmodel, se3::JointDataBase<typename JointModel::JointData> & jdata, const se3::Model& model, se3::Data& data, const Model::Index i, const Eigen::VectorXd & q, const Eigen::VectorXd & v) { using namespace Eigen; using namespace se3; jmodel.calc(jdata.derived(),q,v); const Model::Index & parent = model.parents[i]; data.v[i] = jdata.v(); data.liMi[i] = model.jointPlacements[i]*jdata.M(); if(parent>0) { data.oMi[i] = data.oMi[parent]*data.liMi[i]; data.v[i] += data.liMi[i].actInv(data.v[parent]); } else data.oMi[i] = data.liMi[i]; } }; inline void kinematics(const Model & model, Data& data, const Eigen::VectorXd & q, const Eigen::VectorXd & v) { data.v[0] = Motion::Zero(); for( Model::Index i=1; i<(Model::Index) model.nbody; ++i ) { KinematicsStep::run(model.joints[i],data.joints[i], KinematicsStep::ArgsType(model,data,i,q,v)); } } } // namespace se3 #endif // ifndef __se3_kinematics_hpp__ <|endoftext|>
<commit_before>#include "arch/linux/arch.hpp" #include "arch/linux/coroutines.hpp" #include "concurrency/cond_var.hpp" #include "arch/linux/thread_pool.hpp" #include "config/args.hpp" #include <stdio.h> #include <sys/mman.h> #include <ucontext.h> #include <arch/arch.hpp> #include "utils.hpp" #ifdef VALGRIND #include <valgrind/valgrind.h> #endif #ifndef NDEBUG #include <cxxabi.h> // For __cxa_current_exception_type (see below) #endif perfmon_counter_t pm_active_coroutines("active_coroutines"), pm_allocated_coroutines("allocated_coroutines"); size_t coro_stack_size = COROUTINE_STACK_SIZE; //Default, setable by command-line parameter /* We have a custom implementation of swapcontext() that doesn't swap the floating-point registers, the SSE registers, or the signal mask. This is for performance reasons. */ callable_action_wrapper_t::callable_action_wrapper_t() : action_on_heap(false), action_(NULL) { } callable_action_wrapper_t::~callable_action_wrapper_t() { if(action_ != NULL) { reset(); } } void callable_action_wrapper_t::reset() { rassert(action_ != NULL); if (action_on_heap) { delete action_; action_ = NULL; action_on_heap = false; } else { action_->~callable_action_t(); action_ = NULL; } } void callable_action_wrapper_t::run() { rassert(action_ != NULL); action_->run_action(); } extern "C" { void lightweight_makecontext(lw_ucontext_t *ucp, void (*func) (void), void *stack, size_t stack_size) { uint64_t *sp; /* A pointer into the stack. */ /* Start at the beginning. */ sp = (uint64_t *) ((uintptr_t) stack + stack_size); /* Align stack. The x86-64 ABI requires the stack pointer to always be 16-byte-aligned at function calls. That is, "(%rsp - 8) is always a multiple of 16 when control is transferred to the function entry point". */ sp = (uint64_t *) (((uintptr_t) sp) & -16L); // Currently sp is 16-byte aligned. /* Set up the instruction pointer; this will be popped off the stack by * ret in swapcontext once all the other registers have been "restored". */ sp--; sp--; // Subtracted 2*sizeof(int64_t), so sp is still 16-byte aligned. *sp = (uint64_t) func; /* These registers (r12, r13, r14, r15, rbx, rbp) are going to be * popped off the stack by swapcontext; they're callee-saved, so * whatever happens to be in them will be ignored. */ sp -= 6; // Subtracted 6*sizeof(int64_t), so sp is still 16-byte aligned. /* Set up stack pointer. */ *ucp = sp; /* Our coroutines never return, so we don't put anything else on the * stack. */ } /* The register definitions and the definition of the lightweight context functions are derived from GLibC, which is covered under the LGPL. */ extern void lightweight_swapcontext(lw_ucontext_t *oucp, const lw_ucontext_t uc); asm( ".globl lightweight_swapcontext\n" "lightweight_swapcontext:\n" /* Save preserved registers (the return address is already on the stack). */ "pushq %r12\n" "pushq %r13\n" "pushq %r14\n" "pushq %r15\n" "pushq %rbx\n" "pushq %rbp\n" /* Save old stack pointer. */ "movq %rsp, (%rdi)\n" /* Load the new stack pointer and the preserved registers. */ "movq %rsi, %rsp\n" "popq %rbp\n" "popq %rbx\n" "popq %r15\n" "popq %r14\n" "popq %r13\n" "popq %r12\n" /* The following ret should return to the address set with * makecontext or with the previous swapcontext. The instruction * pointer is saved on the stack from the previous call (or * initialized with makecontext). */ "ret\n" ); } /* The coroutine we're currently in, if any. NULL if we are in the main context. */ static __thread coro_t *current_coro = NULL; /* The main context. */ static __thread lw_ucontext_t scheduler; /* The previous context. */ static __thread coro_t *prev_coro = NULL; /* A list of coro_t objects that are not in use. */ static __thread intrusive_list_t<coro_t> *free_coros = NULL; #ifndef NDEBUG /* An integer counting the number of coros on this thread */ static __thread int coro_count = 0; /* These variables are used in the implementation of `ASSERT_NO_CORO_WAITING` and `ASSERT_FINITE_CORO_WAITING`. They record the number of things that are currently preventing us from `wait()`ing or `notify_now()`ing or whatever. */ __thread int assert_no_coro_waiting_counter = 0; __thread int assert_finite_coro_waiting_counter = 0; #endif // NDEBUG /* coro_globals_t */ coro_globals_t::coro_globals_t() { rassert(!current_coro); rassert(free_coros == NULL); free_coros = new intrusive_list_t<coro_t>; } coro_globals_t::~coro_globals_t() { rassert(!current_coro); /* Destroy remaining coroutines */ while (coro_t *s = free_coros->head()) { free_coros->remove(s); delete s; } delete free_coros; free_coros = NULL; } /* coro_t */ coro_t::coro_t() : home_thread_(get_thread_id()), notified_(false), waiting_(false) { pm_allocated_coroutines++; #ifndef NDEBUG coro_count++; #endif rassert(coro_count < MAX_COROS_PER_THREAD, "Too many coroutines " "allocated on this thread. This is problem due to a misuse of the " "coroutines\n"); stack = malloc_aligned(coro_stack_size, getpagesize()); /* Protect the end of the stack so that we crash when we get a stack overflow instead of corrupting memory. */ mprotect(stack, getpagesize(), PROT_NONE); /* Register our stack with Valgrind so that it understands what's going on and doesn't create spurious errors */ #ifdef VALGRIND valgrind_stack_id = VALGRIND_STACK_REGISTER(stack, (intptr_t)stack + coro_stack_size); #endif /* run() is the main worker loop for a coroutine. */ lightweight_makecontext(&env, &coro_t::run, stack, coro_stack_size); } void coro_t::run() { coro_t *self = current_coro; /* Make sure we're on the right stack. */ #ifndef NDEBUG char dummy; rassert(&dummy >= (char*)self->stack); rassert(&dummy < (char*)self->stack + coro_stack_size); #endif while (true) { rassert(current_coro == self); rassert(self->notified_ == false); rassert(self->waiting_ == true); self->waiting_ = false; self->action_wrapper.run(); self->action_wrapper.reset(); /* Return the context to the free-contexts list we took it from. */ do_on_thread(self->home_thread_, boost::bind(return_coro_to_free_coros, self)); pm_active_coroutines++; if (prev_coro) { lightweight_swapcontext(&self->env, prev_coro->env); } else { lightweight_swapcontext(&self->env, scheduler); } } } coro_t::~coro_t() { #ifdef VALGRIND #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-but-set-variable" VALGRIND_STACK_DEREGISTER(valgrind_stack_id); #pragma GCC diagnostic pop #endif // VALGRIND mprotect(stack, getpagesize(), PROT_READ|PROT_WRITE); //Undo protections changes free(stack); pm_allocated_coroutines--; #ifndef NDEBUG coro_count--; #endif } /* coro_t */ coro_t * coro_t::get_coro(int thread) { coro_t *coro; assert_good_thread_id(thread); pm_active_coroutines++; /* Find us a stack */ if (free_coros->size() == 0) { coro = new coro_t(); } else { coro = free_coros->tail(); free_coros->remove(coro); } coro->current_thread_ = thread; coro->notified_ = false; coro->waiting_ = true; return coro; } void coro_t::return_coro_to_free_coros(coro_t *coro) { free_coros->push_back(coro); } coro_t *coro_t::self() { /* class method */ return current_coro; } void coro_t::wait() { /* class method */ rassert(self(), "Not in a coroutine context"); rassert(assert_no_coro_waiting_counter == 0 && assert_finite_coro_waiting_counter == 0, "This code path is not supposed to use coro_t::wait()."); #ifndef NDEBUG /* It's not safe to wait() in a catch clause of an exception handler. We use the non-standard GCC-only interface "cxxabi.h" to figure out if we're in the catch clause of an exception handler. In C++0x we will be able to use std::current_exception() instead. */ rassert(!abi::__cxa_current_exception_type()); #endif rassert(!current_coro->waiting_); current_coro->waiting_ = true; rassert(current_coro); if (prev_coro) { lightweight_swapcontext(&current_coro->env, prev_coro->env); } else { lightweight_swapcontext(&current_coro->env, scheduler); } rassert(current_coro); rassert(self()->current_thread_ == get_thread_id()); rassert(current_coro->waiting_); current_coro->waiting_ = false; } void coro_t::yield() { /* class method */ rassert(self(), "Not in a coroutine context"); self()->notify_later(); self()->wait(); } void coro_t::notify_now() { rassert(waiting_); rassert(!notified_); rassert(current_thread_ == get_thread_id()); #ifndef NDEBUG rassert(assert_no_coro_waiting_counter == 0, "This code path is not supposed to use notify_now() or spawn_now()."); /* Record old value of `assert_finite_coro_waiting_counter`. It must be legal to call `coro_t::wait()` within the coro we are going to jump to, or else we would never jump back. */ int old_assert_finite_coro_waiting_counter = assert_finite_coro_waiting_counter; assert_finite_coro_waiting_counter = 0; #endif #ifndef NDEBUG /* It's not safe to notify_now() in the catch-clause of an exception handler for the same reason we can't wait(). */ rassert(!abi::__cxa_current_exception_type()); #endif coro_t *prev_prev_coro = prev_coro; prev_coro = current_coro; current_coro = this; if (prev_coro) { lightweight_swapcontext(&prev_coro->env, env); } else { lightweight_swapcontext(&scheduler, env); } rassert(this->current_thread_ == get_thread_id()); rassert(current_coro == this); current_coro = prev_coro; prev_coro = prev_prev_coro; #ifndef NDEBUG /* Restore old value of `assert_finite_coro_waiting_counter`. */ assert_finite_coro_waiting_counter = old_assert_finite_coro_waiting_counter; #endif } void coro_t::notify_later() { rassert(!notified_); notified_ = true; /* notify_later() doesn't switch to the coroutine immediately; instead, it just pushes the coroutine onto the event queue. */ /* current_thread is the thread that the coroutine lives on, which may or may not be the same as get_thread_id(). */ linux_thread_pool_t::thread->message_hub.store_message(current_thread_, this); } void coro_t::move_to_thread(int thread) { /* class method */ assert_good_thread_id(thread); if (thread == get_thread_id()) { // If we're trying to switch to the thread we're currently on, do nothing. return; } rassert(coro_t::self(), "coro_t::move_to_thread() called when not in a coroutine, and the " "desired thread isn't the one we're already on."); self()->current_thread_ = thread; self()->notify_later(); wait(); } void coro_t::on_thread_switch() { rassert(notified_); notified_ = false; notify_now(); } void coro_t::set_coroutine_stack_size(size_t size) { coro_stack_size = size; } /* Called by SIGSEGV handler to identify segfaults that come from overflowing a coroutine's stack. Could also in theory be used by a function to check if it's about to overflow the stack. */ bool is_coroutine_stack_overflow(void *addr) { void *base = (void *)floor_aligned((intptr_t)addr, getpagesize()); return current_coro && current_coro->stack == base; } #ifndef NDEBUG /* These are used in the implementation of `ASSERT_NO_CORO_WAITING` and `ASSERT_FINITE_CORO_WAITING` */ assert_no_coro_waiting_t::assert_no_coro_waiting_t() { assert_no_coro_waiting_counter++; } assert_no_coro_waiting_t::~assert_no_coro_waiting_t() { assert_no_coro_waiting_counter--; } assert_finite_coro_waiting_t::assert_finite_coro_waiting_t() { assert_finite_coro_waiting_counter++; } assert_finite_coro_waiting_t::~assert_finite_coro_waiting_t() { assert_finite_coro_waiting_counter--; } #endif /* NDEBUG */ <commit_msg>removing broken assert<commit_after>#include "arch/linux/arch.hpp" #include "arch/linux/coroutines.hpp" #include "concurrency/cond_var.hpp" #include "arch/linux/thread_pool.hpp" #include "config/args.hpp" #include <stdio.h> #include <sys/mman.h> #include <ucontext.h> #include <arch/arch.hpp> #include "utils.hpp" #ifdef VALGRIND #include <valgrind/valgrind.h> #endif #ifndef NDEBUG #include <cxxabi.h> // For __cxa_current_exception_type (see below) #endif perfmon_counter_t pm_active_coroutines("active_coroutines"), pm_allocated_coroutines("allocated_coroutines"); size_t coro_stack_size = COROUTINE_STACK_SIZE; //Default, setable by command-line parameter /* We have a custom implementation of swapcontext() that doesn't swap the floating-point registers, the SSE registers, or the signal mask. This is for performance reasons. */ callable_action_wrapper_t::callable_action_wrapper_t() : action_on_heap(false), action_(NULL) { } callable_action_wrapper_t::~callable_action_wrapper_t() { if(action_ != NULL) { reset(); } } void callable_action_wrapper_t::reset() { rassert(action_ != NULL); if (action_on_heap) { delete action_; action_ = NULL; action_on_heap = false; } else { action_->~callable_action_t(); action_ = NULL; } } void callable_action_wrapper_t::run() { rassert(action_ != NULL); action_->run_action(); } extern "C" { void lightweight_makecontext(lw_ucontext_t *ucp, void (*func) (void), void *stack, size_t stack_size) { uint64_t *sp; /* A pointer into the stack. */ /* Start at the beginning. */ sp = (uint64_t *) ((uintptr_t) stack + stack_size); /* Align stack. The x86-64 ABI requires the stack pointer to always be 16-byte-aligned at function calls. That is, "(%rsp - 8) is always a multiple of 16 when control is transferred to the function entry point". */ sp = (uint64_t *) (((uintptr_t) sp) & -16L); // Currently sp is 16-byte aligned. /* Set up the instruction pointer; this will be popped off the stack by * ret in swapcontext once all the other registers have been "restored". */ sp--; sp--; // Subtracted 2*sizeof(int64_t), so sp is still 16-byte aligned. *sp = (uint64_t) func; /* These registers (r12, r13, r14, r15, rbx, rbp) are going to be * popped off the stack by swapcontext; they're callee-saved, so * whatever happens to be in them will be ignored. */ sp -= 6; // Subtracted 6*sizeof(int64_t), so sp is still 16-byte aligned. /* Set up stack pointer. */ *ucp = sp; /* Our coroutines never return, so we don't put anything else on the * stack. */ } /* The register definitions and the definition of the lightweight context functions are derived from GLibC, which is covered under the LGPL. */ extern void lightweight_swapcontext(lw_ucontext_t *oucp, const lw_ucontext_t uc); asm( ".globl lightweight_swapcontext\n" "lightweight_swapcontext:\n" /* Save preserved registers (the return address is already on the stack). */ "pushq %r12\n" "pushq %r13\n" "pushq %r14\n" "pushq %r15\n" "pushq %rbx\n" "pushq %rbp\n" /* Save old stack pointer. */ "movq %rsp, (%rdi)\n" /* Load the new stack pointer and the preserved registers. */ "movq %rsi, %rsp\n" "popq %rbp\n" "popq %rbx\n" "popq %r15\n" "popq %r14\n" "popq %r13\n" "popq %r12\n" /* The following ret should return to the address set with * makecontext or with the previous swapcontext. The instruction * pointer is saved on the stack from the previous call (or * initialized with makecontext). */ "ret\n" ); } /* The coroutine we're currently in, if any. NULL if we are in the main context. */ static __thread coro_t *current_coro = NULL; /* The main context. */ static __thread lw_ucontext_t scheduler; /* The previous context. */ static __thread coro_t *prev_coro = NULL; /* A list of coro_t objects that are not in use. */ static __thread intrusive_list_t<coro_t> *free_coros = NULL; #ifndef NDEBUG /* An integer counting the number of coros on this thread */ static __thread int coro_count = 0; /* These variables are used in the implementation of `ASSERT_NO_CORO_WAITING` and `ASSERT_FINITE_CORO_WAITING`. They record the number of things that are currently preventing us from `wait()`ing or `notify_now()`ing or whatever. */ __thread int assert_no_coro_waiting_counter = 0; __thread int assert_finite_coro_waiting_counter = 0; #endif // NDEBUG /* coro_globals_t */ coro_globals_t::coro_globals_t() { rassert(!current_coro); rassert(free_coros == NULL); free_coros = new intrusive_list_t<coro_t>; } coro_globals_t::~coro_globals_t() { rassert(!current_coro); /* Destroy remaining coroutines */ while (coro_t *s = free_coros->head()) { free_coros->remove(s); delete s; } delete free_coros; free_coros = NULL; } /* coro_t */ coro_t::coro_t() : home_thread_(get_thread_id()), notified_(false), waiting_(false) { pm_allocated_coroutines++; #ifndef NDEBUG coro_count++; #endif rassert(coro_count < MAX_COROS_PER_THREAD, "Too many coroutines " "allocated on this thread. This is problem due to a misuse of the " "coroutines\n"); stack = malloc_aligned(coro_stack_size, getpagesize()); /* Protect the end of the stack so that we crash when we get a stack overflow instead of corrupting memory. */ mprotect(stack, getpagesize(), PROT_NONE); /* Register our stack with Valgrind so that it understands what's going on and doesn't create spurious errors */ #ifdef VALGRIND valgrind_stack_id = VALGRIND_STACK_REGISTER(stack, (intptr_t)stack + coro_stack_size); #endif /* run() is the main worker loop for a coroutine. */ lightweight_makecontext(&env, &coro_t::run, stack, coro_stack_size); } void coro_t::run() { coro_t *self = current_coro; /* Make sure we're on the right stack. */ #ifndef NDEBUG char dummy; rassert(&dummy >= (char*)self->stack); rassert(&dummy < (char*)self->stack + coro_stack_size); #endif while (true) { rassert(current_coro == self); rassert(self->notified_ == false); rassert(self->waiting_ == true); self->waiting_ = false; self->action_wrapper.run(); self->action_wrapper.reset(); /* Return the context to the free-contexts list we took it from. */ do_on_thread(self->home_thread_, boost::bind(return_coro_to_free_coros, self)); pm_active_coroutines++; if (prev_coro) { lightweight_swapcontext(&self->env, prev_coro->env); } else { lightweight_swapcontext(&self->env, scheduler); } } } coro_t::~coro_t() { #ifdef VALGRIND #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-but-set-variable" VALGRIND_STACK_DEREGISTER(valgrind_stack_id); #pragma GCC diagnostic pop #endif // VALGRIND mprotect(stack, getpagesize(), PROT_READ|PROT_WRITE); //Undo protections changes free(stack); pm_allocated_coroutines--; #ifndef NDEBUG coro_count--; #endif } /* coro_t */ coro_t * coro_t::get_coro(int thread) { coro_t *coro; assert_good_thread_id(thread); pm_active_coroutines++; /* Find us a stack */ if (free_coros->size() == 0) { coro = new coro_t(); } else { coro = free_coros->tail(); free_coros->remove(coro); } coro->current_thread_ = thread; coro->notified_ = false; coro->waiting_ = true; return coro; } void coro_t::return_coro_to_free_coros(coro_t *coro) { free_coros->push_back(coro); } coro_t *coro_t::self() { /* class method */ return current_coro; } void coro_t::wait() { /* class method */ rassert(self(), "Not in a coroutine context"); rassert(assert_no_coro_waiting_counter == 0 && assert_finite_coro_waiting_counter == 0, "This code path is not supposed to use coro_t::wait()."); #ifndef NDEBUG /* It's not safe to wait() in a catch clause of an exception handler. We use the non-standard GCC-only interface "cxxabi.h" to figure out if we're in the catch clause of an exception handler. In C++0x we will be able to use std::current_exception() instead. */ rassert(!abi::__cxa_current_exception_type()); #endif rassert(!current_coro->waiting_); current_coro->waiting_ = true; rassert(current_coro); if (prev_coro) { lightweight_swapcontext(&current_coro->env, prev_coro->env); } else { lightweight_swapcontext(&current_coro->env, scheduler); } rassert(current_coro); rassert(self()->current_thread_ == get_thread_id()); rassert(current_coro->waiting_); current_coro->waiting_ = false; } void coro_t::yield() { /* class method */ rassert(self(), "Not in a coroutine context"); self()->notify_later(); self()->wait(); } void coro_t::notify_now() { rassert(waiting_); rassert(!notified_); rassert(current_thread_ == get_thread_id()); #ifndef NDEBUG rassert(assert_no_coro_waiting_counter == 0, "This code path is not supposed to use notify_now() or spawn_now()."); /* Record old value of `assert_finite_coro_waiting_counter`. It must be legal to call `coro_t::wait()` within the coro we are going to jump to, or else we would never jump back. */ int old_assert_finite_coro_waiting_counter = assert_finite_coro_waiting_counter; assert_finite_coro_waiting_counter = 0; #endif #ifndef NDEBUG /* It's not safe to notify_now() in the catch-clause of an exception handler for the same reason we can't wait(). */ rassert(!abi::__cxa_current_exception_type()); #endif coro_t *prev_prev_coro = prev_coro; prev_coro = current_coro; current_coro = this; if (prev_coro) { lightweight_swapcontext(&prev_coro->env, env); } else { lightweight_swapcontext(&scheduler, env); } rassert(current_coro == this); current_coro = prev_coro; prev_coro = prev_prev_coro; #ifndef NDEBUG /* Restore old value of `assert_finite_coro_waiting_counter`. */ assert_finite_coro_waiting_counter = old_assert_finite_coro_waiting_counter; #endif } void coro_t::notify_later() { rassert(!notified_); notified_ = true; /* notify_later() doesn't switch to the coroutine immediately; instead, it just pushes the coroutine onto the event queue. */ /* current_thread is the thread that the coroutine lives on, which may or may not be the same as get_thread_id(). */ linux_thread_pool_t::thread->message_hub.store_message(current_thread_, this); } void coro_t::move_to_thread(int thread) { /* class method */ assert_good_thread_id(thread); if (thread == get_thread_id()) { // If we're trying to switch to the thread we're currently on, do nothing. return; } rassert(coro_t::self(), "coro_t::move_to_thread() called when not in a coroutine, and the " "desired thread isn't the one we're already on."); self()->current_thread_ = thread; self()->notify_later(); wait(); } void coro_t::on_thread_switch() { rassert(notified_); notified_ = false; notify_now(); } void coro_t::set_coroutine_stack_size(size_t size) { coro_stack_size = size; } /* Called by SIGSEGV handler to identify segfaults that come from overflowing a coroutine's stack. Could also in theory be used by a function to check if it's about to overflow the stack. */ bool is_coroutine_stack_overflow(void *addr) { void *base = (void *)floor_aligned((intptr_t)addr, getpagesize()); return current_coro && current_coro->stack == base; } #ifndef NDEBUG /* These are used in the implementation of `ASSERT_NO_CORO_WAITING` and `ASSERT_FINITE_CORO_WAITING` */ assert_no_coro_waiting_t::assert_no_coro_waiting_t() { assert_no_coro_waiting_counter++; } assert_no_coro_waiting_t::~assert_no_coro_waiting_t() { assert_no_coro_waiting_counter--; } assert_finite_coro_waiting_t::assert_finite_coro_waiting_t() { assert_finite_coro_waiting_counter++; } assert_finite_coro_waiting_t::~assert_finite_coro_waiting_t() { assert_finite_coro_waiting_counter--; } #endif /* NDEBUG */ <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2012, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ /// \file stereo_rfne.cc /// //#define USE_GRAPHICS #include <asp/Tools/stereo.h> #include <vw/Stereo/PreFilter.h> #include <vw/Stereo/CostFunctions.h> #include <vw/Stereo/SubpixelView.h> #include <vw/Stereo/EMSubpixelCorrelatorView.h> #include <asp/Core/LocalHomography.h> #include <vw/Stereo/DisparityMap.h> using namespace vw; using namespace vw::stereo; using namespace asp; namespace vw { template<> struct PixelFormatID<PixelMask<Vector<float, 5> > > { static const PixelFormatEnum value = VW_PIXEL_GENERIC_6_CHANNEL; }; } template <class Image1T, class Image2T> ImageViewRef<PixelMask<Vector2f> > refine_disparity(Image1T const& left_image, Image2T const& right_image, ImageViewRef< PixelMask<Vector2i> > const& integer_disp, Options const& opt){ ImageViewRef<PixelMask<Vector2f> > refined_disp = pixel_cast<PixelMask<Vector2f> >(integer_disp); if (stereo_settings().subpixel_mode == 0) { // Do nothing } else if (stereo_settings().subpixel_mode == 1) { // Parabola vw_out() << "\t--> Using parabola subpixel mode.\n"; if (stereo_settings().pre_filter_mode == 2) { vw_out() << "\t--> Using LOG pre-processing filter with " << stereo_settings().slogW << " sigma blur.\n"; typedef stereo::LaplacianOfGaussian PreFilter; refined_disp = parabola_subpixel( integer_disp, left_image, right_image, PreFilter(stereo_settings().slogW), stereo_settings().subpixel_kernel ); } else if (stereo_settings().pre_filter_mode == 1) { vw_out() << "\t--> Using Subtracted Mean pre-processing filter with " << stereo_settings().slogW << " sigma blur.\n"; typedef stereo::SubtractedMean PreFilter; refined_disp = parabola_subpixel( integer_disp, left_image, right_image, PreFilter(stereo_settings().slogW), stereo_settings().subpixel_kernel ); } else { vw_out() << "\t--> NO preprocessing" << std::endl; typedef stereo::NullOperation PreFilter; refined_disp = parabola_subpixel( integer_disp, left_image, right_image, PreFilter(), stereo_settings().subpixel_kernel ); } } else if (stereo_settings().subpixel_mode == 2) { // Bayes EM vw_out() << "\t--> Using affine adaptive subpixel mode\n"; vw_out() << "\t--> Forcing use of LOG filter with " << stereo_settings().slogW << " sigma blur.\n"; typedef stereo::LaplacianOfGaussian PreFilter; refined_disp = bayes_em_subpixel( integer_disp, left_image, right_image, PreFilter(stereo_settings().slogW), stereo_settings().subpixel_kernel, stereo_settings().subpixel_max_levels ); } else if (stereo_settings().subpixel_mode == 3) { // Affine and Bayes subpixel refinement always use the // LogPreprocessingFilter... vw_out() << "\t--> Using EM Subpixel mode " << stereo_settings().subpixel_mode << std::endl; vw_out() << "\t--> Mode 3 does internal preprocessing;" << " settings will be ignored. " << std::endl; typedef stereo::EMSubpixelCorrelatorView<float32> EMCorrelator; EMCorrelator em_correlator(channels_to_planes(left_image), channels_to_planes(right_image), pixel_cast<PixelMask<Vector2f> >(integer_disp), -1); em_correlator.set_em_iter_max(stereo_settings().subpixel_em_iter); em_correlator.set_inner_iter_max(stereo_settings().subpixel_affine_iter); em_correlator.set_kernel_size(stereo_settings().subpixel_kernel); em_correlator.set_pyramid_levels(stereo_settings().subpixel_pyramid_levels); DiskImageResourceOpenEXR em_disparity_map_rsrc(opt.out_prefix + "-F6.exr", em_correlator.format()); block_write_image(em_disparity_map_rsrc, em_correlator, TerminalProgressCallback("asp", "\t--> EM Refinement :")); DiskImageResource *em_disparity_map_rsrc_2 = DiskImageResourceOpenEXR::construct_open(opt.out_prefix + "-F6.exr"); DiskImageView<PixelMask<Vector<float, 5> > > em_disparity_disk_image(em_disparity_map_rsrc_2); ImageViewRef<Vector<float, 3> > disparity_uncertainty = per_pixel_filter(em_disparity_disk_image, EMCorrelator::ExtractUncertaintyFunctor()); ImageViewRef<float> spectral_uncertainty = per_pixel_filter(disparity_uncertainty, EMCorrelator::SpectralRadiusUncertaintyFunctor()); write_image(opt.out_prefix+"-US.tif", spectral_uncertainty); write_image(opt.out_prefix+"-U.tif", disparity_uncertainty); refined_disp = per_pixel_filter(em_disparity_disk_image, EMCorrelator::ExtractDisparityFunctor()); } else { vw_out() << "\t--> Invalid Subpixel mode selection: " << stereo_settings().subpixel_mode << std::endl; vw_out() << "\t--> Doing nothing\n"; } return refined_disp; } // Perform refinement in each tile. If using local homography, // apply the local homography transform for the given tile // to the right image before doing refinement in that tile. template <class Image1T, class Image2T, class SeedDispT> class PerTileRfne: public ImageViewBase<PerTileRfne<Image1T, Image2T, SeedDispT> >{ Image1T m_left_image; Image2T m_right_image; ImageViewRef<uint8> m_right_mask; SeedDispT m_integer_disp; SeedDispT m_sub_disp; ImageView<Matrix3x3> m_local_hom; Options const& m_opt; Vector2 m_upscale_factor; public: PerTileRfne( ImageViewBase<Image1T> const& left_image, ImageViewBase<Image2T> const& right_image, ImageViewRef<uint8> const& right_mask, ImageViewBase<SeedDispT> const& integer_disp, ImageViewBase<SeedDispT> const& sub_disp, ImageView<Matrix3x3> const& local_hom, Options const& opt): m_left_image(left_image.impl()), m_right_image(right_image.impl()), m_right_mask(right_mask), m_integer_disp( integer_disp.impl() ), m_sub_disp( sub_disp.impl() ), m_local_hom(local_hom), m_opt(opt){ m_upscale_factor = Vector2(double(m_left_image.impl().cols()) / m_sub_disp.cols(), double(m_left_image.impl().rows()) / m_sub_disp.rows()); } // Image View interface typedef PixelMask<Vector2f> pixel_type; typedef pixel_type result_type; typedef ProceduralPixelAccessor<PerTileRfne> pixel_accessor; inline int32 cols() const { return m_left_image.cols(); } inline int32 rows() const { return m_left_image.rows(); } inline int32 planes() const { return 1; } inline pixel_accessor origin() const { return pixel_accessor( *this, 0, 0 ); } inline pixel_type operator()( double /*i*/, double /*j*/, int32 /*p*/ = 0 ) const { vw_throw(NoImplErr() << "PerTileRfne::operator()(...) is not implemented"); return pixel_type(); } typedef CropView<ImageView<pixel_type> > prerasterize_type; inline prerasterize_type prerasterize(BBox2i const& bbox) const { // We do stereo only in left_image_crop_win. Skip the current tile if // it does not intersect this region. BBox2i left_image_crop_win = m_opt.left_image_crop_win; BBox2i intersection = bbox; intersection.crop(left_image_crop_win); if (intersection.empty()){ return prerasterize_type(ImageView<pixel_type>(bbox.width(), bbox.height()), -bbox.min().x(), -bbox.min().y(), cols(), rows() ); } ImageView<pixel_type> tile_disparity; if (stereo_settings().seed_mode > 0 && stereo_settings().use_local_homography){ int ts = Options::corr_tile_size(); Matrix<double> lowres_hom = m_local_hom(bbox.min().x()/ts, bbox.min().y()/ts); Vector3 upscale( m_upscale_factor[0], m_upscale_factor[1], 1 ); Vector3 dnscale( 1.0/m_upscale_factor[0], 1.0/m_upscale_factor[1], 1 ); Matrix<double> fullres_hom = diagonal_matrix(upscale)*lowres_hom*diagonal_matrix(dnscale); // Must transform the right image by the local disparity // to be in the same conditions as for stereo correlation. typedef typename Image2T::pixel_type right_pix_type; ImageViewRef< PixelMask<right_pix_type> > right_trans_masked_img = transform (copy_mask( m_right_image.impl(), create_mask(m_right_mask) ), HomographyTransform(fullres_hom), m_left_image.impl().cols(), m_left_image.impl().rows()); ImageViewRef<right_pix_type> right_trans_img = apply_mask(right_trans_masked_img); tile_disparity = crop(refine_disparity(m_left_image, right_trans_img, m_integer_disp, m_opt), bbox); // Must undo the local homography transform bool do_round = false; // don't round floating point disparities tile_disparity = transform_disparities(do_round, bbox, inverse(fullres_hom), tile_disparity); }else{ tile_disparity = crop(refine_disparity(m_left_image, m_right_image, m_integer_disp, m_opt), bbox); } prerasterize_type disparity = prerasterize_type(tile_disparity, -bbox.min().x(), -bbox.min().y(), cols(), rows() ); // Set to invalid the disparity outside left_image_crop_win. for (int col = bbox.min().x(); col < bbox.max().x(); col++){ for (int row = bbox.min().y(); row < bbox.max().y(); row++){ if (!left_image_crop_win.contains(Vector2(col, row))){ disparity(col, row) = pixel_type(); } } } return disparity; } template <class DestT> inline void rasterize(DestT const& dest, BBox2i bbox) const { vw::rasterize(prerasterize(bbox), dest, bbox); } }; template <class Image1T, class Image2T, class SeedDispT> PerTileRfne<Image1T, Image2T, SeedDispT> per_tile_rfne( ImageViewBase<Image1T> const& left, ImageViewBase<Image2T> const& right, ImageViewRef<uint8> const& right_mask, ImageViewBase<SeedDispT> const& integer_disp, ImageViewBase<SeedDispT> const& sub_disp, ImageView<Matrix3x3> const& local_hom, Options const& opt) { typedef PerTileRfne<Image1T, Image2T, SeedDispT> return_type; return return_type( left.impl(), right.impl(), right_mask, integer_disp.impl(), sub_disp.impl(), local_hom, opt ); } void stereo_refinement( Options const& opt ) { vw_out() << "\n[ " << current_posix_time_string() << " ] : Stage 2 --> REFINEMENT \n"; ImageViewRef<PixelGray<float> > left_disk_image, right_disk_image; ImageViewRef<uint8> right_mask; ImageViewRef<PixelMask<Vector2i> > integer_disp; ImageViewRef<PixelMask<Vector2i> > sub_disp; ImageView<Matrix3x3> local_hom; try { left_disk_image = DiskImageView< PixelGray<float> >(opt.out_prefix+"-L.tif"); right_disk_image = DiskImageView< PixelGray<float> >(opt.out_prefix+"-R.tif"); right_mask = DiskImageView<uint8>(opt.out_prefix + "-rMask.tif"); integer_disp = DiskImageView< PixelMask<Vector2i> >(opt.out_prefix + "-D.tif"); if ( stereo_settings().seed_mode > 0 && stereo_settings().use_local_homography ){ sub_disp = DiskImageView<PixelMask<Vector2i> >(opt.out_prefix+"-D_sub.tif"); std::string local_hom_file = opt.out_prefix + "-local_hom.txt"; read_local_homographies(local_hom_file, local_hom); } } catch (IOErr const& e) { vw_throw( ArgumentErr() << "\nUnable to start at refinement stage -- could not read input files.\n" << e.what() << "\nExiting.\n\n" ); } ImageViewRef< PixelMask<Vector2f> > refined_disp = per_tile_rfne(left_disk_image, right_disk_image, right_mask, integer_disp, sub_disp, local_hom, opt); asp::block_write_gdal_image( opt.out_prefix + "-RD.tif", refined_disp, opt, TerminalProgressCallback("asp", "\t--> Refinement :") ); } int main(int argc, char* argv[]) { stereo_register_sessions(); Options opt; try { handle_arguments( argc, argv, opt, SubpixelDescription() ); // Internal Processes //--------------------------------------------------------- stereo_refinement( opt ); vw_out() << "\n[ " << current_posix_time_string() << " ] : REFINEMENT FINISHED \n"; } ASP_STANDARD_CATCHES; return 0; } <commit_msg>stereo_rfne: Print messages just once<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2012, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ /// \file stereo_rfne.cc /// //#define USE_GRAPHICS #include <asp/Tools/stereo.h> #include <vw/Stereo/PreFilter.h> #include <vw/Stereo/CostFunctions.h> #include <vw/Stereo/SubpixelView.h> #include <vw/Stereo/EMSubpixelCorrelatorView.h> #include <asp/Core/LocalHomography.h> #include <vw/Stereo/DisparityMap.h> using namespace vw; using namespace vw::stereo; using namespace asp; namespace vw { template<> struct PixelFormatID<PixelMask<Vector<float, 5> > > { static const PixelFormatEnum value = VW_PIXEL_GENERIC_6_CHANNEL; }; } template <class Image1T, class Image2T> ImageViewRef<PixelMask<Vector2f> > refine_disparity(Image1T const& left_image, Image2T const& right_image, ImageViewRef< PixelMask<Vector2i> > const& integer_disp, Options const& opt, bool verbose){ ImageViewRef<PixelMask<Vector2f> > refined_disp = pixel_cast<PixelMask<Vector2f> >(integer_disp); if (stereo_settings().subpixel_mode == 0) { // Do nothing } else if (stereo_settings().subpixel_mode == 1) { // Parabola if (verbose) vw_out() << "\t--> Using parabola subpixel mode.\n"; if (stereo_settings().pre_filter_mode == 2) { if (verbose) vw_out() << "\t--> Using LOG pre-processing filter with " << stereo_settings().slogW << " sigma blur.\n"; typedef stereo::LaplacianOfGaussian PreFilter; refined_disp = parabola_subpixel( integer_disp, left_image, right_image, PreFilter(stereo_settings().slogW), stereo_settings().subpixel_kernel ); } else if (stereo_settings().pre_filter_mode == 1) { if (verbose) vw_out() << "\t--> Using Subtracted Mean pre-processing filter with " << stereo_settings().slogW << " sigma blur.\n"; typedef stereo::SubtractedMean PreFilter; refined_disp = parabola_subpixel( integer_disp, left_image, right_image, PreFilter(stereo_settings().slogW), stereo_settings().subpixel_kernel ); } else { if (verbose) vw_out() << "\t--> NO preprocessing" << std::endl; typedef stereo::NullOperation PreFilter; refined_disp = parabola_subpixel( integer_disp, left_image, right_image, PreFilter(), stereo_settings().subpixel_kernel ); } } else if (stereo_settings().subpixel_mode == 2) { // Bayes EM if (verbose){ vw_out() << "\t--> Using affine adaptive subpixel mode\n"; vw_out() << "\t--> Forcing use of LOG filter with " << stereo_settings().slogW << " sigma blur.\n"; } typedef stereo::LaplacianOfGaussian PreFilter; refined_disp = bayes_em_subpixel( integer_disp, left_image, right_image, PreFilter(stereo_settings().slogW), stereo_settings().subpixel_kernel, stereo_settings().subpixel_max_levels ); } else if (stereo_settings().subpixel_mode == 3) { // Affine and Bayes subpixel refinement always use the // LogPreprocessingFilter... if (verbose){ vw_out() << "\t--> Using EM Subpixel mode " << stereo_settings().subpixel_mode << std::endl; vw_out() << "\t--> Mode 3 does internal preprocessing;" << " settings will be ignored. " << std::endl; } typedef stereo::EMSubpixelCorrelatorView<float32> EMCorrelator; EMCorrelator em_correlator(channels_to_planes(left_image), channels_to_planes(right_image), pixel_cast<PixelMask<Vector2f> >(integer_disp), -1); em_correlator.set_em_iter_max(stereo_settings().subpixel_em_iter); em_correlator.set_inner_iter_max(stereo_settings().subpixel_affine_iter); em_correlator.set_kernel_size(stereo_settings().subpixel_kernel); em_correlator.set_pyramid_levels(stereo_settings().subpixel_pyramid_levels); DiskImageResourceOpenEXR em_disparity_map_rsrc(opt.out_prefix + "-F6.exr", em_correlator.format()); block_write_image(em_disparity_map_rsrc, em_correlator, TerminalProgressCallback("asp", "\t--> EM Refinement :")); DiskImageResource *em_disparity_map_rsrc_2 = DiskImageResourceOpenEXR::construct_open(opt.out_prefix + "-F6.exr"); DiskImageView<PixelMask<Vector<float, 5> > > em_disparity_disk_image(em_disparity_map_rsrc_2); ImageViewRef<Vector<float, 3> > disparity_uncertainty = per_pixel_filter(em_disparity_disk_image, EMCorrelator::ExtractUncertaintyFunctor()); ImageViewRef<float> spectral_uncertainty = per_pixel_filter(disparity_uncertainty, EMCorrelator::SpectralRadiusUncertaintyFunctor()); write_image(opt.out_prefix+"-US.tif", spectral_uncertainty); write_image(opt.out_prefix+"-U.tif", disparity_uncertainty); refined_disp = per_pixel_filter(em_disparity_disk_image, EMCorrelator::ExtractDisparityFunctor()); } else { if (verbose) { vw_out() << "\t--> Invalid Subpixel mode selection: " << stereo_settings().subpixel_mode << std::endl; vw_out() << "\t--> Doing nothing\n"; } } return refined_disp; } // Perform refinement in each tile. If using local homography, // apply the local homography transform for the given tile // to the right image before doing refinement in that tile. template <class Image1T, class Image2T, class SeedDispT> class PerTileRfne: public ImageViewBase<PerTileRfne<Image1T, Image2T, SeedDispT> >{ Image1T m_left_image; Image2T m_right_image; ImageViewRef<uint8> m_right_mask; SeedDispT m_integer_disp; SeedDispT m_sub_disp; ImageView<Matrix3x3> m_local_hom; Options const& m_opt; Vector2 m_upscale_factor; public: PerTileRfne( ImageViewBase<Image1T> const& left_image, ImageViewBase<Image2T> const& right_image, ImageViewRef<uint8> const& right_mask, ImageViewBase<SeedDispT> const& integer_disp, ImageViewBase<SeedDispT> const& sub_disp, ImageView<Matrix3x3> const& local_hom, Options const& opt): m_left_image(left_image.impl()), m_right_image(right_image.impl()), m_right_mask(right_mask), m_integer_disp( integer_disp.impl() ), m_sub_disp( sub_disp.impl() ), m_local_hom(local_hom), m_opt(opt){ m_upscale_factor = Vector2(double(m_left_image.impl().cols()) / m_sub_disp.cols(), double(m_left_image.impl().rows()) / m_sub_disp.rows()); } // Image View interface typedef PixelMask<Vector2f> pixel_type; typedef pixel_type result_type; typedef ProceduralPixelAccessor<PerTileRfne> pixel_accessor; inline int32 cols() const { return m_left_image.cols(); } inline int32 rows() const { return m_left_image.rows(); } inline int32 planes() const { return 1; } inline pixel_accessor origin() const { return pixel_accessor( *this, 0, 0 ); } inline pixel_type operator()( double /*i*/, double /*j*/, int32 /*p*/ = 0 ) const { vw_throw(NoImplErr() << "PerTileRfne::operator()(...) is not implemented"); return pixel_type(); } typedef CropView<ImageView<pixel_type> > prerasterize_type; inline prerasterize_type prerasterize(BBox2i const& bbox) const { // We do stereo only in left_image_crop_win. Skip the current tile if // it does not intersect this region. BBox2i left_image_crop_win = m_opt.left_image_crop_win; BBox2i intersection = bbox; intersection.crop(left_image_crop_win); if (intersection.empty()){ return prerasterize_type(ImageView<pixel_type>(bbox.width(), bbox.height()), -bbox.min().x(), -bbox.min().y(), cols(), rows() ); } ImageView<pixel_type> tile_disparity; bool verbose = false; if (stereo_settings().seed_mode > 0 && stereo_settings().use_local_homography){ int ts = Options::corr_tile_size(); Matrix<double> lowres_hom = m_local_hom(bbox.min().x()/ts, bbox.min().y()/ts); Vector3 upscale( m_upscale_factor[0], m_upscale_factor[1], 1 ); Vector3 dnscale( 1.0/m_upscale_factor[0], 1.0/m_upscale_factor[1], 1 ); Matrix<double> fullres_hom = diagonal_matrix(upscale)*lowres_hom*diagonal_matrix(dnscale); // Must transform the right image by the local disparity // to be in the same conditions as for stereo correlation. typedef typename Image2T::pixel_type right_pix_type; ImageViewRef< PixelMask<right_pix_type> > right_trans_masked_img = transform (copy_mask( m_right_image.impl(), create_mask(m_right_mask) ), HomographyTransform(fullres_hom), m_left_image.impl().cols(), m_left_image.impl().rows()); ImageViewRef<right_pix_type> right_trans_img = apply_mask(right_trans_masked_img); tile_disparity = crop(refine_disparity(m_left_image, right_trans_img, m_integer_disp, m_opt, verbose), bbox); // Must undo the local homography transform bool do_round = false; // don't round floating point disparities tile_disparity = transform_disparities(do_round, bbox, inverse(fullres_hom), tile_disparity); }else{ tile_disparity = crop(refine_disparity(m_left_image, m_right_image, m_integer_disp, m_opt, verbose), bbox); } prerasterize_type disparity = prerasterize_type(tile_disparity, -bbox.min().x(), -bbox.min().y(), cols(), rows() ); // Set to invalid the disparity outside left_image_crop_win. for (int col = bbox.min().x(); col < bbox.max().x(); col++){ for (int row = bbox.min().y(); row < bbox.max().y(); row++){ if (!left_image_crop_win.contains(Vector2(col, row))){ disparity(col, row) = pixel_type(); } } } return disparity; } template <class DestT> inline void rasterize(DestT const& dest, BBox2i bbox) const { vw::rasterize(prerasterize(bbox), dest, bbox); } }; template <class Image1T, class Image2T, class SeedDispT> PerTileRfne<Image1T, Image2T, SeedDispT> per_tile_rfne( ImageViewBase<Image1T> const& left, ImageViewBase<Image2T> const& right, ImageViewRef<uint8> const& right_mask, ImageViewBase<SeedDispT> const& integer_disp, ImageViewBase<SeedDispT> const& sub_disp, ImageView<Matrix3x3> const& local_hom, Options const& opt) { typedef PerTileRfne<Image1T, Image2T, SeedDispT> return_type; return return_type( left.impl(), right.impl(), right_mask, integer_disp.impl(), sub_disp.impl(), local_hom, opt ); } void stereo_refinement( Options const& opt ) { vw_out() << "\n[ " << current_posix_time_string() << " ] : Stage 2 --> REFINEMENT \n"; ImageViewRef<PixelGray<float> > left_disk_image, right_disk_image; ImageViewRef<uint8> right_mask; ImageViewRef<PixelMask<Vector2i> > integer_disp; ImageViewRef<PixelMask<Vector2i> > sub_disp; ImageView<Matrix3x3> local_hom; try { left_disk_image = DiskImageView< PixelGray<float> >(opt.out_prefix+"-L.tif"); right_disk_image = DiskImageView< PixelGray<float> >(opt.out_prefix+"-R.tif"); right_mask = DiskImageView<uint8>(opt.out_prefix + "-rMask.tif"); integer_disp = DiskImageView< PixelMask<Vector2i> >(opt.out_prefix + "-D.tif"); if ( stereo_settings().seed_mode > 0 && stereo_settings().use_local_homography ){ sub_disp = DiskImageView<PixelMask<Vector2i> >(opt.out_prefix+"-D_sub.tif"); std::string local_hom_file = opt.out_prefix + "-local_hom.txt"; read_local_homographies(local_hom_file, local_hom); } } catch (IOErr const& e) { vw_throw( ArgumentErr() << "\nUnable to start at refinement stage -- could not read input files.\n" << e.what() << "\nExiting.\n\n" ); } // The whole goal of this block it to go through the motions of // refining disparity solely for the purpose of printing // the relevant messages. bool verbose = true; ImageView<PixelGray<float> > left_dummy, right_dummy; ImageViewRef<PixelMask<Vector2i> > dummy_disp; refine_disparity(left_dummy, right_dummy, dummy_disp, opt, verbose); ImageViewRef< PixelMask<Vector2f> > refined_disp = per_tile_rfne(left_disk_image, right_disk_image, right_mask, integer_disp, sub_disp, local_hom, opt); asp::block_write_gdal_image( opt.out_prefix + "-RD.tif", refined_disp, opt, TerminalProgressCallback("asp", "\t--> Refinement :") ); } int main(int argc, char* argv[]) { stereo_register_sessions(); Options opt; try { handle_arguments( argc, argv, opt, SubpixelDescription() ); // Internal Processes //--------------------------------------------------------- stereo_refinement( opt ); vw_out() << "\n[ " << current_posix_time_string() << " ] : REFINEMENT FINISHED \n"; } ASP_STANDARD_CATCHES; return 0; } <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_Serial.h" #include "axl_sys_Event.h" namespace axl { namespace io { //.............................................................................. #if (_AXL_OS_WIN) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t accessMode = (flags & FileFlag_ReadOnly) ? GENERIC_READ : (flags & FileFlag_WriteOnly) ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE; uint_t flagsAttributes = (flags & FileFlag_Asynchronous) ? FILE_FLAG_OVERLAPPED : 0; return m_serial.open (name, accessMode, flagsAttributes); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; dcb.fBinary = TRUE; dcb.fDsrSensitivity = FALSE; dcb.fDtrControl = DTR_CONTROL_DISABLE; if (mask & SerialSettingId_BaudRate) dcb.BaudRate = settings->m_baudRate; if (mask & SerialSettingId_DataBits) dcb.ByteSize = settings->m_dataBits; if (mask & SerialSettingId_StopBits) dcb.StopBits = settings->m_stopBits; if (mask & SerialSettingId_Parity) { dcb.fParity = settings->m_parity != SerialParity_None; dcb.Parity = settings->m_parity; } if (mask & SerialSettingId_FlowControl) switch (settings->m_flowControl) { case SerialFlowControl_None: dcb.fOutxCtsFlow = FALSE; dcb.fRtsControl = RTS_CONTROL_DISABLE; break; case SerialFlowControl_RtsCts: dcb.fOutxCtsFlow = TRUE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; break; case SerialFlowControl_XonXoff: dcb.fOutX = TRUE; dcb.fInX = TRUE; break; } if (!(mask & SerialSettingId_ReadInterval)) return m_serial.setSettings (&dcb); COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = settings->m_readInterval == 0 ? -1 : settings->m_readInterval == -1 ? 0 : settings->m_readInterval; return m_serial.setSettings (&dcb) && m_serial.setTimeouts (&timeouts); } bool Serial::getSettings (SerialSettings* settings) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; settings->setDcb (&dcb); return true; } uint_t Serial::getStatusLines () { uint_t lines = m_serial.getStatusLines (); return lines != -1 ? (lines & 0xf0) >> 4 : -1; } #elif (_AXL_OS_POSIX) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t posixFlags = (flags & FileFlag_ReadOnly) ? O_RDONLY : (flags & FileFlag_WriteOnly) ? O_WRONLY : O_RDWR; if (flags & FileFlag_Asynchronous) posixFlags |= O_NONBLOCK; posixFlags |= O_NOCTTY; return m_serial.open (name, posixFlags); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; if (mask & SerialSettingId_BaudRate) { speed_t speed; switch (settings->m_baudRate) { case 110: speed = B110; break; case 300: speed = B300; break; case 600: speed = B600; break; case 1200: speed = B1200; break; case 2400: speed = B2400; break; case 4800: speed = B4800; break; case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; default: // TODO: custom baud rate (currently fall back to 38400) speed = B38400; } cfsetispeed (&attr, speed); cfsetospeed (&attr, speed); } if (mask & SerialSettingId_DataBits) { attr.c_cflag &= ~CSIZE; switch (settings->m_dataBits) { case 5: attr.c_cflag |= CS5; break; case 6: attr.c_cflag |= CS6; break; case 7: attr.c_cflag |= CS7; break; case 8: default: attr.c_cflag |= CS8; break; } } if (mask & SerialSettingId_StopBits) { if (settings->m_stopBits == SerialStopBits_2) attr.c_cflag |= CSTOPB; else attr.c_cflag &= ~CSTOPB; } if (mask & SerialSettingId_Parity) { attr.c_iflag &= ~(PARMRK | INPCK); attr.c_iflag |= IGNPAR; switch (settings->m_parity) { case SerialParity_None: attr.c_cflag &= ~PARENB; break; case SerialParity_Odd: attr.c_cflag |= PARENB | PARODD; break; case SerialParity_Even: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB; break; #ifdef CMSPAR case SerialParity_Mark: attr.c_cflag |= PARENB | CMSPAR | PARODD; break; case SerialParity_Space: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB | CMSPAR; break; #endif default: attr.c_cflag |= PARENB; attr.c_iflag |= PARMRK | INPCK; attr.c_iflag &= ~IGNPAR; } } if (mask & SerialSettingId_FlowControl) switch (settings->m_flowControl) { case SerialFlowControl_RtsCts: attr.c_cflag |= CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); break; case SerialFlowControl_XonXoff: attr.c_cflag &= ~CRTSCTS; attr.c_iflag |= IXON | IXOFF | IXANY; break; case SerialFlowControl_None: default: attr.c_cflag &= ~CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); } // ensure some extra default flags attr.c_cflag |= CREAD | CLOCAL; attr.c_lflag = 0; attr.c_oflag = 0; attr.c_cc [VTIME] = 0; attr.c_cc [VMIN] = 1; return m_serial.setAttr (&attr); } bool Serial::getSettings (SerialSettings* settings) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; settings->setAttr (&attr); return true; } uint_t Serial::getStatusLines () { uint_t result = m_serial.getStatusLines (); if (result == -1) return -1; uint_t lines = 0; if (result & TIOCM_CTS) lines |= SerialStatusLine_Cts; if (result & TIOCM_DSR) lines |= SerialStatusLine_Dsr; if (result & TIOCM_RNG) lines |= SerialStatusLine_Ring; if (result & TIOCM_CAR) lines |= SerialStatusLine_Dcd; return lines; } #endif //.............................................................................. } // namespace io } // namespace axl <commit_msg>[axl_io] clear "bad" termios attributes; apply read interval via c_cc [VTIME]<commit_after>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_Serial.h" #include "axl_sys_Event.h" namespace axl { namespace io { //.............................................................................. #if (_AXL_OS_WIN) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t accessMode = (flags & FileFlag_ReadOnly) ? GENERIC_READ : (flags & FileFlag_WriteOnly) ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE; uint_t flagsAttributes = (flags & FileFlag_Asynchronous) ? FILE_FLAG_OVERLAPPED : 0; return m_serial.open (name, accessMode, flagsAttributes); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; dcb.fBinary = TRUE; dcb.fDsrSensitivity = FALSE; dcb.fDtrControl = DTR_CONTROL_DISABLE; if (mask & SerialSettingId_BaudRate) dcb.BaudRate = settings->m_baudRate; if (mask & SerialSettingId_DataBits) dcb.ByteSize = settings->m_dataBits; if (mask & SerialSettingId_StopBits) dcb.StopBits = settings->m_stopBits; if (mask & SerialSettingId_Parity) { dcb.fParity = settings->m_parity != SerialParity_None; dcb.Parity = settings->m_parity; } if (mask & SerialSettingId_FlowControl) switch (settings->m_flowControl) { case SerialFlowControl_None: dcb.fOutxCtsFlow = FALSE; dcb.fRtsControl = RTS_CONTROL_DISABLE; break; case SerialFlowControl_RtsCts: dcb.fOutxCtsFlow = TRUE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; break; case SerialFlowControl_XonXoff: dcb.fOutX = TRUE; dcb.fInX = TRUE; break; } if (!(mask & SerialSettingId_ReadInterval)) return m_serial.setSettings (&dcb); COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = settings->m_readInterval == 0 ? -1 : settings->m_readInterval == -1 ? 0 : settings->m_readInterval; return m_serial.setSettings (&dcb) && m_serial.setTimeouts (&timeouts); } bool Serial::getSettings (SerialSettings* settings) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; settings->setDcb (&dcb); return true; } uint_t Serial::getStatusLines () { uint_t lines = m_serial.getStatusLines (); return lines != -1 ? (lines & 0xf0) >> 4 : -1; } #elif (_AXL_OS_POSIX) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t posixFlags = (flags & FileFlag_ReadOnly) ? O_RDONLY : (flags & FileFlag_WriteOnly) ? O_WRONLY : O_RDWR; if (flags & FileFlag_Asynchronous) posixFlags |= O_NONBLOCK; posixFlags |= O_NOCTTY; return m_serial.open (name, posixFlags); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; if (mask & SerialSettingId_BaudRate) { speed_t speed; switch (settings->m_baudRate) { case 110: speed = B110; break; case 300: speed = B300; break; case 600: speed = B600; break; case 1200: speed = B1200; break; case 2400: speed = B2400; break; case 4800: speed = B4800; break; case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; default: // TODO: custom baud rate (currently fall back to 38400) speed = B38400; } cfsetispeed (&attr, speed); cfsetospeed (&attr, speed); } if (mask & SerialSettingId_DataBits) { attr.c_cflag &= ~CSIZE; switch (settings->m_dataBits) { case 5: attr.c_cflag |= CS5; break; case 6: attr.c_cflag |= CS6; break; case 7: attr.c_cflag |= CS7; break; case 8: default: attr.c_cflag |= CS8; break; } } if (mask & SerialSettingId_StopBits) { if (settings->m_stopBits == SerialStopBits_2) attr.c_cflag |= CSTOPB; else attr.c_cflag &= ~CSTOPB; } if (mask & SerialSettingId_Parity) { attr.c_iflag &= ~(PARMRK | INPCK); attr.c_iflag |= IGNPAR; switch (settings->m_parity) { case SerialParity_None: attr.c_cflag &= ~PARENB; break; case SerialParity_Odd: attr.c_cflag |= PARENB | PARODD; break; case SerialParity_Even: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB; break; #ifdef CMSPAR case SerialParity_Mark: attr.c_cflag |= PARENB | CMSPAR | PARODD; break; case SerialParity_Space: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB | CMSPAR; break; #endif default: attr.c_cflag |= PARENB; attr.c_iflag |= PARMRK | INPCK; attr.c_iflag &= ~IGNPAR; } } if (mask & SerialSettingId_FlowControl) switch (settings->m_flowControl) { case SerialFlowControl_RtsCts: attr.c_cflag |= CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); break; case SerialFlowControl_XonXoff: attr.c_cflag &= ~CRTSCTS; attr.c_iflag |= IXON | IXOFF | IXANY; break; case SerialFlowControl_None: default: attr.c_cflag &= ~CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); } // ensure some extra default flags attr.c_iflag |= IGNBRK; attr.c_iflag &= ~(BRKINT | IGNCR | INLCR | ICRNL | ISTRIP); attr.c_oflag = 0; attr.c_cflag |= CREAD | CLOCAL; attr.c_lflag = 0; for (size_t i = 0; i < countof (attr.c_cc); i++) attr.c_cc [i] = _POSIX_VDISABLE; attr.c_cc [VTIME] = settings->m_readInterval / 100; // milliseconds -> deciseconds attr.c_cc [VMIN] = 1; return m_serial.setAttr (&attr); } bool Serial::getSettings (SerialSettings* settings) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; settings->setAttr (&attr); return true; } uint_t Serial::getStatusLines () { uint_t result = m_serial.getStatusLines (); if (result == -1) return -1; uint_t lines = 0; if (result & TIOCM_CTS) lines |= SerialStatusLine_Cts; if (result & TIOCM_DSR) lines |= SerialStatusLine_Dsr; if (result & TIOCM_RNG) lines |= SerialStatusLine_Ring; if (result & TIOCM_CAR) lines |= SerialStatusLine_Dcd; return lines; } #endif //.............................................................................. } // namespace io } // namespace axl <|endoftext|>
<commit_before>/* * This source file is part of ARK * For the latest info, see https://github.com/ArkNX * * Copyright (c) 2013-2019 ArkNX authors. * * 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. * */ #pragma once #include "base/AFSingleton.hpp" #include "base/AFMap.hpp" #include "base/AFArrayMap.hpp" #include "base/AFDateTime.hpp" #include "base/AFXml.hpp" #include "base/AFDynLib.hpp" #include "interface/AFIPlugin.hpp" #include "interface/AFIModule.hpp" namespace ark { class AFPluginManager final : public AFSingleton<AFPluginManager> { public: AFPluginManager() : timestamp_(AFDateTime::GetNowTime()) { } bool Start() { ARK_ASSERT_RET_VAL(Init(), false); ARK_ASSERT_RET_VAL(PostInit(), false); ARK_ASSERT_RET_VAL(CheckConfig(), false); ARK_ASSERT_RET_VAL(PreUpdate(), false); return true; } bool Stop() { PreShut(); Shut(); return true; } bool Update() { timestamp_ = AFDateTime::GetNowTime(); // Just loop the modules which have update function. for (const auto& iter : module_updates_) { AFIModule* pModule = iter.second; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->Update(); } return true; } ////////////////////////////////////////////////////////////////////////// template<typename DerivedModule> DerivedModule* FindModule() { AFIModule* pLogicModule = FindModule(GET_CLASS_NAME(DerivedModule)); ARK_ASSERT_RET_VAL(pLogicModule != nullptr, nullptr); if (!std::is_base_of<AFIModule, DerivedModule>::value) { return nullptr; } DerivedModule* derived_module = dynamic_cast<DerivedModule*>(pLogicModule); ARK_ASSERT_RET_VAL(derived_module != nullptr, nullptr); return derived_module; } template<typename PLUGIN_TYPE> void Register() { AFIPlugin* pNewPlugin = ARK_NEW PLUGIN_TYPE(); Register(pNewPlugin); } template<typename PLUGIN_TYPE> void Deregister() { //! Delete plugin memory in Deregister Deregister(FindPlugin(GET_CLASS_NAME(PLUGIN_TYPE))); } void AddModule(const std::string& module_name, AFIModule* module_ptr) { ARK_ASSERT_RET_NONE(FindModule(module_name) == nullptr); if (module_instances_.insert(module_name, module_ptr).second) { ordered_module_instances_.push_back(module_ptr); } } void RemoveModule(const std::string& module_name) { auto iter = module_instances_.find(module_name); if (iter == module_instances_.end()) { return; } auto module_ptr = iter->second; module_instances_.erase(module_name); auto it = std::find(ordered_module_instances_.begin(), ordered_module_instances_.end(), module_ptr); if (it != ordered_module_instances_.end()) { ordered_module_instances_.erase(it); } } bool AddUpdateModule(AFIModule* pModule) { ARK_ASSERT_RET_VAL(pModule != nullptr, false); return module_updates_.insert(pModule->GetName(), pModule).second; } void RemoveUpdateModule(const std::string& module_name) { module_updates_.erase(module_name); } int64_t GetNowTime() const { return timestamp_; } int GetBusID() const { return bus_id_; } void SetBusID(const int value) { bus_id_ = value; } const std::string& GetAppName() const { return app_name_; } void SetAppName(const std::string& value) { app_name_ = value; } const std::string& GetResPath() const { return res_path_; } void SetPluginConf(const std::string& value) { ARK_ASSERT_RET_NONE(!value.empty()); ARK_ASSERT_RET_NONE(value.find(".plugin") != string::npos); plugin_conf_path_ = value; } const std::string& GetLogPath() const { return log_path_; } void SetLogPath(const std::string& value) { log_path_ = value; } protected: void Register(AFIPlugin* plugin) { std::string plugin_name = plugin->GetPluginName(); ARK_ASSERT_RET_NONE(FindPlugin(plugin_name) == false); plugin->SetPluginManager(this); plugin_instances_.insert(plugin_name, plugin); plugin->Install(); } void Deregister(AFIPlugin* plugin) { ARK_ASSERT_RET_NONE(plugin != nullptr); auto find_plugin = FindPlugin(plugin->GetPluginName()); ARK_ASSERT_RET_NONE(find_plugin != nullptr); plugin->Uninstall(); plugin_instances_.erase(plugin->GetPluginName()); ARK_DELETE(plugin); } AFIPlugin* FindPlugin(const std::string& plugin_name) { return plugin_instances_.find_value(plugin_name); } AFIModule* FindModule(const std::string& module_name) { auto iter = module_instances_.find(module_name); return ((iter != module_instances_.end()) ? iter->second : nullptr); } bool Init() { // load plugin configuration ARK_ASSERT_RET_VAL(LoadPluginConf(), false); // load plugin dynamic libraries for (const auto& iter : ordered_plugin_names_) { bool ret = LoadPluginLibrary(iter); ARK_ASSERT_RET_VAL(ret, false); } // initialize all modules for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->Init(); } return true; } bool PostInit() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->PostInit(); } return true; } bool CheckConfig() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->CheckConfig(); } return true; } bool PreUpdate() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->PreUpdate(); } return true; } bool PreShut() { timestamp_ = AFDateTime::GetNowTime(); for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->PreShut(); } return true; } bool Shut() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->Shut(); } for (auto it : plugin_names_) { UnloadPluginLibrary(it.first); } plugin_instances_.clear(); plugin_names_.clear(); return true; } bool LoadPluginConf() { AFXml xml_doc(plugin_conf_path_); auto root_node = xml_doc.GetRootNode(); ARK_ASSERT_RET_VAL(root_node.IsValid(), false); auto plugins_node = root_node.FindNode("plugins"); ARK_ASSERT_RET_VAL(plugins_node.IsValid(), false); plugin_path_ = plugins_node.GetString("path"); ARK_ASSERT_RET_VAL(!plugin_path_.empty(), false); for (auto plugin_node = plugins_node.FindNode("plugin"); plugin_node.IsValid(); plugin_node.NextNode()) { std::string plugin_name = plugin_node.GetString("name"); if (plugin_names_.insert(std::make_pair(plugin_name, true)).second) { ordered_plugin_names_.emplace_back(plugin_name); } } auto res_node = root_node.FindNode("res"); ARK_ASSERT_RET_VAL(res_node.IsValid(), false); res_path_ = res_node.GetString("path"); ARK_ASSERT_RET_VAL(!res_path_.empty(), false); return true; } bool LoadPluginLibrary(const std::string& plugin_name) { auto iter = plugin_libs_.find(plugin_name); ARK_ASSERT_RET_VAL(iter == plugin_libs_.end(), false); AFDynLib* pLib = ARK_NEW AFDynLib(plugin_name); ARK_ASSERT_RET_VAL(pLib != nullptr, false); bool load_ret = pLib->Load(plugin_path_); if (load_ret) { plugin_libs_.insert(plugin_name, pLib); auto func = (DLL_ENTRY_PLUGIN_FUNC)pLib->GetSymbol("DllEntryPlugin"); ARK_ASSERT_RET_VAL(func != nullptr, false); func(this); return true; } else { #ifdef ARK_PLATFORM_WIN CONSOLE_LOG << "Load dynamic library[" << pLib->GetName() << "] failed, ErrorNo=[" << GetLastError() << "]" << std::endl; CONSOLE_LOG << "Load [" << pLib->GetName() << "] failed" << std::endl; assert(0); return false; #else char* error = dlerror(); if (error) { CONSOLE_LOG << stderr << " Load shared library[" << pLib->GetName() << "] failed, ErrorNo=[" << error << "]" << std::endl; CONSOLE_LOG << "Load [" << pLib->GetName() << "] failed" << std::endl; assert(0); return false; } #endif } return true; } bool UnloadPluginLibrary(const std::string& plugin_name) { auto iter = plugin_libs_.find(plugin_name); ARK_ASSERT_RET_VAL(iter != plugin_libs_.end(), false); AFDynLib* pDynLib = iter->second; ARK_ASSERT_RET_VAL(pDynLib != nullptr, false); auto func = (DLL_EXIT_PLUGIN_FUNC)pDynLib->GetSymbol("DllExitPlugin"); ARK_ASSERT_RET_VAL(func != nullptr, false); func(this); pDynLib->UnLoad(); ARK_DELETE(pDynLib); plugin_libs_.erase(plugin_name); return true; } private: // Bus id int bus_id_{0}; // Current time(ms) int64_t timestamp_{0}; // plugin so/dll file path std::string plugin_path_{}; // Resource path std::string res_path_{}; // app.plugin file path std::string plugin_conf_path_{}; // app name std::string app_name_{}; // log output path std::string log_path_{}; using DLL_ENTRY_PLUGIN_FUNC = void (*)(AFPluginManager* p); using DLL_EXIT_PLUGIN_FUNC = void (*)(AFPluginManager* p); std::map<std::string, bool> plugin_names_; std::vector<std::string> ordered_plugin_names_; // order AFMap<std::string, AFDynLib> plugin_libs_; AFMap<std::string, AFIPlugin> plugin_instances_; AFMap<std::string, AFIModule> module_instances_; std::vector<AFIModule*> ordered_module_instances_; // order AFMap<std::string, AFIModule> module_updates_; }; } // namespace ark <commit_msg>fix high version gcc error<commit_after>/* * This source file is part of ARK * For the latest info, see https://github.com/ArkNX * * Copyright (c) 2013-2019 ArkNX authors. * * 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. * */ #pragma once #include "base/AFSingleton.hpp" #include "base/AFMap.hpp" #include "base/AFArrayMap.hpp" #include "base/AFDateTime.hpp" #include "base/AFXml.hpp" #include "base/AFDynLib.hpp" #include "interface/AFIPlugin.hpp" #include "interface/AFIModule.hpp" namespace ark { class AFPluginManager final : public AFSingleton<AFPluginManager> { public: AFPluginManager() : timestamp_(AFDateTime::GetNowTime()) { } bool Start() { ARK_ASSERT_RET_VAL(Init(), false); ARK_ASSERT_RET_VAL(PostInit(), false); ARK_ASSERT_RET_VAL(CheckConfig(), false); ARK_ASSERT_RET_VAL(PreUpdate(), false); return true; } bool Stop() { PreShut(); Shut(); return true; } bool Update() { timestamp_ = AFDateTime::GetNowTime(); // Just loop the modules which have update function. for (const auto& iter : module_updates_) { AFIModule* pModule = iter.second; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->Update(); } return true; } ////////////////////////////////////////////////////////////////////////// template<typename DerivedModule> DerivedModule* FindModule() { AFIModule* pLogicModule = FindModule(GET_CLASS_NAME(DerivedModule)); ARK_ASSERT_RET_VAL(pLogicModule != nullptr, nullptr); if (!std::is_base_of<AFIModule, DerivedModule>::value) { return nullptr; } DerivedModule* derived_module = dynamic_cast<DerivedModule*>(pLogicModule); ARK_ASSERT_RET_VAL(derived_module != nullptr, nullptr); return derived_module; } template<typename PLUGIN_TYPE> void Register() { AFIPlugin* pNewPlugin = ARK_NEW PLUGIN_TYPE(); Register(pNewPlugin); } template<typename PLUGIN_TYPE> void Deregister() { //! Delete plugin memory in Deregister Deregister(FindPlugin(GET_CLASS_NAME(PLUGIN_TYPE))); } void AddModule(const std::string& module_name, AFIModule* module_ptr) { ARK_ASSERT_RET_NONE(FindModule(module_name) == nullptr); if (module_instances_.insert(module_name, module_ptr).second) { ordered_module_instances_.push_back(module_ptr); } } void RemoveModule(const std::string& module_name) { auto iter = module_instances_.find(module_name); if (iter == module_instances_.end()) { return; } auto module_ptr = iter->second; module_instances_.erase(module_name); auto it = std::find(ordered_module_instances_.begin(), ordered_module_instances_.end(), module_ptr); if (it != ordered_module_instances_.end()) { ordered_module_instances_.erase(it); } } bool AddUpdateModule(AFIModule* pModule) { ARK_ASSERT_RET_VAL(pModule != nullptr, false); return module_updates_.insert(pModule->GetName(), pModule).second; } void RemoveUpdateModule(const std::string& module_name) { module_updates_.erase(module_name); } int64_t GetNowTime() const { return timestamp_; } int GetBusID() const { return bus_id_; } void SetBusID(const int value) { bus_id_ = value; } const std::string& GetAppName() const { return app_name_; } void SetAppName(const std::string& value) { app_name_ = value; } const std::string& GetResPath() const { return res_path_; } void SetPluginConf(const std::string& value) { ARK_ASSERT_RET_NONE(!value.empty()); ARK_ASSERT_RET_NONE(value.find(".plugin") != string::npos); plugin_conf_path_ = value; } const std::string& GetLogPath() const { return log_path_; } void SetLogPath(const std::string& value) { log_path_ = value; } protected: void Register(AFIPlugin* plugin) { std::string plugin_name = plugin->GetPluginName(); ARK_ASSERT_RET_NONE(FindPlugin(plugin_name) == nullptr); plugin->SetPluginManager(this); plugin_instances_.insert(plugin_name, plugin); plugin->Install(); } void Deregister(AFIPlugin* plugin) { ARK_ASSERT_RET_NONE(plugin != nullptr); auto find_plugin = FindPlugin(plugin->GetPluginName()); ARK_ASSERT_RET_NONE(find_plugin != nullptr); plugin->Uninstall(); plugin_instances_.erase(plugin->GetPluginName()); ARK_DELETE(plugin); } AFIPlugin* FindPlugin(const std::string& plugin_name) { return plugin_instances_.find_value(plugin_name); } AFIModule* FindModule(const std::string& module_name) { auto iter = module_instances_.find(module_name); return ((iter != module_instances_.end()) ? iter->second : nullptr); } bool Init() { // load plugin configuration ARK_ASSERT_RET_VAL(LoadPluginConf(), false); // load plugin dynamic libraries for (const auto& iter : ordered_plugin_names_) { bool ret = LoadPluginLibrary(iter); ARK_ASSERT_RET_VAL(ret, false); } // initialize all modules for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->Init(); } return true; } bool PostInit() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->PostInit(); } return true; } bool CheckConfig() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->CheckConfig(); } return true; } bool PreUpdate() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->PreUpdate(); } return true; } bool PreShut() { timestamp_ = AFDateTime::GetNowTime(); for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->PreShut(); } return true; } bool Shut() { for (const auto& iter : ordered_module_instances_) { AFIModule* pModule = iter; ARK_ASSERT_CONTINUE(pModule != nullptr); pModule->Shut(); } for (auto it : plugin_names_) { UnloadPluginLibrary(it.first); } plugin_instances_.clear(); plugin_names_.clear(); return true; } bool LoadPluginConf() { AFXml xml_doc(plugin_conf_path_); auto root_node = xml_doc.GetRootNode(); ARK_ASSERT_RET_VAL(root_node.IsValid(), false); auto plugins_node = root_node.FindNode("plugins"); ARK_ASSERT_RET_VAL(plugins_node.IsValid(), false); plugin_path_ = plugins_node.GetString("path"); ARK_ASSERT_RET_VAL(!plugin_path_.empty(), false); for (auto plugin_node = plugins_node.FindNode("plugin"); plugin_node.IsValid(); plugin_node.NextNode()) { std::string plugin_name = plugin_node.GetString("name"); if (plugin_names_.insert(std::make_pair(plugin_name, true)).second) { ordered_plugin_names_.emplace_back(plugin_name); } } auto res_node = root_node.FindNode("res"); ARK_ASSERT_RET_VAL(res_node.IsValid(), false); res_path_ = res_node.GetString("path"); ARK_ASSERT_RET_VAL(!res_path_.empty(), false); return true; } bool LoadPluginLibrary(const std::string& plugin_name) { auto iter = plugin_libs_.find(plugin_name); ARK_ASSERT_RET_VAL(iter == plugin_libs_.end(), false); AFDynLib* pLib = ARK_NEW AFDynLib(plugin_name); ARK_ASSERT_RET_VAL(pLib != nullptr, false); bool load_ret = pLib->Load(plugin_path_); if (load_ret) { plugin_libs_.insert(plugin_name, pLib); auto func = (DLL_ENTRY_PLUGIN_FUNC)pLib->GetSymbol("DllEntryPlugin"); ARK_ASSERT_RET_VAL(func != nullptr, false); func(this); return true; } else { #ifdef ARK_PLATFORM_WIN CONSOLE_LOG << "Load dynamic library[" << pLib->GetName() << "] failed, ErrorNo=[" << GetLastError() << "]" << std::endl; CONSOLE_LOG << "Load [" << pLib->GetName() << "] failed" << std::endl; assert(0); return false; #else char* error = dlerror(); if (error) { CONSOLE_LOG << stderr << " Load shared library[" << pLib->GetName() << "] failed, ErrorNo=[" << error << "]" << std::endl; CONSOLE_LOG << "Load [" << pLib->GetName() << "] failed" << std::endl; assert(0); return false; } #endif } return true; } bool UnloadPluginLibrary(const std::string& plugin_name) { auto iter = plugin_libs_.find(plugin_name); ARK_ASSERT_RET_VAL(iter != plugin_libs_.end(), false); AFDynLib* pDynLib = iter->second; ARK_ASSERT_RET_VAL(pDynLib != nullptr, false); auto func = (DLL_EXIT_PLUGIN_FUNC)pDynLib->GetSymbol("DllExitPlugin"); ARK_ASSERT_RET_VAL(func != nullptr, false); func(this); pDynLib->UnLoad(); ARK_DELETE(pDynLib); plugin_libs_.erase(plugin_name); return true; } private: // Bus id int bus_id_{0}; // Current time(ms) int64_t timestamp_{0}; // plugin so/dll file path std::string plugin_path_{}; // Resource path std::string res_path_{}; // app.plugin file path std::string plugin_conf_path_{}; // app name std::string app_name_{}; // log output path std::string log_path_{}; using DLL_ENTRY_PLUGIN_FUNC = void (*)(AFPluginManager* p); using DLL_EXIT_PLUGIN_FUNC = void (*)(AFPluginManager* p); std::map<std::string, bool> plugin_names_; std::vector<std::string> ordered_plugin_names_; // order AFMap<std::string, AFDynLib> plugin_libs_; AFMap<std::string, AFIPlugin> plugin_instances_; AFMap<std::string, AFIModule> module_instances_; std::vector<AFIModule*> ordered_module_instances_; // order AFMap<std::string, AFIModule> module_updates_; }; } // namespace ark <|endoftext|>
<commit_before>#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "geometry_msgs/Vector3.h" #include "scr_proto/DiffCommand.h" #include <eigen3/Eigen/Dense> // Physical Parameters... What do to with these? double wheel_radius=4.875/2.0*.0254, axle_half_length=8.4*.0254; // Maximum loaded motor rotation speed in radians per sec double motor_max_speed=25; // Global values for velocity storage double cmd_vx=0, cmd_vy=0, cmd_vz=0, cmd_wx=0, cmd_wy=0, cmd_wz=0; // Callback to attach to command velocity subscription void commandCallback(const geometry_msgs::Twist::ConstPtr& msg){ // Pull values from message cmd_vx = msg->linear.x; cmd_wz = msg->angular.z; } // Function to calculate wheel speeds given a diff drive command // Models problem as Ax = b form Eigen::Vector2d getWheelSpeeds(double wheel_offset, double cmd_x, double cmd_th){ /* @ Params: wheel_offset -> Distance between center of wheel axle and center of wheel contact cmd_x -> Commanded forward velocity for the robot cmd_th -> Commanded angular velocity about the reference point @ Returns: x -> Eigen::Vector containing body velocities at wheel; x(0) -> Right Wheel x(1) -> Left Wheel */ // Diff Drive Dynamics Solution, vr = right wheel velocity, vl = left wheel velocity double vr = cmd_x + cmd_th * wheel_offset/2.0; double vl = cmd_x - cmd_th * wheel_offset/2.0; // Vector for result and return Eigen::Vector2d x; // Pack Vector with values and return x(0) = vr; x(1) = vl; return x; } int main(int argc, char **argv){ // Initialize Node ros::init(argc, argv, "base_controller"); // Create Nodehandle ros::NodeHandle n; // Subscribe to Command Velocity topic ros::Subscriber cmd_vel_sub = n.subscribe("cmd_vel", 1000, commandCallback); ros::Publisher motor_pub = n.advertise<scr_proto::DiffCommand>("/motor_command", 1000); ros::Rate loop_rate(10); while(ros::ok()){ // Vector for holding the linear speeds at the wheels Eigen::Vector2d wheel_linear_speeds; // Pass to linear Alg to solver or something? wheel_linear_speeds = getWheelSpeeds(axle_half_length, cmd_vx, cmd_wz); // Convert Wheel Velocities to Angular Velocities // Be careful for sign flip, as motors are not mounted symmetrically double right_wheel_omega = wheel_linear_speeds(0)/wheel_radius; double left_wheel_omega = wheel_linear_speeds(1)/wheel_radius; // Log info to see output of linear system ROS_INFO("Right Motor Desired Speed = [%f]", right_wheel_omega); ROS_INFO("Left Motor Desired Speed = [%f]", left_wheel_omega); // Declare Message scr_proto::DiffCommand motor_com; // Populate Message // Need to map omega's to value between -127 and 127 for motor driver right_wheel_omega *= (127.0/motor_max_speed); left_wheel_omega *= (127.0/motor_max_speed); motor_com.left_motor = (int)left_wheel_omega; motor_com.right_motor = (int)right_wheel_omega; // Log Info for debugging ROS_INFO("Right Motor Command = [%f]", right_wheel_omega); ROS_INFO("Left Motor Command = [%f]", left_wheel_omega); // Publish Message motor_pub.publish(motor_com); // Handle loop rate ros::spinOnce(); loop_rate.sleep(); } } <commit_msg>changed print type on base controller node to double.<commit_after>#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "geometry_msgs/Vector3.h" #include "scr_proto/DiffCommand.h" #include <eigen3/Eigen/Dense> // Physical Parameters... What do to with these? double wheel_radius=4.875/2.0*.0254, axle_half_length=8.4*.0254; // Maximum loaded motor rotation speed in radians per sec double motor_max_speed=25; // Global values for velocity storage double cmd_vx=0, cmd_vy=0, cmd_vz=0, cmd_wx=0, cmd_wy=0, cmd_wz=0; // Callback to attach to command velocity subscription void commandCallback(const geometry_msgs::Twist::ConstPtr& msg){ // Pull values from message cmd_vx = msg->linear.x; cmd_wz = msg->angular.z; } // Function to calculate wheel speeds given a diff drive command // Models problem as Ax = b form Eigen::Vector2d getWheelSpeeds(double wheel_offset, double cmd_x, double cmd_th){ /* @ Params: wheel_offset -> Distance between center of wheel axle and center of wheel contact cmd_x -> Commanded forward velocity for the robot cmd_th -> Commanded angular velocity about the reference point @ Returns: x -> Eigen::Vector containing body velocities at wheel; x(0) -> Right Wheel x(1) -> Left Wheel */ // Diff Drive Dynamics Solution, vr = right wheel velocity, vl = left wheel velocity double vr = cmd_x + cmd_th * wheel_offset/2.0; double vl = cmd_x - cmd_th * wheel_offset/2.0; // Vector for result and return Eigen::Vector2d x; // Pack Vector with values and return x(0) = vr; x(1) = vl; return x; } int main(int argc, char **argv){ // Initialize Node ros::init(argc, argv, "base_controller"); // Create Nodehandle ros::NodeHandle n; // Subscribe to Command Velocity topic ros::Subscriber cmd_vel_sub = n.subscribe("cmd_vel", 1000, commandCallback); ros::Publisher motor_pub = n.advertise<scr_proto::DiffCommand>("/motor_command", 1000); ros::Rate loop_rate(10); while(ros::ok()){ // Vector for holding the linear speeds at the wheels Eigen::Vector2d wheel_linear_speeds; // Pass to linear Alg to solver or something? wheel_linear_speeds = getWheelSpeeds(axle_half_length, cmd_vx, cmd_wz); // Convert Wheel Velocities to Angular Velocities // Be careful for sign flip, as motors are not mounted symmetrically double right_wheel_omega = wheel_linear_speeds(0)/wheel_radius; double left_wheel_omega = wheel_linear_speeds(1)/wheel_radius; // Log info to see output of linear system ROS_INFO("Right Motor Desired Speed = [%d]", right_wheel_omega); ROS_INFO("Left Motor Desired Speed = [%d]", left_wheel_omega); // Declare Message scr_proto::DiffCommand motor_com; // Populate Message // Need to map omega's to value between -127 and 127 for motor driver right_wheel_omega *= (127.0/motor_max_speed); left_wheel_omega *= (127.0/motor_max_speed); motor_com.left_motor = (int)left_wheel_omega; motor_com.right_motor = (int)right_wheel_omega; // Log Info for debugging ROS_INFO("Right Motor Command = [%d]", right_wheel_omega); ROS_INFO("Left Motor Command = [%d]", left_wheel_omega); // Publish Message motor_pub.publish(motor_com); // Handle loop rate ros::spinOnce(); loop_rate.sleep(); } } <|endoftext|>
<commit_before> /** ========================================================================== * 2011 by KjellKod.cc, modified by Vrecan in https://bitbucket.org/vrecan/g2log-dev * 2015, adopted by KjellKod for g3log at:https://github.com/KjellKod/g3sinks * * This code is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================* * PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc * ********************************************* */ #include "g3sinks/LogRotateUtility.h" #include <iostream> #include <sstream> #include <algorithm> #include <g3log/time.hpp> #include <regex> #include <boost/filesystem.hpp> #include <ios> #include <fstream> #include <iomanip> #include <map> namespace LogRotateUtility { #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(__MINGW32__) //http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows char* strptime(const char* s, const char* f, struct tm* tm) { // Isn't the C++ standard lib nice? std::get_time is defined such that its // format parameters are the exact same as strptime. Of course, we have to // create a string stream first, and imbue it with the current C locale, and // we also have to make sure we return the right things if it fails, or // if it succeeds, but this is still far simpler an implementation than any // of the versions in any of the C standard libraries. std::istringstream input(s); input.imbue(std::locale(setlocale(LC_ALL, nullptr))); input >> std::get_time(tm, f); if (input.fail()) { return nullptr; } return (char*)(s + input.tellg()); } #endif // check for filename validity - filename should not be part of PATH bool isValidFilename(const std::string& prefix_filename) { std::string illegal_characters("/,|<>:#$%{}()[]\'\"^!?+* "); size_t pos = prefix_filename.find_first_of(illegal_characters, 0); if (pos != std::string::npos) { std::cerr << "Illegal character [" << prefix_filename.at(pos) << "] in logname prefix: " << "[" << prefix_filename << "]" << std::endl; return false; } else if (prefix_filename.empty()) { std::cerr << "Empty filename prefix is not allowed" << std::endl; return false; } return true; } /// @return a corrected prefix, if needed, /// illegal characters are removed from @param prefix input std::string prefixSanityFix(std::string prefix) { prefix.erase(std::remove_if(prefix.begin(), prefix.end(), ::isspace), prefix.end()); prefix.erase(std::remove(prefix.begin(), prefix.end(), '/'), prefix.end()); // '/' prefix.erase(std::remove(prefix.begin(), prefix.end(), '\\'), prefix.end()); // '\\' prefix.erase(std::remove(prefix.begin(), prefix.end(), '.'), prefix.end()); // '.' if (!isValidFilename(prefix)) { return ""; } return prefix; } /// @return the file header std::string header() { std::ostringstream ss_entry; // Day Month Date Time Year: is written as "%a %b %d %H:%M:%S %Y" and formatted output as : Wed Sep 19 08:28:16 2012 ss_entry << "\ng3log: created log file at: " << g3::localtime_formatted(g3::systemtime_now(), "%a %b %d %H:%M:%S %Y") << "\n"; return ss_entry.str(); } /// @return result as time from the file name bool getDateFromFileName(const std::string& app_name, const std::string& file_name, long& result) { if (file_name.find(app_name) != std::string::npos) { std::string suffix = file_name.substr(app_name.size()); if (suffix.empty()) { //this is the main log file return false; } using namespace std; regex date_regex("\\.(\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2})\\.gz"); smatch date_match; if (regex_match(suffix, date_match, date_regex)) { if (date_match.size() == 2) { std::string date = date_match[1].str(); struct tm tm; time_t t; if (strptime(date.c_str(), "%Y-%m-%d-%H-%M-%S", &tm) == nullptr) { return false; } t = mktime(&tm); if (t == -1) { return false; } result = (long) t; return true; } } } return false; } std::string pathSanityFix(std::string path, std::string file_name) { // Unify the delimeters,. maybe sketchy solution but it seems to work // on at least win7 + ubuntu. All bets are off for older windows std::replace(path.begin(), path.end(), '\\', '/'); // clean up in case of multiples auto contains_end = [&](std::string & in) -> bool { size_t size = in.size(); if (!size) return false; char end = in[size - 1]; return (end == '/' || end == ' '); }; while (contains_end(path)) { path.erase(path.size() - 1); } if (!path.empty()) { path.insert(path.end(), '/'); } path.insert(path.size(), file_name); return path; } /** * Loop through the files in the folder * @param dir * @param file_name */ void expireArchives(const std::string& dir, const std::string& app_name, unsigned long max_log_count) { std::map<long, std::string> files; boost::filesystem::path dir_path(dir); boost::filesystem::directory_iterator end_itr; if (!boost::filesystem::exists(dir_path)) return; for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { std::string current_file(itr->path().filename().string()); long time = 0; if (getDateFromFileName(app_name, current_file, time)) { files.insert(std::pair<long, std::string > (time, current_file)); } } //delete old logs. ptrdiff_t logs_to_delete = files.size() - max_log_count; if (logs_to_delete > 0) { for (std::map<long, std::string>::iterator it = files.begin(); it != files.end(); ++it) { if (logs_to_delete <= 0) { break; } std::string filename_with_path(pathSanityFix(dir, it->second)); remove(filename_with_path.c_str()); --logs_to_delete; } } } std::map<long, std::string> getLogFilesInDirectory(const std::string& dir, const std::string& app_name) { std::map<long, std::string> files; boost::filesystem::path dir_path(dir); boost::filesystem::directory_iterator end_itr; if (!boost::filesystem::exists(dir_path)) return {}; for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { std::string current_file(itr->path().filename().c_str()); long time = 0; if (getDateFromFileName(app_name, current_file, time)) { files.insert(std::pair<long, std::string > (time, current_file)); } } return files; } /// create the file name std::string createLogFileName(const std::string& verified_prefix) { std::stringstream oss_name; oss_name << verified_prefix << ".log"; return oss_name.str(); } /// @return true if @param complete_file_with_path could be opened /// @param outstream is the file stream bool openLogFile(const std::string& complete_file_with_path, std::ofstream& outstream) { std::ios_base::openmode mode = std::ios_base::out; // for clarity: it's really overkill since it's an ofstream mode |= std::ios_base::app; outstream.open(complete_file_with_path, mode); if (!outstream.is_open()) { std::ostringstream ss_error; ss_error << "FILE ERROR: could not open log file:[" << complete_file_with_path << "]"; ss_error << "\n\t\t std::ios_base state = " << outstream.rdstate(); std::cerr << ss_error.str().c_str() << std::endl; outstream.close(); return false; } return true; } /// create the file std::unique_ptr<std::ofstream> createLogFile(const std::string& file_with_full_path) { std::unique_ptr<std::ofstream> out(new std::ofstream); std::ofstream& stream(*(out.get())); bool success_with_open_file = openLogFile(file_with_full_path, stream); if (false == success_with_open_file) { out.release(); } return out; } }<commit_msg>fix compilation in msvc<commit_after> /** ========================================================================== * 2011 by KjellKod.cc, modified by Vrecan in https://bitbucket.org/vrecan/g2log-dev * 2015, adopted by KjellKod for g3log at:https://github.com/KjellKod/g3sinks * * This code is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================* * PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc * ********************************************* */ #include "g3sinks/LogRotateUtility.h" #include <iostream> #include <sstream> #include <algorithm> #include <g3log/time.hpp> #include <regex> #include <boost/filesystem.hpp> #include <ios> #include <fstream> #include <iomanip> #include <map> namespace LogRotateUtility { #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(__MINGW32__) //http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows char* strptime(const char* s, const char* f, struct tm* tm) { // Isn't the C++ standard lib nice? std::get_time is defined such that its // format parameters are the exact same as strptime. Of course, we have to // create a string stream first, and imbue it with the current C locale, and // we also have to make sure we return the right things if it fails, or // if it succeeds, but this is still far simpler an implementation than any // of the versions in any of the C standard libraries. std::istringstream input(s); input.imbue(std::locale(setlocale(LC_ALL, nullptr))); input >> std::get_time(tm, f); if (input.fail()) { return nullptr; } return (char*)(s + input.tellg()); } #endif // check for filename validity - filename should not be part of PATH bool isValidFilename(const std::string& prefix_filename) { std::string illegal_characters("/,|<>:#$%{}()[]\'\"^!?+* "); size_t pos = prefix_filename.find_first_of(illegal_characters, 0); if (pos != std::string::npos) { std::cerr << "Illegal character [" << prefix_filename.at(pos) << "] in logname prefix: " << "[" << prefix_filename << "]" << std::endl; return false; } else if (prefix_filename.empty()) { std::cerr << "Empty filename prefix is not allowed" << std::endl; return false; } return true; } /// @return a corrected prefix, if needed, /// illegal characters are removed from @param prefix input std::string prefixSanityFix(std::string prefix) { prefix.erase(std::remove_if(prefix.begin(), prefix.end(), ::isspace), prefix.end()); prefix.erase(std::remove(prefix.begin(), prefix.end(), '/'), prefix.end()); // '/' prefix.erase(std::remove(prefix.begin(), prefix.end(), '\\'), prefix.end()); // '\\' prefix.erase(std::remove(prefix.begin(), prefix.end(), '.'), prefix.end()); // '.' if (!isValidFilename(prefix)) { return ""; } return prefix; } /// @return the file header std::string header() { std::ostringstream ss_entry; // Day Month Date Time Year: is written as "%a %b %d %H:%M:%S %Y" and formatted output as : Wed Sep 19 08:28:16 2012 ss_entry << "\ng3log: created log file at: " << g3::localtime_formatted(g3::systemtime_now(), "%a %b %d %H:%M:%S %Y") << "\n"; return ss_entry.str(); } /// @return result as time from the file name bool getDateFromFileName(const std::string& app_name, const std::string& file_name, long& result) { if (file_name.find(app_name) != std::string::npos) { std::string suffix = file_name.substr(app_name.size()); if (suffix.empty()) { //this is the main log file return false; } using namespace std; regex date_regex("\\.(\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2})\\.gz"); smatch date_match; if (regex_match(suffix, date_match, date_regex)) { if (date_match.size() == 2) { std::string date = date_match[1].str(); struct tm tm; time_t t; if (strptime(date.c_str(), "%Y-%m-%d-%H-%M-%S", &tm) == nullptr) { return false; } t = mktime(&tm); if (t == -1) { return false; } result = (long) t; return true; } } } return false; } std::string pathSanityFix(std::string path, std::string file_name) { // Unify the delimeters,. maybe sketchy solution but it seems to work // on at least win7 + ubuntu. All bets are off for older windows std::replace(path.begin(), path.end(), '\\', '/'); // clean up in case of multiples auto contains_end = [&](std::string & in) -> bool { size_t size = in.size(); if (!size) return false; char end = in[size - 1]; return (end == '/' || end == ' '); }; while (contains_end(path)) { path.erase(path.size() - 1); } if (!path.empty()) { path.insert(path.end(), '/'); } path.insert(path.size(), file_name); return path; } /** * Loop through the files in the folder * @param dir * @param file_name */ void expireArchives(const std::string& dir, const std::string& app_name, unsigned long max_log_count) { std::map<long, std::string> files; boost::filesystem::path dir_path(dir); boost::filesystem::directory_iterator end_itr; if (!boost::filesystem::exists(dir_path)) return; for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { std::string current_file(itr->path().filename().string()); long time = 0; if (getDateFromFileName(app_name, current_file, time)) { files.insert(std::pair<long, std::string > (time, current_file)); } } //delete old logs. ptrdiff_t logs_to_delete = files.size() - max_log_count; if (logs_to_delete > 0) { for (std::map<long, std::string>::iterator it = files.begin(); it != files.end(); ++it) { if (logs_to_delete <= 0) { break; } std::string filename_with_path(pathSanityFix(dir, it->second)); remove(filename_with_path.c_str()); --logs_to_delete; } } } std::map<long, std::string> getLogFilesInDirectory(const std::string& dir, const std::string& app_name) { std::map<long, std::string> files; boost::filesystem::path dir_path(dir); boost::filesystem::directory_iterator end_itr; if (!boost::filesystem::exists(dir_path)) return {}; for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { std::string current_file(itr->path().filename().string()); long time = 0; if (getDateFromFileName(app_name, current_file, time)) { files.insert(std::pair<long, std::string > (time, current_file)); } } return files; } /// create the file name std::string createLogFileName(const std::string& verified_prefix) { std::stringstream oss_name; oss_name << verified_prefix << ".log"; return oss_name.str(); } /// @return true if @param complete_file_with_path could be opened /// @param outstream is the file stream bool openLogFile(const std::string& complete_file_with_path, std::ofstream& outstream) { std::ios_base::openmode mode = std::ios_base::out; // for clarity: it's really overkill since it's an ofstream mode |= std::ios_base::app; outstream.open(complete_file_with_path, mode); if (!outstream.is_open()) { std::ostringstream ss_error; ss_error << "FILE ERROR: could not open log file:[" << complete_file_with_path << "]"; ss_error << "\n\t\t std::ios_base state = " << outstream.rdstate(); std::cerr << ss_error.str().c_str() << std::endl; outstream.close(); return false; } return true; } /// create the file std::unique_ptr<std::ofstream> createLogFile(const std::string& file_with_full_path) { std::unique_ptr<std::ofstream> out(new std::ofstream); std::ofstream& stream(*(out.get())); bool success_with_open_file = openLogFile(file_with_full_path, stream); if (false == success_with_open_file) { out.release(); } return out; } }<|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/remote_gdb.hh" #include "cpu/exec_context.hh" #include "kern/kernel_stats.hh" #include "mem/functional/memory_control.hh" #include "mem/functional/physical.hh" #include "targetarch/vtophys.hh" #include "sim/builder.hh" #include "sim/system.hh" #include "base/trace.hh" using namespace std; vector<System *> System::systemList; int System::numSystemsRunning = 0; System::System(Params *p) : SimObject(p->name), memctrl(p->memctrl), physmem(p->physmem), init_param(p->init_param), numcpus(0), params(p) { // add self to global system list systemList.push_back(this); kernelSymtab = new SymbolTable; consoleSymtab = new SymbolTable; palSymtab = new SymbolTable; debugSymbolTable = new SymbolTable; /** * Load the kernel, pal, and console code into memory */ // Load kernel code kernel = createObjectFile(params->kernel_path); if (kernel == NULL) fatal("Could not load kernel file %s", params->kernel_path); // Load Console Code console = createObjectFile(params->console_path); if (console == NULL) fatal("Could not load console file %s", params->console_path); // Load pal file pal = createObjectFile(params->palcode); if (pal == NULL) fatal("Could not load PALcode file %s", params->palcode); // Load program sections into memory pal->loadSections(physmem, true); console->loadSections(physmem, true); kernel->loadSections(physmem, true); // setup entry points kernelStart = kernel->textBase(); kernelEnd = kernel->bssBase() + kernel->bssSize(); kernelEntry = kernel->entryPoint(); // load symbols if (!kernel->loadGlobalSymbols(kernelSymtab)) panic("could not load kernel symbols\n"); if (!kernel->loadLocalSymbols(kernelSymtab)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(consoleSymtab)) panic("could not load console symbols\n"); if (!pal->loadGlobalSymbols(palSymtab)) panic("could not load pal symbols\n"); if (!pal->loadLocalSymbols(palSymtab)) panic("could not load pal symbols\n"); if (!kernel->loadGlobalSymbols(debugSymbolTable)) panic("could not load kernel symbols\n"); if (!kernel->loadLocalSymbols(debugSymbolTable)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(debugSymbolTable)) panic("could not load console symbols\n"); if (!pal->loadGlobalSymbols(debugSymbolTable)) panic("could not load pal symbols\n"); if (!pal->loadLocalSymbols(debugSymbolTable)) panic("could not load pal symbols\n"); DPRINTF(Loader, "Kernel start = %#x\n", kernelStart); DPRINTF(Loader, "Kernel end = %#x\n", kernelEnd); DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry); DPRINTF(Loader, "Kernel loaded...\n"); Addr addr = 0; #ifdef DEBUG consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic"); if (consoleSymtab->findAddress("panic", addr)) consolePanicEvent->schedule(addr); #endif /** * Copy the osflags (kernel arguments) into the consoles * memory. (Presently Linux does not use the console service * routine to get these command line arguments, but Tru64 and * others do.) */ if (consoleSymtab->findAddress("env_booted_osflags", addr)) { Addr paddr = vtophys(physmem, addr); char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t)); if (osflags) strcpy(osflags, params->boot_osflags.c_str()); } /** * Set the hardware reset parameter block system type and revision * information to Tsunami. */ if (consoleSymtab->findAddress("m5_rpb", addr)) { Addr paddr = vtophys(physmem, addr); char *hwrpb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (!hwrpb) panic("could not translate hwrpb addr\n"); *(uint64_t*)(hwrpb+0x50) = htoa(params->system_type); *(uint64_t*)(hwrpb+0x58) = htoa(params->system_rev); } else panic("could not find hwrpb\n"); // increment the number of running systms numSystemsRunning++; kernelBinning = new Kernel::Binning(this); } System::~System() { delete kernelSymtab; delete consoleSymtab; delete kernel; delete console; delete pal; delete kernelBinning; #ifdef DEBUG delete consolePanicEvent; #endif } void System::setAlphaAccess(Addr access) { Addr addr = 0; if (consoleSymtab->findAddress("m5AlphaAccess", addr)) { Addr paddr = vtophys(physmem, addr); uint64_t *m5AlphaAccess = (uint64_t *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (!m5AlphaAccess) panic("could not translate m5AlphaAccess addr\n"); *m5AlphaAccess = htoa(EV5::Phys2K0Seg(access)); } else panic("could not find m5AlphaAccess\n"); } bool System::breakpoint() { return remoteGDB[0]->trap(ALPHA_KENTRY_INT); } int System::registerExecContext(ExecContext *xc, int id) { if (id == -1) { for (id = 0; id < execContexts.size(); id++) { if (!execContexts[id]) break; } } if (execContexts.size() <= id) execContexts.resize(id + 1); if (execContexts[id]) panic("Cannot have two CPUs with the same id (%d)\n", id); execContexts[id] = xc; numcpus++; RemoteGDB *rgdb = new RemoteGDB(this, xc); GDBListener *gdbl = new GDBListener(rgdb, 7000 + id); gdbl->listen(); /** * Uncommenting this line waits for a remote debugger to connect * to the simulator before continuing. */ //gdbl->accept(); if (remoteGDB.size() <= id) { remoteGDB.resize(id + 1); } remoteGDB[id] = rgdb; return id; } void System::startup() { if (!execContexts.empty()) { // activate with zero delay so that we start ticking right // away on cycle 0 execContexts[0]->activate(0); } } void System::replaceExecContext(ExecContext *xc, int id) { if (id >= execContexts.size()) { panic("replaceExecContext: bad id, %d >= %d\n", id, execContexts.size()); } execContexts[id] = xc; remoteGDB[id]->replaceExecContext(xc); } void System::regStats() { kernelBinning->regStats(name() + ".kern"); } void System::serialize(ostream &os) { kernelBinning->serialize(os); } void System::unserialize(Checkpoint *cp, const string &section) { kernelBinning->unserialize(cp, section); } void System::printSystems() { vector<System *>::iterator i = systemList.begin(); vector<System *>::iterator end = systemList.end(); for (; i != end; ++i) { System *sys = *i; cerr << "System " << sys->name() << ": " << hex << sys << endl; } } extern "C" void printSystems() { System::printSystems(); } BEGIN_DECLARE_SIM_OBJECT_PARAMS(System) Param<Tick> boot_cpu_frequency; SimObjectParam<MemoryController *> memctrl; SimObjectParam<PhysicalMemory *> physmem; Param<string> kernel; Param<string> console; Param<string> pal; Param<string> boot_osflags; Param<string> readfile; Param<unsigned int> init_param; Param<uint64_t> system_type; Param<uint64_t> system_rev; Param<bool> bin; VectorParam<string> binned_fns; Param<bool> bin_int; END_DECLARE_SIM_OBJECT_PARAMS(System) BEGIN_INIT_SIM_OBJECT_PARAMS(System) INIT_PARAM(boot_cpu_frequency, "Frequency of the boot CPU"), INIT_PARAM(memctrl, "memory controller"), INIT_PARAM(physmem, "phsyical memory"), INIT_PARAM(kernel, "file that contains the kernel code"), INIT_PARAM(console, "file that contains the console code"), INIT_PARAM(pal, "file that contains palcode"), INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot", "a"), INIT_PARAM_DFLT(readfile, "file to read startup script from", ""), INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0), INIT_PARAM_DFLT(system_type, "Type of system we are emulating", 34), INIT_PARAM_DFLT(system_rev, "Revision of system we are emulating", 1<<10), INIT_PARAM_DFLT(bin, "is this system to be binned", false), INIT_PARAM(binned_fns, "functions to be broken down and binned"), INIT_PARAM_DFLT(bin_int, "is interrupt code binned seperately?", true) END_INIT_SIM_OBJECT_PARAMS(System) CREATE_SIM_OBJECT(System) { System::Params *p = new System::Params; p->name = getInstanceName(); p->boot_cpu_frequency = boot_cpu_frequency; p->memctrl = memctrl; p->physmem = physmem; p->kernel_path = kernel; p->console_path = console; p->palcode = pal; p->boot_osflags = boot_osflags; p->init_param = init_param; p->readfile = readfile; p->system_type = system_type; p->system_rev = system_rev; p->bin = bin; p->binned_fns = binned_fns; p->bin_int = bin_int; return new System(p); } REGISTER_SIM_OBJECT("System", System) <commit_msg>Easier remote debugging at boot time.<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/remote_gdb.hh" #include "cpu/exec_context.hh" #include "kern/kernel_stats.hh" #include "mem/functional/memory_control.hh" #include "mem/functional/physical.hh" #include "targetarch/vtophys.hh" #include "sim/builder.hh" #include "sim/system.hh" #include "base/trace.hh" using namespace std; vector<System *> System::systemList; int System::numSystemsRunning = 0; System::System(Params *p) : SimObject(p->name), memctrl(p->memctrl), physmem(p->physmem), init_param(p->init_param), numcpus(0), params(p) { // add self to global system list systemList.push_back(this); kernelSymtab = new SymbolTable; consoleSymtab = new SymbolTable; palSymtab = new SymbolTable; debugSymbolTable = new SymbolTable; /** * Load the kernel, pal, and console code into memory */ // Load kernel code kernel = createObjectFile(params->kernel_path); if (kernel == NULL) fatal("Could not load kernel file %s", params->kernel_path); // Load Console Code console = createObjectFile(params->console_path); if (console == NULL) fatal("Could not load console file %s", params->console_path); // Load pal file pal = createObjectFile(params->palcode); if (pal == NULL) fatal("Could not load PALcode file %s", params->palcode); // Load program sections into memory pal->loadSections(physmem, true); console->loadSections(physmem, true); kernel->loadSections(physmem, true); // setup entry points kernelStart = kernel->textBase(); kernelEnd = kernel->bssBase() + kernel->bssSize(); kernelEntry = kernel->entryPoint(); // load symbols if (!kernel->loadGlobalSymbols(kernelSymtab)) panic("could not load kernel symbols\n"); if (!kernel->loadLocalSymbols(kernelSymtab)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(consoleSymtab)) panic("could not load console symbols\n"); if (!pal->loadGlobalSymbols(palSymtab)) panic("could not load pal symbols\n"); if (!pal->loadLocalSymbols(palSymtab)) panic("could not load pal symbols\n"); if (!kernel->loadGlobalSymbols(debugSymbolTable)) panic("could not load kernel symbols\n"); if (!kernel->loadLocalSymbols(debugSymbolTable)) panic("could not load kernel local symbols\n"); if (!console->loadGlobalSymbols(debugSymbolTable)) panic("could not load console symbols\n"); if (!pal->loadGlobalSymbols(debugSymbolTable)) panic("could not load pal symbols\n"); if (!pal->loadLocalSymbols(debugSymbolTable)) panic("could not load pal symbols\n"); DPRINTF(Loader, "Kernel start = %#x\n", kernelStart); DPRINTF(Loader, "Kernel end = %#x\n", kernelEnd); DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry); DPRINTF(Loader, "Kernel loaded...\n"); Addr addr = 0; #ifdef DEBUG consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic"); if (consoleSymtab->findAddress("panic", addr)) consolePanicEvent->schedule(addr); #endif /** * Copy the osflags (kernel arguments) into the consoles * memory. (Presently Linux does not use the console service * routine to get these command line arguments, but Tru64 and * others do.) */ if (consoleSymtab->findAddress("env_booted_osflags", addr)) { Addr paddr = vtophys(physmem, addr); char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t)); if (osflags) strcpy(osflags, params->boot_osflags.c_str()); } /** * Set the hardware reset parameter block system type and revision * information to Tsunami. */ if (consoleSymtab->findAddress("m5_rpb", addr)) { Addr paddr = vtophys(physmem, addr); char *hwrpb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (!hwrpb) panic("could not translate hwrpb addr\n"); *(uint64_t*)(hwrpb+0x50) = htoa(params->system_type); *(uint64_t*)(hwrpb+0x58) = htoa(params->system_rev); } else panic("could not find hwrpb\n"); // increment the number of running systms numSystemsRunning++; kernelBinning = new Kernel::Binning(this); } System::~System() { delete kernelSymtab; delete consoleSymtab; delete kernel; delete console; delete pal; delete kernelBinning; #ifdef DEBUG delete consolePanicEvent; #endif } void System::setAlphaAccess(Addr access) { Addr addr = 0; if (consoleSymtab->findAddress("m5AlphaAccess", addr)) { Addr paddr = vtophys(physmem, addr); uint64_t *m5AlphaAccess = (uint64_t *)physmem->dma_addr(paddr, sizeof(uint64_t)); if (!m5AlphaAccess) panic("could not translate m5AlphaAccess addr\n"); *m5AlphaAccess = htoa(EV5::Phys2K0Seg(access)); } else panic("could not find m5AlphaAccess\n"); } bool System::breakpoint() { return remoteGDB[0]->trap(ALPHA_KENTRY_INT); } int rgdb_wait = -1; int System::registerExecContext(ExecContext *xc, int id) { if (id == -1) { for (id = 0; id < execContexts.size(); id++) { if (!execContexts[id]) break; } } if (execContexts.size() <= id) execContexts.resize(id + 1); if (execContexts[id]) panic("Cannot have two CPUs with the same id (%d)\n", id); execContexts[id] = xc; numcpus++; RemoteGDB *rgdb = new RemoteGDB(this, xc); GDBListener *gdbl = new GDBListener(rgdb, 7000 + id); gdbl->listen(); /** * Uncommenting this line waits for a remote debugger to connect * to the simulator before continuing. */ if (rgdb_wait != -1 && rgdb_wait == id) gdbl->accept(); if (remoteGDB.size() <= id) { remoteGDB.resize(id + 1); } remoteGDB[id] = rgdb; return id; } void System::startup() { if (!execContexts.empty()) { // activate with zero delay so that we start ticking right // away on cycle 0 execContexts[0]->activate(0); } } void System::replaceExecContext(ExecContext *xc, int id) { if (id >= execContexts.size()) { panic("replaceExecContext: bad id, %d >= %d\n", id, execContexts.size()); } execContexts[id] = xc; remoteGDB[id]->replaceExecContext(xc); } void System::regStats() { kernelBinning->regStats(name() + ".kern"); } void System::serialize(ostream &os) { kernelBinning->serialize(os); } void System::unserialize(Checkpoint *cp, const string &section) { kernelBinning->unserialize(cp, section); } void System::printSystems() { vector<System *>::iterator i = systemList.begin(); vector<System *>::iterator end = systemList.end(); for (; i != end; ++i) { System *sys = *i; cerr << "System " << sys->name() << ": " << hex << sys << endl; } } extern "C" void printSystems() { System::printSystems(); } BEGIN_DECLARE_SIM_OBJECT_PARAMS(System) Param<Tick> boot_cpu_frequency; SimObjectParam<MemoryController *> memctrl; SimObjectParam<PhysicalMemory *> physmem; Param<string> kernel; Param<string> console; Param<string> pal; Param<string> boot_osflags; Param<string> readfile; Param<unsigned int> init_param; Param<uint64_t> system_type; Param<uint64_t> system_rev; Param<bool> bin; VectorParam<string> binned_fns; Param<bool> bin_int; END_DECLARE_SIM_OBJECT_PARAMS(System) BEGIN_INIT_SIM_OBJECT_PARAMS(System) INIT_PARAM(boot_cpu_frequency, "Frequency of the boot CPU"), INIT_PARAM(memctrl, "memory controller"), INIT_PARAM(physmem, "phsyical memory"), INIT_PARAM(kernel, "file that contains the kernel code"), INIT_PARAM(console, "file that contains the console code"), INIT_PARAM(pal, "file that contains palcode"), INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot", "a"), INIT_PARAM_DFLT(readfile, "file to read startup script from", ""), INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0), INIT_PARAM_DFLT(system_type, "Type of system we are emulating", 34), INIT_PARAM_DFLT(system_rev, "Revision of system we are emulating", 1<<10), INIT_PARAM_DFLT(bin, "is this system to be binned", false), INIT_PARAM(binned_fns, "functions to be broken down and binned"), INIT_PARAM_DFLT(bin_int, "is interrupt code binned seperately?", true) END_INIT_SIM_OBJECT_PARAMS(System) CREATE_SIM_OBJECT(System) { System::Params *p = new System::Params; p->name = getInstanceName(); p->boot_cpu_frequency = boot_cpu_frequency; p->memctrl = memctrl; p->physmem = physmem; p->kernel_path = kernel; p->console_path = console; p->palcode = pal; p->boot_osflags = boot_osflags; p->init_param = init_param; p->readfile = readfile; p->system_type = system_type; p->system_rev = system_rev; p->bin = bin; p->binned_fns = binned_fns; p->bin_int = bin_int; return new System(p); } REGISTER_SIM_OBJECT("System", System) <|endoftext|>
<commit_before>#ifndef DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH #define DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH #include <dune/multiscale/msfem/msfem_traits.hh> #include <dune/multiscale/problems/base.hh> #include <dune/multiscale/problems/selector.hh> #include <dune/gdt/functionals/l2.hh> namespace Dune { namespace Multiscale { // forward, to be used in the traits class CoarseBasisProduct; /** * \brief Traits for the Product evaluation. */ class ProductTraitsBase { public: typedef Problem::LocalDiffusionType LocalizableFunctionType; typedef LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple<std::shared_ptr<LocalfunctionType>> LocalfunctionTupleType; static constexpr auto dimDomain = CommonTraits::dimDomain; static constexpr auto dimRange = CommonTraits::dimRange; typedef CommonTraits::DomainFieldType DomainFieldType; static_assert(std::is_base_of<Dune::Stuff::IsLocalizableFunction, LocalizableFunctionType>::value, "LocalizableFunctionImp has to be derived from Stuff::IsLocalizableFunction."); }; struct CoarseBasisProductTraits : public ProductTraitsBase { typedef CoarseBasisProduct derived_type; }; class CoarseBasisProduct : public GDT::LocalEvaluation::Codim0Interface<CoarseBasisProductTraits, 1> { typedef MsFEMTraits::LocalEntityType EntityType; public: typedef CoarseBasisProductTraits Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; CoarseBasisProduct(const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base, const LocalizableFunctionType& inducingFunction, const std::size_t coarseBaseFunc) : inducingFunction_(inducingFunction) , coarse_base_set_(coarse_base) , coarseBaseFunc_(coarseBaseFunc) {} CoarseBasisProduct(const CoarseBasisProduct&) = default; typename Traits::LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template <class E, class D, int d, class R, int rT, int rCT> size_t order(const typename Traits::LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const { const auto localFunction = std::get<0>(localFuncs); return order(*localFunction, testBase); } /** * \todo add copydoc * \return localFunction.order() + testBase.order() */ template <class E, class D, int d, class R, int rL, int rCL, int rT, int rCT> size_t order(const Stuff::LocalfunctionInterface<E, D, d, R, rL, rCL>& localFunction, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const { return localFunction.order() + testBase.order(); } // int order(...) /** * \brief extracts the local functions and calls the correct evaluate() method */ template <class D, int d, class R, int rT, int rCT> void evaluate(const typename Traits::LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface<EntityType, D, d, R, rT, rCT>& testBase, const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const { const auto& localFunction = std::get<0>(localFuncs); evaluate(*localFunction, testBase, localPoint, ret); } template <class E, class D, int d, class R, int rL, int rCL, int rT, int rCT> void evaluate(const Stuff::LocalfunctionInterface<E, D, d, R, rL, rCL>& /*localFunction*/, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase, const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const { // evaluate local function const auto& entity = testBase.entity(); const auto global_point = entity.geometry().global(localPoint); const auto& coarse_entity = coarse_base_set_.entity(); const auto quadInCoarseLocal = coarse_entity.geometry().local(global_point); const auto coarseBaseFuncJacs = coarse_base_set_.jacobian(quadInCoarseLocal); const auto direction = coarseBaseFuncJacs[coarseBaseFunc_]; DMP::JacobianRangeType flux; //! todo make member DMP::getDiffusion().diffusiveFlux(global_point, direction, flux); // evaluate test base const std::size_t size = testBase.size(); const auto transformed_gradients = testBase.jacobian(localPoint); // compute product assert(ret.size() >= size); assert(transformed_gradients.size() >= size); //! \TODO WTF muss hier eigentlich hin for (size_t ii = 0; ii < size; ++ii) { // transformed_gradients[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2> ret[ii] = -1 * (flux[0] * transformed_gradients[ii][0]); // DSC_LOG_DEBUG << "DIFF " << global_point << " | " << flux << " | " << grad_phi_s[ii][0]<< std::endl; } } private: const LocalizableFunctionType& inducingFunction_; const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base_set_; const std::size_t coarseBaseFunc_; }; // class CoarseBasisProduct // forward, to be used in the traits class DirichletProduct; /** * \brief Traits for the Product evaluation. */ struct DirichletProductTraits : public ProductTraitsBase { typedef DirichletProduct derived_type; }; class DirichletProduct : public GDT::LocalEvaluation::Codim0Interface<DirichletProductTraits, 1> { public: typedef DirichletProductTraits Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; DirichletProduct(const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension, const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) , dirichlet_extension_(dirichlet_extension) {} template <class EntityType> class LocalfunctionTuple { typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; public: typedef std::tuple<std::shared_ptr<LocalfunctionType>> Type; }; template <class EntityType> typename LocalfunctionTuple<EntityType>::Type localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template <class E, class D, int d, class R, int rT, int rCT> size_t order(const typename LocalfunctionTuple<E>::Type& localFuncs, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const { const auto localFunction = std::get<0>(localFuncs); return order(*localFunction, testBase); } /** * \todo add copydoc * \return localFunction.order() + testBase.order() */ template <class E, class D, int d, class R, int rL, int rCL, int rT, int rCT> size_t order(const Stuff::LocalfunctionInterface<E, D, d, R, rL, rCL>& localFunction, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const { return localFunction.order() + testBase.order(); } // int order(...) /** * \brief extracts the local functions and calls the correct evaluate() method */ template <class E, class D, int d, class R, int rT, int rCT> void evaluate(const typename LocalfunctionTuple<E>::Type& localFuncs, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase, const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const { const auto& localFunction = std::get<0>(localFuncs); evaluate(*localFunction, testBase, localPoint, ret); } template <class E, class D, int d, class R, int rL, int rCL, int rT, int rCT> void evaluate(const Stuff::LocalfunctionInterface<E, D, d, R, rL, rCL>& /*localFunction*/, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase, const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const { // evaluate local function const auto& entity = testBase.entity(); const auto dirichlet_lf = dirichlet_extension_.local_function(entity); const auto direction = dirichlet_lf->jacobian(localPoint); DMP::JacobianRangeType flux; const auto global_point = entity.geometry().global(localPoint); //!TODO make member DMP::getDiffusion().diffusiveFlux(global_point, direction, flux); // evaluate test base const std::size_t size = testBase.size(); typedef typename Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>::JacobianRangeType JR; const std::vector<JR> grad_phi_s = testBase.jacobian(localPoint); // compute product assert(ret.size() >= size); assert(grad_phi_s.size() >= size); //! \TODO WTF muss hier eigentlich hin for (size_t ii = 0; ii < size; ++ii) { // grad_phi_s[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2> ret[ii] = -1 * (flux[0] * grad_phi_s[ii][0]); } } private: const LocalizableFunctionType& inducingFunction_; const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension_; }; // class Product } // namespace Multiscale { } // namespace Dune { #endif // DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH <commit_msg>fixes type mismatch regression in coarse product evals<commit_after>#ifndef DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH #define DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH #include <dune/multiscale/msfem/msfem_traits.hh> #include <dune/multiscale/problems/base.hh> #include <dune/multiscale/problems/selector.hh> #include <dune/gdt/functionals/l2.hh> namespace Dune { namespace Multiscale { // forward, to be used in the traits class CoarseBasisProduct; /** * \brief Traits for the Product evaluation. */ class ProductTraitsBase { public: typedef Problem::LocalDiffusionType LocalizableFunctionType; typedef LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple<std::shared_ptr<LocalfunctionType>> LocalfunctionTupleType; static constexpr auto dimDomain = CommonTraits::dimDomain; static constexpr auto dimRange = CommonTraits::dimRange; typedef CommonTraits::DomainFieldType DomainFieldType; static_assert(std::is_base_of<Dune::Stuff::IsLocalizableFunction, LocalizableFunctionType>::value, "LocalizableFunctionImp has to be derived from Stuff::IsLocalizableFunction."); }; struct CoarseBasisProductTraits : public ProductTraitsBase { typedef CoarseBasisProduct derived_type; }; class CoarseBasisProduct : public GDT::LocalEvaluation::Codim0Interface<CoarseBasisProductTraits, 1> { typedef MsFEMTraits::LocalEntityType EntityType; public: typedef CoarseBasisProductTraits Traits; typedef typename Traits::DomainFieldType DomainFieldType; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; CoarseBasisProduct(const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base, const LocalizableFunctionType& inducingFunction, const std::size_t coarseBaseFunc) : inducingFunction_(inducingFunction) , coarse_base_set_(coarse_base) , coarseBaseFunc_(coarseBaseFunc) {} CoarseBasisProduct(const CoarseBasisProduct&) = default; typename Traits::LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template <class E, size_t d, class R, size_t rT, size_t rCT> size_t order(const typename Traits::LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface<E, DomainFieldType, d, R, rT, rCT>& testBase) const { const auto localFunction = std::get<0>(localFuncs); return order(*localFunction, testBase); } /** * \todo add copydoc * \return localFunction.order() + testBase.order() */ template <class E, size_t d, class R, size_t rL, size_t rCL, size_t rT, size_t rCT> size_t order(const Stuff::LocalfunctionInterface<E, DomainFieldType, d, R, rL, rCL>& localFunction, const Stuff::LocalfunctionSetInterface<E, DomainFieldType, d, R, rT, rCT>& testBase) const { return localFunction.order() + testBase.order(); } // int order(...) /** * \brief extracts the local functions and calls the correct evaluate() method */ template <size_t d, class R, size_t rT, size_t rCT> void evaluate(const typename Traits::LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface<EntityType, DomainFieldType, d, R, rT, rCT>& testBase, const Dune::FieldVector<DomainFieldType, d>& localPoint, Dune::DynamicVector<R>& ret) const { const auto& localFunction = std::get<0>(localFuncs); evaluate(*localFunction, testBase, localPoint, ret); } template< class R, size_t r, size_t rC > void evaluate(const typename Traits::LocalfunctionTupleType& /*localFunctions_in*/, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { // evaluate local function const auto& entity = testBase.entity(); const auto global_point = entity.geometry().global(localPoint); const auto& coarse_entity = coarse_base_set_.entity(); const auto quadInCoarseLocal = coarse_entity.geometry().local(global_point); const auto coarseBaseFuncJacs = coarse_base_set_.jacobian(quadInCoarseLocal); const auto direction = coarseBaseFuncJacs[coarseBaseFunc_]; DMP::JacobianRangeType flux; //! todo make member DMP::getDiffusion().diffusiveFlux(global_point, direction, flux); // evaluate test base const std::size_t size = testBase.size(); const auto transformed_gradients = testBase.jacobian(localPoint); // compute product assert(ret.size() >= size); assert(transformed_gradients.size() >= size); //! \TODO WTF muss hier eigentlich hin for (size_t ii = 0; ii < size; ++ii) { // transformed_gradients[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2> ret[ii] = -1 * (flux[0] * transformed_gradients[ii][0]); // DSC_LOG_DEBUG << "DIFF " << global_point << " | " << flux << " | " << grad_phi_s[ii][0]<< std::endl; } } private: const LocalizableFunctionType& inducingFunction_; const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base_set_; const std::size_t coarseBaseFunc_; }; // class CoarseBasisProduct // forward, to be used in the traits class DirichletProduct; /** * \brief Traits for the Product evaluation. */ struct DirichletProductTraits : public ProductTraitsBase { typedef DirichletProduct derived_type; }; class DirichletProduct : public GDT::LocalEvaluation::Codim0Interface<DirichletProductTraits, 1> { public: typedef DirichletProductTraits Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; DirichletProduct(const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension, const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) , dirichlet_extension_(dirichlet_extension) {} template <class EntityType> class LocalfunctionTuple { typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; public: typedef std::tuple<std::shared_ptr<LocalfunctionType>> Type; }; template <class EntityType> typename LocalfunctionTuple<EntityType>::Type localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template <class E, class D, size_t d, class R, size_t rT, size_t rCT> size_t order(const typename LocalfunctionTuple<E>::Type& localFuncs, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const { const auto localFunction = std::get<0>(localFuncs); return order(*localFunction, testBase); } /** * \todo add copydoc * \return localFunction.order() + testBase.order() */ template <class E, class D, size_t d, class R, size_t rL, size_t rCL, size_t rT, size_t rCT> size_t order(const Stuff::LocalfunctionInterface<E, D, d, R, rL, rCL>& localFunction, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const { return localFunction.order() + testBase.order(); } // int order(...) /** * \brief extracts the local functions and calls the correct evaluate() method */ template <class E, class D, size_t d, class R, size_t rT, size_t rCT> void evaluate(const typename LocalfunctionTuple<E>::Type& localFuncs, const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase, const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const { const auto& localFunction = std::get<0>(localFuncs); evaluate(*localFunction, testBase, localPoint, ret); } template< class R, size_t r, size_t rC > void evaluate(const typename Traits::LocalfunctionTupleType& /*localFunctions_in*/, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { // evaluate local function const auto& entity = testBase.entity(); const auto dirichlet_lf = dirichlet_extension_.local_function(entity); const auto direction = dirichlet_lf->jacobian(localPoint); DMP::JacobianRangeType flux; const auto global_point = entity.geometry().global(localPoint); //!TODO make member DMP::getDiffusion().diffusiveFlux(global_point, direction, flux); // evaluate test base const std::size_t size = testBase.size(); typedef typename Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>::JacobianRangeType JR; const std::vector<JR> grad_phi_s = testBase.jacobian(localPoint); // compute product assert(ret.size() >= size); assert(grad_phi_s.size() >= size); //! \TODO WTF muss hier eigentlich hin for (size_t ii = 0; ii < size; ++ii) { // grad_phi_s[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2> ret[ii] = -1 * (flux[0] * grad_phi_s[ii][0]); } } private: const LocalizableFunctionType& inducingFunction_; const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension_; }; // class Product } // namespace Multiscale { } // namespace Dune { #endif // DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH <|endoftext|>
<commit_before>/* * imageresizer.cpp * * Created on: Jul 8, 2016 * Author: Jason */ #include "common/base.h" #include "imageresizer.h" #include <stdexcept> ImageResizer::ImageResizer() :m_handle(NULL), m_result(NULL) { } ImageResizer::~ImageResizer() { } void ImageResizer::Create(int target_width, int target_height) { if(eina_lock_new(&m_mutex)==EINA_FALSE) { throw std::runtime_error("fail to create eina_lock_new"); } if(eina_condition_new(&m_cond, &m_mutex)==EINA_FALSE) { throw std::runtime_error("fail to create eina_lock_new"); } int ret = image_util_transform_create(&m_handle); if(ret != IMAGE_UTIL_ERROR_NONE) { throw std::runtime_error(std::string("fail to image_util_transform_create: ")+to_string(ret)); } ret = image_util_transform_set_resolution(m_handle, target_width, target_height); } void ImageResizer::Destroy() { image_util_transform_destroy(m_handle); m_handle = NULL; eina_condition_free(&m_cond); eina_lock_free(&m_mutex); } bool ImageResizer::Resize(media_packet_h packet, media_packet_h* resized_packet) { dlog_print(DLOG_DEBUG, "ImageResizer", "========================original packet==========================="); print_packet_info(packet); bool is_eos = false; media_packet_is_end_of_stream(packet, &is_eos); int ret = image_util_transform_run(m_handle, packet, ImageResizer::resize_completed_cb, (void*)this); dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run[%d]", ret); if(ret != IMAGE_UTIL_ERROR_NONE) { return false; } eina_condition_wait(&m_cond); *resized_packet = m_result; dlog_print(DLOG_DEBUG, "ImageResizer", "========================resized packet=================[%p], [%p]", *resized_packet, m_result); if(is_eos) { media_packet_set_flags(*resized_packet, MEDIA_PACKET_END_OF_STREAM); } print_packet_info(*resized_packet); dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run signaled"); return true; } void ImageResizer::resize_completed(media_packet_h *dst, int error_code) { m_result = *dst; dlog_print(DLOG_DEBUG, "ImageResizer", "condition signal dst[%p], error_code[%d]", *dst, error_code); eina_condition_signal(&m_cond); } void ImageResizer::resize_completed_cb(media_packet_h *dst, int error_code, void *user_data) { dlog_print(DLOG_DEBUG, "ImageResizer", "resize_completed_cb is called [%p]", *dst ); ImageResizer* resizer = (ImageResizer*)user_data; resizer->resize_completed(dst, error_code); } void ImageResizer::print_packet_info(media_packet_h packet) { uint64_t dts = 0; media_packet_get_dts(packet, &dts); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_dts [%llu]", dts); uint64_t duration = 0; media_packet_get_duration(packet, &duration); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_duration [%llu]", dts); media_format_h fmt = NULL; media_format_mimetype_e mimetype; int width = 0, height = 0, avg_bps=0, max_bps = 0; int ret = media_packet_get_format(packet, &fmt); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_format: [%p] [%d]=====", fmt, ret); media_format_get_video_info(fmt, &mimetype, &width, &height, &avg_bps, &max_bps); dlog_print(DLOG_DEBUG, "ImageResizer", "media_format_get_video_info: vidoe mimetype: %x, w:%d, h:%d, avg_bps:%d, max_bps:%d =====", (int)mimetype, width, height, avg_bps, max_bps); media_format_unref(fmt); bool codec_config = false; media_packet_is_codec_config(packet, &codec_config); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_codec_config [%d]", (int)codec_config); bool is_encoded = false; media_packet_is_encoded(packet, &is_encoded); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_encoded [%d]", (int)is_encoded); bool is_eos = false; media_packet_is_end_of_stream(packet, &is_eos); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_end_of_stream [%d]", (int)is_eos); bool is_raw = false; media_packet_is_raw(packet, &is_raw); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_raw [%d]", (int)is_raw); bool is_sync = false; media_packet_is_sync_frame(packet, &is_sync); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_sync_frame [%d]", (int)is_sync); bool is_video = false; media_packet_is_video(packet, &is_video); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_video [%d]", (int)is_video); } <commit_msg>set the pts of original packet after resizing a packet<commit_after>/* * imageresizer.cpp * * Created on: Jul 8, 2016 * Author: Jason */ #include "common/base.h" #include "imageresizer.h" #include <stdexcept> ImageResizer::ImageResizer() :m_handle(NULL), m_result(NULL) { } ImageResizer::~ImageResizer() { } void ImageResizer::Create(int target_width, int target_height) { if(eina_lock_new(&m_mutex)==EINA_FALSE) { throw std::runtime_error("fail to create eina_lock_new"); } if(eina_condition_new(&m_cond, &m_mutex)==EINA_FALSE) { throw std::runtime_error("fail to create eina_lock_new"); } int ret = image_util_transform_create(&m_handle); if(ret != IMAGE_UTIL_ERROR_NONE) { throw std::runtime_error(std::string("fail to image_util_transform_create: ")+to_string(ret)); } ret = image_util_transform_set_resolution(m_handle, target_width, target_height); } void ImageResizer::Destroy() { image_util_transform_destroy(m_handle); m_handle = NULL; eina_condition_free(&m_cond); eina_lock_free(&m_mutex); } bool ImageResizer::Resize(media_packet_h packet, media_packet_h* resized_packet) { dlog_print(DLOG_DEBUG, "ImageResizer", "========================original packet==========================="); print_packet_info(packet); bool is_eos = false; media_packet_is_end_of_stream(packet, &is_eos); uint64_t pts = 0; media_packet_get_pts(packet, &pts); int ret = image_util_transform_run(m_handle, packet, ImageResizer::resize_completed_cb, (void*)this); dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run[%d]", ret); if(ret != IMAGE_UTIL_ERROR_NONE) { return false; } eina_condition_wait(&m_cond); *resized_packet = m_result; dlog_print(DLOG_DEBUG, "ImageResizer", "========================resized packet=================[%p], [%p]", *resized_packet, m_result); if(is_eos) { media_packet_set_flags(*resized_packet, MEDIA_PACKET_END_OF_STREAM); } media_packet_set_pts(*resized_packet, pts); print_packet_info(*resized_packet); dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run signaled"); return true; } void ImageResizer::resize_completed(media_packet_h *dst, int error_code) { m_result = *dst; dlog_print(DLOG_DEBUG, "ImageResizer", "condition signal dst[%p], error_code[%d]", *dst, error_code); eina_condition_signal(&m_cond); } void ImageResizer::resize_completed_cb(media_packet_h *dst, int error_code, void *user_data) { dlog_print(DLOG_DEBUG, "ImageResizer", "resize_completed_cb is called [%p]", *dst ); ImageResizer* resizer = (ImageResizer*)user_data; resizer->resize_completed(dst, error_code); } void ImageResizer::print_packet_info(media_packet_h packet) { uint64_t pts = 0; media_packet_get_pts(packet, &pts); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_pts [%llu]", pts); uint64_t dts = 0; media_packet_get_dts(packet, &dts); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_dts [%llu]", dts); uint64_t duration = 0; media_packet_get_duration(packet, &duration); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_duration [%llu]", dts); media_format_h fmt = NULL; media_format_mimetype_e mimetype; int width = 0, height = 0, avg_bps=0, max_bps = 0; int ret = media_packet_get_format(packet, &fmt); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_format: [%p] [%d]=====", fmt, ret); media_format_get_video_info(fmt, &mimetype, &width, &height, &avg_bps, &max_bps); dlog_print(DLOG_DEBUG, "ImageResizer", "media_format_get_video_info: vidoe mimetype: %x, w:%d, h:%d, avg_bps:%d, max_bps:%d =====", (int)mimetype, width, height, avg_bps, max_bps); media_format_unref(fmt); bool codec_config = false; media_packet_is_codec_config(packet, &codec_config); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_codec_config [%d]", (int)codec_config); bool is_encoded = false; media_packet_is_encoded(packet, &is_encoded); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_encoded [%d]", (int)is_encoded); bool is_eos = false; media_packet_is_end_of_stream(packet, &is_eos); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_end_of_stream [%d]", (int)is_eos); bool is_raw = false; media_packet_is_raw(packet, &is_raw); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_raw [%d]", (int)is_raw); bool is_sync = false; media_packet_is_sync_frame(packet, &is_sync); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_sync_frame [%d]", (int)is_sync); bool is_video = false; media_packet_is_video(packet, &is_video); dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_video [%d]", (int)is_video); } <|endoftext|>
<commit_before>// // simulator.h // AllenCahnFD // // Created by Yue Sun on 7/20/15. // Copyright (c) 2015 Yue Sun. All rights reserved. // #ifndef __AllenCahnFD__simulator__ #define __AllenCahnFD__simulator__ #include <iostream> #include "cl_common.hpp" // Uncomment the following line if using OpenCL Buffer objects instead of Image objects //#define __USE_CL_BUFFER__ typedef struct { unsigned int x; unsigned int y; unsigned int z; }Dim3; template <typename T> class Simulator { protected: cl_context _context; cl_device_id _device; cl_command_queue _queue; Dim3 _dim; unsigned int _ndim; unsigned int _size; T * _data; unsigned int _current_step; unsigned int _time; bool _cl_initialized; bool _sim_initialized; public: /* Variables */ // OpenCL const cl_context & context; const cl_device_id & device; const cl_command_queue & queue; // Simulation // const T * const data; const unsigned int & current_step; const unsigned int & time; /* Constructors & destructors */ Simulator(const unsigned int nx, const unsigned int ny, const unsigned int nz, const unsigned int ndim); Simulator(const Dim3 dim, const unsigned int ndim); virtual ~Simulator(); /* Functions */ // OpenCL virtual cl_int init_cl(const cl_context & context_, const cl_device_id & device_, const cl_command_queue & queue_=NULL); virtual cl_int init_cl(); virtual cl_int init_cl(const cl_device_type & device_type, const unsigned int & device_num); virtual cl_int build_kernel(const char * filename) {return CL_SUCCESS;}; virtual void finishQueue() {if(_queue)clFinish(_queue);} // write array from host to device cl_int WriteArray(const cl_mem & image, const T* orig, size_t x, size_t y, size_t z=1) { #ifdef __USE_CL_BUFFER__ size_t offset=0; size_t size=x*y*z*sizeof(T); clEnqueueWriteBuffer(_queue, image, true, offset, size, orig, 0, NULL, NULL); #else size_t offset[3]={0,0,0}; size_t size[3]={x,y,z}; clEnqueueWriteImage(_queue, image, true, offset, size, 0, 0, orig, 0, NULL, NULL); #endif return CL_SUCCESS; } // read array from device to host cl_int ReadArray(const cl_mem & image, T* dest, size_t x, size_t y, size_t z=1) { #ifdef __USE_CL_BUFFER__ size_t offset=0; size_t size=x*y*z*sizeof(T); clEnqueueReadBuffer(_queue, image, true, offset, size, dest, 0, NULL, NULL); #else size_t offset[3]={0,0,0}; size_t size[3]={x,y,z}; clEnqueueReadImage(_queue, image, true, offset, size, 0, 0, dest, 0, NULL, NULL); #endif return CL_SUCCESS; }; // simulation virtual void init_sim() {}; virtual void step(const T dt); virtual void steps(const T dt,const unsigned int nsteps,const bool finish=true, const bool cputime=true); // output virtual void writefile(const std::string & filename=""); }; #endif /* defined(__AllenCahnFD__simulator__) */ <commit_msg>Add error checking in WriteArray() and ReadArray()<commit_after>// // simulator.h // AllenCahnFD // // Created by Yue Sun on 7/20/15. // Copyright (c) 2015 Yue Sun. All rights reserved. // #ifndef __AllenCahnFD__simulator__ #define __AllenCahnFD__simulator__ #include <iostream> #include "cl_common.hpp" // Uncomment the following line if using OpenCL Buffer objects instead of Image objects //#define __USE_CL_BUFFER__ typedef struct { unsigned int x; unsigned int y; unsigned int z; }Dim3; template <typename T> class Simulator { protected: cl_context _context; cl_device_id _device; cl_command_queue _queue; Dim3 _dim; unsigned int _ndim; unsigned int _size; T * _data; unsigned int _current_step; unsigned int _time; bool _cl_initialized; bool _sim_initialized; public: /* Variables */ // OpenCL const cl_context & context; const cl_device_id & device; const cl_command_queue & queue; // Simulation // const T * const data; const unsigned int & current_step; const unsigned int & time; /* Constructors & destructors */ Simulator(const unsigned int nx, const unsigned int ny, const unsigned int nz, const unsigned int ndim); Simulator(const Dim3 dim, const unsigned int ndim); virtual ~Simulator(); /* Functions */ // OpenCL virtual cl_int init_cl(const cl_context & context_, const cl_device_id & device_, const cl_command_queue & queue_=NULL); virtual cl_int init_cl(); virtual cl_int init_cl(const cl_device_type & device_type, const unsigned int & device_num); virtual cl_int build_kernel(const char * filename) {return CL_SUCCESS;}; virtual void finishQueue() {if(_queue)clFinish(_queue);} // write array from host to device cl_int WriteArray(const cl_mem & image, const T* orig, size_t x, size_t y, size_t z=1) { #ifdef __USE_CL_BUFFER__ size_t offset=0; size_t size=x*y*z*sizeof(T); CHECK_ERROR(clEnqueueWriteBuffer(_queue, image, true, offset, size, orig, 0, NULL, NULL)); #else size_t offset[3]={0,0,0}; size_t size[3]={x,y,z}; CHECK_ERROR(clEnqueueWriteImage(_queue, image, true, offset, size, 0, 0, orig, 0, NULL, NULL)); #endif return CL_SUCCESS; } // read array from device to host cl_int ReadArray(const cl_mem & image, T* dest, size_t x, size_t y, size_t z=1) { #ifdef __USE_CL_BUFFER__ size_t offset=0; size_t size=x*y*z*sizeof(T); CHECK_ERROR(clEnqueueReadBuffer(_queue, image, true, offset, size, dest, 0, NULL, NULL)); #else size_t offset[3]={0,0,0}; size_t size[3]={x,y,z}; CHECK_ERROR(clEnqueueReadImage(_queue, image, true, offset, size, 0, 0, dest, 0, NULL, NULL)); #endif return CL_SUCCESS; }; // simulation virtual void init_sim() {}; virtual void step(const T dt); virtual void steps(const T dt,const unsigned int nsteps,const bool finish=true, const bool cputime=true); // output virtual void writefile(const std::string & filename=""); }; #endif /* defined(__AllenCahnFD__simulator__) */ <|endoftext|>
<commit_before>//////////////////////////////////////////////////////// // // Bucket representation for TKDInterpolator(Base) // // The class store data and provides the interface to draw and print. // The bucket - generalized histogram bin in N dimensions is represented by unprocessed data like // - experimental PDF value and statistical error // - COG position (n-tuplu) // - boundaries // and interpolated data like // - parameters of the local parabolic fit // - their covariance matrix // // For drawing 2D projections the helper class TKDNodeInfo::TKDNodeDraw is used. // // Author Alexandru Bercuci <A.Bercuci@gsi.de> // //////////////////////////////////////////////////////// #include "TKDNodeInfo.h" #include "TVectorD.h" #include "TMatrixD.h" #include "TRandom.h" #include "TMath.h" ClassImp(TKDNodeInfo) ClassImp(TKDNodeInfo::TKDNodeDraw) //_________________________________________________________________ TKDNodeInfo::TKDNodeInfo(Int_t dim): TObject() ,fNDim(3*dim) ,fData(NULL) ,fNpar(0) ,fNcov(0) ,fPar(NULL) ,fCov(NULL) { // Default constructor fVal[0] = 0.; fVal[1] = 0.; Build(dim); } //_________________________________________________________________ TKDNodeInfo::TKDNodeInfo(const TKDNodeInfo &ref): TObject((TObject&) ref) ,fNDim(ref.fNDim) ,fData(NULL) ,fNpar(0) ,fNcov(0) ,fPar(NULL) ,fCov(NULL) { // Copy constructor Build(fNDim/3); fData = new Float_t[fNDim]; memcpy(fData, ref.fData, fNDim*sizeof(Float_t)); fVal[0] = ref.fVal[0]; fVal[1] = ref.fVal[1]; if(ref.fNpar&&ref.fPar){ fNpar = ref.fNpar; fPar=new Double_t[fNpar]; memcpy(fPar, ref.fPar, fNpar*sizeof(Double_t)); } if(ref.fNcov && ref.fCov){ fNcov = ref.fNcov; fCov=new Double_t[fNcov]; memcpy(fCov, ref.fCov, fNcov*sizeof(Double_t)); } } //_________________________________________________________________ TKDNodeInfo::~TKDNodeInfo() { // Destructor if(fData) delete [] fData; if(fPar) delete [] fPar; if(fCov) delete [] fCov; } //_________________________________________________________________ TKDNodeInfo& TKDNodeInfo::operator=(const TKDNodeInfo & ref) { // Info("operator==()", "..."); Int_t ndim = fNDim/3; if(fNDim != ref.fNDim){ fNDim = ref.fNDim; Build(ndim); } memcpy(fData, ref.fData, fNDim*sizeof(Float_t)); fVal[0] = ref.fVal[0]; fVal[1] = ref.fVal[1]; if(ref.fNpar&&ref.fPar){ fNpar = ref.fNpar; fPar=new Double_t[fNpar]; memcpy(fPar, ref.fPar, fNpar*sizeof(Double_t)); } if(ref.fNcov && ref.fCov){ fNcov = ref.fNcov; fCov=new Double_t[fNcov]; memcpy(fCov, ref.fCov, fNcov*sizeof(Double_t)); } return *this; } //_________________________________________________________________ void TKDNodeInfo::Build(Int_t dim) { // Allocate/Reallocate space for this node. // Info("Build()", "..."); if(!dim) return; fNDim = 3*dim; if(fData) delete [] fData; fData = new Float_t[fNDim]; return; } //_________________________________________________________________ void TKDNodeInfo::Bootstrap() { if(!fNpar || !fPar) return; Int_t ndim = Int_t(.5*(TMath::Sqrt(1.+8.*fNpar)-1.))-1; fNDim = 3*ndim; } //_________________________________________________________________ void TKDNodeInfo::SetNode(Int_t ndim, Float_t *data, Float_t *pdf) { Build(ndim); memcpy(fData, data, fNDim*sizeof(Float_t)); fVal[0]=pdf[0]; fVal[1]=pdf[1]; } //_________________________________________________________________ void TKDNodeInfo::Print(const Option_t *opt) const { // Print the content of the node Int_t dim = Int_t(fNDim/3.); printf("x["); for(int idim=0; idim<dim; idim++) printf("%f ", fData?fData[idim]:0.); printf("] f = [%f +- %f]\n", fVal[0], fVal[1]); if(fData){ Float_t *bounds = &fData[dim]; printf("range["); for(int idim=0; idim<dim; idim++) printf("(%f %f) ", bounds[2*idim], bounds[2*idim+1]); printf("]\n"); } if(strcmp(opt, "a")!=0) return; if(fNpar){ printf("Fit parameters : \n"); for(int ip=0; ip<fNpar; ip++) printf("p%d[%f] ", ip, fPar[ip]); printf("\n"); } if(!fNcov) return; for(int ip(0), n(0); ip<fNpar; ip++){ for(int jp(ip); jp<fNpar; jp++) printf("c(%d %d)[%f] ", ip, jp, fCov[n++]); printf("\n"); } } //_________________________________________________________________ void TKDNodeInfo::Store(TVectorD const *par, TMatrixD const *cov) { // Store the parameters and the covariance in the node if(!fPar){SetNpar(); fPar = new Double_t[fNpar];} for(int ip=0; ip<fNpar; ip++) fPar[ip] = (*par)[ip]; if(!cov) return; if(!fCov){SetNcov(); fCov = new Double_t[fNcov];} for(int ip(0), np(0); ip<fNpar; ip++) for(int jp=ip; jp<fNpar; jp++) fCov[np++] = (*cov)(ip,jp); } //_________________________________________________________________ Bool_t TKDNodeInfo::CookPDF(const Double_t *point, Double_t &result, Double_t &error) const { // Recalculate the PDF for one node from the results of interpolation (parameters and covariance matrix) Int_t ndim = Int_t(fNDim/3.); if(ndim>10) return kFALSE; // support only up to 10 dimensions //printf("ndim[%d] npar[%d] ncov[%d]\n", ndim, fNpar, fNcov); Double_t fdfdp[66]; memset(fdfdp, 0, ndim*sizeof(Double_t)); Int_t ipar = 0; fdfdp[ipar++] = 1.; for(int idim=0; idim<ndim; idim++){ fdfdp[ipar++] = point[idim]; for(int jdim=idim; jdim<ndim; jdim++) fdfdp[ipar++] = point[idim]*point[jdim]; } // calculate estimation result =0.; error = 0.; for(int i=0; i<fNpar; i++) result += fdfdp[i]*fPar[i]; if(!fNcov) return kTRUE; for(int i(0), n(0); i<fNpar; i++){ error += fdfdp[i]*fdfdp[i]*fCov[n++]; for(int j(i+1); j<fNpar; j++) error += 2.*fdfdp[i]*fdfdp[j]*fCov[n++]; } error = TMath::Sqrt(error); //printf("TKDNodeInfo::CookPDF() : %6.3f +- %6.3f\n", result, error); return kTRUE; } //_________________________________________________________________ TKDNodeInfo::TKDNodeDraw::TKDNodeDraw() :TBox() ,fCOG() ,fNode(NULL) { SetFillStyle(3002); SetFillColor(50+Int_t(gRandom->Uniform()*50.)); fCOG.SetMarkerStyle(3); fCOG.SetMarkerSize(.7); fCOG.SetMarkerColor(2); } //_________________________________________________________________ void TKDNodeInfo::TKDNodeDraw::Draw(Option_t* option) { TBox::Draw(option); fCOG.Draw("p"); } //_________________________________________________________________ void TKDNodeInfo::TKDNodeDraw::SetNode(TKDNodeInfo *node, UChar_t size, UChar_t ax1, UChar_t ax2) { fNode=node; const Float_t kBorder = 0.;//1.E-4; Float_t *bounds = &(node->Data()[size]); fX1=bounds[2*ax1]+kBorder; fX2=bounds[2*ax1+1]-kBorder; fY1=bounds[2*ax2]+kBorder; fY2=bounds[2*ax2+1]-kBorder; Float_t x(node->Data()[ax1]), y(node->Data()[ax2]); fCOG.SetX(x); fCOG.SetY(y); } //_________________________________________________________________ void TKDNodeInfo::TKDNodeDraw::Print(const Option_t* option) const { if(!fNode) return; fNode->Print(option); } <commit_msg>fix coverity<commit_after>//////////////////////////////////////////////////////// // // Bucket representation for TKDInterpolator(Base) // // The class store data and provides the interface to draw and print. // The bucket - generalized histogram bin in N dimensions is represented by unprocessed data like // - experimental PDF value and statistical error // - COG position (n-tuplu) // - boundaries // and interpolated data like // - parameters of the local parabolic fit // - their covariance matrix // // For drawing 2D projections the helper class TKDNodeInfo::TKDNodeDraw is used. // // Author Alexandru Bercuci <A.Bercuci@gsi.de> // //////////////////////////////////////////////////////// #include "TKDNodeInfo.h" #include "TVectorD.h" #include "TMatrixD.h" #include "TRandom.h" #include "TMath.h" ClassImp(TKDNodeInfo) ClassImp(TKDNodeInfo::TKDNodeDraw) //_________________________________________________________________ TKDNodeInfo::TKDNodeInfo(Int_t dim): TObject() ,fNDim(3*dim) ,fData(NULL) ,fNpar(0) ,fNcov(0) ,fPar(NULL) ,fCov(NULL) { // Default constructor fVal[0] = 0.; fVal[1] = 0.; Build(dim); } //_________________________________________________________________ TKDNodeInfo::TKDNodeInfo(const TKDNodeInfo &ref): TObject((TObject&) ref) ,fNDim(ref.fNDim) ,fData(NULL) ,fNpar(0) ,fNcov(0) ,fPar(NULL) ,fCov(NULL) { // Copy constructor Build(fNDim/3); fData = new Float_t[fNDim]; memcpy(fData, ref.fData, fNDim*sizeof(Float_t)); fVal[0] = ref.fVal[0]; fVal[1] = ref.fVal[1]; if(ref.fNpar&&ref.fPar){ fNpar = ref.fNpar; fPar=new Double_t[fNpar]; memcpy(fPar, ref.fPar, fNpar*sizeof(Double_t)); } if(ref.fNcov && ref.fCov){ fNcov = ref.fNcov; fCov=new Double_t[fNcov]; memcpy(fCov, ref.fCov, fNcov*sizeof(Double_t)); } } //_________________________________________________________________ TKDNodeInfo::~TKDNodeInfo() { // Destructor if(fData) delete [] fData; if(fPar) delete [] fPar; if(fCov) delete [] fCov; } //_________________________________________________________________ TKDNodeInfo& TKDNodeInfo::operator=(const TKDNodeInfo & ref) { // Info("operator==()", "..."); if(this == &ref) return *this; Int_t ndim = fNDim/3; if(fNDim != ref.fNDim){ fNDim = ref.fNDim; Build(ndim); } memcpy(fData, ref.fData, fNDim*sizeof(Float_t)); fVal[0] = ref.fVal[0]; fVal[1] = ref.fVal[1]; if(ref.fNpar&&ref.fPar){ fNpar = ref.fNpar; fPar=new Double_t[fNpar]; memcpy(fPar, ref.fPar, fNpar*sizeof(Double_t)); } if(ref.fNcov && ref.fCov){ fNcov = ref.fNcov; fCov=new Double_t[fNcov]; memcpy(fCov, ref.fCov, fNcov*sizeof(Double_t)); } return *this; } //_________________________________________________________________ void TKDNodeInfo::Build(Int_t dim) { // Allocate/Reallocate space for this node. // Info("Build()", "..."); if(!dim) return; fNDim = 3*dim; if(fData) delete [] fData; fData = new Float_t[fNDim]; return; } //_________________________________________________________________ void TKDNodeInfo::Bootstrap() { if(!fNpar || !fPar) return; Int_t ndim = Int_t(.5*(TMath::Sqrt(1.+8.*fNpar)-1.))-1; fNDim = 3*ndim; } //_________________________________________________________________ void TKDNodeInfo::SetNode(Int_t ndim, Float_t *data, Float_t *pdf) { Build(ndim); memcpy(fData, data, fNDim*sizeof(Float_t)); fVal[0]=pdf[0]; fVal[1]=pdf[1]; } //_________________________________________________________________ void TKDNodeInfo::Print(const Option_t *opt) const { // Print the content of the node Int_t dim = Int_t(fNDim/3.); printf("x["); for(int idim=0; idim<dim; idim++) printf("%f ", fData?fData[idim]:0.); printf("] f = [%f +- %f]\n", fVal[0], fVal[1]); if(fData){ Float_t *bounds = &fData[dim]; printf("range["); for(int idim=0; idim<dim; idim++) printf("(%f %f) ", bounds[2*idim], bounds[2*idim+1]); printf("]\n"); } if(strcmp(opt, "a")!=0) return; if(fNpar){ printf("Fit parameters : \n"); for(int ip=0; ip<fNpar; ip++) printf("p%d[%f] ", ip, fPar[ip]); printf("\n"); } if(!fNcov) return; for(int ip(0), n(0); ip<fNpar; ip++){ for(int jp(ip); jp<fNpar; jp++) printf("c(%d %d)[%f] ", ip, jp, fCov[n++]); printf("\n"); } } //_________________________________________________________________ void TKDNodeInfo::Store(TVectorD const *par, TMatrixD const *cov) { // Store the parameters and the covariance in the node if(!fPar){SetNpar(); fPar = new Double_t[fNpar];} for(int ip=0; ip<fNpar; ip++) fPar[ip] = (*par)[ip]; if(!cov) return; if(!fCov){SetNcov(); fCov = new Double_t[fNcov];} for(int ip(0), np(0); ip<fNpar; ip++) for(int jp=ip; jp<fNpar; jp++) fCov[np++] = (*cov)(ip,jp); } //_________________________________________________________________ Bool_t TKDNodeInfo::CookPDF(const Double_t *point, Double_t &result, Double_t &error) const { // Recalculate the PDF for one node from the results of interpolation (parameters and covariance matrix) Int_t ndim = Int_t(fNDim/3.); if(ndim>10) return kFALSE; // support only up to 10 dimensions //printf("ndim[%d] npar[%d] ncov[%d]\n", ndim, fNpar, fNcov); Double_t fdfdp[66]; memset(fdfdp, 0, ndim*sizeof(Double_t)); Int_t ipar = 0; fdfdp[ipar++] = 1.; for(int idim=0; idim<ndim; idim++){ fdfdp[ipar++] = point[idim]; for(int jdim=idim; jdim<ndim; jdim++) fdfdp[ipar++] = point[idim]*point[jdim]; } // calculate estimation result =0.; error = 0.; for(int i=0; i<fNpar; i++) result += fdfdp[i]*fPar[i]; if(!fNcov) return kTRUE; for(int i(0), n(0); i<fNpar; i++){ error += fdfdp[i]*fdfdp[i]*fCov[n++]; for(int j(i+1); j<fNpar; j++) error += 2.*fdfdp[i]*fdfdp[j]*fCov[n++]; } error = TMath::Sqrt(error); //printf("TKDNodeInfo::CookPDF() : %6.3f +- %6.3f\n", result, error); return kTRUE; } //_________________________________________________________________ TKDNodeInfo::TKDNodeDraw::TKDNodeDraw() :TBox() ,fCOG() ,fNode(NULL) { SetFillStyle(3002); SetFillColor(50+Int_t(gRandom->Uniform()*50.)); fCOG.SetMarkerStyle(3); fCOG.SetMarkerSize(.7); fCOG.SetMarkerColor(2); } //_________________________________________________________________ void TKDNodeInfo::TKDNodeDraw::Draw(Option_t* option) { TBox::Draw(option); fCOG.Draw("p"); } //_________________________________________________________________ void TKDNodeInfo::TKDNodeDraw::SetNode(TKDNodeInfo *node, UChar_t size, UChar_t ax1, UChar_t ax2) { fNode=node; const Float_t kBorder = 0.;//1.E-4; Float_t *bounds = &(node->Data()[size]); fX1=bounds[2*ax1]+kBorder; fX2=bounds[2*ax1+1]-kBorder; fY1=bounds[2*ax2]+kBorder; fY2=bounds[2*ax2+1]-kBorder; Float_t x(node->Data()[ax1]), y(node->Data()[ax2]); fCOG.SetX(x); fCOG.SetY(y); } //_________________________________________________________________ void TKDNodeInfo::TKDNodeDraw::Print(const Option_t* option) const { if(!fNode) return; fNode->Print(option); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Implementation of the AliTracker class // that is the base for AliTPCtracker, AliITStrackerV2 and AliTRDtracker // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch //------------------------------------------------------------------------- #include <TMath.h> #include "AliTracker.h" #include "AliCluster.h" #include "AliKalmanTrack.h" #include "AliLog.h" #include "AliRun.h" #include "AliMagF.h" const AliMagF *AliTracker::fgkFieldMap=0; ClassImp(AliTracker) AliTracker::AliTracker(): fEventN(0), fStoreBarrel(1), fX(0), fY(0), fZ(0), fSigmaX(0.005), fSigmaY(0.005), fSigmaZ(0.010) { //-------------------------------------------------------------------- // The default constructor. //-------------------------------------------------------------------- AliRunLoader* runLoader = AliRunLoader::GetRunLoader(); if (!runLoader) AliFatal("Can't get the default run loader"); if (!runLoader->GetAliRun()) runLoader->LoadgAlice(); if (!runLoader->GetAliRun()) AliFatal("Can't get the AliRun object"); AliMagF *field=runLoader->GetAliRun()->Field(); if (field==0) AliFatal("Can't access the field map !"); SetFieldMap(field); } void AliTracker::SetFieldMap(const AliMagF* map) { //-------------------------------------------------------------------- //This passes the field map to the reconstruction. //-------------------------------------------------------------------- if (map==0) AliFatalClass("Can't access the field map !"); AliKalmanTrack::SetConvConst(1000/0.299792458/(map->SolenoidField()+1e-13)); fgkFieldMap=map; } //__________________________________________________________________________ void AliTracker::CookLabel(AliKalmanTrack *t, Float_t wrong) const { //-------------------------------------------------------------------- //This function "cooks" a track label. If label<0, this track is fake. //-------------------------------------------------------------------- Int_t noc=t->GetNumberOfClusters(); Int_t *lb=new Int_t[noc]; Int_t *mx=new Int_t[noc]; AliCluster **clusters=new AliCluster*[noc]; Int_t i; for (i=0; i<noc; i++) { lb[i]=mx[i]=0; Int_t index=t->GetClusterIndex(i); clusters[i]=GetCluster(index); } Int_t lab=123456789; for (i=0; i<noc; i++) { AliCluster *c=clusters[i]; lab=TMath::Abs(c->GetLabel(0)); Int_t j; for (j=0; j<noc; j++) if (lb[j]==lab || mx[j]==0) break; lb[j]=lab; (mx[j])++; } Int_t max=0; for (i=0; i<noc; i++) if (mx[i]>max) {max=mx[i]; lab=lb[i];} for (i=0; i<noc; i++) { AliCluster *c=clusters[i]; //if (TMath::Abs(c->GetLabel(1)) == lab || // TMath::Abs(c->GetLabel(2)) == lab ) max++; if (TMath::Abs(c->GetLabel(0)!=lab)) if (TMath::Abs(c->GetLabel(1)) == lab || TMath::Abs(c->GetLabel(2)) == lab ) max++; } if ((1.- Float_t(max)/noc) > wrong) lab=-lab; t->SetFakeRatio((1.- Float_t(max)/noc)); t->SetLabel(lab); delete[] lb; delete[] mx; delete[] clusters; } //____________________________________________________________________________ void AliTracker::UseClusters(const AliKalmanTrack *t, Int_t from) const { //------------------------------------------------------------------ //This function marks clusters associated with the track. //------------------------------------------------------------------ Int_t noc=t->GetNumberOfClusters(); for (Int_t i=from; i<noc; i++) { Int_t index=t->GetClusterIndex(i); AliCluster *c=GetCluster(index); c->Use(); } } <commit_msg>don't set the field map in the constructor (it's done by AliReconstruction)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Implementation of the AliTracker class // that is the base for AliTPCtracker, AliITStrackerV2 and AliTRDtracker // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch //------------------------------------------------------------------------- #include <TMath.h> #include "AliTracker.h" #include "AliCluster.h" #include "AliKalmanTrack.h" #include "AliLog.h" #include "AliRun.h" #include "AliMagF.h" const AliMagF *AliTracker::fgkFieldMap=0; ClassImp(AliTracker) AliTracker::AliTracker(): fEventN(0), fStoreBarrel(1), fX(0), fY(0), fZ(0), fSigmaX(0.005), fSigmaY(0.005), fSigmaZ(0.010) { //-------------------------------------------------------------------- // The default constructor. //-------------------------------------------------------------------- if (!fgkFieldMap) AliWarning("Field map is not set. Call AliTracker::SetFieldMap before creating a tracker!"); } void AliTracker::SetFieldMap(const AliMagF* map) { //-------------------------------------------------------------------- //This passes the field map to the reconstruction. //-------------------------------------------------------------------- if (map==0) AliFatalClass("Can't access the field map !"); AliKalmanTrack::SetConvConst(1000/0.299792458/(map->SolenoidField()+1e-13)); fgkFieldMap=map; } //__________________________________________________________________________ void AliTracker::CookLabel(AliKalmanTrack *t, Float_t wrong) const { //-------------------------------------------------------------------- //This function "cooks" a track label. If label<0, this track is fake. //-------------------------------------------------------------------- Int_t noc=t->GetNumberOfClusters(); Int_t *lb=new Int_t[noc]; Int_t *mx=new Int_t[noc]; AliCluster **clusters=new AliCluster*[noc]; Int_t i; for (i=0; i<noc; i++) { lb[i]=mx[i]=0; Int_t index=t->GetClusterIndex(i); clusters[i]=GetCluster(index); } Int_t lab=123456789; for (i=0; i<noc; i++) { AliCluster *c=clusters[i]; lab=TMath::Abs(c->GetLabel(0)); Int_t j; for (j=0; j<noc; j++) if (lb[j]==lab || mx[j]==0) break; lb[j]=lab; (mx[j])++; } Int_t max=0; for (i=0; i<noc; i++) if (mx[i]>max) {max=mx[i]; lab=lb[i];} for (i=0; i<noc; i++) { AliCluster *c=clusters[i]; //if (TMath::Abs(c->GetLabel(1)) == lab || // TMath::Abs(c->GetLabel(2)) == lab ) max++; if (TMath::Abs(c->GetLabel(0)!=lab)) if (TMath::Abs(c->GetLabel(1)) == lab || TMath::Abs(c->GetLabel(2)) == lab ) max++; } if ((1.- Float_t(max)/noc) > wrong) lab=-lab; t->SetFakeRatio((1.- Float_t(max)/noc)); t->SetLabel(lab); delete[] lb; delete[] mx; delete[] clusters; } //____________________________________________________________________________ void AliTracker::UseClusters(const AliKalmanTrack *t, Int_t from) const { //------------------------------------------------------------------ //This function marks clusters associated with the track. //------------------------------------------------------------------ Int_t noc=t->GetNumberOfClusters(); for (Int_t i=from; i<noc; i++) { Int_t index=t->GetClusterIndex(i); AliCluster *c=GetCluster(index); c->Use(); } } <|endoftext|>
<commit_before>// Copyright 2020 the Open GEE Contributors. // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <sys/prctl.h> #include <sys/types.h> #include <unistd.h> #include <Qt/qobjectdefs.h> #include <Qt/qapplication.h> #include <Qt/qpainter.h> #include <Qt/qstylefactory.h> #include <gstRegistry.h> #include <Qt/qtranslator.h> #include <Qt/qtextcodec.h> #include <Qt/qgl.h> #include <Qt/qwidget.h> #include <Qt/qimage.h> #include <Qt/qfile.h> #include <Qt/qeventloop.h> #include <Qt/qdesktopwidget.h> #include <Qt/qsplashscreen.h> #include <builddate.h> #include "fusion/fusionversion.h" #include "fusion/fusionui/MainWindow.h" #include "fusion/fusionui/GlobalFusion.h" #include "fusion/fusionui/Preferences.h" #include "fusion/fusionui/SystemListener.h" #include "fusion/autoingest/khVolumeManager.h" #include "fusion/autoingest/MiscConfig.h" #include "fusion/fusionui/GfxView.h" #include "common/geFilePool.h" #include "common/geInstallPaths.h" #include "common/khFileUtils.h" #include "common/khGetopt.h" // generated rcc -name resources -namespace resources.qrc >resources.cpp #include "images/resources.cpp" class SplashScreen : public QSplashScreen { public: explicit SplashScreen(const QPixmap& pix = QPixmap(), Qt::WindowFlags f = 0); void setStatus(const QString &message, int alignment = Qt::AlignLeft, const QColor &color = Qt::white); void finish(QWidget* main_win); void repaint(); private: QPixmap pix_; }; // WStyle_Customize no longer needed: https://doc.qt.io/archives/qt-4.8/qt.html SplashScreen::SplashScreen(const QPixmap& pix, Qt::WindowFlags f) : QSplashScreen(0, pix, f), pix_(pix) { resize(pix_.size()); QRect scr = QApplication::desktop()->screenGeometry(); move(scr.center() - rect().center()); QString versionText = QString("%1 v%2") .arg(GetFusionProductShortName().c_str()) .arg(GEE_VERSION); setFont(QFont("arial", 13)); QPainter painter(&pix_); QColor dark_green(3, 158, 40); painter.setPen(dark_green); QRect r = rect(); painter.boundingRect(r, Qt::AlignLeft | Qt::AlignTop, versionText); painter.drawText(5, r.height() - 16, versionText); setErasePixmap(pix_); show(); repaint(); } void SplashScreen::repaint() { QWidget::repaint(); QApplication::flush(); } void SplashScreen::finish(QWidget* main_win) { close(); } void SplashScreen::setStatus(const QString& message, int alignment, const QColor& color) { setFont(QFont("Times", 10, QFont::Bold)); QPixmap text_pix = pix_; QPainter painter(&text_pix); painter.setPen(color); QRect r = rect(); r.setRect(r.x() + 10, r.y() + 10, r.width() - 20, r.height() - 20); painter.drawText(r, alignment, message); setErasePixmap(text_pix); repaint(); } // ----------------------------------------------------------------------------- int main(int argc, char** argv) { int argn; FusionProductType type = GetFusionProductType(); khGetopt options; options.choiceOpt("mode", type, makemap(std::string("LT"), FusionLT, std::string("Pro"), FusionPro, std::string("Internal"), FusionInternal)); if (!options.processAll(argc, argv, argn)) { notify(NFY_FATAL, "Error processing commandline options"); } SetFusionProductType(type); // // must always create QApplication before initializing gst library // QApplication a(argc, argv); Q_INIT_RESOURCE(resources); // // confirm opengl support // if (!QGLFormat::hasOpenGL()) { qWarning("This system has no OpenGL support. Exiting."); return EXIT_FAILURE; } // // Pre-initialize the volume manager so it will find any problems // before we really do any work // theVolumeManager.Init(); // Turn off any site-configured delay before accessing small files. // This just causes the GUI to look like it's hung. If the file really // isn't written yet, the low level routines will report an arror that // the GUI will report. The user can then retry it later. MiscConfig::Instance().NFSVisibilityDelay = 0; // // display splash screen // QString pixname("fusion_splash.png"); if (!QFile::exists(pixname)) { pixname = khComposePath(kGESharePath, pixname.toUtf8().constData()).c_str(); if (!QFile::exists(pixname)) pixname.resize(0); } SplashScreen* splash = NULL; if (!pixname.isEmpty()) { QPixmap pixmap(pixname); splash = new SplashScreen(pixmap); a.processEvents(); } // // initialize the gst library // geFilePool file_pool; gstInit(&file_pool); // // initialize all fusion globals // Preferences::init(); GlobalFusion::init(); // // qglwidget defaults to no alpha channel, turn this on // QGLFormat f; f.setAlpha(true); QGLFormat::setDefaultFormat(f); // TODO: translations // install translator // disabling for now /*QTranslator translator(0,0); if (translator.load(QString("fusion_") + QTextCodec::locale(), ".")) { a.installTranslator(&translator); } else if (translator.load(QString("fusion_") + QTextCodec::locale(), kGESharePath)) { a.installTranslator(&translator); }*/ // // configure qt style // a.setStyle(QStyleFactory::create("platinum")); try { // // launch the system listener // SystemListener listener; AssetWatcherManager watcherManager; // // launch gui now // MainWindow* w = new MainWindow(); // check if system has valid GL context. if (!w->gfxview->isValid()) { if (splash) { splash->finish(w); delete splash; } delete w; qWarning("Sorry, this system doesn't have sufficient OpenGL resources."); qWarning("Try setting LIBGL_ALWAYS_INDIRECT=yes in your environment."); return EXIT_FAILURE; } // initialize main window. w->Init(); // first event is really slow for some unknown reason // so process it now before taking the splash screen away try { a.processEvents(QEventLoop::ExcludeUserInputEvents, 10); w->show(); } catch(const std::exception& e) { notify(NFY_WARN, "Caught exception: %s", e.what()); } if (splash) { splash->finish(w); delete splash; } a.connect(&a, SIGNAL(lastWindowClosed()), w, SLOT(fileExit())); // qt3 support method a.setMainWidget(w); int status = a.exec(); delete w; return status; } catch(const std::exception& e) { notify(NFY_FATAL, "Caught exception: %s", e.what()); } catch(...) { notify(NFY_FATAL, "Caught unknown exception"); } return 1; } <commit_msg>Enable setgid support for fusion ui (#1964)<commit_after>// Copyright 2020 the Open GEE Contributors. // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <sys/prctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <Qt/qobjectdefs.h> #include <Qt/qapplication.h> #include <Qt/qpainter.h> #include <Qt/qstylefactory.h> #include <gstRegistry.h> #include <Qt/qtranslator.h> #include <Qt/qtextcodec.h> #include <Qt/qgl.h> #include <Qt/qwidget.h> #include <Qt/qimage.h> #include <Qt/qfile.h> #include <Qt/qeventloop.h> #include <Qt/qdesktopwidget.h> #include <Qt/qsplashscreen.h> #include <builddate.h> #include "fusion/fusionversion.h" #include "fusion/fusionui/MainWindow.h" #include "fusion/fusionui/GlobalFusion.h" #include "fusion/fusionui/Preferences.h" #include "fusion/fusionui/SystemListener.h" #include "fusion/autoingest/khVolumeManager.h" #include "fusion/autoingest/MiscConfig.h" #include "fusion/fusionui/GfxView.h" #include "common/geFilePool.h" #include "common/geInstallPaths.h" #include "common/khFileUtils.h" #include "common/khGetopt.h" // generated rcc -name resources -namespace resources.qrc >resources.cpp #include "images/resources.cpp" class SplashScreen : public QSplashScreen { public: explicit SplashScreen(const QPixmap& pix = QPixmap(), Qt::WindowFlags f = 0); void setStatus(const QString &message, int alignment = Qt::AlignLeft, const QColor &color = Qt::white); void finish(QWidget* main_win); void repaint(); private: QPixmap pix_; }; // WStyle_Customize no longer needed: https://doc.qt.io/archives/qt-4.8/qt.html SplashScreen::SplashScreen(const QPixmap& pix, Qt::WindowFlags f) : QSplashScreen(0, pix, f), pix_(pix) { resize(pix_.size()); QRect scr = QApplication::desktop()->screenGeometry(); move(scr.center() - rect().center()); QString versionText = QString("%1 v%2") .arg(GetFusionProductShortName().c_str()) .arg(GEE_VERSION); setFont(QFont("arial", 13)); QPainter painter(&pix_); QColor dark_green(3, 158, 40); painter.setPen(dark_green); QRect r = rect(); painter.boundingRect(r, Qt::AlignLeft | Qt::AlignTop, versionText); painter.drawText(5, r.height() - 16, versionText); setErasePixmap(pix_); show(); repaint(); } void SplashScreen::repaint() { QWidget::repaint(); QApplication::flush(); } void SplashScreen::finish(QWidget* main_win) { close(); } void SplashScreen::setStatus(const QString& message, int alignment, const QColor& color) { setFont(QFont("Times", 10, QFont::Bold)); QPixmap text_pix = pix_; QPainter painter(&text_pix); painter.setPen(color); QRect r = rect(); r.setRect(r.x() + 10, r.y() + 10, r.width() - 20, r.height() - 20); painter.drawText(r, alignment, message); setErasePixmap(text_pix); repaint(); } // ----------------------------------------------------------------------------- int main(int argc, char** argv) { int argn; // requires chmod g+s and /sbin/setcap cap_setgid=ep to be used. if(getgid() != getegid()) { setgid(getegid()); umask(002); } FusionProductType type = GetFusionProductType(); khGetopt options; options.choiceOpt("mode", type, makemap(std::string("LT"), FusionLT, std::string("Pro"), FusionPro, std::string("Internal"), FusionInternal)); if (!options.processAll(argc, argv, argn)) { notify(NFY_FATAL, "Error processing commandline options"); } SetFusionProductType(type); // // must always create QApplication before initializing gst library // QApplication a(argc, argv); Q_INIT_RESOURCE(resources); // // confirm opengl support // if (!QGLFormat::hasOpenGL()) { qWarning("This system has no OpenGL support. Exiting."); return EXIT_FAILURE; } // // Pre-initialize the volume manager so it will find any problems // before we really do any work // theVolumeManager.Init(); // Turn off any site-configured delay before accessing small files. // This just causes the GUI to look like it's hung. If the file really // isn't written yet, the low level routines will report an arror that // the GUI will report. The user can then retry it later. MiscConfig::Instance().NFSVisibilityDelay = 0; // // display splash screen // QString pixname("fusion_splash.png"); if (!QFile::exists(pixname)) { pixname = khComposePath(kGESharePath, pixname.toUtf8().constData()).c_str(); if (!QFile::exists(pixname)) pixname.resize(0); } SplashScreen* splash = NULL; if (!pixname.isEmpty()) { QPixmap pixmap(pixname); splash = new SplashScreen(pixmap); a.processEvents(); } // // initialize the gst library // geFilePool file_pool; gstInit(&file_pool); // // initialize all fusion globals // Preferences::init(); GlobalFusion::init(); // // qglwidget defaults to no alpha channel, turn this on // QGLFormat f; f.setAlpha(true); QGLFormat::setDefaultFormat(f); // TODO: translations // install translator // disabling for now /*QTranslator translator(0,0); if (translator.load(QString("fusion_") + QTextCodec::locale(), ".")) { a.installTranslator(&translator); } else if (translator.load(QString("fusion_") + QTextCodec::locale(), kGESharePath)) { a.installTranslator(&translator); }*/ // // configure qt style // a.setStyle(QStyleFactory::create("platinum")); try { // // launch the system listener // SystemListener listener; AssetWatcherManager watcherManager; // // launch gui now // MainWindow* w = new MainWindow(); // check if system has valid GL context. if (!w->gfxview->isValid()) { if (splash) { splash->finish(w); delete splash; } delete w; qWarning("Sorry, this system doesn't have sufficient OpenGL resources."); qWarning("Try setting LIBGL_ALWAYS_INDIRECT=yes in your environment."); return EXIT_FAILURE; } // initialize main window. w->Init(); // first event is really slow for some unknown reason // so process it now before taking the splash screen away try { a.processEvents(QEventLoop::ExcludeUserInputEvents, 10); w->show(); } catch(const std::exception& e) { notify(NFY_WARN, "Caught exception: %s", e.what()); } if (splash) { splash->finish(w); delete splash; } a.connect(&a, SIGNAL(lastWindowClosed()), w, SLOT(fileExit())); // qt3 support method a.setMainWidget(w); int status = a.exec(); delete w; return status; } catch(const std::exception& e) { notify(NFY_FATAL, "Caught exception: %s", e.what()); } catch(...) { notify(NFY_FATAL, "Caught unknown exception"); } return 1; } <|endoftext|>
<commit_before>#include <cstring> #include "ch.h" #include "hal.h" #include "chprintf.h" #include "ff.h" #include "ADXL345.h" #include "ITG3200.h" #include "HMC5843.h" #include "SampleAndControl.h" #include "SampleBuffer.h" #include "SpeedController.h" // Class static data SampleAndControl * SampleAndControl::instance_ = 0; WORKING_AREA(SampleAndControl::waControlThread, 1024); FIL SampleAndControl::f_; EncoderTimers SampleAndControl::timers; SampleAndControl::SampleAndControl() : Control_tp_(NULL), Enabled_(false) { SetFilename("samples.dat"); } __attribute__((noreturn)) void SampleAndControl::Control(__attribute__((unused))void * arg) { chRegSetThreadName("Control"); /* * Initialize the StickIMU Sensors */ ITG3200Init(); ADXL345Init(); HMC5843Init(); FloatSpeedController & speedControl = FloatSpeedController::Instance(); SampleBuffer & sb = SampleBuffer::Instance(); systime_t time = chTimeNow(); // Initial time for (uint32_t i = 0; !chThdShouldTerminate(); ++i) { time += MS2ST(5); // Next deadline palTogglePad(IOPORT3, GPIOC_TIMING_PIN); // Sanity check for loop timing Sample & s = sb.CurrentSample(); s.systemTime = chTimeNow(); ITG3200Acquire(s); ADXL345Acquire(s); // copy magnetometer signal to the current sample if (i % 4 == 0) { HMC5843Acquire(s); } else { sb.HoldMagnetometer(); } s.steerAngle = STM32_TIM3->CNT; // Capture encoder angle s.rearWheelRate = SampleAndControl::timers.Clockticks[0]; s.frontWheelRate = SampleAndControl::timers.Clockticks[1]; s.steerRate = SampleAndControl::timers.Clockticks[2]; s.Speed_sp = speedControl.SetPoint(); s.YawRate_sp = 0.0; // need to implement yaw rate controller // Compute new speed control action if controller is enabled. if (speedControl.Enabled() && ((i % 4) == 0)) speedControl.Update(s); // if (yawControl.Enabled()) // yawControl.Update(s); s.CCR_rw = STM32_TIM1->CCR[1]; // Save rear wheel duty s.CCR_steer = STM32_TIM1->CCR[0]; // Save steer duty ++sb; // Increment to the next sample // Otherwise go to sleep until next 5ms interval chThdSleepUntil(time); } sb.Flush(); chThdExit(0); } void SampleAndControl::chshellcmd(BaseSequentialStream *chp, int argc, char *argv[]) { SampleAndControl::Instance().shellcmd(chp, argc, argv); } void SampleAndControl::shellcmd(BaseSequentialStream *chp, int argc, char *argv[]) { if (argc == 0) { // toggle enabled/disabled if (Enabled()) { Disable(); if (Disabled()) { chprintf(chp, "Sample & Control thread disabled.\r\n"); } else { chprintf(chp, "Unable to disable Sample & Control thread.\r\n"); } } else { Enable(); if (Enabled()) { chprintf(chp, "Sample & Control thread enabled.\r\n"); } else { chprintf(chp, "Unable to enable Sample & Control thread.\r\n"); } } } else if (argc == 1) { // change filename if (Enabled()) { chprintf(chp, "Disable control thread before changing files.\r\n"); } else { SetFilename(argv[0]); chprintf(chp, "Filename changed to %s.\r\n", Filename_); } } return; } SampleAndControl & SampleAndControl::Instance() { static uint8_t allocation[sizeof(SampleAndControl)]; if (instance_ == 0) instance_ = new (allocation) SampleAndControl; return *instance_; } void * SampleAndControl::operator new(std::size_t, void * location) { return location; } /* * This function should: * 1) Open a FIL object in write mode with filename Filename_ * a) if unable, return without Enabling * 2) Get a reference to SampleBuffer call connectToFile(&f); * a) file must be Open and Writable for this to work. It is up to client of * SampleBuffer to ensure this is the case, no error checking is * performed. * 3) Start the control thread. */ void SampleAndControl::Enable() { if (f_open(&SampleAndControl::f_, Filename_, FA_CREATE_ALWAYS | FA_WRITE)) return; SampleBuffer::Instance().File(&SampleAndControl::f_); nvicEnableVector(TIM4_IRQn, CORTEX_PRIORITY_MASK(7)); Control_tp_ = chThdCreateStatic(SampleAndControl::waControlThread, sizeof(waControlThread), NORMALPRIO, (tfunc_t) Control, NULL); Enabled_ = true; } void SampleAndControl::Disable() { chThdTerminate(Control_tp_); chThdWait(Control_tp_); Control_tp_ = NULL; nvicDisableVector(TIM4_IRQn); Enabled_ = false; } void SampleAndControl::SetFilename(const char * name) { std::strcpy(Filename_, name); } <commit_msg>Disable the speed controller when main control loop is disabled.<commit_after>#include <cstring> #include "ch.h" #include "hal.h" #include "chprintf.h" #include "ff.h" #include "ADXL345.h" #include "ITG3200.h" #include "HMC5843.h" #include "SampleAndControl.h" #include "SampleBuffer.h" #include "SpeedController.h" // Class static data SampleAndControl * SampleAndControl::instance_ = 0; WORKING_AREA(SampleAndControl::waControlThread, 1024); FIL SampleAndControl::f_; EncoderTimers SampleAndControl::timers; SampleAndControl::SampleAndControl() : Control_tp_(NULL), Enabled_(false) { SetFilename("samples.dat"); } __attribute__((noreturn)) void SampleAndControl::Control(__attribute__((unused))void * arg) { chRegSetThreadName("Control"); /* * Initialize the StickIMU Sensors */ ITG3200Init(); ADXL345Init(); HMC5843Init(); FloatSpeedController & speedControl = FloatSpeedController::Instance(); SampleBuffer & sb = SampleBuffer::Instance(); systime_t time = chTimeNow(); // Initial time for (uint32_t i = 0; !chThdShouldTerminate(); ++i) { time += MS2ST(5); // Next deadline palTogglePad(IOPORT3, GPIOC_TIMING_PIN); // Sanity check for loop timing Sample & s = sb.CurrentSample(); s.systemTime = chTimeNow(); ITG3200Acquire(s); ADXL345Acquire(s); // copy magnetometer signal to the current sample if (i % 4 == 0) { HMC5843Acquire(s); } else { sb.HoldMagnetometer(); } s.steerAngle = STM32_TIM3->CNT; // Capture encoder angle s.rearWheelRate = SampleAndControl::timers.Clockticks[0]; s.frontWheelRate = SampleAndControl::timers.Clockticks[1]; s.steerRate = SampleAndControl::timers.Clockticks[2]; s.Speed_sp = speedControl.SetPoint(); s.YawRate_sp = 0.0; // need to implement yaw rate controller // Compute new speed control action if controller is enabled. if (speedControl.Enabled() && ((i % 4) == 0)) speedControl.Update(s); // if (yawControl.Enabled()) // yawControl.Update(s); s.CCR_rw = STM32_TIM1->CCR[1]; // Save rear wheel duty s.CCR_steer = STM32_TIM1->CCR[0]; // Save steer duty ++sb; // Increment to the next sample // Otherwise go to sleep until next 5ms interval chThdSleepUntil(time); } sb.Flush(); chThdExit(0); } void SampleAndControl::chshellcmd(BaseSequentialStream *chp, int argc, char *argv[]) { SampleAndControl::Instance().shellcmd(chp, argc, argv); } void SampleAndControl::shellcmd(BaseSequentialStream *chp, int argc, char *argv[]) { if (argc == 0) { // toggle enabled/disabled if (Enabled()) { Disable(); if (Disabled()) { chprintf(chp, "Sample & Control thread disabled.\r\n"); } else { chprintf(chp, "Unable to disable Sample & Control thread.\r\n"); } } else { Enable(); if (Enabled()) { chprintf(chp, "Sample & Control thread enabled.\r\n"); } else { chprintf(chp, "Unable to enable Sample & Control thread.\r\n"); } } } else if (argc == 1) { // change filename if (Enabled()) { chprintf(chp, "Disable control thread before changing files.\r\n"); } else { SetFilename(argv[0]); chprintf(chp, "Filename changed to %s.\r\n", Filename_); } } return; } SampleAndControl & SampleAndControl::Instance() { static uint8_t allocation[sizeof(SampleAndControl)]; if (instance_ == 0) instance_ = new (allocation) SampleAndControl; return *instance_; } void * SampleAndControl::operator new(std::size_t, void * location) { return location; } /* * This function should: * 1) Open a FIL object in write mode with filename Filename_ * a) if unable, return without Enabling * 2) Get a reference to SampleBuffer call connectToFile(&f); * a) file must be Open and Writable for this to work. It is up to client of * SampleBuffer to ensure this is the case, no error checking is * performed. * 3) Start the control thread. */ void SampleAndControl::Enable() { if (f_open(&SampleAndControl::f_, Filename_, FA_CREATE_ALWAYS | FA_WRITE)) return; SampleBuffer::Instance().File(&SampleAndControl::f_); nvicEnableVector(TIM4_IRQn, CORTEX_PRIORITY_MASK(7)); Control_tp_ = chThdCreateStatic(SampleAndControl::waControlThread, sizeof(waControlThread), NORMALPRIO, (tfunc_t) Control, NULL); Enabled_ = true; } void SampleAndControl::Disable() { FloatSpeedController::Instance().Disable(); chThdTerminate(Control_tp_); chThdWait(Control_tp_); Control_tp_ = NULL; nvicDisableVector(TIM4_IRQn); Enabled_ = false; } void SampleAndControl::SetFilename(const char * name) { std::strcpy(Filename_, name); } <|endoftext|>
<commit_before>#include <functional> #include <array> #include <iostream> #include <random> #include "Common.h" #include "CGame.h" namespace odb { void CGame::reset() { timeEllapsed = 0; } CGame::CGame() { gameState = EGameState::kGame; reset(); } void CGame::tick(long ms) { timeEllapsed += ms; //20 km/h //1h = 60 minutes * 60 seconds * 1000 ms float secondsSinceLastTick = ms / 1000.0f; float distanceSinceLastTick = carSpeed * secondsSinceLastTick; distanceRan += distanceSinceLastTick; distanceToNextElement -= distanceSinceLastTick; if (distanceToNextElement <= 0 ) { distanceToNextElement = kSegmentLengthInMeters; elementIndex = ( elementIndex + 1) % track.size(); //len track } x += xSpeed * carSpeed * 0.2f; if ( distanceToNextElement < ( kSegmentLengthInMeters / 2) ) { char shape = track[elementIndex]; int shapeDelta = 0; if (shape == ')') { shapeDelta = -1; x+= 0.15f * carSpeed; } if (shape == '(') { shapeDelta = 1; x-= 0.15f * carSpeed; } mHeading -= (shapeDelta / 1000.0f) + ( x / (640.0f * 10000.0f) ); } if ( x < -160 || x > 160 ) { } } CControlCallback CGame::getKeyPressedCallback() { return [&](ECommand command) { if (command == ECommand::kLeft) { std::cout << "left pressed" << std::endl; xSpeed = -1; } if (command == ECommand::kRight) { std::cout << "Right pressed" << std::endl; xSpeed = 1; } if (command == ECommand::kUp) { std::cout << "up pressed" << std::endl; } if (command == ECommand::kDown) { std::cout << "down pressed" << std::endl; } if (command == ECommand::kFire1) { std::cout << "fire1 pressed" << std::endl; } }; } CControlCallback CGame::getKeyReleasedCallback() { return [&](ECommand command) { xSpeed = 0; switch (gameState) { case EGameState::kGame: if (command == ECommand::kLeft) { std::cout << "left released" << std::endl; } if (command == ECommand::kRight) { std::cout << "right released" << std::endl; } if (command == ECommand::kUp) { std::cout << "up released" << std::endl; carSpeed = std::min( carSpeed + 5, 50); } if (command == ECommand::kDown) { std::cout << "down released" << std::endl; carSpeed = std::max( carSpeed - 5, 0); } if (command == ECommand::kFire1) { std::cout << "fire1 released" << std::endl; carSpeed = 0; } return; case EGameState::kGameOver: case EGameState::kVictory: if (command == ECommand::kFire1) { std::cout << "fire1 released" << std::endl; gameState = EGameState::kGame; reset(); } return; case EGameState::kTitleScreen: gameState = EGameState::kGame; reset(); return; } }; } } <commit_msg>Progress to the next zone once clearing the circuit<commit_after>#include <functional> #include <array> #include <iostream> #include <random> #include "Common.h" #include "CGame.h" namespace odb { void CGame::reset() { timeEllapsed = 0; } CGame::CGame() { gameState = EGameState::kGame; reset(); } void CGame::tick(long ms) { timeEllapsed += ms; //20 km/h //1h = 60 minutes * 60 seconds * 1000 ms float secondsSinceLastTick = ms / 1000.0f; float distanceSinceLastTick = carSpeed * secondsSinceLastTick; distanceRan += distanceSinceLastTick; distanceToNextElement -= distanceSinceLastTick; if (distanceToNextElement <= 0 ) { distanceToNextElement = kSegmentLengthInMeters; elementIndex++; } if ( elementIndex >= track.size() ) { elementIndex = 0; ++zone; } x += xSpeed * carSpeed * 0.2f; if ( distanceToNextElement < ( kSegmentLengthInMeters / 2) ) { char shape = track[elementIndex]; int shapeDelta = 0; if (shape == ')') { shapeDelta = -1; x+= 0.15f * carSpeed; } if (shape == '(') { shapeDelta = 1; x-= 0.15f * carSpeed; } mHeading -= (shapeDelta / 1000.0f) + ( x / (640.0f * 10000.0f) ); } if ( x < -160 || x > 160 ) { } } CControlCallback CGame::getKeyPressedCallback() { return [&](ECommand command) { if (command == ECommand::kLeft) { std::cout << "left pressed" << std::endl; xSpeed = -1; } if (command == ECommand::kRight) { std::cout << "Right pressed" << std::endl; xSpeed = 1; } if (command == ECommand::kUp) { std::cout << "up pressed" << std::endl; } if (command == ECommand::kDown) { std::cout << "down pressed" << std::endl; } if (command == ECommand::kFire1) { std::cout << "fire1 pressed" << std::endl; } }; } CControlCallback CGame::getKeyReleasedCallback() { return [&](ECommand command) { xSpeed = 0; switch (gameState) { case EGameState::kGame: if (command == ECommand::kLeft) { std::cout << "left released" << std::endl; } if (command == ECommand::kRight) { std::cout << "right released" << std::endl; } if (command == ECommand::kUp) { std::cout << "up released" << std::endl; carSpeed = std::min( carSpeed + 5, 50); } if (command == ECommand::kDown) { std::cout << "down released" << std::endl; carSpeed = std::max( carSpeed - 5, 0); } if (command == ECommand::kFire1) { std::cout << "fire1 released" << std::endl; carSpeed = 0; } return; case EGameState::kGameOver: case EGameState::kVictory: if (command == ECommand::kFire1) { std::cout << "fire1 released" << std::endl; gameState = EGameState::kGame; reset(); } return; case EGameState::kTitleScreen: gameState = EGameState::kGame; reset(); return; } }; } } <|endoftext|>
<commit_before>#include "unittest/gtest.hpp" #include "clustering/registrar.hpp" #include "clustering/registrant.hpp" #include "unittest/clustering_utils.hpp" #include "unittest/dummy_metadata_controller.hpp" #include "unittest/unittest_utils.hpp" namespace unittest { namespace { class monitoring_controller_t { public: class registrant_t { public: registrant_t(monitoring_controller_t *c, const std::string& data) : parent(c) { EXPECT_FALSE(parent->has_registrant); parent->has_registrant = true; parent->registrant_data = data; } ~registrant_t() { EXPECT_TRUE(parent->has_registrant); parent->has_registrant = false; } monitoring_controller_t *parent; }; monitoring_controller_t() : has_registrant(false) { } bool has_registrant; std::string registrant_data; }; /* `let_stuff_happen()` delays for some time to let events occur */ void let_stuff_happen() { nap(1000); } } /* anonymous namespace */ /* `Register` tests registration, updating, and deregistration of a single registrant. */ void run_register_test() { simple_mailbox_cluster_t cluster; monitoring_controller_t controller; registrar_t<std::string, monitoring_controller_t *, monitoring_controller_t::registrant_t> registrar( cluster.get_mailbox_manager(), &controller); simple_directory_manager_t<boost::optional<registrar_business_card_t<std::string> > > metadata_controller( &cluster, boost::optional<registrar_business_card_t<std::string> >(registrar.get_business_card()) ); EXPECT_FALSE(controller.has_registrant); { registrant_t<std::string> registrant( cluster.get_mailbox_manager(), metadata_controller.get_root_view()->get_peer_view(cluster.get_connectivity_service()->get_me()), "hello"); let_stuff_happen(); EXPECT_FALSE(registrant.get_failed_signal()->is_pulsed()); EXPECT_TRUE(controller.has_registrant); EXPECT_EQ("hello", controller.registrant_data); } let_stuff_happen(); EXPECT_FALSE(controller.has_registrant); } TEST(ClusteringRegistration, Register) { run_in_thread_pool(&run_register_test); } /* `RegistrarDeath` tests the case where the registrar dies while the registrant is registered. */ void run_registrar_death_test() { simple_mailbox_cluster_t cluster; monitoring_controller_t controller; /* Set up `registrar` in a `boost::scoped_ptr` so we can destroy it whenever we want to */ boost::scoped_ptr<registrar_t<std::string, monitoring_controller_t *, monitoring_controller_t::registrant_t> > registrar( new registrar_t<std::string, monitoring_controller_t *, monitoring_controller_t::registrant_t>( cluster.get_mailbox_manager(), &controller )); EXPECT_FALSE(controller.has_registrant); simple_directory_manager_t<boost::optional<registrar_business_card_t<std::string> > > metadata_controller( &cluster, boost::optional<registrar_business_card_t<std::string> >(registrar->get_business_card()) ); registrant_t<std::string> registrant( cluster.get_mailbox_manager(), metadata_controller.get_root_view()->get_peer_view(cluster.get_connectivity_service()->get_me()), "hello"); let_stuff_happen(); EXPECT_FALSE(registrant.get_failed_signal()->is_pulsed()); EXPECT_TRUE(controller.has_registrant); EXPECT_EQ("hello", controller.registrant_data); /* Kill the registrar */ { directory_write_service_t::our_value_lock_acq_t lock(&metadata_controller); metadata_controller.get_root_view()->set_our_value( boost::optional<registrar_business_card_t<std::string> >(), &lock); } registrar.reset(); let_stuff_happen(); EXPECT_TRUE(registrant.get_failed_signal()->is_pulsed()); EXPECT_FALSE(controller.has_registrant); } TEST(ClusteringRegistration, RegistrarDeath) { run_in_thread_pool(&run_registrar_death_test); } } /* namespace unittest */ <commit_msg>Wrote a test that should expose issue #576 in theory, but doesn't in practice.<commit_after>#include "unittest/gtest.hpp" #include "clustering/registrar.hpp" #include "clustering/registrant.hpp" #include "unittest/clustering_utils.hpp" #include "unittest/dummy_metadata_controller.hpp" #include "unittest/unittest_utils.hpp" namespace unittest { namespace { class monitoring_controller_t { public: class registrant_t { public: registrant_t(monitoring_controller_t *c, const std::string& data) : parent(c) { EXPECT_FALSE(parent->has_registrant); parent->has_registrant = true; parent->registrant_data = data; } ~registrant_t() { EXPECT_TRUE(parent->has_registrant); parent->has_registrant = false; } monitoring_controller_t *parent; }; monitoring_controller_t() : has_registrant(false) { } bool has_registrant; std::string registrant_data; }; /* `let_stuff_happen()` delays for some time to let events occur */ void let_stuff_happen() { nap(1000); } } /* anonymous namespace */ /* `Register` tests registration, updating, and deregistration of a single registrant. */ void run_register_test() { simple_mailbox_cluster_t cluster; monitoring_controller_t controller; registrar_t<std::string, monitoring_controller_t *, monitoring_controller_t::registrant_t> registrar( cluster.get_mailbox_manager(), &controller); simple_directory_manager_t<boost::optional<registrar_business_card_t<std::string> > > metadata_controller( &cluster, boost::optional<registrar_business_card_t<std::string> >(registrar.get_business_card()) ); EXPECT_FALSE(controller.has_registrant); { registrant_t<std::string> registrant( cluster.get_mailbox_manager(), metadata_controller.get_root_view()->get_peer_view(cluster.get_connectivity_service()->get_me()), "hello"); let_stuff_happen(); EXPECT_FALSE(registrant.get_failed_signal()->is_pulsed()); EXPECT_TRUE(controller.has_registrant); EXPECT_EQ("hello", controller.registrant_data); } let_stuff_happen(); EXPECT_FALSE(controller.has_registrant); } TEST(ClusteringRegistration, Register) { run_in_thread_pool(&run_register_test); } /* `RegistrarDeath` tests the case where the registrar dies while the registrant is registered. */ void run_registrar_death_test() { simple_mailbox_cluster_t cluster; monitoring_controller_t controller; /* Set up `registrar` in a `boost::scoped_ptr` so we can destroy it whenever we want to */ boost::scoped_ptr<registrar_t<std::string, monitoring_controller_t *, monitoring_controller_t::registrant_t> > registrar( new registrar_t<std::string, monitoring_controller_t *, monitoring_controller_t::registrant_t>( cluster.get_mailbox_manager(), &controller )); EXPECT_FALSE(controller.has_registrant); simple_directory_manager_t<boost::optional<registrar_business_card_t<std::string> > > metadata_controller( &cluster, boost::optional<registrar_business_card_t<std::string> >(registrar->get_business_card()) ); registrant_t<std::string> registrant( cluster.get_mailbox_manager(), metadata_controller.get_root_view()->get_peer_view(cluster.get_connectivity_service()->get_me()), "hello"); let_stuff_happen(); EXPECT_FALSE(registrant.get_failed_signal()->is_pulsed()); EXPECT_TRUE(controller.has_registrant); EXPECT_EQ("hello", controller.registrant_data); /* Kill the registrar */ { directory_write_service_t::our_value_lock_acq_t lock(&metadata_controller); metadata_controller.get_root_view()->set_our_value( boost::optional<registrar_business_card_t<std::string> >(), &lock); } registrar.reset(); let_stuff_happen(); EXPECT_TRUE(registrant.get_failed_signal()->is_pulsed()); EXPECT_FALSE(controller.has_registrant); } TEST(ClusteringRegistration, RegistrarDeath) { run_in_thread_pool(&run_registrar_death_test); } /* `QuickDisconnect` is to expose a bug that could appear if the registrant is deleted immediately after being created. */ void run_quick_disconnect_test() { simple_mailbox_cluster_t cluster; monitoring_controller_t controller; registrar_t<std::string, monitoring_controller_t *, monitoring_controller_t::registrant_t> registrar( cluster.get_mailbox_manager(), &controller); simple_directory_manager_t<boost::optional<registrar_business_card_t<std::string> > > metadata_controller( &cluster, boost::optional<registrar_business_card_t<std::string> >(registrar.get_business_card()) ); EXPECT_FALSE(controller.has_registrant); { registrant_t<std::string> registrant( cluster.get_mailbox_manager(), metadata_controller.get_root_view()->get_peer_view(cluster.get_connectivity_service()->get_me()), "hello"); } let_stuff_happen(); EXPECT_FALSE(controller.has_registrant); } TEST(ClusteringRegistration, QuickDisconnect) { run_in_thread_pool(&run_quick_disconnect_test); } } /* namespace unittest */ <|endoftext|>
<commit_before>// // XMLInterpreter.cpp // SwingGame // // Created by Tim Brier on 11/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "XMLInterpreter.hpp" #include "SystemUtilities.hpp" #include "GameOptions.hpp" namespace XMLInterpreter { // ============================================================================= // XMLInterpreter::ReadConfig // Set the game options from a config file // ----------------------------------------------------------------------------- void ReadConfig(std::string filename) { // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng config xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); // Bail out return; } // Begin processing pugi::xml_node theRoot = theDocument.document_element(); // Go through all children of the root and process each in turn for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "windowHeight") == 0) { GameOptions::windowHeight = GetInt(theNode); } else if (strcmp(theNode.name(), "windowWidth") == 0) { GameOptions::windowWidth = GetInt(theNode); } else if (strcmp(theNode.name(), "useVsync") == 0) { GameOptions::doVsync = GetBool(theNode); } else if (strcmp(theNode.name(), "fullscreen") == 0) { GameOptions::fullscreen = GetBool(theNode); } else if (strcmp(theNode.name(), "preserveAspect") == 0) { GameOptions::preserveAspect = GetBool(theNode); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } } // ============================================================================= // XMLInterpreter::ReadBestTimes // ----------------------------------------------------------------------------- std::map<std::string, CTime> ReadBestTimes(std::string filename) { std::map<std::string, CTime> theTimes; // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng times xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); } // Begin processing pugi::xml_node theRoot = theDocument.document_element(); // Go through all children of the root and process each in turn for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { theTimes[theNode.name()] = GetTime(theNode); } return theTimes; } // ============================================================================= // XMLInterpreter::WriteBestTimes // ----------------------------------------------------------------------------- void WriteBestTimes(std::string filename, std::map<std::string, CTime> theTimes) { pugi::xml_document doc; doc.load("<times></times>"); pugi::xml_node theRoot = doc.document_element(); for (std::map<std::string, CTime>::iterator it = theTimes.begin(); it != theTimes.end(); ++it) { std::string key = it->first; CTime value = it->second; pugi::xml_node theChild = theRoot.append_child(key.c_str()); char valueString[32]; sprintf(valueString, "%f", value.asSeconds()); theChild.text().set(valueString); } std::string fullName = SystemUtilities::GetResourcePath() + filename; doc.save_file(fullName.c_str()); } // ============================================================================= // XMLInterpreter::ProcessLevel // Populate the given level using the given xml file // ----------------------------------------------------------------------------- void ProcessLevel(std::string filename, CLevel *theLevel) { DEBUG_LOG("Loading level from %s", filename.c_str()); // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng level xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); } // Begin processing the level(root) node DEBUG_LOG("Processing level node"); // Get the name and ID from the root element pugi::xml_node theRoot = theDocument.document_element(); CHECK_ATTRIBUTE(theRoot, "name"); theLevel->SetName(theRoot.attribute("name").value()); // Report missing required nodes CHECK_CHILD(theRoot, "start"); CHECK_CHILD(theRoot, "goal"); CHECK_CHILD(theRoot, "background"); // Don't check for obstacles, strictly speaking they are not required // Don't check tutorial text, it's not needed // Go through all children of the root and process each in turn for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "start") == 0) { theLevel->SetStartPosition(GetStartPosition(theNode)); } else if (strcmp(theNode.name(), "goal") == 0) { theLevel->SetGoal(GetGoal(theNode)); } else if (strcmp(theNode.name(), "background") == 0) { DEBUG_LOG("Processing background node"); theLevel->SetBackground(CSprite(theNode.text().as_string())); } else if (strcmp(theNode.name(), "obstacle") == 0) { theLevel->AddObstacle(GetObstacle(theNode)); } else if (strcmp(theNode.name(), "key") == 0) { theLevel->AddKeyAt(GetVector2f(theNode)); } else if (strcmp(theNode.name(), "tutorialText") == 0) { theLevel->SetTutorialText(GetLevelText(theNode)); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } } // ============================================================================= // XMLInterpreter::GetLevelName // ----------------------------------------------------------------------------- std::string GetLevelName(std::string filename) { // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng level xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); } // Get the name and ID from the root element pugi::xml_node theRoot = theDocument.document_element(); CHECK_ATTRIBUTE(theRoot, "name"); std::string theName = theRoot.attribute("name").as_string(); return theName; } // ============================================================================= // XMLInterpreter::GetInt // ----------------------------------------------------------------------------- int GetInt(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_int(); return theResult; } // ============================================================================= // XMLInterpreter::GetBool // ----------------------------------------------------------------------------- bool GetBool(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_bool(); return theResult; } // ============================================================================= // XMLInterpreter::GetVector2f // ----------------------------------------------------------------------------- CVector2f GetVector2f(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "x"); CHECK_CHILD(theRoot, "y"); CVector2f theResult; theResult.x = theRoot.child("x").text().as_float(); theResult.y = theRoot.child("y").text().as_float(); return theResult; } // ============================================================================= // XMLInterpreter::GetTime // ----------------------------------------------------------------------------- CTime GetTime(pugi::xml_node theRoot) { float seconds = theRoot.text().as_float(); CTime theResult = CTime::Seconds(seconds); return theResult; } // ============================================================================= // XMLInterpreter::GetLevelItem // ----------------------------------------------------------------------------- CPhysicsBody GetLevelItem(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "position"); CHECK_CHILD(theRoot, "texture"); CPhysicsBody theResult; std::list<CVector2f> thePoints; CVector2f thePosition = CVector2f(0.0f, 0.0f); // Process each child for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "position") == 0) { thePosition = GetVector2f(theNode); } else if (strcmp(theNode.name(), "texture") == 0) { bool flipX = false; bool flipY = false; if (theNode.attribute("flipX") != NULL) { flipX = theNode.attribute("flipX").as_bool(); } if (theNode.attribute("flipY") != NULL) { flipY = theNode.attribute("flipY").as_bool(); } std::string filename = theNode.text().as_string(); // TODO: Texture item shapes DEBUG_LOG("Texturing level items not implemented"); } else if (strcmp(theNode.name(), "point") == 0) { CVector2f thePoint = GetVector2f(theNode); thePoints.push_back(thePoint); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } // Create and initialise the shape theResult.SetShape(CConvexShape(thePoints)); theResult.GetShape()->setPosition(thePosition); return theResult; } // ============================================================================= // XMLInterpreter::GetStartPosition // ----------------------------------------------------------------------------- SStartPosition GetStartPosition(pugi::xml_node theRoot) { DEBUG_LOG("Processing start node"); CHECK_CHILD(theRoot, "position"); CHECK_CHILD(theRoot, "swingTarget"); CHECK_CHILD(theRoot, "velocity") CHECK_CHILD(theRoot, "swingType") SStartPosition theResult; for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "position") == 0) { theResult.mPosition = XMLInterpreter::GetVector2f(theNode); } else if (strcmp(theNode.name(), "swingTarget") == 0) { theResult.mSwingTarget = XMLInterpreter::GetVector2f(theNode); } else if (strcmp(theNode.name(), "velocity") == 0) { theResult.mVelocity = XMLInterpreter::GetVector2f(theNode); } else if (strcmp(theNode.name(), "swingType") == 0) { theResult.mSwingType = XMLInterpreter::GetSwingType(theNode); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } return theResult; } // ============================================================================= // XMLInterpreter::GetGoal // ----------------------------------------------------------------------------- CPhysicsBody GetGoal(pugi::xml_node theRoot) { DEBUG_LOG("Processing goal node"); CPhysicsBody theResult = XMLInterpreter::GetLevelItem(theRoot); // Default goal to green theResult.GetShape()->setFillColor(CColour::Green); return theResult; } // ============================================================================= // XMLInterpreter::GetObstacle // ----------------------------------------------------------------------------- CPhysicsBody GetObstacle(pugi::xml_node theRoot) { DEBUG_LOG("Processing goal node"); CPhysicsBody theResult = XMLInterpreter::GetLevelItem(theRoot); // Default obstacle to black theResult.GetShape()->setFillColor(CColour::Black); return theResult; } // ============================================================================= // XMLInterpreter::GetSwingType // ----------------------------------------------------------------------------- ESwingTypes GetSwingType(pugi::xml_node theRoot) { ESwingTypes theResult = kSwingTypeRigid; if (strcmp(theRoot.text().as_string(), "rigid") == 0) { theResult = kSwingTypeRigid; } else if (strcmp(theRoot.text().as_string(), "flexible") == 0) { theResult = kSwingTypeFlexible; } else if (strcmp(theRoot.text().as_string(), "pulling") == 0) { theResult = kSwingTypePulling; } else if (strcmp(theRoot.text().as_string(), "spring") == 0) { theResult = kSwingTypeSpring; } return theResult; } // ============================================================================= // XMLInterpreter::GetLevelText // ----------------------------------------------------------------------------- CText GetLevelText(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "text"); std::string theString = theRoot.child("text").text().as_string(); CVector2f thePos = GetVector2f(theRoot); CText theResult = CText(theString, thePos); return theResult; } } // namespace XMLInterpreter<commit_msg>Recognise circle shapes from xml<commit_after>// // XMLInterpreter.cpp // SwingGame // // Created by Tim Brier on 11/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "XMLInterpreter.hpp" #include "SystemUtilities.hpp" #include "GameOptions.hpp" namespace XMLInterpreter { // ============================================================================= // XMLInterpreter::ReadConfig // Set the game options from a config file // ----------------------------------------------------------------------------- void ReadConfig(std::string filename) { // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng config xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); // Bail out return; } // Begin processing pugi::xml_node theRoot = theDocument.document_element(); // Go through all children of the root and process each in turn for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "windowHeight") == 0) { GameOptions::windowHeight = GetInt(theNode); } else if (strcmp(theNode.name(), "windowWidth") == 0) { GameOptions::windowWidth = GetInt(theNode); } else if (strcmp(theNode.name(), "useVsync") == 0) { GameOptions::doVsync = GetBool(theNode); } else if (strcmp(theNode.name(), "fullscreen") == 0) { GameOptions::fullscreen = GetBool(theNode); } else if (strcmp(theNode.name(), "preserveAspect") == 0) { GameOptions::preserveAspect = GetBool(theNode); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } } // ============================================================================= // XMLInterpreter::ReadBestTimes // ----------------------------------------------------------------------------- std::map<std::string, CTime> ReadBestTimes(std::string filename) { std::map<std::string, CTime> theTimes; // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng times xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); } // Begin processing pugi::xml_node theRoot = theDocument.document_element(); // Go through all children of the root and process each in turn for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { theTimes[theNode.name()] = GetTime(theNode); } return theTimes; } // ============================================================================= // XMLInterpreter::WriteBestTimes // ----------------------------------------------------------------------------- void WriteBestTimes(std::string filename, std::map<std::string, CTime> theTimes) { pugi::xml_document doc; doc.load("<times></times>"); pugi::xml_node theRoot = doc.document_element(); for (std::map<std::string, CTime>::iterator it = theTimes.begin(); it != theTimes.end(); ++it) { std::string key = it->first; CTime value = it->second; pugi::xml_node theChild = theRoot.append_child(key.c_str()); char valueString[32]; sprintf(valueString, "%f", value.asSeconds()); theChild.text().set(valueString); } std::string fullName = SystemUtilities::GetResourcePath() + filename; doc.save_file(fullName.c_str()); } // ============================================================================= // XMLInterpreter::ProcessLevel // Populate the given level using the given xml file // ----------------------------------------------------------------------------- void ProcessLevel(std::string filename, CLevel *theLevel) { DEBUG_LOG("Loading level from %s", filename.c_str()); // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng level xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); } // Begin processing the level(root) node DEBUG_LOG("Processing level node"); // Get the name and ID from the root element pugi::xml_node theRoot = theDocument.document_element(); CHECK_ATTRIBUTE(theRoot, "name"); theLevel->SetName(theRoot.attribute("name").value()); // Report missing required nodes CHECK_CHILD(theRoot, "start"); CHECK_CHILD(theRoot, "goal"); CHECK_CHILD(theRoot, "background"); // Don't check for obstacles, strictly speaking they are not required // Don't check tutorial text, it's not needed // Go through all children of the root and process each in turn for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "start") == 0) { theLevel->SetStartPosition(GetStartPosition(theNode)); } else if (strcmp(theNode.name(), "goal") == 0) { theLevel->SetGoal(GetGoal(theNode)); } else if (strcmp(theNode.name(), "background") == 0) { DEBUG_LOG("Processing background node"); theLevel->SetBackground(CSprite(theNode.text().as_string())); } else if (strcmp(theNode.name(), "obstacle") == 0) { theLevel->AddObstacle(GetObstacle(theNode)); } else if (strcmp(theNode.name(), "key") == 0) { theLevel->AddKeyAt(GetVector2f(theNode)); } else if (strcmp(theNode.name(), "tutorialText") == 0) { theLevel->SetTutorialText(GetLevelText(theNode)); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } } // ============================================================================= // XMLInterpreter::GetLevelName // ----------------------------------------------------------------------------- std::string GetLevelName(std::string filename) { // Read the file pugi::xml_document theDocument; std::string fullName = SystemUtilities::GetResourcePath() + filename; pugi::xml_parse_result theResult = theDocument.load_file(fullName.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng level xml file: %s", filename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); } // Get the name and ID from the root element pugi::xml_node theRoot = theDocument.document_element(); CHECK_ATTRIBUTE(theRoot, "name"); std::string theName = theRoot.attribute("name").as_string(); return theName; } // ============================================================================= // XMLInterpreter::GetInt // ----------------------------------------------------------------------------- int GetInt(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_int(); return theResult; } // ============================================================================= // XMLInterpreter::GetBool // ----------------------------------------------------------------------------- bool GetBool(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_bool(); return theResult; } // ============================================================================= // XMLInterpreter::GetVector2f // ----------------------------------------------------------------------------- CVector2f GetVector2f(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "x"); CHECK_CHILD(theRoot, "y"); CVector2f theResult; theResult.x = theRoot.child("x").text().as_float(); theResult.y = theRoot.child("y").text().as_float(); return theResult; } // ============================================================================= // XMLInterpreter::GetTime // ----------------------------------------------------------------------------- CTime GetTime(pugi::xml_node theRoot) { float seconds = theRoot.text().as_float(); CTime theResult = CTime::Seconds(seconds); return theResult; } // ============================================================================= // XMLInterpreter::GetLevelItem // ----------------------------------------------------------------------------- CPhysicsBody GetLevelItem(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "position"); CPhysicsBody theResult; std::list<CVector2f> thePoints; CVector2f thePosition = CVector2f(0.0f, 0.0f); float theRadius = 0.0f; // Process each child for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "position") == 0) { thePosition = GetVector2f(theNode); } else if (strcmp(theNode.name(), "texture") == 0) { bool flipX = false; bool flipY = false; if (theNode.attribute("flipX") != NULL) { flipX = theNode.attribute("flipX").as_bool(); } if (theNode.attribute("flipY") != NULL) { flipY = theNode.attribute("flipY").as_bool(); } std::string filename = theNode.text().as_string(); // TODO: Texture item shapes DEBUG_LOG("Texturing level items not implemented"); } else if (strcmp(theNode.name(), "point") == 0) { CVector2f thePoint = GetVector2f(theNode); thePoints.push_back(thePoint); } else if (strcmp(theNode.name(), "radius") == 0) { theRadius = theNode.text().as_float(); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } // Create and initialise the shape CConvexShape theShape; // Are we a circle or a normal shape if (thePoints.size() > 0) { if (theRadius > 0.0f) { DEBUG_LOG("Shape has both circle and normal shape properties," "treating as a normal shape"); } theShape = CConvexShape(thePoints); } else if (thePoints.size() == 0 && theRadius > 0.0f) { theShape = CCircleShape(theRadius); } theResult.SetShape(theShape); theResult.GetShape()->setPosition(thePosition); return theResult; } // ============================================================================= // XMLInterpreter::GetStartPosition // ----------------------------------------------------------------------------- SStartPosition GetStartPosition(pugi::xml_node theRoot) { DEBUG_LOG("Processing start node"); CHECK_CHILD(theRoot, "position"); CHECK_CHILD(theRoot, "swingTarget"); CHECK_CHILD(theRoot, "velocity") CHECK_CHILD(theRoot, "swingType") SStartPosition theResult; for (pugi::xml_node theNode = theRoot.first_child(); theNode; theNode = theNode.next_sibling()) { if (strcmp(theNode.name(), "position") == 0) { theResult.mPosition = XMLInterpreter::GetVector2f(theNode); } else if (strcmp(theNode.name(), "swingTarget") == 0) { theResult.mSwingTarget = XMLInterpreter::GetVector2f(theNode); } else if (strcmp(theNode.name(), "velocity") == 0) { theResult.mVelocity = XMLInterpreter::GetVector2f(theNode); } else if (strcmp(theNode.name(), "swingType") == 0) { theResult.mSwingType = XMLInterpreter::GetSwingType(theNode); } else { DEBUG_LOG("Unknown xml node: %s", theNode.name()); } } return theResult; } // ============================================================================= // XMLInterpreter::GetGoal // ----------------------------------------------------------------------------- CPhysicsBody GetGoal(pugi::xml_node theRoot) { DEBUG_LOG("Processing goal node"); CPhysicsBody theResult = XMLInterpreter::GetLevelItem(theRoot); // Default goal to green theResult.GetShape()->setFillColor(CColour::Green); return theResult; } // ============================================================================= // XMLInterpreter::GetObstacle // ----------------------------------------------------------------------------- CPhysicsBody GetObstacle(pugi::xml_node theRoot) { DEBUG_LOG("Processing goal node"); CPhysicsBody theResult = XMLInterpreter::GetLevelItem(theRoot); // Default obstacle to black theResult.GetShape()->setFillColor(CColour::Black); return theResult; } // ============================================================================= // XMLInterpreter::GetSwingType // ----------------------------------------------------------------------------- ESwingTypes GetSwingType(pugi::xml_node theRoot) { ESwingTypes theResult = kSwingTypeRigid; if (strcmp(theRoot.text().as_string(), "rigid") == 0) { theResult = kSwingTypeRigid; } else if (strcmp(theRoot.text().as_string(), "flexible") == 0) { theResult = kSwingTypeFlexible; } else if (strcmp(theRoot.text().as_string(), "pulling") == 0) { theResult = kSwingTypePulling; } else if (strcmp(theRoot.text().as_string(), "spring") == 0) { theResult = kSwingTypeSpring; } return theResult; } // ============================================================================= // XMLInterpreter::GetLevelText // ----------------------------------------------------------------------------- CText GetLevelText(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "text"); std::string theString = theRoot.child("text").text().as_string(); CVector2f thePos = GetVector2f(theRoot); CText theResult = CText(theString, thePos); return theResult; } } // namespace XMLInterpreter<|endoftext|>
<commit_before>#ifndef _MSC_VER #include <signal.h> #endif #include <iostream> #include <sstream> #include "HTTP/Server.h" #include "HTTP/RespSources/FSRespSource.h" #include "HTTP/RespSources/ZipRespSource.h" #include "HTTP/RespSources/WSEchoRespSource.h" #include "HTTP/RespSources/CombinerRespSource.h" #include "HTTP/ServerLogs/OStreamServerLog.h" ////////////////////////////////////// // OS-specific helpers. #ifdef _MSC_VER #include <windows.h> #endif volatile bool IsRunning=true; #ifdef _MSC_VER HANDLE MainThreadH=INVALID_HANDLE_VALUE; BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: IsRunning=false; WaitForSingleObject(MainThreadH,5500); break; } return TRUE; } #else void SigHandler(int sig) { if ((sig==SIGQUIT) || (sig==SIGINT)) IsRunning=false; } #endif ////////////////////////////////////// // Form parameter tester. class FormTestRS : public HTTP::IRespSource { public: class SStreamResp : public HTTP::IResponse { public: virtual unsigned int GetResponseCode() { return HTTP::RC_OK; } virtual const char *GetContentType() const { return "text/plain"; } virtual const char *GetContentTypeCharset() const { return "utf-8"; } virtual unsigned long long GetLength() { return (unsigned long long)MyStream.tellp(); } virtual bool Read(unsigned char *TargetBuff, unsigned int MaxLength, unsigned int &OutLength, boost::asio::yield_context &Ctx) { MyStream.read((char *)TargetBuff,MaxLength); return (OutLength=(unsigned int)(MyStream.gcount()))!=0; } inline operator std::stringstream &() { return MyStream; } private: std::stringstream MyStream; }; virtual HTTP::IResponse *Create(HTTP::METHOD Method, const std::string &Resource, const HTTP::QueryParams &Query, const std::vector<HTTP::Header> &HeaderA, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd, AsyncHelperHolder AsyncHelpers, void *ParentConn) { SStreamResp *MyResp=new SStreamResp(); std::stringstream &RespStream=*MyResp; RespStream << "Got method "; switch (Method) { case HTTP::METHOD_GET: RespStream << "GET.\n"; break; case HTTP::METHOD_POST: RespStream << "POST.\n"; break; case HTTP::METHOD_HEAD: RespStream << "HEAD.\n"; break; default: RespStream << "(unknown).\n"; break; } RespStream << "\nParams:\n"; for (const HTTP::QueryParams::ParamMapType::value_type &Param : Query.Params()) RespStream << Param.first << ": \"" << Param.second << "\"\n"; RespStream << "\nFiles:\n"; for (const HTTP::QueryParams::FileMapType::value_type &File : Query.Files()) RespStream << File.first << ": OrigFileName: \"" << File.second.OrigFileName << "\", " "Path: \"" << File.second.Path.string() << "\", MimeType: \"" << File.second.MimeType << "\", " "[Size]: " << boost::filesystem::file_size(File.second.Path) << "\n"; return MyResp; } }; ////////////////////////////////////// // Main entry point. int main(int argc, char* argv[]) { #ifdef _MSC_VER MainThreadH=GetCurrentThread(); SetConsoleCtrlHandler(&ConsoleCtrlHandler,TRUE); #else signal(SIGQUIT,&SigHandler); signal(SIGINT,&SigHandler); #endif std::cout << "Starting." << std::endl; HTTP::Server MiniWS(8880); MiniWS.SetName("MiniWebServer/v0.2.0"); { HTTP::RespSource::Combiner *Combiner=new HTTP::RespSource::Combiner(); Combiner->AddRespSource("/gallery",new HTTP::RespSource::Zip("../Doc/gallery.zip")); Combiner->AddRespSource("/formtest",new FormTestRS()); Combiner->AddRespSource("/echo",new HTTP::WebSocket::EchoRespSource()); Combiner->AddRespSource("",new HTTP::RespSource::FS("../Doc")); Combiner->AddRedirect("/","/test.html"); MiniWS.SetResponseSource(Combiner); MiniWS.SetServerLog(new HTTP::ServerLog::OStream(std::cout)); } MiniWS.Run(); std::cout << "Started." << std::endl; while (IsRunning) std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::cout << "Stopping." << std::endl; if (MiniWS.Stop(std::chrono::seconds(4))) std::cout << "Stopped gracefully." << std::endl; else std::cout << "Stopped forcefully." << std::endl; return 0; } <commit_msg>MiniWebSrv.cpp: StaticRespSource demo<commit_after>#ifndef _MSC_VER #include <signal.h> #endif #include <iostream> #include <sstream> #include "HTTP/Server.h" #include "HTTP/RespSources/FSRespSource.h" #include "HTTP/RespSources/ZipRespSource.h" #include "HTTP/RespSources/WSEchoRespSource.h" #include "HTTP/RespSources/CombinerRespSource.h" #include "HTTP/RespSources/StaticRespSource.h" #include "HTTP/ServerLogs/OStreamServerLog.h" ////////////////////////////////////// // OS-specific helpers. #ifdef _MSC_VER #include <windows.h> #endif volatile bool IsRunning=true; #ifdef _MSC_VER HANDLE MainThreadH=INVALID_HANDLE_VALUE; BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: IsRunning=false; WaitForSingleObject(MainThreadH,5500); break; } return TRUE; } #else void SigHandler(int sig) { if ((sig==SIGQUIT) || (sig==SIGINT)) IsRunning=false; } #endif ////////////////////////////////////// // Form parameter tester. class FormTestRS : public HTTP::IRespSource { public: class SStreamResp : public HTTP::IResponse { public: virtual unsigned int GetResponseCode() { return HTTP::RC_OK; } virtual const char *GetContentType() const { return "text/plain"; } virtual const char *GetContentTypeCharset() const { return "utf-8"; } virtual unsigned long long GetLength() { return (unsigned long long)MyStream.tellp(); } virtual bool Read(unsigned char *TargetBuff, unsigned int MaxLength, unsigned int &OutLength, boost::asio::yield_context &Ctx) { MyStream.read((char *)TargetBuff,MaxLength); return (OutLength=(unsigned int)(MyStream.gcount()))!=0; } inline operator std::stringstream &() { return MyStream; } private: std::stringstream MyStream; }; virtual HTTP::IResponse *Create(HTTP::METHOD Method, const std::string &Resource, const HTTP::QueryParams &Query, const std::vector<HTTP::Header> &HeaderA, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd, AsyncHelperHolder AsyncHelpers, void *ParentConn) { SStreamResp *MyResp=new SStreamResp(); std::stringstream &RespStream=*MyResp; RespStream << "Got method "; switch (Method) { case HTTP::METHOD_GET: RespStream << "GET.\n"; break; case HTTP::METHOD_POST: RespStream << "POST.\n"; break; case HTTP::METHOD_HEAD: RespStream << "HEAD.\n"; break; default: RespStream << "(unknown).\n"; break; } RespStream << "\nParams:\n"; for (const HTTP::QueryParams::ParamMapType::value_type &Param : Query.Params()) RespStream << Param.first << ": \"" << Param.second << "\"\n"; RespStream << "\nFiles:\n"; for (const HTTP::QueryParams::FileMapType::value_type &File : Query.Files()) RespStream << File.first << ": OrigFileName: \"" << File.second.OrigFileName << "\", " "Path: \"" << File.second.Path.string() << "\", MimeType: \"" << File.second.MimeType << "\", " "[Size]: " << boost::filesystem::file_size(File.second.Path) << "\n"; return MyResp; } }; ////////////////////////////////////// // Main entry point. int main(int argc, char* argv[]) { #ifdef _MSC_VER MainThreadH=GetCurrentThread(); SetConsoleCtrlHandler(&ConsoleCtrlHandler,TRUE); #else signal(SIGQUIT,&SigHandler); signal(SIGINT,&SigHandler); #endif std::string StaticRespStr("<h1>Static response, resource embedded in executable</h1>"); std::cout << "Starting." << std::endl; HTTP::Server MiniWS(8880); MiniWS.SetName("MiniWebServer/v0.2.0"); { HTTP::RespSource::Combiner *Combiner=new HTTP::RespSource::Combiner(); Combiner->AddRespSource("/gallery",new HTTP::RespSource::Zip("../Doc/gallery.zip")); Combiner->AddRespSource("/formtest",new FormTestRS()); Combiner->AddRespSource("/echo",new HTTP::WebSocket::EchoRespSource()); Combiner->AddRespSource("/static", new HTTP::RespSource::StaticRespSource(&StaticRespStr, "text/html")); Combiner->AddRespSource("",new HTTP::RespSource::FS("../Doc")); Combiner->AddRedirect("/","/test.html"); MiniWS.SetResponseSource(Combiner); MiniWS.SetServerLog(new HTTP::ServerLog::OStream(std::cout)); } MiniWS.Run(); std::cout << "Started." << std::endl; while (IsRunning) std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::cout << "Stopping." << std::endl; if (MiniWS.Stop(std::chrono::seconds(4))) std::cout << "Stopped gracefully." << std::endl; else std::cout << "Stopped forcefully." << std::endl; return 0; } <|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #define OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #include "../../core/Setup.h" #if OUZEL_COMPILE_OPENGL #include <algorithm> #include <stdexcept> #include "OGL.h" #if OUZEL_OPENGLES # include "GLES/gl.h" # include "GLES2/gl2.h" # include "GLES2/gl2ext.h" # include "GLES3/gl3.h" #else # include "GL/glcorearb.h" # include "GL/glext.h" #endif #if OUZEL_OPENGL_INTERFACE_EGL # include "EGL/egl.h" #elif OUZEL_OPENGL_INTERFACE_WGL # include "GL/wglext.h" # include "../../platform/winapi/Library.hpp" #endif #include "../../core/Engine.hpp" #include "../../utils/Utils.hpp" namespace ouzel::graphics::opengl { class ProcedureGetter final { public: ProcedureGetter(ApiVersion version): apiVersion{version} { const auto glGetErrorProc = getProcAddress<PFNGLGETERRORPROC>("glGetError", ApiVersion{1, 0}); if (apiVersion >= ApiVersion{3, 0}) { const auto glGetIntegervProc = getProcAddress<PFNGLGETINTEGERVPROC>("glGetIntegerv", ApiVersion{1, 0}); const auto glGetStringiProc = getProcAddress<PFNGLGETSTRINGIPROC>("glGetStringi", ApiVersion{3, 0}); GLint extensionCount; glGetIntegervProc(GL_NUM_EXTENSIONS, &extensionCount); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension count, error: " + std::to_string(error); else for (GLuint i = 0; i < static_cast<GLuint>(extensionCount); ++i) { const auto extensionPtr = glGetStringiProc(GL_EXTENSIONS, i); if (const auto getStringError = glGetErrorProc(); getStringError != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension, error: " + std::to_string(getStringError); else if (!extensionPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extension"; else extensions.emplace_back(reinterpret_cast<const char*>(extensionPtr)); } } else { const auto glGetStringProc = getProcAddress<PFNGLGETSTRINGPROC>("glGetString", ApiVersion{1, 0}); const auto extensionsPtr = glGetStringProc(GL_EXTENSIONS); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions, error: " + std::to_string(error); else if (!extensionsPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions"; else extensions = explodeString(reinterpret_cast<const char*>(extensionsPtr), ' '); } logger.log(Log::Level::all) << "Supported OpenGL extensions: " << extensions; } template <typename T> T get(const char* name, ApiVersion procApiVersion) const noexcept { return (apiVersion >= procApiVersion) ? getProcAddress<T>(name, procApiVersion) : nullptr; } template <typename T> T get(const char* name, const char* extension) const noexcept { return hasExtension(extension) ? getProcAddress<T>(name) : nullptr; } template <typename T> T get(const char* name, ApiVersion procApiVersion, const std::map<const char*, const char*>& procExtensions) const noexcept { if (apiVersion >= procApiVersion) return getProcAddress<T>(name, procApiVersion); else for (const auto [procName, extension] : procExtensions) if (auto result = get<T>(procName, extension)) return result; return nullptr; } bool hasExtension(const char* ext) const noexcept { return std::find(extensions.begin(), extensions.end(), ext) != extensions.end(); } private: template <typename T> T getProcAddress(const char* name, ApiVersion procApiVersion) const noexcept { #if OUZEL_OPENGL_INTERFACE_EGL # if OUZEL_OPENGLES return procApiVersion >= ApiVersion{3, 0} ? reinterpret_cast<T>(eglGetProcAddress(name)) : reinterpret_cast<T>(dlsym(RTLD_DEFAULT, name)); # else (void)procApiVersion; return reinterpret_cast<T>(eglGetProcAddress(name)); # endif #elif OUZEL_OPENGL_INTERFACE_WGL return procApiVersion > ApiVersion{1, 1} ? reinterpret_cast<T>(wglGetProcAddress(name)) : reinterpret_cast<T>(library.getProcAddress(name)); #else (void)procApiVersion; return reinterpret_cast<T>(dlsym(RTLD_DEFAULT, name)); #endif } template <typename T> T getProcAddress(const char* name) const noexcept { #if OUZEL_OPENGL_INTERFACE_EGL return reinterpret_cast<T>(eglGetProcAddress(name)); #elif OUZEL_OPENGL_INTERFACE_WGL return reinterpret_cast<T>(wglGetProcAddress(name)); #else return reinterpret_cast<T>(dlsym(RTLD_DEFAULT, name)); #endif } ApiVersion apiVersion; std::vector<std::string> extensions; #if OUZEL_OPENGL_INTERFACE_WGL platform::winapi::Library library{"opengl32.dll"}; #endif }; } #endif #endif // OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP <commit_msg>Throw an exception if dlsym failed<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #define OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #include "../../core/Setup.h" #if OUZEL_COMPILE_OPENGL #include <algorithm> #include <stdexcept> #include "OGL.h" #if OUZEL_OPENGLES # include "GLES/gl.h" # include "GLES2/gl2.h" # include "GLES2/gl2ext.h" # include "GLES3/gl3.h" #else # include "GL/glcorearb.h" # include "GL/glext.h" #endif #if OUZEL_OPENGL_INTERFACE_EGL # include "EGL/egl.h" #elif OUZEL_OPENGL_INTERFACE_WGL # include "GL/wglext.h" # include "../../platform/winapi/Library.hpp" #endif #include "../../core/Engine.hpp" #include "../../utils/Utils.hpp" namespace ouzel::graphics::opengl { class ProcedureGetter final { public: ProcedureGetter(ApiVersion version): apiVersion{version} { const auto glGetErrorProc = getProcAddress<PFNGLGETERRORPROC>("glGetError", ApiVersion{1, 0}); if (apiVersion >= ApiVersion{3, 0}) { const auto glGetIntegervProc = getProcAddress<PFNGLGETINTEGERVPROC>("glGetIntegerv", ApiVersion{1, 0}); const auto glGetStringiProc = getProcAddress<PFNGLGETSTRINGIPROC>("glGetStringi", ApiVersion{3, 0}); GLint extensionCount; glGetIntegervProc(GL_NUM_EXTENSIONS, &extensionCount); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension count, error: " + std::to_string(error); else for (GLuint i = 0; i < static_cast<GLuint>(extensionCount); ++i) { const auto extensionPtr = glGetStringiProc(GL_EXTENSIONS, i); if (const auto getStringError = glGetErrorProc(); getStringError != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension, error: " + std::to_string(getStringError); else if (!extensionPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extension"; else extensions.emplace_back(reinterpret_cast<const char*>(extensionPtr)); } } else { const auto glGetStringProc = getProcAddress<PFNGLGETSTRINGPROC>("glGetString", ApiVersion{1, 0}); const auto extensionsPtr = glGetStringProc(GL_EXTENSIONS); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions, error: " + std::to_string(error); else if (!extensionsPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions"; else extensions = explodeString(reinterpret_cast<const char*>(extensionsPtr), ' '); } logger.log(Log::Level::all) << "Supported OpenGL extensions: " << extensions; } template <typename T> T get(const char* name, ApiVersion procApiVersion) const { return (apiVersion >= procApiVersion) ? getProcAddress<T>(name, procApiVersion) : nullptr; } template <typename T> T get(const char* name, const char* extension) const { return hasExtension(extension) ? getProcAddress<T>(name) : nullptr; } template <typename T> T get(const char* name, ApiVersion procApiVersion, const std::map<const char*, const char*>& procExtensions) const { if (apiVersion >= procApiVersion) return getProcAddress<T>(name, procApiVersion); else for (const auto [procName, extension] : procExtensions) if (auto result = get<T>(procName, extension)) return result; return nullptr; } bool hasExtension(const char* ext) const noexcept { return std::find(extensions.begin(), extensions.end(), ext) != extensions.end(); } private: template <typename T> T getProcAddress(const char* name, ApiVersion procApiVersion) const { #if OUZEL_OPENGL_INTERFACE_EGL # if OUZEL_OPENGLES if (procApiVersion >= ApiVersion{3, 0}) return reinterpret_cast<T>(eglGetProcAddress(name)); else if (auto p = dlsym(RTLD_DEFAULT, name); p) return reinterpret_cast<T>(p); else throw std::runtime_error(dlerror()); # else (void)procApiVersion; return reinterpret_cast<T>(eglGetProcAddress(name)); # endif #elif OUZEL_OPENGL_INTERFACE_WGL return procApiVersion > ApiVersion{1, 1} ? reinterpret_cast<T>(wglGetProcAddress(name)) : reinterpret_cast<T>(library.getProcAddress(name)); #else (void)procApiVersion; if (auto p = dlsym(RTLD_DEFAULT, name); p) return reinterpret_cast<T>(p); else throw std::runtime_error(dlerror()); #endif } template <typename T> T getProcAddress(const char* name) const { #if OUZEL_OPENGL_INTERFACE_EGL return reinterpret_cast<T>(eglGetProcAddress(name)); #elif OUZEL_OPENGL_INTERFACE_WGL return reinterpret_cast<T>(wglGetProcAddress(name)); #else if (auto p = dlsym(RTLD_DEFAULT, name); p) return reinterpret_cast<T>(p); else throw std::runtime_error(dlerror()); #endif } ApiVersion apiVersion; std::vector<std::string> extensions; #if OUZEL_OPENGL_INTERFACE_WGL platform::winapi::Library library{"opengl32.dll"}; #endif }; } #endif #endif // OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * TeapotNet 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 Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/splicer.h" #include "tpn/request.h" #include "tpn/pipe.h" #include "tpn/config.h" namespace tpn { Map<ByteString, Splicer::CacheEntry*> Splicer::Cache; Mutex Splicer::CacheMutex; Splicer::Splicer(const ByteString &target, int64_t begin, int64_t end) : mFirstBlock(0), mCurrentBlock(0), mBegin(begin), mEnd(end), mPosition(0) { { CacheMutex.lock(); if(!Cache.get(target, mCacheEntry)) { LogDebug("Splicer", "No cached file, creating a new one"); try { mCacheEntry = new CacheEntry(target); } catch(...) { CacheMutex.unlock(); throw; } Cache.insert(target, mCacheEntry); } Map<ByteString, CacheEntry*>::iterator it = Cache.begin(); while(it != Cache.end()) { if(!it->second || Time::Now() - it->second->lastAccessTime() > 3600) Cache.erase(it++); else it++; } CacheMutex.unlock(); } mCacheEntry->getSources(mSources); if(mSources.empty()) throw Exception("No sources found for " + target.toString()); // OK, the cache entry is initialized // Initialize variables mBegin = bounds(mBegin, int64_t(0), mCacheEntry->size()); if(mEnd < 0) mEnd = mCacheEntry->size(); else mEnd = bounds(mEnd, mBegin, mCacheEntry->size()); mPosition = mBegin; mCurrentBlock = mCacheEntry->block(mBegin); mFirstBlock = mCurrentBlock; while(mCacheEntry->isBlockFinished(mFirstBlock)) ++mFirstBlock; } Splicer::~Splicer(void) { stop(); } String Splicer::name(void) const { return mCacheEntry->name(); } int64_t Splicer::size(void) const { return mEnd - mBegin; } int64_t Splicer::begin(void) const { return mBegin; } int64_t Splicer::end(void) const { return mEnd; } bool Splicer::finished(void) const { return mCacheEntry->finished(); } bool Splicer::outputFinished(void) const { return (mPosition == mEnd); } void Splicer::start(void) { stop(); if(finished()) return; LogDebug("Splicer", "Starting splicer for " + mCacheEntry->name() + " [" + String::number(mBegin) + "," + String::number(mEnd) + "]"); // Request stripes int nbStripes = std::max(1, int(mSources.size())); // TODO mRequests.fill(NULL, nbStripes); mStripes.fill(NULL, nbStripes); Set<Identifier>::iterator it = mSources.begin(); int i = 0; while(i<nbStripes) { if(!query(i, *it)) { mCacheEntry->refreshSources(); mCacheEntry->getSources(mSources); it = mSources.begin(); if(mSources.empty()) throw Exception("No sources found for " + mCacheEntry->name()); continue; } ++i; ++it; if(it == mSources.end()) it = mSources.begin(); } LogDebug("Splicer", "Transfers launched successfully"); } void Splicer::stop(void) { if(!mRequests.empty()) { LogDebug("Splicer", "Stopping splicer for " + mCacheEntry->name()); for(int i=0; i<mRequests.size(); ++i) delete mRequests[i]; mRequests.clear(); } // Deleting the requests deletes the responses // Deleting the responses deletes the contents // So the stripes are already deleted mStripes.clear(); } int64_t Splicer::process(ByteStream *output) { int64_t written = 0; mCacheEntry->setAccessTime(); if(!mRequests.size()) return 0; unsigned lastBlock = mCacheEntry->block(mCacheEntry->size()) + 1; unsigned currentBlock = lastBlock; int nbPending = 0; for(int i=0; i<mRequests.size(); ++i) { Assert(mRequests[i]); Assert(mStripes[i]); Synchronize(mRequests[i]); if(mRequests[i]->responsesCount()) { const Request::Response *response = mRequests[i]->response(0); Assert(response != NULL); if(response->finished()) continue; } //std::cout<<i<<" -> "<<mStripes[i]->tellWriteBlock()<<std::endl; currentBlock = std::min(currentBlock, mStripes[i]->tellWriteBlock()); mStripes[i]->flush(); ++nbPending; } if(!nbPending) ++currentBlock; //if(mCurrentBlock < currentBlock) //{ // double progress = double(currentBlock) / double(lastBlock); // LogDebug("Splicer", "Download position: " + String::number(progress*100,2) + "%"); //} while(mCurrentBlock < currentBlock) { mCacheEntry->markBlockFinished(mCurrentBlock); ++mCurrentBlock; } unsigned block = mCacheEntry->block(mPosition); if(mPosition < mEnd && block < currentBlock) { size_t size = size_t(std::min(int64_t((block+1)*mCacheEntry->blockSize())-mPosition, mEnd-mPosition)); Assert(size <= mCacheEntry->blockSize()); if(output) { // Open file to read File file(mCacheEntry->fileName(), File::Read); file.seekRead(mPosition); size = file.readBinary(*output, size); file.close(); } mPosition+= size; written+= size; //if(output) //{ // double progress = double(mPosition-mBegin) / double(mEnd-mBegin); // LogDebug("Splicer", "Reading progress: " + String::number(progress*100,2) + "%"); //} if(mPosition == mEnd) return written; } std::vector<int> onError; std::multimap<unsigned, int> byBlocks; for(int i=0; i<mRequests.size(); ++i) { Assert(mRequests[i]); Assert(mStripes[i]); Synchronize(mRequests[i]); byBlocks.insert(std::pair<unsigned,int>(mStripes[i]->tellWriteBlock(), i)); if(mRequests[i]->responsesCount()) { const Request::Response *response = mRequests[i]->response(0); Assert(response != NULL); if(response->error()) onError.push_back(i); } } if(onError.empty()) { if(mRequests.size() >= 2) { int slowest = byBlocks.begin()->second; int fastest = byBlocks.rbegin()->second; if(mRequests[fastest]->receiver() != mRequests[slowest]->receiver()) { if((mStripes[fastest]->tellWriteBlock()-mFirstBlock) > 2*(mStripes[slowest]->tellWriteBlock()-mFirstBlock) + 2) query(slowest, mRequests[fastest]->receiver()); } } } else for(int k=0; k<onError.size(); ++k) { int i = onError[k]; LogWarn("Splicer::process", String("Error on request ") + String::number(i)); Identifier formerSource = mRequests[i]->receiver(); Identifier source; Map<unsigned, int>::reverse_iterator it = byBlocks.rbegin(); while(true) { source = mRequests[it->second]->receiver(); if(source != formerSource) break; ++it; if(it == byBlocks.rend()) { Set<Identifier> sources; mCacheEntry->refreshSources(); mCacheEntry->getSources(sources); if(sources.empty()) { msleep(30000); return written; } if(sources.find(formerSource) != sources.end()) { if(sources.size()> 1) sources.erase(formerSource); else msleep(30000); } Set<Identifier>::iterator jt = sources.begin(); int r = rand() % sources.size(); for(int i=0; i<r; ++i) jt++; source = *jt; break; } } query(i, source); } return written; } bool Splicer::query(int i, const Identifier &source) { Assert(i < mRequests.size()); Assert(i < mStripes.size()); int nbStripes = mStripes.size(); unsigned block = mFirstBlock; size_t offset = 0; if(mStripes[i]) { block = std::max(block, mStripes[i]->tellWriteBlock()); mStripes[i]->flush(); } if(mRequests[i]) delete mRequests[i]; mStripes[i] = NULL; mRequests[i] = NULL; File *file = new File(mCacheEntry->fileName(), File::ReadWrite); StripedFile *striped = new StripedFile(file, mCacheEntry->blockSize(), nbStripes, i); striped->seekWrite(block, offset); mStripes[i] = striped; StringMap parameters; parameters["block-size"] << mCacheEntry->blockSize(); parameters["stripes-count"] << nbStripes; parameters["stripe"] << i; parameters["block"] << block; parameters["offset"] << offset; Request *request = new Request; request->setTarget(mCacheEntry->target().toString(),true); request->setParameters(parameters); request->setContentSink(striped); try { request->submit(source); } catch(...) { return false; } mRequests[i] = request; return true; } Splicer::CacheEntry::CacheEntry(const ByteString &target) : mTarget(target), mSize(0), mBlockSize(128*1024), // TODO mTime(Time::Now()) { mFileName = File::TempName(); File dummy(mFileName, File::TruncateReadWrite); dummy.close(); } Splicer::CacheEntry::~CacheEntry(void) { File::Remove(mFileName); } ByteString Splicer::CacheEntry::target(void) const { Synchronize(this); return mTarget; } String Splicer::CacheEntry::fileName(void) const { Synchronize(this); return mFileName; } String Splicer::CacheEntry::name(void) const { Synchronize(this); if(!mName.empty()) return mName; else return "unknwon"; } int64_t Splicer::CacheEntry::size(void) const { Synchronize(this); return mSize; } size_t Splicer::CacheEntry::blockSize(void) const { Synchronize(this); return mBlockSize; } bool Splicer::CacheEntry::finished(void) const { Synchronize(this); if(mFinishedBlocks.size() < (mSize + mBlockSize - 1) / mBlockSize) return false; if(std::find(mFinishedBlocks.begin(), mFinishedBlocks.end(), false) != mFinishedBlocks.end()) return false; return true; } Time Splicer::CacheEntry::lastAccessTime(void) const { Synchronize(this); return mTime; } void Splicer::CacheEntry::setAccessTime(void) { Synchronize(this); mTime = Time::Now(); } unsigned Splicer::CacheEntry::block(int64_t position) const { Synchronize(this); return unsigned(position / int64_t(mBlockSize)); } bool Splicer::CacheEntry::getSources(Set<Identifier> &sources) { Synchronize(this); if(mSources.empty()) refreshSources(); sources = mSources; return !sources.empty(); } void Splicer::CacheEntry::refreshSources(void) { Synchronize(this); LogDebug("Splicer", "Requesting available sources..."); const unsigned timeout = Config::Get("request_timeout").toInt(); Request request(mTarget.toString(), false); request.submit(); DesynchronizeStatement(this, request.wait(timeout)); { Synchronize(&request); mSources.clear(); for(int i=0; i<request.responsesCount(); ++i) { Request::Response *response = request.response(i); const StringMap &parameters = response->parameters(); if(!response->error()) { if(mName.empty() && parameters.contains("name")) mName = parameters.get("name"); // TODO: check size if(mSize == 0 && parameters.contains("size")) parameters.get("size").extract(mSize); mSources.insert(response->peering()); } } } if(mName.empty()) throw Exception("Unable to retrieve the file name"); LogDebug("Splicer", "Found " + String::number(int(mSources.size())) + " sources"); } bool Splicer::CacheEntry::isBlockFinished(unsigned block) const { Synchronize(this); if(block >= mFinishedBlocks.size()) return false; return mFinishedBlocks[block]; } bool Splicer::CacheEntry::markBlockFinished(unsigned block) { Synchronize(this); if(block >= mFinishedBlocks.size()) { unsigned i = mFinishedBlocks.size(); mFinishedBlocks.resize(block+1); while(i < mFinishedBlocks.size()-1) { mFinishedBlocks[i] = false; ++i; } } mFinishedBlocks[block] = true; return true; } } <commit_msg>Cleaning sources refresh system<commit_after>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * TeapotNet 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 Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/splicer.h" #include "tpn/request.h" #include "tpn/pipe.h" #include "tpn/config.h" namespace tpn { Map<ByteString, Splicer::CacheEntry*> Splicer::Cache; Mutex Splicer::CacheMutex; Splicer::Splicer(const ByteString &target, int64_t begin, int64_t end) : mFirstBlock(0), mCurrentBlock(0), mBegin(begin), mEnd(end), mPosition(0) { { CacheMutex.lock(); if(!Cache.get(target, mCacheEntry)) { LogDebug("Splicer", "No cached file, creating a new one"); try { mCacheEntry = new CacheEntry(target); } catch(...) { CacheMutex.unlock(); throw; } Cache.insert(target, mCacheEntry); } Map<ByteString, CacheEntry*>::iterator it = Cache.begin(); while(it != Cache.end()) { if(!it->second || Time::Now() - it->second->lastAccessTime() > 3600) Cache.erase(it++); else it++; } CacheMutex.unlock(); } mCacheEntry->getSources(mSources); if(mSources.empty()) throw Exception("No sources found for " + target.toString()); // OK, the cache entry is initialized // Initialize variables mBegin = bounds(mBegin, int64_t(0), mCacheEntry->size()); if(mEnd < 0) mEnd = mCacheEntry->size(); else mEnd = bounds(mEnd, mBegin, mCacheEntry->size()); mPosition = mBegin; mCurrentBlock = mCacheEntry->block(mBegin); mFirstBlock = mCurrentBlock; while(mCacheEntry->isBlockFinished(mFirstBlock)) ++mFirstBlock; } Splicer::~Splicer(void) { stop(); } String Splicer::name(void) const { return mCacheEntry->name(); } int64_t Splicer::size(void) const { return mEnd - mBegin; } int64_t Splicer::begin(void) const { return mBegin; } int64_t Splicer::end(void) const { return mEnd; } bool Splicer::finished(void) const { return mCacheEntry->finished(); } bool Splicer::outputFinished(void) const { return (mPosition == mEnd); } void Splicer::start(void) { stop(); if(finished()) return; LogDebug("Splicer", "Starting splicer for " + mCacheEntry->name() + " [" + String::number(mBegin) + "," + String::number(mEnd) + "]"); // Request stripes int nbStripes = std::max(1, int(mSources.size())); // TODO mRequests.fill(NULL, nbStripes); mStripes.fill(NULL, nbStripes); Set<Identifier>::iterator it = mSources.begin(); int i = 0; while(i<nbStripes) { if(!query(i, *it)) { mCacheEntry->refreshSources(); mCacheEntry->getSources(mSources); it = mSources.begin(); if(mSources.empty()) throw Exception("No sources found for " + mCacheEntry->name()); continue; } ++i; ++it; if(it == mSources.end()) it = mSources.begin(); } LogDebug("Splicer", "Transfers launched successfully"); } void Splicer::stop(void) { if(!mRequests.empty()) { LogDebug("Splicer", "Stopping splicer for " + mCacheEntry->name()); for(int i=0; i<mRequests.size(); ++i) delete mRequests[i]; mRequests.clear(); } // Deleting the requests deletes the responses // Deleting the responses deletes the contents // So the stripes are already deleted mStripes.clear(); } int64_t Splicer::process(ByteStream *output) { int64_t written = 0; mCacheEntry->setAccessTime(); if(!mRequests.size()) return 0; unsigned lastBlock = mCacheEntry->block(mCacheEntry->size()) + 1; unsigned currentBlock = lastBlock; int nbPending = 0; for(int i=0; i<mRequests.size(); ++i) { Assert(mRequests[i]); Assert(mStripes[i]); Synchronize(mRequests[i]); if(mRequests[i]->responsesCount()) { const Request::Response *response = mRequests[i]->response(0); Assert(response != NULL); if(response->finished()) continue; } //std::cout<<i<<" -> "<<mStripes[i]->tellWriteBlock()<<std::endl; currentBlock = std::min(currentBlock, mStripes[i]->tellWriteBlock()); mStripes[i]->flush(); ++nbPending; } if(!nbPending) ++currentBlock; //if(mCurrentBlock < currentBlock) //{ // double progress = double(currentBlock) / double(lastBlock); // LogDebug("Splicer", "Download position: " + String::number(progress*100,2) + "%"); //} while(mCurrentBlock < currentBlock) { mCacheEntry->markBlockFinished(mCurrentBlock); ++mCurrentBlock; } unsigned block = mCacheEntry->block(mPosition); if(mPosition < mEnd && block < currentBlock) { size_t size = size_t(std::min(int64_t((block+1)*mCacheEntry->blockSize())-mPosition, mEnd-mPosition)); Assert(size <= mCacheEntry->blockSize()); if(output) { // Open file to read File file(mCacheEntry->fileName(), File::Read); file.seekRead(mPosition); size = file.readBinary(*output, size); file.close(); } mPosition+= size; written+= size; //if(output) //{ // double progress = double(mPosition-mBegin) / double(mEnd-mBegin); // LogDebug("Splicer", "Reading progress: " + String::number(progress*100,2) + "%"); //} if(mPosition == mEnd) return written; } std::vector<int> onError; std::multimap<unsigned, int> byBlocks; for(int i=0; i<mRequests.size(); ++i) { Assert(mRequests[i]); Assert(mStripes[i]); Synchronize(mRequests[i]); byBlocks.insert(std::pair<unsigned,int>(mStripes[i]->tellWriteBlock(), i)); if(mRequests[i]->responsesCount()) { const Request::Response *response = mRequests[i]->response(0); Assert(response != NULL); if(response->error()) onError.push_back(i); } } if(onError.empty()) { if(mRequests.size() >= 2) { int slowest = byBlocks.begin()->second; int fastest = byBlocks.rbegin()->second; if(mRequests[fastest]->receiver() != mRequests[slowest]->receiver()) { if((mStripes[fastest]->tellWriteBlock()-mFirstBlock) > 2*(mStripes[slowest]->tellWriteBlock()-mFirstBlock) + 2) query(slowest, mRequests[fastest]->receiver()); } } } else for(int k=0; k<onError.size(); ++k) { int i = onError[k]; LogDebug("Splicer::process", String("Request ") + String::number(i) + " is in error state"); Identifier formerSource = mRequests[i]->receiver(); Identifier source; Map<unsigned, int>::reverse_iterator it = byBlocks.rbegin(); while(true) { Assert(it->second < mRequests.size()); source = mRequests[it->second]->receiver(); if(source != formerSource) break; ++it; if(it == byBlocks.rend()) { Set<Identifier> sources; mCacheEntry->refreshSources(); mCacheEntry->getSources(sources); if(sources.empty()) { LogDebug("Splicer::process", "No sources found, waiting..."); msleep(30000); return written; } if(sources.size() > 1 && sources.find(formerSource) != sources.end()) sources.erase(formerSource); Assert(!sources.empty()); Set<Identifier>::iterator jt = sources.begin(); if(sources.size() > 1) { int r = rand() % sources.size(); while(r--) ++jt; } source = *jt; break; } } query(i, source); } return written; } bool Splicer::query(int i, const Identifier &source) { Assert(i < mRequests.size()); Assert(i < mStripes.size()); int nbStripes = mStripes.size(); unsigned block = mFirstBlock; size_t offset = 0; if(mStripes[i]) { block = std::max(block, mStripes[i]->tellWriteBlock()); mStripes[i]->flush(); } if(mRequests[i]) delete mRequests[i]; mStripes[i] = NULL; mRequests[i] = NULL; File *file = new File(mCacheEntry->fileName(), File::ReadWrite); StripedFile *striped = new StripedFile(file, mCacheEntry->blockSize(), nbStripes, i); striped->seekWrite(block, offset); mStripes[i] = striped; StringMap parameters; parameters["block-size"] << mCacheEntry->blockSize(); parameters["stripes-count"] << nbStripes; parameters["stripe"] << i; parameters["block"] << block; parameters["offset"] << offset; Request *request = new Request; request->setTarget(mCacheEntry->target().toString(),true); request->setParameters(parameters); request->setContentSink(striped); try { request->submit(source); } catch(...) { return false; } mRequests[i] = request; return true; } Splicer::CacheEntry::CacheEntry(const ByteString &target) : mTarget(target), mSize(0), mBlockSize(128*1024), // TODO mTime(Time::Now()) { mFileName = File::TempName(); File dummy(mFileName, File::TruncateReadWrite); dummy.close(); } Splicer::CacheEntry::~CacheEntry(void) { File::Remove(mFileName); } ByteString Splicer::CacheEntry::target(void) const { Synchronize(this); return mTarget; } String Splicer::CacheEntry::fileName(void) const { Synchronize(this); return mFileName; } String Splicer::CacheEntry::name(void) const { Synchronize(this); if(!mName.empty()) return mName; else return "unknwon"; } int64_t Splicer::CacheEntry::size(void) const { Synchronize(this); return mSize; } size_t Splicer::CacheEntry::blockSize(void) const { Synchronize(this); return mBlockSize; } bool Splicer::CacheEntry::finished(void) const { Synchronize(this); if(mFinishedBlocks.size() < (mSize + mBlockSize - 1) / mBlockSize) return false; if(std::find(mFinishedBlocks.begin(), mFinishedBlocks.end(), false) != mFinishedBlocks.end()) return false; return true; } Time Splicer::CacheEntry::lastAccessTime(void) const { Synchronize(this); return mTime; } void Splicer::CacheEntry::setAccessTime(void) { Synchronize(this); mTime = Time::Now(); } unsigned Splicer::CacheEntry::block(int64_t position) const { Synchronize(this); return unsigned(position / int64_t(mBlockSize)); } bool Splicer::CacheEntry::getSources(Set<Identifier> &sources) { Synchronize(this); if(mSources.empty()) refreshSources(); sources = mSources; return !sources.empty(); } void Splicer::CacheEntry::refreshSources(void) { Synchronize(this); LogDebug("Splicer", "Requesting available sources..."); const unsigned timeout = Config::Get("request_timeout").toInt(); Request request(mTarget.toString(), false); request.submit(); DesynchronizeStatement(this, request.wait(timeout)); { Synchronize(&request); mSources.clear(); for(int i=0; i<request.responsesCount(); ++i) { Request::Response *response = request.response(i); const StringMap &parameters = response->parameters(); if(!response->error()) { if(mName.empty() && parameters.contains("name")) mName = parameters.get("name"); // TODO: check size if(mSize == 0 && parameters.contains("size")) parameters.get("size").extract(mSize); mSources.insert(response->peering()); } } } if(mName.empty()) throw Exception("Unable to retrieve the file name"); LogDebug("Splicer", "Found " + String::number(int(mSources.size())) + " sources"); } bool Splicer::CacheEntry::isBlockFinished(unsigned block) const { Synchronize(this); if(block >= mFinishedBlocks.size()) return false; return mFinishedBlocks[block]; } bool Splicer::CacheEntry::markBlockFinished(unsigned block) { Synchronize(this); if(block >= mFinishedBlocks.size()) { unsigned i = mFinishedBlocks.size(); mFinishedBlocks.resize(block+1); while(i < mFinishedBlocks.size()-1) { mFinishedBlocks[i] = false; ++i; } } mFinishedBlocks[block] = true; return true; } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_PERIODIC_HPP #define STAN_MATH_PRIM_MAT_FUN_COV_PERIODIC_HPP #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/distance.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/fun/inv_square.hpp> #include <stan/math/prim/scal/fun/inv.hpp> #include <vector> #include <cmath> namespace stan { namespace math { /** * Returns a periodic covariance matrix \f$ \mathbf{K} \f$ using the input \f$ * \mathbf{X} \f$. The elements of \f$ \mathbf{K} \f$ are defined as \f$ * \mathbf{K}_{ij} = k(\mathbf{X}_i,\mathbf{X}_j), \f$ where \f$ \mathbf{X}_i * \f$ is the \f$i\f$-th row of \f$ \mathbf{X} \f$ and \n \f$ * k(\mathbf{x},\mathbf{x}^\prime) = \sigma^2 \exp\left(-\frac{2\sin^2(\pi * |\mathbf{x}-\mathbf{x}^\prime|/p)}{\ell^2}\right), \f$ \n where \f$ \sigma^2 * \f$, \f$ \ell \f$ and \f$ p \f$ are the signal variance, length-scale and * period. * * @tparam T_x type of std::vector elements of x. * T_x can be a scalar, an Eigen::Vector, or an Eigen::RowVector. * @tparam T_sigma type of sigma * @tparam T_l type of length-scale * @tparam T_p type of period * * @param x std::vector of input elements. * This function assumes that all elements of x have the same size. * @param sigma standard deviation of the signal * @param l length-scale * @param p period * @return periodic covariance matrix * @throw std::domain_error if sigma <= 0, l <= 0, p <= 0 or * x is nan or infinite */ template <typename T_x, typename T_sigma, typename T_l, typename T_p> inline typename Eigen::Matrix< typename stan::return_type<T_x, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov_periodic(const std::vector<T_x>& x, const T_sigma& sigma, const T_l& l, const T_p& p) { using std::exp; const char* fun = "cov_periodic"; check_positive(fun, "signal standard deviation", sigma); check_positive(fun, "length-scale", l); check_positive(fun, "period", p); for (size_t n = 0; n < x.size(); ++n) check_not_nan(fun, "element of x", x[n]); Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x.size(), x.size()); size_t x_size = x.size(); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); T_l neg_two_inv_l_sq = -2.0 * inv_square(l); T_p pi_div_p = M_PI / p; for (size_t j = 0; j < x_size; ++j) { cov(j, j) = sigma_sq; for (size_t i = j + 1; i < x_size; ++i) { cov(i, j) = sigma_sq * exp(square(sin(pi_div_p * distance(x[i], x[j]))) * neg_two_inv_l_sq); cov(j, i) = cov(i, j); } } return cov; } /** * Returns a periodic covariance matrix \f$ \mathbf{K} \f$ using inputs * \f$ \mathbf{X}_1 \f$ and \f$ \mathbf{X}_2 \f$. * The elements of \f$ \mathbf{K} \f$ are defined as * \f$ \mathbf{K}_{ij} = k(\mathbf{X}_{1_i},\mathbf{X}_{2_j}), \f$ where * \f$ \mathbf{X}_{1_i} \f$ and \f$ \mathbf{X}_{2_j} \f$ are the \f$i\f$-th and * \f$j\f$-th rows of \f$ \mathbf{X}_1 \f$ and \f$ \mathbf{X}_2 \f$ and \n \f$ * k(\mathbf{x},\mathbf{x}^\prime) = \sigma^2 \exp\left(-\frac{2\sin^2(\pi * |\mathbf{x}-\mathbf{x}^\prime|/p)}{\ell^2}\right), \f$ \n where \f$ \sigma^2 * \f$, \f$ \ell \f$ and \f$ p \f$ are the signal variance, length-scale and * period. * * @tparam T_x1 type of std::vector elements of x1 * T_x1 can be a scalar, an Eigen::Vector, or an Eigen::RowVector. * @tparam T_x2 type of std::vector elements of x2 * T_x2 can be a scalar, an Eigen::Vector, or an Eigen::RowVector. * @tparam T_sigma type of sigma * @tparam T_l type of length-scale * @tparam T_p type of period * * @param x1 std::vector of first input elements * @param x2 std::vector of second input elements. * This function assumes that all the elements of x1 and x2 have the same * sizes. * @param sigma standard deviation of the signal * @param l length-scale * @param p period * @return periodic covariance matrix * @throw std::domain_error if sigma <= 0, l <= 0, p <= 0 , * x1 or x2 is nan or infinite */ template <typename T_x1, typename T_x2, typename T_sigma, typename T_l, typename T_p> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov_periodic(const std::vector<T_x1>& x1, const std::vector<T_x2>& x2, const T_sigma& sigma, const T_l& l, const T_p& p) { using std::exp; const char* fun = "cov_periodic"; check_positive(fun, "signal standard deviation", sigma); check_positive(fun, "length-scale", l); check_positive(fun, "period", p); for (size_t n = 0; n < x1.size(); ++n) check_not_nan(fun, "element of x1", x1[n]); for (size_t n = 0; n < x2.size(); ++n) check_not_nan(fun, "element of x2", x2[n]); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1.size(), x2.size()); if (x1.size() == 0 || x2.size() == 0) return cov; T_sigma sigma_sq = square(sigma); T_l neg_two_inv_l_sq = -2.0 * inv_square(l); T_p pi_div_p = M_PI / p; for (size_t i = 0; i < x1.size(); ++i) { for (size_t j = 0; j < x2.size(); ++j) { cov(i, j) = sigma_sq * exp(square(sin(pi_div_p * distance(x1[i], x2[j]))) * neg_two_inv_l_sq); } } return cov; } } // namespace math } // namespace stan #endif <commit_msg>Added back missing include<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_PERIODIC_HPP #define STAN_MATH_PRIM_MAT_FUN_COV_PERIODIC_HPP #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/distance.hpp> #include <stan/math/prim/scal/fun/distance.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/fun/inv_square.hpp> #include <stan/math/prim/scal/fun/inv.hpp> #include <vector> #include <cmath> namespace stan { namespace math { /** * Returns a periodic covariance matrix \f$ \mathbf{K} \f$ using the input \f$ * \mathbf{X} \f$. The elements of \f$ \mathbf{K} \f$ are defined as \f$ * \mathbf{K}_{ij} = k(\mathbf{X}_i,\mathbf{X}_j), \f$ where \f$ \mathbf{X}_i * \f$ is the \f$i\f$-th row of \f$ \mathbf{X} \f$ and \n \f$ * k(\mathbf{x},\mathbf{x}^\prime) = \sigma^2 \exp\left(-\frac{2\sin^2(\pi * |\mathbf{x}-\mathbf{x}^\prime|/p)}{\ell^2}\right), \f$ \n where \f$ \sigma^2 * \f$, \f$ \ell \f$ and \f$ p \f$ are the signal variance, length-scale and * period. * * @tparam T_x type of std::vector elements of x. * T_x can be a scalar, an Eigen::Vector, or an Eigen::RowVector. * @tparam T_sigma type of sigma * @tparam T_l type of length-scale * @tparam T_p type of period * * @param x std::vector of input elements. * This function assumes that all elements of x have the same size. * @param sigma standard deviation of the signal * @param l length-scale * @param p period * @return periodic covariance matrix * @throw std::domain_error if sigma <= 0, l <= 0, p <= 0 or * x is nan or infinite */ template <typename T_x, typename T_sigma, typename T_l, typename T_p> inline typename Eigen::Matrix< typename stan::return_type<T_x, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov_periodic(const std::vector<T_x>& x, const T_sigma& sigma, const T_l& l, const T_p& p) { using std::exp; const char* fun = "cov_periodic"; check_positive(fun, "signal standard deviation", sigma); check_positive(fun, "length-scale", l); check_positive(fun, "period", p); for (size_t n = 0; n < x.size(); ++n) check_not_nan(fun, "element of x", x[n]); Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x.size(), x.size()); size_t x_size = x.size(); if (x_size == 0) return cov; T_sigma sigma_sq = square(sigma); T_l neg_two_inv_l_sq = -2.0 * inv_square(l); T_p pi_div_p = M_PI / p; for (size_t j = 0; j < x_size; ++j) { cov(j, j) = sigma_sq; for (size_t i = j + 1; i < x_size; ++i) { cov(i, j) = sigma_sq * exp(square(sin(pi_div_p * distance(x[i], x[j]))) * neg_two_inv_l_sq); cov(j, i) = cov(i, j); } } return cov; } /** * Returns a periodic covariance matrix \f$ \mathbf{K} \f$ using inputs * \f$ \mathbf{X}_1 \f$ and \f$ \mathbf{X}_2 \f$. * The elements of \f$ \mathbf{K} \f$ are defined as * \f$ \mathbf{K}_{ij} = k(\mathbf{X}_{1_i},\mathbf{X}_{2_j}), \f$ where * \f$ \mathbf{X}_{1_i} \f$ and \f$ \mathbf{X}_{2_j} \f$ are the \f$i\f$-th and * \f$j\f$-th rows of \f$ \mathbf{X}_1 \f$ and \f$ \mathbf{X}_2 \f$ and \n \f$ * k(\mathbf{x},\mathbf{x}^\prime) = \sigma^2 \exp\left(-\frac{2\sin^2(\pi * |\mathbf{x}-\mathbf{x}^\prime|/p)}{\ell^2}\right), \f$ \n where \f$ \sigma^2 * \f$, \f$ \ell \f$ and \f$ p \f$ are the signal variance, length-scale and * period. * * @tparam T_x1 type of std::vector elements of x1 * T_x1 can be a scalar, an Eigen::Vector, or an Eigen::RowVector. * @tparam T_x2 type of std::vector elements of x2 * T_x2 can be a scalar, an Eigen::Vector, or an Eigen::RowVector. * @tparam T_sigma type of sigma * @tparam T_l type of length-scale * @tparam T_p type of period * * @param x1 std::vector of first input elements * @param x2 std::vector of second input elements. * This function assumes that all the elements of x1 and x2 have the same * sizes. * @param sigma standard deviation of the signal * @param l length-scale * @param p period * @return periodic covariance matrix * @throw std::domain_error if sigma <= 0, l <= 0, p <= 0 , * x1 or x2 is nan or infinite */ template <typename T_x1, typename T_x2, typename T_sigma, typename T_l, typename T_p> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov_periodic(const std::vector<T_x1>& x1, const std::vector<T_x2>& x2, const T_sigma& sigma, const T_l& l, const T_p& p) { using std::exp; const char* fun = "cov_periodic"; check_positive(fun, "signal standard deviation", sigma); check_positive(fun, "length-scale", l); check_positive(fun, "period", p); for (size_t n = 0; n < x1.size(); ++n) check_not_nan(fun, "element of x1", x1[n]); for (size_t n = 0; n < x2.size(); ++n) check_not_nan(fun, "element of x2", x2[n]); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l, T_p>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1.size(), x2.size()); if (x1.size() == 0 || x2.size() == 0) return cov; T_sigma sigma_sq = square(sigma); T_l neg_two_inv_l_sq = -2.0 * inv_square(l); T_p pi_div_p = M_PI / p; for (size_t i = 0; i < x1.size(); ++i) { for (size_t j = 0; j < x2.size(); ++j) { cov(i, j) = sigma_sq * exp(square(sin(pi_div_p * distance(x1[i], x2[j]))) * neg_two_inv_l_sq); } } return cov; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "Image.h" namespace sfc { Image::Image(const std::string& path) { std::vector<unsigned char> buffer; unsigned w, h; unsigned error = lodepng::load_file(buffer, path); if (error) throw std::runtime_error(lodepng_error_text(error)); lodepng::State state; state.decoder.color_convert = false; state.decoder.ignore_crc = true; error = lodepng::decode(_data, w, h, state, buffer); if (error) throw std::runtime_error(lodepng_error_text(error)); bool needs_conversion = false; if (state.info_raw.colortype == LCT_PALETTE) { if (state.info_raw.bitdepth && state.info_raw.bitdepth < 8) { // unpack 2/4 bit data _indexed_data = std::vector<index_t>(w * h); unsigned depth = state.info_raw.bitdepth; unsigned ppb = 8 / state.info_raw.bitdepth; index_t mask = 0; for (unsigned i = 0; i < depth; ++i) mask = (mask << 1) + 1; for (unsigned i = 0; i < _indexed_data.size(); ++i) { unsigned pack_shift = 8 - depth - ((i * depth) % 8); _indexed_data[i] = mask & (_data[i / ppb] >> pack_shift); } } else { _indexed_data = _data; } for (unsigned i = 0; i < state.info_raw.palettesize * 4; i += 4) { uint32_t color = (state.info_raw.palette[i]) + (state.info_raw.palette[i + 1] << 8) + (state.info_raw.palette[i + 2] << 16) + (state.info_raw.palette[i + 3] << 24); _palette.push_back(color); } needs_conversion = true; state.info_raw.colortype = LCT_RGBA; } if (state.info_png.color.colortype == LCT_RGB || state.info_png.color.colortype == LCT_GREY || state.info_png.color.colortype == LCT_GREY_ALPHA) { state.info_raw.colortype = LCT_RGBA; needs_conversion = true; } if (state.info_png.color.bitdepth != 8) { state.info_raw.bitdepth = 8; needs_conversion = true; } if (needs_conversion) { _data.clear(); state.decoder.color_convert = true; error = lodepng::decode(_data, w, h, state, buffer); if (error) throw std::runtime_error(lodepng_error_text(error)); } _width = w; _height = h; auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } Image::Image(const sfc::Palette& palette) { auto v = palette.normalized_colors(); if (v.empty() || v[0].empty()) throw std::runtime_error("No colors"); _width = palette.max_colors_per_subpalette(); _height = (unsigned)v.size(); _data.resize(_width * _height * 4); std::fill(_data.begin(), _data.end(), 0); for (unsigned y = 0; y < v.size(); ++y) { auto vy = v[y]; for (unsigned x = 0; x < vy.size(); ++x) set_pixel(sfc::rgba_color(vy[x]), x, y); } auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } Image::Image(const sfc::Tileset& tileset) { const auto tiles = tileset.tiles(); const unsigned image_width = 128; const unsigned tile_width = tileset.tile_width(); const unsigned tile_height = tileset.tile_height(); const unsigned tiles_per_row = sfc::div_ceil(image_width, tile_width); const unsigned rows = sfc::div_ceil(tileset.size(), tiles_per_row); _width = image_width; _height = rows * tileset.tile_height(); _data.resize(_width * _height * 4); std::fill(_data.begin(), _data.end(), 0); _indexed_data.resize(_width * _height); std::fill(_indexed_data.begin(), _indexed_data.end(), 0); if (_data.empty()) return; _palette = tileset.tiles()[0].palette(); for (unsigned tile_index = 0; tile_index < tiles.size(); ++tile_index) { auto tile_rgba = tiles[tile_index].rgba_data(); blit(tile_rgba, (tile_index % tiles_per_row) * tile_width, (tile_index / tiles_per_row) * tile_height, tile_width); auto tile_data = tiles[tile_index].data(); blit_indexed(tile_data, (tile_index % tiles_per_row) * tile_width, (tile_index / tiles_per_row) * tile_height, tile_width); } auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } // Make new normalized image with color indices mapped to palette Image::Image(const Image& image, const sfc::Subpalette& subpalette) : _width(image.width()), _height(image.height()), _palette(subpalette.normalized_colors()) { if (_palette.empty()) throw std::runtime_error("No colors"); sfc::Mode mode = subpalette.mode(); unsigned size = _width * _height; _indexed_data.resize(size); _data.resize(size * 4); for (unsigned i = 0; i < size; ++i) { rgba_t color = sfc::normalize_color(sfc::reduce_color(image.rgba_color_at(i), mode), mode); if (color == transparent_color) { _indexed_data[i] = 0; set_pixel(transparent_color, i); } else { size_t palette_index = std::find(_palette.begin(), _palette.end(), color) - _palette.begin(); if (palette_index < _palette.size()) { _indexed_data[i] = (index_t)palette_index; set_pixel(sfc::rgba_color(_palette[palette_index]), i); } else { throw std::runtime_error("Color not in palette"); } } } auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } std::vector<rgba_t> Image::rgba_data() const { return sfc::to_rgba(_data); } Image Image::crop(unsigned x, unsigned y, unsigned crop_width, unsigned crop_height) const { Image img; img._palette = _palette; img._width = crop_width; img._height = crop_height; img._src_coord_x = x; img._src_coord_y = y; img._data.resize(crop_width * crop_height * 4); uint32_t fillval = transparent_color; size_t fillsize = img._data.size(); for (size_t i = 0; i < fillsize; i += 4) std::memcpy(img._data.data() + i, &fillval, sizeof(fillval)); if (x > _width || y > _height) { // Crop outside source image: return empty if (_indexed_data.size()) img._indexed_data.resize(crop_width * crop_height); return img; } unsigned blit_width = (x + crop_width > _width) ? _width - x : crop_width; unsigned blit_height = (y + crop_height > _height) ? _height - y : crop_height; for (unsigned iy = 0; iy < blit_height; ++iy) { std::memcpy(&img._data[iy * img._width * 4], &_data[(x * 4) + ((iy + y) * _width * 4)], blit_width * 4); } if (_indexed_data.size()) { img._indexed_data.resize(crop_width * crop_height); for (unsigned iy = 0; iy < blit_height; ++iy) { std::memcpy(&img._indexed_data[iy * img._width], &_indexed_data[x + ((iy + y) * _width)], blit_width); } } auto rgba_v = img.rgba_data(); img._colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); return img; } std::vector<Image> Image::crops(unsigned tile_width, unsigned tile_height) const { std::vector<Image> v; unsigned x = 0; unsigned y = 0; while (y < _height) { while (x < _width) { v.push_back(crop(x, y, tile_width, tile_height)); x += tile_width; } x = 0; y += tile_width; } return v; } void Image::save(const std::string& path) const { unsigned error = lodepng::encode(path.c_str(), _data, _width, _height, LCT_RGBA, 8); if (error) throw std::runtime_error(lodepng_error_text(error)); } void Image::save_indexed(const std::string& path) { if (_palette.empty()) set_default_palette(); lodepng::State state; for (const auto& c : _palette) { rgba_color rgba(c); lodepng_palette_add(&state.info_png.color, rgba.r, rgba.g, rgba.b, rgba.a); lodepng_palette_add(&state.info_raw, rgba.r, rgba.g, rgba.b, rgba.a); } state.info_png.color.colortype = state.info_raw.colortype = LCT_PALETTE; state.info_png.color.bitdepth = state.info_raw.bitdepth = 8; state.encoder.auto_convert = 0; std::vector<uint8_t> buffer; unsigned error = lodepng::encode(buffer, _indexed_data, _width, _height, state); if (error) throw std::runtime_error(lodepng_error_text(error)); lodepng::save_file(buffer, path.c_str()); } const std::string Image::description() const { return fmt::format("{}x{}, {}", width(), height(), palette_size() ? "indexed color" : "RGB color"); } inline void Image::set_pixel(const rgba_t color, const unsigned index) { const unsigned offset = index * 4; if ((offset + 3) > _data.size()) return; _data[offset + 0] = (channel_t)(color & 0xff); _data[offset + 1] = (channel_t)((color >> 8) & 0xff); _data[offset + 2] = (channel_t)((color >> 16) & 0xff); _data[offset + 3] = (channel_t)((color >> 24) & 0xff); _colors.insert(color); } inline void Image::set_pixel(const rgba_t color, const unsigned x, const unsigned y) { const unsigned offset = ((y * _width) + x) * 4; if ((offset + 3) > _data.size()) return; _data[offset + 0] = (channel_t)(color & 0xff); _data[offset + 1] = (channel_t)((color >> 8) & 0xff); _data[offset + 2] = (channel_t)((color >> 16) & 0xff); _data[offset + 3] = (channel_t)((color >> 24) & 0xff); _colors.insert(color); } void Image::blit(const std::vector<rgba_t>& rgba_data, const unsigned x, const unsigned y, const unsigned width) { for (unsigned i = 0; i < rgba_data.size(); ++i) set_pixel(rgba_data[i], (i % width) + x, (i / width) + y); } inline void Image::set_pixel_indexed(const index_t color, const unsigned index) { if ((index) > _indexed_data.size()) return; _indexed_data[index] = color; } inline void Image::set_pixel_indexed(const index_t color, const unsigned x, const unsigned y) { const unsigned offset = (y * _width) + x; if (offset > _indexed_data.size()) return; _indexed_data[offset] = color; } void Image::blit_indexed(const std::vector<channel_t>& data, const unsigned x, const unsigned y, const unsigned width) { for (unsigned i = 0; i < data.size(); ++i) set_pixel_indexed(data[i], (i % width) + x, (i / width) + y); } void Image::set_default_palette(const unsigned indices) { _palette.resize(indices); channel_t add = 0x100 / _palette.size(); for (unsigned i = 0; i < _palette.size(); ++i) { channel_t value = add * i; _palette[i] = (rgba_t)(0xff000000 + value + (value << 8) + (value << 16)); } } } /* namespace sfc */ <commit_msg>Safer Image struct initialization<commit_after>#include "Image.h" namespace sfc { Image::Image(const std::string& path) { std::vector<unsigned char> buffer; unsigned w, h; unsigned error = lodepng::load_file(buffer, path); if (error) throw std::runtime_error(lodepng_error_text(error)); lodepng::State state; state.decoder.color_convert = false; state.decoder.ignore_crc = true; error = lodepng::decode(_data, w, h, state, buffer); if (error) throw std::runtime_error(lodepng_error_text(error)); bool needs_conversion = false; if (state.info_raw.colortype == LCT_PALETTE) { if (state.info_raw.bitdepth && state.info_raw.bitdepth < 8) { // unpack 2/4 bit data _indexed_data = std::vector<index_t>(w * h); unsigned depth = state.info_raw.bitdepth; unsigned ppb = 8 / state.info_raw.bitdepth; index_t mask = 0; for (unsigned i = 0; i < depth; ++i) mask = (mask << 1) + 1; for (unsigned i = 0; i < _indexed_data.size(); ++i) { unsigned pack_shift = 8 - depth - ((i * depth) % 8); _indexed_data[i] = mask & (_data[i / ppb] >> pack_shift); } } else { _indexed_data = _data; } for (unsigned i = 0; i < state.info_raw.palettesize * 4; i += 4) { uint32_t color = (state.info_raw.palette[i]) + (state.info_raw.palette[i + 1] << 8) + (state.info_raw.palette[i + 2] << 16) + (state.info_raw.palette[i + 3] << 24); _palette.push_back(color); } needs_conversion = true; state.info_raw.colortype = LCT_RGBA; } if (state.info_png.color.colortype == LCT_RGB || state.info_png.color.colortype == LCT_GREY || state.info_png.color.colortype == LCT_GREY_ALPHA) { state.info_raw.colortype = LCT_RGBA; needs_conversion = true; } if (state.info_png.color.bitdepth != 8) { state.info_raw.bitdepth = 8; needs_conversion = true; } if (needs_conversion) { _data.clear(); state.decoder.color_convert = true; error = lodepng::decode(_data, w, h, state, buffer); if (error) throw std::runtime_error(lodepng_error_text(error)); } _width = w; _height = h; _src_coord_x = _src_coord_y = 0; auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } Image::Image(const sfc::Palette& palette) { auto v = palette.normalized_colors(); if (v.empty() || v[0].empty()) throw std::runtime_error("No colors"); _width = palette.max_colors_per_subpalette(); _height = (unsigned)v.size(); _data.resize(_width * _height * 4); std::fill(_data.begin(), _data.end(), 0); for (unsigned y = 0; y < v.size(); ++y) { auto vy = v[y]; for (unsigned x = 0; x < vy.size(); ++x) set_pixel(sfc::rgba_color(vy[x]), x, y); } _src_coord_x = _src_coord_y = 0; auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } Image::Image(const sfc::Tileset& tileset) { const auto tiles = tileset.tiles(); const unsigned image_width = 128; const unsigned tile_width = tileset.tile_width(); const unsigned tile_height = tileset.tile_height(); const unsigned tiles_per_row = sfc::div_ceil(image_width, tile_width); const unsigned rows = sfc::div_ceil(tileset.size(), tiles_per_row); _width = image_width; _height = rows * tileset.tile_height(); _data.resize(_width * _height * 4); std::fill(_data.begin(), _data.end(), 0); _indexed_data.resize(_width * _height); std::fill(_indexed_data.begin(), _indexed_data.end(), 0); if (_data.empty()) return; _palette = tileset.tiles()[0].palette(); for (unsigned tile_index = 0; tile_index < tiles.size(); ++tile_index) { auto tile_rgba = tiles[tile_index].rgba_data(); blit(tile_rgba, (tile_index % tiles_per_row) * tile_width, (tile_index / tiles_per_row) * tile_height, tile_width); auto tile_data = tiles[tile_index].data(); blit_indexed(tile_data, (tile_index % tiles_per_row) * tile_width, (tile_index / tiles_per_row) * tile_height, tile_width); } _src_coord_x = _src_coord_y = 0; auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } // Make new normalized image with color indices mapped to palette Image::Image(const Image& image, const sfc::Subpalette& subpalette) : _width(image.width()), _height(image.height()), _palette(subpalette.normalized_colors()) { if (_palette.empty()) throw std::runtime_error("No colors"); unsigned size = _width * _height; _indexed_data.resize(size); _data.resize(size * 4); for (unsigned i = 0; i < size; ++i) { rgba_t color = sfc::normalize_color(sfc::reduce_color(image.rgba_color_at(i), subpalette.mode()), subpalette.mode()); if (color == transparent_color) { _indexed_data[i] = 0; set_pixel(transparent_color, i); } else { size_t palette_index = std::find(_palette.begin(), _palette.end(), color) - _palette.begin(); if (palette_index < _palette.size()) { _indexed_data[i] = (index_t)palette_index; set_pixel(sfc::rgba_color(_palette[palette_index]), i); } else { throw std::runtime_error("Color not in palette"); } } } _src_coord_x = _src_coord_y = 0; auto rgba_v = rgba_data(); _colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); } std::vector<rgba_t> Image::rgba_data() const { return sfc::to_rgba(_data); } Image Image::crop(unsigned x, unsigned y, unsigned crop_width, unsigned crop_height) const { Image img; img._palette = _palette; img._width = crop_width; img._height = crop_height; img._src_coord_x = x; img._src_coord_y = y; img._data.resize(crop_width * crop_height * 4); uint32_t fillval = transparent_color; size_t fillsize = img._data.size(); for (size_t i = 0; i < fillsize; i += 4) std::memcpy(img._data.data() + i, &fillval, sizeof(fillval)); if (x > _width || y > _height) { // Crop outside source image: return empty if (_indexed_data.size()) img._indexed_data.resize(crop_width * crop_height); return img; } unsigned blit_width = (x + crop_width > _width) ? _width - x : crop_width; unsigned blit_height = (y + crop_height > _height) ? _height - y : crop_height; for (unsigned iy = 0; iy < blit_height; ++iy) { std::memcpy(&img._data[iy * img._width * 4], &_data[(x * 4) + ((iy + y) * _width * 4)], blit_width * 4); } if (_indexed_data.size()) { img._indexed_data.resize(crop_width * crop_height); for (unsigned iy = 0; iy < blit_height; ++iy) { std::memcpy(&img._indexed_data[iy * img._width], &_indexed_data[x + ((iy + y) * _width)], blit_width); } } auto rgba_v = img.rgba_data(); img._colors = std::set<rgba_t>(rgba_v.begin(), rgba_v.end()); return img; } std::vector<Image> Image::crops(unsigned tile_width, unsigned tile_height) const { std::vector<Image> v; unsigned x = 0; unsigned y = 0; while (y < _height) { while (x < _width) { v.push_back(crop(x, y, tile_width, tile_height)); x += tile_width; } x = 0; y += tile_width; } return v; } void Image::save(const std::string& path) const { unsigned error = lodepng::encode(path.c_str(), _data, _width, _height, LCT_RGBA, 8); if (error) throw std::runtime_error(lodepng_error_text(error)); } void Image::save_indexed(const std::string& path) { if (_palette.empty()) set_default_palette(); lodepng::State state; for (const auto& c : _palette) { rgba_color rgba(c); lodepng_palette_add(&state.info_png.color, rgba.r, rgba.g, rgba.b, rgba.a); lodepng_palette_add(&state.info_raw, rgba.r, rgba.g, rgba.b, rgba.a); } state.info_png.color.colortype = state.info_raw.colortype = LCT_PALETTE; state.info_png.color.bitdepth = state.info_raw.bitdepth = 8; state.encoder.auto_convert = 0; std::vector<uint8_t> buffer; unsigned error = lodepng::encode(buffer, _indexed_data, _width, _height, state); if (error) throw std::runtime_error(lodepng_error_text(error)); lodepng::save_file(buffer, path.c_str()); } const std::string Image::description() const { return fmt::format("{}x{}, {}", width(), height(), palette_size() ? "indexed color" : "RGB color"); } inline void Image::set_pixel(const rgba_t color, const unsigned index) { const unsigned offset = index * 4; if ((offset + 3) > _data.size()) return; _data[offset + 0] = (channel_t)(color & 0xff); _data[offset + 1] = (channel_t)((color >> 8) & 0xff); _data[offset + 2] = (channel_t)((color >> 16) & 0xff); _data[offset + 3] = (channel_t)((color >> 24) & 0xff); _colors.insert(color); } inline void Image::set_pixel(const rgba_t color, const unsigned x, const unsigned y) { const unsigned offset = ((y * _width) + x) * 4; if ((offset + 3) > _data.size()) return; _data[offset + 0] = (channel_t)(color & 0xff); _data[offset + 1] = (channel_t)((color >> 8) & 0xff); _data[offset + 2] = (channel_t)((color >> 16) & 0xff); _data[offset + 3] = (channel_t)((color >> 24) & 0xff); _colors.insert(color); } void Image::blit(const std::vector<rgba_t>& rgba_data, const unsigned x, const unsigned y, const unsigned width) { for (unsigned i = 0; i < rgba_data.size(); ++i) set_pixel(rgba_data[i], (i % width) + x, (i / width) + y); } inline void Image::set_pixel_indexed(const index_t color, const unsigned index) { if ((index) > _indexed_data.size()) return; _indexed_data[index] = color; } inline void Image::set_pixel_indexed(const index_t color, const unsigned x, const unsigned y) { const unsigned offset = (y * _width) + x; if (offset > _indexed_data.size()) return; _indexed_data[offset] = color; } void Image::blit_indexed(const std::vector<channel_t>& data, const unsigned x, const unsigned y, const unsigned width) { for (unsigned i = 0; i < data.size(); ++i) set_pixel_indexed(data[i], (i % width) + x, (i / width) + y); } void Image::set_default_palette(const unsigned indices) { _palette.resize(indices); channel_t add = 0x100 / _palette.size(); for (unsigned i = 0; i < _palette.size(); ++i) { channel_t value = add * i; _palette[i] = (rgba_t)(0xff000000 + value + (value << 8) + (value << 16)); } } } /* namespace sfc */ <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexVB.cxx ** Lexer for Visual Basic and VBScript. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool IsVBComment(Accessor &styler, int pos, int len) { return len>0 && styler[pos]=='\''; } inline bool IsTypeCharacter(const int ch) { return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$'; } static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler, bool vbScriptSyntax) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); int visibleChars = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_B_OPERATOR) { sc.SetState(SCE_B_DEFAULT); } else if (sc.state == SCE_B_KEYWORD) { if (!iswordchar(sc.ch)) { if (vbScriptSyntax || !IsTypeCharacter(sc.ch)) { if (sc.ch == ']') sc.Forward(); char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { if (strcmp(s, "rem") == 0) { sc.ChangeState(SCE_C_COMMENTLINE); } } else { sc.ChangeState(SCE_B_IDENTIFIER); } sc.SetState(SCE_B_DEFAULT); } } } else if (sc.state == SCE_B_NUMBER) { if (!iswordchar(sc.ch)) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_STRING) { // VB doubles quotes to preserve them, so just end this string // state now as a following quote will start again if (sc.ch == '\"') { if (tolower(sc.chNext) == 'c') { sc.Forward(); } sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_PREPROCESSOR) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_DATE) { if (sc.ch == '#') { sc.ForwardSetState(SCE_B_DEFAULT); } } if (sc.state == SCE_B_DEFAULT) { if (sc.ch == '\'') { sc.SetState(SCE_B_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_B_STRING); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_B_PREPROCESSOR); } else if (sc.ch == '#') { int n = 1; int chSeek = ' '; while (chSeek == ' ' || chSeek == '\t') { chSeek = sc.GetRelative(n); n++; } if (IsADigit(chSeek)) { sc.SetState(SCE_B_DATE); } else { sc.SetState(SCE_B_OPERATOR); } } else if (sc.ch == '&' && tolower(sc.chNext) == 'h') { sc.SetState(SCE_B_NUMBER); } else if (sc.ch == '&' && tolower(sc.chNext) == 'o') { sc.SetState(SCE_B_NUMBER); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_B_NUMBER); } else if (iswordstart(sc.ch) || (sc.ch == '[')) { sc.SetState(SCE_B_KEYWORD); } else if (isoperator(sc.ch) || (sc.ch == '\\')) { sc.SetState(SCE_B_OPERATOR); } } if (sc.atLineEnd) { visibleChars = 0; } if (!IsASpace(sc.ch)) { visibleChars++; } } sc.Complete(); } static void FoldVBDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { int endPos = startPos + length; // Backtrack to previous line in case need to fix its fold status int lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); if (startPos == 0) initStyle = SCE_B_DEFAULT; else initStyle = styler.StyleAt(startPos-1); } } int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment); char chNext = styler[startPos]; for (int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) { int lev = indentCurrent; int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } static void ColouriseVBNetDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, false); } static void ColouriseVBScriptDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, true); } LexerModule lmVB(SCLEX_VB, ColouriseVBNetDoc, "vb", FoldVBDoc); LexerModule lmVBScript(SCLEX_VBSCRIPT, ColouriseVBScriptDoc, "vbscript", FoldVBDoc); <commit_msg>Fixed comments that use rem rather than '.<commit_after>// Scintilla source code edit control /** @file LexVB.cxx ** Lexer for Visual Basic and VBScript. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool IsVBComment(Accessor &styler, int pos, int len) { return len>0 && styler[pos]=='\''; } inline bool IsTypeCharacter(const int ch) { return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$'; } static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler, bool vbScriptSyntax) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); int visibleChars = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_B_OPERATOR) { sc.SetState(SCE_B_DEFAULT); } else if (sc.state == SCE_B_KEYWORD) { if (!iswordchar(sc.ch)) { if (vbScriptSyntax || !IsTypeCharacter(sc.ch)) { if (sc.ch == ']') sc.Forward(); char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { if (strcmp(s, "rem") == 0) { sc.ChangeState(SCE_B_COMMENT); if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else { sc.SetState(SCE_B_DEFAULT); } } else { sc.ChangeState(SCE_B_IDENTIFIER); sc.SetState(SCE_B_DEFAULT); } } } } else if (sc.state == SCE_B_NUMBER) { if (!iswordchar(sc.ch)) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_STRING) { // VB doubles quotes to preserve them, so just end this string // state now as a following quote will start again if (sc.ch == '\"') { if (tolower(sc.chNext) == 'c') { sc.Forward(); } sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_PREPROCESSOR) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_DATE) { if (sc.ch == '#') { sc.ForwardSetState(SCE_B_DEFAULT); } } if (sc.state == SCE_B_DEFAULT) { if (sc.ch == '\'') { sc.SetState(SCE_B_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_B_STRING); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_B_PREPROCESSOR); } else if (sc.ch == '#') { int n = 1; int chSeek = ' '; while (chSeek == ' ' || chSeek == '\t') { chSeek = sc.GetRelative(n); n++; } if (IsADigit(chSeek)) { sc.SetState(SCE_B_DATE); } else { sc.SetState(SCE_B_OPERATOR); } } else if (sc.ch == '&' && tolower(sc.chNext) == 'h') { sc.SetState(SCE_B_NUMBER); } else if (sc.ch == '&' && tolower(sc.chNext) == 'o') { sc.SetState(SCE_B_NUMBER); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_B_NUMBER); } else if (iswordstart(sc.ch) || (sc.ch == '[')) { sc.SetState(SCE_B_KEYWORD); } else if (isoperator(sc.ch) || (sc.ch == '\\')) { sc.SetState(SCE_B_OPERATOR); } } if (sc.atLineEnd) { visibleChars = 0; } if (!IsASpace(sc.ch)) { visibleChars++; } } sc.Complete(); } static void FoldVBDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { int endPos = startPos + length; // Backtrack to previous line in case need to fix its fold status int lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); if (startPos == 0) initStyle = SCE_B_DEFAULT; else initStyle = styler.StyleAt(startPos-1); } } int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment); char chNext = styler[startPos]; for (int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) { int lev = indentCurrent; int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } static void ColouriseVBNetDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, false); } static void ColouriseVBScriptDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, true); } LexerModule lmVB(SCLEX_VB, ColouriseVBNetDoc, "vb", FoldVBDoc); LexerModule lmVBScript(SCLEX_VBSCRIPT, ColouriseVBScriptDoc, "vbscript", FoldVBDoc); <|endoftext|>
<commit_before>#include <GL/glew.h> #include <glm/glm.hpp> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "Model.h" #include "Vertex.h" using namespace eyesore; using namespace glm; using std::string; using std::vector; static Mesh extractMesh(const aiMesh *mesh) { vector<Vertex> vertices; vector<GLuint> indices; for (int i = 0; i < mesh->mNumVertices; i++) { aiVector3D pos = mesh->mVertices[i]; aiVector3D norm = mesh->mNormals[i]; aiVector3D uv = mesh->mTextureCoords[0][i]; vertices.push_back(Vertex(vec3(pos.x, pos.y, pos.z), vec3(norm.x, norm.y, norm.z), vec2(uv.x, uv.y))); } for (int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (int j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } return Mesh(vertices, indices); } eyesore::Model::Model(const string &path) { Assimp::Importer importer; const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate); for (int i = 0; i < scene->mNumMeshes; i++) meshes.push_back(extractMesh(scene->mMeshes[i])); } void eyesore::Model::render() { for (const Mesh &mesh : meshes) mesh.render(); } <commit_msg>Fix improper include<commit_after>#include <GL/glew.h> #include <glm/glm.hpp> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "Model.h" #include "Vertex.h" using namespace eyesore; using namespace glm; using std::string; using std::vector; static Mesh extractMesh(const aiMesh *mesh) { vector<Vertex> vertices; vector<GLuint> indices; for (int i = 0; i < mesh->mNumVertices; i++) { aiVector3D pos = mesh->mVertices[i]; aiVector3D norm = mesh->mNormals[i]; aiVector3D uv = mesh->mTextureCoords[0][i]; vertices.push_back(Vertex(vec3(pos.x, pos.y, pos.z), vec3(norm.x, norm.y, norm.z), vec2(uv.x, uv.y))); } for (int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (int j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } return Mesh(vertices, indices); } eyesore::Model::Model(const string &path) { Assimp::Importer importer; const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate); for (int i = 0; i < scene->mNumMeshes; i++) meshes.push_back(extractMesh(scene->mMeshes[i])); } void eyesore::Model::render() { for (const Mesh &mesh : meshes) mesh.render(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SwUndoTOXChange.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-03-29 14:39:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <SwUndoTOXChange.hxx> #include <swundo.hxx> #include <doctxm.hxx> SwUndoTOXChange::SwUndoTOXChange(SwTOXBase * _pTOX, const SwTOXBase & rNew) : SwUndo(UNDO_TOXCHANGE), pTOX(_pTOX), aOld(*_pTOX), aNew(rNew) { } SwUndoTOXChange::~SwUndoTOXChange() { } void SwUndoTOXChange::UpdateTOXBaseSection() { if (pTOX->ISA(SwTOXBaseSection)) { SwTOXBaseSection * pTOXBase = static_cast<SwTOXBaseSection *>(pTOX); pTOXBase->Update(); pTOXBase->UpdatePageNum(); } } void SwUndoTOXChange::Undo(SwUndoIter & rIter) { *pTOX = aOld; UpdateTOXBaseSection(); } void SwUndoTOXChange::Redo(SwUndoIter & rIter) { *pTOX = aNew; UpdateTOXBaseSection(); } void SwUndoTOXChange::Repeat(SwUndoIter & rIter) { Redo(rIter); } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.226); FILE MERGED 2005/09/05 13:41:22 rt 1.3.226.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SwUndoTOXChange.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:16:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <SwUndoTOXChange.hxx> #include <swundo.hxx> #include <doctxm.hxx> SwUndoTOXChange::SwUndoTOXChange(SwTOXBase * _pTOX, const SwTOXBase & rNew) : SwUndo(UNDO_TOXCHANGE), pTOX(_pTOX), aOld(*_pTOX), aNew(rNew) { } SwUndoTOXChange::~SwUndoTOXChange() { } void SwUndoTOXChange::UpdateTOXBaseSection() { if (pTOX->ISA(SwTOXBaseSection)) { SwTOXBaseSection * pTOXBase = static_cast<SwTOXBaseSection *>(pTOX); pTOXBase->Update(); pTOXBase->UpdatePageNum(); } } void SwUndoTOXChange::Undo(SwUndoIter & rIter) { *pTOX = aOld; UpdateTOXBaseSection(); } void SwUndoTOXChange::Redo(SwUndoIter & rIter) { *pTOX = aNew; UpdateTOXBaseSection(); } void SwUndoTOXChange::Repeat(SwUndoIter & rIter) { Redo(rIter); } <|endoftext|>
<commit_before>#include "World.hh" World::World() { int banki = 0; uint32_t *bankptr = (uint32_t *) (rom + BANK_PTR); uint32_t rel = bankptr[banki]; uint32_t next = bankptr[banki + 1]; while (next > ROM_OFFSET) { _banks.push_back(std::vector<Map>()); std::vector<Map> &maps = _banks.back(); for (int mapi = rel; mapi < next; mapi += 4) { maps.push_back(Map()); Map &map = maps.back(); uint32_t mapaddr = *((uint32_t *) gbaMem(mapi)); Header *header = (Header *) gbaMem(mapaddr); DataHeader *dheader = (DataHeader *) gbaMem(header->mapPtr); TilesetHeader *global = (TilesetHeader *) gbaMem(dheader->globalTileset); TilesetHeader *local = (TilesetHeader *) gbaMem(dheader->localTileset); Map::TileAttr *globPtr = (Map::TileAttr *) gbaMem(global->behaviorPtr); Map::TileAttr *localPtr = (Map::TileAttr *) gbaMem(local->behaviorPtr); uint16_t *d = (uint16_t *) gbaMem(dheader->data); Event *evtPtr = (Event *) gbaMem(header->evtPtr); map.width = dheader->width; map.height = dheader->height; map.nbPersons = evtPtr->nbPersons; map.nbWarps = evtPtr->nbWarps; map.nbScripts = evtPtr->nbScripts; map.nbSigns = evtPtr->nbSigns; map.persons = (PersonEvt *) gbaMem(evtPtr->personsPtr); map.warps = (WarpEvt *) gbaMem(evtPtr->warpsPtr); map.scripts = (ScriptEvt *) gbaMem(evtPtr->scriptsPtr); map.signs = (SignEvt *) gbaMem(evtPtr->signsPtr); map.nbConnects = ((uint32_t *) gbaMem(header->connectPtr))[0]; map.connects = (Connection *) gbaMem(((uint32_t *) gbaMem(header->connectPtr))[1]); map.data = new Map::Node*[map.height](); for (int y = 0; y < map.height; y++) { map.data[y] = new Map::Node[map.width](); for (int x = 0; x < map.width; x++) { uint16_t t = d[y * map.width + x] & ((1 << 10) - 1); map.data[y][x] = Map::Node(x, y); map.data[y][x].status = d[y * map.width + x] >> 10; map.data[y][x].tile = t; map.data[y][x].attr = t < 0x280 ? globPtr + t : localPtr + t - 0x280; } } } banki++; rel = next; next = bankptr[banki + 1]; } } World::~World() { } int World::Map::_getNextIndex(std::vector<Node*> *set) { int i = -1; uint32_t min; uint32_t count = 0; for (std::vector<Node*>::iterator it = set->begin(); it != set->end(); it++) { if (i == -1 || (*it)->f < min) { i = count; min = (*it)->f; } count++; } return (i); } std::vector<World::Map::Node*>* World::Map::_rebuildPath(std::vector<Node*>* set, Node *node) { if (node->from) _rebuildPath(set, node->from); set->push_back(node); return (set); } bool checkHills(int i, int j, uint16_t next_behavior, uint16_t curr_behavior) { // Jump down hill return ((j == 1 && next_behavior == 0x3b) || (j == 1 && curr_behavior == 0x3b) || // Jump right hill (i == 1 && next_behavior == 0x38) || (i == 1 && curr_behavior == 0x38) || // Jump left hill (i == -1 && next_behavior == 0x39) || (i == -1 && curr_behavior == 0x39)) } bool checkWalkableTiles(std::vector<uint8_t> walkableTiles, uint8_t status, uint16_t behavior) { // Check walkable tiles (grass/tile near escalator, for now) return (std::find(walkableTiles.begin(), walkableTiles.end(), data[y][x].status) != walkableTiles.end() && // Check that it's not an escalator data[y][x].attr->behavior != 0x6b && data[y][x].attr->behavior != 0x6a) } std::vector<World::Map::Node*>* World::Map::findPath(uint32_t xs, uint32_t ys, uint32_t xe, uint32_t ye) { std::vector<Node*> openset; std::vector<Node*> closedset; static const uint8_t arr[] = {0x0C, //Grass/Road 0x00, //Area around objects 0x10}; //Escalators std::vector<uint8_t> walkableTiles(arr, arr + sizeof(arr) / sizeof(arr[0])); openset.push_back(new Node(xs, ys)); openset.back()->setF(xe, ye); while (openset.size()) { int i = _getNextIndex(&openset); Node* curr = openset[i]; openset.erase(openset.begin() + i); if (curr->x == xe && curr->y == ye) return (_rebuildPath(new std::vector<Node*>, curr)); closedset.push_back(curr); for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { int x = curr->x + i; int y = curr->y + j; // Boundaries check if (x < 0 || x >= width || y < 0 || y >= height || (!i && !j) || (i && j)) continue; // Tile type check if (!(checkHills(i, j, data[y][x].attr->behavior, data[curr->y][curr->x].attr->behavior) || checkWalkableTiles(walkableTiles, data[y][x].status, data[y][x].attr->behavior) || // Block access to hill from a lower level data[y][x].attr->behavior == 0x32 || // Check if escalator is the final tile (!j && (data[y][x].attr->behavior == 0x6b || data[y][x].attr->behavior == 0x6a) && x == xe && y == ye))) continue; Node *neighbor = &(data[y][x]); std::vector<Node*>::iterator it = std::find(closedset.begin(), closedset.end(), neighbor); uint32_t g = curr->g + (!i || !j ? 10 : 14); if (it != closedset.end() && g >= neighbor->g) continue; if (it == closedset.end() || g < neighbor->g) { neighbor->from = curr; neighbor->setG(g); neighbor->setF(xe, ye); if (std::find(openset.begin(), openset.end(), neighbor) == openset.end()) openset.push_back(neighbor); } } } } return (NULL); } <commit_msg>fix: typos<commit_after>#include "World.hh" World::World() { int banki = 0; uint32_t *bankptr = (uint32_t *) (rom + BANK_PTR); uint32_t rel = bankptr[banki]; uint32_t next = bankptr[banki + 1]; while (next > ROM_OFFSET) { _banks.push_back(std::vector<Map>()); std::vector<Map> &maps = _banks.back(); for (int mapi = rel; mapi < next; mapi += 4) { maps.push_back(Map()); Map &map = maps.back(); uint32_t mapaddr = *((uint32_t *) gbaMem(mapi)); Header *header = (Header *) gbaMem(mapaddr); DataHeader *dheader = (DataHeader *) gbaMem(header->mapPtr); TilesetHeader *global = (TilesetHeader *) gbaMem(dheader->globalTileset); TilesetHeader *local = (TilesetHeader *) gbaMem(dheader->localTileset); Map::TileAttr *globPtr = (Map::TileAttr *) gbaMem(global->behaviorPtr); Map::TileAttr *localPtr = (Map::TileAttr *) gbaMem(local->behaviorPtr); uint16_t *d = (uint16_t *) gbaMem(dheader->data); Event *evtPtr = (Event *) gbaMem(header->evtPtr); map.width = dheader->width; map.height = dheader->height; map.nbPersons = evtPtr->nbPersons; map.nbWarps = evtPtr->nbWarps; map.nbScripts = evtPtr->nbScripts; map.nbSigns = evtPtr->nbSigns; map.persons = (PersonEvt *) gbaMem(evtPtr->personsPtr); map.warps = (WarpEvt *) gbaMem(evtPtr->warpsPtr); map.scripts = (ScriptEvt *) gbaMem(evtPtr->scriptsPtr); map.signs = (SignEvt *) gbaMem(evtPtr->signsPtr); map.nbConnects = ((uint32_t *) gbaMem(header->connectPtr))[0]; map.connects = (Connection *) gbaMem(((uint32_t *) gbaMem(header->connectPtr))[1]); map.data = new Map::Node*[map.height](); for (int y = 0; y < map.height; y++) { map.data[y] = new Map::Node[map.width](); for (int x = 0; x < map.width; x++) { uint16_t t = d[y * map.width + x] & ((1 << 10) - 1); map.data[y][x] = Map::Node(x, y); map.data[y][x].status = d[y * map.width + x] >> 10; map.data[y][x].tile = t; map.data[y][x].attr = t < 0x280 ? globPtr + t : localPtr + t - 0x280; } } } banki++; rel = next; next = bankptr[banki + 1]; } } World::~World() { } int World::Map::_getNextIndex(std::vector<Node*> *set) { int i = -1; uint32_t min; uint32_t count = 0; for (std::vector<Node*>::iterator it = set->begin(); it != set->end(); it++) { if (i == -1 || (*it)->f < min) { i = count; min = (*it)->f; } count++; } return (i); } std::vector<World::Map::Node*>* World::Map::_rebuildPath(std::vector<Node*>* set, Node *node) { if (node->from) _rebuildPath(set, node->from); set->push_back(node); return (set); } bool checkHills(int i, int j, uint16_t next_behavior, uint16_t curr_behavior) { // Jump down hill return ((j == 1 && next_behavior == 0x3b) || (j == 1 && curr_behavior == 0x3b) || // Jump right hill (i == 1 && next_behavior == 0x38) || (i == 1 && curr_behavior == 0x38) || // Jump left hill (i == -1 && next_behavior == 0x39) || (i == -1 && curr_behavior == 0x39)); } bool checkWalkableTiles(std::vector<uint8_t> walkableTiles, uint8_t status, uint16_t behavior) { // Check walkable tiles (grass/tile near escalator, for now) return (std::find(walkableTiles.begin(), walkableTiles.end(), status) != walkableTiles.end() && // Check that it's not an escalator behavior != 0x6b && behavior != 0x6a); } std::vector<World::Map::Node*>* World::Map::findPath(uint32_t xs, uint32_t ys, uint32_t xe, uint32_t ye) { std::vector<Node*> openset; std::vector<Node*> closedset; static const uint8_t arr[] = {0x0C, //Grass/Road 0x00, //Area around objects 0x10}; //Escalators std::vector<uint8_t> walkableTiles(arr, arr + sizeof(arr) / sizeof(arr[0])); openset.push_back(new Node(xs, ys)); openset.back()->setF(xe, ye); while (openset.size()) { int i = _getNextIndex(&openset); Node* curr = openset[i]; openset.erase(openset.begin() + i); if (curr->x == xe && curr->y == ye) return (_rebuildPath(new std::vector<Node*>, curr)); closedset.push_back(curr); for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { int x = curr->x + i; int y = curr->y + j; // Boundaries check if (x < 0 || x >= width || y < 0 || y >= height || (!i && !j) || (i && j)) continue; // Tile type check if (!(checkHills(i, j, data[y][x].attr->behavior, data[curr->y][curr->x].attr->behavior) || checkWalkableTiles(walkableTiles, data[y][x].status, data[y][x].attr->behavior) || // Block access to hill from a lower level data[y][x].attr->behavior == 0x32 || // Check if escalator is the final tile (!j && (data[y][x].attr->behavior == 0x6b || data[y][x].attr->behavior == 0x6a) && x == xe && y == ye))) continue; Node *neighbor = &(data[y][x]); std::vector<Node*>::iterator it = std::find(closedset.begin(), closedset.end(), neighbor); uint32_t g = curr->g + (!i || !j ? 10 : 14); if (it != closedset.end() && g >= neighbor->g) continue; if (it == closedset.end() || g < neighbor->g) { neighbor->from = curr; neighbor->setG(g); neighbor->setF(xe, ye); if (std::find(openset.begin(), openset.end(), neighbor) == openset.end()) openset.push_back(neighbor); } } } } return (NULL); } <|endoftext|>
<commit_before>/** * @file amici.cpp * @brief core routines for integration */ #include "amici/amici.h" #include "amici/steadystateproblem.h" #include "amici/backwardproblem.h" #include "amici/forwardproblem.h" #include "amici/misc.h" #include <cvodes/cvodes.h> //return codes #include <sundials/sundials_types.h> //realtype #include <cassert> #include <cstdarg> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <type_traits> // ensure definitions are in sync static_assert(amici::AMICI_SUCCESS == CV_SUCCESS, "AMICI_SUCCESS != CV_SUCCESS"); static_assert(amici::AMICI_DATA_RETURN == CV_TSTOP_RETURN, "AMICI_DATA_RETURN != CV_TSTOP_RETURN"); static_assert(amici::AMICI_ROOT_RETURN == CV_ROOT_RETURN, "AMICI_ROOT_RETURN != CV_ROOT_RETURN"); static_assert(amici::AMICI_ILL_INPUT == CV_ILL_INPUT, "AMICI_ILL_INPUT != CV_ILL_INPUT"); static_assert(amici::AMICI_NORMAL == CV_NORMAL, "AMICI_NORMAL != CV_NORMAL"); static_assert(amici::AMICI_ONE_STEP == CV_ONE_STEP, "AMICI_ONE_STEP != CV_ONE_STEP"); static_assert(std::is_same<amici::realtype, realtype>::value, "Definition of realtype does not match"); namespace amici { /** AMICI default application context, kept around for convenience for using * amici::runAmiciSimulation or instantiating Solver and Model without special * needs. */ AmiciApplication defaultContext = AmiciApplication(); std::unique_ptr<ReturnData> runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { return defaultContext.runAmiciSimulation(solver, edata, model, rethrow); } void printErrMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Error] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } void printWarnMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Warning] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } std::vector<std::unique_ptr<ReturnData>> runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, const bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { #if defined(_OPENMP) return defaultContext.runAmiciSimulations( solver, edatas, model, failfast, num_threads); #else return defaultContext.runAmiciSimulations(solver, edatas, model, failfast, 1); #endif } std::unique_ptr<ReturnData> AmiciApplication::runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { /* Applies condition-specific model settings and restores them when going * out of scope */ ConditionContext cc1(&model, edata, FixedParameterContext::simulation); std::unique_ptr<ReturnData> rdata = std::make_unique<ReturnData>(solver, model); if (model.nx_solver <= 0) { return rdata; } std::unique_ptr<SteadystateProblem> preeq {}; std::unique_ptr<ForwardProblem> fwd {}; std::unique_ptr<BackwardProblem> bwd {}; std::unique_ptr<SteadystateProblem> posteq {}; try { if (solver.getPreequilibration() || (edata && !edata->fixedParametersPreequilibration.empty())) { ConditionContext cc2( &model, edata, FixedParameterContext::preequilibration ); preeq = std::make_unique<SteadystateProblem>(solver, model); preeq->workSteadyStateProblem(&solver, &model, -1); } fwd = std::make_unique<ForwardProblem>(edata, &model, &solver, preeq.get()); fwd->workForwardProblem(); if (fwd->getCurrentTimeIteration() < model.nt()) { posteq = std::make_unique<SteadystateProblem>(solver, model); posteq->workSteadyStateProblem(&solver, &model, fwd->getCurrentTimeIteration()); } if (edata && solver.computingASA()) { fwd->getAdjointUpdates(model, *edata); if (posteq) { posteq->getAdjointUpdates(model, *edata); posteq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } bwd = std::make_unique<BackwardProblem>(*fwd, posteq.get()); bwd->workBackwardProblem(); if (preeq) { ConditionContext cc2(&model, edata, FixedParameterContext::preequilibration); preeq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } } rdata->status = AMICI_SUCCESS; } catch (amici::IntegrationFailure const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF("AMICI:simulation", "AMICI forward simulation failed at t = %f:\n%s\n", ex.time, ex.what()); } catch (amici::IntegrationFailureB const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF( "AMICI:simulation", "AMICI backward simulation failed when trying to solve until t = %f" " (see message above):\n%s\n", ex.time, ex.what()); } catch (amici::AmiException const& ex) { rdata->status = AMICI_ERROR; if (rethrow) throw; warningF("AMICI:simulation", "AMICI simulation failed:\n%s\nError occured in:\n%s", ex.what(), ex.getBacktrace()); } rdata->processSimulationObjects(preeq.get(), fwd.get(), bwd.get(), posteq.get(), model, solver, edata); return rdata; } std::vector<std::unique_ptr<ReturnData>> AmiciApplication::runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { std::vector<std::unique_ptr<ReturnData>> results(edatas.size()); // is set to true if one simulation fails and we should skip the rest. // shared across threads. bool skipThrough = false; #if defined(_OPENMP) #pragma omp parallel for num_threads(num_threads) #endif for (int i = 0; i < (int)edatas.size(); ++i) { auto mySolver = std::unique_ptr<Solver>(solver.clone()); auto myModel = std::unique_ptr<Model>(model.clone()); /* if we fail we need to write empty return datas for the python interface */ if (skipThrough) { ConditionContext conditionContext(myModel.get(), edatas[i]); results[i] = std::unique_ptr<ReturnData>(new ReturnData(solver, model)); } else { results[i] = runAmiciSimulation(*mySolver, edatas[i], *myModel); } skipThrough |= failfast && results[i]->status < 0; } return results; } void AmiciApplication::warningF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); warning(identifier, str); } void AmiciApplication::errorF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); error(identifier, str); } int AmiciApplication::checkFinite(gsl::span<const realtype> array, const char* fun) { for (int idx = 0; idx < (int)array.size(); idx++) { if (isNaN(array[idx])) { warningF("AMICI:NaN", "AMICI encountered a NaN value at index %i of %i in %s!", idx, (int)array.size(), fun); return AMICI_RECOVERABLE_ERROR; } if (isInf(array[idx])) { warningF("AMICI:Inf", "AMICI encountered an Inf value at index %i of %i in %s!", idx, (int)array.size(), fun); return AMICI_RECOVERABLE_ERROR; } } return AMICI_SUCCESS; } } // namespace amici <commit_msg>Fix warnings: account for zero indexing in nan/inf error (#1197)<commit_after>/** * @file amici.cpp * @brief core routines for integration */ #include "amici/amici.h" #include "amici/steadystateproblem.h" #include "amici/backwardproblem.h" #include "amici/forwardproblem.h" #include "amici/misc.h" #include <cvodes/cvodes.h> //return codes #include <sundials/sundials_types.h> //realtype #include <cassert> #include <cstdarg> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <type_traits> // ensure definitions are in sync static_assert(amici::AMICI_SUCCESS == CV_SUCCESS, "AMICI_SUCCESS != CV_SUCCESS"); static_assert(amici::AMICI_DATA_RETURN == CV_TSTOP_RETURN, "AMICI_DATA_RETURN != CV_TSTOP_RETURN"); static_assert(amici::AMICI_ROOT_RETURN == CV_ROOT_RETURN, "AMICI_ROOT_RETURN != CV_ROOT_RETURN"); static_assert(amici::AMICI_ILL_INPUT == CV_ILL_INPUT, "AMICI_ILL_INPUT != CV_ILL_INPUT"); static_assert(amici::AMICI_NORMAL == CV_NORMAL, "AMICI_NORMAL != CV_NORMAL"); static_assert(amici::AMICI_ONE_STEP == CV_ONE_STEP, "AMICI_ONE_STEP != CV_ONE_STEP"); static_assert(std::is_same<amici::realtype, realtype>::value, "Definition of realtype does not match"); namespace amici { /** AMICI default application context, kept around for convenience for using * amici::runAmiciSimulation or instantiating Solver and Model without special * needs. */ AmiciApplication defaultContext = AmiciApplication(); std::unique_ptr<ReturnData> runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { return defaultContext.runAmiciSimulation(solver, edata, model, rethrow); } void printErrMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Error] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } void printWarnMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Warning] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } std::vector<std::unique_ptr<ReturnData>> runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, const bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { #if defined(_OPENMP) return defaultContext.runAmiciSimulations( solver, edatas, model, failfast, num_threads); #else return defaultContext.runAmiciSimulations(solver, edatas, model, failfast, 1); #endif } std::unique_ptr<ReturnData> AmiciApplication::runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { /* Applies condition-specific model settings and restores them when going * out of scope */ ConditionContext cc1(&model, edata, FixedParameterContext::simulation); std::unique_ptr<ReturnData> rdata = std::make_unique<ReturnData>(solver, model); if (model.nx_solver <= 0) { return rdata; } std::unique_ptr<SteadystateProblem> preeq {}; std::unique_ptr<ForwardProblem> fwd {}; std::unique_ptr<BackwardProblem> bwd {}; std::unique_ptr<SteadystateProblem> posteq {}; try { if (solver.getPreequilibration() || (edata && !edata->fixedParametersPreequilibration.empty())) { ConditionContext cc2( &model, edata, FixedParameterContext::preequilibration ); preeq = std::make_unique<SteadystateProblem>(solver, model); preeq->workSteadyStateProblem(&solver, &model, -1); } fwd = std::make_unique<ForwardProblem>(edata, &model, &solver, preeq.get()); fwd->workForwardProblem(); if (fwd->getCurrentTimeIteration() < model.nt()) { posteq = std::make_unique<SteadystateProblem>(solver, model); posteq->workSteadyStateProblem(&solver, &model, fwd->getCurrentTimeIteration()); } if (edata && solver.computingASA()) { fwd->getAdjointUpdates(model, *edata); if (posteq) { posteq->getAdjointUpdates(model, *edata); posteq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } bwd = std::make_unique<BackwardProblem>(*fwd, posteq.get()); bwd->workBackwardProblem(); if (preeq) { ConditionContext cc2(&model, edata, FixedParameterContext::preequilibration); preeq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } } rdata->status = AMICI_SUCCESS; } catch (amici::IntegrationFailure const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF("AMICI:simulation", "AMICI forward simulation failed at t = %f:\n%s\n", ex.time, ex.what()); } catch (amici::IntegrationFailureB const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF( "AMICI:simulation", "AMICI backward simulation failed when trying to solve until t = %f" " (see message above):\n%s\n", ex.time, ex.what()); } catch (amici::AmiException const& ex) { rdata->status = AMICI_ERROR; if (rethrow) throw; warningF("AMICI:simulation", "AMICI simulation failed:\n%s\nError occured in:\n%s", ex.what(), ex.getBacktrace()); } rdata->processSimulationObjects(preeq.get(), fwd.get(), bwd.get(), posteq.get(), model, solver, edata); return rdata; } std::vector<std::unique_ptr<ReturnData>> AmiciApplication::runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { std::vector<std::unique_ptr<ReturnData>> results(edatas.size()); // is set to true if one simulation fails and we should skip the rest. // shared across threads. bool skipThrough = false; #if defined(_OPENMP) #pragma omp parallel for num_threads(num_threads) #endif for (int i = 0; i < (int)edatas.size(); ++i) { auto mySolver = std::unique_ptr<Solver>(solver.clone()); auto myModel = std::unique_ptr<Model>(model.clone()); /* if we fail we need to write empty return datas for the python interface */ if (skipThrough) { ConditionContext conditionContext(myModel.get(), edatas[i]); results[i] = std::unique_ptr<ReturnData>(new ReturnData(solver, model)); } else { results[i] = runAmiciSimulation(*mySolver, edatas[i], *myModel); } skipThrough |= failfast && results[i]->status < 0; } return results; } void AmiciApplication::warningF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); warning(identifier, str); } void AmiciApplication::errorF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); error(identifier, str); } int AmiciApplication::checkFinite(gsl::span<const realtype> array, const char* fun) { for (int idx = 0; idx < (int)array.size(); idx++) { if (isNaN(array[idx])) { warningF("AMICI:NaN", "AMICI encountered a NaN value at index %i/%i in %s!", idx, (int)array.size()-1, fun); return AMICI_RECOVERABLE_ERROR; } if (isInf(array[idx])) { warningF("AMICI:Inf", "AMICI encountered an Inf value at index %i/%i in %s!", idx, (int)array.size()-1, fun); return AMICI_RECOVERABLE_ERROR; } } return AMICI_SUCCESS; } } // namespace amici <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_ #define _SNARKFRONT_DSL_UTILITY_HPP_ #include <array> #include <cassert> #include <cstdint> #include <istream> #include <ostream> #include <string> #include <vector> #include <snarklib/Util.hpp> #include <cryptl/BitwiseLUT.hpp> #include <cryptl/ASCII_Hex.hpp> #include <snarkfront/Alg.hpp> #include <snarkfront/AST.hpp> #include <snarkfront/BitwiseAST.hpp> #include <snarkfront/DSL_base.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // elliptic curve pairing // // check if string name is: BN128, Edwards bool validPairingName(const std::string& name); // returns true if "BN128" bool pairingBN128(const std::string& name); // returns true if "Edwards" bool pairingEdwards(const std::string& name); //////////////////////////////////////////////////////////////////////////////// // SHA-2 // // check if: "1", "224", "256", "384", "512", "512_224", "512_256" bool validSHA2Name(const std::string& shaBits); // check if: 1, 224, 256, 384, 512 bool validSHA2Name(const std::size_t shaBits); // returns true if "SHA256" bool nameSHA256(const std::string& shaBits); // returns true if "SHA512" bool nameSHA512(const std::string& shaBits); //////////////////////////////////////////////////////////////////////////////// // AES // // check if: 128, 192, 256 bool validAESName(const std::size_t aesBits); //////////////////////////////////////////////////////////////////////////////// // powers of 2 // template <typename ALG> std::size_t sizeBits(const AST_Const<ALG>&) { typename AST_Const<ALG>::ValueType dummy; return sizeBits(dummy); } template <typename ALG> std::size_t sizeBits(const AST_Var<ALG>&) { typename AST_Var<ALG>::ValueType dummy; return sizeBits(dummy); } //////////////////////////////////////////////////////////////////////////////// // convert between hexadecimal ASCII and binary // #define DEFN_ASCII_HEX_ARRAY(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::array<uint ## BITS ## _x<FR>, N>& a, \ const bool space = false) \ { \ std::array<uint ## BITS ## _t, N> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return cryptl::asciiHex(tmp, space); \ } DEFN_ASCII_HEX_ARRAY(8) DEFN_ASCII_HEX_ARRAY(32) DEFN_ASCII_HEX_ARRAY(64) #undef DEFN_ASCII_HEX_ARRAY #define DEFN_ASCII_HEX_VECTOR(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::vector<uint ## BITS ## _x<FR>>& a, \ const bool space = false) \ { \ std::vector<uint ## BITS ## _t> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return cryptl::asciiHex(tmp, space); \ } DEFN_ASCII_HEX_VECTOR(8) DEFN_ASCII_HEX_VECTOR(32) DEFN_ASCII_HEX_VECTOR(64) #undef DEFN_ASCII_HEX_VECTOR //////////////////////////////////////////////////////////////////////////////// // serialize hash digests and preimages // #define DEFN_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::array<UINT, N>& a) \ { \ const char *ptr = reinterpret_cast<const char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ os.put(ptr[i * sizeof(UINT) + j]); \ } \ } \ } else { \ os.write(ptr, sizeof(a)); \ } \ return os; \ } DEFN_ARRAY_OUT(std::uint8_t) DEFN_ARRAY_OUT(std::uint32_t) DEFN_ARRAY_OUT(std::uint64_t) #undef DEFN_ARRAY_OUT #define DEFN_VECTOR_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::vector<std::array<UINT, N>>& a) \ { \ os << a.size() << ' '; \ for (const auto& r : a) \ os << r; \ return os; \ } DEFN_VECTOR_ARRAY_OUT(std::uint8_t) DEFN_VECTOR_ARRAY_OUT(std::uint32_t) DEFN_VECTOR_ARRAY_OUT(std::uint64_t) #undef DEFN_VECTOR_ARRAY_OUT #define DEFN_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::array<UINT, N>& a) \ { \ char *ptr = reinterpret_cast<char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ if (! is.get(ptr[i * sizeof(UINT) + j])) \ return is; \ } \ } \ } else { \ is.read(ptr, sizeof(a)); \ } \ return is; \ } DEFN_ARRAY_IN(std::uint8_t) DEFN_ARRAY_IN(std::uint32_t) DEFN_ARRAY_IN(std::uint64_t) #undef DEFN_ARRAY_IN #define DEFN_VECTOR_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::vector<std::array<UINT, N>>& a) \ { \ std::size_t len = -1; \ if (!(is >> len) || (-1 == len)) return is; \ char c; \ if (!is.get(c) || (' ' != c)) return is; \ a.resize(len); \ for (auto& r : a) \ if (!(is >> r)) break; \ return is; \ } DEFN_VECTOR_ARRAY_IN(std::uint8_t) DEFN_VECTOR_ARRAY_IN(std::uint32_t) DEFN_VECTOR_ARRAY_IN(std::uint64_t) #undef DEFN_VECTOR_ARRAY_IN //////////////////////////////////////////////////////////////////////////////// // lookup table for unsigned integer types // template <typename FR> using array_uint8 = cryptl::BitwiseLUT< AST_Node<Alg_uint8<FR>>, AST_Op<Alg_uint8<FR>>, std::uint8_t, BitwiseAST<Alg_uint8<FR>>>; template <typename FR> using array_uint32 = cryptl::BitwiseLUT< AST_Node<Alg_uint32<FR>>, AST_Op<Alg_uint32<FR>>, std::uint32_t, BitwiseAST<Alg_uint32<FR>>>; template <typename FR> using array_uint64 = cryptl::BitwiseLUT< AST_Node<Alg_uint64<FR>>, AST_Op<Alg_uint64<FR>>, std::uint64_t, BitwiseAST<Alg_uint64<FR>>>; //////////////////////////////////////////////////////////////////////////////// // finite field exponentiation // template <typename FR> AST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base, const AST_Node<Alg_bool<FR>>& exponent) { // base * exponent + ~exponent = exponent ? base : one return AST_Op<Alg_Field<FR>>( Alg_Field<FR>::OpType::ADD, new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, _xword(exponent, base)), _xword(~exponent, base)); } template <typename FR> AST_Op<Alg_Field<FR>>* _pow(const AST_Node<Alg_Field<FR>>& base, const AST_Node<Alg_bool<FR>>& exponent) { // base * exponent + ~exponent = exponent ? base : one return new AST_Op<Alg_Field<FR>>( Alg_Field<FR>::OpType::ADD, new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, _xword(exponent, base)), _xword(~exponent, base)); } template <typename FR> AST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base, const std::vector<AST_Node<Alg_bool<FR>>>& exponent) { const auto expBits = exponent.size(); #ifdef USE_ASSERT // no exponent bits does not make sense assert(expBits > 0); #endif if (1 == expBits) { return pow(base, exponent[0]); } else { auto sum = _pow(base, exponent[0]); // pow(base, 2) auto powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, base); for (std::size_t i = 1; i < expBits - 1; ++i) { sum = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD, sum, _pow(powbase, exponent[i])); // pow(base, pow(2, i + 1)) powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, powbase, powbase); } return AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD, sum, _pow(powbase, exponent[expBits - 1])); } } } // namespace snarkfront #endif <commit_msg>remove BitwiseLUT<commit_after>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_ #define _SNARKFRONT_DSL_UTILITY_HPP_ #include <array> #include <cassert> #include <cstdint> #include <istream> #include <ostream> #include <string> #include <vector> #include <snarklib/Util.hpp> #include <cryptl/ASCII_Hex.hpp> #include <snarkfront/Alg.hpp> #include <snarkfront/AST.hpp> #include <snarkfront/BitwiseAST.hpp> #include <snarkfront/DSL_base.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // elliptic curve pairing // // check if string name is: BN128, Edwards bool validPairingName(const std::string& name); // returns true if "BN128" bool pairingBN128(const std::string& name); // returns true if "Edwards" bool pairingEdwards(const std::string& name); //////////////////////////////////////////////////////////////////////////////// // SHA-2 // // check if: "1", "224", "256", "384", "512", "512_224", "512_256" bool validSHA2Name(const std::string& shaBits); // check if: 1, 224, 256, 384, 512 bool validSHA2Name(const std::size_t shaBits); // returns true if "SHA256" bool nameSHA256(const std::string& shaBits); // returns true if "SHA512" bool nameSHA512(const std::string& shaBits); //////////////////////////////////////////////////////////////////////////////// // AES // // check if: 128, 192, 256 bool validAESName(const std::size_t aesBits); //////////////////////////////////////////////////////////////////////////////// // powers of 2 // template <typename ALG> std::size_t sizeBits(const AST_Const<ALG>&) { typename AST_Const<ALG>::ValueType dummy; return sizeBits(dummy); } template <typename ALG> std::size_t sizeBits(const AST_Var<ALG>&) { typename AST_Var<ALG>::ValueType dummy; return sizeBits(dummy); } //////////////////////////////////////////////////////////////////////////////// // convert between hexadecimal ASCII and binary // #define DEFN_ASCII_HEX_ARRAY(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::array<uint ## BITS ## _x<FR>, N>& a, \ const bool space = false) \ { \ std::array<uint ## BITS ## _t, N> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return cryptl::asciiHex(tmp, space); \ } DEFN_ASCII_HEX_ARRAY(8) DEFN_ASCII_HEX_ARRAY(32) DEFN_ASCII_HEX_ARRAY(64) #undef DEFN_ASCII_HEX_ARRAY #define DEFN_ASCII_HEX_VECTOR(BITS) \ template <typename FR, std::size_t N> \ std::string asciiHex( \ const std::vector<uint ## BITS ## _x<FR>>& a, \ const bool space = false) \ { \ std::vector<uint ## BITS ## _t> tmp; \ for (std::size_t i = 0; i < N; ++i) \ tmp[i] = a[i]->value(); \ return cryptl::asciiHex(tmp, space); \ } DEFN_ASCII_HEX_VECTOR(8) DEFN_ASCII_HEX_VECTOR(32) DEFN_ASCII_HEX_VECTOR(64) #undef DEFN_ASCII_HEX_VECTOR //////////////////////////////////////////////////////////////////////////////// // serialize hash digests and preimages // #define DEFN_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::array<UINT, N>& a) \ { \ const char *ptr = reinterpret_cast<const char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ os.put(ptr[i * sizeof(UINT) + j]); \ } \ } \ } else { \ os.write(ptr, sizeof(a)); \ } \ return os; \ } DEFN_ARRAY_OUT(std::uint8_t) DEFN_ARRAY_OUT(std::uint32_t) DEFN_ARRAY_OUT(std::uint64_t) #undef DEFN_ARRAY_OUT #define DEFN_VECTOR_ARRAY_OUT(UINT) \ template <std::size_t N> \ std::ostream& operator<< ( \ std::ostream& os, \ const std::vector<std::array<UINT, N>>& a) \ { \ os << a.size() << ' '; \ for (const auto& r : a) \ os << r; \ return os; \ } DEFN_VECTOR_ARRAY_OUT(std::uint8_t) DEFN_VECTOR_ARRAY_OUT(std::uint32_t) DEFN_VECTOR_ARRAY_OUT(std::uint64_t) #undef DEFN_VECTOR_ARRAY_OUT #define DEFN_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::array<UINT, N>& a) \ { \ char *ptr = reinterpret_cast<char*>(a.data()); \ if (snarklib::is_big_endian<int>()) { \ for (std::size_t i = 0; i < N; ++i) { \ for (int j = sizeof(UINT) - 1; j >= 0; --j) { \ if (! is.get(ptr[i * sizeof(UINT) + j])) \ return is; \ } \ } \ } else { \ is.read(ptr, sizeof(a)); \ } \ return is; \ } DEFN_ARRAY_IN(std::uint8_t) DEFN_ARRAY_IN(std::uint32_t) DEFN_ARRAY_IN(std::uint64_t) #undef DEFN_ARRAY_IN #define DEFN_VECTOR_ARRAY_IN(UINT) \ template <std::size_t N> \ std::istream& operator>> ( \ std::istream& is, \ std::vector<std::array<UINT, N>>& a) \ { \ std::size_t len = -1; \ if (!(is >> len) || (-1 == len)) return is; \ char c; \ if (!is.get(c) || (' ' != c)) return is; \ a.resize(len); \ for (auto& r : a) \ if (!(is >> r)) break; \ return is; \ } DEFN_VECTOR_ARRAY_IN(std::uint8_t) DEFN_VECTOR_ARRAY_IN(std::uint32_t) DEFN_VECTOR_ARRAY_IN(std::uint64_t) #undef DEFN_VECTOR_ARRAY_IN //////////////////////////////////////////////////////////////////////////////// // finite field exponentiation // template <typename FR> AST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base, const AST_Node<Alg_bool<FR>>& exponent) { // base * exponent + ~exponent = exponent ? base : one return AST_Op<Alg_Field<FR>>( Alg_Field<FR>::OpType::ADD, new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, _xword(exponent, base)), _xword(~exponent, base)); } template <typename FR> AST_Op<Alg_Field<FR>>* _pow(const AST_Node<Alg_Field<FR>>& base, const AST_Node<Alg_bool<FR>>& exponent) { // base * exponent + ~exponent = exponent ? base : one return new AST_Op<Alg_Field<FR>>( Alg_Field<FR>::OpType::ADD, new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, _xword(exponent, base)), _xword(~exponent, base)); } template <typename FR> AST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base, const std::vector<AST_Node<Alg_bool<FR>>>& exponent) { const auto expBits = exponent.size(); #ifdef USE_ASSERT // no exponent bits does not make sense assert(expBits > 0); #endif if (1 == expBits) { return pow(base, exponent[0]); } else { auto sum = _pow(base, exponent[0]); // pow(base, 2) auto powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, base, base); for (std::size_t i = 1; i < expBits - 1; ++i) { sum = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD, sum, _pow(powbase, exponent[i])); // pow(base, pow(2, i + 1)) powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL, powbase, powbase); } return AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD, sum, _pow(powbase, exponent[expBits - 1])); } } } // namespace snarkfront #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/FailableMemoryAllocator.h" #include "CppUTest/TestTestingFixture.h" TEST_GROUP(FailableMemoryAllocator) { FailableMallocAllocator *failableMallocAllocator; TestTestingFixture *fixture; void setup() { failableMallocAllocator = new FailableMallocAllocator("Failable malloc"); fixture = new TestTestingFixture; setCurrentMallocAllocator(failableMallocAllocator); } void teardown() { setCurrentMallocAllocatorToDefault(); delete failableMallocAllocator; delete fixture; } }; TEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail) { int *memory = (int*)malloc(sizeof(int)); *memory = 1; CHECK(memory != NULL); free(memory); // Try commenting this out } TEST(FailableMemoryAllocator, FailFirstMalloc) { failableMallocAllocator->failMallocNumber(1); LONGS_EQUAL(NULL, (int*)malloc(sizeof(int))); } TEST(FailableMemoryAllocator, FailSecondAndFourthMalloc) { failableMallocAllocator->failMallocNumber(2); failableMallocAllocator->failMallocNumber(4); int *memory1 = (int*)malloc(sizeof(int)); int *memory2 = (int*)malloc(sizeof(int)); int *memory3 = (int*)malloc(sizeof(int)); int *memory4 = (int*)malloc(sizeof(int)); CHECK(NULL != memory1); LONGS_EQUAL(NULL, memory2); CHECK(NULL != memory3); LONGS_EQUAL(NULL, memory4); free(memory1); free(memory3); } static void setUpTooManyFailedMallocs() { FailableMallocAllocator allocator; for (int i = 0; i <= allocator.MAX_NUMBER_OF_FAILED_ALLOCS; i++) allocator.failMallocNumber(i + 1); } TEST(FailableMemoryAllocator, SettingUpTooManyFailedAllocsWillFail) { fixture->setTestFunction(setUpTooManyFailedMallocs); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); fixture->assertPrintContains("Maximum number of failed memory allocations exceeded"); } <commit_msg>Memory leak detector crashes with my memory allocator<commit_after>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/FailableMemoryAllocator.h" #include "CppUTest/TestTestingFixture.h" TEST_GROUP(FailableMemoryAllocator) { FailableMallocAllocator *failableMallocAllocator; TestTestingFixture *fixture; void setup() { failableMallocAllocator = new FailableMallocAllocator("Failable malloc"); fixture = new TestTestingFixture; setCurrentMallocAllocator(failableMallocAllocator); } void teardown() { setCurrentMallocAllocatorToDefault(); delete failableMallocAllocator; delete fixture; } }; TEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail) { int *memory = (int*)malloc(sizeof(int)); *memory = 1; CHECK(memory != NULL); // free(memory); } TEST(FailableMemoryAllocator, FailFirstMalloc) { failableMallocAllocator->failMallocNumber(1); LONGS_EQUAL(NULL, (int*)malloc(sizeof(int))); } TEST(FailableMemoryAllocator, FailSecondAndFourthMalloc) { failableMallocAllocator->failMallocNumber(2); failableMallocAllocator->failMallocNumber(4); int *memory1 = (int*)malloc(sizeof(int)); int *memory2 = (int*)malloc(sizeof(int)); int *memory3 = (int*)malloc(sizeof(int)); int *memory4 = (int*)malloc(sizeof(int)); CHECK(NULL != memory1); LONGS_EQUAL(NULL, memory2); CHECK(NULL != memory3); LONGS_EQUAL(NULL, memory4); free(memory1); free(memory3); } static void setUpTooManyFailedMallocs() { FailableMallocAllocator allocator; for (int i = 0; i <= allocator.MAX_NUMBER_OF_FAILED_ALLOCS; i++) allocator.failMallocNumber(i + 1); } TEST(FailableMemoryAllocator, SettingUpTooManyFailedAllocsWillFail) { fixture->setTestFunction(setUpTooManyFailedMallocs); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); fixture->assertPrintContains("Maximum number of failed memory allocations exceeded"); } <|endoftext|>