hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
d01103efef5d7119a48afd53996f7d0d68957148
1,511
hpp
C++
source/hls/_FIRMWARE/shared_dram.hpp
somdipdey/Traffic_Analysis_Images__Dataset
9620c68ca71cda951a821aeaf89fcde6a7bb81fb
[ "MIT" ]
1
2019-02-22T12:23:31.000Z
2019-02-22T12:23:31.000Z
source/hls/_FIRMWARE/shared_dram.hpp
maxpark/MAT-CNN-SOPC
9620c68ca71cda951a821aeaf89fcde6a7bb81fb
[ "MIT" ]
1
2018-06-26T22:17:03.000Z
2018-06-26T22:17:34.000Z
source/hls/_FIRMWARE/shared_dram.hpp
somdipdey/MAT-CNN-FPGA_Traffic_Analysis_Using_CNNs_On_FPGA
9620c68ca71cda951a821aeaf89fcde6a7bb81fb
[ "MIT" ]
1
2018-06-29T09:59:33.000Z
2018-06-29T09:59:33.000Z
#ifndef SHARED_DRAM_H_9B5B43B5 #define SHARED_DRAM_H_9B5B43B5 #include <sys/mman.h> #include <fcntl.h> #include <err.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stddef.h> #include <stdint.h> #include "xfpga_hw.hpp" // Register addresses typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; // Location + Size of SHARED DRAM segment: // - from Vivado Block Designer (Address Editor): // AXI M memory bus starts at 0x00000000 – 0xFFFFFFFF, SIZE: 4GB // - from information by Simon Wright: // top 128MB of 1GB system memory are not OS-managed // - from "free -m" on Zynq: // total mem 882MB -> 118MB not OS-managed // -> place SHARED_DRAM at 896MB (-> max. activations ~100MB) // -> 896MB = 896*1024*1024 = 0x3800'0000 bytes // -> 96MB = 96*1024*1024 = 0x600'0000 bytes const off_t SHARED_DRAM_BASE_ADDR = 0x38000000; const size_t SHARED_DRAM_MEM_SIZE = 0x06000000; extern int SHARED_DRAM_FD; extern volatile u32* SHARED_DRAM_PTR; // External Interface bool SHARED_DRAM_open(); bool SHARED_DRAM_close(); volatile u32* SHARED_DRAM_virtual(); volatile u32* SHARED_DRAM_physical(); // Internal Functions volatile u32* map_SHARED_DRAM(off_t base_addr); void release_SHARED_DRAM(volatile u32* axilite); // unused: // 32-bit word read + write (other sizes not supported!) /* void shared_DRAM_write(u32 byte_addr, u32 value); u32 shared_DRAM_read(u32 byte_addr); */ #endif /* end of include guard: SHARED_DRAM_H_9B5B43B5 */
26.982143
68
0.733951
somdipdey
d011cc3e7e0512dd095e3bef663f0c6469948965
19,018
cpp
C++
moai/src/moaicore/MOAICameraFitter2D.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAICameraFitter2D.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAICameraFitter2D.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAICameraAnchor2D.h> #include <moaicore/MOAICameraFitter2D.h> #include <moaicore/MOAIGfxDevice.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAITransform.h> #include <moaicore/MOAIViewport.h> //----------------------------------------------------------------// /** @name clearAnchors @text Remove all camera anchors from the fitter. @in MOAICameraFitter2D self @out nil */ int MOAICameraFitter2D::_clearAnchors ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->Clear (); return 0; } //----------------------------------------------------------------// /** @name clearFitMode @text Clears bits in the fitting mask. @in MOAICameraFitter2D self @opt number mask Default value is FITTING_MODE_MASK @out nil */ int MOAICameraFitter2D::_clearFitMode( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) u32 mask = state.GetValue < u32 >( 2, FITTING_MODE_MASK ); self->mFittingMode &= ~mask; return 0; } //----------------------------------------------------------------// /** @name getFitDistance @text Returns the distance between the camera's current x, y, scale and the target x, y, scale. As the camera approaches its target, the distance approaches 0. Check the value returned by this function against a small epsilon value. @in MOAICameraFitter2D self @out number distance */ int MOAICameraFitter2D::_getFitDistance ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) float distance = self->GetFitDistance (); lua_pushnumber ( state, distance ); return 1; } //----------------------------------------------------------------// /** @name getFitLoc @text Get the fitter location. @in MOAICameraFitter2D self @out number x @out number y */ int MOAICameraFitter2D::_getFitLoc ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mFitLoc.mX ); lua_pushnumber ( state, self->mFitLoc.mY ); return 2; } //----------------------------------------------------------------// /** @name getFitMode @text Gets bits in the fitting mask. @in MOAICameraFitter2D self @out number mask */ int MOAICameraFitter2D::_getFitMode ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) state.Push ( self->mFittingMode ); return 1; } //----------------------------------------------------------------// /** @name getFitScale @text Returns the fit scale @in MOAICameraFitter2D self @out number scale */ int MOAICameraFitter2D::_getFitScale ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mFitScale ); return 1; } //----------------------------------------------------------------// /** @name getTargetLoc @text Get the target location. @in MOAICameraFitter2D self @out number x @out number y */ int MOAICameraFitter2D::_getTargetLoc ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mTargetLoc.mX ); lua_pushnumber ( state, self->mTargetLoc.mY ); return 2; } //----------------------------------------------------------------// /** @name getTargetScale @text Returns the target scale @in MOAICameraFitter2D self @out number scale */ int MOAICameraFitter2D::_getTargetScale ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mTargetScale ); return 1; } //----------------------------------------------------------------// /** @name insertAnchor @text Add an anchor to the fitter. @in MOAICameraFitter2D self @in MOAICameraAnchor2D anchor @out nil */ int MOAICameraFitter2D::_insertAnchor ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "UU" ) MOAICameraAnchor2D* anchor = state.GetLuaObject < MOAICameraAnchor2D >( 2, true ); if ( anchor ) { self->AddAnchor ( *anchor ); } return 0; } //----------------------------------------------------------------// /** @name removeAnchor @text Remove an anchor from the fitter. @in MOAICameraFitter2D self @in MOAICameraAnchor2D anchor @out nil */ int MOAICameraFitter2D::_removeAnchor ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "UU" ) MOAICameraAnchor2D* anchor = state.GetLuaObject < MOAICameraAnchor2D >( 2, true ); if ( anchor ) { self->RemoveAnchor ( *anchor ); } return 0; } //----------------------------------------------------------------// /** @name setBounds @text Sets or clears the world bounds of the fitter. The camera will not move outside of the fitter's bounds. @overload @in MOAICameraFitter2D self @in number xMin @in number yMin @in number xMax @in number yMax @out nil @overload @in MOAICameraFitter2D self @out nil */ int MOAICameraFitter2D::_setBounds ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) if ( state.CheckParams ( 2, "NNNN" )) { float x0 = state.GetValue < float >( 2, 0.0f ); float y0 = state.GetValue < float >( 3, 0.0f ); float x1 = state.GetValue < float >( 4, 0.0f ); float y1 = state.GetValue < float >( 5, 0.0f ); self->mBounds.Init ( x0, y0, x1, y1 ); self->mFittingMode |= FITTING_MODE_APPLY_BOUNDS; } else { self->mFittingMode &= ~FITTING_MODE_APPLY_BOUNDS; } return 0; } //----------------------------------------------------------------// /** @name setCamera @text Set a MOAITransform for the fitter to use as a camera. The fitter will dynamically change the location and scale of the camera to keep all of the anchors on the screen. @in MOAICameraFitter2D self @opt MOAITransform camera Default value is nil. @out nil */ int MOAICameraFitter2D::_setCamera ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mCamera.Set ( *self, state.GetLuaObject < MOAITransform >( 2, true )); return 0; } //----------------------------------------------------------------// /** @name setDamper @text Set's the fitter's damper coefficient. This is a scalar applied to the difference between the camera transform's location and the fitter's target location every frame. The smaller the coefficient, the tighter the fit will be. A value of '0' will not dampen at all; a value of '1' will never move the camera. @in MOAICameraFitter2D self @opt number damper Default value is 0. @out nil */ int MOAICameraFitter2D::_setDamper ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mDamper = state.GetValue < float >( 2, 0.0f ); return 0; } //----------------------------------------------------------------// /** @name setFitLoc @text Set the fitter's location. @in MOAICameraFitter2D self @opt number x Default value is 0. @opt number y Default value is 0. @opt boolean snap Default value is false. @out nil */ int MOAICameraFitter2D::_setFitLoc ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mFitLoc.mX = state.GetValue < float >( 2, 0.0f ); self->mFitLoc.mY = state.GetValue < float >( 3, 0.0f ); self->mFittingMode &= ~FITTING_MODE_APPLY_ANCHORS; self->UpdateTarget (); bool snap = state.GetValue < bool >( 4, false ); if ( snap && self->mCamera ) { self->SnapToTargetLoc ( *self->mCamera ); } return 0; } //----------------------------------------------------------------// /** @name setFitMode @text Sets bits in the fitting mask. @in MOAICameraFitter2D self @opt number mask Default value is FITTING_MODE_DEFAULT @out nil */ int MOAICameraFitter2D::_setFitMode ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mFittingMode |= state.GetValue < u32 >( 2, FITTING_MODE_DEFAULT ); return 0; } //----------------------------------------------------------------// /** @name setFitScale @text Set the fitter's scale. @in MOAICameraFitter2D self @opt number scale Default value is 1. @opt boolean snap Default value is false. @out nil */ int MOAICameraFitter2D::_setFitScale ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mFitScale = state.GetValue < float >( 2, 1.0f ); self->mFittingMode &= ~FITTING_MODE_APPLY_ANCHORS; self->UpdateTarget (); bool snap = state.GetValue < bool >( 3, false ); if ( snap && self->mCamera ) { self->SnapToTargetScale ( *self->mCamera ); } return 0; } //----------------------------------------------------------------// /** @name setMin @text Set the minimum number of world units to be displayed by the camera along either axis. @in MOAICameraFitter2D self @opt number min Default value is 0. @out nil */ int MOAICameraFitter2D::_setMin ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mMin = state.GetValue < float >( 2, 0.0f ); return 0; } //----------------------------------------------------------------// /** @name setViewport @text Set the viewport to be used for fitting. @in MOAICameraFitter2D self @opt MOAIViewport viewport Default value is nil. @out nil */ int MOAICameraFitter2D::_setViewport ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mViewport.Set ( *self, state.GetLuaObject < MOAIViewport >( 2, true )); return 0; } //----------------------------------------------------------------// /** @name snapToTarget @text Snap the camera to the target fitting. @overload Snap the fitter's camera transform to the target. @in MOAICameraFitter2D self @out nil @overload Snap a passed in transform to the target. @in MOAICameraFitter2D self @in MOAITransform @out nil */ int MOAICameraFitter2D::_snapToTarget ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) MOAITransform* camera = state.GetLuaObject < MOAITransform >( 2, true ); if ( camera ) { self->SnapToTargetLoc ( *camera ); self->SnapToTargetScale ( *camera ); } else { if ( self->mCamera ) { self->SnapToTargetLoc ( *self->mCamera ); self->SnapToTargetScale ( *self->mCamera ); } } return 0; } //================================================================// // MOAICameraFitter2D //================================================================// //----------------------------------------------------------------// void MOAICameraFitter2D::AddAnchor ( MOAICameraAnchor2D& anchor ) { if ( !this->mAnchors.contains ( &anchor )) { this->LuaRetain ( &anchor ); this->mAnchors.insert ( &anchor ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::Clear () { while ( this->mAnchors.size ()) { AnchorIt anchorIt = this->mAnchors.begin (); MOAICameraAnchor2D* anchor = *anchorIt; this->mAnchors.erase ( anchorIt ); this->LuaRelease ( anchor ); } this->mCamera.Set ( *this, 0 ); this->mViewport.Set ( *this, 0 ); } //----------------------------------------------------------------// USRect MOAICameraFitter2D::GetAnchorRect () { // expand the world rect to include all the anchors AnchorIt anchorIt = this->mAnchors.begin (); USRect worldRect = ( *anchorIt )->GetRect (); ++anchorIt; for ( ; anchorIt != this->mAnchors.end (); ++anchorIt ) { MOAICameraAnchor2D* anchor = *anchorIt; worldRect.Grow ( anchor->GetRect ()); } // clip the world rect to the bounds if ( this->mFittingMode & FITTING_MODE_APPLY_BOUNDS ) { this->mBounds.Clip ( worldRect ); } // enforce the minimum float width = worldRect.Width (); float height = worldRect.Height (); float pad; if ( this->mMin > 0.0f ) { if ( width < this->mMin ) { pad = ( this->mMin - width ) * 0.5f; worldRect.mXMin -= pad; worldRect.mXMax += pad; } if ( height < this->mMin ) { pad = ( this->mMin - height ) * 0.5f; worldRect.mYMin -= pad; worldRect.mYMax += pad; } } return worldRect; } //----------------------------------------------------------------// void MOAICameraFitter2D::GetCamera ( USAffine3D& camera ) { camera.ScRoTr ( this->mTargetScale, this->mTargetScale, 1.0f, 0.0f, 0.0f, 0.0f, this->mTargetLoc.mX, this->mTargetLoc.mY, 0.0f ); } //----------------------------------------------------------------// float MOAICameraFitter2D::GetFitDistance () { if ( this->mCamera ) { USVec3D loc = this->mCamera->GetLoc (); float scale = this->mCamera->GetScl ().mX; USVec3D current ( loc.mX, loc.mY, scale ); USVec3D target ( this->mTargetLoc.mX, this->mTargetLoc.mY, this->mTargetScale ); return USDist::VecToVec ( current, target ); } return 0.0f; } //----------------------------------------------------------------// bool MOAICameraFitter2D::IsDone () { return false; } //----------------------------------------------------------------// MOAICameraFitter2D::MOAICameraFitter2D () : mMin ( 0.0f ), mDamper ( 0.0f ), mFittingMode ( FITTING_MODE_DEFAULT ) { RTTI_BEGIN RTTI_EXTEND ( MOAIAction ) RTTI_EXTEND ( MOAINode ) RTTI_END this->mFitLoc.Init ( 0.0f, 0.0f, 0.0f ); this->mFitScale = 1.0f; this->mTargetLoc.Init ( 0.0f, 0.0f, 0.0f ); this->mTargetScale = 1.0f; } //----------------------------------------------------------------// MOAICameraFitter2D::~MOAICameraFitter2D () { this->Clear (); } //----------------------------------------------------------------// void MOAICameraFitter2D::OnDepNodeUpdate () { this->UpdateFit (); this->UpdateTarget (); if ( this->mCamera ) { float d = 1.0f - USFloat::Clamp ( this->mDamper, 0.0f, 1.0f ); USVec3D loc = this->mCamera->GetLoc (); float scale = this->mCamera->GetScl ().mX; loc.mX += ( this->mTargetLoc.mX - loc.mX ) * d; loc.mY += ( this->mTargetLoc.mY - loc.mY ) * d; scale += ( this->mTargetScale - scale ) * d; USVec3D scaleVec; scaleVec.Init ( scale, scale, 1.0f ); this->mCamera->SetScl ( scaleVec ); this->mCamera->SetLoc ( loc ); this->mCamera->ScheduleUpdate (); } } //----------------------------------------------------------------// void MOAICameraFitter2D::OnUpdate ( float step ) { UNUSED ( step ); this->ScheduleUpdate (); // make sure all the anchors are ahead of fitter in the update schedule AnchorIt anchorIt = this->mAnchors.begin (); for ( ; anchorIt != this->mAnchors.end (); ++anchorIt ) { MOAICameraAnchor2D* anchor = *anchorIt; anchor->Activate ( *this ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::RemoveAnchor ( MOAICameraAnchor2D& anchor ) { if ( this->mAnchors.contains ( &anchor )) { this->mAnchors.erase ( &anchor ); this->LuaRelease ( &anchor ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::SnapToTargetLoc ( MOAITransform& camera ) { camera.SetLoc ( this->mTargetLoc ); camera.ScheduleUpdate (); } //----------------------------------------------------------------// void MOAICameraFitter2D::SnapToTargetScale ( MOAITransform& camera ) { USVec3D scaleVec; scaleVec.Init ( this->mTargetScale, this->mTargetScale, 1.0f ); camera.SetScl ( scaleVec ); camera.ScheduleUpdate (); } //----------------------------------------------------------------// void MOAICameraFitter2D::UpdateFit () { if ( !( this->mFittingMode & FITTING_MODE_APPLY_ANCHORS )) return; if ( !this->mAnchors.size ()) return; if ( !this->mViewport ) return; // reset the fitter this->mFitLoc.Init ( 0.0f, 0.0f, 0.0f ); this->mFitScale = 1.0f; // grab the view transform USMatrix4x4 ident; ident.Ident (); USMatrix4x4 wndToWorld = this->mViewport->GetWndToWorldMtx ( ident ); // grab the view rect in world space // TODO: take viewport offset into account USRect worldViewRect = this->mViewport->GetRect (); wndToWorld.Transform ( worldViewRect ); worldViewRect.Bless (); // build the anchor rect (clipped to bounds) USRect anchorRect = this->GetAnchorRect (); // fit the view rect around the target rect while preserving aspect ratio USRect fitViewRect = worldViewRect; anchorRect.FitOutside ( fitViewRect ); // get the fitting this->mFitScale = fitViewRect.Width () / worldViewRect.Width (); fitViewRect.GetCenter ( this->mFitLoc ); } //----------------------------------------------------------------// void MOAICameraFitter2D::UpdateTarget () { if ( !this->mViewport ) return; // reset the fitter this->mTargetLoc = this->mFitLoc; this->mTargetScale = this->mFitScale; // clamp to bounds if ( this->mFittingMode & FITTING_MODE_APPLY_BOUNDS ) { // grab the view transform USMatrix4x4 ident; ident.Ident (); USMatrix4x4 wndToWorld = this->mViewport->GetWndToWorldMtx ( ident ); // grab the view rect in world space // TODO: take viewport offset into account USRect worldViewRect = this->mViewport->GetRect (); wndToWorld.Transform ( worldViewRect ); worldViewRect.Bless (); // get the camera's target position and scale USAffine3D cameraMtx; float rot = this->mCamera ? this->mCamera->GetRot ().mZ : 0.0f; cameraMtx.ScRoTr ( this->mFitScale, this->mFitScale, 1.0f, 0.0f, 0.0f, rot * ( float )D2R, this->mFitLoc.mX, this->mFitLoc.mY, 0.0f ); // get the camera rect USRect cameraRect = worldViewRect; cameraMtx.Transform ( cameraRect ); cameraRect.Bless (); this->mBounds.ConstrainWithAspect ( cameraRect ); // get the fitting this->mTargetScale = cameraRect.Width () / worldViewRect.Width (); cameraRect.GetCenter ( this->mTargetLoc ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::RegisterLuaClass ( MOAILuaState& state ) { MOAIAction::RegisterLuaClass ( state ); MOAINode::RegisterLuaClass ( state ); } //----------------------------------------------------------------// void MOAICameraFitter2D::RegisterLuaFuncs ( MOAILuaState& state ) { MOAIAction::RegisterLuaFuncs ( state ); MOAINode::RegisterLuaFuncs ( state ); state.SetField ( -1, "FITTING_MODE_SEEK_LOC", ( u32 )FITTING_MODE_SEEK_LOC ); state.SetField ( -1, "FITTING_MODE_SEEK_SCALE", ( u32 )FITTING_MODE_SEEK_SCALE ); state.SetField ( -1, "FITTING_MODE_APPLY_ANCHORS", ( u32 )FITTING_MODE_APPLY_ANCHORS ); state.SetField ( -1, "FITTING_MODE_APPLY_BOUNDS", ( u32 )FITTING_MODE_APPLY_BOUNDS ); state.SetField ( -1, "FITTING_MODE_DEFAULT", ( u32 )FITTING_MODE_DEFAULT ); state.SetField ( -1, "FITTING_MODE_MASK", ( u32 )FITTING_MODE_MASK ); luaL_Reg regTable [] = { { "clearAnchors", _clearAnchors }, { "clearFitMode", _clearFitMode }, { "getFitDistance", _getFitDistance }, { "getFitLoc", _getFitLoc }, { "getFitMode", _getFitMode }, { "getFitScale", _getFitScale }, { "getTargetLoc", _getTargetLoc }, { "getTargetScale", _getTargetScale }, { "insertAnchor", _insertAnchor }, { "removeAnchor", _removeAnchor }, { "setBounds", _setBounds }, { "setCamera", _setCamera }, { "setDamper", _setDamper }, { "setFitLoc", _setFitLoc }, { "setFitMode", _setFitMode }, { "setFitScale", _setFitScale }, { "setMin", _setMin }, { "setViewport", _setViewport }, { "snapToTarget", _snapToTarget }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); }
27.723032
136
0.595331
jjimenezg93
d015e1d47dab3b6f4d16d5072775e6aef3825b17
76,269
cpp
C++
cpu/sh2/sh2.cpp
ssilverm/pifba-code
386ff10535af1e9353488b98a49777ee5499d86e
[ "Xnet", "X11" ]
8
2017-08-10T14:04:14.000Z
2021-12-08T15:35:34.000Z
cpu/sh2/sh2.cpp
ssilverm/pifba-code
386ff10535af1e9353488b98a49777ee5499d86e
[ "Xnet", "X11" ]
null
null
null
cpu/sh2/sh2.cpp
ssilverm/pifba-code
386ff10535af1e9353488b98a49777ee5499d86e
[ "Xnet", "X11" ]
7
2017-04-09T13:46:34.000Z
2021-03-04T01:55:47.000Z
/***************************************************************************** * * Portable Hitachi SH-2 (SH7600 family) emulator * * Copyright (c) 2000 Juergen Buchmueller <pullmoll@t-online.de>, * all rights reserved. * * - This source code is released as freeware for non-commercial purposes. * - You are free to use and redistribute this code in modified or * unmodified form, provided you list me in the credits. * - If you modify this source code, you must add a notice to each modified * source file that it has been changed. If you're a nice person, you * will clearly mark each change too. :) * - If you wish to use this for commercial purposes, please contact me at * pullmoll@t-online.de * - The author of this copywritten work reserves the right to change the * terms of its usage and license at any time, including retroactively * - This entire notice must remain in the source code. * * This work is based on <tiraniddo@hotmail.com> C/C++ implementation of * the SH-2 CPU core and was adapted to the MAME CPU core requirements. * Thanks also go to Chuck Mason <chukjr@sundail.net> and Olivier Galibert * <galibert@pobox.com> for letting me peek into their SEMU code :-) * ***************************************************************************** * * Port to Finalburn Alpha by OopsWare * http://oopsware.googlepages.com/ * *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sh2.h" //#include "tchar.h" //extern int (__cdecl *bprintf) (int nStatus, TCHAR* szFormat, ...); int has_sh2; typedef signed char INT8; typedef unsigned char UINT8; typedef signed short INT16; typedef unsigned short UINT16; typedef signed int INT32; typedef unsigned int UINT32; typedef signed long long INT64; typedef unsigned long long UINT64; #define BUSY_LOOP_HACKS 0 #define FAST_OP_FETCH 1 #define USE_JUMPTABLE 0 #define SH2_INT_15 15 #define INLINE #if FAST_OP_FETCH #define change_pc(newpc) \ sh2->pc = (newpc); \ pSh2Ext->opbase = pSh2Ext->MemMap[ (sh2->pc >> SH2_SHIFT) + SH2_WADD * 2 ]; \ pSh2Ext->opbase -= (sh2->pc & ~SH2_PAGEM); #else #define change_pc(newpc) sh2->pc = (newpc); #endif #define COMBINE_DATA(varptr) (*(varptr) = (*(varptr) & mem_mask) | (data & ~mem_mask)) typedef struct { int irq_vector; int irq_priority; } irq_entry; typedef struct { UINT32 ppc; UINT32 pc; UINT32 pr; UINT32 sr; UINT32 gbr, vbr; UINT32 mach, macl; UINT32 r[16]; UINT32 ea; UINT32 delay; UINT32 cpu_off; UINT32 dvsr, dvdnth, dvdntl, dvcr; UINT32 pending_irq; UINT32 test_irq; irq_entry irq_queue[16]; INT8 irq_line_state[17]; UINT32 m[0x200]; INT8 nmi_line_state; UINT16 frc; UINT16 ocra, ocrb, icr; UINT32 frc_base; int frt_input; int internal_irq_level; int internal_irq_vector; // emu_timer *timer; UINT32 timer_cycles; UINT32 timer_base; int timer_active; // emu_timer *dma_timer[2]; UINT32 dma_timer_cycles[2]; UINT32 dma_timer_base[2]; int dma_timer_active[2]; // int is_slave, cpu_number; UINT32 cycle_counts; UINT32 sh2_cycles_to_run; INT32 sh2_icount; int (*irq_callback)(int irqline); } SH2; static SH2 * sh2; static UINT32 sh2_GetTotalCycles() { return sh2->cycle_counts + sh2->sh2_cycles_to_run - sh2->sh2_icount; } static const int div_tab[4] = { 3, 5, 3, 0 }; enum { ICF = 0x00800000, OCFA = 0x00080000, OCFB = 0x00040000, OVF = 0x00020000 }; //static TIMER_CALLBACK( sh2_timer_callback ); #define T 0x00000001 #define S 0x00000002 #define I 0x000000f0 #define Q 0x00000100 #define M 0x00000200 #define AM 0xc7ffffff #define FLAGS (M|Q|I|S|T) #define Rn ((opcode>>8)&15) #define Rm ((opcode>>4)&15) static UINT32 sh2_internal_r(UINT32 A, UINT32 mask); static void sh2_internal_w(UINT32 offset, UINT32 data, UINT32 mem_mask); //-- sh2 memory handler for Finalburn Alpha --------------------- #define SH2_BITS (16) // 16 = 0x10000 page size #define SH2_PAGE_COUNT (1 << (32 - SH2_BITS)) // Number of pages #define SH2_SHIFT (SH2_BITS) // Shift value = page bits #define SH2_PAGE_SIZE (1 << SH2_BITS) // Page size #define SH2_PAGEM (SH2_PAGE_SIZE - 1) #define SH2_WADD (SH2_PAGE_COUNT) // Value to add for write section = Number of pages #define SH2_MASK (SH2_WADD - 1) #define SH2_MAXHANDLER (8) typedef struct { SH2 sh2; unsigned char * MemMap[SH2_PAGE_COUNT * 3]; pSh2ReadByteHandler ReadByte[SH2_MAXHANDLER]; pSh2WriteByteHandler WriteByte[SH2_MAXHANDLER]; pSh2ReadWordHandler ReadWord[SH2_MAXHANDLER]; pSh2WriteWordHandler WriteWord[SH2_MAXHANDLER]; pSh2ReadLongHandler ReadLong[SH2_MAXHANDLER]; pSh2WriteLongHandler WriteLong[SH2_MAXHANDLER]; unsigned char * opbase; int suspend; } SH2EXT; static SH2EXT * pSh2Ext; static SH2EXT * Sh2Ext = NULL; /* SH-2 Memory Map: * 0x00000000 ~ 0x07ffffff : user * 0x08000000 ~ 0x0fffffff : user ( mirror ) * 0x10000000 ~ 0x17ffffff : user ( mirror ) * 0x18000000 ~ 0x1fffffff : user ( mirror ) * 0x20000000 ~ 0x27ffffff : user ( mirror ) * 0x28000000 ~ 0x2fffffff : user ( mirror ) * 0x30000000 ~ 0x37ffffff : user ( mirror ) * 0x38000000 ~ 0x3fffffff : user ( mirror ) * 0x40000000 ~ 0xbfffffff : fill with 0xa5 * 0xc0000000 ~ 0xdfffffff : extend user * 0xe0000000 ~ 0xffffffff : internal mem */ int Sh2MapMemory(unsigned char* pMemory, unsigned int nStart, unsigned int nEnd, int nType) { unsigned char* Ptr = pMemory - nStart; unsigned char** pMemMap = pSh2Ext->MemMap + (nStart >> SH2_SHIFT); int need_mirror = (nStart < 0x08000000) ? 1 : 0; for (unsigned long long i = (nStart & ~SH2_PAGEM); i <= nEnd; i += SH2_PAGE_SIZE, pMemMap++) { if (nType & 0x01 /*SM_READ*/) pMemMap[0] = Ptr + i; if (nType & 0x02 /*SM_WRITE*/) pMemMap[SH2_WADD] = Ptr + i; if (nType & 0x04 /*SM_FETCH*/) pMemMap[SH2_WADD*2] = Ptr + i; if ( need_mirror ) { if (nType & 0x01 /*SM_READ*/) { pMemMap[0 + (0x08000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[0 + (0x10000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[0 + (0x18000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[0 + (0x20000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[0 + (0x28000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[0 + (0x30000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[0 + (0x38000000 >> SH2_SHIFT)] = Ptr + i; } if (nType & 0x02 /*SM_WRITE*/) { pMemMap[SH2_WADD + (0x08000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD + (0x10000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD + (0x18000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD + (0x20000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD + (0x28000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD + (0x30000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD + (0x38000000 >> SH2_SHIFT)] = Ptr + i; } if (nType & 0x04 /*SM_FETCH*/) { pMemMap[SH2_WADD*2 + (0x08000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD*2 + (0x10000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD*2 + (0x18000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD*2 + (0x20000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD*2 + (0x28000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD*2 + (0x30000000 >> SH2_SHIFT)] = Ptr + i; pMemMap[SH2_WADD*2 + (0x38000000 >> SH2_SHIFT)] = Ptr + i; } } } return 0; } int Sh2MapHandler(unsigned int nHandler, unsigned int nStart, unsigned int nEnd, int nType) { unsigned char** pMemMap = pSh2Ext->MemMap + (nStart >> SH2_SHIFT); int need_mirror = (nStart < 0x08000000) ? 1 : 0; for (unsigned long long i = (nStart & ~SH2_PAGEM); i <= nEnd; i += SH2_PAGE_SIZE, pMemMap++) { if (nType & 0x01 /*SM_READ*/) pMemMap[0] = (unsigned char*)nHandler; if (nType & 0x02 /*SM_WRITE*/) pMemMap[SH2_WADD] = (unsigned char*)nHandler; if (nType & 0x04 /*SM_FETCH*/) pMemMap[SH2_WADD*2] = (unsigned char*)nHandler; if ( need_mirror ) { if (nType & 0x01 /*SM_READ*/) { pMemMap[0 + (0x08000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[0 + (0x10000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[0 + (0x18000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[0 + (0x20000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[0 + (0x28000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[0 + (0x30000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[0 + (0x38000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; } if (nType & 0x02 /*SM_WRITE*/) { pMemMap[SH2_WADD + (0x08000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD + (0x10000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD + (0x18000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD + (0x20000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD + (0x28000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD + (0x30000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD + (0x38000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; } if (nType & 0x04 /*SM_FETCH*/) { pMemMap[SH2_WADD*2 + (0x08000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD*2 + (0x10000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD*2 + (0x18000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD*2 + (0x20000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD*2 + (0x28000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD*2 + (0x30000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; pMemMap[SH2_WADD*2 + (0x38000000 >> SH2_SHIFT)] = (unsigned char*)nHandler; } } } return 0; } int Sh2SetReadByteHandler(int i, pSh2ReadByteHandler pHandler) { if (i >= SH2_MAXHANDLER) return 1; pSh2Ext->ReadByte[i] = pHandler; return 0; } int Sh2SetWriteByteHandler(int i, pSh2WriteByteHandler pHandler) { if (i >= SH2_MAXHANDLER) return 1; pSh2Ext->WriteByte[i] = pHandler; return 0; } int Sh2SetReadWordHandler(int i, pSh2ReadWordHandler pHandler) { if (i >= SH2_MAXHANDLER) return 1; pSh2Ext->ReadWord[i] = pHandler; return 0; } int Sh2SetWriteWordHandler(int i, pSh2WriteWordHandler pHandler) { if (i >= SH2_MAXHANDLER) return 1; pSh2Ext->WriteWord[i] = pHandler; return 0; } int Sh2SetReadLongHandler(int i, pSh2ReadLongHandler pHandler) { if (i >= SH2_MAXHANDLER) return 1; pSh2Ext->ReadLong[i] = pHandler; return 0; } int Sh2SetWriteLongHandler(int i, pSh2WriteLongHandler pHandler) { if (i >= SH2_MAXHANDLER) return 1; pSh2Ext->WriteLong[i] = pHandler; return 0; } unsigned char __fastcall Sh2InnerReadByte(unsigned int a) { return sh2_internal_r((a & 0x1fc)>>2, ~(0xff << (((~a) & 3)*8))) >> (((~a) & 3)*8); } unsigned short __fastcall Sh2InnerReadWord(unsigned int a) { return sh2_internal_r((a & 0x1fc)>>2, ~(0xffff << (((~a) & 2)*8))) >> (((~a) & 2)*8); } unsigned int __fastcall Sh2InnerReadLong(unsigned int a) { return sh2_internal_r((a & 0x1fc)>>2, 0); } void __fastcall Sh2InnerWriteByte(unsigned int a, unsigned char d) { //bprintf(0, _T("Attempt to write byte value %02x to location %8x offset: %04x\n"), d, a, (a & 0x1fc)>>2); sh2_internal_w((a & 0x1fc)>>2, d << (((~a) & 3)*8), ~(0xff << (((~a) & 3)*8))); } void __fastcall Sh2InnerWriteWord(unsigned int a, unsigned short d) { sh2_internal_w((a & 0x1fc)>>2, d << (((~a) & 2)*8), ~(0xffff << (((~a) & 2)*8))); } void __fastcall Sh2InnerWriteLong(unsigned int a, unsigned int d) { sh2_internal_w((a & 0x1fc)>>2, d, 0); } unsigned char __fastcall Sh2EmptyReadByte(unsigned int) { return 0xa5; } unsigned short __fastcall Sh2EmptyReadWord(unsigned int) { return 0xa5a5; } unsigned int __fastcall Sh2EmptyReadLong(unsigned int) { return 0xa5a5a5a5; } void __fastcall Sh2EmptyWriteByte(unsigned int, unsigned char) { } void __fastcall Sh2EmptyWriteWord(unsigned int, unsigned short) { } void __fastcall Sh2EmptyWriteLong(unsigned int, unsigned int) { } int Sh2Exit() { has_sh2 = 0; if (Sh2Ext) { free(Sh2Ext); Sh2Ext = NULL; } pSh2Ext = NULL; return 0; } int Sh2Init(int nCount) { has_sh2 = 1; Sh2Ext = (SH2EXT *)malloc(sizeof(SH2EXT) * nCount); if (Sh2Ext == NULL) { Sh2Exit(); return 1; } memset(Sh2Ext, 0, sizeof(SH2EXT) * nCount); // init default memory handler for (int i=0; i<nCount; i++) { pSh2Ext = Sh2Ext + i; //sh2 = & pSh2Ext->sh2; Sh2MapHandler(SH2_MAXHANDLER - 1, 0xE0000000, 0xFFFFFFFF, 0x07); Sh2MapHandler(SH2_MAXHANDLER - 2, 0x40000000, 0xBFFFFFFF, 0x07); // Sh2MapHandler(SH2_MAXHANDLER - 3, 0xC0000000, 0xDFFFFFFF, 0x07); Sh2SetReadByteHandler (SH2_MAXHANDLER - 1, Sh2InnerReadByte); Sh2SetReadWordHandler (SH2_MAXHANDLER - 1, Sh2InnerReadWord); Sh2SetReadLongHandler (SH2_MAXHANDLER - 1, Sh2InnerReadLong); Sh2SetWriteByteHandler(SH2_MAXHANDLER - 1, Sh2InnerWriteByte); Sh2SetWriteWordHandler(SH2_MAXHANDLER - 1, Sh2InnerWriteWord); Sh2SetWriteLongHandler(SH2_MAXHANDLER - 1, Sh2InnerWriteLong); Sh2SetReadByteHandler (SH2_MAXHANDLER - 2, Sh2EmptyReadByte); Sh2SetReadWordHandler (SH2_MAXHANDLER - 2, Sh2EmptyReadWord); Sh2SetReadLongHandler (SH2_MAXHANDLER - 2, Sh2EmptyReadLong); Sh2SetWriteByteHandler(SH2_MAXHANDLER - 2, Sh2EmptyWriteByte); Sh2SetWriteWordHandler(SH2_MAXHANDLER - 2, Sh2EmptyWriteWord); Sh2SetWriteLongHandler(SH2_MAXHANDLER - 2, Sh2EmptyWriteLong); } return 0; } void Sh2Open(const int i) { pSh2Ext = Sh2Ext + i; sh2 = & (pSh2Ext->sh2); } void Sh2Close() { } void Sh2Reset(unsigned int pc, unsigned r15) { memset(sh2, 0, sizeof(SH2) - 4); sh2->pc = pc; sh2->r[15] = r15; sh2->sr = I; change_pc(sh2->pc & AM); sh2->internal_irq_level = -1; } //---------------------------------------------------------------- unsigned char program_read_byte_32be(unsigned int /*A*/) { return 0; } unsigned short program_read_word_32be(unsigned int /*A*/) { return 0; } unsigned int program_read_dword_32be(unsigned int /*A*/) { return 0; } void program_write_byte_32be(unsigned int /*A*/, unsigned char /*V*/) { } void program_write_word_32be(unsigned int /*A*/, unsigned short /*V*/) { } void program_write_dword_32be(unsigned int /*A*/, unsigned int /*V*/) { } //pSh2Ext->opbase #if FAST_OP_FETCH #define cpu_readop16(A) *(unsigned short *)(pSh2Ext->opbase + (A ^ 0x02)) #else INLINE unsigned short cpu_readop16(unsigned int A) { unsigned char * pr; pr = pSh2Ext->MemMap[ (A >> SH2_SHIFT) + SH2_WADD * 2 ]; if ( (unsigned int)pr >= SH2_MAXHANDLER ) { A ^= 2; return *((unsigned short *)(pr + (A & SH2_PAGEM))); } return pSh2Ext->ReadWord[(unsigned int)pr](A); } #endif // ------------------------------------------------------ INLINE UINT8 RB(UINT32 A) { /* if (A >= 0xe0000000) return sh2_internal_r((A & 0x1fc)>>2, ~(0xff << (((~A) & 3)*8))) >> (((~A) & 3)*8); if (A >= 0xc0000000) return program_read_byte_32be(A); if (A >= 0x40000000) return 0xa5; return program_read_byte_32be(A & AM); */ unsigned char * pr; pr = pSh2Ext->MemMap[ A >> SH2_SHIFT ]; if ( (unsigned int)pr >= SH2_MAXHANDLER ) { A ^= 3; return pr[A & SH2_PAGEM]; } return pSh2Ext->ReadByte[(unsigned int)pr](A); } INLINE UINT16 RW(UINT32 A) { /* if (A >= 0xe0000000) return sh2_internal_r((A & 0x1fc)>>2, ~(0xffff << (((~A) & 2)*8))) >> (((~A) & 2)*8); if (A >= 0xc0000000) return program_read_word_32be(A); if (A >= 0x40000000) return 0xa5a5; return program_read_word_32be(A & AM); */ unsigned char * pr; pr = pSh2Ext->MemMap[ A >> SH2_SHIFT ]; if ( (unsigned int)pr >= SH2_MAXHANDLER ) { A ^= 2; //return (pr[A & SH2_PAGEM] << 8) | pr[(A & SH2_PAGEM) + 1]; return *((unsigned short *)(pr + (A & SH2_PAGEM))); } return pSh2Ext->ReadWord[(unsigned int)pr](A); } INLINE UINT16 OPRW(UINT32 A) { unsigned char * pr; pr = pSh2Ext->MemMap[ (A >> SH2_SHIFT) + SH2_WADD * 2 ]; if ( (unsigned int)pr >= SH2_MAXHANDLER ) { A ^= 2; return *((unsigned short *)(pr + (A & SH2_PAGEM))); } return 0x0000; } INLINE UINT32 RL(UINT32 A) { /* if (A >= 0xe0000000) return sh2_internal_r((A & 0x1fc)>>2, 0); if (A >= 0xc0000000) return program_read_dword_32be(A); if (A >= 0x40000000) return 0xa5a5a5a5; return program_read_dword_32be(A & AM); */ unsigned char * pr; pr = pSh2Ext->MemMap[ A >> SH2_SHIFT ]; if ( (unsigned int)pr >= SH2_MAXHANDLER ) { //return (pr[(A & SH2_PAGEM) + 0] << 24) | (pr[(A & SH2_PAGEM) + 1] << 16) | (pr[(A & SH2_PAGEM) + 2] << 8) | (pr[(A & SH2_PAGEM) + 3] << 0); return *((unsigned int *)(pr + (A & SH2_PAGEM))); } return pSh2Ext->ReadLong[(unsigned int)pr](A); } INLINE void WB(UINT32 A, UINT8 V) { /* if (A >= 0xe0000000) { sh2_internal_w((A & 0x1fc)>>2, V << (((~A) & 3)*8), ~(0xff << (((~A) & 3)*8))); return; } if (A >= 0xc0000000) { program_write_byte_32be(A,V); return; } if (A >= 0x40000000) return; program_write_byte_32be(A & AM,V); */ unsigned char* pr; pr = pSh2Ext->MemMap[(A >> SH2_SHIFT) + SH2_WADD]; if ((unsigned int)pr >= SH2_MAXHANDLER) { A ^= 3; pr[A & SH2_PAGEM] = (unsigned char)V; return; } pSh2Ext->WriteByte[(unsigned int)pr](A, V); } INLINE void WW(UINT32 A, UINT16 V) { /* if (A >= 0xe0000000) { sh2_internal_w((A & 0x1fc)>>2, V << (((~A) & 2)*8), ~(0xffff << (((~A) & 2)*8))); return; } if (A >= 0xc0000000) { program_write_word_32be(A,V); return; } if (A >= 0x40000000) return; program_write_word_32be(A & AM,V); */ unsigned char * pr; pr = pSh2Ext->MemMap[(A >> SH2_SHIFT) + SH2_WADD]; if ((unsigned int)pr >= SH2_MAXHANDLER) { A ^= 2; *((unsigned short *)(pr + (A & SH2_PAGEM))) = (unsigned short)V; return; } pSh2Ext->WriteWord[(unsigned int)pr](A, V); } INLINE void WL(UINT32 A, UINT32 V) { /* if (A >= 0xe0000000) { sh2_internal_w((A & 0x1fc)>>2, V, 0); return; } if (A >= 0xc0000000) { program_write_dword_32be(A,V); return; } if (A >= 0x40000000) return; program_write_dword_32be(A & AM,V); */ unsigned char * pr; pr = pSh2Ext->MemMap[(A >> SH2_SHIFT) + SH2_WADD]; if ((unsigned int)pr >= SH2_MAXHANDLER) { *((unsigned int *)(pr + (A & SH2_PAGEM))) = (unsigned int)V; return; } pSh2Ext->WriteLong[(unsigned int)pr](A, V); } INLINE void sh2_exception(/*const char *message,*/ int irqline) { int vector; if (irqline != 16) { if (irqline <= (signed int)((sh2->sr >> 4) & 15)) /* If the cpu forbids this interrupt */ return; // if this is an sh2 internal irq, use its vector if (sh2->internal_irq_level == irqline) { vector = sh2->internal_irq_vector; //LOG(("SH-2 #%d exception #%d (internal vector: $%x) after [%s]\n", cpu_getactivecpu(), irqline, vector, message)); } else { if(sh2->m[0x38] & 0x00010000) { //vector = sh2->irq_callback(irqline); //LOG(("SH-2 #%d exception #%d (external vector: $%x) after [%s]\n", cpu_getactivecpu(), irqline, vector, message)); //bprintf(0, _T("SH-2 exception #%d (external vector: $%x)\n"), irqline, vector); vector = 64 + irqline/2; } else { //sh2->irq_callback(irqline); vector = 64 + irqline/2; //LOG(("SH-2 #%d exception #%d (autovector: $%x) after [%s]\n", cpu_getactivecpu(), irqline, vector, message)); } } } else { vector = 11; //LOG(("SH-2 #%d nmi exception (autovector: $%x) after [%s]\n", cpu_getactivecpu(), vector, message)); } sh2->r[15] -= 4; WL( sh2->r[15], sh2->sr ); /* push SR onto stack */ sh2->r[15] -= 4; WL( sh2->r[15], sh2->pc ); /* push PC onto stack */ /* set I flags in SR */ if (irqline > SH2_INT_15) sh2->sr = sh2->sr | I; else sh2->sr = (sh2->sr & ~I) | (irqline << 4); /* fetch PC */ sh2->pc = RL( sh2->vbr + vector * 4 ); change_pc(sh2->pc & AM); } #define CHECK_PENDING_IRQ(/*message*/) \ do { \ int irq = -1; \ if (sh2->pending_irq & (1 << 0)) irq = 0; \ if (sh2->pending_irq & (1 << 1)) irq = 1; \ if (sh2->pending_irq & (1 << 2)) irq = 2; \ if (sh2->pending_irq & (1 << 3)) irq = 3; \ if (sh2->pending_irq & (1 << 4)) irq = 4; \ if (sh2->pending_irq & (1 << 5)) irq = 5; \ if (sh2->pending_irq & (1 << 6)) irq = 6; \ if (sh2->pending_irq & (1 << 7)) irq = 7; \ if (sh2->pending_irq & (1 << 8)) irq = 8; \ if (sh2->pending_irq & (1 << 9)) irq = 9; \ if (sh2->pending_irq & (1 << 10)) irq = 10; \ if (sh2->pending_irq & (1 << 11)) irq = 11; \ if (sh2->pending_irq & (1 << 12)) irq = 12; \ if (sh2->pending_irq & (1 << 13)) irq = 13; \ if (sh2->pending_irq & (1 << 14)) irq = 14; \ if (sh2->pending_irq & (1 << 15)) irq = 15; \ if ((sh2->internal_irq_level != -1) && (sh2->internal_irq_level > irq)) irq = sh2->internal_irq_level; \ if (irq >= 0) \ sh2_exception(/*message,*/irq); \ } while(0) #if USE_JUMPTABLE #include "sh2op.c" #else /* code cycles t-bit * 0011 nnnn mmmm 1100 1 - * ADD Rm,Rn */ INLINE void ADD(UINT32 m, UINT32 n) { sh2->r[n] += sh2->r[m]; } /* code cycles t-bit * 0111 nnnn iiii iiii 1 - * ADD #imm,Rn */ INLINE void ADDI(UINT32 i, UINT32 n) { sh2->r[n] += (INT32)(INT16)(INT8)i; } /* code cycles t-bit * 0011 nnnn mmmm 1110 1 carry * ADDC Rm,Rn */ INLINE void ADDC(UINT32 m, UINT32 n) { UINT32 tmp0, tmp1; tmp1 = sh2->r[n] + sh2->r[m]; tmp0 = sh2->r[n]; sh2->r[n] = tmp1 + (sh2->sr & T); if (tmp0 > tmp1) sh2->sr |= T; else sh2->sr &= ~T; if (tmp1 > sh2->r[n]) sh2->sr |= T; } /* code cycles t-bit * 0011 nnnn mmmm 1111 1 overflow * ADDV Rm,Rn */ INLINE void ADDV(UINT32 m, UINT32 n) { INT32 dest, src, ans; if ((INT32) sh2->r[n] >= 0) dest = 0; else dest = 1; if ((INT32) sh2->r[m] >= 0) src = 0; else src = 1; src += dest; sh2->r[n] += sh2->r[m]; if ((INT32) sh2->r[n] >= 0) ans = 0; else ans = 1; ans += dest; if (src == 0 || src == 2) { if (ans == 1) sh2->sr |= T; else sh2->sr &= ~T; } else sh2->sr &= ~T; } /* code cycles t-bit * 0010 nnnn mmmm 1001 1 - * AND Rm,Rn */ INLINE void AND(UINT32 m, UINT32 n) { sh2->r[n] &= sh2->r[m]; } /* code cycles t-bit * 1100 1001 iiii iiii 1 - * AND #imm,R0 */ INLINE void ANDI(UINT32 i) { sh2->r[0] &= i; } /* code cycles t-bit * 1100 1101 iiii iiii 1 - * AND.B #imm,@(R0,GBR) */ INLINE void ANDM(UINT32 i) { UINT32 temp; sh2->ea = sh2->gbr + sh2->r[0]; temp = i & RB( sh2->ea ); WB( sh2->ea, temp ); sh2->sh2_icount -= 2; } /* code cycles t-bit * 1000 1011 dddd dddd 3/1 - * BF disp8 */ INLINE void BF(UINT32 d) { if ((sh2->sr & T) == 0) { INT32 disp = ((INT32)d << 24) >> 24; sh2->pc = sh2->ea = sh2->pc + disp * 2 + 2; change_pc(sh2->pc & AM); sh2->sh2_icount -= 2; } } /* code cycles t-bit * 1000 1111 dddd dddd 3/1 - * BFS disp8 */ INLINE void BFS(UINT32 d) { if ((sh2->sr & T) == 0) { INT32 disp = ((INT32)d << 24) >> 24; sh2->delay = sh2->pc; sh2->pc = sh2->ea = sh2->pc + disp * 2 + 2; sh2->sh2_icount--; } } /* code cycles t-bit * 1010 dddd dddd dddd 2 - * BRA disp12 */ INLINE void BRA(UINT32 d) { INT32 disp = ((INT32)d << 20) >> 20; #if BUSY_LOOP_HACKS if (disp == -2) { UINT32 next_opcode = RW(sh2->ppc & AM); //UINT32 next_opcode = OPRW(sh2->ppc & AM); /* BRA $ * NOP */ if (next_opcode == 0x0009){ //bprintf(0, _T("SH2: BUSY_LOOP_HACKS %d\n"), sh2->sh2_icount); sh2->sh2_icount %= 3; /* cycles for BRA $ and NOP taken (3) */ } } #endif sh2->delay = sh2->pc; sh2->pc = sh2->ea = sh2->pc + disp * 2 + 2; sh2->sh2_icount--; } /* code cycles t-bit * 0000 mmmm 0010 0011 2 - * BRAF Rm */ INLINE void BRAF(UINT32 m) { sh2->delay = sh2->pc; sh2->pc += sh2->r[m] + 2; sh2->sh2_icount--; } /* code cycles t-bit * 1011 dddd dddd dddd 2 - * BSR disp12 */ INLINE void BSR(UINT32 d) { INT32 disp = ((INT32)d << 20) >> 20; sh2->pr = sh2->pc + 2; sh2->delay = sh2->pc; sh2->pc = sh2->ea = sh2->pc + disp * 2 + 2; sh2->sh2_icount--; } /* code cycles t-bit * 0000 mmmm 0000 0011 2 - * BSRF Rm */ INLINE void BSRF(UINT32 m) { sh2->pr = sh2->pc + 2; sh2->delay = sh2->pc; sh2->pc += sh2->r[m] + 2; sh2->sh2_icount--; } /* code cycles t-bit * 1000 1001 dddd dddd 3/1 - * BT disp8 */ INLINE void BT(UINT32 d) { if ((sh2->sr & T) != 0) { INT32 disp = ((INT32)d << 24) >> 24; sh2->pc = sh2->ea = sh2->pc + disp * 2 + 2; change_pc(sh2->pc & AM); sh2->sh2_icount -= 2; } } /* code cycles t-bit * 1000 1101 dddd dddd 2/1 - * BTS disp8 */ INLINE void BTS(UINT32 d) { if ((sh2->sr & T) != 0) { INT32 disp = ((INT32)d << 24) >> 24; sh2->delay = sh2->pc; sh2->pc = sh2->ea = sh2->pc + disp * 2 + 2; sh2->sh2_icount--; } } /* code cycles t-bit * 0000 0000 0010 1000 1 - * CLRMAC */ INLINE void CLRMAC(void) { sh2->mach = 0; sh2->macl = 0; } /* code cycles t-bit * 0000 0000 0000 1000 1 - * CLRT */ INLINE void CLRT(void) { sh2->sr &= ~T; } /* code cycles t-bit * 0011 nnnn mmmm 0000 1 comparison result * CMP_EQ Rm,Rn */ INLINE void CMPEQ(UINT32 m, UINT32 n) { if (sh2->r[n] == sh2->r[m]) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0011 nnnn mmmm 0011 1 comparison result * CMP_GE Rm,Rn */ INLINE void CMPGE(UINT32 m, UINT32 n) { if ((INT32) sh2->r[n] >= (INT32) sh2->r[m]) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0011 nnnn mmmm 0111 1 comparison result * CMP_GT Rm,Rn */ INLINE void CMPGT(UINT32 m, UINT32 n) { if ((INT32) sh2->r[n] > (INT32) sh2->r[m]) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0011 nnnn mmmm 0110 1 comparison result * CMP_HI Rm,Rn */ INLINE void CMPHI(UINT32 m, UINT32 n) { if ((UINT32) sh2->r[n] > (UINT32) sh2->r[m]) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0011 nnnn mmmm 0010 1 comparison result * CMP_HS Rm,Rn */ INLINE void CMPHS(UINT32 m, UINT32 n) { if ((UINT32) sh2->r[n] >= (UINT32) sh2->r[m]) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0100 nnnn 0001 0101 1 comparison result * CMP_PL Rn */ INLINE void CMPPL(UINT32 n) { if ((INT32) sh2->r[n] > 0) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0100 nnnn 0001 0001 1 comparison result * CMP_PZ Rn */ INLINE void CMPPZ(UINT32 n) { if ((INT32) sh2->r[n] >= 0) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0010 nnnn mmmm 1100 1 comparison result * CMP_STR Rm,Rn */ INLINE void CMPSTR(UINT32 m, UINT32 n) { UINT32 temp; INT32 HH, HL, LH, LL; temp = sh2->r[n] ^ sh2->r[m]; HH = (temp >> 24) & 0xff; HL = (temp >> 16) & 0xff; LH = (temp >> 8) & 0xff; LL = temp & 0xff; if (HH && HL && LH && LL) sh2->sr &= ~T; else sh2->sr |= T; } /* code cycles t-bit * 1000 1000 iiii iiii 1 comparison result * CMP/EQ #imm,R0 */ INLINE void CMPIM(UINT32 i) { UINT32 imm = (UINT32)(INT32)(INT16)(INT8)i; if (sh2->r[0] == imm) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0010 nnnn mmmm 0111 1 calculation result * DIV0S Rm,Rn */ INLINE void DIV0S(UINT32 m, UINT32 n) { if ((sh2->r[n] & 0x80000000) == 0) sh2->sr &= ~Q; else sh2->sr |= Q; if ((sh2->r[m] & 0x80000000) == 0) sh2->sr &= ~M; else sh2->sr |= M; if ((sh2->r[m] ^ sh2->r[n]) & 0x80000000) sh2->sr |= T; else sh2->sr &= ~T; } /* code cycles t-bit * 0000 0000 0001 1001 1 0 * DIV0U */ INLINE void DIV0U(void) { sh2->sr &= ~(M | Q | T); } /* code cycles t-bit * 0011 nnnn mmmm 0100 1 calculation result * DIV1 Rm,Rn */ INLINE void DIV1(UINT32 m, UINT32 n) { UINT32 tmp0; UINT32 old_q; old_q = sh2->sr & Q; if (0x80000000 & sh2->r[n]) sh2->sr |= Q; else sh2->sr &= ~Q; sh2->r[n] = (sh2->r[n] << 1) | (sh2->sr & T); if (!old_q) { if (!(sh2->sr & M)) { tmp0 = sh2->r[n]; sh2->r[n] -= sh2->r[m]; if(!(sh2->sr & Q)) if(sh2->r[n] > tmp0) sh2->sr |= Q; else sh2->sr &= ~Q; else if(sh2->r[n] > tmp0) sh2->sr &= ~Q; else sh2->sr |= Q; } else { tmp0 = sh2->r[n]; sh2->r[n] += sh2->r[m]; if(!(sh2->sr & Q)) { if(sh2->r[n] < tmp0) sh2->sr &= ~Q; else sh2->sr |= Q; } else { if(sh2->r[n] < tmp0) sh2->sr |= Q; else sh2->sr &= ~Q; } } } else { if (!(sh2->sr & M)) { tmp0 = sh2->r[n]; sh2->r[n] += sh2->r[m]; if(!(sh2->sr & Q)) if(sh2->r[n] < tmp0) sh2->sr |= Q; else sh2->sr &= ~Q; else if(sh2->r[n] < tmp0) sh2->sr &= ~Q; else sh2->sr |= Q; } else { tmp0 = sh2->r[n]; sh2->r[n] -= sh2->r[m]; if(!(sh2->sr & Q)) if(sh2->r[n] > tmp0) sh2->sr &= ~Q; else sh2->sr |= Q; else if(sh2->r[n] > tmp0) sh2->sr |= Q; else sh2->sr &= ~Q; } } tmp0 = (sh2->sr & (Q | M)); if((!tmp0) || (tmp0 == 0x300)) /* if Q == M set T else clear T */ sh2->sr |= T; else sh2->sr &= ~T; } /* DMULS.L Rm,Rn */ INLINE void DMULS(UINT32 m, UINT32 n) { UINT32 RnL, RnH, RmL, RmH, Res0, Res1, Res2; UINT32 temp0, temp1, temp2, temp3; INT32 tempm, tempn, fnLmL; tempn = (INT32) sh2->r[n]; tempm = (INT32) sh2->r[m]; if (tempn < 0) tempn = 0 - tempn; if (tempm < 0) tempm = 0 - tempm; if ((INT32) (sh2->r[n] ^ sh2->r[m]) < 0) fnLmL = -1; else fnLmL = 0; temp1 = (UINT32) tempn; temp2 = (UINT32) tempm; RnL = temp1 & 0x0000ffff; RnH = (temp1 >> 16) & 0x0000ffff; RmL = temp2 & 0x0000ffff; RmH = (temp2 >> 16) & 0x0000ffff; temp0 = RmL * RnL; temp1 = RmH * RnL; temp2 = RmL * RnH; temp3 = RmH * RnH; Res2 = 0; Res1 = temp1 + temp2; if (Res1 < temp1) Res2 += 0x00010000; temp1 = (Res1 << 16) & 0xffff0000; Res0 = temp0 + temp1; if (Res0 < temp0) Res2++; Res2 = Res2 + ((Res1 >> 16) & 0x0000ffff) + temp3; if (fnLmL < 0) { Res2 = ~Res2; if (Res0 == 0) Res2++; else Res0 = (~Res0) + 1; } sh2->mach = Res2; sh2->macl = Res0; sh2->sh2_icount--; } /* DMULU.L Rm,Rn */ INLINE void DMULU(UINT32 m, UINT32 n) { UINT32 RnL, RnH, RmL, RmH, Res0, Res1, Res2; UINT32 temp0, temp1, temp2, temp3; RnL = sh2->r[n] & 0x0000ffff; RnH = (sh2->r[n] >> 16) & 0x0000ffff; RmL = sh2->r[m] & 0x0000ffff; RmH = (sh2->r[m] >> 16) & 0x0000ffff; temp0 = RmL * RnL; temp1 = RmH * RnL; temp2 = RmL * RnH; temp3 = RmH * RnH; Res2 = 0; Res1 = temp1 + temp2; if (Res1 < temp1) Res2 += 0x00010000; temp1 = (Res1 << 16) & 0xffff0000; Res0 = temp0 + temp1; if (Res0 < temp0) Res2++; Res2 = Res2 + ((Res1 >> 16) & 0x0000ffff) + temp3; sh2->mach = Res2; sh2->macl = Res0; sh2->sh2_icount--; } /* DT Rn */ INLINE void DT(UINT32 n) { sh2->r[n]--; if (sh2->r[n] == 0) sh2->sr |= T; else sh2->sr &= ~T; #if BUSY_LOOP_HACKS { UINT32 next_opcode = RW(sh2->ppc & AM); //UINT32 next_opcode = OPRW(sh2->ppc & AM); /* DT Rn * BF $-2 */ if (next_opcode == 0x8bfd) { //bprintf(0, _T("SH2: BUSY_LOOP_HACKS (%d)--; \n"), sh2->r[n], sh2->sh2_icount); while (sh2->r[n] > 1 && sh2->sh2_icount > 4) { sh2->r[n]--; sh2->sh2_icount -= 4; /* cycles for DT (1) and BF taken (3) */ } } } #endif } /* EXTS.B Rm,Rn */ INLINE void EXTSB(UINT32 m, UINT32 n) { sh2->r[n] = ((INT32)sh2->r[m] << 24) >> 24; } /* EXTS.W Rm,Rn */ INLINE void EXTSW(UINT32 m, UINT32 n) { sh2->r[n] = ((INT32)sh2->r[m] << 16) >> 16; } /* EXTU.B Rm,Rn */ INLINE void EXTUB(UINT32 m, UINT32 n) { sh2->r[n] = sh2->r[m] & 0x000000ff; } /* EXTU.W Rm,Rn */ INLINE void EXTUW(UINT32 m, UINT32 n) { sh2->r[n] = sh2->r[m] & 0x0000ffff; } /* JMP @Rm */ INLINE void JMP(UINT32 m) { sh2->delay = sh2->pc; sh2->pc = sh2->ea = sh2->r[m]; } /* JSR @Rm */ INLINE void JSR(UINT32 m) { sh2->delay = sh2->pc; sh2->pr = sh2->pc + 2; sh2->pc = sh2->ea = sh2->r[m]; sh2->sh2_icount--; } /* LDC Rm,SR */ INLINE void LDCSR(UINT32 m) { sh2->sr = sh2->r[m] & FLAGS; sh2->test_irq = 1; } /* LDC Rm,GBR */ INLINE void LDCGBR(UINT32 m) { sh2->gbr = sh2->r[m]; } /* LDC Rm,VBR */ INLINE void LDCVBR(UINT32 m) { sh2->vbr = sh2->r[m]; } /* LDC.L @Rm+,SR */ INLINE void LDCMSR(UINT32 m) { sh2->ea = sh2->r[m]; sh2->sr = RL( sh2->ea ) & FLAGS; sh2->r[m] += 4; sh2->sh2_icount -= 2; sh2->test_irq = 1; } /* LDC.L @Rm+,GBR */ INLINE void LDCMGBR(UINT32 m) { sh2->ea = sh2->r[m]; sh2->gbr = RL( sh2->ea ); sh2->r[m] += 4; sh2->sh2_icount -= 2; } /* LDC.L @Rm+,VBR */ INLINE void LDCMVBR(UINT32 m) { sh2->ea = sh2->r[m]; sh2->vbr = RL( sh2->ea ); sh2->r[m] += 4; sh2->sh2_icount -= 2; } /* LDS Rm,MACH */ INLINE void LDSMACH(UINT32 m) { sh2->mach = sh2->r[m]; } /* LDS Rm,MACL */ INLINE void LDSMACL(UINT32 m) { sh2->macl = sh2->r[m]; } /* LDS Rm,PR */ INLINE void LDSPR(UINT32 m) { sh2->pr = sh2->r[m]; } /* LDS.L @Rm+,MACH */ INLINE void LDSMMACH(UINT32 m) { sh2->ea = sh2->r[m]; sh2->mach = RL( sh2->ea ); sh2->r[m] += 4; } /* LDS.L @Rm+,MACL */ INLINE void LDSMMACL(UINT32 m) { sh2->ea = sh2->r[m]; sh2->macl = RL( sh2->ea ); sh2->r[m] += 4; } /* LDS.L @Rm+,PR */ INLINE void LDSMPR(UINT32 m) { sh2->ea = sh2->r[m]; sh2->pr = RL( sh2->ea ); sh2->r[m] += 4; } /* MAC.L @Rm+,@Rn+ */ INLINE void MAC_L(UINT32 m, UINT32 n) { UINT32 RnL, RnH, RmL, RmH, Res0, Res1, Res2; UINT32 temp0, temp1, temp2, temp3; INT32 tempm, tempn, fnLmL; tempn = (INT32) RL( sh2->r[n] ); sh2->r[n] += 4; tempm = (INT32) RL( sh2->r[m] ); sh2->r[m] += 4; if ((INT32) (tempn ^ tempm) < 0) fnLmL = -1; else fnLmL = 0; if (tempn < 0) tempn = 0 - tempn; if (tempm < 0) tempm = 0 - tempm; temp1 = (UINT32) tempn; temp2 = (UINT32) tempm; RnL = temp1 & 0x0000ffff; RnH = (temp1 >> 16) & 0x0000ffff; RmL = temp2 & 0x0000ffff; RmH = (temp2 >> 16) & 0x0000ffff; temp0 = RmL * RnL; temp1 = RmH * RnL; temp2 = RmL * RnH; temp3 = RmH * RnH; Res2 = 0; Res1 = temp1 + temp2; if (Res1 < temp1) Res2 += 0x00010000; temp1 = (Res1 << 16) & 0xffff0000; Res0 = temp0 + temp1; if (Res0 < temp0) Res2++; Res2 = Res2 + ((Res1 >> 16) & 0x0000ffff) + temp3; if (fnLmL < 0) { Res2 = ~Res2; if (Res0 == 0) Res2++; else Res0 = (~Res0) + 1; } if (sh2->sr & S) { Res0 = sh2->macl + Res0; if (sh2->macl > Res0) Res2++; Res2 += (sh2->mach & 0x0000ffff); if (((INT32) Res2 < 0) && (Res2 < 0xffff8000)) { Res2 = 0x00008000; Res0 = 0x00000000; } else if (((INT32) Res2 > 0) && (Res2 > 0x00007fff)) { Res2 = 0x00007fff; Res0 = 0xffffffff; } sh2->mach = Res2; sh2->macl = Res0; } else { Res0 = sh2->macl + Res0; if (sh2->macl > Res0) Res2++; Res2 += sh2->mach; sh2->mach = Res2; sh2->macl = Res0; } sh2->sh2_icount -= 2; } /* MAC.W @Rm+,@Rn+ */ INLINE void MAC_W(UINT32 m, UINT32 n) {{ INT32 tempm, tempn, dest, src, ans; UINT32 templ; tempn = (INT32) RW( sh2->r[n] ); sh2->r[n] += 2; tempm = (INT32) RW( sh2->r[m] ); sh2->r[m] += 2; templ = sh2->macl; tempm = ((INT32) (short) tempn * (INT32) (short) tempm); if ((INT32) sh2->macl >= 0) dest = 0; else dest = 1; if ((INT32) tempm >= 0) { src = 0; tempn = 0; } else { src = 1; tempn = 0xffffffff; } src += dest; sh2->macl += tempm; if ((INT32) sh2->macl >= 0) ans = 0; else ans = 1; ans += dest; if (sh2->sr & S) { if (ans == 1) { if (src == 0) sh2->macl = 0x7fffffff; if (src == 2) sh2->macl = 0x80000000; } } else { sh2->mach += tempn; if (templ > sh2->macl) sh2->mach += 1; } sh2->sh2_icount -= 2; }} /* MOV Rm,Rn */ INLINE void MOV(UINT32 m, UINT32 n) { sh2->r[n] = sh2->r[m]; } /* MOV.B Rm,@Rn */ INLINE void MOVBS(UINT32 m, UINT32 n) { sh2->ea = sh2->r[n]; WB( sh2->ea, sh2->r[m] & 0x000000ff); } /* MOV.W Rm,@Rn */ INLINE void MOVWS(UINT32 m, UINT32 n) { sh2->ea = sh2->r[n]; WW( sh2->ea, sh2->r[m] & 0x0000ffff); } /* MOV.L Rm,@Rn */ INLINE void MOVLS(UINT32 m, UINT32 n) { sh2->ea = sh2->r[n]; WL( sh2->ea, sh2->r[m] ); } /* MOV.B @Rm,Rn */ INLINE void MOVBL(UINT32 m, UINT32 n) { sh2->ea = sh2->r[m]; sh2->r[n] = (UINT32)(INT32)(INT16)(INT8) RB( sh2->ea ); } /* MOV.W @Rm,Rn */ INLINE void MOVWL(UINT32 m, UINT32 n) { sh2->ea = sh2->r[m]; sh2->r[n] = (UINT32)(INT32)(INT16) RW( sh2->ea ); } /* MOV.L @Rm,Rn */ INLINE void MOVLL(UINT32 m, UINT32 n) { sh2->ea = sh2->r[m]; sh2->r[n] = RL( sh2->ea ); } /* MOV.B Rm,@-Rn */ INLINE void MOVBM(UINT32 m, UINT32 n) { /* SMG : bug fix, was reading sh2->r[n] */ UINT32 data = sh2->r[m] & 0x000000ff; sh2->r[n] -= 1; WB( sh2->r[n], data ); } /* MOV.W Rm,@-Rn */ INLINE void MOVWM(UINT32 m, UINT32 n) { UINT32 data = sh2->r[m] & 0x0000ffff; sh2->r[n] -= 2; WW( sh2->r[n], data ); } /* MOV.L Rm,@-Rn */ INLINE void MOVLM(UINT32 m, UINT32 n) { UINT32 data = sh2->r[m]; sh2->r[n] -= 4; WL( sh2->r[n], data ); } /* MOV.B @Rm+,Rn */ INLINE void MOVBP(UINT32 m, UINT32 n) { sh2->r[n] = (UINT32)(INT32)(INT16)(INT8) RB( sh2->r[m] ); if (n != m) sh2->r[m] += 1; } /* MOV.W @Rm+,Rn */ INLINE void MOVWP(UINT32 m, UINT32 n) { sh2->r[n] = (UINT32)(INT32)(INT16) RW( sh2->r[m] ); if (n != m) sh2->r[m] += 2; } /* MOV.L @Rm+,Rn */ INLINE void MOVLP(UINT32 m, UINT32 n) { sh2->r[n] = RL( sh2->r[m] ); if (n != m) sh2->r[m] += 4; } /* MOV.B Rm,@(R0,Rn) */ INLINE void MOVBS0(UINT32 m, UINT32 n) { sh2->ea = sh2->r[n] + sh2->r[0]; WB( sh2->ea, sh2->r[m] & 0x000000ff ); } /* MOV.W Rm,@(R0,Rn) */ INLINE void MOVWS0(UINT32 m, UINT32 n) { sh2->ea = sh2->r[n] + sh2->r[0]; WW( sh2->ea, sh2->r[m] & 0x0000ffff ); } /* MOV.L Rm,@(R0,Rn) */ INLINE void MOVLS0(UINT32 m, UINT32 n) { sh2->ea = sh2->r[n] + sh2->r[0]; WL( sh2->ea, sh2->r[m] ); } /* MOV.B @(R0,Rm),Rn */ INLINE void MOVBL0(UINT32 m, UINT32 n) { sh2->ea = sh2->r[m] + sh2->r[0]; sh2->r[n] = (UINT32)(INT32)(INT16)(INT8) RB( sh2->ea ); } /* MOV.W @(R0,Rm),Rn */ INLINE void MOVWL0(UINT32 m, UINT32 n) { sh2->ea = sh2->r[m] + sh2->r[0]; sh2->r[n] = (UINT32)(INT32)(INT16) RW( sh2->ea ); } /* MOV.L @(R0,Rm),Rn */ INLINE void MOVLL0(UINT32 m, UINT32 n) { sh2->ea = sh2->r[m] + sh2->r[0]; sh2->r[n] = RL( sh2->ea ); } /* MOV #imm,Rn */ INLINE void MOVI(UINT32 i, UINT32 n) { sh2->r[n] = (UINT32)(INT32)(INT16)(INT8) i; } /* MOV.W @(disp8,PC),Rn */ INLINE void MOVWI(UINT32 d, UINT32 n) { UINT32 disp = d & 0xff; sh2->ea = sh2->pc + disp * 2 + 2; sh2->r[n] = (UINT32)(INT32)(INT16) RW( sh2->ea ); } /* MOV.L @(disp8,PC),Rn */ INLINE void MOVLI(UINT32 d, UINT32 n) { UINT32 disp = d & 0xff; sh2->ea = ((sh2->pc + 2) & ~3) + disp * 4; sh2->r[n] = RL( sh2->ea ); } /* MOV.B @(disp8,GBR),R0 */ INLINE void MOVBLG(UINT32 d) { UINT32 disp = d & 0xff; sh2->ea = sh2->gbr + disp; sh2->r[0] = (UINT32)(INT32)(INT16)(INT8) RB( sh2->ea ); } /* MOV.W @(disp8,GBR),R0 */ INLINE void MOVWLG(UINT32 d) { UINT32 disp = d & 0xff; sh2->ea = sh2->gbr + disp * 2; sh2->r[0] = (INT32)(INT16) RW( sh2->ea ); } /* MOV.L @(disp8,GBR),R0 */ INLINE void MOVLLG(UINT32 d) { UINT32 disp = d & 0xff; sh2->ea = sh2->gbr + disp * 4; sh2->r[0] = RL( sh2->ea ); } /* MOV.B R0,@(disp8,GBR) */ INLINE void MOVBSG(UINT32 d) { UINT32 disp = d & 0xff; sh2->ea = sh2->gbr + disp; WB( sh2->ea, sh2->r[0] & 0x000000ff ); } /* MOV.W R0,@(disp8,GBR) */ INLINE void MOVWSG(UINT32 d) { UINT32 disp = d & 0xff; sh2->ea = sh2->gbr + disp * 2; WW( sh2->ea, sh2->r[0] & 0x0000ffff ); } /* MOV.L R0,@(disp8,GBR) */ INLINE void MOVLSG(UINT32 d) { UINT32 disp = d & 0xff; sh2->ea = sh2->gbr + disp * 4; WL( sh2->ea, sh2->r[0] ); } /* MOV.B R0,@(disp4,Rn) */ INLINE void MOVBS4(UINT32 d, UINT32 n) { UINT32 disp = d & 0x0f; sh2->ea = sh2->r[n] + disp; WB( sh2->ea, sh2->r[0] & 0x000000ff ); } /* MOV.W R0,@(disp4,Rn) */ INLINE void MOVWS4(UINT32 d, UINT32 n) { UINT32 disp = d & 0x0f; sh2->ea = sh2->r[n] + disp * 2; WW( sh2->ea, sh2->r[0] & 0x0000ffff ); } /* MOV.L Rm,@(disp4,Rn) */ INLINE void MOVLS4(UINT32 m, UINT32 d, UINT32 n) { UINT32 disp = d & 0x0f; sh2->ea = sh2->r[n] + disp * 4; WL( sh2->ea, sh2->r[m] ); } /* MOV.B @(disp4,Rm),R0 */ INLINE void MOVBL4(UINT32 m, UINT32 d) { UINT32 disp = d & 0x0f; sh2->ea = sh2->r[m] + disp; sh2->r[0] = (UINT32)(INT32)(INT16)(INT8) RB( sh2->ea ); } /* MOV.W @(disp4,Rm),R0 */ INLINE void MOVWL4(UINT32 m, UINT32 d) { UINT32 disp = d & 0x0f; sh2->ea = sh2->r[m] + disp * 2; sh2->r[0] = (UINT32)(INT32)(INT16) RW( sh2->ea ); } /* MOV.L @(disp4,Rm),Rn */ INLINE void MOVLL4(UINT32 m, UINT32 d, UINT32 n) { UINT32 disp = d & 0x0f; sh2->ea = sh2->r[m] + disp * 4; sh2->r[n] = RL( sh2->ea ); } /* MOVA @(disp8,PC),R0 */ INLINE void MOVA(UINT32 d) { UINT32 disp = d & 0xff; sh2->ea = ((sh2->pc + 2) & ~3) + disp * 4; sh2->r[0] = sh2->ea; } /* MOVT Rn */ INLINE void MOVT(UINT32 n) { sh2->r[n] = sh2->sr & T; } /* MUL.L Rm,Rn */ INLINE void MULL(UINT32 m, UINT32 n) { sh2->macl = sh2->r[n] * sh2->r[m]; sh2->sh2_icount--; } /* MULS Rm,Rn */ INLINE void MULS(UINT32 m, UINT32 n) { sh2->macl = (INT16) sh2->r[n] * (INT16) sh2->r[m]; } /* MULU Rm,Rn */ INLINE void MULU(UINT32 m, UINT32 n) { sh2->macl = (UINT16) sh2->r[n] * (UINT16) sh2->r[m]; } /* NEG Rm,Rn */ INLINE void NEG(UINT32 m, UINT32 n) { sh2->r[n] = 0 - sh2->r[m]; } /* NEGC Rm,Rn */ INLINE void NEGC(UINT32 m, UINT32 n) { UINT32 temp; temp = sh2->r[m]; sh2->r[n] = -temp - (sh2->sr & T); if (temp || (sh2->sr & T)) sh2->sr |= T; else sh2->sr &= ~T; } /* NOP */ INLINE void NOP(void) { } /* NOT Rm,Rn */ INLINE void NOT(UINT32 m, UINT32 n) { sh2->r[n] = ~sh2->r[m]; } /* OR Rm,Rn */ INLINE void OR(UINT32 m, UINT32 n) { sh2->r[n] |= sh2->r[m]; } /* OR #imm,R0 */ INLINE void ORI(UINT32 i) { sh2->r[0] |= i; sh2->sh2_icount -= 2; } /* OR.B #imm,@(R0,GBR) */ INLINE void ORM(UINT32 i) { UINT32 temp; sh2->ea = sh2->gbr + sh2->r[0]; temp = RB( sh2->ea ); temp |= i; WB( sh2->ea, temp ); } /* ROTCL Rn */ INLINE void ROTCL(UINT32 n) { UINT32 temp; temp = (sh2->r[n] >> 31) & T; sh2->r[n] = (sh2->r[n] << 1) | (sh2->sr & T); sh2->sr = (sh2->sr & ~T) | temp; } /* ROTCR Rn */ INLINE void ROTCR(UINT32 n) { UINT32 temp; temp = (sh2->sr & T) << 31; if (sh2->r[n] & T) sh2->sr |= T; else sh2->sr &= ~T; sh2->r[n] = (sh2->r[n] >> 1) | temp; } /* ROTL Rn */ INLINE void ROTL(UINT32 n) { sh2->sr = (sh2->sr & ~T) | ((sh2->r[n] >> 31) & T); sh2->r[n] = (sh2->r[n] << 1) | (sh2->r[n] >> 31); } /* ROTR Rn */ INLINE void ROTR(UINT32 n) { sh2->sr = (sh2->sr & ~T) | (sh2->r[n] & T); sh2->r[n] = (sh2->r[n] >> 1) | (sh2->r[n] << 31); } /* RTE */ INLINE void RTE(void) { sh2->ea = sh2->r[15]; sh2->delay = sh2->pc; sh2->pc = RL( sh2->ea ); sh2->r[15] += 4; sh2->ea = sh2->r[15]; sh2->sr = RL( sh2->ea ) & FLAGS; sh2->r[15] += 4; sh2->sh2_icount -= 3; sh2->test_irq = 1; } /* RTS */ INLINE void RTS(void) { sh2->delay = sh2->pc; sh2->pc = sh2->ea = sh2->pr; sh2->sh2_icount--; } /* SETT */ INLINE void SETT(void) { sh2->sr |= T; } /* SHAL Rn (same as SHLL) */ INLINE void SHAL(UINT32 n) { sh2->sr = (sh2->sr & ~T) | ((sh2->r[n] >> 31) & T); sh2->r[n] <<= 1; } /* SHAR Rn */ INLINE void SHAR(UINT32 n) { sh2->sr = (sh2->sr & ~T) | (sh2->r[n] & T); sh2->r[n] = (UINT32)((INT32)sh2->r[n] >> 1); } /* SHLL Rn (same as SHAL) */ INLINE void SHLL(UINT32 n) { sh2->sr = (sh2->sr & ~T) | ((sh2->r[n] >> 31) & T); sh2->r[n] <<= 1; } /* SHLL2 Rn */ INLINE void SHLL2(UINT32 n) { sh2->r[n] <<= 2; } /* SHLL8 Rn */ INLINE void SHLL8(UINT32 n) { sh2->r[n] <<= 8; } /* SHLL16 Rn */ INLINE void SHLL16(UINT32 n) { sh2->r[n] <<= 16; } /* SHLR Rn */ INLINE void SHLR(UINT32 n) { sh2->sr = (sh2->sr & ~T) | (sh2->r[n] & T); sh2->r[n] >>= 1; } /* SHLR2 Rn */ INLINE void SHLR2(UINT32 n) { sh2->r[n] >>= 2; } /* SHLR8 Rn */ INLINE void SHLR8(UINT32 n) { sh2->r[n] >>= 8; } /* SHLR16 Rn */ INLINE void SHLR16(UINT32 n) { sh2->r[n] >>= 16; } /* SLEEP */ INLINE void SLEEP(void) { sh2->pc -= 2; sh2->sh2_icount -= 2; /* Wait_for_exception; */ } /* STC SR,Rn */ INLINE void STCSR(UINT32 n) { sh2->r[n] = sh2->sr; } /* STC GBR,Rn */ INLINE void STCGBR(UINT32 n) { sh2->r[n] = sh2->gbr; } /* STC VBR,Rn */ INLINE void STCVBR(UINT32 n) { sh2->r[n] = sh2->vbr; } /* STC.L SR,@-Rn */ INLINE void STCMSR(UINT32 n) { sh2->r[n] -= 4; sh2->ea = sh2->r[n]; WL( sh2->ea, sh2->sr ); sh2->sh2_icount--; } /* STC.L GBR,@-Rn */ INLINE void STCMGBR(UINT32 n) { sh2->r[n] -= 4; sh2->ea = sh2->r[n]; WL( sh2->ea, sh2->gbr ); sh2->sh2_icount--; } /* STC.L VBR,@-Rn */ INLINE void STCMVBR(UINT32 n) { sh2->r[n] -= 4; sh2->ea = sh2->r[n]; WL( sh2->ea, sh2->vbr ); sh2->sh2_icount--; } /* STS MACH,Rn */ INLINE void STSMACH(UINT32 n) { sh2->r[n] = sh2->mach; } /* STS MACL,Rn */ INLINE void STSMACL(UINT32 n) { sh2->r[n] = sh2->macl; } /* STS PR,Rn */ INLINE void STSPR(UINT32 n) { sh2->r[n] = sh2->pr; } /* STS.L MACH,@-Rn */ INLINE void STSMMACH(UINT32 n) { sh2->r[n] -= 4; sh2->ea = sh2->r[n]; WL( sh2->ea, sh2->mach ); } /* STS.L MACL,@-Rn */ INLINE void STSMMACL(UINT32 n) { sh2->r[n] -= 4; sh2->ea = sh2->r[n]; WL( sh2->ea, sh2->macl ); } /* STS.L PR,@-Rn */ INLINE void STSMPR(UINT32 n) { sh2->r[n] -= 4; sh2->ea = sh2->r[n]; WL( sh2->ea, sh2->pr ); } /* SUB Rm,Rn */ INLINE void SUB(UINT32 m, UINT32 n) { sh2->r[n] -= sh2->r[m]; } /* SUBC Rm,Rn */ INLINE void SUBC(UINT32 m, UINT32 n) { UINT32 tmp0, tmp1; tmp1 = sh2->r[n] - sh2->r[m]; tmp0 = sh2->r[n]; sh2->r[n] = tmp1 - (sh2->sr & T); if (tmp0 < tmp1) sh2->sr |= T; else sh2->sr &= ~T; if (tmp1 < sh2->r[n]) sh2->sr |= T; } /* SUBV Rm,Rn */ INLINE void SUBV(UINT32 m, UINT32 n) { INT32 dest, src, ans; if ((INT32) sh2->r[n] >= 0) dest = 0; else dest = 1; if ((INT32) sh2->r[m] >= 0) src = 0; else src = 1; src += dest; sh2->r[n] -= sh2->r[m]; if ((INT32) sh2->r[n] >= 0) ans = 0; else ans = 1; ans += dest; if (src == 1) { if (ans == 1) sh2->sr |= T; else sh2->sr &= ~T; } else sh2->sr &= ~T; } /* SWAP.B Rm,Rn */ INLINE void SWAPB(UINT32 m, UINT32 n) { UINT32 temp0, temp1; temp0 = sh2->r[m] & 0xffff0000; temp1 = (sh2->r[m] & 0x000000ff) << 8; sh2->r[n] = (sh2->r[m] >> 8) & 0x000000ff; sh2->r[n] = sh2->r[n] | temp1 | temp0; } /* SWAP.W Rm,Rn */ INLINE void SWAPW(UINT32 m, UINT32 n) { UINT32 temp; temp = (sh2->r[m] >> 16) & 0x0000ffff; sh2->r[n] = (sh2->r[m] << 16) | temp; } /* TAS.B @Rn */ INLINE void TAS(UINT32 n) { UINT32 temp; sh2->ea = sh2->r[n]; /* Bus Lock enable */ temp = RB( sh2->ea ); if (temp == 0) sh2->sr |= T; else sh2->sr &= ~T; temp |= 0x80; /* Bus Lock disable */ WB( sh2->ea, temp ); sh2->sh2_icount -= 3; } /* TRAPA #imm */ INLINE void TRAPA(UINT32 i) { UINT32 imm = i & 0xff; sh2->ea = sh2->vbr + imm * 4; sh2->r[15] -= 4; WL( sh2->r[15], sh2->sr ); sh2->r[15] -= 4; WL( sh2->r[15], sh2->pc ); sh2->pc = RL( sh2->ea ); change_pc(sh2->pc & AM); sh2->sh2_icount -= 7; } /* TST Rm,Rn */ INLINE void TST(UINT32 m, UINT32 n) { if ((sh2->r[n] & sh2->r[m]) == 0) sh2->sr |= T; else sh2->sr &= ~T; } /* TST #imm,R0 */ INLINE void TSTI(UINT32 i) { UINT32 imm = i & 0xff; if ((imm & sh2->r[0]) == 0) sh2->sr |= T; else sh2->sr &= ~T; } /* TST.B #imm,@(R0,GBR) */ INLINE void TSTM(UINT32 i) { UINT32 imm = i & 0xff; sh2->ea = sh2->gbr + sh2->r[0]; if ((imm & RB( sh2->ea )) == 0) sh2->sr |= T; else sh2->sr &= ~T; sh2->sh2_icount -= 2; } /* XOR Rm,Rn */ INLINE void XOR(UINT32 m, UINT32 n) { sh2->r[n] ^= sh2->r[m]; } /* XOR #imm,R0 */ INLINE void XORI(UINT32 i) { UINT32 imm = i & 0xff; sh2->r[0] ^= imm; } /* XOR.B #imm,@(R0,GBR) */ INLINE void XORM(UINT32 i) { UINT32 imm = i & 0xff; UINT32 temp; sh2->ea = sh2->gbr + sh2->r[0]; temp = RB( sh2->ea ); temp ^= imm; WB( sh2->ea, temp ); sh2->sh2_icount -= 2; } /* XTRCT Rm,Rn */ INLINE void XTRCT(UINT32 m, UINT32 n) { UINT32 temp; temp = (sh2->r[m] << 16) & 0xffff0000; sh2->r[n] = (sh2->r[n] >> 16) & 0x0000ffff; sh2->r[n] |= temp; } /***************************************************************************** * OPCODE DISPATCHERS *****************************************************************************/ INLINE void op0000(UINT16 opcode) { switch (opcode & 0x3F) { case 0x00: NOP(); break; case 0x01: NOP(); break; case 0x02: STCSR(Rn); break; case 0x03: BSRF(Rn); break; case 0x04: MOVBS0(Rm, Rn); break; case 0x05: MOVWS0(Rm, Rn); break; case 0x06: MOVLS0(Rm, Rn); break; case 0x07: MULL(Rm, Rn); break; case 0x08: CLRT(); break; case 0x09: NOP(); break; case 0x0a: STSMACH(Rn); break; case 0x0b: RTS(); break; case 0x0c: MOVBL0(Rm, Rn); break; case 0x0d: MOVWL0(Rm, Rn); break; case 0x0e: MOVLL0(Rm, Rn); break; case 0x0f: MAC_L(Rm, Rn); break; case 0x10: NOP(); break; case 0x11: NOP(); break; case 0x12: STCGBR(Rn); break; case 0x13: NOP(); break; case 0x14: MOVBS0(Rm, Rn); break; case 0x15: MOVWS0(Rm, Rn); break; case 0x16: MOVLS0(Rm, Rn); break; case 0x17: MULL(Rm, Rn); break; case 0x18: SETT(); break; case 0x19: DIV0U(); break; case 0x1a: STSMACL(Rn); break; case 0x1b: SLEEP(); break; case 0x1c: MOVBL0(Rm, Rn); break; case 0x1d: MOVWL0(Rm, Rn); break; case 0x1e: MOVLL0(Rm, Rn); break; case 0x1f: MAC_L(Rm, Rn); break; case 0x20: NOP(); break; case 0x21: NOP(); break; case 0x22: STCVBR(Rn); break; case 0x23: BRAF(Rn); break; case 0x24: MOVBS0(Rm, Rn); break; case 0x25: MOVWS0(Rm, Rn); break; case 0x26: MOVLS0(Rm, Rn); break; case 0x27: MULL(Rm, Rn); break; case 0x28: CLRMAC(); break; case 0x29: MOVT(Rn); break; case 0x2a: STSPR(Rn); break; case 0x2b: RTE(); break; case 0x2c: MOVBL0(Rm, Rn); break; case 0x2d: MOVWL0(Rm, Rn); break; case 0x2e: MOVLL0(Rm, Rn); break; case 0x2f: MAC_L(Rm, Rn); break; case 0x30: NOP(); break; case 0x31: NOP(); break; case 0x32: NOP(); break; case 0x33: NOP(); break; case 0x34: MOVBS0(Rm, Rn); break; case 0x35: MOVWS0(Rm, Rn); break; case 0x36: MOVLS0(Rm, Rn); break; case 0x37: MULL(Rm, Rn); break; case 0x38: NOP(); break; case 0x39: NOP(); break; case 0x3a: NOP(); break; case 0x3b: NOP(); break; case 0x3c: MOVBL0(Rm, Rn); break; case 0x3d: MOVWL0(Rm, Rn); break; case 0x3e: MOVLL0(Rm, Rn); break; case 0x3f: MAC_L(Rm, Rn); break; } } INLINE void op0001(UINT16 opcode) { MOVLS4(Rm, opcode & 0x0f, Rn); } INLINE void op0010(UINT16 opcode) { switch (opcode & 15) { case 0: MOVBS(Rm, Rn); break; case 1: MOVWS(Rm, Rn); break; case 2: MOVLS(Rm, Rn); break; case 3: NOP(); break; case 4: MOVBM(Rm, Rn); break; case 5: MOVWM(Rm, Rn); break; case 6: MOVLM(Rm, Rn); break; case 7: DIV0S(Rm, Rn); break; case 8: TST(Rm, Rn); break; case 9: AND(Rm, Rn); break; case 10: XOR(Rm, Rn); break; case 11: OR(Rm, Rn); break; case 12: CMPSTR(Rm, Rn); break; case 13: XTRCT(Rm, Rn); break; case 14: MULU(Rm, Rn); break; case 15: MULS(Rm, Rn); break; } } INLINE void op0011(UINT16 opcode) { switch (opcode & 15) { case 0: CMPEQ(Rm, Rn); break; case 1: NOP(); break; case 2: CMPHS(Rm, Rn); break; case 3: CMPGE(Rm, Rn); break; case 4: DIV1(Rm, Rn); break; case 5: DMULU(Rm, Rn); break; case 6: CMPHI(Rm, Rn); break; case 7: CMPGT(Rm, Rn); break; case 8: SUB(Rm, Rn); break; case 9: NOP(); break; case 10: SUBC(Rm, Rn); break; case 11: SUBV(Rm, Rn); break; case 12: ADD(Rm, Rn); break; case 13: DMULS(Rm, Rn); break; case 14: ADDC(Rm, Rn); break; case 15: ADDV(Rm, Rn); break; } } INLINE void op0100(UINT16 opcode) { switch (opcode & 0x3F) { case 0x00: SHLL(Rn); break; case 0x01: SHLR(Rn); break; case 0x02: STSMMACH(Rn); break; case 0x03: STCMSR(Rn); break; case 0x04: ROTL(Rn); break; case 0x05: ROTR(Rn); break; case 0x06: LDSMMACH(Rn); break; case 0x07: LDCMSR(Rn); break; case 0x08: SHLL2(Rn); break; case 0x09: SHLR2(Rn); break; case 0x0a: LDSMACH(Rn); break; case 0x0b: JSR(Rn); break; case 0x0c: NOP(); break; case 0x0d: NOP(); break; case 0x0e: LDCSR(Rn); break; case 0x0f: MAC_W(Rm, Rn); break; case 0x10: DT(Rn); break; case 0x11: CMPPZ(Rn); break; case 0x12: STSMMACL(Rn); break; case 0x13: STCMGBR(Rn); break; case 0x14: NOP(); break; case 0x15: CMPPL(Rn); break; case 0x16: LDSMMACL(Rn); break; case 0x17: LDCMGBR(Rn); break; case 0x18: SHLL8(Rn); break; case 0x19: SHLR8(Rn); break; case 0x1a: LDSMACL(Rn); break; case 0x1b: TAS(Rn); break; case 0x1c: NOP(); break; case 0x1d: NOP(); break; case 0x1e: LDCGBR(Rn); break; case 0x1f: MAC_W(Rm, Rn); break; case 0x20: SHAL(Rn); break; case 0x21: SHAR(Rn); break; case 0x22: STSMPR(Rn); break; case 0x23: STCMVBR(Rn); break; case 0x24: ROTCL(Rn); break; case 0x25: ROTCR(Rn); break; case 0x26: LDSMPR(Rn); break; case 0x27: LDCMVBR(Rn); break; case 0x28: SHLL16(Rn); break; case 0x29: SHLR16(Rn); break; case 0x2a: LDSPR(Rn); break; case 0x2b: JMP(Rn); break; case 0x2c: NOP(); break; case 0x2d: NOP(); break; case 0x2e: LDCVBR(Rn); break; case 0x2f: MAC_W(Rm, Rn); break; case 0x30: NOP(); break; case 0x31: NOP(); break; case 0x32: NOP(); break; case 0x33: NOP(); break; case 0x34: NOP(); break; case 0x35: NOP(); break; case 0x36: NOP(); break; case 0x37: NOP(); break; case 0x38: NOP(); break; case 0x39: NOP(); break; case 0x3a: NOP(); break; case 0x3b: NOP(); break; case 0x3c: NOP(); break; case 0x3d: NOP(); break; case 0x3e: NOP(); break; case 0x3f: MAC_W(Rm, Rn); break; } } INLINE void op0101(UINT16 opcode) { MOVLL4(Rm, opcode & 0x0f, Rn); } INLINE void op0110(UINT16 opcode) { switch (opcode & 15) { case 0: MOVBL(Rm, Rn); break; case 1: MOVWL(Rm, Rn); break; case 2: MOVLL(Rm, Rn); break; case 3: MOV(Rm, Rn); break; case 4: MOVBP(Rm, Rn); break; case 5: MOVWP(Rm, Rn); break; case 6: MOVLP(Rm, Rn); break; case 7: NOT(Rm, Rn); break; case 8: SWAPB(Rm, Rn); break; case 9: SWAPW(Rm, Rn); break; case 10: NEGC(Rm, Rn); break; case 11: NEG(Rm, Rn); break; case 12: EXTUB(Rm, Rn); break; case 13: EXTUW(Rm, Rn); break; case 14: EXTSB(Rm, Rn); break; case 15: EXTSW(Rm, Rn); break; } } INLINE void op0111(UINT16 opcode) { ADDI(opcode & 0xff, Rn); } INLINE void op1000(UINT16 opcode) { switch ( opcode & (15<<8) ) { case 0 << 8: MOVBS4(opcode & 0x0f, Rm); break; case 1 << 8: MOVWS4(opcode & 0x0f, Rm); break; case 2<< 8: NOP(); break; case 3<< 8: NOP(); break; case 4<< 8: MOVBL4(Rm, opcode & 0x0f); break; case 5<< 8: MOVWL4(Rm, opcode & 0x0f); break; case 6<< 8: NOP(); break; case 7<< 8: NOP(); break; case 8<< 8: CMPIM(opcode & 0xff); break; case 9<< 8: BT(opcode & 0xff); break; case 10<< 8: NOP(); break; case 11<< 8: BF(opcode & 0xff); break; case 12<< 8: NOP(); break; case 13<< 8: BTS(opcode & 0xff); break; case 14<< 8: NOP(); break; case 15<< 8: BFS(opcode & 0xff); break; } } INLINE void op1001(UINT16 opcode) { MOVWI(opcode & 0xff, Rn); } INLINE void op1010(UINT16 opcode) { BRA(opcode & 0xfff); } INLINE void op1011(UINT16 opcode) { BSR(opcode & 0xfff); } INLINE void op1100(UINT16 opcode) { switch (opcode & (15<<8)) { case 0<<8: MOVBSG(opcode & 0xff); break; case 1<<8: MOVWSG(opcode & 0xff); break; case 2<<8: MOVLSG(opcode & 0xff); break; case 3<<8: TRAPA(opcode & 0xff); break; case 4<<8: MOVBLG(opcode & 0xff); break; case 5<<8: MOVWLG(opcode & 0xff); break; case 6<<8: MOVLLG(opcode & 0xff); break; case 7<<8: MOVA(opcode & 0xff); break; case 8<<8: TSTI(opcode & 0xff); break; case 9<<8: ANDI(opcode & 0xff); break; case 10<<8: XORI(opcode & 0xff); break; case 11<<8: ORI(opcode & 0xff); break; case 12<<8: TSTM(opcode & 0xff); break; case 13<<8: ANDM(opcode & 0xff); break; case 14<<8: XORM(opcode & 0xff); break; case 15<<8: ORM(opcode & 0xff); break; } } INLINE void op1101(UINT16 opcode) { MOVLI(opcode & 0xff, Rn); } INLINE void op1110(UINT16 opcode) { MOVI(opcode & 0xff, Rn); } INLINE void op1111(UINT16 /*opcode*/) { NOP(); } #endif // USE_JUMPTABLE /***************************************************************************** * MAME CPU INTERFACE *****************************************************************************/ static void sh2_timer_resync(void) { int divider = div_tab[(sh2->m[5] >> 8) & 3]; UINT32 cur_time = sh2_GetTotalCycles(); if(divider) sh2->frc += (cur_time - sh2->frc_base) >> divider; sh2->frc_base = cur_time; } static void sh2_timer_activate(void) { int max_delta = 0xfffff; UINT16 frc; //timer_adjust(sh2->timer, attotime_never, 0, attotime_zero); sh2->timer_active = 0; // sh2->timer_cycles = 0; frc = sh2->frc; if(!(sh2->m[4] & OCFA)) { UINT16 delta = sh2->ocra - frc; if(delta < max_delta) max_delta = delta; } if(!(sh2->m[4] & OCFB) && (sh2->ocra <= sh2->ocrb || !(sh2->m[4] & 0x010000))) { UINT16 delta = sh2->ocrb - frc; if(delta < max_delta) max_delta = delta; } if(!(sh2->m[4] & OVF) && !(sh2->m[4] & 0x010000)) { int delta = 0x10000 - frc; if(delta < max_delta) max_delta = delta; } if(max_delta != 0xfffff) { int divider = div_tab[(sh2->m[5] >> 8) & 3]; if(divider) { max_delta <<= divider; sh2->frc_base = sh2_GetTotalCycles(); //timer_adjust(sh2->timer, ATTOTIME_IN_CYCLES(max_delta, sh2->cpu_number), sh2->cpu_number, attotime_zero); //bprintf(0, _T("SH2 Timer Actived %d\n"), max_delta); sh2->timer_active = 1; sh2->timer_cycles = max_delta; sh2->timer_base = sh2->frc_base; } else { // logerror("SH2.%d: Timer event in %d cycles of external clock", sh2->cpu_number, max_delta); //bprintf(0, _T("SH2.0: Timer event in %d cycles of external clock\n"), max_delta); } } } static void sh2_recalc_irq(void) { int irq = 0, vector = -1; int level; // Timer irqs if((sh2->m[4]>>8) & sh2->m[4] & (ICF|OCFA|OCFB|OVF)) { level = (sh2->m[0x18] >> 24) & 15; if(level > irq) { int mask = (sh2->m[4]>>8) & sh2->m[4]; irq = level; if(mask & ICF) vector = (sh2->m[0x19] >> 8) & 0x7f; else if(mask & (OCFA|OCFB)) vector = sh2->m[0x19] & 0x7f; else vector = (sh2->m[0x1a] >> 24) & 0x7f; } } // DMA irqs if((sh2->m[0x63] & 6) == 6) { level = (sh2->m[0x38] >> 8) & 15; if(level > irq) { irq = level; vector = (sh2->m[0x68] >> 24) & 0x7f; } } if((sh2->m[0x67] & 6) == 6) { level = (sh2->m[0x38] >> 8) & 15; if(level > irq) { irq = level; vector = (sh2->m[0x6a] >> 24) & 0x7f; } } sh2->internal_irq_level = irq; sh2->internal_irq_vector = vector; sh2->test_irq = 1; } static void sh2_timer_callback() { UINT16 frc; // int cpunum = param; // cpuintrf_push_context(cpunum); sh2_timer_resync(); frc = sh2->frc; if(frc == sh2->ocrb) sh2->m[4] |= OCFB; if(frc == 0x0000) sh2->m[4] |= OVF; if(frc == sh2->ocra) { sh2->m[4] |= OCFA; if(sh2->m[4] & 0x010000) sh2->frc = 0; } sh2_recalc_irq(); sh2_timer_activate(); // cpuintrf_pop_context(); } static void sh2_dmac_callback(int dma) { // cpuintrf_push_context(cpunum); // LOG(("SH2.%d: DMA %d complete\n", cpunum, dma)); // bprintf(0, _T("SH2: DMA %d complete at %d\n"), dma, sh2_GetTotalCycles()); sh2->m[0x63+4*dma] |= 2; sh2->dma_timer_active[dma] = 0; sh2_recalc_irq(); // cpuintrf_pop_context(); } static void sh2_dmac_check(int dma) { if(sh2->m[0x63+4*dma] & sh2->m[0x6c] & 1) { if(!sh2->dma_timer_active[dma] && !(sh2->m[0x63+4*dma] & 2)) { int incs, incd, size; UINT32 src, dst, count; incd = (sh2->m[0x63+4*dma] >> 14) & 3; incs = (sh2->m[0x63+4*dma] >> 12) & 3; size = (sh2->m[0x63+4*dma] >> 10) & 3; if(incd == 3 || incs == 3) { // logerror("SH2: DMA: bad increment values (%d, %d, %d, %04x)\n", incd, incs, size, sh2->m[0x63+4*dma]); //bprintf(0, _T("SH2: DMA: bad increment values (%d, %d, %d, %04x)\n"), incd, incs, size, sh2->m[0x63+4*dma]); return; } src = sh2->m[0x60+4*dma]; dst = sh2->m[0x61+4*dma]; count = sh2->m[0x62+4*dma]; if(!count) count = 0x1000000; // LOG(("SH2: DMA %d start %x, %x, %x, %04x, %d, %d, %d\n", dma, src, dst, count, sh2->m[0x63+4*dma], incs, incd, size)); //bprintf(1, _T("DMA %d start %08x, %08x, %x, %04x, %d, %d, %d : %d cys from %d\n"), dma, src, dst, count, sh2->m[0x63+4*dma], incs, incd, size, 2*count+1, Sh2GetTotalCycles()); sh2->dma_timer_active[dma] = 1; //timer_adjust(sh2->dma_timer[dma], ATTOTIME_IN_CYCLES(2*count+1, sh2->cpu_number), (sh2->cpu_number<<1)|dma, attotime_zero); sh2->dma_timer_cycles[dma] = 2 * count + 1; sh2->dma_timer_base[dma] = sh2_GetTotalCycles(); src &= AM; dst &= AM; switch(size) { case 0: for(;count > 0; count --) { if(incs == 2) src --; if(incd == 2) dst --; program_write_byte_32be(dst, program_read_byte_32be(src)); if(incs == 1) src ++; if(incd == 1) dst ++; } break; case 1: src &= ~1; dst &= ~1; for(;count > 0; count --) { if(incs == 2) src -= 2; if(incd == 2) dst -= 2; program_write_word_32be(dst, program_read_word_32be(src)); if(incs == 1) src += 2; if(incd == 1) dst += 2; } break; case 2: src &= ~3; dst &= ~3; for(;count > 0; count --) { if(incs == 2) src -= 4; if(incd == 2) dst -= 4; //program_write_dword_32be(dst, program_read_dword_32be(src)); WL(dst, RL(src)); if(incs == 1) src += 4; if(incd == 1) dst += 4; } break; case 3: src &= ~3; dst &= ~3; count &= ~3; for(;count > 0; count -= 4) { if(incd == 2) dst -= 16; program_write_dword_32be(dst, program_read_dword_32be(src)); program_write_dword_32be(dst+4, program_read_dword_32be(src+4)); program_write_dword_32be(dst+8, program_read_dword_32be(src+8)); program_write_dword_32be(dst+12, program_read_dword_32be(src+12)); src += 16; if(incd == 1) dst += 16; } break; } } } else { if(sh2->dma_timer_active[dma]) { // logerror("SH2: DMA %d cancelled in-flight", dma); //bprintf(0, _T("SH2: DMA %d cancelled in-flight"), dma); //timer_adjust(sh2->dma_timer[dma], attotime_never, 0, attotime_zero); sh2->dma_timer_active[dma] = 0; } } } static void sh2_internal_w(UINT32 offset, UINT32 data, UINT32 mem_mask) { UINT32 old = sh2->m[offset]; COMBINE_DATA(sh2->m+offset); // if(offset != 0x20) // logerror("sh2_internal_w: Write %08x (%x), %08x @ %08x\n", 0xfffffe00+offset*4, offset, data, mem_mask); switch( offset ) { // Timers case 0x04: // TIER, FTCSR, FRC if((mem_mask & 0x00ffffff) != 0xffffff) sh2_timer_resync(); //logerror("SH2.%d: TIER write %04x @ %04x\n", sh2->cpu_number, data >> 16, mem_mask>>16); sh2->m[4] = (sh2->m[4] & ~(ICF|OCFA|OCFB|OVF)) | (old & sh2->m[4] & (ICF|OCFA|OCFB|OVF)); COMBINE_DATA(&sh2->frc); if((mem_mask & 0x00ffffff) != 0xffffff) sh2_timer_activate(); sh2_recalc_irq(); break; case 0x05: // OCRx, TCR, TOCR //logerror("SH2.%d: TCR write %08x @ %08x\n", sh2->cpu_number, data, mem_mask); sh2_timer_resync(); if(sh2->m[5] & 0x10) sh2->ocrb = (sh2->ocrb & (mem_mask >> 16)) | ((data & ~mem_mask) >> 16); else sh2->ocra = (sh2->ocra & (mem_mask >> 16)) | ((data & ~mem_mask) >> 16); sh2_timer_activate(); break; case 0x06: // ICR break; // Interrupt vectors case 0x18: // IPRB, VCRA case 0x19: // VCRB, VCRC case 0x1a: // VCRD sh2_recalc_irq(); break; // DMA case 0x1c: // DRCR0, DRCR1 break; // Watchdog case 0x20: // WTCNT, RSTCSR break; // Standby and cache case 0x24: // SBYCR, CCR break; // Interrupt vectors cont. case 0x38: // ICR, IRPA break; case 0x39: // VCRWDT break; // Division box case 0x40: // DVSR break; case 0x41: // DVDNT { INT32 a = sh2->m[0x41]; INT32 b = sh2->m[0x40]; // LOG(("SH2 #%d div+mod %d/%d\n", cpu_getactivecpu(), a, b)); if (b) { sh2->m[0x45] = a / b; sh2->m[0x44] = a % b; } else { sh2->m[0x42] |= 0x00010000; sh2->m[0x45] = 0x7fffffff; sh2->m[0x44] = 0x7fffffff; sh2_recalc_irq(); } break; } case 0x42: // DVCR sh2->m[0x42] = (sh2->m[0x42] & ~0x00001000) | (old & sh2->m[0x42] & 0x00010000); sh2_recalc_irq(); break; case 0x43: // VCRDIV sh2_recalc_irq(); break; case 0x44: // DVDNTH break; case 0x45: // DVDNTL { INT64 a = sh2->m[0x45] | ((UINT64)(sh2->m[0x44]) << 32); INT64 b = (INT32)sh2->m[0x40]; // LOG(("SH2 #%d div+mod %lld/%lld\n", cpu_getactivecpu(), a, b)); if (b) { INT64 q = a / b; if (q != (INT32)q) { sh2->m[0x42] |= 0x00010000; sh2->m[0x45] = 0x7fffffff; sh2->m[0x44] = 0x7fffffff; sh2_recalc_irq(); } else { sh2->m[0x45] = q; sh2->m[0x44] = a % b; } } else { sh2->m[0x42] |= 0x00010000; sh2->m[0x45] = 0x7fffffff; sh2->m[0x44] = 0x7fffffff; sh2_recalc_irq(); } break; } // DMA controller case 0x60: // SAR0 case 0x61: // DAR0 break; case 0x62: // DTCR0 sh2->m[0x62] &= 0xffffff; break; case 0x63: // CHCR0 sh2->m[0x63] = (sh2->m[0x63] & ~2) | (old & sh2->m[0x63] & 2); sh2_dmac_check(0); break; case 0x64: // SAR1 case 0x65: // DAR1 break; case 0x66: // DTCR1 sh2->m[0x66] &= 0xffffff; break; case 0x67: // CHCR1 sh2->m[0x67] = (sh2->m[0x67] & ~2) | (old & sh2->m[0x67] & 2); sh2_dmac_check(1); break; case 0x68: // VCRDMA0 case 0x6a: // VCRDMA1 sh2_recalc_irq(); break; case 0x6c: // DMAOR sh2->m[0x6c] = (sh2->m[0x6c] & ~6) | (old & sh2->m[0x6c] & 6); sh2_dmac_check(0); sh2_dmac_check(1); break; // Bus controller case 0x78: // BCR1 case 0x79: // BCR2 case 0x7a: // WCR case 0x7b: // MCR case 0x7c: // RTCSR case 0x7d: // RTCNT case 0x7e: // RTCOR break; default: //logerror("sh2_internal_w: Unmapped write %08x, %08x @ %08x\n", 0xfffffe00+offset*4, data, mem_mask); break; } } static UINT32 sh2_internal_r(UINT32 offset, UINT32 mem_mask) { // logerror("sh2_internal_r: Read %08x (%x) @ %08x\n", 0xfffffe00+offset*4, offset, mem_mask); //bprintf(0, _T("sh2_internal_r: Read %08x (%x) @ %08x\n"), 0xfffffe00+offset*4, offset, mem_mask); switch( offset ) { case 0x04: // TIER, FTCSR, FRC sh2_timer_resync(); return (sh2->m[4] & 0xffff0000) | sh2->frc; case 0x05: // OCRx, TCR, TOCR if(sh2->m[5] & 0x10) return (sh2->ocrb << 16) | (sh2->m[5] & 0xffff); else return (sh2->ocra << 16) | (sh2->m[5] & 0xffff); case 0x06: // ICR return sh2->icr << 16; case 0x38: // ICR, IPRA // return (sh2->m[0x38] & 0x7fffffff) | (sh2->nmi_line_state == ASSERT_LINE ? 0 : 0x80000000); return (sh2->m[0x38] & 0x7fffffff) | 0x80000000; case 0x78: // BCR1 // return sh2->is_slave ? 0x00008000 : 0; return 0; case 0x41: // dvdntl mirrors case 0x47: return sh2->m[0x45]; case 0x46: // dvdnth mirror return sh2->m[0x44]; } return sh2->m[offset]; } // ------------------------------------------------------- #if USE_JUMPTABLE int Sh2Run(int cycles) { sh2->sh2_icount = cycles; sh2->sh2_cycles_to_run = cycles; do { if ( pSh2Ext->suspend ) { sh2->sh2_icount = 0; break; } UINT16 opcode; if (sh2->delay) { //opcode = cpu_readop16(WORD_XOR_BE((UINT32)(sh2->delay & AM))); opcode = cpu_readop16(sh2->delay & AM); change_pc(sh2->pc & AM); sh2->delay = 0; } else { //opcode = cpu_readop16(WORD_XOR_BE((UINT32)(sh2->pc & AM))); opcode = cpu_readop16(sh2->pc & AM); sh2->pc += 2; } sh2->ppc = sh2->pc; opcode_jumptable[opcode](opcode); if(sh2->test_irq && !sh2->delay) { CHECK_PENDING_IRQ(/*"mame_sh2_execute"*/); sh2->test_irq = 0; } sh2->sh2_icount--; // timer check { unsigned int cy = sh2_GetTotalCycles(); if (sh2->dma_timer_active[0]) if ((cy - sh2->dma_timer_base[0]) >= sh2->dma_timer_cycles[0]) sh2_dmac_callback(0); if (sh2->dma_timer_active[1]) if ((cy - sh2->dma_timer_base[1]) >= sh2->dma_timer_cycles[1]) sh2_dmac_callback(1); if ( sh2->timer_active ) if ((cy - sh2->timer_base) >= sh2->timer_cycles) sh2_timer_callback(); } } while( sh2->sh2_icount > 0 ); sh2->cycle_counts += cycles - (UINT32)sh2->sh2_icount; return cycles - sh2->sh2_icount; } #else int Sh2Run(int cycles) { sh2->sh2_icount = cycles; sh2->sh2_cycles_to_run = cycles; do { if ( pSh2Ext->suspend ) { sh2->sh2_icount = 0; break; } UINT16 opcode; if (sh2->delay) { //opcode = cpu_readop16(WORD_XOR_BE((UINT32)(sh2->delay & AM))); opcode = cpu_readop16(sh2->delay & AM); change_pc(sh2->pc & AM); sh2->delay = 0; } else { //opcode = cpu_readop16(WORD_XOR_BE((UINT32)(sh2->pc & AM))); opcode = cpu_readop16(sh2->pc & AM); sh2->pc += 2; } sh2->ppc = sh2->pc; switch (opcode & ( 15 << 12)) { case 0<<12: op0000(opcode); break; case 1<<12: op0001(opcode); break; case 2<<12: op0010(opcode); break; case 3<<12: op0011(opcode); break; case 4<<12: op0100(opcode); break; case 5<<12: op0101(opcode); break; case 6<<12: op0110(opcode); break; case 7<<12: op0111(opcode); break; case 8<<12: op1000(opcode); break; case 9<<12: op1001(opcode); break; case 10<<12: op1010(opcode); break; case 11<<12: op1011(opcode); break; case 12<<12: op1100(opcode); break; case 13<<12: op1101(opcode); break; case 14<<12: op1110(opcode); break; default: op1111(opcode); break; } #endif if(sh2->test_irq && !sh2->delay) { CHECK_PENDING_IRQ(/*"mame_sh2_execute"*/); sh2->test_irq = 0; } sh2->sh2_icount--; // timer check { unsigned int cy = sh2_GetTotalCycles(); if (sh2->dma_timer_active[0]) if ((cy - sh2->dma_timer_base[0]) >= sh2->dma_timer_cycles[0]) sh2_dmac_callback(0); if (sh2->dma_timer_active[1]) if ((cy - sh2->dma_timer_base[1]) >= sh2->dma_timer_cycles[1]) sh2_dmac_callback(1); if ( sh2->timer_active ) if ((cy - sh2->timer_base) >= sh2->timer_cycles) sh2_timer_callback(); } } while( sh2->sh2_icount > 0 ); sh2->cycle_counts += cycles - (UINT32)sh2->sh2_icount; sh2->sh2_cycles_to_run = sh2->sh2_icount; return cycles - sh2->sh2_icount; } void Sh2SetIRQLine(const int line, const int state) { if (sh2->irq_line_state[line] == state) return; sh2->irq_line_state[line] = state; if( state == SH2_IRQSTATUS_NONE ) { // LOG(("SH-2 #%d cleared irq #%d\n", cpu_getactivecpu(), line)); sh2->pending_irq &= ~(1 << line); } else { //LOG(("SH-2 #%d assert irq #%d\n", cpu_getactivecpu(), line)); sh2->pending_irq |= 1 << line; if(sh2->delay) sh2->test_irq = 1; else CHECK_PENDING_IRQ(/*"sh2_set_irq_line"*/); pSh2Ext->suspend = 0; } } unsigned int Sh2GetPC(int) { return (sh2->delay) ? (sh2->delay & AM) : (sh2->pc & AM); } void Sh2SetVBR(unsigned int i) { sh2->vbr = i; } void Sh2BurnUntilInt(int) { pSh2Ext->suspend = 1; } void Sh2StopRun() { sh2->sh2_icount = 0; sh2->sh2_cycles_to_run = 0; } void __fastcall Sh2WriteByte(unsigned int a, unsigned char d) { WB(a, d); } unsigned char __fastcall Sh2ReadByte(unsigned int a) { return RB(a); } #include "state.h" int Sh2Scan(int nAction) { if (nAction & ACB_DRIVER_DATA) { char szText[] = "SH2 #0"; for (int i = 0; i < 1 /*nCPUCount*/; i++) { szText[5] = '1' + i; ScanVar(& ( Sh2Ext[i].sh2 ), sizeof(SH2) - 4, szText); SCAN_VAR (Sh2Ext[i].suspend); SCAN_VAR (Sh2Ext[i].opbase); #if FAST_OP_FETCH // Sh2Ext[i].opbase if (nAction & ACB_WRITE) { change_pc(sh2->pc & AM); } #endif } } return 0; }
22.869265
181
0.541898
ssilverm
d016c65b6c93c608d54d99c52c4a512c7f7617cd
6,369
hpp
C++
include/private/configuration.hpp
TetraSomia/liblapin
f5ee3ce9b0fff8459ec15d5e24287f2c16e5ae35
[ "BSD-3-Clause" ]
1
2021-06-14T19:26:42.000Z
2021-06-14T19:26:42.000Z
include/private/configuration.hpp
TetraSomia/liblapin
f5ee3ce9b0fff8459ec15d5e24287f2c16e5ae35
[ "BSD-3-Clause" ]
null
null
null
include/private/configuration.hpp
TetraSomia/liblapin
f5ee3ce9b0fff8459ec15d5e24287f2c16e5ae35
[ "BSD-3-Clause" ]
null
null
null
/* ** Jason Brillante "Damdoshi" ** Hanged Bunny Studio 2014-2016 ** ** ** Bibliotheque Lapin */ #ifndef __LAPIN_PRIVATE_CONFIGURATION_HPP__ # define __LAPIN_PRIVATE_CONFIGURATION_HPP__ # include <iomanip> # include <sstream> struct SmallConf; t_bunny_configuration *_bunny_read_ini(const char *code, t_bunny_configuration *config); t_bunny_configuration *_bunny_read_dabsic(const char *code, t_bunny_configuration *config); t_bunny_configuration *_bunny_read_xml(const char *code, t_bunny_configuration *config); t_bunny_configuration *_bunny_read_lua(const char *code, t_bunny_configuration *config); char *_bunny_write_ini(const t_bunny_configuration *config); char *_bunny_write_dabsic(const t_bunny_configuration *config); char *_bunny_write_xml(const t_bunny_configuration *config); char *_bunny_write_lua(const t_bunny_configuration *config); int chekchar(const char *str, ssize_t &index, const char *token); bool readchar(const char *str, ssize_t &index, const char *token); bool readtext(const char *str, ssize_t &index, const char *token); void skipspace(const char *str, ssize_t &i); bool readfield(const char *str, ssize_t &index); bool getfieldname(const char *code, ssize_t &i, char *out, ssize_t len, SmallConf &scope, bool overwrite); bool readdouble(const char *code, ssize_t &i, double &d); bool readinteger(const char *code, ssize_t &i, int &d); bool readstring(const char *code, ssize_t &i, char *d, ssize_t len); bool readrawchar(const char *code, ssize_t &i, char *d, ssize_t len, char endtok); bool readvalue(const char *code, ssize_t &i, SmallConf &nod, char endtok); int whichline(const char *code, int i); void writestring(std::stringstream &ss, std::string &str); bool read_data(const char *code, ssize_t &i, SmallConf &config); bool read_sequence(const char *code, ssize_t &i, SmallConf &config); bool read_function(const char *code, ssize_t &i, SmallConf &config); void writevalue(std::stringstream &ss, const SmallConf &cnf); extern const char *fieldname_first_char; extern const char *fieldname; extern const char *numbers; struct SmallConf { enum Type { INTEGER, DOUBLE, STRING, RAWSTRING }; std::map <std::string, SmallConf*> nodes; std::vector <SmallConf*> array; std::map< std::string, SmallConf* >::iterator iterator; std::string name; mutable bool have_value; mutable std::string original_value; mutable double converted; mutable int converted_2; mutable bool is_converted; static bool create_mode; SmallConf *father; Type last_type; void SetCreateMode(bool cm) { create_mode = cm; } std::map <std::string, SmallConf*> ::iterator Begin(void) { return (iterator = nodes.begin()); } std::map <std::string, SmallConf*> ::iterator End(void) { return (nodes.end()); } std::map <std::string, SmallConf*> ::iterator &It(void) { return (iterator); } size_t Size(void) const { return (array.size()); } SmallConf &operator[](const std::string &str) { SmallConf **slot; if (*(slot = &nodes[str]) == NULL) { if (create_mode) { *slot = new SmallConf; (*slot)->name = str; (*slot)->father = this; } else { nodes.erase(str); throw 0; } } return (**slot); } SmallConf &operator[](size_t i) { size_t olsize; if ((olsize = array.size()) <= i) { if (!create_mode) throw 0; array.resize(i + 1); while (olsize <= i) { std::stringstream ss; ss << this->name << "[" << i << "]"; array[olsize] = new SmallConf; array[olsize]->father = this; array[olsize]->name = ss.str(); olsize += 1; } } return (*array[i]); } bool Access(const std::string &str) { return (nodes.find(str) != nodes.end()); } bool Access(ssize_t i) { std::stringstream ss; ss << std::setfill('0') << std::setw(8) << i; return (nodes.find(ss.str()) != nodes.end()); } void SetString(const std::string &in, bool raw = false) { original_value = in; have_value = true; if (raw) last_type = RAWSTRING; else last_type = STRING; } bool GetString(const char **out) const { if (have_value == false) return (false); *out = original_value.c_str(); return (true); } void SetInt(int i) { std::stringstream ss; ss << i; original_value = ss.str(); converted_2 = converted = i; is_converted = true; have_value = true; last_type = INTEGER; } bool GetInt(int *i) const { double d; if (GetDouble(&d) == false) return (false); converted_2 = converted; *i = converted_2; return (true); } void SetDouble(double v) { std::stringstream ss; ss << v; original_value = ss.str(); converted_2 = converted = v; is_converted = true; have_value = true; last_type = DOUBLE; } bool GetDouble(double *v) const { if (have_value == false) return (false); if (is_converted == false) { ssize_t i; if (readdouble(original_value.c_str(), i, converted) == false) return (false); is_converted = true; } *v = converted; return (true); } SmallConf(void) : have_value(false), converted(0), converted_2(0), is_converted(false), father(NULL) {} ~SmallConf(void) { std::map<std::string, SmallConf*>::iterator it; std::map<std::string, SmallConf*> dup = nodes; if (father != NULL) father->nodes.erase(name); for (it = dup.begin(); it != dup.end(); ++it) delete it->second; } }; #endif /* __LAPIN_PRIVATE_CONFIGURATION_HPP__ */
22.347368
66
0.57403
TetraSomia
d016f0b1044b6e6dca3486f07fb52fd71862cea4
4,463
hpp
C++
Genesis/include/Genesis/LegacyBackend/LegacyBackend.hpp
JoshuaMasci/Genesis
761060626a92e3df7b860a97209fca341cdda240
[ "MIT" ]
2
2020-01-22T05:57:12.000Z
2020-04-06T01:15:30.000Z
Genesis/include/Genesis/LegacyBackend/LegacyBackend.hpp
JoshuaMasci/Genesis
761060626a92e3df7b860a97209fca341cdda240
[ "MIT" ]
null
null
null
Genesis/include/Genesis/LegacyBackend/LegacyBackend.hpp
JoshuaMasci/Genesis
761060626a92e3df7b860a97209fca341cdda240
[ "MIT" ]
null
null
null
#pragma once #include "Genesis/RenderingBackend/VertexInputDescription.hpp" #include "Genesis/RenderingBackend/RenderingTypes.hpp" #include "Genesis/RenderingBackend/PipelineSettings.hpp" namespace Genesis { enum class DepthFormat { depth_16, depth_24, depth_32, depth_32f, }; enum class TextureWrapMode { Repeat, Mirrored_Repeat, Clamp_Edge, Clamp_Border }; enum class TextureFilterMode { Nearest, Linear }; struct TextureCreateInfo { vector2U size; ImageFormat format; TextureWrapMode wrap_mode; TextureFilterMode filter_mode; }; enum class MultisampleCount { Sample_1 = 1, Sample_2 = 2, Sample_4 = 4, Sample_8 = 8, Sample_16 = 16, Sample_32 = 32, Sample_64 = 64 }; struct FramebufferAttachmentInfo { ImageFormat format; MultisampleCount samples; }; struct FramebufferDepthInfo { DepthFormat format; MultisampleCount samples; }; struct FramebufferCreateInfo { vector2U size; FramebufferAttachmentInfo* attachments; uint32_t attachment_count; FramebufferDepthInfo* depth_attachment; }; typedef void* Framebuffer; typedef void* ShaderProgram; struct FrameStats { uint64_t draw_calls; uint64_t triangles_count; }; class LegacyBackend { public: virtual ~LegacyBackend() {}; virtual vector2U getScreenSize() = 0; virtual void startFrame() = 0; virtual void endFrame() = 0; virtual VertexBuffer createVertexBuffer(void* data, uint64_t data_size, const VertexInputDescriptionCreateInfo& vertex_description) = 0; virtual void destoryVertexBuffer(VertexBuffer buffer) = 0; virtual IndexBuffer createIndexBuffer(void* data, uint64_t data_size, IndexType type) = 0; virtual void destoryIndexBuffer(IndexBuffer buffer) = 0; virtual Texture2D createTexture(const TextureCreateInfo& create_info, void* data) = 0; virtual void destoryTexture(Texture2D texture) = 0; virtual ShaderProgram createShaderProgram(const char* vert_data, uint32_t vert_size, const char* frag_data, uint32_t frag_size) = 0; virtual ShaderProgram createComputeShader(const char* data, uint32_t size) = 0; virtual void destoryShaderProgram(ShaderProgram program) = 0; virtual Framebuffer createFramebuffer(const FramebufferCreateInfo& create_info) = 0; virtual void destoryFramebuffer(Framebuffer framebuffer) = 0; virtual Texture2D getFramebufferColorAttachment(Framebuffer framebuffer, uint32_t index) = 0; virtual Texture2D getFramebufferDepthAttachment(Framebuffer framebuffer) = 0; //Commands virtual void bindFramebuffer(Framebuffer framebuffer) = 0; virtual void clearFramebuffer(bool color, bool depth, vector4F* clear_color = nullptr, float* clear_depth = nullptr) = 0; virtual void setPipelineState(const PipelineSettings& pipeline_state) = 0; virtual void bindShaderProgram(ShaderProgram program) = 0; virtual void setUniform1i(const string& name, const int32_t& value) = 0; virtual void setUniform1u(const string& name, const uint32_t& value) = 0; virtual void setUniform2u(const string& name, const vector2U& value) = 0; virtual void setUniform3u(const string& name, const vector3U& value) = 0; virtual void setUniform4u(const string& name, const vector4U& value) = 0; virtual void setUniform1f(const string& name, const float& value) = 0; virtual void setUniform2f(const string& name, const vector2F& value) = 0; virtual void setUniform3f(const string& name, const vector3F& value) = 0; virtual void setUniform4f(const string& name, const vector4F& value) = 0; virtual void setUniformMat3f(const string& name, const matrix3F& value) = 0; virtual void setUniformMat4f(const string& name, const matrix4F& value) = 0; virtual void setUniformTexture(const string& name, const uint32_t texture_slot, Texture2D value) = 0; virtual void setUniformTextureImage(const string& name, const uint32_t texture_slot, Texture2D value) = 0; virtual void setScissor(vector2I offset, vector2U extent) = 0; virtual void clearScissor() = 0; virtual void bindVertexBuffer(VertexBuffer buffer) = 0; virtual void bindIndexBuffer(IndexBuffer buffer) = 0; virtual void drawIndex(uint32_t index_count, uint32_t index_offset = 0) = 0; virtual void draw(VertexBuffer vertex_buffer, IndexBuffer index_buffer, uint32_t triangle_count) = 0; virtual void dispatchCompute(uint32_t groups_x = 1, uint32_t groups_y = 1, uint32_t groups_z = 1) = 0; //Stats virtual FrameStats getLastFrameStats() = 0; }; }
30.568493
138
0.766077
JoshuaMasci
d01efa51e1883ccdcd82c4418fbaf02af8fea6f1
861
cpp
C++
TouchBarConfig.cpp
RPBCACUEAIIBH/HexaLib-Arduino
0f61cb0c1fd560df5a6395749376e1123ba0a8f5
[ "BSD-3-Clause" ]
3
2020-09-10T18:36:25.000Z
2020-12-18T03:34:08.000Z
TouchBarConfig.cpp
RPBCACUEAIIBH/TouchBar
96378d143a57e1a0e5e32b2577d94ee717c5c6cf
[ "BSD-3-Clause" ]
null
null
null
TouchBarConfig.cpp
RPBCACUEAIIBH/TouchBar
96378d143a57e1a0e5e32b2577d94ee717c5c6cf
[ "BSD-3-Clause" ]
null
null
null
#include "TouchBar.h" /* Configure Private */ void TouchBarConfig::SetFlags (boolean SpringBackFlag, boolean SnapFlag, boolean RampFlag, boolean FlipFlag) { Flags = 0; bitWrite(Flags, 6, SpringBackFlag); bitWrite(Flags, 5, SnapFlag); bitWrite(Flags, 4, RampFlag); bitWrite(Flags, 3, FlipFlag); } void TouchBarConfig::SetFlags (boolean RollOverFlag, boolean FlipFlag) { Flags = 0; bitWrite(Flags, 7, RollOverFlag); bitWrite(Flags, 3, FlipFlag); } /* Get Private */ boolean TouchBarConfig::GetRollOverFlag () { return bitRead (Flags, 7); } boolean TouchBarConfig::GetSpringBackFlag () { return bitRead (Flags, 6); } boolean TouchBarConfig::GetSnapFlag () { return bitRead (Flags, 5); } boolean TouchBarConfig::GetRampFlag () { return bitRead (Flags, 4); } boolean TouchBarConfig::GetFlipFlag () { return bitRead (Flags, 3); }
17.571429
108
0.711963
RPBCACUEAIIBH
d0221ec0649cad315b8faa29b379bb05862f5f92
31,902
cpp
C++
src/builder.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
12
2015-03-04T15:07:00.000Z
2019-09-13T16:31:06.000Z
src/builder.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
null
null
null
src/builder.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
5
2017-04-22T08:16:48.000Z
2020-07-12T03:35:16.000Z
/* $Id: builder.cpp 49134 2011-04-09 16:00:16Z mordante $ */ /* Copyright (C) 2004 - 2011 by Philippe Plantier <ayin@anathas.org> Part of the Battle for Wesnoth Project http://www.wesnoth.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * @file * Terrain builder. */ #include "builder.hpp" #include "foreach.hpp" #include "loadscreen.hpp" #include "log.hpp" #include "map.hpp" #include "serialization/string_utils.hpp" #include "image.hpp" static lg::log_domain log_engine("engine"); #define ERR_NG LOG_STREAM(err, log_engine) #define WRN_NG LOG_STREAM(warn, log_engine) terrain_builder::building_ruleset terrain_builder::building_rules_; const config* terrain_builder::rules_cfg_ = NULL; terrain_builder::rule_image::rule_image(int layer, int x, int y, bool global_image, int cx, int cy) : layer(layer), basex(x), basey(y), variants(), global_image(global_image), center_x(cx), center_y(cy) {} terrain_builder::tile::tile() : flags(), images(), images_foreground(), images_background(), last_tod("invalid_tod"), sorted_images(false) {} void terrain_builder::tile::rebuild_cache(const std::string& tod, logs* log) { images_background.clear(); images_foreground.clear(); if(!sorted_images){ //sort images by their layer (and basey) //but use stable to keep the insertion order in equal cases std::stable_sort(images.begin(), images.end()); sorted_images = true; } foreach(const rule_image_rand& ri, images){ bool is_background = ri->is_background(); imagelist& img_list = is_background ? images_background : images_foreground; foreach(const rule_image_variant& variant, ri->variants){ if(!variant.tods.empty() && variant.tods.find(tod) == variant.tods.end()) continue; //need to break parity pattern in RNG ///@TODO improve this unsigned int rnd = ri.rand / 7919; //just the 1000th prime img_list.push_back(variant.images[rnd % variant.images.size()]); if(variant.random_start) img_list.back().set_animation_time(ri.rand % img_list.back().get_animation_duration()); if(log) { log->push_back(std::make_pair(&ri, &variant)); } break; // found a matching variant } } } void terrain_builder::tile::clear() { flags.clear(); images.clear(); sorted_images = false; images_foreground.clear(); images_background.clear(); last_tod = "invalid_tod"; } static unsigned int get_noise(const map_location& loc, unsigned int index){ unsigned int a = (loc.x + 92872973) ^ 918273; unsigned int b = (loc.y + 1672517) ^ 128123; unsigned int c = (index + 127390) ^ 13923787; unsigned int abc = a*b*c + a*b + b*c + a*c + a + b + c; return abc*abc; } void terrain_builder::tilemap::reset() { for(std::vector<tile>::iterator it = tiles_.begin(); it != tiles_.end(); ++it) it->clear(); } void terrain_builder::tilemap::reload(int x, int y) { x_ = x; y_ = y; std::vector<terrain_builder::tile> new_tiles((x + 4) * (y + 4)); tiles_.swap(new_tiles); reset(); } bool terrain_builder::tilemap::on_map(const map_location &loc) const { if(loc.x < -2 || loc.y < -2 || loc.x > (x_ + 1) || loc.y > (y_ + 1)) { return false; } return true; } terrain_builder::tile& terrain_builder::tilemap::operator[](const map_location &loc) { assert(on_map(loc)); return tiles_[(loc.x + 2) + (loc.y + 2) * (x_ + 4)]; } const terrain_builder::tile& terrain_builder::tilemap::operator[] (const map_location &loc) const { assert(on_map(loc)); return tiles_[(loc.x + 2) + (loc.y + 2) * (x_ + 4)]; } terrain_builder::terrain_builder(const config& level, const gamemap* m, const std::string& offmap_image) : map_(m), tile_map_(map().w(), map().h()), terrain_by_type_() { image::precache_file_existence("terrain/"); if(building_rules_.empty() && rules_cfg_){ //off_map first to prevent some default rule seems to block it add_off_map_rule(offmap_image); // parse global terrain rules parse_global_config(*rules_cfg_); } else { // use cached global rules but clear local rules flush_local_rules(); } // parse local rules parse_config(level); build_terrains(); } void terrain_builder::flush_local_rules() { building_ruleset::iterator i = building_rules_.begin(); for(; i != building_rules_.end();){ if (i->local) building_rules_.erase(i++); else ++i; } } void terrain_builder::set_terrain_rules_cfg(const config& cfg) { rules_cfg_ = &cfg; // use the swap trick to clear the rules cache and get a fresh one. // because simple clear() seems to cause some progressive memory degradation. building_ruleset empty; std::swap(building_rules_, empty); } void terrain_builder::reload_map() { tile_map_.reload(map().w(), map().h()); terrain_by_type_.clear(); build_terrains(); } void terrain_builder::change_map(const gamemap* m) { map_ = m; reload_map(); } const terrain_builder::imagelist *terrain_builder::get_terrain_at(const map_location &loc, const std::string &tod, const TERRAIN_TYPE terrain_type) { if(!tile_map_.on_map(loc)) return NULL; tile& tile_at = tile_map_[loc]; if(tod != tile_at.last_tod) { tile_at.rebuild_cache(tod); tile_at.last_tod = tod; } const imagelist& img_list = (terrain_type == BACKGROUND) ? tile_at.images_background : tile_at.images_foreground; if(!img_list.empty()) { return &img_list; } return NULL; } bool terrain_builder::update_animation(const map_location &loc) { if(!tile_map_.on_map(loc)) return false; bool changed = false; tile& btile = tile_map_[loc]; foreach(animated<image::locator>& a, btile.images_background) { if(a.need_update()) changed = true; a.update_last_draw_time(); } foreach(animated<image::locator>& a, btile.images_foreground) { if(a.need_update()) changed = true; a.update_last_draw_time(); } return changed; } /** @todo TODO: rename this function */ void terrain_builder::rebuild_terrain(const map_location &loc) { if (tile_map_.on_map(loc)) { tile& btile = tile_map_[loc]; // btile.images.clear(); btile.images_foreground.clear(); btile.images_background.clear(); const std::string filename = map().get_terrain_info(map().get_terrain(loc)).minimap_image(); animated<image::locator> img_loc; img_loc.add_frame(100,image::locator("terrain/" + filename + ".png")); img_loc.start_animation(0, true); btile.images_background.push_back(img_loc); //Combine base and overlay image if necessary if(map().get_terrain_info(map().get_terrain(loc)).is_combined()) { const std::string filename_ovl = map().get_terrain_info(map().get_terrain(loc)).minimap_image_overlay(); animated<image::locator> img_loc_ovl; img_loc_ovl.add_frame(100,image::locator("terrain/" + filename_ovl + ".png")); img_loc_ovl.start_animation(0, true); btile.images_background.push_back(img_loc_ovl); } } } void terrain_builder::rebuild_all() { tile_map_.reset(); terrain_by_type_.clear(); build_terrains(); } static bool image_exists(const std::string& name) { bool precached = name.find("..") == std::string::npos; if(precached && image::precached_file_exists(name)) { return true; } else if(image::exists(name)) { return true; } return false; } static std::vector<std::string> get_variations(const std::string& base, const std::string& variations) { ///@TODO optimize this function std::vector<std::string> res; if(variations.empty()){ res.push_back(base); return res; } std::string::size_type pos = base.find("@V", 0); if(pos == std::string::npos) { res.push_back(base); return res; } std::vector<std::string> vars = utils::split(variations, ';', 0); foreach(const std::string& v, vars){ res.push_back(base); std::string::size_type pos = 0; while ((pos = res.back().find("@V", pos)) != std::string::npos) { res.back().replace(pos, 2, v); pos += v.size(); } } return res; } bool terrain_builder::load_images(building_rule &rule) { // If the rule has no constraints, it is invalid if(rule.constraints.empty()) return false; // Parse images and animations data // If one is not valid, return false. foreach(terrain_constraint &constraint, rule.constraints) { foreach(rule_image& ri, constraint.images) { foreach(rule_image_variant& variant, ri.variants) { std::vector<std::string> var_strings = get_variations(variant.image_string, variant.variations); foreach(const std::string& var, var_strings) { ///@TODO improve this, 99% of terrains are not animated. std::vector<std::string> frames = utils::parenthetical_split(var,','); animated<image::locator> res; foreach(const std::string& frame, frames) { const std::vector<std::string> items = utils::split(frame, ':'); const std::string& str = items.front(); const size_t tilde = str.find('~'); bool has_tilde = tilde != std::string::npos; const std::string filename = "terrain/" + (has_tilde ? str.substr(0,tilde) : str); if(!image_exists(filename)){ continue; // ignore missing frames } const std::string modif = (has_tilde ? str.substr(tilde+1) : ""); int time = 100; if(items.size() > 1) { time = atoi(items.back().c_str()); } image::locator locator; if(ri.global_image) { locator = image::locator(filename, constraint.loc, ri.center_x, ri.center_y, modif); } else { locator = image::locator(filename, modif); } res.add_frame(time, locator); } if(res.get_frames_count() == 0) break; // no valid images, don't register it res.start_animation(0, true); variant.images.push_back(res); } if(variant.images.empty()) return false; //no valid images, rule is invalid } } } return true; } void terrain_builder::rotate(terrain_constraint &ret, int angle) { static const struct { int ii; int ij; int ji; int jj; } rotations[6] = { { 1, 0, 0, 1 }, { 1, 1, -1, 0 }, { 0, 1, -1, -1 }, { -1, 0, 0, -1 }, { -1, -1, 1, 0 }, { 0, -1, 1, 1 } }; // The following array of matrices is intended to rotate the (x,y) // coordinates of a point in a wesnoth hex (and wesnoth hexes are not // regular hexes :) ). // The base matrix for a 1-step rotation with the wesnoth tile shape // is: // // r = s^-1 * t * s // // with s = [[ 1 0 ] // [ 0 -sqrt(3)/2 ]] // // and t = [[ -1/2 sqrt(3)/2 ] // [ -sqrt(3)/2 1/2 ]] // // With t being the rotation matrix (pi/3 rotation), and s a matrix // that transforms the coordinates of the wesnoth hex to make them // those of a regular hex. // // (demonstration left as an exercise for the reader) // // So we have // // r = [[ 1/2 -3/4 ] // [ 1 1/2 ]] // // And the following array contains I(2), r, r^2, r^3, r^4, r^5 // (with r^3 == -I(2)), which are the successive rotations. static const struct { double xx; double xy; double yx; double yy; } xyrotations[6] = { { 1., 0., 0., 1. }, { 1./2. , -3./4., 1., 1./2. }, { -1./2., -3./4., 1, -1./2.}, { -1. , 0., 0., -1. }, { -1./2., 3./4., -1., -1./2.}, { 1./2. , 3./4., -1., 1./2. }, }; assert(angle >= 0); angle %= 6; // Vector i is going from n to s, vector j is going from ne to sw. int vi = ret.loc.y - ret.loc.x/2; int vj = ret.loc.x; int ri = rotations[angle].ii * vi + rotations[angle].ij * vj; int rj = rotations[angle].ji * vi + rotations[angle].jj * vj; ret.loc.x = rj; ret.loc.y = ri + (rj >= 0 ? rj/2 : (rj-1)/2); for (rule_imagelist::iterator itor = ret.images.begin(); itor != ret.images.end(); ++itor) { double vx, vy, rx, ry; vx = double(itor->basex) - double(TILEWIDTH)/2; vy = double(itor->basey) - double(TILEWIDTH)/2; rx = xyrotations[angle].xx * vx + xyrotations[angle].xy * vy; ry = xyrotations[angle].yx * vx + xyrotations[angle].yy * vy; itor->basex = int(rx + TILEWIDTH/2); itor->basey = int(ry + TILEWIDTH/2); //std::cerr << "Rotation: from " << vx << ", " << vy << " to " << itor->basex << // ", " << itor->basey << "\n"; } } void terrain_builder::replace_rotate_tokens(std::string &s, int angle, const std::vector<std::string> &replacement) { std::string::size_type pos = 0; while ((pos = s.find("@R", pos)) != std::string::npos) { if (pos + 2 >= s.size()) return; unsigned i = s[pos + 2] - '0' + angle; if (i >= 6) i -= 6; if (i >= 6) { pos += 2; continue; } const std::string &r = replacement[i]; s.replace(pos, 3, r); pos += r.size(); } } void terrain_builder::replace_rotate_tokens(rule_image &image, int angle, const std::vector<std::string> &replacement) { foreach(rule_image_variant& variant, image.variants) { replace_rotate_tokens(variant, angle, replacement); } } void terrain_builder::replace_rotate_tokens(rule_imagelist &list, int angle, const std::vector<std::string> &replacement) { foreach (rule_image &img, list) { replace_rotate_tokens(img, angle, replacement); } } void terrain_builder::replace_rotate_tokens(building_rule &rule, int angle, const std::vector<std::string> &replacement) { foreach (terrain_constraint &cons, rule.constraints) { // Transforms attributes foreach (std::string &flag, cons.set_flag) { replace_rotate_tokens(flag, angle, replacement); } foreach (std::string &flag, cons.no_flag) { replace_rotate_tokens(flag, angle, replacement); } foreach (std::string &flag, cons.has_flag) { replace_rotate_tokens(flag, angle, replacement); } replace_rotate_tokens(cons.images, angle, replacement); } //replace_rotate_tokens(rule.images, angle, replacement); } void terrain_builder::rotate_rule(building_rule &ret, int angle, const std::vector<std::string> &rot) { if (rot.size() != 6) { ERR_NG << "invalid rotations\n"; return; } foreach (terrain_constraint &cons, ret.constraints) { rotate(cons, angle); } // Normalize the rotation, so that it starts on a positive location int minx = INT_MAX; int miny = INT_MAX; foreach (const terrain_constraint &cons, ret.constraints) { minx = std::min<int>(cons.loc.x, minx); miny = std::min<int>(2 * cons.loc.y + (cons.loc.x & 1), miny); } if((miny & 1) && (minx & 1) && (minx < 0)) miny += 2; if(!(miny & 1) && (minx & 1) && (minx > 0)) miny -= 2; foreach (terrain_constraint &cons, ret.constraints) { cons.loc.legacy_sum_assign(map_location(-minx, -((miny - 1) / 2))); } replace_rotate_tokens(ret, angle, rot); } terrain_builder::rule_image_variant::rule_image_variant(const std::string &image_string, const std::string& variations, const std::string& tod, bool random_start) : image_string(image_string), variations(variations), images(), tods(), random_start(random_start) { if(!tod.empty()) { const std::vector<std::string> tod_list = utils::split(tod); tods.insert(tod_list.begin(), tod_list.end()); } } void terrain_builder::add_images_from_config(rule_imagelist& images, const config &cfg, bool global, int dx, int dy) { foreach (const config &img, cfg.child_range("image")) { int layer = img["layer"]; int basex = TILEWIDTH / 2 + dx, basey = TILEWIDTH / 2 + dy; if (const config::attribute_value *base_ = img.get("base")) { std::vector<std::string> base = utils::split(*base_); if(base.size() >= 2) { basex = atoi(base[0].c_str()); basey = atoi(base[1].c_str()); } } int center_x = -1, center_y = -1; if (const config::attribute_value *center_ = img.get("center")) { std::vector<std::string> center = utils::split(*center_); if(center.size() >= 2) { center_x = atoi(center[0].c_str()); center_y = atoi(center[1].c_str()); } } images.push_back(rule_image(layer, basex - dx, basey - dy, global, center_x, center_y)); // Adds the other variants of the image foreach (const config &variant, img.child_range("variant")) { const std::string &name = variant["name"]; const std::string &variations = img["variations"]; const std::string &tod = variant["tod"]; bool random_start = variant["random_start"].to_bool(true); images.back().variants.push_back(rule_image_variant(name, variations, tod, random_start)); } // Adds the main (default) variant of the image at the end, // (will be used only if previous variants don't match) const std::string &name = img["name"]; const std::string &variations = img["variations"]; bool random_start = img["random_start"].to_bool(true); images.back().variants.push_back(rule_image_variant(name, variations, random_start)); } } terrain_builder::terrain_constraint &terrain_builder::add_constraints( terrain_builder::constraint_set& constraints, const map_location& loc, const t_translation::t_match& type, const config& global_images) { terrain_constraint *cons = NULL; foreach (terrain_constraint &c, constraints) { if (c.loc == loc) { cons = &c; break; } } if (!cons) { // The terrain at the current location did not exist, so create it constraints.push_back(terrain_constraint(loc)); cons = &constraints.back(); } if(!type.terrain.empty()) { cons->terrain_types_match = type; } int x = loc.x * TILEWIDTH * 3 / 4; int y = loc.y * TILEWIDTH + (loc.x % 2) * TILEWIDTH / 2; add_images_from_config(cons->images, global_images, true, x, y); return *cons; } void terrain_builder::add_constraints(terrain_builder::constraint_set &constraints, const map_location& loc, const config& cfg, const config& global_images) { terrain_constraint& constraint = add_constraints(constraints, loc, t_translation::t_match(cfg["type"], t_translation::WILDCARD), global_images); std::vector<std::string> item_string = utils::split(cfg["set_flag"]); constraint.set_flag.insert(constraint.set_flag.end(), item_string.begin(), item_string.end()); item_string = utils::split(cfg["has_flag"]); constraint.has_flag.insert(constraint.has_flag.end(), item_string.begin(), item_string.end()); item_string = utils::split(cfg["no_flag"]); constraint.no_flag.insert(constraint.no_flag.end(), item_string.begin(), item_string.end()); item_string = utils::split(cfg["set_no_flag"]); constraint.set_flag.insert(constraint.set_flag.end(), item_string.begin(), item_string.end()); constraint.no_flag.insert(constraint.no_flag.end(), item_string.begin(), item_string.end()); add_images_from_config(constraint.images, cfg, false); } void terrain_builder::parse_mapstring(const std::string &mapstring, struct building_rule &br, anchormap& anchors, const config& global_images) { const t_translation::t_map map = t_translation::read_builder_map(mapstring); // If there is an empty map leave directly. // Determine after conversion, since a // non-empty string can return an empty map. if(map.empty()) { return; } int lineno = (map[0][0] == t_translation::NONE_TERRAIN) ? 1 : 0; int x = lineno; int y = 0; for(size_t y_off = 0; y_off < map.size(); ++y_off) { for(size_t x_off = x; x_off < map[y_off].size(); ++x_off) { const t_translation::t_terrain terrain = map[y_off][x_off]; if(terrain.base == t_translation::TB_DOT) { // Dots are simple placeholders, // which do not represent actual terrains. } else if (terrain.overlay != 0 ) { anchors.insert(std::pair<int, map_location>(terrain.overlay, map_location(x, y))); } else if (terrain.base == t_translation::TB_STAR) { add_constraints(br.constraints, map_location(x, y), t_translation::STAR, global_images); } else { ERR_NG << "Invalid terrain (" << t_translation::write_terrain_code(terrain) << ") in builder map\n"; assert(false); return; } x += 2; } if(lineno % 2 == 1) { ++y; x = 0; } else { x = 1; } ++lineno; } } void terrain_builder::add_rule(building_ruleset &rules, building_rule &rule) { if(load_images(rule)) { rules.insert(rule); } } void terrain_builder::add_rotated_rules(building_ruleset &rules, building_rule &tpl, const std::string &rotations) { if(rotations.empty()) { // Adds the parsed built terrain to the list add_rule(rules, tpl); } else { const std::vector<std::string>& rot = utils::split(rotations, ','); for(size_t angle = 0; angle < rot.size(); ++angle) { /* Only 5% of the rules have valid images, so most of them will be discarded. If the ratio was higher, it would be more efficient to insert a copy of the template rule into the ruleset, modify it in place, and remove it if invalid. But since the ratio is so low, the speedup is not worth the extra multiset manipulations. */ building_rule rule = tpl; rotate_rule(rule, angle, rot); add_rule(rules, rule); } } } void terrain_builder::parse_config(const config &cfg, bool local) { log_scope("terrain_builder::parse_config"); // Parses the list of building rules (BRs) foreach (const config &br, cfg.child_range("terrain_graphics")) { building_rule pbr; // Parsed Building rule pbr.local = local; // add_images_from_config(pbr.images, **br); pbr.location_constraints = map_location(br["x"].to_int() - 1, br["y"].to_int() - 1); pbr.probability = br["probability"].to_int(100); // Mapping anchor indices to anchor locations. anchormap anchors; // Parse the map= , if there is one (and fill the anchors list) parse_mapstring(br["map"], pbr, anchors, br); // Parses the terrain constraints (TCs) foreach (const config &tc, br.child_range("tile")) { // Adds the terrain constraint to the current built terrain's list // of terrain constraints, if it does not exist. map_location loc; if (const config::attribute_value *v = tc.get("x")) { loc.x = *v; } if (const config::attribute_value *v = tc.get("y")) { loc.y = *v; } if (const config::attribute_value *v = tc.get("loc")) { std::vector<std::string> sloc = utils::split(*v); if(sloc.size() == 2) { loc.x = atoi(sloc[0].c_str()); loc.y = atoi(sloc[1].c_str()); } } if(loc.valid()) { add_constraints(pbr.constraints, loc, tc, br); } if (const config::attribute_value *v = tc.get("pos")) { int pos = *v; if(anchors.find(pos) == anchors.end()) { WRN_NG << "Invalid anchor!\n"; continue; } std::pair<anchormap::const_iterator, anchormap::const_iterator> range = anchors.equal_range(pos); for(; range.first != range.second; ++range.first) { loc = range.first->second; add_constraints(pbr.constraints, loc, tc, br); } } } const std::vector<std::string> global_set_flag = utils::split(br["set_flag"]); const std::vector<std::string> global_no_flag = utils::split(br["no_flag"]); const std::vector<std::string> global_has_flag = utils::split(br["has_flag"]); const std::vector<std::string> global_set_no_flag = utils::split(br["set_no_flag"]); foreach (terrain_constraint &constraint, pbr.constraints) { constraint.set_flag.insert(constraint.set_flag.end(), global_set_flag.begin(), global_set_flag.end()); constraint.no_flag.insert(constraint.no_flag.end(), global_no_flag.begin(), global_no_flag.end()); constraint.has_flag.insert(constraint.has_flag.end(), global_has_flag.begin(), global_has_flag.end()); constraint.set_flag.insert(constraint.set_flag.end(), global_set_no_flag.begin(), global_set_no_flag.end()); constraint.no_flag.insert(constraint.no_flag.end(), global_set_no_flag.begin(), global_set_no_flag.end()); } // Handles rotations const std::string &rotations = br["rotations"]; pbr.precedence = br["precedence"]; add_rotated_rules(building_rules_, pbr, rotations); loadscreen::increment_progress(); } // Debug output for the terrain rules #if 0 std::cerr << "Built terrain rules: \n"; building_ruleset::const_iterator rule; for(rule = building_rules_.begin(); rule != building_rules_.end(); ++rule) { std::cerr << ">> New rule: image_background = " << "\n>> Location " << rule->second.location_constraints << "\n>> Probability " << rule->second.probability for(constraint_set::const_iterator constraint = rule->second.constraints.begin(); constraint != rule->second.constraints.end(); ++constraint) { std::cerr << ">>>> New constraint: location = (" << constraint->second.loc << "), terrain types = '" << t_translation::write_list(constraint->second.terrain_types_match.terrain) << "'\n"; std::vector<std::string>::const_iterator flag; for(flag = constraint->second.set_flag.begin(); flag != constraint->second.set_flag.end(); ++flag) { std::cerr << ">>>>>> Set_flag: " << *flag << "\n"; } for(flag = constraint->second.no_flag.begin(); flag != constraint->second.no_flag.end(); ++flag) { std::cerr << ">>>>>> No_flag: " << *flag << "\n"; } } } #endif } void terrain_builder::add_off_map_rule(const std::string& image) { // Build a config object config cfg; config &item = cfg.add_child("terrain_graphics"); config &tile = item.add_child("tile"); tile["x"] = 0; tile["y"] = 0; tile["type"] = t_translation::write_terrain_code(t_translation::OFF_MAP_USER); config &tile_image = tile.add_child("image"); tile_image["layer"] = -1000; tile_image["name"] = image; item["probability"] = 100; item["no_flag"] = "base"; item["set_flag"] = "base"; // Parse the object parse_global_config(cfg); } bool terrain_builder::rule_matches(const terrain_builder::building_rule &rule, const map_location &loc, const terrain_constraint *type_checked) const { if(rule.location_constraints.valid() && rule.location_constraints != loc) { return false; } if(rule.probability != 100) { unsigned int random = get_noise(loc, rule.get_hash()) % 100; if(random > static_cast<unsigned int>(rule.probability)) { return false; } } foreach (const terrain_constraint &cons, rule.constraints) { // Translated location const map_location tloc = loc.legacy_sum(cons.loc); if(!tile_map_.on_map(tloc)) { return false; } //std::cout << "testing..." << builder_letter(map().get_terrain(tloc)) // check if terrain matches except if we already know that it does if (&cons != type_checked && !terrain_matches(map().get_terrain(tloc), cons.terrain_types_match)) { return false; } const std::set<std::string> &flags = tile_map_[tloc].flags; foreach (const std::string &s, cons.no_flag) { // If a flag listed in "no_flag" is present, the rule does not match if (flags.find(s) != flags.end()) { return false; } } foreach (const std::string &s, cons.has_flag) { // If a flag listed in "has_flag" is not present, this rule does not match if (flags.find(s) == flags.end()) { return false; } } } return true; } void terrain_builder::apply_rule(const terrain_builder::building_rule &rule, const map_location &loc) { unsigned int rand_seed = get_noise(loc, rule.get_hash()); foreach (const terrain_constraint &constraint, rule.constraints) { const map_location tloc = loc.legacy_sum(constraint.loc); if(!tile_map_.on_map(tloc)) { return; } tile& btile = tile_map_[tloc]; foreach (const rule_image &img, constraint.images) { btile.images.push_back(tile::rule_image_rand(&img, rand_seed)); } // Sets flags foreach (const std::string &flag, constraint.set_flag) { btile.flags.insert(flag); } } } // copied from text_surface::hash() // but keep it separated because the needs are different // and changing it will modify the map random variations static unsigned int hash_str(const std::string& str) { unsigned int h = 0; for(std::string::const_iterator it = str.begin(), it_end = str.end(); it != it_end; ++it) h = ((h << 9) | (h >> (sizeof(int) * 8 - 9))) ^ (*it); return h; } unsigned int terrain_builder::building_rule::get_hash() const { if(hash_ != DUMMY_HASH) return hash_; foreach(const terrain_constraint &constraint, constraints) { foreach(const rule_image& ri, constraint.images) { foreach(const rule_image_variant& variant, ri.variants) { // we will often hash the same string, but that seems fast enough hash_ += hash_str(variant.image_string); } } } //don't use the reserved dummy hash if(hash_ == DUMMY_HASH) hash_ = 105533; // just a random big prime number return hash_; } void terrain_builder::build_terrains() { log_scope("terrain_builder::build_terrains"); // Builds the terrain_by_type_ cache for(int x = -2; x <= map().w(); ++x) { for(int y = -2; y <= map().h(); ++y) { const map_location loc(x,y); const t_translation::t_terrain t = map().get_terrain(loc); terrain_by_type_[t].push_back(loc); } } foreach (const building_rule &rule, building_rules_) { // Find the constraint that contains the less terrain of all terrain rules. // We will keep a track of the matching terrains of this constraint // and later try to apply the rule only on them size_t min_size = INT_MAX; t_translation::t_list min_types; const terrain_constraint *min_constraint = NULL; foreach (const terrain_constraint &constraint, rule.constraints) { const t_translation::t_match& match = constraint.terrain_types_match; t_translation::t_list matching_types; size_t constraint_size = 0; for (terrain_by_type_map::iterator type_it = terrain_by_type_.begin(); type_it != terrain_by_type_.end(); ++type_it) { const t_translation::t_terrain t = type_it->first; if (terrain_matches(t, match)) { const size_t match_size = type_it->second.size(); constraint_size += match_size; if (constraint_size >= min_size) { break; // not a minimum, bail out } matching_types.push_back(t); } } if (constraint_size < min_size) { min_size = constraint_size; min_types = matching_types; min_constraint = &constraint; if (min_size == 0) { // a constraint is never matched on this map // we break with a empty type list break; } } } //NOTE: if min_types is not empty, we have found a valid min_constraint; for(t_translation::t_list::const_iterator t = min_types.begin(); t != min_types.end(); ++t) { const std::vector<map_location>* locations = &terrain_by_type_[*t]; for(std::vector<map_location>::const_iterator itor = locations->begin(); itor != locations->end(); ++itor) { const map_location loc = itor->legacy_difference(min_constraint->loc); if(rule_matches(rule, loc, min_constraint)) { apply_rule(rule, loc); } } } } } terrain_builder::tile* terrain_builder::get_tile(const map_location &loc) { if(tile_map_.on_map(loc)) return &(tile_map_[loc]); return NULL; }
29.375691
165
0.648486
blackberry
d02248a925b2e191b000ae89b231c53d74468938
17,691
cc
C++
protocal/guardian/guardian.pb.cc
racestart/g2r
d115ebaab13829d716750eab2ebdcc51d79ff32e
[ "Apache-2.0" ]
1
2020-03-05T12:49:21.000Z
2020-03-05T12:49:21.000Z
protocal/guardian/guardian.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
null
null
null
protocal/guardian/guardian.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
1
2020-03-25T15:06:39.000Z
2020-03-25T15:06:39.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: guardian/guardian.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "guardian/guardian.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace apollo { namespace guardian { namespace { const ::google::protobuf::Descriptor* GuardianCommand_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* GuardianCommand_reflection_ = NULL; } // namespace void protobuf_AssignDesc_guardian_2fguardian_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_guardian_2fguardian_2eproto() { protobuf_AddDesc_guardian_2fguardian_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "guardian/guardian.proto"); GOOGLE_CHECK(file != NULL); GuardianCommand_descriptor_ = file->message_type(0); static const int GuardianCommand_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, header_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, control_command_), }; GuardianCommand_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( GuardianCommand_descriptor_, GuardianCommand::default_instance_, GuardianCommand_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, _has_bits_[0]), -1, -1, sizeof(GuardianCommand), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, _internal_metadata_), -1); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_guardian_2fguardian_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( GuardianCommand_descriptor_, &GuardianCommand::default_instance()); } } // namespace void protobuf_ShutdownFile_guardian_2fguardian_2eproto() { delete GuardianCommand::default_instance_; delete GuardianCommand_reflection_; } void protobuf_AddDesc_guardian_2fguardian_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AddDesc_guardian_2fguardian_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::apollo::common::protobuf_AddDesc_common_2fheader_2eproto(); ::apollo::control::protobuf_AddDesc_control_2fcontrol_5fcmd_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\027guardian/guardian.proto\022\017apollo.guardi" "an\032\023common/header.proto\032\031control/control" "_cmd.proto\"q\n\017GuardianCommand\022%\n\006header\030" "\001 \001(\0132\025.apollo.common.Header\0227\n\017control_" "command\030\002 \001(\0132\036.apollo.control.ControlCo" "mmand", 205); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "guardian/guardian.proto", &protobuf_RegisterTypes); GuardianCommand::default_instance_ = new GuardianCommand(); GuardianCommand::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_guardian_2fguardian_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_guardian_2fguardian_2eproto { StaticDescriptorInitializer_guardian_2fguardian_2eproto() { protobuf_AddDesc_guardian_2fguardian_2eproto(); } } static_descriptor_initializer_guardian_2fguardian_2eproto_; // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int GuardianCommand::kHeaderFieldNumber; const int GuardianCommand::kControlCommandFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 GuardianCommand::GuardianCommand() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.guardian.GuardianCommand) } void GuardianCommand::InitAsDefaultInstance() { header_ = const_cast< ::apollo::common::Header*>(&::apollo::common::Header::default_instance()); control_command_ = const_cast< ::apollo::control::ControlCommand*>(&::apollo::control::ControlCommand::default_instance()); } GuardianCommand::GuardianCommand(const GuardianCommand& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.guardian.GuardianCommand) } void GuardianCommand::SharedCtor() { _cached_size_ = 0; header_ = NULL; control_command_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } GuardianCommand::~GuardianCommand() { // @@protoc_insertion_point(destructor:apollo.guardian.GuardianCommand) SharedDtor(); } void GuardianCommand::SharedDtor() { if (this != default_instance_) { delete header_; delete control_command_; } } void GuardianCommand::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* GuardianCommand::descriptor() { protobuf_AssignDescriptorsOnce(); return GuardianCommand_descriptor_; } const GuardianCommand& GuardianCommand::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_guardian_2fguardian_2eproto(); return *default_instance_; } GuardianCommand* GuardianCommand::default_instance_ = NULL; GuardianCommand* GuardianCommand::New(::google::protobuf::Arena* arena) const { GuardianCommand* n = new GuardianCommand; if (arena != NULL) { arena->Own(n); } return n; } void GuardianCommand::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.guardian.GuardianCommand) if (_has_bits_[0 / 32] & 3u) { if (has_header()) { if (header_ != NULL) header_->::apollo::common::Header::Clear(); } if (has_control_command()) { if (control_command_ != NULL) control_command_->::apollo::control::ControlCommand::Clear(); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool GuardianCommand::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.guardian.GuardianCommand) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .apollo.common.Header header = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_header())); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_control_command; break; } // optional .apollo.control.ControlCommand control_command = 2; case 2: { if (tag == 18) { parse_control_command: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_control_command())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.guardian.GuardianCommand) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.guardian.GuardianCommand) return false; #undef DO_ } void GuardianCommand::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.guardian.GuardianCommand) // optional .apollo.common.Header header = 1; if (has_header()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->header_, output); } // optional .apollo.control.ControlCommand control_command = 2; if (has_control_command()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->control_command_, output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.guardian.GuardianCommand) } ::google::protobuf::uint8* GuardianCommand::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.guardian.GuardianCommand) // optional .apollo.common.Header header = 1; if (has_header()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *this->header_, false, target); } // optional .apollo.control.ControlCommand control_command = 2; if (has_control_command()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->control_command_, false, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.guardian.GuardianCommand) return target; } int GuardianCommand::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.guardian.GuardianCommand) int total_size = 0; if (_has_bits_[0 / 32] & 3u) { // optional .apollo.common.Header header = 1; if (has_header()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->header_); } // optional .apollo.control.ControlCommand control_command = 2; if (has_control_command()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->control_command_); } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void GuardianCommand::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.guardian.GuardianCommand) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const GuardianCommand* source = ::google::protobuf::internal::DynamicCastToGenerated<const GuardianCommand>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.guardian.GuardianCommand) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.guardian.GuardianCommand) MergeFrom(*source); } } void GuardianCommand::MergeFrom(const GuardianCommand& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.guardian.GuardianCommand) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_header()) { mutable_header()->::apollo::common::Header::MergeFrom(from.header()); } if (from.has_control_command()) { mutable_control_command()->::apollo::control::ControlCommand::MergeFrom(from.control_command()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void GuardianCommand::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.guardian.GuardianCommand) if (&from == this) return; Clear(); MergeFrom(from); } void GuardianCommand::CopyFrom(const GuardianCommand& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.guardian.GuardianCommand) if (&from == this) return; Clear(); MergeFrom(from); } bool GuardianCommand::IsInitialized() const { return true; } void GuardianCommand::Swap(GuardianCommand* other) { if (other == this) return; InternalSwap(other); } void GuardianCommand::InternalSwap(GuardianCommand* other) { std::swap(header_, other->header_); std::swap(control_command_, other->control_command_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GuardianCommand::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = GuardianCommand_descriptor_; metadata.reflection = GuardianCommand_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // GuardianCommand // optional .apollo.common.Header header = 1; bool GuardianCommand::has_header() const { return (_has_bits_[0] & 0x00000001u) != 0; } void GuardianCommand::set_has_header() { _has_bits_[0] |= 0x00000001u; } void GuardianCommand::clear_has_header() { _has_bits_[0] &= ~0x00000001u; } void GuardianCommand::clear_header() { if (header_ != NULL) header_->::apollo::common::Header::Clear(); clear_has_header(); } const ::apollo::common::Header& GuardianCommand::header() const { // @@protoc_insertion_point(field_get:apollo.guardian.GuardianCommand.header) return header_ != NULL ? *header_ : *default_instance_->header_; } ::apollo::common::Header* GuardianCommand::mutable_header() { set_has_header(); if (header_ == NULL) { header_ = new ::apollo::common::Header; } // @@protoc_insertion_point(field_mutable:apollo.guardian.GuardianCommand.header) return header_; } ::apollo::common::Header* GuardianCommand::release_header() { // @@protoc_insertion_point(field_release:apollo.guardian.GuardianCommand.header) clear_has_header(); ::apollo::common::Header* temp = header_; header_ = NULL; return temp; } void GuardianCommand::set_allocated_header(::apollo::common::Header* header) { delete header_; header_ = header; if (header) { set_has_header(); } else { clear_has_header(); } // @@protoc_insertion_point(field_set_allocated:apollo.guardian.GuardianCommand.header) } // optional .apollo.control.ControlCommand control_command = 2; bool GuardianCommand::has_control_command() const { return (_has_bits_[0] & 0x00000002u) != 0; } void GuardianCommand::set_has_control_command() { _has_bits_[0] |= 0x00000002u; } void GuardianCommand::clear_has_control_command() { _has_bits_[0] &= ~0x00000002u; } void GuardianCommand::clear_control_command() { if (control_command_ != NULL) control_command_->::apollo::control::ControlCommand::Clear(); clear_has_control_command(); } const ::apollo::control::ControlCommand& GuardianCommand::control_command() const { // @@protoc_insertion_point(field_get:apollo.guardian.GuardianCommand.control_command) return control_command_ != NULL ? *control_command_ : *default_instance_->control_command_; } ::apollo::control::ControlCommand* GuardianCommand::mutable_control_command() { set_has_control_command(); if (control_command_ == NULL) { control_command_ = new ::apollo::control::ControlCommand; } // @@protoc_insertion_point(field_mutable:apollo.guardian.GuardianCommand.control_command) return control_command_; } ::apollo::control::ControlCommand* GuardianCommand::release_control_command() { // @@protoc_insertion_point(field_release:apollo.guardian.GuardianCommand.control_command) clear_has_control_command(); ::apollo::control::ControlCommand* temp = control_command_; control_command_ = NULL; return temp; } void GuardianCommand::set_allocated_control_command(::apollo::control::ControlCommand* control_command) { delete control_command_; control_command_ = control_command; if (control_command) { set_has_control_command(); } else { clear_has_control_command(); } // @@protoc_insertion_point(field_set_allocated:apollo.guardian.GuardianCommand.control_command) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace guardian } // namespace apollo // @@protoc_insertion_point(global_scope)
35.170974
125
0.738907
racestart
d02270a485173a1eff99d741d0d39f556f84faa4
1,046
cpp
C++
code/cpp/NumberOfSymbolsCommonInaSetOfStrings.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/NumberOfSymbolsCommonInaSetOfStrings.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/NumberOfSymbolsCommonInaSetOfStrings.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <map> #include <vector> using namespace std; void remove_dup(string& gems) { map<char, bool> visited; int len = gems.length(); int i = 0; while(i < len) { if(visited[gems[i]]) { gems.erase(i, 1); len--; continue; } visited[gems[i]] = true; ++i; } } int commons(vector<string>& stones) { map<char, int> element_map; int commons = 0; for(int i = 0; i < stones.size(); ++i) { for(int j = 0; j < stones[i].length(); ++j) { element_map[stones[i][j]]++; } } for(map<char, int>::iterator it = element_map.begin(); it != element_map.end(); ++it ) { if(it->second == stones.size()) commons++; } return commons; } int main() { int N; vector<string> stones; cin>>N; for(int i=0; i < N; i++) { string gem; cin>>gem; remove_dup(gem); stones.push_back(gem); } cout<<commons(stones)<<endl; }
20.509804
92
0.5
analgorithmaday
d022d9f43f19a76814e537c7f00d33fcfa32a76e
12,745
cpp
C++
test/err/id/System.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
null
null
null
test/err/id/System.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
178
2018-08-08T04:04:27.000Z
2019-12-15T01:47:58.000Z
test/err/id/System.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
null
null
null
#include "Test.h" #include "test/Message.h" #include "test/Variable.h" #include "test/Case.h" #include "test/var/At.h" #include "err/id/System.h" #include "err/id/rec/ToBytes.h" #include <type_traits> #include <utility> BASIC_TEST_CONSTRUCT; #define BUFFER_FORMAT_CSTRING 256 basic::test::CString<char> IdentificationToString(basic::err::Identification * && id) { typedef typename basic::err::Identification::RecordType RecordType; constexpr std::size_t max_allocation = RecordType::MaximumAllocation(); std::uint8_t block[max_allocation]; std::size_t size_block = basic::err::id::rec:: ToBytes((const RecordType &)*id, block, max_allocation); const std::size_t size = (size_block * 2); char * tmp = new char[size + 1]; for(std::size_t i = 0, j = 0; i < size; i += 2, ++j) { std::uint8_t hex0 = block[j] >> 4; std::uint8_t hex1 = block[j] & std::uint8_t(0x0F); char ch0 = '0', ch1 = '0'; ch0 += (hex0 <= 9 ? hex0 : (hex0 + 7)); ch1 += (hex1 <= 9 ? hex1 : (hex1 + 7)); tmp[i] = ch0; tmp[i + 1] = ch1; } tmp[size] = '\0'; auto ret = basic::test::cstr::Format(BUFFER_FORMAT_CSTRING, "{Size : %d, Block : 0x%s}", size_block, tmp); delete[] tmp; return std::move(ret); } struct TestAliasSystemCategoryValueType {}; struct TestAliasSystemCodeValueType {}; struct TestBaseOfIdentification {}; struct TestCastToIdentification {}; template<typename TObj> using VariableTestIdSystem = basic::test::Variable< basic::err::defn::type::code::Value, basic::err::defn::type::sys::categ::Value, basic::err::defn::type::sys::code::Value, basic::err::Identification, TObj, basic::test::Value<const char *>, basic::test::Value<TObj *>, basic::test::Value<basic::err::Identification *>, basic::test::type::Function<basic::test::CString<char>(basic::err:: Identification * &&), &IdentificationToString>>; constexpr std::size_t ICodeValueType = 0; constexpr std::size_t ISystemCategoryValueType = 1; constexpr std::size_t ISystemCodeValueType = 2; constexpr std::size_t IIdentificationType = 3; constexpr std::size_t IObjType = 4; constexpr std::size_t IObjName = 5; constexpr std::size_t IObjValue = 6; constexpr std::size_t IIdentificationValue = 7; constexpr std::size_t IIdentificationToStringFunc = 8; typedef basic::test::msg::Argument<TestAliasSystemCategoryValueType, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<ISystemCategoryValueType>> ArgTestAliasSystemCategoryValueType; typedef basic::test::msg::Base<TestAliasSystemCategoryValueType, char, ArgTestAliasSystemCategoryValueType, ArgTestAliasSystemCategoryValueType, ArgTestAliasSystemCategoryValueType> MessageBaseTestAliasSystemCategoryValueType; typedef basic::test::msg::Argument<TestAliasSystemCodeValueType, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<ISystemCodeValueType>> ArgTestAliasSystemCodeValueType; typedef basic::test::msg::Base<TestAliasSystemCodeValueType, char, ArgTestAliasSystemCodeValueType, ArgTestAliasSystemCodeValueType, ArgTestAliasSystemCodeValueType> MessageBaseTestAliasSystemCodeValueType; typedef basic::test::msg::Argument<TestBaseOfIdentification, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<IIdentificationType>> ArgTestBaseOfIdentification; typedef basic::test::msg::Base<TestBaseOfIdentification, char, ArgTestBaseOfIdentification, ArgTestBaseOfIdentification, ArgTestBaseOfIdentification> MessageBaseTestBaseOfIdentification; typedef basic::test::msg::Argument<TestCastToIdentification, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<IIdentificationType>, basic::test::msg::arg::type::Function<IIdentificationToStringFunc, basic::test::msg::arg::Value<IIdentificationValue>>> ArgTestCastToIdentification; typedef basic::test::msg::Base<TestCastToIdentification, char, ArgTestCastToIdentification, ArgTestCastToIdentification, ArgTestCastToIdentification> MessageBaseTestCastToIdentification; template<typename TCases, typename... TVariables> struct TestIdSystem : public basic::test::Message<BASIC_TEST, TestIdSystem<TCases, TVariables...>>, public basic::test::Case<TestIdSystem<TCases, TVariables...>, TCases>, public basic::test::Base<TestIdSystem<TCases, TVariables...>, TVariables...>, public MessageBaseTestAliasSystemCategoryValueType, public MessageBaseTestAliasSystemCodeValueType, public MessageBaseTestBaseOfIdentification, public MessageBaseTestCastToIdentification { public: using MessageBaseTestAliasSystemCategoryValueType::Format; using MessageBaseTestAliasSystemCategoryValueType::SetFormat; using MessageBaseTestAliasSystemCategoryValueType::Argument; using MessageBaseTestAliasSystemCodeValueType::Format; using MessageBaseTestAliasSystemCodeValueType::SetFormat; using MessageBaseTestAliasSystemCodeValueType::Argument; using MessageBaseTestBaseOfIdentification::Format; using MessageBaseTestBaseOfIdentification::SetFormat; using MessageBaseTestBaseOfIdentification::Argument; using MessageBaseTestCastToIdentification::Format; using MessageBaseTestCastToIdentification::SetFormat; using MessageBaseTestCastToIdentification::Argument; using basic::test::Case<TestIdSystem<TCases, TVariables...>, TCases>::Run; using basic::test::Base<TestIdSystem<TCases, TVariables...>, TVariables...>::Run; public: TestIdSystem(TVariables & ... var) : basic::test::Message<BASIC_TEST, TestIdSystem<TCases, TVariables...>>(*this), basic::test::Case<TestIdSystem<TCases, TVariables...>, TCases>(*this), basic::test::Base<TestIdSystem<TCases, TVariables...>, TVariables...>(*this, var...) { basic::test::msg::base::Info info; basic::test::msg::base::Debug debug; basic::test::msg::base::Error err; TestAliasSystemCategoryValueType testAliasSystemCategoryValueType; SetFormat(info, testAliasSystemCategoryValueType, "Test alias type " "%s::SystemCategoryValueType {%s} is same with %s\n"); SetFormat(debug, testAliasSystemCategoryValueType, "Test alias type " "%s::SystemCategoryValueType {%s} is same with %s\n"); SetFormat(err, testAliasSystemCategoryValueType, "Error alias type " "%s::SystemCategoryValueType {%s} is not same with %s\n"); TestAliasSystemCodeValueType testAliasSystemCodeValueType; SetFormat(info, testAliasSystemCodeValueType, "Test alias type " "%s::SystemCodeValueType {%s} is same with %s\n"); SetFormat(debug, testAliasSystemCodeValueType, "Test alias type " "%s::SystemCodeValueType {%s} is same with %s\n"); SetFormat(err, testAliasSystemCodeValueType, "Error alias type " "%s::SystemCodeValueType {%s} is not same with %s\n"); TestBaseOfIdentification testBaseOfIdentification; SetFormat(info, testBaseOfIdentification, "Test %s {%s} is base of " "%s\n"); SetFormat(debug, testBaseOfIdentification, "Test %s {%s} is base of " "%s\n"); SetFormat(err, testBaseOfIdentification, "Error %s {%s} is not " "base of %s\n"); TestCastToIdentification testCastToIdentification; SetFormat(info, testCastToIdentification, "Test %s {%s} is same with " "%s %s\n"); SetFormat(debug, testCastToIdentification, "Test %s {%s} is same with " "%s %s\n"); SetFormat(err, testCastToIdentification, "Error %s {%s} is not " "same with %s %s\n"); } template<typename TObj> bool Result(const TestAliasSystemCategoryValueType &, VariableTestIdSystem<TObj> & var) { return typeid(typename basic::err::id::System:: SystemCategoryValueType).hash_code() == typeid(basic::err:: defn::type::sys::categ::Value).hash_code(); } template<typename TObj> bool Result(const TestAliasSystemCodeValueType &, VariableTestIdSystem<TObj> & var) { return typeid(typename basic::err::id::System:: SystemCodeValueType).hash_code() == typeid(basic::err:: defn::type::sys::code::Value).hash_code(); } template<typename TObj> bool Result(const TestBaseOfIdentification &, VariableTestIdSystem<TObj> & var) { return std::is_base_of<basic::err::Identification, TObj>::value; } template<typename TObj> bool Result(const TestCastToIdentification &, VariableTestIdSystem<TObj> & var) { const auto & id_sys = *basic::test::var::At<IObjValue>(var). Get().Get(); const auto & id = *basic::test::var::At<IIdentificationValue>(var). Get().Get(); const bool check_err = id_sys.IsSystem() ? true : (id_sys.Error().Code() == id.Error().Code()); const bool check_err_sys = !id_sys.IsSystem() ? true : (id_sys.ErrorSystem().Code() == id.ErrorSystem().Code() && id_sys.ErrorSystem().Category() == id.ErrorSystem().Category()); return id_sys.IsDefault() == id.IsDefault() && id_sys.IsBad() == id.IsBad() && id_sys.IsStandard() == id.IsStandard() && id_sys.IsCatch() == id.IsCatch() && id_sys.IsSystem() == id.IsSystem() && check_err && check_err_sys; } }; using Case1 = basic::test::type::Parameter<TestAliasSystemCategoryValueType, TestAliasSystemCodeValueType, TestBaseOfIdentification, TestCastToIdentification>; BASIC_TEST_TYPE_NAME("signed char", signed char); BASIC_TEST_TYPE_NAME("char", char); BASIC_TEST_TYPE_NAME("unsigned char", unsigned char); BASIC_TEST_TYPE_NAME("short", short); BASIC_TEST_TYPE_NAME("unsigned short", unsigned short); BASIC_TEST_TYPE_NAME("int", int); BASIC_TEST_TYPE_NAME("unsigned int", unsigned int); BASIC_TEST_TYPE_NAME("long", long); BASIC_TEST_TYPE_NAME("unsigned long", unsigned long); BASIC_TEST_TYPE_NAME("long long", long long); BASIC_TEST_TYPE_NAME("unsigned long long", unsigned long long); BASIC_TEST_TYPE_NAME("basic::err::id::System", basic::err::id::System); BASIC_TEST_TYPE_NAME("basic::err::Identification", basic::err::Identification); typedef VariableTestIdSystem<basic::err::id::System> T1Var1; constexpr typename basic::err::id::System::CodeValueType code_value1 = 4; constexpr typename basic::err::id::System::CategoryValueType categ_value1 = 0xB; basic::err::id::System obj1_1; basic::err::id::System obj1_2{categ_value1, code_value1}; basic::err::id::System obj1_3{basic::err::id::flag::Standard{}, categ_value1, code_value1}; basic::err::Identification id1_1; basic::err::Identification id1_2{basic::err::id::flag::System{}, categ_value1, code_value1}; basic::err::Identification id1_3{basic::err::id::flag::System{}, basic::err::id::flag::Standard{}, categ_value1, code_value1}; T1Var1 t1_var1{"obj1_1", &obj1_1, &id1_1}; T1Var1 t1_var2{"obj1_2", &obj1_2, &id1_2}; T1Var1 t1_var3{"obj1_3", &obj1_3, &id1_3}; REGISTER_TEST(t1, new TestIdSystem<Case1, T1Var1, T1Var1, T1Var1>(t1_var1, t1_var2, t1_var3)); basic::err::id::System obj2_1{obj1_1}; basic::err::id::System obj2_2{obj1_2}; basic::err::id::System obj2_3{obj1_3}; T1Var1 t2_var1{"obj2_1", &obj2_1, &id1_1}; T1Var1 t2_var2{"obj2_2", &obj2_2, &id1_2}; T1Var1 t2_var3{"obj2_3", &obj2_3, &id1_3}; REGISTER_TEST(t2, new TestIdSystem<Case1, T1Var1, T1Var1, T1Var1>(t2_var1, t2_var2, t2_var3)); basic::err::id::System obj2_1_c{obj2_1}; basic::err::id::System obj2_2_c{obj2_2}; basic::err::id::System obj2_3_c{obj2_3}; basic::err::id::System obj3_1{std::move(obj2_1_c)}; basic::err::id::System obj3_2{std::move(obj2_2_c)}; basic::err::id::System obj3_3{std::move(obj2_3_c)}; T1Var1 t3_var1{"obj3_1", &obj3_1, &id1_1}; T1Var1 t3_var2{"obj3_2", &obj3_2, &id1_2}; T1Var1 t3_var3{"obj3_3", &obj3_3, &id1_3}; T1Var1 t3_var4{"obj3_1_c", &obj2_1_c, &id1_1}; T1Var1 t3_var5{"obj3_2_c", &obj2_2_c, &id1_1}; T1Var1 t3_var6{"obj3_3_c", &obj2_3_c, &id1_1}; REGISTER_TEST(t3, new TestIdSystem<Case1, T1Var1, T1Var1, T1Var1, T1Var1, T1Var1, T1Var1>(t3_var1, t3_var2, t3_var3, t3_var4,t3_var5, t3_var6)); int main() { return RUN_TEST(); }
40.332278
79
0.691487
AnantaYudica
d0247ebaf87e6150cd5095f285103e5820f9b090
1,686
hpp
C++
plansys2_problem_expert/include/plansys2_problem_expert/ProblemExpertInterface.hpp
mjcarroll/ros2_planning_system
676d0d3a9629446cdc0797df8daa808e75728cf3
[ "Apache-2.0" ]
null
null
null
plansys2_problem_expert/include/plansys2_problem_expert/ProblemExpertInterface.hpp
mjcarroll/ros2_planning_system
676d0d3a9629446cdc0797df8daa808e75728cf3
[ "Apache-2.0" ]
null
null
null
plansys2_problem_expert/include/plansys2_problem_expert/ProblemExpertInterface.hpp
mjcarroll/ros2_planning_system
676d0d3a9629446cdc0797df8daa808e75728cf3
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Intelligent Robotics Lab // // 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 PLANSYS2_PROBLEM_EXPERT__PROBLEMEXPERTINTERFACE_HPP_ #define PLANSYS2_PROBLEM_EXPERT__PROBLEMEXPERTINTERFACE_HPP_ #include <string> #include <vector> #include "plansys2_domain_expert/Types.hpp" #include "plansys2_problem_expert/Types.hpp" namespace plansys2 { class ProblemExpertInterface { public: ProblemExpertInterface() {} virtual std::vector<Instance> getInstances() = 0; virtual bool addInstance(const Instance & instance) = 0; virtual bool removeInstance(const std::string & name) = 0; virtual boost::optional<Instance> getInstance(const std::string & name) = 0; virtual std::vector<Predicate> getPredicates() = 0; virtual bool addPredicate(const Predicate & predicate) = 0; virtual bool removePredicate(const Predicate & predicate) = 0; virtual bool existPredicate(const Predicate & predicate) = 0; virtual Goal getGoal() = 0; virtual bool setGoal(const Goal & goal) = 0; virtual bool clearGoal() = 0; virtual std::string getProblem() = 0; }; } // namespace plansys2 #endif // PLANSYS2_PROBLEM_EXPERT__PROBLEMEXPERTINTERFACE_HPP_
32.423077
78
0.759786
mjcarroll
d02509ddd5dc23605bb012f156f495806568657e
4,758
cc
C++
ash/autoclick/common/autoclick_controller_common.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
ash/autoclick/common/autoclick_controller_common.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
ash/autoclick/common/autoclick_controller_common.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 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 "ash/autoclick/common/autoclick_controller_common.h" #include "ash/autoclick/common/autoclick_controller_common_delegate.h" #include "ui/aura/window.h" #include "ui/display/screen.h" #include "ui/events/event.h" #include "ui/events/event_constants.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/wm/core/coordinate_conversion.h" namespace ash { namespace { // The threshold of mouse movement measured in DIP that will // initiate a new autoclick. const int kMovementThreshold = 20; bool IsModifierKey(const ui::KeyboardCode key_code) { return key_code == ui::VKEY_SHIFT || key_code == ui::VKEY_LSHIFT || key_code == ui::VKEY_CONTROL || key_code == ui::VKEY_LCONTROL || key_code == ui::VKEY_RCONTROL || key_code == ui::VKEY_MENU || key_code == ui::VKEY_LMENU || key_code == ui::VKEY_RMENU; } } // namespace AutoclickControllerCommon::AutoclickControllerCommon( base::TimeDelta delay, AutoclickControllerCommonDelegate* delegate) : delay_(delay), mouse_event_flags_(ui::EF_NONE), delegate_(delegate), widget_(nullptr), anchor_location_(-kMovementThreshold, -kMovementThreshold), autoclick_ring_handler_(new AutoclickRingHandler()) { InitClickTimer(); } AutoclickControllerCommon::~AutoclickControllerCommon() {} void AutoclickControllerCommon::HandleMouseEvent(const ui::MouseEvent& event) { gfx::Point mouse_location = event.location(); if (event.type() == ui::ET_MOUSE_MOVED && !(event.flags() & ui::EF_IS_SYNTHESIZED)) { mouse_event_flags_ = event.flags(); // TODO(riajiang): Make getting screen location work for mus as well. // Also switch to take in a PointerEvent instead of a MouseEvent after // this is done. (crbug.com/608547) if (event.target() != nullptr) { ::wm::ConvertPointToScreen(static_cast<aura::Window*>(event.target()), &mouse_location); } UpdateRingWidget(mouse_location); // The distance between the mouse location and the anchor location // must exceed a certain threshold to initiate a new autoclick countdown. // This ensures that mouse jitter caused by poor motor control does not // 1. initiate an unwanted autoclick from rest // 2. prevent the autoclick from ever occuring when the mouse // arrives at the target. gfx::Vector2d delta = mouse_location - anchor_location_; if (delta.LengthSquared() >= kMovementThreshold * kMovementThreshold) { anchor_location_ = mouse_location; autoclick_timer_->Reset(); autoclick_ring_handler_->StartGesture(delay_, anchor_location_, widget_); } else if (autoclick_timer_->IsRunning()) { autoclick_ring_handler_->SetGestureCenter(mouse_location, widget_); } } else if (event.type() == ui::ET_MOUSE_PRESSED) { CancelAutoclick(); } else if (event.type() == ui::ET_MOUSEWHEEL && autoclick_timer_->IsRunning()) { autoclick_timer_->Reset(); UpdateRingWidget(mouse_location); autoclick_ring_handler_->StartGesture(delay_, anchor_location_, widget_); } } void AutoclickControllerCommon::HandleKeyEvent(const ui::KeyEvent& event) { int modifier_mask = ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN | ui::EF_IS_EXTENDED_KEY; int new_modifiers = event.flags() & modifier_mask; mouse_event_flags_ = (mouse_event_flags_ & ~modifier_mask) | new_modifiers; if (!IsModifierKey(event.key_code())) CancelAutoclick(); } void AutoclickControllerCommon::SetAutoclickDelay(const base::TimeDelta delay) { delay_ = delay; InitClickTimer(); } void AutoclickControllerCommon::CancelAutoclick() { autoclick_timer_->Stop(); autoclick_ring_handler_->StopGesture(); delegate_->OnAutoclickCanceled(); } void AutoclickControllerCommon::InitClickTimer() { autoclick_timer_.reset(new base::Timer( FROM_HERE, delay_, base::Bind(&AutoclickControllerCommon::DoAutoclick, base::Unretained(this)), false)); } void AutoclickControllerCommon::DoAutoclick() { gfx::Point screen_location = display::Screen::GetScreen()->GetCursorScreenPoint(); anchor_location_ = screen_location; delegate_->DoAutoclick(screen_location, mouse_event_flags_); } void AutoclickControllerCommon::UpdateRingWidget( const gfx::Point& mouse_location) { if (!widget_) { widget_ = delegate_->CreateAutoclickRingWidget(mouse_location); } else { delegate_->UpdateAutoclickRingWidget(widget_, mouse_location); } } } // namespace ash
36.320611
80
0.714586
google-ar
d02544ddd1be1a6bf3b41d3a07d7085e57b7c2f1
739
cpp
C++
UVa Online Judge (UVa)/Volume 102/10226 - Hardwood Species.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 102/10226 - Hardwood Species.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 102/10226 - Hardwood Species.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
2
2018-11-06T19:37:56.000Z
2018-11-09T19:05:46.000Z
#include <bits/stdc++.h> using namespace std; string name; map <string, int> msi; map <string, int> :: iterator mit; int main( int argc, char ** argv ) { // freopen( "in.txt", "r", stdin ); int tc; scanf( "%d ", &tc ); for( int nCase = 1 ; nCase <= tc ; ++nCase ) { msi.clear(); int total = 0; while( getline( cin, name ) && name.size() ) { ++msi[name]; ++total; } if( nCase > 1 ) puts( "" ); for( mit = msi.begin() ; mit != msi.end() ; ++mit ) { double result = ((double) (mit->second * 100) ) / ((double) total); cout << mit->first << " " << fixed << setprecision( 4 ) << result << endl; } } return 0; }
24.633333
86
0.460081
sreejonK19
d0283ea2630da8f55c697dd4ced02391d4f5681d
4,951
cpp
C++
tasks/FrameFilter.cpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
1
2022-01-31T01:59:52.000Z
2022-01-31T01:59:52.000Z
tasks/FrameFilter.cpp
PhischDotOrg/stm32-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
5
2020-04-13T21:55:12.000Z
2020-06-27T17:44:44.000Z
tasks/FrameFilter.cpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
null
null
null
/*- * $Copyright$ -*/ #include "tasks/FrameSampler.hpp" #ifndef _FRAME_FILTER_CPP_4085c3de_7e34_4002_a351_d24c2cd81aff #define _FRAME_FILTER_CPP_4085c3de_7e34_4002_a351_d24c2cd81aff #if defined(__cplusplus) extern "C" { #endif /* defined(__cplusplus) */ #include "FreeRTOS/FreeRTOS.h" #include "FreeRTOS/task.h" #include "FreeRTOS/queue.h" #include "FreeRTOS/semphr.h" #if defined(__cplusplus) } /* extern "C" */ #endif /* defined(__cplusplus) */ namespace tasks { /******************************************************************************* * ******************************************************************************/ template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterT, typename PinT, typename UartT> FrameFilterT<InputBufferT, OutputBufferT, N, FilterT, PinT, UartT>::FrameFilterT(const char * const p_name, const unsigned p_priority, UartT &p_uart, OutputBufferT (&p_frames)[N], FilterT &p_filter) : Task(p_name, p_priority, configMINIMAL_STACK_SIZE * 2), m_uart(p_uart), m_frames(p_frames), m_filter(p_filter), m_activeIndicationPin(NULL), m_current(0), m_rxQueue(NULL), m_txQueue(NULL) { } /******************************************************************************* * ******************************************************************************/ template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterChainT, typename PinT, typename UartT> FrameFilterT<InputBufferT, OutputBufferT, N, FilterChainT, PinT, UartT>::~FrameFilterT() { } /******************************************************************************* * ******************************************************************************/ template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterChainT, typename PinT, typename UartT> void FrameFilterT<InputBufferT, OutputBufferT, N, FilterChainT, PinT, UartT>::run(void) { this->m_uart.printf("Task '%s' starting...\r\n", this->m_name); InputBufferT *rxBuffer; int rc = 0; /* Can't do this in the constructor; FreeRTOS must be running */ for (unsigned i = 0; i < N; i++) { this->m_frames[i].unlock(); } for (OutputBufferT *txBuffer = &this->m_frames[0]; ; txBuffer = &this->m_frames[++this->m_current % N]) { if (xQueueReceive(*this->m_rxQueue, &rxBuffer, portMAX_DELAY) != pdTRUE) { this->m_uart.printf("%s(): Failed to receive buffer from queue. Aborting!\r\n", this->m_name); break; } #if defined(WITH_PROFILING) if (this->m_activeIndicationPin != NULL) this->m_activeIndicationPin->set(gpio::Pin::On); #endif /* defined(WITH_PROFILING) */ if (rxBuffer->lock() != 0) { this->m_uart.printf("%s(): Failed to lock Rx Buffer. Aborting!\r\n", this->m_name); break; }; if (txBuffer->lock() != 0) { this->m_uart.printf("%s(): Failed to lock Buffer %u. Aborting!\r\n", this->m_name, this->m_current); break; }; this->m_filter.filter(*rxBuffer, *txBuffer); #if defined(DEBUG_FRAME_FILTER) unsigned idx = 0; for (typename OutputBufferT::const_iterator iter = txBuffer->begin(); iter != txBuffer->end(); iter++, idx++) { volatile unsigned value = ((*iter) * 1000); m_uart.printf("%s(): %d: %d\r\n", this->m_name, idx, (value + 500) / 1000); } #endif /* defined(DEBUG_FRAME_FILTER) */ if (txBuffer->unlock() != 0) { this->m_uart.printf("%s(): Failed to unlock Buffer %u. Aborting!\r\n", this->m_name, this->m_current); break; }; if (rxBuffer->unlock() != 0) { this->m_uart.printf("%s(): Failed to unlock Rx Buffer. Aborting!\r\n", this->m_name); break; } if (rc == 0) { /* * This copies n bytes from &buffer into the queue. The value n is * configured as sizeof(OutputBufferT*) when the queue was created). So * basically, this copies the contents of the buffer pointer to the * queue which, in effect, writes a OutputBufferT * to the queue. */ if (xQueueSend(*this->m_txQueue, &txBuffer, 0) != pdTRUE) { this->m_uart.printf("%s(): Failed to post buffer %d to queue. Aborting!\r\n", this->m_name, this->m_current % N); break; } } else { this->m_uart.printf("%s(): Failed to fill frame buffer with samples!\r\n", this->m_name); } #if defined(WITH_PROFILING) if (this->m_activeIndicationPin != NULL) this->m_activeIndicationPin->set(gpio::Pin::Off); #endif /* defined(WITH_PROFILING) */ } this->m_uart.printf("%s() ended!\r\n", this->m_name); halt(__FILE__, __LINE__); } } /* namespace tasks */ #endif /* _FRAME_FILTER_CPP_4085c3de_7e34_4002_a351_d24c2cd81aff */
40.252033
146
0.565946
PhischDotOrg
d02d99d2d8fdc4ae9ca2b31e5ac7d74a8c51bd3e
3,321
cpp
C++
src/menustate.cpp
jumpmanmv/pixeltetris
4a40543e5919b3ca3b35c2310da258a6cf5d224f
[ "MIT" ]
2
2021-05-07T15:05:56.000Z
2021-11-16T17:33:46.000Z
src/menustate.cpp
jumpmanmv/pixeltetris
4a40543e5919b3ca3b35c2310da258a6cf5d224f
[ "MIT" ]
null
null
null
src/menustate.cpp
jumpmanmv/pixeltetris
4a40543e5919b3ca3b35c2310da258a6cf5d224f
[ "MIT" ]
null
null
null
#include "menustate.hpp" #include <iostream> //debug #include <vector> #include <SDL2/SDL.h> #include "config.hpp" #include "inputmanager.hpp" #include "renderer.hpp" #include "state.hpp" /* * ==================================== * Public methods start here * ==================================== */ MenuState::MenuState (InputManager *manager) : State (manager) {} MenuState::~MenuState () { exit(); } void MenuState::initialize () { index = 0; title_text = new Texture(); title_text->loadFromText ("Pixeltetris!", Game::getInstance()->mRenderer->bigFont, config::default_text_color); #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) mButtons.push_back(new Button ("../../assets/button-play.png", &Game::pushNewGame, (config::logical_window_width-80)/2, 130)); mButtons.push_back(new Button ("../../assets/button-options.png", &Game::pushOptions, (config::logical_window_width-80)/2, 180)); mButtons.push_back(new Button ("../../assets/button-exit.png", &Game::goBack, (config::logical_window_width-80)/2, 230)); #else mButtons.push_back(new Button ("../assets/button-play.png", &Game::pushNewGame, (config::logical_window_width-80)/2, 130)); mButtons.push_back(new Button ("../assets/button-options.png", &Game::pushOptions, (config::logical_window_width-80)/2, 180)); mButtons.push_back(new Button ("../assets/button-exit.png", &Game::goBack, (config::logical_window_width-80)/2, 230)); #endif } void MenuState::exit () { for (auto i : mButtons) { delete i; } } void MenuState::run () { update(); draw(); } void MenuState::update () { while (mInputManager->pollAction() != 0) { if (mInputManager->isGameExiting()) { nextStateID = STATE_EXIT; break; } switch (mInputManager->getAction()) { case Action::select: { mButtons[index]->callbackFunction(); break; } case Action::move_up: { if (index > 0) { --index; } break; } case Action::move_down: { if (index < mButtons.size()-1) { ++index; } break; } } } } void MenuState::draw () { Game::getInstance()->mRenderer->clearScreen(); for (auto i : mButtons) { i->draw(); } title_text->renderCentered(config::logical_window_width/2, 50); SDL_Rect highlight_box = {mButtons[index]->getX(), mButtons[index]->getY(), mButtons[index]->getWidth(), mButtons[index]->getHeight()}; SDL_SetRenderDrawBlendMode (Game::getInstance()->mRenderer->mSDLRenderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor (Game::getInstance()->mRenderer->mSDLRenderer, 255, 255, 255, config::transparency_alpha-20); SDL_RenderFillRect(Game::getInstance()->mRenderer->mSDLRenderer, &highlight_box); SDL_SetRenderDrawBlendMode (Game::getInstance()->mRenderer->mSDLRenderer, SDL_BLENDMODE_NONE); Game::getInstance()->mRenderer->updateScreen(); } void MenuState::addButton (Button *button) { mButtons.push_back(button); }
28.878261
139
0.586871
jumpmanmv
d02db68039e6d395d4ec07e96e7f37ef581edfb8
2,315
cpp
C++
admin/wmi/wbem/winmgmt/esscomp/forwarding/fconprov.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/winmgmt/esscomp/forwarding/fconprov.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/winmgmt/esscomp/forwarding/fconprov.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "precomp.h" #include <assert.h> #include <sync.h> #include <arrtempl.h> #include <wstring.h> #include <comutl.h> #include <statsync.h> #include <map> #include <wstlallc.h> #include "fconprov.h" #include "fconnspc.h" #include "fconsink.h" LPCWSTR g_wszNamespace = L"__NAMESPACE"; LPCWSTR g_wszClass = L"__CLASS"; LPCWSTR g_wszEventFwdCons = L"MSFT_EventForwardingConsumer"; LPCWSTR g_wszDataFwdCons = L"MSFT_DataForwardingConsumer"; static CStaticCritSec g_cs; typedef CWbemPtr<CFwdConsNamespace> CFwdConsNamespaceP; typedef std::map<WString,CFwdConsNamespaceP,WSiless,wbem_allocator<CFwdConsNamespaceP> > NamespaceMap; NamespaceMap* g_pNamespaces; HRESULT CFwdConsProv::InitializeModule() { g_pNamespaces = new NamespaceMap; if ( g_pNamespaces == NULL ) { return WBEM_E_OUT_OF_MEMORY; } return WBEM_S_NO_ERROR; } void CFwdConsProv::UninitializeModule() { delete g_pNamespaces; } HRESULT CFwdConsProv::FindConsumer( IWbemClassObject* pCons, IWbemUnboundObjectSink** ppSink ) { ENTER_API_CALL HRESULT hr; // // workaround for bogus context object left on thread by wmi. // just remove it. shouldn't leak because this call doesn't addref it. // IUnknown* pCtx; CoSwitchCallContext( NULL, &pCtx ); // // first obtain the namespace object. we derive the namespace from // the consumer object. If no namespace obj is there, create one. // CPropVar vNamespace; hr = pCons->Get( g_wszNamespace, 0, &vNamespace, NULL, NULL ); if ( FAILED(hr) || FAILED(hr=vNamespace.SetType(VT_BSTR)) ) { return hr; } CInCritSec ics( &g_cs ); CWbemPtr<CFwdConsNamespace> pNspc = (*g_pNamespaces)[V_BSTR(&vNamespace)]; if ( pNspc == NULL ) { pNspc = new CFwdConsNamespace; if ( pNspc == NULL ) { return WBEM_E_OUT_OF_MEMORY; } hr = pNspc->Initialize( V_BSTR(&vNamespace) ); if ( FAILED(hr) ) { return hr; } (*g_pNamespaces)[V_BSTR(&vNamespace)] = pNspc; } return CFwdConsSink::Create( m_pControl, pNspc, pCons, ppSink ); EXIT_API_CALL }
23.865979
104
0.631102
npocmaka
d02e2fef6086d606dee2b2a510ff67a73450e2b3
175
cpp
C++
applications/sandbox/systems/gui_test.cpp
Rythe-Interactive/Rythe-Engine.rythe-legacy
c119c494524b069a73100b12dc3d8b898347830d
[ "MIT" ]
2
2022-03-08T09:46:17.000Z
2022-03-28T08:07:05.000Z
applications/sandbox/systems/gui_test.cpp
Rythe-Interactive/Rythe-Engine.rythe-legacy
c119c494524b069a73100b12dc3d8b898347830d
[ "MIT" ]
3
2022-03-02T13:49:10.000Z
2022-03-22T11:54:06.000Z
applications/sandbox/systems/gui_test.cpp
Rythe-Interactive/Rythe-Engine.rythe-legacy
c119c494524b069a73100b12dc3d8b898347830d
[ "MIT" ]
null
null
null
#include "gui_test.hpp" bool legion::GuiTestSystem::captured = false; bool legion::GuiTestSystem::isEditingText = false; legion::ecs::entity legion::GuiTestSystem::selected;
29.166667
52
0.782857
Rythe-Interactive
d0317bfdeb24757d771b5c209eff14e2866e5de9
736
cpp
C++
source.cpp
IshaySela/lightningPlusPlus
bdd81921c6f112b7ed51bb3297ffc213d256e178
[ "MIT" ]
1
2022-01-20T15:51:04.000Z
2022-01-20T15:51:04.000Z
source.cpp
IshaySela/lightningPlusPlus
bdd81921c6f112b7ed51bb3297ffc213d256e178
[ "MIT" ]
1
2022-01-30T10:15:29.000Z
2022-01-30T10:15:29.000Z
source.cpp
IshaySela/lightningPlusPlus
bdd81921c6f112b7ed51bb3297ffc213d256e178
[ "MIT" ]
null
null
null
#include <iostream> #include <lightning/httpServer/ServerBuilder.hpp> constexpr const char *PublicKeyPath = "/home/ishaysela/projects/lightningPlusPlus/tests/localhost.cert"; constexpr const char *PrivateKeyPath = "/home/ishaysela/projects/lightningPlusPlus/tests/localhost.key"; auto main() -> int { auto server = lightning::ServerBuilder::createNew(8080) .withSsl(PublicKeyPath, PrivateKeyPath) .withThreads(1) .build(); auto getForcast = [](lightning::HttpRequest request) { int x; return lightning::HttpResponseBuilder::create() .build(); }; server.get("/forcast", getForcast); server.start(); return 0; }
29.44
104
0.641304
IshaySela
d0327b0a24259003449b06c9f5d018f72a0dc192
33
cpp
C++
tutorials/learncpp.com#1.0#1/control_flow/for_statements/source8.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/control_flow/for_statements/source8.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/control_flow/for_statements/source8.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
if (nValue == 0); nValue = 1;
16.5
17
0.484848
officialrafsan
d0345f9e3c9d3fad1356be7892fbeaf358ead281
231
cpp
C++
GreetingKit/HelloCpp.cpp
skyfe79/GreetingKit
034ad4bb8687bcfa24168f5a0803af89210bb73e
[ "MIT" ]
null
null
null
GreetingKit/HelloCpp.cpp
skyfe79/GreetingKit
034ad4bb8687bcfa24168f5a0803af89210bb73e
[ "MIT" ]
null
null
null
GreetingKit/HelloCpp.cpp
skyfe79/GreetingKit
034ad4bb8687bcfa24168f5a0803af89210bb73e
[ "MIT" ]
null
null
null
// // HelloCpp.cpp // GreetingKit // // Created by burt on 2016. 3. 3.. // Copyright © 2016년 BurtK. All rights reserved. // #include "HelloCpp.hpp" HelloCpp::HelloCpp(std::string msg) { printf("C++ %s\n", msg.c_str()); }
16.5
49
0.614719
skyfe79
d035e73431be12b96218067cda121ca7284e9d35
3,089
cpp
C++
Task 1/LongestArithmeticSubsequence/answer.cpp
anjali-coder/Hacktoberfest_2020
05cf51d9b791b89f93158971637ba931a3037dc5
[ "MIT" ]
74
2021-09-22T06:29:40.000Z
2022-01-20T14:46:11.000Z
Task 1/LongestArithmeticSubsequence/answer.cpp
anjali-coder/Hacktoberfest_2020
05cf51d9b791b89f93158971637ba931a3037dc5
[ "MIT" ]
65
2020-10-02T11:03:42.000Z
2020-11-01T06:00:25.000Z
Task 1/LongestArithmeticSubsequence/answer.cpp
anjali-coder/Hacktoberfest_2020
05cf51d9b791b89f93158971637ba931a3037dc5
[ "MIT" ]
184
2020-10-02T10:53:53.000Z
2021-08-20T12:27:04.000Z
// longest arithmetic progression subsequence #138 #include <iostream> #include <vector> #include <algorithm> using namespace std; int longestAP (int set[], int n) { if (n <= 2) return n; //create a table and init all vals as 2. int TBL[n][n]; int lapLen = 2; for (int i = 0; i < n; i++) TBL[i][n-1] = 2; // consider every element as second element of ap for ( int j=n-2; j >= 1; j--) { // search for i and k for j int i = j-1, k = j+1; while (i >= 0 && k <= n-1) { if (set[i] + set[k] < 2*set[j]) k++; // before changing i set TBL[i][j] as 2 else if (set[i] + set[k] > 2*set[j]) { TBL[i][j] =2, i--; } else { // found i and k for j, lapLen with i and j as the first two elements // are equal to lapLen with j and k as the first two elements +1 TBL[i][j] = TBL[j][k] +1; // update overall lapLen if needed lapLen = max(lapLen, TBL[i][j]); // change i and k to fill more TBL[i][j] values for current j i--; k++; } } // set remaining enitites in collum j as 2 while (i >= 0) { TBL[i][j] = 2; i--; } } return lapLen; } // this function improves space complexity from O(h) -> O(n) int improvedSpaceSol (vector<int> A) { int len = 2; int n = A.size(); if (n <= 2) return n; vector<int> ap(n, 2); sort(A.begin(), A.end()); for (int j = n-2; j >= 0; j--) { int i = j-1; int k = j+1; while ( i >= 0 && k < n) { if(A[i] + A[k] == 2 * A[j]){ ap[j] = max(ap[k] + 1, ap[j]); len = max(len, ap[j]); i -= 1; k += 1; } else if (A[i] + A[k] < 2 * A[j]) { k += 1; } else { i -= 1; } } } return len; } // this function using vector<vector<int> is faster then other 2d / x_map approaches. int lasl (vector<int> A) { int len = 2; int n = A.size(); vector<vector<int>> dp(n, vector<int>(2000,0)); for (int i = 0; i < n; i++){ for(int j = i+1; j < n; j++){ int dif = A[j] - A[i] + 1000; dp[j][dif] = max(2, dp[i][dif] +1 ); len = max(len, dp[j][dif]); } } return len; } // tests int main() { cout << "first approach in O(n^2) time & O(n^2) space\n"; int set[] = {1, 7, 10, 13, 14, 19}; int n1 = sizeof(set)/sizeof(set[0]); cout << longestAP(set, n1) << endl; cout << "improved approach in O(n^2) time & O(n) space\n"; vector<int>set2({1, 7, 10, 13, 14, 19}); cout << improvedSpaceSol(set2) << endl; cout << "vector of vector runs faster but idk wh..\n"; vector<int>set3({1, 3, 5, 7, 9, 30}); cout << lasl(set2) << endl; return 0; }
31.845361
87
0.431208
anjali-coder
d03699385d86d7ebf09248cf6c615dcf06c65221
7,717
cpp
C++
codecparsers/mpeg2_parser_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
89
2015-01-09T10:31:13.000Z
2018-01-18T12:48:21.000Z
codecparsers/mpeg2_parser_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
626
2015-01-12T00:01:26.000Z
2018-01-23T18:58:58.000Z
codecparsers/mpeg2_parser_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
104
2015-01-12T04:02:09.000Z
2017-12-28T08:27:42.000Z
/* * Copyright 2016 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // primary header #include "mpeg2_parser.h" // library headers #include "common/Array.h" #include "common/log.h" #include "common/unittest.h" // system headers #include <limits> #include <time.h> //using rand namespace YamiParser { namespace MPEG2 { const static std::array<const uint8_t, 9> SequenceHeader = { 0xb3, 0x20, 0x01, 0x20, 0x34, 0xff, 0xff, 0xe0, 0x18 }; const static std::array<const uint8_t, 7> SequenceExtension = { 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00 }; const static std::array<const uint8_t, 5> GroupOfPicturesHeader = { 0xb8, 0x00, 0x08, 0x06, 0x00 }; const static std::array<const uint8_t, 5> PictureHeaderArray = { 0x00, 0x00, 0x0f, 0xff, 0xf8 }; const static std::array<const uint8_t, 6> PictureCodingExtensionArray = { 0xb5, 0x8f, 0xff, 0xf3, 0x41, 0x80 }; const static std::array<const uint8_t, 124> SliceArray = { 0x01, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0x00 }; class MPEG2ParserTest : public ::testing::Test { protected: #define MEMBER_VARIABLE(result_type, var) \ result_type& var(Parser& p) { return p.var; } MEMBER_VARIABLE(SeqHeader, m_sequenceHdr); MEMBER_VARIABLE(SeqExtension, m_sequenceExtension); MEMBER_VARIABLE(GOPHeader, m_GOPHeader); MEMBER_VARIABLE(PictureHeader, m_pictureHeader); MEMBER_VARIABLE(PictureCodingExtension, m_pictureCodingExtension); #undef MEMBER_VARIABLE void checkParamsSeqHeader(const Parser& parser) { EXPECT_EQ(0x200u, parser.m_sequenceHdr.horizontal_size_value); EXPECT_EQ(0x120u, parser.m_sequenceHdr.vertical_size_value); EXPECT_EQ(3u, parser.m_sequenceHdr.aspect_ratio_info); EXPECT_EQ(4u, parser.m_sequenceHdr.frame_rate_code); EXPECT_EQ(0x3ffffu, parser.m_sequenceHdr.bit_rate_value); EXPECT_EQ(3u, parser.m_sequenceHdr.vbv_buffer_size_value); } void checkParamsSeqExtension(const Parser& parser) { EXPECT_EQ(0x48u, parser.m_sequenceExtension.profile_and_level_indication); EXPECT_EQ(1, parser.m_sequenceExtension.progressive_sequence); EXPECT_EQ(1u, parser.m_sequenceExtension.chroma_format); } void checkParamsPictureHeader(const Parser& parser) { EXPECT_EQ(1u, parser.m_pictureHeader.picture_coding_type); EXPECT_EQ(0xffffu, parser.m_pictureHeader.vbv_delay); } void checkParamsPictureCodingExtension(const Parser& parser) { EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[0][0]); EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[0][1]); EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[1][0]); EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[1][1]); EXPECT_EQ(0u, parser.m_pictureCodingExtension.intra_dc_precision); EXPECT_EQ(3u, parser.m_pictureCodingExtension.picture_structure); EXPECT_EQ(1, parser.m_pictureCodingExtension.frame_pred_frame_dct); EXPECT_EQ(1, parser.m_pictureCodingExtension.chrome_420_type); EXPECT_EQ(1, parser.m_pictureCodingExtension.progressive_frame); } void checkParamsSlice(const Parser& parser, Slice& slice) { EXPECT_EQ(6u, slice.sliceHeaderSize); EXPECT_EQ(0u, slice.macroblockRow); EXPECT_EQ(0u, slice.macroblockColumn); } }; bool createDu(DecodeUnit& du, const uint8_t* data, size_t size, StartCodeType expected) { if (!du.parse(data, size)) return false; return du.m_type == expected; } bool checkExtension(BitReader& br, ExtensionIdentifierType expected) { uint32_t id; if (!br.read(id, 4)) return false; return id == expected; } #define MPEG2_PARSER_TEST(name) TEST_F(MPEG2ParserTest, name) MPEG2_PARSER_TEST(ParseSequenceHeader) { Parser parser; DecodeUnit du; EXPECT_TRUE(createDu(du, &SequenceHeader[0], SequenceHeader.size(), MPEG2_SEQUENCE_HEADER_CODE)); SharedPtr<QuantMatrices> m; EXPECT_TRUE(parser.parseSequenceHeader(du, m)); EXPECT_TRUE(m); checkParamsSeqHeader(parser); } MPEG2_PARSER_TEST(ParseSequenceExtension) { DecodeUnit du; EXPECT_TRUE(createDu(du, &SequenceExtension[0], SequenceExtension.size(), MPEG2_EXTENSION_START_CODE)); BitReader br(du.m_data, du.m_size); EXPECT_TRUE(checkExtension(br, kSequence)); Parser parser; EXPECT_TRUE(parser.parseSequenceExtension(br)); checkParamsSeqExtension(parser); } MPEG2_PARSER_TEST(ParseGOPHeader) { DecodeUnit du; EXPECT_TRUE(createDu(du, &GroupOfPicturesHeader[0], GroupOfPicturesHeader.size(), MPEG2_GROUP_START_CODE)); Parser parser; EXPECT_TRUE(parser.parseGOPHeader(du)); //all params will be zero for this unittest } MPEG2_PARSER_TEST(ParsePictureHeader) { DecodeUnit du; EXPECT_TRUE(createDu(du, &PictureHeaderArray[0], PictureHeaderArray.size(), MPEG2_PICTURE_START_CODE)); Parser parser; EXPECT_TRUE(parser.parsePictureHeader(du)); checkParamsPictureHeader(parser); } MPEG2_PARSER_TEST(ParsePictureCodingExtension) { DecodeUnit du; EXPECT_TRUE(createDu(du, &PictureCodingExtensionArray[0], PictureCodingExtensionArray.size(), MPEG2_EXTENSION_START_CODE)); BitReader br(du.m_data, du.m_size); EXPECT_TRUE(checkExtension(br, kPictureCoding)); Parser parser; EXPECT_TRUE(parser.parsePictureCodingExtension(br)); checkParamsPictureCodingExtension(parser); } MPEG2_PARSER_TEST(ParseSlice) { DecodeUnit du; EXPECT_TRUE(createDu(du, &SliceArray[0], SliceArray.size(), MPEG2_SLICE_START_CODE_MIN)); Parser parser; Slice slice; EXPECT_TRUE(parser.parseSlice(slice, du)); checkParamsSlice(parser, slice); } } // namespace MPEG2 } // namespace YamiParser
35.237443
131
0.662434
genisysram
d036ee1170c75bf67a68afdc072618208fbac472
867
cpp
C++
src/tuw_geometry/polar2d.cpp
baluke/tuw_geometry
eaa03386d91f38f70a11dac242ff92eca24906e5
[ "BSD-2-Clause" ]
null
null
null
src/tuw_geometry/polar2d.cpp
baluke/tuw_geometry
eaa03386d91f38f70a11dac242ff92eca24906e5
[ "BSD-2-Clause" ]
null
null
null
src/tuw_geometry/polar2d.cpp
baluke/tuw_geometry
eaa03386d91f38f70a11dac242ff92eca24906e5
[ "BSD-2-Clause" ]
null
null
null
#include <memory> #include <tuw_geometry/polar2d.h> using namespace tuw; Polar2D::Polar2D () : Point2D ( 0,0 ) {}; Polar2D::Polar2D ( const Point2D &p ) : Point2D ( atan2( p.y(), p.x()), sqrt( p.x() * p.x() + p.y()* p.y() ), 1 ) {}; Polar2D::Polar2D ( double alpha, double rho ) : Point2D ( alpha,rho ) {}; Polar2D::Polar2D ( double alpha, double rho, double h ) : Point2D ( alpha, rho, h ) {}; /** * @return alpha **/ const double &Polar2D::alpha () const { return x(); } /** * @return alpha **/ double &Polar2D::alpha () { return x(); } /** * @return rho component **/ const double &Polar2D::rho () const { return y(); } /** * @return rho component **/ double &Polar2D::rho () { return y(); } /** * @return point in cartesian space **/ Point2D Polar2D::point () const { return Point2D(cos(alpha()) * rho(), sin(alpha()) * rho()); }
21.146341
117
0.579008
baluke
d038351d3a364558234f3d429eb9cc35c15e8c5b
1,606
hpp
C++
Header Files/Game.hpp
zhihanLin/text-based-RPG
1d4919a3d9569739ea924a5aa4699a3995dab043
[ "FSFAP" ]
null
null
null
Header Files/Game.hpp
zhihanLin/text-based-RPG
1d4919a3d9569739ea924a5aa4699a3995dab043
[ "FSFAP" ]
null
null
null
Header Files/Game.hpp
zhihanLin/text-based-RPG
1d4919a3d9569739ea924a5aa4699a3995dab043
[ "FSFAP" ]
null
null
null
// // Game.hpp // idleRPG // // Created by ZHIHAN LIN on 4/17/20. // Copyright © 2020 ZHIHAN LIN. All rights reserved. // #ifndef Game_hpp #define Game_hpp #include <stdio.h> #include <iterator> #include <algorithm> #include <ctime> #include <string> #include <vector> #include <deque> #include <fstream> #include "Inventory.hpp" #include "Dungeon.hpp" #include "InvalidMenuChoice.hpp" #include "Shop.hpp" using namespace std; class Game{ private: // for menu int choice; bool tryAgain = false; bool ifPlaying = true; bool lv15Recruitment = true; bool lv30Recruitment = true; protected: vector<Hero> heros; vector<Hero> newHeros; vector<Hero>::iterator it; // for save and load ofstream herosOut; ifstream herosIn; // temporarily store record in queue, // 10 records of heros are allowed, // the latest record will push out the oldest one string record; deque<string> herosRecords; public: Inventory backPack; Game(); ~Game(); // function void menu(); void choiceBetween(const int &begin, const int &end); void menu_inventory(); void menu_applyWeapon(const int &index, string &itemName, int &itemLevel); void menu_applyArmor(const int &index, string &itemName, int &itemLevel); void createHero(); void save(); // 10 records are allowed void load(); void pause(); // setter void setPlaying(bool tf) { this->ifPlaying = tf; } // gettet bool getPlaying() { return this->ifPlaying; } }; #endif /* Game_hpp */
21.131579
78
0.640722
zhihanLin
d03a3dfeb4eaf07698b73b1f08901ead91400deb
1,052
hpp
C++
ios/Pods/boost-for-react-native/boost/hana/concept/logical.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/hana/concept/logical.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/hana/concept/logical.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
/*! @file Defines `boost::hana::Logical`. @copyright Louis Dionne 2013-2016 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_CONCEPT_LOGICAL_HPP #define BOOST_HANA_CONCEPT_LOGICAL_HPP #include <boost/hana/fwd/concept/logical.hpp> #include <boost/hana/config.hpp> #include <boost/hana/core/default.hpp> #include <boost/hana/core/tag_of.hpp> #include <boost/hana/detail/integral_constant.hpp> #include <boost/hana/eval_if.hpp> #include <boost/hana/not.hpp> #include <boost/hana/while.hpp> BOOST_HANA_NAMESPACE_BEGIN template <typename L> struct Logical : hana::integral_constant<bool, !is_default<eval_if_impl<typename tag_of<L>::type>>::value && !is_default<not_impl<typename tag_of<L>::type>>::value && !is_default<while_impl<typename tag_of<L>::type>>::value > { }; BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_CONCEPT_LOGICAL_HPP
29.222222
79
0.706274
rudylee
d03bd3c5964ebbbad0644444a9a8065c1aac4201
2,088
cpp
C++
domain/thumbnaildatabase.cpp
goph-R/Pixie
89beacd5aca02a3fe4a9f8dcbe9eeda7ca0f1a37
[ "Apache-2.0" ]
2
2016-10-16T13:06:42.000Z
2020-06-07T19:30:34.000Z
domain/thumbnaildatabase.cpp
goph-R/Pixie
89beacd5aca02a3fe4a9f8dcbe9eeda7ca0f1a37
[ "Apache-2.0" ]
2
2019-12-20T11:35:51.000Z
2019-12-20T11:37:26.000Z
domain/thumbnaildatabase.cpp
goph-R/Pixie
89beacd5aca02a3fe4a9f8dcbe9eeda7ca0f1a37
[ "Apache-2.0" ]
null
null
null
#include "domain/thumbnaildatabase.h" #include <QSqlQuery> #include <QSqlRecord> #include <QSqlField> #include <QBuffer> #include <QSqlError> #include <QSqlDriver> #include <QDebug> ThumbnailDatabase::ThumbnailDatabase(QString path) : QObject() { databasePath = path; } void ThumbnailDatabase::connect() { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(databasePath); } ThumbnailDatabase::~ThumbnailDatabase() { if (db.open()) { db.close(); } } const char* ThumbnailDatabase::getImageFormat(int format) { return format == FORMAT_PNG ? "png" : "jpg"; } void ThumbnailDatabase::find(QString path) { if (!db.open()) { emit notFound(path); return; } QSqlQuery query; QSqlRecord record; QImage image; query.prepare("SELECT format, image FROM thumbnail WHERE path = :path"); query.bindValue(":path", path); if (!query.exec()) { } if (query.first()) { record = query.record(); auto format = record.field("format").value().toInt(); auto data = record.field("image").value().toByteArray(); image.loadFromData(data, getImageFormat(format)); emit found(path, image); } else { emit notFound(path); } } void ThumbnailDatabase::save(QString path, QImage image, int format) { if (!db.open()) { return; } QByteArray ba; QBuffer buffer(&ba); QSqlQuery query; buffer.open(QIODevice::WriteOnly | QIODevice::Truncate); image.save(&buffer, getImageFormat(format), 85); // TODO: settings query.prepare("INSERT INTO thumbnail (path, format, image) VALUES (:path, :format, :image)"); query.bindValue(":path", path); query.bindValue(":format", format); query.bindValue(":image", buffer.data()); if (!query.exec()) { } buffer.close(); } void ThumbnailDatabase::remove(QString path) { if (!db.open()) { return; } QSqlQuery query; query.prepare("DELETE FROM thumbnail WHERE path = :path"); query.bindValue(":path", path); if (!query.exec()) { } }
25.156627
97
0.630747
goph-R
d03c2682b2d823739f16d8d3dc226c1b93040ac3
6,817
cpp
C++
booster/lib/regex/test/test_regex.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
388
2017-03-01T07:39:21.000Z
2022-03-30T19:38:41.000Z
booster/lib/regex/test/test_regex.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
81
2017-03-08T20:28:00.000Z
2022-01-23T08:19:31.000Z
booster/lib/regex/test/test_regex.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
127
2017-03-05T21:53:40.000Z
2022-02-25T02:31:01.000Z
// // Copyright (C) 2009-2012 Artyom Beilis (Tonkikh) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <booster/regex.h> #include "test.h" #include <pcre.h> #define THROWS(x,te) do { \ try{x;}catch(te const &){break;}catch(...){} \ std::ostringstream oss; \ oss << "Error " << __FILE__ << ":"<<__LINE__ << " "#x; \ throw std::runtime_error(oss.str()); \ }while(0) #include <iostream> bool search(std::string r,std::string t,int flags=0) { booster::regex re(r,flags); bool v1 = re.search(t.c_str(),t.c_str()+t.size()); std::vector<std::pair<int,int> > m; bool v2 = re.search(t.c_str(),t.c_str()+t.size(),m); TEST(v1==v2); return v1; } bool match(std::string r,std::string t,int flags = 0) { booster::regex re(r,flags); std::vector<std::pair<int,int> > m; bool v1 = re.match(t.c_str(),t.c_str()+t.size()); bool v2 = re.match(t.c_str(),t.c_str()+t.size(),m); TEST(v1==v2); return v1; } template<typename Match,typename Other> void check_less(Match const &a,Other b) { TEST(a<b); TEST(a<=b); TEST(!(a>b)); TEST(!(a>=b)); TEST(b>a); TEST(b>=a); TEST(!(b<a)); TEST(!(b<=a)); TEST(a!=b); TEST(b!=a); TEST(!(a==b)); TEST(!(b==a)); } template<typename Match,typename Other> void check_equal(Match const &a,Other b) { TEST(a==b); TEST(b==a); TEST(!(a!=b)); TEST(!(b!=a)); } template<typename Param,typename MatchType> void test_match(Param str) { MatchType cm; TEST(booster::regex_match(str,cm,booster::regex("(a)(a)(x)?(b)"))); TEST(cm.size()==5); TEST(cm[0].matched && cm[1].matched && cm[1].matched && !cm[3].matched && cm[4].matched); TEST(cm[0]=="aab"); TEST(cm[1]=="a"); TEST(cm[2]=="a"); TEST(cm[3]!="a"); TEST(cm[3]==""); TEST(cm[4]=="b"); check_equal(cm[1],cm[2]); check_less(cm[1],cm[4]); check_less(cm[3],cm[1]); check_equal(cm[1],"a"); check_less(cm[1],"b"); check_less("",cm[1]); check_equal(cm[1],std::string("a")); check_less(cm[1],std::string("b")); check_less(std::string(""),cm[1]); TEST(cm[1]+cm[4]=="ab"); TEST("a"+cm[4]=="ab"); TEST(cm[1]+"b"=="ab"); TEST(std::string("a")+cm[4]=="ab"); TEST(cm[1]+std::string("b")=="ab"); } void re_match(bool result,std::string re,std::string pat,std::string key="",int pos=0) { TEST(booster::regex_match(pat,booster::regex(re))==result); TEST(booster::regex_match(pat.c_str(),pat.c_str()+pat.size(),booster::regex(re))==result); TEST(booster::regex_match(pat.c_str(),booster::regex(re))==result); if(result) { { booster::smatch sm; TEST(booster::regex_match(pat,sm,booster::regex(re))); TEST(sm[pos]==key); } { booster::cmatch cm; TEST(booster::regex_match(pat.c_str(),pat.c_str()+pat.size(),cm,booster::regex(re))); TEST(cm[pos]==key); } { booster::cmatch cm; TEST(booster::regex_match(pat.c_str(),cm,booster::regex(re))); TEST(cm[pos]==key); } } } void re_search(bool result,std::string re,std::string pat,std::string key="",int pos=0) { TEST(booster::regex_search(pat,booster::regex(re))==result); TEST(booster::regex_search(pat.c_str(),pat.c_str()+pat.size(),booster::regex(re))==result); TEST(booster::regex_search(pat.c_str(),booster::regex(re))==result); if(result) { { booster::smatch sm; TEST(booster::regex_search(pat,sm,booster::regex(re))); TEST(sm[pos]==key); } { booster::cmatch cm; TEST(booster::regex_search(pat.c_str(),pat.c_str()+pat.size(),cm,booster::regex(re))); TEST(cm[pos]==key); } { booster::cmatch cm; TEST(booster::regex_search(pat.c_str(),cm,booster::regex(re))); TEST(cm[pos]==key); } } } int main() { try { { std::cout << "Testing search/match" << std::endl; TEST(search("foo","foo")); TEST(search("foo","foobar")); TEST(search("foo","zeefoo")); TEST(!search("foo","bar")); TEST(match("foo","foo")); TEST(match("(http|https|ftp|mailto)","https")); TEST(!match("foo","zeefoo")); TEST(!match("foo","foobar")); TEST(match("(foo)","foo")); TEST(!match("(foo)","zeefoo")); TEST(!match("(foo)","foobar")); TEST(match("((((((((((foo))))))))))","foo")); TEST(!match("((((((((((foo))))))))))","foox")); TEST(!match("((((((((((foo))))))))))","xfoo")); TEST(!match("a","A",0)); TEST(!search("a","xAz",0)); TEST(match("a","A",booster::regex::icase)); TEST(search("a","xAz",booster::regex::icase)); int utf8 = 0; #ifdef PCRE_UTF8 pcre_config(PCRE_CONFIG_UTF8,&utf8); #endif if(utf8) { std::cout << "Testing UTF-8" << std::endl; TEST(match(".","\xD7\x90",booster::regex::utf8)); TEST(match(".","\xD0\x96",booster::regex::utf8)); TEST(match("\xD0\x96","\xD0\xB6",booster::regex::icase | booster::regex::utf8)); int prop=0; pcre_config(PCRE_CONFIG_UNICODE_PROPERTIES,&prop); if(prop) { std::cout << "Testing Unicode Properties" << std::endl; TEST(match("\\p{Hebrew}","\xD7\x90",booster::regex::utf8)); TEST(!match("\\p{Hebrew}","\xD0\x96",booster::regex::utf8)); TEST(!match("\\p{Hebrew}","a",booster::regex::utf8)); } else { std::cout << "Unicode properties not compiled in" << std::endl; THROWS(match("\\p{Hebrew}","a",booster::regex::utf8),booster::regex_error); } } else { std::cout << "UTF-8 is not compiled in" << std::endl; THROWS(match(".","a",booster::regex::utf8),booster::regex_error); } std::cout << "Testing match_result" << std::endl; test_match<std::string,booster::smatch>("aab"); test_match<char const *,booster::cmatch>("aab"); re_match(true,"foo","foo","foo",0); re_match(false,"foo","Foo"); re_search(false,"foo","Foo"); re_match(false,"f.o","foobar"); re_search(true,"f.o","foobar","foo",0); std::cout << "Testing regex match/search" << std::endl; booster::regex re("foo"); booster::cmatch cm; TEST(booster::regex_search("foo",cm,re)); TEST(cm.prefix()=="" && cm.suffix()==""); TEST(booster::regex_search("foobee",cm,re)); TEST(cm.prefix()=="" && cm.suffix()=="bee"); TEST(booster::regex_search("zfoo",cm,re)); TEST(cm.prefix()=="z" && cm.suffix()==""); TEST(booster::regex_search("zfoobee",cm,re)); TEST(cm.prefix()=="z" && cm.suffix()=="bee"); { std::cout << "Testing regex ctor/operator=" << std::endl; booster::regex r; r.assign("(t(x))"); TEST(r.str()=="(t(x))"); TEST(r.mark_count() == 2); booster::regex rc(r); TEST(booster::regex_match("tx",rc)); TEST(!booster::regex_match("ty",rc)); re = r; TEST(booster::regex_match("tx",re)); TEST(!booster::regex_match("ty",re)); } } } catch(std::exception const &e) { std::cerr << "Fail: " << e.what() << std::endl; return 1; } std::cout << "Ok" << std::endl; return 0; }
25.920152
92
0.589702
gatehouse
d03cee142a4da717978b38dfc5f2362cd0df7d42
3,520
cpp
C++
injectors/Kd.cpp
TedBrookings/fitneuron
2ab68481a4caf64a18da9ffc6302b004345fd173
[ "MIT" ]
null
null
null
injectors/Kd.cpp
TedBrookings/fitneuron
2ab68481a4caf64a18da9ffc6302b004345fd173
[ "MIT" ]
null
null
null
injectors/Kd.cpp
TedBrookings/fitneuron
2ab68481a4caf64a18da9ffc6302b004345fd173
[ "MIT" ]
null
null
null
#include "OhmicChannel.h" // Delayed rectifier potassium current (mPower = 4, hPower = 0) // Base formula from Turrigiano et al., 1995 // Cultured spiny lobster STG cells, recorded at room temperature (22-25 C) // Adjustable with vShift, vScale, tauScale class Kd : public OhmicChannel<4,0> { public: // Define the parameters of the ion channel virtual void defineParameters(ParameterDescriptionList & parametersList, const list<Trace> & traces, NeuronModel & model); // use initialize to effect fudge-factor shifts and scales virtual void initialize(void); protected: // model activation and inactivation dynamics // (assign mInf, mTau, hInf, and hTau) virtual void dynamics(const FDouble & v, const double & t) const; // model parameters double mOffset; // (mV) double mScale; // (mV) double mTauA; // (ms) double mTauB; // (ms) double mTauOffset; // (mV) double mTauVScale; // (mV) double eK; // (mV) // fudge-factors double vShift; // (mV) double mVShift; // (mV) double vScale; // (pure) double mVScale; // (pure) double tauScale; // (pure) double mTauScale; // (pure) // fudged model parameters double mOffsetF; // (mV) double mScaleF; // (mv) double mTauAF; // (ms) double mTauBF; // (ms) double mTauOffsetF; // (mV) double mTauVScaleF; // (mV) }; void Kd::defineParameters(ParameterDescriptionList & parametersList, const list<Trace> & traces, NeuronModel & model) { celsiusBase = 23.5; // (C) (Actually 22-25 C) DEFINE_PARAMETER( gBarQ10, 2.0, UNITLESS ); // wild guess DEFINE_PARAMETER( mQ10, 3.0, UNITLESS ); // wild guess // parameters of the model DEFINE_PARAMETER( gBar, 0.0, "uS/nF" ); DEFINE_PARAMETER( eK, -80.0, "mV" ); DEFINE_PARAMETER( mOffset, 12.3, "mV" ); DEFINE_PARAMETER( mScale, 11.8, "mV" ); DEFINE_PARAMETER( mTauA, 7.2, "ms" ); DEFINE_PARAMETER( mTauB, 6.4, "ms" ); DEFINE_PARAMETER( mTauOffset, 28.3, "mV" ); DEFINE_PARAMETER( mTauVScale, 19.2, "mV" ); // fudge-factors DEFINE_PARAMETER( vShift, 0.0, "mV" ); DEFINE_PARAMETER( mVShift, 0.0, "mV" ); DEFINE_PARAMETER( vScale, 1.0, UNITLESS ); DEFINE_PARAMETER( mVScale, 1.0, UNITLESS ); DEFINE_PARAMETER( tauScale, 1.0, UNITLESS ); DEFINE_PARAMETER( mTauScale, 1.0, UNITLESS ); } void Kd::initialize(void) { // initialize the OhmicChannel base object OhmicChannel<4,0>::initialize(); // use initialize to effect fudge-factor shifts and scales // set reversal potential E = eK; // effect shifts and scales on fudged model parameters mOffsetF = mOffset + vShift + mVShift; mTauOffsetF = mTauOffset + vShift + mVShift; mScaleF = mScale * vScale * mVScale; mTauVScaleF = mTauVScale * vScale * mVScale; mTauAF = mTauA * tauScale * mTauScale; mTauBF = mTauB * tauScale * mTauScale; } void Kd::dynamics(const FDouble & v, const double & t) const { (void)t; mInf = logistic((v + mOffsetF) / mScaleF); mTau = mTauAF - scaleLogistic(mTauBF, (v + mTauOffsetF) / mTauVScaleF); } // register channel so it can be loaded dynamically by injectorFactory REGISTER_CLASS(CurrentInjector, Kd, injectorFactory);
29.830508
76
0.608239
TedBrookings
d03d4d9b0eac61733880aa3f0b3d4c7062f0312f
692
cpp
C++
Codeforces/1005C - Summarize to the Power of Two.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1005C - Summarize to the Power of Two.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1005C - Summarize to the Power of Two.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<int> val; int n, arr[120100]; unordered_map<int, int> freq; int main() { cin >> n; for (int i = 1; i <= 30; ++i) val.push_back(pow(2, i)); for (int i = 0; i < n; ++i) cin >> arr[i], freq[arr[i]]++; int cnt = 0; for (int i = 0; i < n; ++i) { bool flag = false; freq[arr[i]]--; for ( auto el: val ) { if (el <= arr[i]) continue; int left = el - arr[i]; if (freq[left] > 0) { flag = true; break; } } freq[arr[i]]++; if (!flag) cnt++; } cout << cnt << endl; return 0; }
20.352941
62
0.413295
naimulcsx
d03fe15639f5eed4b5640e406a4891ea6bcc5cf9
1,835
hpp
C++
src/main/cpp/RLBotInterface/RLBotMessages/BoostUtilities/BoostUtilities.hpp
whokRL/RLBot
a39ad1aa21298cc78162b694c850ff031fbf6816
[ "MIT" ]
null
null
null
src/main/cpp/RLBotInterface/RLBotMessages/BoostUtilities/BoostUtilities.hpp
whokRL/RLBot
a39ad1aa21298cc78162b694c850ff031fbf6816
[ "MIT" ]
null
null
null
src/main/cpp/RLBotInterface/RLBotMessages/BoostUtilities/BoostUtilities.hpp
whokRL/RLBot
a39ad1aa21298cc78162b694c850ff031fbf6816
[ "MIT" ]
1
2019-01-19T12:54:41.000Z
2019-01-19T12:54:41.000Z
#ifndef BOOSTUTILITIES_HPP #define BOOSTUTILITIES_HPP #include "..\MessageStructs\ByteBuffer.hpp" #include "..\ErrorCodes\ErrorCodes.hpp" #include <boost\interprocess\ipc\message_queue.hpp> #include <boost\interprocess\shared_memory_object.hpp> #include <boost\interprocess\mapped_region.hpp> #include <boost\interprocess\sync\named_sharable_mutex.hpp> #include <boost\interprocess\sync\sharable_lock.hpp> #include "BoostConstants.hpp" /* This typedef is advice from one of the boost maintainers on how to make message queues work between 32 and 64 bit processes. It looks pretty janky. I believe the reason it's not "fixed" in the library is that it can't be done consistently on windows vs linux. "In general I regret putting message_queue in Interprocess, as IMHO it's not good enough to be in the library. Some people find it useful, though." https://lists.boost.org/Archives/boost/2014/06/214746.php */ typedef boost::interprocess::message_queue_t< boost::interprocess::offset_ptr<void, boost::int32_t, boost::uint64_t>> interop_message_queue; namespace BoostUtilities { class QueueSender { private: interop_message_queue queue; public: QueueSender(const char* queueName): queue(boost::interprocess::open_only, queueName) { } RLBotCoreStatus sendMessage(void* message, int messageSize); }; class SharedMemReader { private: boost::interprocess::shared_memory_object* sharedMem; boost::interprocess::named_sharable_mutex* mutex; public: SharedMemReader(const char* name); ByteBuffer fetchData(); }; class SharedMemWriter { private: boost::interprocess::shared_memory_object* sharedMem; boost::interprocess::named_sharable_mutex* mutex; public: SharedMemWriter(const char* name); void writeData(void* address, int size); }; } #endif
33.363636
148
0.760218
whokRL
d041fe83c7009ef6a47479db78296e97b3170338
887
hpp
C++
src/network/server.hpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
351
2016-10-12T14:06:09.000Z
2022-03-24T14:53:54.000Z
src/network/server.hpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
7
2017-03-07T01:49:16.000Z
2018-07-27T08:51:54.000Z
src/network/server.hpp
UncP/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
62
2016-10-31T12:46:45.000Z
2021-12-28T11:25:26.000Z
/** * > Author: UncP * > Github: www.github.com/UncP/Mushroom * > License: BSD-3 * > Time: 2017-04-23 10:50:39 **/ #ifndef _SERVER_HPP_ #define _SERVER_HPP_ #include <vector> #include "../include/utility.hpp" #include "callback.hpp" #include "socket.hpp" namespace Mushroom { class Channel; class EventBase; class Server : private NoCopy { public: Server(EventBase *event_base, uint16_t port); virtual ~Server(); void Start(); void Close(); void OnConnect(const ConnectCallBack &connectcb); std::vector<Connection *>& Connections(); uint16_t Port() const; protected: uint16_t port_; EventBase *event_base_; Socket socket_; Channel *listen_; std::vector<Connection *> connections_; ConnectCallBack connectcb_; private: void HandleAccept(); }; } // namespace Mushroom #endif /* _SERVER_HPP_ */
16.425926
51
0.662909
leezhenghui
d04467c608396feed828918927c8fc6759d68d76
2,587
hpp
C++
src/libvisr/parameter_config_base.hpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
17
2019-03-12T14:52:22.000Z
2021-11-09T01:16:23.000Z
src/libvisr/parameter_config_base.hpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
null
null
null
src/libvisr/parameter_config_base.hpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
2
2019-08-11T12:53:07.000Z
2021-06-22T10:08:08.000Z
/* Copyright Institute of Sound and Vibration Research - All rights reserved */ #ifndef VISR_PARAMETER_CONFIG_BASE_HPP_INCLUDED #define VISR_PARAMETER_CONFIG_BASE_HPP_INCLUDED #include "parameter_base.hpp" #include "export_symbols.hpp" #include <memory> namespace visr { /** * Base class for parameter configuration objects. * A parameter configuration object adds information about the transmitted parameter objects to a parameter port or communication protocol. * This information contains additional information about the parameter (e.g., the dimension of the matrix), but not the type itself. Each parameter class is associated * with a specific parameter configuration type, but the same parameter configuration class can be potentially used by multiple parameter classes. * Parameter configuration objects are used by the runtime system to check compatibility of parameter connections, and to construct parameter objects. */ class VISR_CORE_LIBRARY_SYMBOL ParameterConfigBase { protected: /** * Default constructor. * This constructor is protected because only derived classes can be instantiated. */ /*VISR_CORE_LIBRARY_SYMBOL*/ ParameterConfigBase(); /** * Copy constructor. * This constructor is protected because only derived classes can be instantiated. * @note It is defined explicitly in order to have the symbol placed in the library */ /*VISR_CORE_LIBRARY_SYMBOL*/ ParameterConfigBase( ParameterConfigBase const & ); public: /** * Destructor (virtual). * Parameter configuration objects are instantiated and managed polymorphically, therefore the destructor has to be virtual */ /*VISR_CORE_LIBRARY_SYMBOL*/ virtual ~ParameterConfigBase(); /** * Comparison function between parameter configurations. * Must only be called between objects of equal dynamic type. * Pure virtual function interface, must be implemented by derived parameter config types. * @param rhs The parameter configuration object to compare with. * @return True if the parameter objects are compatible, false otherwise * @throw std::invalid_argument it the \p this object and \p rhs have nonmatching dynamic types. */ virtual bool compare( ParameterConfigBase const & rhs) const = 0; /** * Clone (virtual copy construction) function. * Pure virtual function, must be defined in derived types. * @return A shared pointer to an object of the derived type. */ virtual std::unique_ptr<ParameterConfigBase> clone() const = 0; }; } // namespace visr #endif // #ifndef VISR_TYPED_PARAMETER_BASE_HPP_INCLUDED
39.19697
169
0.770004
s3a-spatialaudio
d044926c25f487951aed32ee722aae0fe10578c0
1,598
cpp
C++
source/pkgsrc/graphics/gimmage/patches/patch-src_ImageEventBox.cpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
1
2021-11-20T22:46:39.000Z
2021-11-20T22:46:39.000Z
source/pkgsrc/graphics/gimmage/patches/patch-src_ImageEventBox.cpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
source/pkgsrc/graphics/gimmage/patches/patch-src_ImageEventBox.cpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
$NetBSD: patch-src_ImageEventBox.cpp,v 1.1 2017/02/09 00:22:35 joerg Exp $ --- src/ImageEventBox.cpp.orig 2017-01-08 18:51:01.889096829 +0000 +++ src/ImageEventBox.cpp @@ -149,7 +149,7 @@ void ImageEventBox::LoadImage( const Gli void ImageEventBox::ScaleImage( double scalefactor, Gdk::InterpType interp_type) { - if(ImagePixbuf_Original != 0 && loaded == true) + if(ImagePixbuf_Original && loaded == true) { int new_width = (int)(scalefactor * (double)ImagePixbuf_Original->get_width()); int new_height = (int)(scalefactor * (double)ImagePixbuf_Original->get_height()); @@ -176,7 +176,7 @@ void ImageEventBox::ScaleImage( int widt double * scalefactor, Gdk::InterpType interp_type) { - if(ImagePixbuf_Original != 0 && loaded == true) + if(ImagePixbuf_Original && loaded == true) { double ratioh = (double)height/(double)ImagePixbuf_Original->get_height(); double ratiow = (double)width/(double)ImagePixbuf_Original->get_width(); @@ -206,7 +206,7 @@ void ImageEventBox::ScaleImage2( int wid double * scalefactor, Gdk::InterpType interp_type) { - if(ImagePixbuf_Original != 0 && loaded == true) + if(ImagePixbuf_Original && loaded == true) { if( width <= ImagePixbuf_Original->get_width() || height <= ImagePixbuf_Original->get_height() ) { @@ -242,7 +242,7 @@ void ImageEventBox::ScaleImage2( int wid // the rotation of the image void ImageEventBox::RotateImage(Gdk::PixbufRotation rotateby) { - if(ImagePixbuf_Original != 0 && loaded == true) + if(ImagePixbuf_Original && loaded == true) { try {
38.97561
99
0.684606
Scottx86-64
d0467369531d2e1f3dd01fea8c395f1a8a034d25
6,751
cpp
C++
source/ashes/renderer/D3D11Renderer/Miscellaneous/D3D11QueryPool.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/D3D11Renderer/Miscellaneous/D3D11QueryPool.cpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/D3D11Renderer/Miscellaneous/D3D11QueryPool.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
#include "Miscellaneous/D3D11QueryPool.hpp" #include "Core/D3D11Device.hpp" #include "ashesd3d11_api.hpp" namespace ashes::d3d11 { namespace { D3D11_QUERY convert( VkQueryType type ) { switch ( type ) { case VK_QUERY_TYPE_OCCLUSION: return D3D11_QUERY_OCCLUSION; case VK_QUERY_TYPE_PIPELINE_STATISTICS: return D3D11_QUERY_PIPELINE_STATISTICS; case VK_QUERY_TYPE_TIMESTAMP: return D3D11_QUERY_TIMESTAMP; default: assert( false ); return D3D11_QUERY_TIMESTAMP; } } UINT64 getPipelineStatistic( uint32_t index , D3D11_QUERY_DATA_PIPELINE_STATISTICS const & stats ) { switch ( index ) { case 0: return stats.IAVertices; case 1: return stats.IAPrimitives; case 2: return stats.VSInvocations; case 3: return stats.CInvocations; case 4: return stats.CPrimitives; case 5: return stats.PSInvocations; case 6: return stats.GSPrimitives; case 7: return stats.GSInvocations; case 8: return stats.HSInvocations; case 9: return stats.DSInvocations; case 10: return stats.CSInvocations; } return 0ull; } uint32_t adjustQueryCount( uint32_t count , VkQueryType type , VkQueryPipelineStatisticFlags pipelineStatistics ) { if ( type != VK_QUERY_TYPE_PIPELINE_STATISTICS ) { return count; } return 1u; } } QueryPool::QueryPool( VkDevice device , VkQueryPoolCreateInfo createInfo ) : m_device{ device } , m_createInfo{ std::move( createInfo ) } { D3D11_QUERY_DESC desc; desc.MiscFlags = 0u; desc.Query = convert( m_createInfo.queryType ); m_queries.resize( adjustQueryCount( m_createInfo.queryCount, m_createInfo.queryType, m_createInfo.pipelineStatistics ) ); for ( auto & query : m_queries ) { auto hr = get( m_device )->getDevice()->CreateQuery( &desc, &query ); if ( checkError( m_device, hr, "CreateQuery" ) ) { dxDebugName( query, Query ); } } switch ( m_createInfo.queryType ) { case VK_QUERY_TYPE_OCCLUSION: m_data.resize( sizeof( uint64_t ) ); getUint32 = [this]( uint32_t index ) { return uint32_t( *reinterpret_cast< uint64_t * >( m_data.data() ) ); }; getUint64 = [this]( uint32_t index ) { return *reinterpret_cast< uint64_t * >( m_data.data() ); }; break; case VK_QUERY_TYPE_PIPELINE_STATISTICS: m_data.resize( sizeof( D3D11_QUERY_DATA_PIPELINE_STATISTICS ) ); getUint32 = [this]( uint32_t index ) { D3D11_QUERY_DATA_PIPELINE_STATISTICS data = *reinterpret_cast< D3D11_QUERY_DATA_PIPELINE_STATISTICS * >( m_data.data() ); return uint32_t( getPipelineStatistic( index, data ) ); }; getUint64 = [this]( uint32_t index ) { D3D11_QUERY_DATA_PIPELINE_STATISTICS data = *reinterpret_cast< D3D11_QUERY_DATA_PIPELINE_STATISTICS * >( m_data.data() ); return getPipelineStatistic( index, data ); }; break; case VK_QUERY_TYPE_TIMESTAMP: m_data.resize( sizeof( uint64_t ) ); getUint32 = [this]( uint32_t index ) { return uint32_t( *reinterpret_cast< uint64_t * >( m_data.data() ) ); }; getUint64 = [this]( uint32_t index ) { return *reinterpret_cast< uint64_t * >( m_data.data() ); }; break; default: break; } } QueryPool::~QueryPool() { for ( auto & query : m_queries ) { safeRelease( query ); } } VkResult QueryPool::getResults( uint32_t firstQuery , uint32_t queryCount , VkDeviceSize stride , VkQueryResultFlags flags , VkDeviceSize dataSize , void * data )const { if ( m_createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS ) { return getPipelineStatisticsResults( firstQuery , queryCount , stride , flags , dataSize , data ); } return getOtherResults( firstQuery , queryCount , stride , flags , dataSize , data ); } VkResult QueryPool::getPipelineStatisticsResults( uint32_t firstQuery , uint32_t queryCount , VkDeviceSize stride , VkQueryResultFlags flags , VkDeviceSize dataSize , void * data )const { auto max = firstQuery + queryCount; assert( max <= m_queries.size() ); auto context{ get( m_device )->getImmediateContext() }; VkResult result = VK_SUCCESS; for ( auto i = firstQuery; i < max; ++i ) { HRESULT hr; do { hr = context->GetData( m_queries[i] , m_data.data() , UINT( m_data.size() ) , 0u ); } while ( hr == S_FALSE ); if ( hr == S_FALSE ) { result = VK_INCOMPLETE; } else if ( checkError( m_device, hr, "GetData" ) ) { auto buffer = reinterpret_cast< uint8_t * >( data ); size_t size = 0u; if ( checkFlag( flags, VK_QUERY_RESULT_64_BIT ) ) { auto resmax = ( m_createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS ? uint32_t( m_data.size() / sizeof( uint64_t ) ) : queryCount ); stride = stride ? stride : sizeof( uint64_t ); for ( uint32_t resi = 0; resi < resmax && size < dataSize; ++resi ) { *reinterpret_cast< uint64_t * >( buffer ) = getUint64( resi ); buffer += stride; size += stride; } } else { auto resmax = ( m_createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS ? uint32_t( m_data.size() / sizeof( uint32_t ) ) : queryCount ); stride = stride ? stride : sizeof( uint32_t ); for ( uint32_t resi = 0; resi < resmax && size < dataSize; ++resi ) { *reinterpret_cast< uint32_t * >( buffer ) = getUint32( resi ); buffer += stride; size += stride; } } } } return result; } VkResult QueryPool::getOtherResults( uint32_t firstQuery , uint32_t queryCount , VkDeviceSize stride , VkQueryResultFlags flags , VkDeviceSize dataSize , void * data )const { auto max = firstQuery + queryCount; assert( max <= m_queries.size() ); auto context{ get( m_device )->getImmediateContext() }; VkResult result = VK_SUCCESS; stride = stride ? stride : ( checkFlag( flags, VK_QUERY_RESULT_64_BIT ) ? sizeof( uint64_t ) : sizeof( uint32_t ) ); auto buffer = reinterpret_cast< uint8_t * >( data ); for ( auto i = firstQuery; i < max; ++i ) { HRESULT hr; do { hr = context->GetData( m_queries[i] , m_data.data() , UINT( m_data.size() ) , 0u ); } while ( hr == S_FALSE ); if ( hr == S_FALSE ) { result = VK_INCOMPLETE; } else if ( checkError( m_device, hr, "GetData" ) ) { if ( checkFlag( flags, VK_QUERY_RESULT_64_BIT ) ) { *reinterpret_cast< uint64_t * >( buffer ) = getUint64( 0 ); buffer += stride; } else { *reinterpret_cast< uint32_t * >( buffer ) = getUint32( 0 ); buffer += stride; } } } return result; } }
22.654362
125
0.642423
DragonJoker
d04673c6ad39eb0f6b8d6314dabf44ca8fd740fe
113
cpp
C++
Resources/Example Code/04 Functions/Functions in another file/Maths.cpp
tdfairch2/CS200-Concepts-of-Progamming-Algorithms
050510da8eea06aff3519097cc5f22831036b7cf
[ "MIT" ]
null
null
null
Resources/Example Code/04 Functions/Functions in another file/Maths.cpp
tdfairch2/CS200-Concepts-of-Progamming-Algorithms
050510da8eea06aff3519097cc5f22831036b7cf
[ "MIT" ]
null
null
null
Resources/Example Code/04 Functions/Functions in another file/Maths.cpp
tdfairch2/CS200-Concepts-of-Progamming-Algorithms
050510da8eea06aff3519097cc5f22831036b7cf
[ "MIT" ]
null
null
null
float Sum( float a, float b ) { return a + b; } float Difference( float a, float b ) { return a - b; }
10.272727
36
0.557522
tdfairch2
d04c91744f1a6c6667ac3c3789968adc006c2afb
516
cpp
C++
Codeforces/559A - Gerald's Hexagon.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
2
2019-03-19T23:59:48.000Z
2019-03-21T20:13:12.000Z
Codeforces/559A - Gerald's Hexagon.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
null
null
null
Codeforces/559A - Gerald's Hexagon.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <algorithm> #include <cmath> using namespace std; int main() { bool ok = true; int a[6], sum = 0; for (int i = 0; i < 6; i++) { cin >> a[i]; } while (ok) { ok = false; for (int i = 0; i < 6; i++) { if (a[i] > 1 && a[(i + 2) % 6] > 1) { sum += (a[i + 1] * 2 + 1); a[i + 1]++; a[i]--; a[i + 2]--; ok = true; break; } } } sort(a, a + 6); cout << (a[5] * 2 + 1) * 2 + sum << endl; }
11.727273
43
0.362403
SamanKhamesian
d04fde4bfe918b8eb904aee533cd4970efd83576
637
cpp
C++
frontend/ast_test.cpp
DennisZZH/CS263_Project_Garbage_Collector
07e81c0eb532792cb3d1fd504b501bca67b5365d
[ "MIT" ]
null
null
null
frontend/ast_test.cpp
DennisZZH/CS263_Project_Garbage_Collector
07e81c0eb532792cb3d1fd504b501bca67b5365d
[ "MIT" ]
null
null
null
frontend/ast_test.cpp
DennisZZH/CS263_Project_Garbage_Collector
07e81c0eb532792cb3d1fd504b501bca67b5365d
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" #include "frontend/parser.h" using namespace cs160::frontend; TEST_CASE("Builder methods", "[ast]") { SECTION("makeVar") { auto tok = std::make_unique<const Variable>("x"); REQUIRE(tok->name() == "x"); } SECTION("makeInt") { auto tok = std::make_unique<const IntegerExpr>(4); REQUIRE(tok->value() == 4); } } TEST_CASE("toString", "[ast]") { Parser p({}); auto ast = std::make_unique<const Program>( FunctionDef::Block(), Statement::Block(), std::move(std::make_unique<const Variable>("x"))); CHECK(p.toString(std::move(ast)) == "x"); }
23.592593
56
0.629513
DennisZZH
d0539e7bca2dd480d666f8f4e02fbec4a66ea861
27,036
hpp
C++
include/ResourceState.hpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
1
2020-04-08T03:12:17.000Z
2020-04-08T03:12:17.000Z
include/ResourceState.hpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
null
null
null
include/ResourceState.hpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once namespace D3D12TranslationLayer { class CommandListManager; // These are defined in the private d3d12 header #define UNKNOWN_RESOURCE_STATE (D3D12_RESOURCE_STATES)0x8000u #define RESOURCE_STATE_VALID_BITS 0x2f3fff #define RESOURCE_STATE_VALID_INTERNAL_BITS 0x2fffff constexpr D3D12_RESOURCE_STATES RESOURCE_STATE_ALL_WRITE_BITS = D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS | D3D12_RESOURCE_STATE_DEPTH_WRITE | D3D12_RESOURCE_STATE_STREAM_OUT | D3D12_RESOURCE_STATE_COPY_DEST | D3D12_RESOURCE_STATE_RESOLVE_DEST | D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE | D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE; enum class SubresourceTransitionFlags { None = 0, TransitionPreDraw = 1, NoBindingTransitions = 2, StateMatchExact = 4, ForceExclusiveState = 8, NotUsedInCommandListIfNoStateChange = 0x10, }; DEFINE_ENUM_FLAG_OPERATORS(SubresourceTransitionFlags); inline bool IsD3D12WriteState(UINT State, SubresourceTransitionFlags Flags) { return (State & RESOURCE_STATE_ALL_WRITE_BITS) != 0 || (Flags & SubresourceTransitionFlags::ForceExclusiveState) != SubresourceTransitionFlags::None; } //================================================================================================================================== // CDesiredResourceState // Stores the current desired state of either an entire resource, or each subresource. //================================================================================================================================== class CDesiredResourceState { public: struct SubresourceInfo { D3D12_RESOURCE_STATES State = UNKNOWN_RESOURCE_STATE; COMMAND_LIST_TYPE CommandListType = COMMAND_LIST_TYPE::UNKNOWN; SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None; }; private: bool m_bAllSubresourcesSame = true; PreallocatedArray<SubresourceInfo> m_spSubresourceInfo; public: static size_t CalcPreallocationSize(UINT SubresourceCount) { return sizeof(SubresourceInfo) * SubresourceCount; } CDesiredResourceState(UINT SubresourceCount, void*& pPreallocatedMemory) noexcept : m_spSubresourceInfo(SubresourceCount, pPreallocatedMemory) // throw( bad_alloc ) { } bool AreAllSubresourcesSame() const noexcept { return m_bAllSubresourcesSame; } SubresourceInfo const& GetSubresourceInfo(UINT SubresourceIndex) const noexcept; void SetResourceState(SubresourceInfo const& Info) noexcept; void SetSubresourceState(UINT SubresourceIndex, SubresourceInfo const& Info) noexcept; void Reset() noexcept; }; //================================================================================================================================== // CCurrentResourceState // Stores the current state of either an entire resource, or each subresource. // Current state can either be shared read across multiple queues, or exclusive on a single queue. //================================================================================================================================== class CCurrentResourceState { public: static constexpr unsigned NumCommandListTypes = static_cast<UINT>(COMMAND_LIST_TYPE::MAX_VALID); struct ExclusiveState { UINT64 FenceValue = 0; D3D12_RESOURCE_STATES State = D3D12_RESOURCE_STATE_COMMON; COMMAND_LIST_TYPE CommandListType = COMMAND_LIST_TYPE::UNKNOWN; // There are cases where we want to synchronize against last write, instead // of last access. Therefore the exclusive state of a (sub)resource is not // overwritten when transitioning to shared state, simply marked as stale. // So Map(READ) always synchronizes against the most recent exclusive state, // while Map(WRITE) always synchronizes against the most recent state, whether // it's exclusive or shared. bool IsMostRecentlyExclusiveState = true; }; struct SharedState { UINT64 FenceValues[NumCommandListTypes] = {}; D3D12_RESOURCE_STATES State[NumCommandListTypes] = {}; }; private: const bool m_bSimultaneousAccess; bool m_bAllSubresourcesSame = true; // Note: As a (minor) memory optimization, using a contiguous block of memory for exclusive + shared state. // The memory is owned by the exclusive state pointer. The shared state pointer is non-owning and possibly null. PreallocatedArray<ExclusiveState> m_spExclusiveState; PreallocatedArray<SharedState> m_pSharedState; void ConvertToSubresourceTracking() noexcept; public: static size_t CalcPreallocationSize(UINT SubresourceCount, bool bSimultaneousAccess) { return (sizeof(ExclusiveState) + (bSimultaneousAccess ? sizeof(SharedState) : 0u)) * SubresourceCount; } CCurrentResourceState(UINT SubresourceCount, bool bSimultaneousAccess, void*& pPreallocatedMemory) noexcept; bool SupportsSimultaneousAccess() const noexcept { return m_bSimultaneousAccess; } bool AreAllSubresourcesSame() const noexcept { return m_bAllSubresourcesSame; } bool IsExclusiveState(UINT SubresourceIndex) const noexcept; void SetExclusiveResourceState(ExclusiveState const& State) noexcept; void SetSharedResourceState(COMMAND_LIST_TYPE Type, UINT64 FenceValue, D3D12_RESOURCE_STATES State) noexcept; void SetExclusiveSubresourceState(UINT SubresourceIndex, ExclusiveState const& State) noexcept; void SetSharedSubresourceState(UINT SubresourceIndex, COMMAND_LIST_TYPE Type, UINT64 FenceValue, D3D12_RESOURCE_STATES State) noexcept; ExclusiveState const& GetExclusiveSubresourceState(UINT SubresourceIndex) const noexcept; SharedState const& GetSharedSubresourceState(UINT SubresourceIndex) const noexcept; UINT GetCommandListTypeMask() const noexcept; UINT GetCommandListTypeMask(CViewSubresourceSubset const& Subresources) const noexcept; UINT GetCommandListTypeMask(UINT Subresource) const noexcept; void Reset() noexcept; }; //================================================================================================================================== // DeferredWait //================================================================================================================================== struct DeferredWait { std::shared_ptr<Fence> fence; UINT64 value; }; //================================================================================================================================== // TransitionableResourceBase // A base class that transitionable resources should inherit from. //================================================================================================================================== struct TransitionableResourceBase { LIST_ENTRY m_TransitionListEntry; CDesiredResourceState m_DesiredState; const bool m_bTriggersDeferredWaits; std::vector<DeferredWait> m_DeferredWaits; static size_t CalcPreallocationSize(UINT NumSubresources) { return CDesiredResourceState::CalcPreallocationSize(NumSubresources); } TransitionableResourceBase(UINT NumSubresources, bool bTriggersDeferredWaits, void*& pPreallocatedMemory) noexcept : m_DesiredState(NumSubresources, pPreallocatedMemory) , m_bTriggersDeferredWaits(bTriggersDeferredWaits) { D3D12TranslationLayer::InitializeListHead(&m_TransitionListEntry); } ~TransitionableResourceBase() noexcept { if (IsTransitionPending()) { D3D12TranslationLayer::RemoveEntryList(&m_TransitionListEntry); } } bool IsTransitionPending() const noexcept { return !D3D12TranslationLayer::IsListEmpty(&m_TransitionListEntry); } void AddDeferredWaits(const std::vector<DeferredWait>& DeferredWaits) noexcept(false) { m_DeferredWaits.insert(m_DeferredWaits.end(), DeferredWaits.begin(), DeferredWaits.end()); // throw( bad_alloc ) } }; //================================================================================================================================== // ResourceStateManagerBase // The main business logic for handling resource transitions, including multi-queue sync and shared/exclusive state changes. // // Requesting a resource to transition simply updates destination state, and ensures it's in a list to be processed later. // // When processing ApplyAllResourceTransitions, we build up sets of vectors. // There's a source one for each command list type, and a single one for the dest because we are applying // the resource transitions for a single operation. // There's also a vector for "tentative" barriers, which are merged into the destination vector if // no flushing occurs as a result of submitting the final barrier operation. // 99% of the time, there will only be the source being populated, but sometimes there will be a destination as well. // If the source and dest of a transition require different types, we put a (source->COMMON) in the approriate source vector, // and a (COMMON->dest) in the destination vector. // // Once all resources are processed, we: // 1. Submit all source barriers, except ones belonging to the destination queue. // 2. Flush all source command lists, except ones belonging to the destination queue. // 3. Determine if the destination queue is going to be flushed. // If so: Submit source barriers on that command list first, then flush it. // If not: Accumulate source, dest, and tentative barriers so they can be sent to D3D12 in a single API call. // 4. Insert waits on the destination queue - deferred waits, and waits for work on other queues. // 5. Insert destination barriers. // // Only once all of this has been done do we update the "current" state of resources, // because this is the only way that we know whether or not the destination queue has been flushed, // and therefore, we can get the correct fence values to store in the subresources. //================================================================================================================================== class ResourceStateManagerBase { protected: LIST_ENTRY m_TransitionListHead; std::vector<DeferredWait> m_DeferredWaits; // State that is reset during the preamble, accumulated during resource traversal, // and applied during the submission phase. enum class PostApplyExclusiveState { Exclusive, Shared, SharedIfFlushed }; struct PostApplyUpdate { TransitionableResourceBase& AffectedResource; CCurrentResourceState& CurrentState; UINT SubresourceIndex; D3D12_RESOURCE_STATES NewState; PostApplyExclusiveState ExclusiveState; bool WasTransitioningToDestinationType; }; std::vector<D3D12_RESOURCE_BARRIER> m_vSrcResourceBarriers[(UINT)COMMAND_LIST_TYPE::MAX_VALID]; std::vector<D3D12_RESOURCE_BARRIER> m_vDstResourceBarriers; std::vector<D3D12_RESOURCE_BARRIER> m_vTentativeResourceBarriers; std::vector<PostApplyUpdate> m_vPostApplyUpdates; COMMAND_LIST_TYPE m_DestinationCommandListType; bool m_bApplyDeferredWaits; bool m_bFlushQueues[(UINT)COMMAND_LIST_TYPE::MAX_VALID]; UINT64 m_QueueFenceValuesToWaitOn[(UINT)COMMAND_LIST_TYPE::MAX_VALID]; ResourceStateManagerBase() noexcept(false); ~ResourceStateManagerBase() noexcept { // All resources should be gone by this point, and each resource ensures it is no longer in this list. assert(D3D12TranslationLayer::IsListEmpty(&m_TransitionListHead)); } // These methods set the destination state of the resource/subresources and ensure it's in the transition list. void TransitionResource(TransitionableResourceBase& Resource, CDesiredResourceState::SubresourceInfo const& State) noexcept; void TransitionSubresources(TransitionableResourceBase& Resource, CViewSubresourceSubset const& Subresources, CDesiredResourceState::SubresourceInfo const& State) noexcept; void TransitionSubresource(TransitionableResourceBase& Resource, UINT SubresourceIndex, CDesiredResourceState::SubresourceInfo const& State) noexcept; // Deferred waits are inserted when a transition is processing that puts applicable resources // into a write state. The command list is flushed, and these waits are inserted before the barriers. void AddDeferredWait(std::shared_ptr<Fence> const& spFence, UINT64 Value) noexcept(false); // Clear out any state from previous iterations. void ApplyResourceTransitionsPreamble() noexcept; // What to do with the resource, in the context of the transition list, after processing it. enum class TransitionResult { // There are no more pending transitions that may be processed at a later time (i.e. draw time), // so remove it from the pending transition list. Remove, // There are more transitions to be done, so keep it in the list. Keep }; // For every entry in the transition list, call a routine. // This routine must return a TransitionResult which indicates what to do with the list. template <typename TFunc> void ForEachTransitioningResource(TFunc&& func) noexcept(noexcept(func(std::declval<TransitionableResourceBase&>()))) { for (LIST_ENTRY *pListEntry = m_TransitionListHead.Flink; pListEntry != &m_TransitionListHead;) { TransitionableResourceBase* pResource = CONTAINING_RECORD(pListEntry, TransitionableResourceBase, m_TransitionListEntry); TransitionResult result = func(*pResource); auto pNextListEntry = pListEntry->Flink; if (result == TransitionResult::Remove) { D3D12TranslationLayer::RemoveEntryList(pListEntry); D3D12TranslationLayer::InitializeListHead(pListEntry); } pListEntry = pNextListEntry; } } // Updates vectors with the operations that should be applied to the requested resource. // May update the destination state of the resource. TransitionResult ProcessTransitioningResource(ID3D12Resource* pTransitioningResource, TransitionableResourceBase& TransitionableResource, CCurrentResourceState& CurrentState, CResourceBindings& BindingState, UINT NumTotalSubresources, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* CurrentFenceValues, bool bIsPreDraw) noexcept(false); // This method is templated so that it can have the same code for two implementations without copy/paste. // It is not intended to be completely exstensible. One implementation is leveraged by the translation layer // itself using lambdas that can be inlined. The other uses std::functions which cannot and is intended for tests. template < typename TSubmitBarriersImpl, typename TSubmitCmdListImpl, typename THasCommandsImpl, typename TGetCurrentFenceImpl, typename TInsertDeferredWaitsImpl, typename TInsertQueueWaitImpl > void SubmitResourceTransitionsImpl(TSubmitBarriersImpl&&, TSubmitCmdListImpl&&, THasCommandsImpl&&, TGetCurrentFenceImpl&&, TInsertDeferredWaitsImpl&&, TInsertQueueWaitImpl&&); // Call the D3D12 APIs to perform the resource barriers, command list submission, and command queue sync // that was determined by previous calls to ProcessTransitioningResource. void SubmitResourceTransitions(_In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) CommandListManager** ppManagers) noexcept(false); // Call the callbacks provided to allow tests to inspect what D3D12 APIs would've been called // as part of finalizing a set of barrier operations. void SimulateSubmitResourceTransitions(std::function<void(std::vector<D3D12_RESOURCE_BARRIER>&, COMMAND_LIST_TYPE)> SubmitBarriers, std::function<void(COMMAND_LIST_TYPE)> SubmitCmdList, std::function<bool(COMMAND_LIST_TYPE)> HasCommands, std::function<UINT64(COMMAND_LIST_TYPE)> GetCurrentFenceImpl, std::function<void(COMMAND_LIST_TYPE)> InsertDeferredWaits, std::function<void(UINT64, COMMAND_LIST_TYPE Src, COMMAND_LIST_TYPE Dst)> InsertQueueWait); // Update the current state of resources now that all barriers and sync have been done. // Callback provided to allow this information to be used by concrete implementation as well. template <typename TFunc> void PostSubmitUpdateState(TFunc&& callback, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* PreviousFenceValues, UINT64 NewFenceValue) { for (auto& update : m_vPostApplyUpdates) { COMMAND_LIST_TYPE UpdateCmdListType = m_DestinationCommandListType; UINT64 UpdateFenceValue = NewFenceValue; bool Flushed = m_DestinationCommandListType != COMMAND_LIST_TYPE::UNKNOWN && NewFenceValue != PreviousFenceValues[(UINT)m_DestinationCommandListType]; if (update.ExclusiveState == PostApplyExclusiveState::Exclusive || (update.ExclusiveState == PostApplyExclusiveState::SharedIfFlushed && !Flushed)) { CCurrentResourceState::ExclusiveState NewExclusiveState = {}; if (update.WasTransitioningToDestinationType) { NewExclusiveState.CommandListType = m_DestinationCommandListType; NewExclusiveState.FenceValue = NewFenceValue; } else { auto& OldExclusiveState = update.CurrentState.GetExclusiveSubresourceState(update.SubresourceIndex); UpdateCmdListType = NewExclusiveState.CommandListType = OldExclusiveState.CommandListType; UpdateFenceValue = NewExclusiveState.FenceValue = PreviousFenceValues[(UINT)OldExclusiveState.CommandListType]; } NewExclusiveState.State = update.NewState; if (update.SubresourceIndex == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) { update.CurrentState.SetExclusiveResourceState(NewExclusiveState); } else { update.CurrentState.SetExclusiveSubresourceState(update.SubresourceIndex, NewExclusiveState); } } else if (update.WasTransitioningToDestinationType) { if (update.SubresourceIndex == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) { update.CurrentState.SetSharedResourceState(m_DestinationCommandListType, NewFenceValue, update.NewState); } else { update.CurrentState.SetSharedSubresourceState(update.SubresourceIndex, m_DestinationCommandListType, NewFenceValue, update.NewState); } } else { continue; } callback(update, UpdateCmdListType, UpdateFenceValue); } } private: // Helpers static bool TransitionRequired(D3D12_RESOURCE_STATES CurrentState, D3D12_RESOURCE_STATES& DestinationState, SubresourceTransitionFlags Flags) noexcept; void AddCurrentStateUpdate(TransitionableResourceBase& Resource, CCurrentResourceState& CurrentState, UINT SubresourceIndex, D3D12_RESOURCE_STATES NewState, PostApplyExclusiveState ExclusiveState, bool IsGoingToDestinationType) noexcept(false); void ProcessTransitioningSubresourceExclusive(CCurrentResourceState& CurrentState, UINT i, COMMAND_LIST_TYPE curCmdListType, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* CurrentFenceValues, CDesiredResourceState::SubresourceInfo& SubresourceDestinationInfo, D3D12_RESOURCE_STATES after, TransitionableResourceBase& TransitionableResource, D3D12_RESOURCE_BARRIER& TransitionDesc, SubresourceTransitionFlags Flags) noexcept(false); void ProcessTransitioningSubresourceShared(CCurrentResourceState& CurrentState, UINT i, D3D12_RESOURCE_STATES after, SubresourceTransitionFlags Flags, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* CurrentFenceValues, COMMAND_LIST_TYPE curCmdListType, D3D12_RESOURCE_BARRIER& TransitionDesc, TransitionableResourceBase& TransitionableResource) noexcept(false); void SubmitResourceBarriers(_In_reads_(Count) D3D12_RESOURCE_BARRIER const* pBarriers, UINT Count, _In_ CommandListManager* pManager) noexcept; }; //================================================================================================================================== // ResourceStateManager // The implementation of state management tailored to the ImmediateContext and Resource classes. //================================================================================================================================== class ResourceStateManager : public ResourceStateManagerBase { private: ImmediateContext& m_ImmCtx; public: ResourceStateManager(ImmediateContext& ImmCtx) : m_ImmCtx(ImmCtx) { } // *** NOTE: DEFAULT DESTINATION IS GRAPHICS, NOT INFERRED FROM STATE BITS. *** // Transition the entire resource to a particular destination state on a particular command list. void TransitionResource(Resource* pResource, D3D12_RESOURCE_STATES State, COMMAND_LIST_TYPE DestinationCommandListType = COMMAND_LIST_TYPE::GRAPHICS, SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None) noexcept; // Transition a set of subresources to a particular destination state. Fast-path provided when subset covers entire resource. void TransitionSubresources(Resource* pResource, CViewSubresourceSubset const& Subresources, D3D12_RESOURCE_STATES State, COMMAND_LIST_TYPE DestinationCommandListType = COMMAND_LIST_TYPE::GRAPHICS, SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None) noexcept; // Transition a single subresource to a particular destination state. void TransitionSubresource(Resource* pResource, UINT SubresourceIndex, D3D12_RESOURCE_STATES State, COMMAND_LIST_TYPE DestinationCommandListType = COMMAND_LIST_TYPE::GRAPHICS, SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None) noexcept; // Update destination state of a resource to correspond to the resource's bind points. void TransitionResourceForBindings(Resource* pResource) noexcept; // Update destination state of specified subresources to correspond to the resource's bind points. void TransitionSubresourcesForBindings(Resource* pResource, CViewSubresourceSubset const& Subresources) noexcept; // Submit all barriers and queue sync. void ApplyAllResourceTransitions(bool bIsPreDraw = false) noexcept(false); using ResourceStateManagerBase::AddDeferredWait; }; };
57.892934
160
0.593579
procedural
d05485f7df5f87e26ce8365e46fbfa8ed8418a55
1,758
hpp
C++
progression/resource/shader.hpp
LiamTyler/OpenGL_Starter
7110e94cb583e5fbfefb70ede40d305674261c5a
[ "MIT" ]
null
null
null
progression/resource/shader.hpp
LiamTyler/OpenGL_Starter
7110e94cb583e5fbfefb70ede40d305674261c5a
[ "MIT" ]
null
null
null
progression/resource/shader.hpp
LiamTyler/OpenGL_Starter
7110e94cb583e5fbfefb70ede40d305674261c5a
[ "MIT" ]
null
null
null
#pragma once #include "core/math.hpp" #include "core/platform_defines.hpp" #include "graphics/graphics_api.hpp" #include "resource/resource.hpp" #include <vulkan/vulkan.h> #include <unordered_map> namespace Progression { namespace Gfx { enum class ShaderStage { VERTEX = 0x00000001, TESSELLATION_CONTROL = 0x00000002, TESSELLATION_EVALUATION = 0x00000004, GEOMETRY = 0x00000008, FRAGMENT = 0x00000010, COMPUTE = 0x00000020, }; } struct ShaderCreateInfo : public ResourceCreateInfo { std::string filename; }; class ShaderReflectInfo { public: ShaderReflectInfo() = default; std::string entryPoint; Gfx::ShaderStage stage; std::unordered_map< std::string, uint32_t > inputLocations; std::unordered_map< std::string, uint32_t > outputLocations; std::vector< Gfx::DescriptorSetLayoutData > descriptorSetLayouts; std::vector< VkPushConstantRange > pushConstants; }; class Shader : public Resource { public: Shader(); ~Shader(); Shader( Shader&& shader ); Shader& operator=( Shader&& shader ); bool Load( ResourceCreateInfo* createInfo ) override; void Move( std::shared_ptr< Resource > dst ) override; bool Serialize( std::ofstream& out ) const override; bool Deserialize( char*& buffer ) override; static ShaderReflectInfo Reflect( const uint32_t* spirv, size_t spirvSizeInBytes ); VkPipelineShaderStageCreateInfo GetVkPipelineShaderStageCreateInfo() const; void Free(); VkShaderModule GetHandle() const; operator bool() const; ShaderReflectInfo reflectInfo; protected: VkShaderModule m_shaderModule; }; } // namespace Progression
24.760563
87
0.684869
LiamTyler
d05bac40c19604712852e8646c9c812c72dff4b1
724
hpp
C++
libuavcan/include/uavcan/util/placement_new.hpp
tridge/uavcan_old
6dd432c9742c22e1dd1638c7f91cf937e4bdb2f1
[ "MIT" ]
null
null
null
libuavcan/include/uavcan/util/placement_new.hpp
tridge/uavcan_old
6dd432c9742c22e1dd1638c7f91cf937e4bdb2f1
[ "MIT" ]
null
null
null
libuavcan/include/uavcan/util/placement_new.hpp
tridge/uavcan_old
6dd432c9742c22e1dd1638c7f91cf937e4bdb2f1
[ "MIT" ]
null
null
null
/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #pragma once #include <cstddef> #include <uavcan/build_config.hpp> /* * Some embedded C++ implementations don't implement the placement new operator. * Define UAVCAN_IMPLEMENT_PLACEMENT_NEW to apply this workaround. */ #ifndef UAVCAN_IMPLEMENT_PLACEMENT_NEW # error UAVCAN_IMPLEMENT_PLACEMENT_NEW #endif #if UAVCAN_IMPLEMENT_PLACEMENT_NEW inline void* operator new (std::size_t, void* ptr) throw() { return ptr; } inline void* operator new[](std::size_t, void* ptr) throw() { return ptr; } inline void operator delete (void*, void*) throw() { } inline void operator delete[](void*, void*) throw() { } #else # include <new> #endif
20.111111
80
0.723757
tridge
d05c0e47dfcfbf4580a6c245ee181ec570c96dd5
811
cpp
C++
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/RangedWeapon.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
16
2019-05-23T08:10:39.000Z
2021-12-21T11:20:37.000Z
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/RangedWeapon.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
null
null
null
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/RangedWeapon.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
2
2019-05-23T18:37:43.000Z
2021-08-24T21:29:40.000Z
#include "RangedWeapon.h" #include "Sprite.h" #include "EntitySprite.h" using namespace qge; /// Returns the point at which projectiles will be spawn. /// This point is in local coordinates (relative to the RangedWeapon itself). QPointF RangedWeapon::projectileSpawnPoint() { return this->projectileSpawnPoint_; } void RangedWeapon::setProjectileSpawnPoint(QPointF point) { this->projectileSpawnPoint_ = point; } /// Resets the projectile spawn point to be at the very center of the RangedWeapon's sprite. void RangedWeapon::resetProjectileSpawnPoint() { double length = sprite()->currentlyDisplayedFrame().width(); double width = sprite()->currentlyDisplayedFrame().height(); QPointF center; center.setX(length/2); center.setY(width/2); setProjectileSpawnPoint(center); }
26.16129
92
0.747226
JamesMBallard
d05ca859750fea2d1ea71087dfe4f78008fc544e
7,973
cpp
C++
modfile/records/SrScrlRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
11
2015-07-19T08:33:00.000Z
2021-07-28T17:40:26.000Z
modfile/records/SrScrlRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
null
null
null
modfile/records/SrScrlRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
1
2015-02-28T22:52:18.000Z
2015-02-28T22:52:18.000Z
/*=========================================================================== * * File: SrScrlRecord.CPP * Author: Dave Humphrey (dave@uesp.net) * Created On: 5 December 2011 * * Description * *=========================================================================*/ /* Include Files */ #include "srScrlrecord.h" #include "../srrecordhandler.h" srscrldata_t CSrScrlRecord::s_NullScrollData; srscrlspitdata_t CSrScrlRecord::s_NullSpitData; /*=========================================================================== * * Begin Subrecord Creation Array * *=========================================================================*/ BEGIN_SRSUBRECCREATE(CSrScrlRecord, CSrItem1Record) DEFINE_SRSUBRECCREATE(SR_NAME_ETYP, CSrFormidSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_EFID, CSrFormidSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_DESC, CSrLStringSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_MDOB, CSrFormidSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_DATA, CSrScrlDataSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_SPIT, CSrScrlSpitSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_EFIT, CSrEfitSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_CTDA, CSrCtdaSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_CIS1, CSrStringSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_CIS2, CSrStringSubrecord::Create) END_SRSUBRECCREATE() /*=========================================================================== * End of Subrecord Creation Array *=========================================================================*/ /*=========================================================================== * * Begin CSrItem1Record Field Map * *=========================================================================*/ BEGIN_SRFIELDMAP(CSrScrlRecord, CSrItem1Record) ADD_SRFIELDALL("ItemName", SR_FIELD_ITEMNAME, 0, CSrScrlRecord, FieldItemName) ADD_SRFIELDALL("Description", SR_FIELD_DESCRIPTION, 0, CSrScrlRecord, FieldDescription) ADD_SRFIELDALL("EffectCount", SR_FIELD_EFFECTCOUNT, 0, CSrScrlRecord, FieldEffectCount) ADD_SRFIELDALL("EquipSlot", SR_FIELD_EQUIPSLOT, 0, CSrScrlRecord, FieldEquipSlot) ADD_SRFIELDALL("InventoryModel", SR_FIELD_INVENTORYMODEL, 0, CSrScrlRecord, FieldInventoryModel) ADD_SRFIELDALL("Weight", SR_FIELD_WEIGHT, 0, CSrScrlRecord, FieldWeight) ADD_SRFIELDALL("Value", SR_FIELD_VALUE, 0, CSrScrlRecord, FieldValue) ADD_SRFIELDALL("Range", SR_FIELD_RANGE, 0, CSrScrlRecord, FieldRange) ADD_SRFIELDALL("CastDuration", SR_FIELD_CASTTIME, 0, CSrScrlRecord, FieldCastDuration) ADD_SRFIELDALL("ChargeTime", SR_FIELD_CHARGETIME, 0, CSrScrlRecord, FieldChargeTime) ADD_SRFIELDALL("DeliveryType", SR_FIELD_DELIVERYTYPE, 0, CSrScrlRecord, FieldDeliveryType) ADD_SRFIELDALL("CastType", SR_FIELD_CASTTYPE, 0, CSrScrlRecord, FieldCastType) ADD_SRFIELDALL("BaseCost", SR_FIELD_BASECOST, 0, CSrScrlRecord, FieldBaseCost) ADD_SRFIELDALL("AutoCalc", SR_FIELD_AUTOCALC, 0, CSrScrlRecord, FieldAutoCalc) ADD_SRFIELDALL("AreaIgnoresLOS", SR_FIELD_AREAIGNORESLOS, 0, CSrScrlRecord, FieldAreaIgnoresLOS) ADD_SRFIELDALL("NoAbsorbReflect", SR_FIELD_NOABSORBREFLECT, 0, CSrScrlRecord, FieldNoAbsorbReflect) ADD_SRFIELDALL("ScriptAlwaysApplies", SR_FIELD_SCRIPTALWAYSAPPLIES, 0, CSrScrlRecord, FieldScriptAlwaysApplies) ADD_SRFIELDALL("ForceExplode", SR_FIELD_FORCEEXPLODE, 0, CSrScrlRecord, FieldForceExplode) END_SRFIELDMAP() /*=========================================================================== * End of CObRecord Field Map *=========================================================================*/ /*=========================================================================== * * Class CSrScrlRecord Constructor * *=========================================================================*/ CSrScrlRecord::CSrScrlRecord () { m_pEquipSlot = NULL; m_pDescription = NULL; m_pScrlData = NULL; m_pSpitData = NULL; m_pInventoryModel = NULL; } /*=========================================================================== * End of Class CSrScrlRecord Constructor *=========================================================================*/ /*=========================================================================== * * Class CSrScrlRecord Method - void Destroy (void); * *=========================================================================*/ void CSrScrlRecord::Destroy (void) { m_pEquipSlot = NULL; m_pDescription = NULL; m_pScrlData = NULL; m_pSpitData = NULL; m_pInventoryModel = NULL; CSrItem1Record::Destroy(); } /*=========================================================================== * End of Class Method CSrScrlRecord::Destroy() *=========================================================================*/ /*=========================================================================== * * Class CSrScrlRecord Method - void InitializeNew (void); * *=========================================================================*/ void CSrScrlRecord::InitializeNew (void) { CSrItem1Record::InitializeNew(); AddNewSubrecord(SR_NAME_DATA); if (m_pScrlData != NULL) m_pScrlData->InitializeNew(); AddNewSubrecord(SR_NAME_SPIT); if (m_pSpitData != NULL) m_pSpitData->InitializeNew(); AddNewSubrecord(SR_NAME_DESC); if (m_pDescription != NULL) m_pDescription->InitializeNew(); AddNewSubrecord(SR_NAME_ETYP); if (m_pEquipSlot != NULL) m_pEquipSlot->InitializeNew(); } /*=========================================================================== * End of Class Method CSrScrlRecord::InitializeNew() *=========================================================================*/ /*=========================================================================== * * Class CSrScrlRecord Event - void OnAddSubrecord (pSubrecord); * *=========================================================================*/ void CSrScrlRecord::OnAddSubrecord (CSrSubrecord* pSubrecord) { if (pSubrecord->GetRecordType() == SR_NAME_ETYP) { m_pEquipSlot = SrCastClass(CSrFormidSubrecord, pSubrecord); } else if (pSubrecord->GetRecordType() == SR_NAME_MDOB) { m_pInventoryModel = SrCastClass(CSrFormidSubrecord, pSubrecord); } else if (pSubrecord->GetRecordType() == SR_NAME_DESC) { m_pDescription = SrCastClass(CSrLStringSubrecord, pSubrecord); } else if (pSubrecord->GetRecordType() == SR_NAME_DATA) { m_pScrlData = SrCastClass(CSrScrlDataSubrecord, pSubrecord); } else if (pSubrecord->GetRecordType() == SR_NAME_SPIT) { m_pSpitData = SrCastClass(CSrScrlSpitSubrecord, pSubrecord); } else { CSrItem1Record::OnAddSubrecord(pSubrecord); } } /*=========================================================================== * End of Class Event CSrScrlRecord::OnAddSubRecord() *=========================================================================*/ /*=========================================================================== * * Class CSrScrlRecord Event - void OnDeleteSubrecord (pSubrecord); * *=========================================================================*/ void CSrScrlRecord::OnDeleteSubrecord (CSrSubrecord* pSubrecord) { if (m_pEquipSlot == pSubrecord) m_pEquipSlot = NULL; else if (m_pInventoryModel == pSubrecord) m_pInventoryModel = NULL; else if (m_pDescription == pSubrecord) m_pDescription = NULL; else if (m_pScrlData == pSubrecord) m_pScrlData = NULL; else if (m_pSpitData == pSubrecord) m_pSpitData = NULL; else CSrItem1Record::OnDeleteSubrecord(pSubrecord); } /*=========================================================================== * End of Class Event CSrScrlRecord::OnDeleteSubrecord() *=========================================================================*/
40.065327
113
0.529286
uesp
d05e3e0d3573e3c438f91f523f2f6aea7cd28bd5
231
hpp
C++
chaine/src/mesh/mesh/create_triangle.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/mesh/create_triangle.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/mesh/create_triangle.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
#pragma once #include "mesh.hpp" #include "topology.hpp" #include "mesh/triangle/proxy.hpp" namespace face_vertex { inline TriangleProxy create_triangle(Mesh& m) { return proxy(m, index(create_triangle(topology(m)))); } }
14.4375
57
0.731602
the-last-willy
d05fd6b7b0023145cccda237ec0572e8b738aa7b
1,550
hpp
C++
ufora/FORA/TypedFora/ABI/ArbitraryNativeConstantForCSTValue.hpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/FORA/TypedFora/ABI/ArbitraryNativeConstantForCSTValue.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/FORA/TypedFora/ABI/ArbitraryNativeConstantForCSTValue.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora 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. ****************************************************************************/ #pragma once #include "../../Native/NativeCode.hppml" #include "../../Native/ArbitraryNativeConstant.hpp" #include "../../Core/CSTValue.hppml" namespace TypedFora { namespace Abi { class ArbitraryNativeConstantForCSTValueType; class ArbitraryNativeConstantForCSTValue : public ArbitraryNativeConstant { public: ArbitraryNativeConstantForCSTValue(const CSTValue& in, bool asImplval); ArbitraryNativeConstantType* type(); NativeType nativeType(); void* pointerToData(); std::string description(); hash_type hash(); static NativeExpression expressionForCSTValueTyped(const CSTValue& in); static NativeExpression expressionForCSTValueAsImplval(const CSTValue& in); private: friend class ArbitraryNativeConstantForCSTValueType; ImplVal mReference; CSTValue mValue; bool mAsImplval; }; } }
26.271186
77
0.696129
ufora
d05ff47f5ed157f07009b8184251062ba1117a46
681
cpp
C++
optimal-division.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
1
2021-01-20T16:04:54.000Z
2021-01-20T16:04:54.000Z
optimal-division.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
293
2018-11-29T14:54:29.000Z
2021-01-29T16:07:26.000Z
optimal-division.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
1
2020-11-10T10:49:12.000Z
2020-11-10T10:49:12.000Z
/* * Copyright (c) 2018 Christopher Friedt * * SPDX-License-Identifier: MIT */ #include <string> #include <vector> using namespace std; class Solution { public: // https://leetcode.com/problems/optimal-division string optimalDivision(vector<int> &nums) { size_t N = nums.size(); if (N > 2) { string s(to_string(nums[0]) + "/(" + to_string(nums[1])); for (size_t i = 2; i < N; i++) { s += "/" + to_string(nums[i]); } s += ")"; return s; } else if (2 == N) { return to_string(nums[0]) + "/" + to_string(nums[1]); } else if (1 == N) { return to_string(nums[0]); } else { return ""; } } };
19.457143
63
0.530103
cfriedt
d0611935cfb85c847eb933c2b5fd27f1284aa6d8
1,100
hpp
C++
Oem/dbxml/dbxml/src/dbxml/UpdateContext.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/dbxml/dbxml/src/dbxml/UpdateContext.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/dbxml/dbxml/src/dbxml/UpdateContext.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // See the file LICENSE for redistribution information. // // Copyright (c) 2002,2009 Oracle. All rights reserved. // // #ifndef __UPDATECONTEXT_HPP #define __UPDATECONTEXT_HPP #include "ReferenceCounted.hpp" #include "Container.hpp" #include "Indexer.hpp" #include "IndexSpecification.hpp" #include "OperationContext.hpp" #include "KeyStash.hpp" namespace DbXml { class DBXML_EXPORT UpdateContext : public ReferenceCounted { public: /// Constructor. UpdateContext(XmlManager &mgr); virtual ~UpdateContext(); void init(Transaction *txn, Container *container); Indexer &getIndexer(); KeyStash &getKeyStash(bool reset = true); IndexSpecification &getIndexSpecification(); OperationContext &getOperationContext(); private: // no need for copy and assignment UpdateContext(const UpdateContext&); UpdateContext &operator=(const UpdateContext &); // Hold a reference to the XmlManager, so it isn't destroyed before we are XmlManager mgr_; // Avoid re-making each of these objects Indexer indexer_; KeyStash stash_; IndexSpecification is_; OperationContext oc_; }; } #endif
20.754717
75
0.764545
achilex
d0620f145594274dab3e17380e893ce23bf4a984
2,440
cpp
C++
src/ui/contacts/VKUContactsPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/contacts/VKUContactsPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/contacts/VKUContactsPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
#include "AppResourceId.h" #include "VKUContactsPanel.h" #include "VKUApi.h" #include "UsersPanel.h" #include "SceneRegister.h" #include "ObjectCounter.h" using namespace Tizen::Base; using namespace Tizen::Ui; using namespace Tizen::Ui::Controls; using namespace Tizen::Ui::Scenes; using namespace Tizen::Base::Collection; using namespace Tizen::Web::Json; VKUContactsPanel::VKUContactsPanel(void) { CONSTRUCT(L"VKUContactsPanel"); // pProvider = new ContactsTableProvider(); } VKUContactsPanel::~VKUContactsPanel(void) { DESTRUCT(L"VKUContactsPanel"); // delete pProvider; } bool VKUContactsPanel::Initialize() { Panel::Construct(IDC_PANEL_CONTACTS); return true; } result VKUContactsPanel::OnInitializing(void) { result r = E_SUCCESS; Integer userIdInt = Integer(VKUAuthConfig::GetUserId()); _usersPanel = new UsersPanel(); _usersPanel->Construct(GetBounds()); r = AddControl(_usersPanel); _usersPanel->AddUserSelectedListener(this); Form * form = dynamic_cast<Form *>(GetParent()); RelativeLayout * layout = dynamic_cast<RelativeLayout *>(form->GetLayoutN()); layout->SetVerticalFitPolicy(*this, FIT_POLICY_PARENT); return r; } result VKUContactsPanel::OnTerminating(void) { result r = E_SUCCESS; // TODO: Add your termination code here return r; } void VKUContactsPanel::ClearItems() { AppLog("CONTACTSEVENT: scene deactivated"); // GroupedTableView* pTable = static_cast<GroupedTableView*>(GetControl(IDC_GROUPEDTABLEVIEW1)); // pTable->Invalidate(true); } void VKUContactsPanel::OnSceneActivatedN(const Tizen::Ui::Scenes::SceneId& previousSceneId, const Tizen::Ui::Scenes::SceneId& currentSceneId, Tizen::Base::Collection::IList* pArgs) { AppLog("contacts activated"); _usersPanel->RequestModel(MODEL_TYPE_FRIENDS_ALPHA); } void VKUContactsPanel::OnSceneDeactivated(const Tizen::Ui::Scenes::SceneId& currentSceneId, const Tizen::Ui::Scenes::SceneId& nextSceneId) { AppLog("contacts deactivated"); _usersPanel->ClearModel(); } void VKUContactsPanel::OnUserSelected(const Tizen::Web::Json::JsonObject * userJson) { SceneManager* pSceneManager = SceneManager::GetInstance(); AppAssert(pSceneManager); ArrayList* pList = new (std::nothrow) ArrayList(SingleObjectDeleter); pList->Construct(1); pList->Add(userJson->CloneN()); pSceneManager->GoForward(ForwardSceneTransition(SCENE_USER, SCENE_TRANSITION_ANIMATION_TYPE_LEFT, SCENE_HISTORY_OPTION_ADD_HISTORY), pList); }
27.727273
141
0.766803
igorglotov
d0622848b7eb8afef2a3a200338bcddad81d9cca
19,655
cpp
C++
pwiz/analysis/spectrum_processing/SpectrumList_FilterTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
2
2019-12-28T21:24:36.000Z
2020-04-18T03:52:05.000Z
pwiz/analysis/spectrum_processing/SpectrumList_FilterTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
pwiz/analysis/spectrum_processing/SpectrumList_FilterTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
// // $Id: SpectrumList_FilterTest.cpp 10462 2017-02-10 17:52:32Z chambm $ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2008 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // 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 "SpectrumList_Filter.hpp" #include "pwiz/utility/misc/unit.hpp" #include "pwiz/utility/misc/IntegerSet.hpp" #include "pwiz/utility/misc/Std.hpp" #include "pwiz/data/msdata/examples.hpp" #include "pwiz/data/msdata/Serializer_mzML.hpp" #include <cstring> using namespace pwiz; using namespace pwiz::msdata; using namespace pwiz::analysis; using namespace pwiz::util; using boost::logic::tribool; ostream* os_ = 0; void printSpectrumList(const SpectrumList& sl, ostream& os) { os << "size: " << sl.size() << endl; for (size_t i=0, end=sl.size(); i<end; i++) { SpectrumPtr spectrum = sl.spectrum(i, false); os << spectrum->index << " " << spectrum->id << " " << "ms" << spectrum->cvParam(MS_ms_level).value << " " << "scanEvent:" << spectrum->scanList.scans[0].cvParam(MS_preset_scan_configuration).value << " " << "scanTime:" << spectrum->scanList.scans[0].cvParam(MS_scan_start_time).timeInSeconds() << " " << endl; } } SpectrumListPtr createSpectrumList() { SpectrumListSimplePtr sl(new SpectrumListSimple); for (size_t i=0; i<10; ++i) { SpectrumPtr spectrum(new Spectrum); spectrum->index = i; spectrum->id = "scan=" + lexical_cast<string>(100+i); spectrum->setMZIntensityPairs(vector<MZIntensityPair>(i), MS_number_of_detector_counts); // add mz/intensity to the spectra for mzPresent filter vector<MZIntensityPair> mzint(i*2); for (size_t j=1.0; j<i*2; ++j) { mzint.insert(mzint.end(), MZIntensityPair(j*100, j*j)); } spectrum->setMZIntensityPairs(mzint, MS_number_of_detector_counts); bool isMS1 = i%3==0; spectrum->set(MS_ms_level, isMS1 ? 1 : 2); spectrum->set(isMS1 ? MS_MS1_spectrum : MS_MSn_spectrum); // outfit the spectra with mass analyzer definitions to test the massAnalyzer filter spectrum->scanList.scans.push_back(Scan()); spectrum->scanList.scans[0].instrumentConfigurationPtr = InstrumentConfigurationPtr(new InstrumentConfiguration()); InstrumentConfigurationPtr p = spectrum->scanList.scans[0].instrumentConfigurationPtr; if (i%3 == 0) { p->componentList.push_back(Component(MS_orbitrap, 0/*order*/)); } else { if (i%2) p->componentList.push_back(Component(MS_orbitrap, 0/*order*/)); else p->componentList.push_back(Component(MS_radial_ejection_linear_ion_trap, 0/*order*/)); } if (i%3 != 0) spectrum->precursors.push_back(Precursor(500, 3)); // add precursors and activation types to the MS2 spectra if (i==1 || i ==5) // ETD { spectrum->precursors[0].activation.set(MS_electron_transfer_dissociation); } else if (i==2) // CID { spectrum->precursors[0].activation.set(MS_collision_induced_dissociation); } else if (i==4) // HCD { spectrum->precursors[0].activation.set(MS_HCD); } else if (i==8) // IRMPD { spectrum->precursors[0].activation.set(MS_IRMPD); } else if (i==7) // ETD + SA { spectrum->precursors[0].activation.set(MS_electron_transfer_dissociation); spectrum->precursors[0].activation.set(MS_collision_induced_dissociation); } spectrum->scanList.scans.push_back(Scan()); spectrum->scanList.scans[0].set(MS_preset_scan_configuration, i%4); spectrum->scanList.scans[0].set(MS_scan_start_time, 420+i, UO_second); sl->spectra.push_back(spectrum); } if (os_) { *os_ << "original spectrum list:\n"; printSpectrumList(*sl, *os_); *os_ << endl; } return sl; } struct EvenPredicate : public SpectrumList_Filter::Predicate { virtual tribool accept(const SpectrumIdentity& spectrumIdentity) const { return spectrumIdentity.index%2 == 0; } }; void testEven(SpectrumListPtr sl) { if (os_) *os_ << "testEven:\n"; SpectrumList_Filter filter(sl, EvenPredicate()); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 5); for (size_t i=0, end=filter.size(); i<end; i++) { const SpectrumIdentity& id = filter.spectrumIdentity(i); unit_assert(id.index == i); unit_assert(id.id == "scan=" + lexical_cast<string>(100+i*2)); SpectrumPtr spectrum = filter.spectrum(i); unit_assert(spectrum->index == i); unit_assert(spectrum->id == "scan=" + lexical_cast<string>(100+i*2)); } } struct EvenMS2Predicate : public SpectrumList_Filter::Predicate { virtual tribool accept(const SpectrumIdentity& spectrumIdentity) const { if (spectrumIdentity.index%2 != 0) return false; return boost::logic::indeterminate; } virtual tribool accept(const Spectrum& spectrum) const { CVParam param = spectrum.cvParamChild(MS_spectrum_type); if (param.cvid == CVID_Unknown) return boost::logic::indeterminate; if (!cvIsA(param.cvid, MS_mass_spectrum)) return true; // MS level filter doesn't affect non-MS spectra param = spectrum.cvParam(MS_ms_level); if (param.cvid == CVID_Unknown) return boost::logic::indeterminate; return (param.valueAs<int>() == 2); } }; void testEvenMS2(SpectrumListPtr sl) { if (os_) *os_ << "testEvenMS2:\n"; SpectrumList_Filter filter(sl, EvenMS2Predicate()); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 3); unit_assert(filter.spectrumIdentity(0).id == "scan=102"); unit_assert(filter.spectrumIdentity(1).id == "scan=104"); unit_assert(filter.spectrumIdentity(2).id == "scan=108"); } struct SelectedIndexPredicate : public SpectrumList_Filter::Predicate { mutable bool pastMaxIndex; SelectedIndexPredicate() : pastMaxIndex(false) {} virtual tribool accept(const SpectrumIdentity& spectrumIdentity) const { if (spectrumIdentity.index>5) pastMaxIndex = true; return (spectrumIdentity.index==1 || spectrumIdentity.index==3 || spectrumIdentity.index==5); } virtual bool done() const { return pastMaxIndex; } }; void testSelectedIndices(SpectrumListPtr sl) { if (os_) *os_ << "testSelectedIndices:\n"; SpectrumList_Filter filter(sl, SelectedIndexPredicate()); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 3); unit_assert(filter.spectrumIdentity(0).id == "scan=101"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=105"); } struct HasBinaryDataPredicate : public SpectrumList_Filter::Predicate { HasBinaryDataPredicate(DetailLevel suggestedDetailLevel) : detailLevel_(suggestedDetailLevel) {} DetailLevel detailLevel_; virtual DetailLevel suggestedDetailLevel() const {return detailLevel_;} virtual tribool accept(const msdata::SpectrumIdentity& spectrumIdentity) const { return boost::logic::indeterminate; } virtual tribool accept(const Spectrum& spectrum) const { if (spectrum.binaryDataArrayPtrs.empty()) return boost::logic::indeterminate; return !spectrum.binaryDataArrayPtrs[0]->data.empty(); } }; void testHasBinaryData(SpectrumListPtr sl) { if (os_) *os_ << "testHasBinaryData:\n"; MSData msd; examples::initializeTiny(msd); shared_ptr<stringstream> ss(new stringstream); Serializer_mzML serializer; serializer.write(*ss, msd); MSData msd2; serializer.read(ss, msd2); sl = msd2.run.spectrumListPtr; { SpectrumList_Filter filter(sl, HasBinaryDataPredicate(DetailLevel_FullMetadata)); unit_assert(filter.empty()); } { SpectrumList_Filter filter(sl, HasBinaryDataPredicate(DetailLevel_FullData)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert_operator_equal(4, filter.size()); } } void testIndexSet(SpectrumListPtr sl) { if (os_) *os_ << "testIndexSet:\n"; IntegerSet indexSet; indexSet.insert(3,5); indexSet.insert(7); indexSet.insert(9); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_IndexSet(indexSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 5); unit_assert(filter.spectrumIdentity(0).id == "scan=103"); unit_assert(filter.spectrumIdentity(1).id == "scan=104"); unit_assert(filter.spectrumIdentity(2).id == "scan=105"); unit_assert(filter.spectrumIdentity(3).id == "scan=107"); unit_assert(filter.spectrumIdentity(4).id == "scan=109"); } void testScanNumberSet(SpectrumListPtr sl) { if (os_) *os_ << "testScanNumberSet:\n"; IntegerSet scanNumberSet; scanNumberSet.insert(102,104); scanNumberSet.insert(107); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanNumberSet(scanNumberSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 4); unit_assert(filter.spectrumIdentity(0).id == "scan=102"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=104"); unit_assert(filter.spectrumIdentity(3).id == "scan=107"); } void testScanEventSet(SpectrumListPtr sl) { if (os_) *os_ << "testScanEventSet:\n"; IntegerSet scanEventSet; scanEventSet.insert(0,0); scanEventSet.insert(2,3); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanEventSet(scanEventSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 7); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); unit_assert(filter.spectrumIdentity(1).id == "scan=102"); unit_assert(filter.spectrumIdentity(2).id == "scan=103"); unit_assert(filter.spectrumIdentity(3).id == "scan=104"); unit_assert(filter.spectrumIdentity(4).id == "scan=106"); unit_assert(filter.spectrumIdentity(5).id == "scan=107"); unit_assert(filter.spectrumIdentity(6).id == "scan=108"); } void testScanTimeRange(SpectrumListPtr sl) { if (os_) *os_ << "testScanTimeRange:\n"; const double low = 422.5; const double high = 427.5; SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanTimeRange(low, high)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 5); unit_assert(filter.spectrumIdentity(0).id == "scan=103"); unit_assert(filter.spectrumIdentity(1).id == "scan=104"); unit_assert(filter.spectrumIdentity(2).id == "scan=105"); unit_assert(filter.spectrumIdentity(3).id == "scan=106"); unit_assert(filter.spectrumIdentity(4).id == "scan=107"); } void testMSLevelSet(SpectrumListPtr sl) { if (os_) *os_ << "testMSLevelSet:\n"; IntegerSet msLevelSet; msLevelSet.insert(1); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_MSLevelSet(msLevelSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 4); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=106"); unit_assert(filter.spectrumIdentity(3).id == "scan=109"); IntegerSet msLevelSet2; msLevelSet2.insert(2); SpectrumList_Filter filter2(sl, SpectrumList_FilterPredicate_MSLevelSet(msLevelSet2)); if (os_) { printSpectrumList(filter2, *os_); *os_ << endl; } unit_assert(filter2.size() == 6); unit_assert(filter2.spectrumIdentity(0).id == "scan=101"); unit_assert(filter2.spectrumIdentity(1).id == "scan=102"); unit_assert(filter2.spectrumIdentity(2).id == "scan=104"); unit_assert(filter2.spectrumIdentity(3).id == "scan=105"); unit_assert(filter2.spectrumIdentity(4).id == "scan=107"); unit_assert(filter2.spectrumIdentity(5).id == "scan=108"); } void testMS2Activation(SpectrumListPtr sl) { if (os_) *os_ << "testMS2Activation:\n"; SpectrumListPtr ms2filter(new SpectrumList_Filter(sl, SpectrumList_FilterPredicate_MSLevelSet(IntegerSet(2)))); set<CVID> cvIDs; // CID cvIDs.insert(MS_electron_transfer_dissociation); cvIDs.insert(MS_HCD); cvIDs.insert(MS_IRMPD); SpectrumList_Filter filter(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, true)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 1); unit_assert(filter.spectrumIdentity(0).id == "scan=102"); // ETD + SA cvIDs.clear(); cvIDs.insert(MS_electron_transfer_dissociation); cvIDs.insert(MS_collision_induced_dissociation); SpectrumList_Filter filter1(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter1, *os_); *os_ << endl; } unit_assert(filter1.size() == 1); unit_assert(filter1.spectrumIdentity(0).id == "scan=107"); // ETD cvIDs.clear(); cvIDs.insert(MS_electron_transfer_dissociation); SpectrumList_Filter filter2(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter2, *os_); *os_ << endl; } unit_assert(filter2.size() == 3); unit_assert(filter2.spectrumIdentity(0).id == "scan=101"); unit_assert(filter2.spectrumIdentity(1).id == "scan=105"); unit_assert(filter2.spectrumIdentity(2).id == "scan=107"); // HCD cvIDs.clear(); cvIDs.insert(MS_HCD); SpectrumList_Filter filter3(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter3, *os_); *os_ << endl; } unit_assert(filter3.size() == 1); unit_assert(filter3.spectrumIdentity(0).id == "scan=104"); // IRMPD cvIDs.clear(); cvIDs.insert(MS_IRMPD); SpectrumList_Filter filter4(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter4, *os_); *os_ << endl; } unit_assert(filter4.size() == 1); unit_assert(filter4.spectrumIdentity(0).id == "scan=108"); } void testMassAnalyzerFilter(SpectrumListPtr sl) { if (os_) *os_ << "testMassAnalyzerFilter:\n"; set<CVID> cvIDs; // msconvert mass analyzer filter FTMS option cvIDs.insert(MS_orbitrap); cvIDs.insert(MS_fourier_transform_ion_cyclotron_resonance_mass_spectrometer); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_AnalyzerType(cvIDs)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 7); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); cvIDs.clear(); // msconvert mass analyzer filter ITMS option cvIDs.insert(MS_ion_trap); SpectrumList_Filter filter1(sl, SpectrumList_FilterPredicate_AnalyzerType(cvIDs)); if (os_) { printSpectrumList(filter1, *os_); *os_ << endl; } unit_assert(filter1.size() == 3); unit_assert(filter1.spectrumIdentity(0).id == "scan=102"); } void testMZPresentFilter(SpectrumListPtr sl) { if (os_) *os_ << "testMZPresentFilter:\n"; // test mzpresent on MS level 2 (include test) SpectrumListPtr ms2filter(new SpectrumList_Filter(sl, SpectrumList_FilterPredicate_MSLevelSet(IntegerSet(2)))); chemistry::MZTolerance mzt(3.0); std::set<double> mzSet; mzSet.insert(200.0); mzSet.insert(300.0); mzSet.insert(400.0); double threshold = 10; IntegerSet msLevels(1, INT_MAX); ThresholdFilter tf(ThresholdFilter::ThresholdingBy_Count, threshold, ThresholdFilter::Orientation_MostIntense, msLevels); SpectrumList_Filter filter(ms2filter, SpectrumList_FilterPredicate_MzPresent(mzt, mzSet, tf, SpectrumList_Filter::Predicate::FilterMode_Include)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert_operator_equal(4, filter.size()); unit_assert_operator_equal("scan=102", filter.spectrumIdentity(0).id); unit_assert_operator_equal("scan=104", filter.spectrumIdentity(1).id); unit_assert_operator_equal("scan=105", filter.spectrumIdentity(2).id); unit_assert_operator_equal("scan=107", filter.spectrumIdentity(3).id); // test mz present on MS level 1 (exclude test) SpectrumListPtr ms1filter(new SpectrumList_Filter(sl, SpectrumList_FilterPredicate_MSLevelSet(IntegerSet(1)))); chemistry::MZTolerance mzt1(3.0); std::set<double> mzSet1; mzSet1.insert(200.0); mzSet1.insert(300.0); double threshold1 = 5; ThresholdFilter tf1(ThresholdFilter::ThresholdingBy_Count, threshold1, ThresholdFilter::Orientation_MostIntense, msLevels); SpectrumList_Filter filter1(ms1filter, SpectrumList_FilterPredicate_MzPresent(mzt1, mzSet1, tf1, SpectrumList_Filter::Predicate::FilterMode_Exclude)); if (os_) { printSpectrumList(filter1, *os_); *os_ << endl; } unit_assert_operator_equal(3, filter1.size()); unit_assert_operator_equal("scan=100", filter1.spectrumIdentity(0).id); unit_assert_operator_equal("scan=106", filter1.spectrumIdentity(1).id); unit_assert_operator_equal("scan=109", filter1.spectrumIdentity(2).id); } void test() { SpectrumListPtr sl = createSpectrumList(); testEven(sl); testEvenMS2(sl); testSelectedIndices(sl); testHasBinaryData(sl); testIndexSet(sl); testScanNumberSet(sl); testScanEventSet(sl); testScanTimeRange(sl); testMSLevelSet(sl); testMS2Activation(sl); testMassAnalyzerFilter(sl); testMZPresentFilter(sl); } int main(int argc, char* argv[]) { TEST_PROLOG(argc, argv) try { if (argc>1 && !strcmp(argv[1],"-v")) os_ = &cout; test(); } catch (exception& e) { TEST_FAILED(e.what()) } catch (...) { TEST_FAILED("Caught unknown exception.") } TEST_EPILOG }
29.379671
154
0.654846
shze
d06472c7490413f30aa3bc094faa073afb2a4f1d
14,820
cpp
C++
src/mruntime/GlobalEventReceiver.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
1
2016-03-26T13:25:08.000Z
2016-03-26T13:25:08.000Z
src/mruntime/GlobalEventReceiver.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
src/mruntime/GlobalEventReceiver.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
#include "GlobalEventReceiver.h" #include "OSRenderBehaviourNotifier.h" #include "OSAttachControllersBehaviourNotifier.h" #include "OSDetachControllersBehaviourNotifier.h" #include "OSScriptRunBehaviourNotifier.h" #include "OSWindowCloseBehaviourNotifier.h" #include "OSStartWindowBehaviourNotifier.h" #include "OSStartApplicationBehaviourNotifier.h" #include "OSQtWidgetInitBehaviourNotifier.h" #include "RuntimeScript.h" #include "ApplicationLoader.h" #include "WindowManager.h" #include "SystemComObjectManager.h" using namespace Magna::SystemComponent; #include <QApplication> namespace Magna{ namespace Runtime{ GlobalEventReceiver& GlobalEventReceiver::getGlobalEventReceiver(){ OSBehaviourNotifierHandler & _handler = OSBehaviourNotifierHandler::getOSBehaviourNotifierHandler(); static SharedPtr<GlobalEventReceiver> eventReceiver = new GlobalEventReceiver( &_handler ); return *eventReceiver; } GlobalEventReceiver::GlobalEventReceiver(OSBehaviourNotifierHandler *handler ) :m_mutex() ,m_handler( handler ){ } GlobalEventReceiver::~GlobalEventReceiver(){ } void GlobalEventReceiver::requestWindowMoved(const unicode_char *id, const IntegerDyadCoordinate& coord ){ QString _movedScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); _movedScript.append( RuntimeScript::shared_JavaScript_Service_set_window_pos ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( coord.getX() ) ) .append( "," ) .append( QString::number( coord.getY() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _movedScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestDraggableWindowMove( const unicode_char *id, const IntegerDyadCoordinate& trigger_coord, const IntegerDyadCoordinate& offset ){ QString _movedScript = QString( RuntimeScript::shared_JavaScript_Functionality_Window_Rubber_Band ); _movedScript.append( RuntimeScript::shared_JavaScript_Functionality_trigger_translate ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( trigger_coord.getX() ) ) .append( "," ) .append( QString::number( trigger_coord.getY() ) ) .append( "," ) .append( QString::number( offset.getX()) ) .append( "," ) .append( QString::number( offset.getY() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _movedScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowResized( const unicode_char *id, const IntegerSize& size){ QString _resizedScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); _resizedScript.append( RuntimeScript::shared_JavaScript_Service_set_window_size ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _resizedScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowRendering( ManipulateEngine& engine ){ OSRenderBehaviourNotifier *notifier = new OSRenderBehaviourNotifier( engine ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllersAttached( std::vector<SharedPtr<Controller::ControllerRoot> > & ctrls ,RunnableContext * context){ OSAttachControllersBehaviourNotifier *notifier = new OSAttachControllersBehaviourNotifier( context, ctrls ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllersDetached( const std::vector< uint64 > & ids) { OSDetachControllersBehaviourNotifier *notifier = new OSDetachControllersBehaviourNotifier( ids ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowClose( uint32 id) { OSWindowCloseBehaviourNotifier *notifier = new OSWindowCloseBehaviourNotifier( id ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowVisibilityChanged( const unicode_char *id, bool isVisible) { QString visibScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); if( isVisible ){ visibScript.append( RuntimeScript::shared_JavaScript_Service_set_window_visible ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( ");" ); } else{ visibScript.append( RuntimeScript::shared_JavaScript_Service_set_window_hidden ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( ");" ); } OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( visibScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowFocusChanged( const unicode_char * _id, uint32 _int_id, bool isFocusIn ) { //focus script QString focusScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); if( isFocusIn ){ focusScript.append( RuntimeScript::shared_JavaScript_Service_window_focus_in ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( _id ) ) ) #else .append( QString::fromStdWString( _id ) ) #endif .append( ");" ); } else{ focusScript.append( RuntimeScript::shared_JavaScript_Service_window_focus_out ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( _id ) ) ) #else .append( QString::fromStdWString( _id ) ) #endif .append( ");" ); } OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( focusScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); auto & _coms_manager = SystemComObjectManager::getSystemComObjectManager(); _coms_manager.getDesktopObject().actDispatchWindowFocusChanged( _int_id, isFocusIn ); } void GlobalEventReceiver::requestStartPopOutWindow( const SharedPtr<Window::WindowRoot>& w) { if( !w.isNull() && w->m_requester != Nullptr && w->m_RunnableContext != Nullptr ){ OSStartWindowBehaviourNotifier*notifier = new OSStartWindowBehaviourNotifier( w, WindowManager::WindowType_PopOut ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } } void GlobalEventReceiver::requestStartNewWindow( const SharedPtr<Window::WindowRoot>& w ) { if( !w.isNull() && w->m_requester != Nullptr && w->m_RunnableContext != Nullptr ){ OSStartWindowBehaviourNotifier*notifier = new OSStartWindowBehaviourNotifier( w, WindowManager::WindowType_Normal ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } } void GlobalEventReceiver::requestStartNewApplication( const String& p, RunnableContext * r ) { OSStartApplicationBehaviourNotifier *notifier = new OSStartApplicationBehaviourNotifier( false, p, r ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestScriptEval( const String& sc ){ if( !sc.empty() ){ #ifdef _MSC_VER QString _sc = QString::fromUtf16( reinterpret_cast<const ushort *>( sc.c_str() ), sc.size() ) ; #else QString _sc = QString::fromStdWString( sc ) ; #endif OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } } void GlobalEventReceiver::askObtainApplicationInfo( const String& a1, String& a2, String& a3){ auto &_loader = ApplicationLoader::obtainLoader(); _loader.loadApplicationExpInfo( a1, a2, a3 ); } void GlobalEventReceiver::requestStartNewApplicationWithDialog( const String& p, RunnableContext * r ) { OSStartApplicationBehaviourNotifier *notifier = new OSStartApplicationBehaviourNotifier( !false, p, r ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllerResized( const unicode_char *id, const IntegerSize& size ) { QString resized_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); resized_sc.append( RuntimeScript::shared_JavaScript_Service_controller_resize ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( resized_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllerMoved( const unicode_char *id, const IntegerDyadCoordinate& coord ) { QString moved_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); moved_sc.append( RuntimeScript::shared_JavaScript_Service_controller_move ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( coord.getX() ) ) .append( "," ) .append( QString::number( coord.getY() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( moved_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestContentResized( const unicode_char *id, const IntegerSize& size ) { QString resized_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); resized_sc.append( RuntimeScript::shared_JavaScript_Service_content_resize ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( resized_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWrapperResized( const unicode_char *id, const IntegerSize& size) { QString resized_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); resized_sc.append( RuntimeScript::shared_JavaScript_Service_wrapper_resize ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( resized_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestQtWidgetInit( QtWidgetInitializer *init ) { OSQtWidgetInitBehaviourNotifier*notifier = new OSQtWidgetInitBehaviourNotifier( init ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestNotifierRunOnCore( const SharedPtr<AbstractedNotifier>& n ) { } } }//namespace Magna
38.493506
167
0.631242
0of
d0671748b70bb83cf7a659a55423e7f4ff7865ef
1,399
cpp
C++
src/Matrix4.cpp
ianmurfinxyz/software_renderer
1feef4754509d99013dc4bbe51006d858bc27561
[ "Unlicense" ]
null
null
null
src/Matrix4.cpp
ianmurfinxyz/software_renderer
1feef4754509d99013dc4bbe51006d858bc27561
[ "Unlicense" ]
null
null
null
src/Matrix4.cpp
ianmurfinxyz/software_renderer
1feef4754509d99013dc4bbe51006d858bc27561
[ "Unlicense" ]
null
null
null
#include "Matrix4.h" using namespace gr; Matrix4::Matrix4(){ this->e[0][0] = 0.f; this->e[0][1] = 0.f; this->e[0][2] = 0.f; this->e[0][3] = 0.f; this->e[1][0] = 0.f; this->e[1][1] = 0.f; this->e[1][2] = 0.f; this->e[1][3] = 0.f; this->e[2][0] = 0.f; this->e[2][1] = 0.f; this->e[2][2] = 0.f; this->e[2][3] = 0.f; this->e[3][0] = 0.f; this->e[3][1] = 0.f; this->e[3][2] = 0.f; this->e[3][3] = 0.f; } Matrix4::Matrix4(float e00, float e01, float e02, float e03, float e10, float e11, float e12, float e13, float e20, float e21, float e22, float e23, float e30, float e31, float e32, float e33){ this->e[0][0] = e00; this->e[0][1] = e01; this->e[0][2] = e02; this->e[0][3] = e03; this->e[1][0] = e10; this->e[1][1] = e11; this->e[1][2] = e12; this->e[1][3] = e13; this->e[2][0] = e20; this->e[2][1] = e21; this->e[2][2] = e22; this->e[2][3] = e23; this->e[3][0] = e30; this->e[3][1] = e31; this->e[3][2] = e32; this->e[3][3] = e33; } Matrix4 Matrix4::mul(const Matrix4& m) const{ Matrix4 tmp; for(int k = 0; k <= 3; k++){ for(int j = 0; j <= 3; j++){ for(int i = 0; i <= 3; i++){ tmp.e[k][j] += this->e[k][i] * m.e[i][j]; } } } return tmp; }
22.564516
61
0.425304
ianmurfinxyz
d0681640cd60261669e246ddaef044d5576a7fd4
189
cpp
C++
CodeForces/Complete/200-299/246A-BuggySorting.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/200-299/246A-BuggySorting.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/200-299/246A-BuggySorting.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> int main(){ int n; scanf("%d", &n); if(n <= 2){printf("-1\n");} else{printf("3 2 ");for(int k = 0;k < n-2; k++){printf("1 ");};printf("\n");} return 0; }
21
81
0.465608
Ashwanigupta9125
d0695eaf6fa81759dadae3c3475dd9bcf0ed247b
35,813
cpp
C++
Underlight/Interface.cpp
christyganger/ULClient
bc008ab3042ff9b74d47cdda47ce2318311a51db
[ "BSD-3-Clause" ]
5
2018-08-17T17:17:01.000Z
2020-11-14T05:41:31.000Z
Underlight/Interface.cpp
christyganger/ULClient
bc008ab3042ff9b74d47cdda47ce2318311a51db
[ "BSD-3-Clause" ]
16
2018-08-16T15:37:04.000Z
2019-12-24T19:09:19.000Z
Underlight/Interface.cpp
christyganger/ULClient
bc008ab3042ff9b74d47cdda47ce2318311a51db
[ "BSD-3-Clause" ]
5
2018-08-16T15:34:41.000Z
2019-03-04T04:06:11.000Z
// Interface: utility functions for making the interface pretty // Copyright Lyra LLC, 1997. All rights reserved. #define STRICT #define OEMRESOURCE // to get defines for windows cursor id's #include "Central.h" #include <windows.h> #include <windowsx.h> #include "Utils.h" #include "Resource.h" #include "cGameServer.h" #include "Options.h" #include "SharedConstants.h" #include "cPlayer.h" #include "cDDraw.h" #include "cDSound.h" #include "Realm.h" #include "cChat.h" #include "Dialogs.h" #include "cOutput.h" #include "cKeymap.h" #include "Mouse.h" #include "cArts.h" #include "Interface.h" #include "cEffects.h" ///////////////////////////////////////////////// // External Global Variables extern cGameServer *gs; extern HINSTANCE hInstance; extern cPlayer *player; extern cDDraw *cDD; extern cDSound *cDS; extern cArts *arts; extern cEffects *effects; extern bool ready; extern options_t options; extern cKeymap *keymap; extern cChat *display; extern HFONT display_font[MAX_RESOLUTIONS]; extern float scale_x; extern float scale_y; //const unsigned long lyra_colors[9] = {BLUE, LTBLUE, DKBLUE, LTBLUE, ORANGE, BLUE, // ORANGE, BLACK, ORANGE}; ////////////////////////////////////////////////////////////////// // Constant Structures // Pointers to functions for subclassing static WNDPROC lpfnPushButtonProc; static WNDPROC lpfnStateButtonProc; // radio,check buttons static WNDPROC lpfnStaticTextProc; static WNDPROC lpfnListBoxProc; static WNDPROC lpfnComboBoxProc; static WNDPROC lpfnTrackBarProc; static WNDPROC lpfnEditProc; static WNDPROC lpfnGenericProc; static HBRUSH blueBrush = NULL; static HBRUSH blackBrush = NULL; // pointer to handles for check and radio button state indicator bitmaps // i.e the checkbox and round radio button. These are created once on start up // and deleted at shutdown. static HBITMAP *hRadioButtons = NULL; static HBITMAP *hCheckButtons = NULL; static HBITMAP hBackground = NULL; static HBITMAP hGoldBackground = NULL; static HBITMAP hListBoxArrow = NULL; //////////////////////////////////////////////////////////////////////////////////////////////////// // Lyra Dialog Manager // Blits bitmap to dc at the co-ord in region //void BlitBitmap(HDC dc, HBITMAP bitmap, RECT *region, const window_pos_t& srcregion, int mask) void BlitBitmap(HDC dc, HBITMAP bitmap, RECT *region, int stretch, int mask) { HGDIOBJ old_object; HDC bitmap_dc; bitmap_dc = CreateCompatibleDC(dc); old_object = SelectObject(bitmap_dc, bitmap); //RECT src; //PrepareSrcRect(&src, region, stretch); BitBlt(dc, region->left, region->top, (region->right - region->left), (region->bottom - region->top), bitmap_dc, 0, 0, mask); //StretchBlt(dc, region->left, region->top, (region->right - region->left), //(region->bottom - region->top), bitmap_dc, //src.left, src.top, (src.right - src.left), (src.bottom - src.top), mask); //0, 0, (src.right - src.left), (src.bottom - src.top), mask); SelectObject(bitmap_dc, old_object); DeleteDC(bitmap_dc); return; } void TransparentBlitBitmap(HDC dc, int bitmap_id, RECT *region, int stretch, int mask) { HBITMAP hBitmap; if (effects->EffectWidth(bitmap_id) == 0 ) return ; effects->LoadEffectBitmaps(bitmap_id, 1); hBitmap = effects->CreateBitmap(bitmap_id); BlitBitmap(dc, hBitmap, region, stretch, mask); DeleteObject(hBitmap); effects->FreeEffectBitmaps(bitmap_id); } HCURSOR __cdecl BitmapToCursor(HBITMAP bmp, HCURSOR cursor) { HDC hDC = GetDC(NULL); HDC hMainDC = CreateCompatibleDC(hDC); HDC hAndMaskDC = CreateCompatibleDC(hDC); HDC hXorMaskDC = CreateCompatibleDC(hDC); HBITMAP cursorandmask = NULL; HBITMAP cursorxormask = NULL; //Get the dimensions of the source bitmap BITMAP bm; GetObject(bmp, sizeof(BITMAP), &bm); cursorandmask = CreateCompatibleBitmap(hDC, bm.bmWidth,bm.bmHeight); cursorxormask = CreateCompatibleBitmap(hDC, bm.bmWidth,bm.bmHeight); //Select the bitmaps to DC HBITMAP hOldMainBitmap = (HBITMAP)::SelectObject(hMainDC, bmp); HBITMAP hOldAndMaskBitmap = (HBITMAP)::SelectObject(hAndMaskDC, cursorandmask); HBITMAP hOldXorMaskBitmap = (HBITMAP)::SelectObject(hXorMaskDC, cursorxormask); //Scan each pixel of the souce bitmap and create the masks COLORREF MainBitPixel; for(int x=0;x<bm.bmWidth;++x) { for(int y=0;y<bm.bmHeight;++y) { MainBitPixel = ::GetPixel(hMainDC,x,y); if(MainBitPixel == 0) { SetPixel(hAndMaskDC,x,y,RGB(255,255,255)); SetPixel(hXorMaskDC,x,y,RGB(0,0,0)); } else { SetPixel(hAndMaskDC,x,y,RGB(0,0,0)); SetPixel(hXorMaskDC,x,y,MainBitPixel); } } } SelectObject(hMainDC,hOldMainBitmap); SelectObject(hAndMaskDC,hOldAndMaskBitmap); SelectObject(hXorMaskDC,hOldXorMaskBitmap); DeleteDC(hXorMaskDC); DeleteDC(hAndMaskDC); DeleteDC(hMainDC); ReleaseDC(NULL,hDC); ICONINFO iconinfo = {0}; iconinfo.fIcon = FALSE; iconinfo.xHotspot = 0; iconinfo.yHotspot = 0; iconinfo.hbmMask = cursorandmask; iconinfo.hbmColor = cursorxormask; cursor = CreateIconIndirect(&iconinfo); return cursor; } // Creates a windows bitmap from an effects bitmap with given bitmap ID HBITMAP CreateWindowsBitmap(int bitmap_id) { HBITMAP hBitmap; if (effects->EffectWidth(bitmap_id) == 0 ) return NULL; effects->LoadEffectBitmaps(bitmap_id, 2); hBitmap = effects->CreateBitmap(bitmap_id); effects->FreeEffectBitmaps(bitmap_id); return hBitmap; } // Creates a windows bitmap, and a grayed version of that,from a game bitmap with given bitmap ID // Bitmap handles are returned in hBitmaps array, normal first, grayed second void CreateWindowsBitmaps(int bitmap_id, HBITMAP hBitmaps[] ) { if (effects->EffectWidth(bitmap_id ) != 0 ) { effects->LoadEffectBitmaps(bitmap_id, 3); int size = effects->EffectWidth(bitmap_id)* effects->EffectHeight(bitmap_id); PIXEL *src = (PIXEL *)effects->EffectBitmap(bitmap_id)->address; // Normal Version hBitmaps[0] = effects->Create16bppBitmapFromBits((unsigned char *)src, effects->EffectWidth(bitmap_id), effects->EffectHeight(bitmap_id)); // Grayed Version PIXEL *buffer = new PIXEL[size]; // Go thru bitmap and create new 'grayed' bitmap for (int i = 0; i < size; i++) { //extract colors int red = (src[i] & 0xF800) >> 11; int green = (src[i] & 0x03E0) >> 5; int blue = (src[i] & 0x001F); // average the colors and set each color to this PIXEL average = ((red+blue+green)/3) & 0x1F; buffer[i] = (average << 11) | (average<< 6) | average; } hBitmaps[1] = effects->Create16bppBitmapFromBits((unsigned char *)buffer, effects->EffectWidth(bitmap_id), effects->EffectHeight(bitmap_id)); delete [] buffer; effects->FreeEffectBitmaps(bitmap_id); } else { hBitmaps[0] = NULL; hBitmaps[1] = NULL; } } // Create Windows bitmaps for a dialog control from effects bitmaps // If the control has more than one state e.g a radio button, then is // assumed there are two effects , one for each state, and that the second effect ID is // one more than the first. const int NUM_CONTROL_BITMAPS = 4; HBITMAP *CreateControlBitmaps( int effect_id, int num_states) { HBITMAP *bitmaps = new HBITMAP [NUM_CONTROL_BITMAPS]; memset(bitmaps,0, sizeof HBITMAP * NUM_CONTROL_BITMAPS); for (int i = 0; i < num_states; i++) CreateWindowsBitmaps(effect_id+i, &bitmaps[i*2]); // if no bitmaps were actually created, return NULL bool success = false; for (int i = 0; i < num_states; i++) if (bitmaps[i] != NULL) success = true; if (!success) { delete bitmaps; bitmaps = NULL; } return bitmaps; } // Deletes bitmaps created above void DeleteControlBitmaps(HBITMAP *bitmaps) { if (!bitmaps) return; for (int i = 0; (i < NUM_CONTROL_BITMAPS); i++) if (bitmaps[i]) DeleteObject(bitmaps[i]); delete bitmaps; } // Resizes a Button Window (Should have been in Windows) void ResizeButton(HWND hWnd, int new_width, int new_height) { RECT r; // determine size of button borders int border_x = GetSystemMetrics(SM_CXBORDER) + GetSystemMetrics(SM_CXEDGE); int border_y = GetSystemMetrics(SM_CYBORDER) + GetSystemMetrics(SM_CYEDGE); GetWindowRect(hWnd,&r); MapWindowPoints(NULL,GetParent(hWnd),LPPOINT(&r),2); MoveWindow(hWnd, r.left, r.top, new_width + border_x, new_height + border_y,0); } // Resizes a Label Window (Should have been in Windows) void ResizeLabel(HWND hWnd, int new_width, int new_height) { RECT r; GetWindowRect(hWnd,&r); MapWindowPoints(NULL,GetParent(hWnd),LPPOINT(&r),2); MoveWindow(hWnd, r.left, r.top, new_width, new_height, 0); } // Callback for push buttons BOOL CALLBACK PushButtonProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { // Extract pointer to handle array of button text HBITMAP *hButtonText = (HBITMAP *)GetWindowLong(hWnd,GWL_USERDATA); switch (Message) { case WM_SETFOCUS: // Ensures that the focus is never on a button case WM_KILLFOCUS: // and that the annoying focus rectangle is not displayed return 0; case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); return 0; case WM_ENABLE: { if ((BOOL)wParam) // If window is being enabled SendMessage(hWnd, BM_SETIMAGE, WPARAM (IMAGE_BITMAP), LPARAM (hButtonText[0])); else SendMessage(hWnd, BM_SETIMAGE, WPARAM (IMAGE_BITMAP), LPARAM (hButtonText[1])); } break; case WM_CAPTURECHANGED: SendMessage(GetParent(hWnd),WM_CAPTURECHANGED, wParam, lParam); // Allows parent to set focus to another window break; case WM_DESTROY: DeleteControlBitmaps(hButtonText); break; } return CallWindowProc(lpfnPushButtonProc,hWnd, Message, wParam, lParam) ; } // Callback for radio and check boxes BOOL CALLBACK StateButtonProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { // Extract pointer to handle array of button text HBITMAP *hButtonText = (HBITMAP *)GetWindowLong(hWnd,GWL_USERDATA); switch (Message) { case WM_DESTROY: { DeleteControlBitmaps(hButtonText); break; } case WM_SETFOCUS: // Ensures that the focus is never on a button case WM_KILLFOCUS: // and that the annoying focus rectangle is not displayed return 0; case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); return 0; case WM_PAINT: if (hButtonText) { HBITMAP *hButtons; // Determine which bitmaps to used based on button's style int style =GetWindowStyle(hWnd); switch (style & 0x000F) // styles are any integer from 0..16 { case BS_AUTORADIOBUTTON: hButtons = hRadioButtons; break; case BS_AUTOCHECKBOX: hButtons = hCheckButtons; break; } if (!IsWindowEnabled(hWnd)) // If window is disabled hButtons+=1; // Use grayed out bitmaps PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); RECT button_rect, text_rect; GetClientRect(hWnd, &button_rect); GetClientRect(hWnd, &text_rect); //Determine size of state indicator bitmap int size; BITMAP bm; GetObject(hButtons[0],sizeof BITMAP, &bm); size = bm.bmWidth; // Determine where button and text go depending on button style if (style & BS_LEFTTEXT) button_rect.left = button_rect.right - size; else text_rect.left += size; // Blit button depending on check state BlitBitmap(dc, hButtons[(Button_GetCheck(hWnd)) ? 0 : 2], &button_rect, NOSTRETCH); // Blit button text if (hButtonText) BlitBitmap(dc, hButtonText[IsWindowEnabled(hWnd)?0:1], &text_rect, NOSTRETCH); EndPaint(hWnd,&Paint); return 0; } else break; case BM_SETCHECK: case BM_SETSTATE: // State of button has changed CallWindowProc(lpfnStateButtonProc,hWnd, Message, wParam, lParam); // Windows paints its own stuff during above call so we MUST repaint InvalidateRect(hWnd,NULL,0); UpdateWindow(hWnd); // Repaint return 0; case WM_CAPTURECHANGED: // Tell parent we no logner have the focuse SendMessage(GetParent(hWnd),WM_CAPTURECHANGED, wParam, lParam); } return CallWindowProc(lpfnStateButtonProc,hWnd, Message, wParam, lParam) ; } // Callback for static text BOOL CALLBACK StaticTextProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { // Extract pointer to handle array of text HBITMAP *hBitmaps = (HBITMAP *)GetWindowLong(hWnd,GWL_USERDATA); switch (Message) { case WM_DESTROY: { DeleteControlBitmaps(hBitmaps); break; } case WM_SETFOCUS: // Ensures that the focus is never on a button case WM_KILLFOCUS: // and that the annoying focus rectangle is not displayed return 0; case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); return 0; case WM_PAINT: if (hBitmaps) { PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); RECT r; GetClientRect(hWnd, &r); if (hBitmaps) BlitBitmap(dc, hBitmaps[IsWindowEnabled(hWnd)?0:1], &r, NOSTRETCH); EndPaint(hWnd,&Paint); return 0; }; // pass on to normal handler if no bitmaps break; } return CallWindowProc(lpfnStaticTextProc,hWnd, Message, wParam, lParam) ; } // returns true if we're dealing with a "special" list box that doesn't // get normal processing below bool IsSpecialListBox(HWND hWnd) { if ((GetDlgCtrlID(hWnd) == IDC_KEY_EFFECT_COMBO) || (GetDlgCtrlID(hWnd) == IDC_GUILDS) || (GetDlgCtrlID(hWnd) == IDC_IGNORE_LIST) || (GetDlgCtrlID(hWnd) == IDC_WATCH_LIST)) return true; else return false; } void DrawListBoxArrow(HWND hWnd, HDC dc, RECT r) //### { HDC bitmap_dc = CreateCompatibleDC(dc); HGDIOBJ old_object = SelectObject(bitmap_dc, hListBoxArrow); BitBlt(dc, r.left, 0, effects->EffectWidth(LyraBitmap::LISTBOX_ARROWS), effects->EffectHeight(LyraBitmap::LISTBOX_ARROWS), bitmap_dc, 0, 0, SRCCOPY); SelectObject(bitmap_dc, old_object); DeleteDC(bitmap_dc); } // Callback for list boxes BOOL CALLBACK ListBoxProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; case WM_KEYDOWN: { PostMessage(GetParent(hWnd), Message, wParam, lParam); int old_sel = ListBox_GetCurSel(hWnd); int sel = old_sel; if (wParam == VK_UP && sel == 0) sel = ListBox_GetCount(hWnd) - 1; else if (wParam == VK_DOWN && sel == (ListBox_GetCount(hWnd) - 1)) sel = 0; if (old_sel != sel) { ListBox_SetCurSel(hWnd, sel); InvalidateRect(hWnd, NULL, TRUE); //..since Windows does its own painting in SetCurSel... PostMessage(GetParent(hWnd), WM_COMMAND, (WPARAM)MAKEWPARAM(GetDlgCtrlID(hWnd), LBN_SELCHANGE), (LPARAM)hWnd); // Windows should send LBN_SELCHANGE out in SetCurSel but does not return 0; } } break; case LB_SETCURSEL: if (IsSpecialListBox(hWnd)) break; InvalidateRect(hWnd, NULL, TRUE); break; case WM_MOUSEMOVE: if (IsSpecialListBox(hWnd)) break; return 0; case WM_SETFOCUS: case WM_KILLFOCUS: if (IsSpecialListBox(hWnd)) break; InvalidateRect(hWnd, NULL, TRUE); InvalidateRect(hWnd, NULL, TRUE); return 0; case WM_LBUTTONDOWN: { if (IsSpecialListBox(hWnd)) break; int x = (int)(short)LOWORD(lParam); int y = (int)(short)HIWORD(lParam); RECT r; GetWindowRect(hWnd, &r); // if within the up/down arrow... if (x >= (r.right - r.left - effects->EffectWidth(LyraBitmap::LISTBOX_ARROWS))) { //generate corrosponding keyboard message if (y < (effects->EffectHeight(LyraBitmap::LISTBOX_ARROWS)/2)) SendMessage(hWnd,WM_KEYDOWN, VK_UP,0); // in up arrow else SendMessage(hWnd,WM_KEYDOWN, VK_DOWN,0); // in down arrow } break; } case WM_PAINT: { // important - do NOT custom paint the keyboard config or // select guild listboxes - they are different! if (IsSpecialListBox(hWnd)) break; TCHAR buffer[DEFAULT_MESSAGE_SIZE]; HFONT pOldFont; PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); SetTextColor(dc, ORANGE); SetBkMode(dc, OPAQUE); SetBkColor(dc, DKBLUE); int curr_selection = ListBox_GetCurSel(hWnd); if (curr_selection != -1) { TEXTMETRIC tm; RECT text_region; pOldFont = (HFONT)SelectObject(dc, display_font[0]); GetTextMetrics(dc, &tm); GetWindowRect(hWnd, &text_region); ListBox_GetText(hWnd, curr_selection, buffer); int clip_width = text_region.right - text_region.left; // EITHER /* int counter = 0; int text_width = 0; int char_width; while (buffer[counter] != '\0') { GetCharWidth(dc, buffer[counter], buffer[counter], &char_width); text_width += char_width; if (text_width + tm.tmAveCharWidth > clip_width) { buffer[counter] = '\0'; break; } counter++; } */ // OR buffer[(int)((clip_width-(4*tm.tmAveCharWidth)) / tm.tmAveCharWidth)]='\0'; TextOut(dc, 0, 0, buffer, _tcslen(buffer)); SelectObject(dc, pOldFont); } RECT r; GetClientRect(hWnd, &r); r.left = r.right - effects->EffectWidth(LyraBitmap::LISTBOX_ARROWS); DrawListBoxArrow(hWnd, dc, r); // ensure the focus rect is painted consistently GetClientRect(hWnd, &r); r.top = 1; r.bottom = effects->EffectHeight(LyraBitmap::LISTBOX_ARROWS) - 1; if (GetFocus() == hWnd) DrawFocusRect(dc, &r); EndPaint(hWnd,&Paint); return 0; }; // pass on to normal handler if no bitmaps break; } return CallWindowProc(lpfnListBoxProc,hWnd, Message, wParam, lParam) ; } // Callback for combo boxes BOOL CALLBACK ComboBoxProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } return CallWindowProc(lpfnComboBoxProc, hWnd, Message, wParam, lParam) ; } // Callback for trackbars BOOL CALLBACK TrackBarProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } return CallWindowProc(lpfnTrackBarProc, hWnd, Message, wParam, lParam) ; } // Callback for all other controls BOOL CALLBACK EditProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: switch (LOWORD(wParam)) { case VK_ESCAPE: case VK_RETURN: PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } case WM_RBUTTONDOWN: return 0; break; } return CallWindowProc(lpfnEditProc, hWnd, Message, wParam, lParam) ; } // Callback for all other controls BOOL CALLBACK GenericProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } return CallWindowProc(lpfnGenericProc, hWnd, Message, wParam, lParam) ; } void ResizeDlg(HWND hDlg) { int w,h; RECT rect; if ((scale_x == 0.0f) || (!ready)) return; // now resize appropriately, based on fonts GetWindowRect(hDlg, &rect); w = rect.right - rect.left; h = rect.bottom - rect.top; MoveWindow(hDlg, rect.left, rect.top, w, h, TRUE); // and resize all child windows appropriately EnumChildWindows(hDlg, EnumChildProcSize, NULL); } // callback to set size of child windows BOOL CALLBACK EnumChildProcSize( HWND hChild, LPARAM lParam ) { int w,h,x,y; RECT rect1, rect2; // now resize appropriately, based on fonts GetWindowRect(GetParent(hChild), &rect1); GetWindowRect(hChild, &rect2); x = rect2.left - rect1.left; y = rect2.top - rect1.top; w = rect2.right - rect2.left; h = rect2.bottom - rect2.top; MoveWindow(hChild, x, y, w, h, TRUE); return TRUE; } // Callback to enumerate through all controls of a dialog and set up // apropriate callbacks and bitmaps BOOL CALLBACK EnumChildProcSetup( HWND hChild, LPARAM lParam ) { TCHAR class_name[30]; int effect_id = GetDlgCtrlID(hChild); SendMessage(hChild, WM_SETFONT, WPARAM(display_font[0]), 0); GetClassName(hChild, class_name, sizeof class_name); if(_tcscmp(class_name, _T("Edit")) && _tcscmp(class_name, _T("ComboBox"))&& _tcscmp(class_name, _T("ListBox")) ) // These controls won't have their TABSTOP style unset, so they can receive the focus // All others cannot receive focus { int style = GetWindowLong(hChild, GWL_STYLE); style &= ~WS_TABSTOP; SetWindowLong(hChild, GWL_STYLE, style); } if (_tcscmp(class_name, _T("Static")) == 0) // if window is a static text control { // bitmaps will be null if this is drawn as text HBITMAP *hBitmaps = CreateControlBitmaps(effect_id,1); SetWindowLong(hChild, GWL_USERDATA, LONG(hBitmaps)); if (hBitmaps) { BITMAP bm; GetObject(hBitmaps[0],sizeof BITMAP, &bm); ResizeButton(hChild,bm.bmWidth,bm.bmHeight); } lpfnStaticTextProc = SubclassWindow(hChild, StaticTextProc); return TRUE; } //if (_tcscmp(class_name, "ComboBox") == 0) //{ // if window is a combo box // lpfnComboBoxProc = SubclassWindow(hChild, ComboBoxProc); // return TRUE; //} if (_tcscmp(class_name, _T("ListBox")) == 0) { lpfnListBoxProc = SubclassWindow(hChild, ListBoxProc); return TRUE; } if (_tcscmp(class_name, _T("ComboBox")) == 0) { // if window is a list box lpfnComboBoxProc = SubclassWindow(hChild, ComboBoxProc); return TRUE; } if (_tcscmp(class_name, _T("msctls_trackbar32")) == 0) { // track bar lpfnTrackBarProc = SubclassWindow(hChild, TrackBarProc); return TRUE; } if (_tcscmp(class_name, _T("Edit")) == 0) { // edit lpfnEditProc = SubclassWindow(hChild, EditProc); return TRUE; } if (_tcscmp(class_name, _T("Button"))) // if window is not a button type { // use generic proc lpfnGenericProc = SubclassWindow(hChild, GenericProc); return TRUE; } int style =GetWindowStyle(hChild); switch (style & 0x000F) // styles are any integer from 0..16 { // window data for radio & checkboxes is the bitmap handle case BS_AUTORADIOBUTTON: case BS_AUTOCHECKBOX: { HBITMAP *hBitmaps = CreateControlBitmaps(effect_id,1); if (hBitmaps) { SetWindowLong(hChild,GWL_USERDATA ,LONG(hBitmaps)); //BITMAP bm; //GetObject(hBitmaps[0], sizeof BITMAP, &bm); //ResizeButton(hChild,bm.bmWidth,bm.bmHeight); } lpfnStateButtonProc = SubclassWindow(hChild, StateButtonProc); } break; case BS_PUSHBUTTON: case BS_DEFPUSHBUTTON: { switch (effect_id) { case IDC_OK: effect_id = LyraBitmap::OK; break; case IDC_CANCEL: effect_id = LyraBitmap::CANCEL; break; } // Use standard IDS for common buttons // window data for buttons is the bitmap handle HBITMAP *hBitmaps = CreateControlBitmaps(effect_id,1); if (hBitmaps) { int style = GetWindowLong(hChild, GWL_STYLE); style |= BS_BITMAP; SetWindowLong(hChild, GWL_STYLE, style); SetWindowLong(hChild, GWL_USERDATA, LONG(hBitmaps)); SendMessage(hChild, BM_SETIMAGE,WPARAM (IMAGE_BITMAP), LPARAM (hBitmaps[0])); BITMAP bm; GetObject(hBitmaps[0], sizeof BITMAP, &bm); ResizeButton(hChild,bm.bmWidth,bm.bmHeight); ResizeButton(hChild,bm.bmWidth,bm.bmHeight); } lpfnPushButtonProc = SubclassWindow(hChild, PushButtonProc); } break; } return TRUE; // Continue enumeration } // Callback for master dialog proc. Sets up child controls,paints background,etc BOOL CALLBACK LyraDialogProc(HWND hDlg, UINT Message, WPARAM wParam, LPARAM lParam) { DLGPROC windowProc; switch(Message) { case WM_INITDIALOG: SetWindowLong(hDlg, GWL_USERDATA, lParam); SendMessage(hDlg, WM_SETFONT, WPARAM(display_font[0]), 0); ResizeDlg(hDlg); EnumChildWindows(hDlg, EnumChildProcSetup, NULL); break; } windowProc = DLGPROC(GetWindowLong(hDlg, GWL_USERDATA)); if (windowProc) return windowProc(hDlg, Message, wParam, lParam); else return 0; } static HWND hCurrentDlg; // modeless version of dlg box proc to call HWND __cdecl CreateLyraDialog( HINSTANCE hInstance, int dialog, HWND hWndParent, DLGPROC lpDialogFunc) { hCurrentDlg = CreateDialogParam(hInstance,MAKEINTRESOURCE(dialog),hWndParent,LyraDialogProc, LPARAM(lpDialogFunc)); cDS->PlaySound(LyraSound::MESSAGE_ALERT); return hCurrentDlg; } bool IsLyraDialogMessage(MSG *msg) { if (msg->message == WM_KEYDOWN && msg->wParam == VK_TAB) // tabs are used to move in dialog return IsDialogMessage(hCurrentDlg, msg); // Seems that Windows checks if hCurrent is valid,returns false if not else return false; } // modal version of dlg box proc to call int __cdecl LyraDialogBox( HINSTANCE hInstance, int dialog, HWND hWndParent, DLGPROC lpDialogFunc) { DLGPROC lpDialogProc = lpDialogFunc; if (cDS) cDS->PlaySound(LyraSound::MESSAGE_ALERT); if (!ready) // use plain dialogs for startup error messages to avoid weird color combinations return DialogBox (hInstance, MAKEINTRESOURCE(dialog), hWndParent, lpDialogFunc); else return DialogBoxParam(hInstance, MAKEINTRESOURCE(dialog), hWndParent, LyraDialogProc, LPARAM(lpDialogFunc)); } // Creates cursor from bitmap in effects.rlm: first creates windows bitmap, creates windows // bitmap mask from this, creates windows cursor from these, and sets the system cursor to this. static void SetupLyraCursor(void) { /* int bitmap_id = LyraBitmap::CURSOR; if (effects->EffectWidth(bitmap_id ) == 0 ) return; effects->LoadEffectBitmaps(bitmap_id); int width = effects->EffectWidth(bitmap_id); int height= effects->EffectHeight(bitmap_id); HBITMAP hCursorBitmap = CreateBitmap(width, height, 1, BITS_PER_PIXEL, effects->EffectBitmap(bitmap_id)->address); // Create cursor mask bitmap from cursor. int size = width*height/8; // its a 1 bit per pixel bitmap UCHAR *maskbits = new UCHAR [size]; UCHAR *dest = maskbits; PIXEL *src = (PIXEL*)effects->EffectBitmap(bitmap_id)->address; memset(maskbits,0,size); for (int i = 0; i < size; i++) { int j = 8; while (j--) if (!*src++) // if the source pixel is black *dest |= 1 << j; // set the mask bit on (which makes black transparent) *dest++ ; } HBITMAP hCursorMask = CreateBitmap(width, height, 1, 1, maskbits); delete [] maskbits; effects->FreeEffectBitmaps(bitmap_id); // Create Windows cursor ICONINFO ii; ii.fIcon = false ; // cursor (false) or icon (true) ii.xHotspot = 0; ii.yHotspot = 0; ii.hbmMask = hCursorMask; ii.hbmColor = hCursorBitmap; HCURSOR hCursor = CreateIconIndirect(&ii); DeleteObject(hCursorMask); // CreateIconIdirect makes copies of these so DeleteObject(hCursorBitmap); // they can be deleted here */ // Set system cursor to Lyra cursor HCURSOR hCursor = LoadCursor(NULL,IDC_ARROW); SetCursor(hCursor); SetSystemCursor(hCursor,OCR_NORMAL ); } // Restores the system cursor by accessing the registry for the previous (software)cursor's filename static void RestoreSystemCursor(void) { HKEY reg_key = NULL; DWORD reg_type; TCHAR cursor_file[DEFAULT_MESSAGE_SIZE] = _T(""); DWORD size = sizeof cursor_file; RegOpenKeyEx(HKEY_CURRENT_USER, _T("Control Panel\\Cursors"),0,KEY_ALL_ACCESS ,&reg_key); if (reg_key) { // Get name of file of the regular arrow cursor RegQueryValueEx(reg_key,_T("Arrow"),NULL,&reg_type, (LPBYTE)cursor_file, &size); // Load cursor and set system cursor to it HCURSOR hCursor; if (_tcslen(cursor_file)) hCursor = LoadCursorFromFile(cursor_file);// software cursor else hCursor = LoadCursor(NULL,IDC_ARROW); // hardware cursor (or registry calls failed) SetSystemCursor(hCursor, OCR_NORMAL); RegCloseKey(reg_key); } } void __cdecl InitLyraDialogController(void) { hRadioButtons = CreateControlBitmaps(LyraBitmap::BULLET,2); hCheckButtons = CreateControlBitmaps(LyraBitmap::CHECK_BUTTON, 2); hBackground = CreateWindowsBitmap(LyraBitmap::DLG_BACKGROUND); hGoldBackground = CreateWindowsBitmap(LyraBitmap::DLG_BACKGROUND2); hListBoxArrow = CreateWindowsBitmap(LyraBitmap::LISTBOX_ARROWS); blueBrush = CreateSolidBrush(DKBLUE); blackBrush = CreateSolidBrush(BLACK); SetupLyraCursor(); } void __cdecl DeInitLyraDialogController(void) { RestoreSystemCursor(); if (hRadioButtons) DeleteControlBitmaps(hRadioButtons); if (hCheckButtons) DeleteControlBitmaps(hCheckButtons); if (hBackground) DeleteObject(hBackground); if (hGoldBackground) DeleteObject(hGoldBackground); if (hListBoxArrow) DeleteObject(hListBoxArrow); if (blueBrush) DeleteObject(blueBrush); if (blackBrush) DeleteObject(blackBrush); } bool TileBackground(HWND hWnd, int which_bitmap) { RECT r; BITMAP bm; GetClientRect(hWnd,&r); int bytes; if (!ready) // no coloration before game starts return false; if (which_bitmap == 0) bytes = GetObject(hBackground,sizeof(BITMAP),&bm); else bytes = GetObject(hGoldBackground,sizeof(BITMAP),&bm); if (!bytes || (&bm == NULL)) return false; PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); SetTextColor(dc, ORANGE); int repeat_x = (r.right/bm.bmWidth) + 1; int repeat_y = (r.bottom/bm.bmHeight) + 1; // Tile background bitmap for (int x= 0; x < repeat_x; x++) for (int y= 0; y < repeat_y; y++) { r.left = x*bm.bmWidth; r.top = y*bm.bmHeight; r.right = r.left + bm.bmWidth; r.bottom = r.top + bm.bmHeight; if (which_bitmap == 0) BlitBitmap(dc,hBackground,&r, NOSTRETCH); else BlitBitmap(dc,hGoldBackground,&r, NOSTRETCH); } EndPaint(hWnd,&Paint); return true; } // sets standard colors for controls; returns true if the message is handled HBRUSH SetControlColors(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam, bool goalposting) { if (!ready) // no coloration before game starts return NULL; TCHAR class_name[30]; switch(Message) { case WM_CTLCOLORSTATIC: // set color of Static controls { GetClassName((HWND)lParam, class_name, sizeof class_name); if (_tcscmp(class_name, _T("msctls_trackbar32")) == 0) { HDC dc = (HDC)wParam; SetTextColor(dc, ORANGE); SetBkMode(dc, OPAQUE); SetBkColor(dc, BLACK); return blackBrush; } else { HDC dc = (HDC)wParam; SetTextColor(dc, ORANGE); if (goalposting) { SetBkMode(dc, OPAQUE); SetBkColor(dc, BLACK); return blackBrush; } else { SetBkMode(dc, TRANSPARENT); return ((HBRUSH)GetStockObject(NULL_BRUSH)); } } } case WM_CTLCOLOREDIT: // set color of edit controls case WM_CTLCOLORLISTBOX: // set color of listbox controls case WM_CTLCOLORBTN: // set color of button controls { HDC dc = (HDC)wParam; SetTextColor(dc, ORANGE); SetBkMode(dc, OPAQUE); if (goalposting) { SetBkColor(dc, BLACK); return blackBrush; } else { SetBkColor(dc, DKBLUE); return blueBrush; } } default: return NULL; } } /* // code for custom painting combo boxes SIZE size; PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); RECT rc, rcTab, rcFocus; // draw border GetClientRect( hWnd, &rc ); Draw3DRect( dc, &rc, lyra_colors[COLOR_HIGHLIGHT], lyra_colors[COLOR_BTNSHADOW] ); DeflateRect( &rc, 2, 2 ); // draw tab rcTab = rc; rcTab.left = rc.right = rcTab.right - GetSystemMetrics( SM_CXHTHUMB ); RECT rcTab2 = rcTab; bool m_dropDown = SendMessage(hWnd, CB_GETDROPPEDSTATE, 0, 0); if( m_dropDown ) { Draw3DRect( dc, &rcTab, lyra_colors[COLOR_HIGHLIGHT], lyra_colors[COLOR_BTNSHADOW] ); rcTab.top++; rcTab.left++; // last param was m_crThumbDn Draw3DRect( dc, &rcTab, lyra_colors[COLOR_BTNSHADOW], lyra_colors[COLOR_3DLIGHT]); DeflateRect( &rcTab, 1, 1 ); // last param was m_crThumbDn HBRUSH thumbDnBrush = CreateSolidBrush(lyra_colors[COLOR_3DLIGHT]); FillRect( dc, &rcTab, thumbDnBrush); DeleteObject(thumbDnBrush); } else { Draw3DRect( dc, &rcTab, lyra_colors[COLOR_HIGHLIGHT], lyra_colors[COLOR_BTNSHADOW] ); DeflateRect( &rcTab, 2, 2 ); rcTab.right++; rcTab.bottom++; // last param was m_crThumbUp HBRUSH thumbUpBrush = CreateSolidBrush(lyra_colors[COLOR_3DLIGHT]); FillRect( dc, &rcTab, thumbUpBrush ); DeleteObject(thumbUpBrush); } rcTab = rcTab2; // draw arrow HPEN darkpen = CreatePen( PS_SOLID, 1, lyra_colors[COLOR_BTNSHADOW] ); HPEN lightpen = CreatePen( PS_SOLID, 1, lyra_colors[COLOR_HIGHLIGHT] ); POINT topleft = {rcTab.left + ( (rcTab.right - rcTab.left) / 3 ) + m_dropDown, rcTab.top + ( (rcTab.bottom - rcTab.top) / 3 ) + m_dropDown }; POINT topright = { rcTab.right - ( (rcTab.right - rcTab.left) / 3 ) + m_dropDown, rcTab.top + ( (rcTab.bottom - rcTab.top) / 3 ) + m_dropDown }; POINT bottom = { rcTab.left + ( (rcTab.right - rcTab.left) / 2 ) + m_dropDown, rcTab.bottom - ( (rcTab.bottom - rcTab.top) / 3 ) + m_dropDown }; HPEN OldPen = (HPEN)SelectObject(dc, lightpen); MoveToEx( dc, topright.x, topright.y, NULL ); LineTo( dc, bottom.x, bottom.y ); SelectObject(dc, darkpen ); LineTo( dc, topleft.x, topleft.y ); LineTo( dc, topright.x, topright.y ); SelectObject(dc, OldPen ); // draw background rc.bottom++; // BOGON - ALIGNMENT FIX HBRUSH bgbrush = CreateSolidBrush(DKBLUE); FrameRect( dc, &rc, bgbrush ); DeflateRect( &rc, 1, 1 ); HBRUSH focbrush = CreateSolidBrush(lyra_colors[COLOR_3DLIGHT]); if( GetFocus() == hWnd ) FillRect( dc, &rc, focbrush ); else FillRect( dc, &rc, bgbrush ) ; DeleteObject(bgbrush); DeleteObject(focbrush); // draw text TCHAR text[64]; HFONT pOldFont; //pOldFont = dc.SelectObject( GetFont() ); SetTextColor(dc, lyra_colors[COLOR_WINDOWTEXT]); SetBkMode( dc, TRANSPARENT ); _tcscpy(text, "W"); GetTextExtentPoint(dc, text, 1, &size); rc.left += size.cx; GetWindowText( hWnd, text, sizeof(text) ); DrawText( dc, text, _tcslen(text), &rc, DT_LEFT|DT_SINGLELINE|DT_VCENTER ); //dc.SelectObject( pOldFont ); EndPaint(hWnd,&Paint); return 0; */ /* // following are functions ripped off from MFC to ease porting of // the combo box drawing code void Draw3DRect(HDC dc, RECT *lpRect, COLORREF clrTopLeft, COLORREF clrBottomRight) { Draw3DRect(dc, lpRect->left, lpRect->top, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, clrTopLeft, clrBottomRight); } void Draw3DRect(HDC dc, int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight) { FillSolidRect(dc, x, y, cx - 1, 1, clrTopLeft); FillSolidRect(dc, x, y, 1, cy - 1, clrTopLeft); FillSolidRect(dc, x + cx, y, -1, cy, clrBottomRight); FillSolidRect(dc, x, y + cy, cx, -1, clrBottomRight); } void FillSolidRect(HDC dc, int x, int y, int cx, int cy, COLORREF clr) { SetBkColor(dc, clr); RECT rect = {x, y, x + cx, y + cy}; ExtTextOut(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); } void DeflateRect(RECT *rect, int x, int y) { rect->left += x; rect->top += y; rect->right -= x; rect->bottom -= y; } */ // Disables options for GM invisible avatars void DisableTalkDialogOptionsForInvisAvatar(HWND hWindow) { LmAvatar tempavatar = player->Avatar(); if (tempavatar.Hidden()) { Button_SetCheck(GetDlgItem(hWindow, IDC_RAW_EMOTE), 1); Button_SetCheck(GetDlgItem(hWindow, IDC_EMOTE), 0); Button_SetCheck(GetDlgItem(hWindow, IDC_TALK), 0); Button_SetCheck(GetDlgItem(hWindow, IDC_SHOUT), 0); ShowWindow(GetDlgItem(hWindow, IDC_TALK), SW_HIDE); ShowWindow(GetDlgItem(hWindow, IDC_SHOUT), SW_HIDE); ShowWindow(GetDlgItem(hWindow, IDC_EMOTE), SW_HIDE); } }
27.172231
147
0.699578
christyganger
d06af26600b503a2b881f5ff5f8e9a08460cf32d
1,452
cpp
C++
examples/multistep/main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
7
2018-01-19T00:19:19.000Z
2021-06-22T00:53:00.000Z
examples/multistep/main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
66
2021-06-22T22:44:21.000Z
2022-03-16T15:18:00.000Z
examples/multistep/main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
6
2017-04-13T19:42:27.000Z
2022-03-26T18:46:24.000Z
// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com> // SPDX-License-Identifier: MIT #include <cstdlib> #include <exception> #include <iostream> #include "multistep2d.hpp" #include "multistep3d.hpp" #include "scheme.hpp" int main(int argc, char* argv[]) { if (argc < 8) { std::cerr << "Usage: multistep <dim> <p> <n> <scheme> <order> <steps> <dt>" << std::endl; std::cerr << "Scheme format: \"s | a(s-1) ... a(0) | b(s) b(s-1) ... b(0) \"" << std::endl; return 0; } auto D = std::atoi(argv[1]); auto p = std::atoi(argv[2]); auto n = std::atoi(argv[3]); auto scheme_name = std::string{argv[4]}; auto order = std::atoi(argv[5]); auto nsteps = std::atoi(argv[6]); auto dt = std::atof(argv[7]); ads::dim_config dim{p, n}; ads::timesteps_config steps{nsteps, dt}; int ders = 1; try { auto scm = ads::get_scheme(scheme_name); // std::cout << "Scheme: " << scm << std::endl; if (D == 2) { ads::config_2d c{dim, dim, steps, ders}; ads::problems::multistep2d sim{c, scm, order}; sim.run(); } else if (D == 3) { ads::config_3d c{dim, dim, dim, steps, ders}; ads::problems::multistep3d sim{c, scm, order}; sim.run(); } } catch (std::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; std::exit(1); } }
30.25
99
0.53168
Pan-Maciek
d06b3400af1c40f7f62a8edba47d77dba695b222
7,281
cpp
C++
Source/DreamPlace/DreamPlaceCharacter.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
Source/DreamPlace/DreamPlaceCharacter.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
Source/DreamPlace/DreamPlaceCharacter.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. #include "DreamPlaceCharacter.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" #include "DreamPlacePlayerState.h" #include "Bullet.h" ////////////////////////////////////////////////////////////////////////// // ADreamPlaceCharacter ADreamPlaceCharacter::ADreamPlaceCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } ////////////////////////////////////////////////////////////////////////// // Input void ADreamPlaceCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &ADreamPlaceCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &ADreamPlaceCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &ADreamPlaceCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &ADreamPlaceCharacter::LookUpAtRate); // Shoot PlayerInputComponent->BindAction("Shoot", IE_Pressed, this, &ADreamPlaceCharacter::Shoot); PlayerInputComponent->BindAction("Shoot", IE_Released, this, &ADreamPlaceCharacter::StopShooting); // Fire PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &ADreamPlaceCharacter::Fire); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &ADreamPlaceCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &ADreamPlaceCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ADreamPlaceCharacter::OnResetVR); } void ADreamPlaceCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void ADreamPlaceCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void ADreamPlaceCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void ADreamPlaceCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void ADreamPlaceCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void ADreamPlaceCharacter::MoveForward(float Value) { if ((Controller != NULL) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void ADreamPlaceCharacter::MoveRight(float Value) { if ( (Controller != NULL) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } } void ADreamPlaceCharacter::Shoot() { IsInShooting = true; } void ADreamPlaceCharacter::StopShooting() { IsInShooting = false; } void ADreamPlaceCharacter::Fire() { if (ProjectileClass) { // Get camera position FVector CharacterLocation; FRotator CharacterRotation; //USkeletalMeshComponent *GunMeshComponent = GetMesh(); //GunMeshComponent->GetSocketWorldLocationAndRotation(TEXT("gun_Socket"), CharacterLocation, CharacterRotation); CharacterLocation = GetActorLocation(); // Adjuct to the gun's location CharacterLocation += FVector(0.0f, 0.0f, 65.0f); CharacterRotation = GetActorRotation(); //GetActorEyesViewPoint(CameraLocation, CameraRotation); // Change muzzle offset from camera space to world space FVector MuzzleLocation = CharacterLocation + FTransform(CharacterRotation).TransformVector(MuzzleOffset); FRotator MuzzleRotation = CharacterRotation; MuzzleRotation.Pitch += 0.0f; UWorld* World = GetWorld(); if (World) { FActorSpawnParameters SpawnParams; SpawnParams.Owner = this; SpawnParams.Instigator = GetInstigator(); // Instigater is private // Generate the bullet ABullet* Bullet = World->SpawnActor<ABullet>(ProjectileClass, MuzzleLocation, MuzzleRotation, SpawnParams); if (Bullet) { // Set bullet's initial direction FVector LaunchDirection = MuzzleRotation.Vector(); Bullet->FireInDirection(LaunchDirection); } } } } void ADreamPlaceCharacter::AddScore() { GetPlayerState()->SetScore(GetPlayerState()->GetScore() + 1); } int ADreamPlaceCharacter::GetScore() { return (int)GetPlayerState()->GetScore(); }
35.691176
180
0.757039
YuanweiZHANG
d06ffe07c97d5c57e68e29c9e2f3be27a088053e
2,327
cpp
C++
android/android_9/hardware/intel/img/hwcomposer/moorefield_hdmi/common/buffers/BufferCache.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
1
2017-09-22T01:41:30.000Z
2017-09-22T01:41:30.000Z
intel/img/hwcomposer/moorefield_hdmi/common/buffers/BufferCache.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
null
null
null
intel/img/hwcomposer/moorefield_hdmi/common/buffers/BufferCache.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
1
2018-02-24T19:09:04.000Z
2018-02-24T19:09:04.000Z
/* // Copyright (c) 2014 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 <common/utils/HwcTrace.h> #include <common/buffers/BufferCache.h> namespace android { namespace intel { BufferCache::BufferCache(int size) { mBufferPool.setCapacity(size); } BufferCache::~BufferCache() { if (mBufferPool.size() != 0) { ELOGTRACE("buffer cache is not empty"); } mBufferPool.clear(); } bool BufferCache::addMapper(uint64_t handle, BufferMapper* mapper) { ssize_t index = mBufferPool.indexOfKey(handle); if (index >= 0) { ELOGTRACE("buffer %#llx exists", handle); return false; } // add mapper index = mBufferPool.add(handle, mapper); if (index < 0) { ELOGTRACE("failed to add mapper. err = %d", index); return false; } return true; } bool BufferCache::removeMapper(BufferMapper* mapper) { ssize_t index; if (!mapper) { ELOGTRACE("invalid mapper"); return false; } index = mBufferPool.removeItem(mapper->getKey()); if (index < 0) { WLOGTRACE("failed to remove mapper. err = %d", index); return false; } return true; } BufferMapper* BufferCache::getMapper(uint64_t handle) { ssize_t index = mBufferPool.indexOfKey(handle); if (index < 0) { // don't add ELOGTRACE here as this condition will happen frequently return 0; } return mBufferPool.valueAt(index); } size_t BufferCache::getCacheSize() const { return mBufferPool.size(); } BufferMapper* BufferCache::getMapper(size_t index) { if (index >= mBufferPool.size()) { ELOGTRACE("invalid index"); return 0; } BufferMapper* mapper = mBufferPool.valueAt(index); return mapper; } } // namespace intel } // namespace android
23.744898
76
0.662656
yakuizhao
d072835d11b23cf20363c92f5d5a2a057f3a7b3c
4,631
cpp
C++
LeapMotion/src/leap/LeapListener.cpp
kondrak/oculusvr_samples
553c2f6f6c1dcf5071aa3c423436d92449eb2038
[ "MIT" ]
64
2015-06-16T18:39:34.000Z
2022-03-22T14:13:23.000Z
LeapMotion/src/leap/LeapListener.cpp
kondrak/oculusvr_samples
553c2f6f6c1dcf5071aa3c423436d92449eb2038
[ "MIT" ]
null
null
null
LeapMotion/src/leap/LeapListener.cpp
kondrak/oculusvr_samples
553c2f6f6c1dcf5071aa3c423436d92449eb2038
[ "MIT" ]
13
2015-07-01T09:20:37.000Z
2020-11-06T17:12:36.000Z
#include "leap/LeapListener.hpp" #include "leap/LeapLogger.hpp" #ifdef _DEBUG #define LEAP_DEBUG_ENABLED #endif void LeapListener::onInit(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Initialized"); } void LeapListener::onConnect(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Device Connected"); // track all the gestures controller.enableGesture(Leap::Gesture::TYPE_CIRCLE); controller.enableGesture(Leap::Gesture::TYPE_KEY_TAP); controller.enableGesture(Leap::Gesture::TYPE_SCREEN_TAP); controller.enableGesture(Leap::Gesture::TYPE_SWIPE); // allow processing images + optimize for HMD controller.setPolicy(static_cast<Leap::Controller::PolicyFlag>(Leap::Controller::POLICY_IMAGES | Leap::Controller::POLICY_OPTIMIZE_HMD)); } void LeapListener::onDisconnect(const Leap::Controller& controller) { // Note: not dispatched when running in a debugger. LOG_MESSAGE("[LeapMotion] Device Disconnected"); } void LeapListener::onExit(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Exited"); } void LeapListener::onFrame(const Leap::Controller& controller) { // Get the most recent frame and report some basic information const Leap::Frame frame = controller.frame(); #ifdef LEAP_DEBUG_ENABLED debugFrameInfo(frame); #endif Leap::HandList hands = frame.hands(); for (Leap::HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) { // Get the first hand const Leap::Hand hand = *hl; // Get the Arm bone Leap::Arm arm = hand.arm(); #ifdef LEAP_DEBUG_ENABLED debugHandInfo(hand); debugArmInfo(arm); #endif // Get fingers const Leap::FingerList fingers = hand.fingers(); for (Leap::FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) { const Leap::Finger finger = *fl; #ifdef LEAP_DEBUG_ENABLED debugFingerInfo(finger); #endif // Get finger bones for (int b = 0; b < 4; ++b) { Leap::Bone::Type boneType = static_cast<Leap::Bone::Type>(b); Leap::Bone bone = finger.bone(boneType); #ifdef LEAP_DEBUG_ENABLED debugBoneInfo(bone, boneType); #endif } } } // Get tools const Leap::ToolList tools = frame.tools(); for (Leap::ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) { const Leap::Tool tool = *tl; #ifdef LEAP_DEBUG_ENABLED debugToolInfo(tool); #endif } // Get gestures const Leap::GestureList gestures = frame.gestures(); for (int g = 0; g < gestures.count(); ++g) { Leap::Gesture gesture = gestures[g]; switch (gesture.type()) { case Leap::Gesture::TYPE_CIRCLE: { Leap::CircleGesture circle = gesture; #ifdef LEAP_DEBUG_ENABLED debugCircleGestureInfo(circle, controller); #endif break; } case Leap::Gesture::TYPE_SWIPE: { Leap::SwipeGesture swipe = gesture; #ifdef LEAP_DEBUG_ENABLED debugSwipeGestureInfo(swipe); #endif break; } case Leap::Gesture::TYPE_KEY_TAP: { Leap::KeyTapGesture tap = gesture; #ifdef LEAP_DEBUG_ENABLED debugKeyTapGestureInfo(tap); #endif break; } case Leap::Gesture::TYPE_SCREEN_TAP: { Leap::ScreenTapGesture screentap = gesture; #ifdef LEAP_DEBUG_ENABLED debugScreenTapGestureInfo(screentap); #endif break; } default: LOG_MESSAGE_ASSERT(false, "Unknown gesture type."); break; } } } void LeapListener::onFocusGained(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Focus Gained"); } void LeapListener::onFocusLost(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Focus Lost"); } void LeapListener::onDeviceChange(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Device Changed"); const Leap::DeviceList devices = controller.devices(); for (int i = 0; i < devices.count(); ++i) { #ifdef LEAP_DEBUG_ENABLED debugDeviceInfo(devices[i]); #endif } } void LeapListener::onServiceConnect(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Service Connected"); } void LeapListener::onServiceDisconnect(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Service Disconnected"); }
26.3125
141
0.635932
kondrak
d072ddb0cb8f3cc8a41af4c90db3edac8f827734
549
cpp
C++
test/src/gl/GLDemo.cpp
tjakway/pyramid-scheme-simulator
4de02ac120b39185342f433999c2d360a7ccbf7e
[ "MIT" ]
null
null
null
test/src/gl/GLDemo.cpp
tjakway/pyramid-scheme-simulator
4de02ac120b39185342f433999c2d360a7ccbf7e
[ "MIT" ]
null
null
null
test/src/gl/GLDemo.cpp
tjakway/pyramid-scheme-simulator
4de02ac120b39185342f433999c2d360a7ccbf7e
[ "MIT" ]
null
null
null
#include "gl/GLBackend.hpp" #include "PopulationGraph.hpp" #include "TestConfig.hpp" #include "BasicGraphSetup.hpp" namespace pyramid_scheme_simulator { TEST_F(BasicGraphSetup, gldemo) { gl::GLBackend backend( Config::Defaults::defaultGraphLayoutOptions, Config::Defaults::defaultWindowOptions); backend.exportData( std::make_shared<Simulation::Backend::Data>( std::shared_ptr<PopulationGraph>(tinyGraph->clone()), 0, nullptr, nullptr, nullptr)); backend.join(); } }
22.875
69
0.672131
tjakway
d0736005758779572892e66bf354b1819ccd9fcb
3,319
cpp
C++
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Machine_Learning/K_Nearest_Neighbours/K_Nearest_Neighbors.cpp
rajatenzyme/Coding-Journey-
65a0570153b7e3393d78352e78fb2111223049f3
[ "MIT" ]
null
null
null
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Machine_Learning/K_Nearest_Neighbours/K_Nearest_Neighbors.cpp
rajatenzyme/Coding-Journey-
65a0570153b7e3393d78352e78fb2111223049f3
[ "MIT" ]
null
null
null
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Machine_Learning/K_Nearest_Neighbours/K_Nearest_Neighbors.cpp
rajatenzyme/Coding-Journey-
65a0570153b7e3393d78352e78fb2111223049f3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct point { float w, x, y, z; // w, x, y and z are the values of the dataset float distance; // distance will store the distance of dataset point from the unknown test point int op; // op will store the class of the point }; int main() { int i, j, n, k; struct point p; struct point temp; cout << "Number of data points: "; cin >> n; struct point arr[n]; cout << "\nEnter the dataset values: \n"; cout << "w\tx\ty\tz\top\n"; // Taking dataset for (i = 0; i < n; i++) { cin >> arr[i].w >> arr[i].x >> arr[i].y >> arr[i].z >> arr[i].op; } cout << "\nw\tx\ty\tz\top\n"; for (i = 0; i < n; i++) { cout << fixed << setprecision(2) << arr[i].w << '\t' << arr[i].x << '\t' << arr[i].y << '\t' << arr[i].z << '\t' << arr[i].op << '\n'; } cout << "\nEnter the feature values of the unknown point: \nw\tx\ty\tz\n"; cin >> p.w >> p.x >> p.y >> p.z; // Measuring the Euclidean distance for (i = 0; i < n; i++) { arr[i].distance = sqrt(((arr[i].w - p.w) * (arr[i].w - p.w)) + ((arr[i].x - p.x) * (arr[i].x - p.x)) + ((arr[i].y - p.y) * (arr[i].y - p.y)) + ((arr[i].z - p.z) * (arr[i].z - p.z))); } // Sorting the training data with respect to distance for (i = 1; i < n; i++) { for (j = 0; j < n - i; j++) { if (arr[j].distance > arr[j + 1].distance) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } cout << "\nw\tx\ty\tz\top\tdistance\n"; for (i = 0; i < n; i++) { cout << fixed << setprecision(2) << arr[i].w << '\t' << arr[i].x << '\t' << arr[i].y << '\t' << arr[i].z << '\t' << arr[i].op << '\t' << arr[i].distance << '\n'; } // Taking the K nearest neighbors cout << "\nNumber of nearest neighbors(k): "; cin >> k; int freq[1000] = {0}; int index = 0, maxfreq = 0; // Creating frequency array of the class of k nearest neighbors for (int i = 0; i < k; i++) { freq[arr[i].op]++; } // Finding the most frequent occurring class for (int i = 0; i < 1000; i++) { if(freq[i] > maxfreq) { maxfreq = freq[i]; index = i; } } cout << "The class of unknown point is " << index; return 0; } // Sample Output /* Number of data points: 5 Enter the dataset values: w x y z op 1 2 3 4 5 10 20 30 40 50 5 2 40 7 10 40 30 100 28 3 20 57 98 46 8 w x y z op 1.00 2.00 3.00 4.00 5 10.00 20.00 30.00 40.00 50 5.00 2.00 40.00 7.00 10 40.00 30.00 100.00 28.00 3 20.00 57.00 98.00 46.00 8 Enter the feature values of the unknown point: w x y z 40 30 80 30 w x y z op distance 40.00 30.00 100.00 28.00 3 20.10 20.00 57.00 98.00 46.00 8 41.34 10.00 20.00 30.00 40.00 50 60.00 5.00 2.00 40.00 7.00 10 64.33 1.00 2.00 3.00 4.00 5 94.39 Number of nearest neighbors(k): 3 The class of unknown point is 3 */
29.633929
190
0.456764
rajatenzyme
d07561bdbc2874279e756285f36484c58f2a3b15
5,198
cpp
C++
dev/Code/CryEngine/CrySystem/MissingFileReport.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Code/CryEngine/CrySystem/MissingFileReport.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Code/CryEngine/CrySystem/MissingFileReport.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "StdAfx.h" #include "MissingFileReport.h" #include <AzCore/Asset/AssetManagerBus.h> #include <AzFramework/Asset/AssetCatalogBus.h> #include <AzFramework/FileTag/FileTag.h> #include <AzFramework/FileTag/FileTagBus.h> #include <AzFramework/Logging/MissingAssetNotificationBus.h> #include <AzFramework/StringFunc/StringFunc.h> namespace CryPakInternal { void ReportFileMissingFromPak(const char *szPath, SSystemCVars cvars) { if (!cvars.sys_report_files_not_found_in_paks) { return; } if (IsIgnored(szPath)) { return; } AzFramework::MissingAssetNotificationBus::Broadcast(&AzFramework::MissingAssetNotificationBus::Events::FileMissing, szPath); const int LogMissingFileAccess = 1; const int WarnMissingFileAccess = 2; AZStd::string missingMessage(AZStd::string::format("Missing from bundle: %s", szPath)); switch (cvars.sys_report_files_not_found_in_paks) { case LogMissingFileAccess: AZ_TracePrintf("CryPak", missingMessage.c_str()); break; case WarnMissingFileAccess: AZ_Warning("CryPak", false, missingMessage.c_str()); break; default: AZ_Error("CryPak", false, missingMessage.c_str()); break; } } bool IsIgnored(const char *szPath) { if (IgnoreCGFDependencies(szPath)) { return true; } using namespace AzFramework::FileTag; AZStd::vector<AZStd::string> tags{ FileTags[static_cast<unsigned int>(FileTagsIndex::Ignore)], FileTags[static_cast<unsigned int>(FileTagsIndex::ProductDependency)] }; bool shouldIgnore = false; QueryFileTagsEventBus::EventResult(shouldIgnore, FileTagType::BlackList, &QueryFileTagsEventBus::Events::Match, szPath, tags); return shouldIgnore; } // This is a quick and simple solution to handle .cgfm and LOD files // We only report them as missing files if they are created by // Resource Compiler during the process for source CGF assets // A better solution could be to load only valid files that are actually needed bool IgnoreCGFDependencies(const char *szPath) { if (AzFramework::StringFunc::Path::IsExtension(szPath, "cgfm")) { // Ignore all the .cgfm files return true; } AZStd::smatch matches; const AZStd::regex lodRegex("@assets@\\\\(.*)_lod[0-9]+(\\.cgfm?)"); if (!AZStd::regex_match(szPath, matches, lodRegex) || matches.size() != 3) { // The current file is not a valid LOD file return false; } AZStd::string nonLodFileName = matches.str(1) + matches.str(2); AZ::Data::AssetId nonLodFileId; AZ::Data::AssetCatalogRequestBus::BroadcastResult( nonLodFileId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, nonLodFileName.c_str(), AZ::Data::s_invalidAssetType, false); if (!nonLodFileId.IsValid()) { // The current LOD file is not generated from a valid CGF file return false; } AZ::Outcome<AZStd::vector<AZ::Data::ProductDependency>, AZStd::string> result = AZ::Failure<AZStd::string>("No response"); AZ::Data::AssetCatalogRequestBus::BroadcastResult(result, &AZ::Data::AssetCatalogRequestBus::Events::GetDirectProductDependencies, nonLodFileId); if (!result.IsSuccess()) { return false; } AZStd::vector<AZ::Data::ProductDependency> dependencies = result.TakeValue(); for (const AZ::Data::ProductDependency& dependency : dependencies) { AZ::Data::AssetInfo assetInfo; AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, dependency.m_assetId); if (assetInfo.m_assetType == AZ::Data::s_invalidAssetType) { // This dependency has unresolved path. Cannot compare it with the current LOD file. continue; } AZStd::string dependencyRelativePath = assetInfo.m_relativePath; AZStd::replace(dependencyRelativePath.begin(), dependencyRelativePath.end(), AZ_WRONG_FILESYSTEM_SEPARATOR, AZ_CORRECT_FILESYSTEM_SEPARATOR); if (strstr(szPath, dependencyRelativePath.c_str())) { // The current LOD file is a product dependency of the source CGF file return false; } } return true; } }
39.378788
156
0.649288
jeikabu
d0757df2d5eb7c106e301451dafe2f006825c5e5
16,881
cpp
C++
src/core/FlamePart/SlidePartition.cpp
jeffhammond/Elemental
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
[ "Apache-2.0" ]
null
null
null
src/core/FlamePart/SlidePartition.cpp
jeffhammond/Elemental
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
[ "Apache-2.0" ]
null
null
null
src/core/FlamePart/SlidePartition.cpp
jeffhammond/Elemental
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2009-2016, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include <El-lite.hpp> namespace El { // Slide a partition upward // ======================== template<typename T> void SlidePartitionUp ( Matrix<T>& AT, Matrix<T>& A0, Matrix<T>& A1, Matrix<T>& AB, Matrix<T>& A2 ) { DEBUG_CSE View( AT, A0 ); Merge2x1( AB, A1, A2 ); } template<typename T> void SlidePartitionUp ( ElementalMatrix<T>& AT, ElementalMatrix<T>& A0, ElementalMatrix<T>& A1, ElementalMatrix<T>& AB, ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AT, AB, A0, A1, A2 ); AssertSameDists( AT, AB, A0, A1, A2 ); ) View( AT, A0 ); Merge2x1( AB, A1, A2 ); } template<typename T> void SlideLockedPartitionUp ( Matrix<T>& AT, const Matrix<T>& A0, const Matrix<T>& A1, Matrix<T>& AB, const Matrix<T>& A2 ) { DEBUG_CSE LockedView( AT, A0 ); LockedMerge2x1( AB, A1, A2 ); } template<typename T> void SlideLockedPartitionUp ( ElementalMatrix<T>& AT, const ElementalMatrix<T>& A0, const ElementalMatrix<T>& A1, ElementalMatrix<T>& AB, const ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AT, AB, A0, A1, A2 ); AssertSameDists( AT, AB, A0, A1, A2 ); ) LockedView( AT, A0 ); LockedMerge2x1( AB, A1, A2 ); } // Slide a partition downward // ========================== template<typename T> void SlidePartitionDown ( Matrix<T>& AT, Matrix<T>& A0, Matrix<T>& A1, Matrix<T>& AB, Matrix<T>& A2 ) { DEBUG_CSE Merge2x1( AT, A0, A1 ); View( AB, A2 ); } template<typename T> void SlidePartitionDown ( ElementalMatrix<T>& AT, ElementalMatrix<T>& A0, ElementalMatrix<T>& A1, ElementalMatrix<T>& AB, ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AT, AB, A0, A1, A2 ); AssertSameDists( AT, AB, A0, A1, A2 ); ) Merge2x1( AT, A0, A1 ); View( AB, A2 ); } template<typename T> void SlideLockedPartitionDown ( Matrix<T>& AT, const Matrix<T>& A0, const Matrix<T>& A1, Matrix<T>& AB, const Matrix<T>& A2 ) { DEBUG_CSE LockedMerge2x1( AT, A0, A1 ); LockedView( AB, A2 ); } template<typename T> void SlideLockedPartitionDown ( ElementalMatrix<T>& AT, const ElementalMatrix<T>& A0, const ElementalMatrix<T>& A1, ElementalMatrix<T>& AB, const ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AT, AB, A0, A1, A2 ); AssertSameDists( AT, AB, A0, A1, A2 ); ) LockedMerge2x1( AT, A0, A1 ); LockedView( AB, A2 ); } // Slide a partition leftward // ========================== template<typename T> void SlidePartitionLeft ( Matrix<T>& AL, Matrix<T>& AR, Matrix<T>& A0, Matrix<T>& A1, Matrix<T>& A2 ) { DEBUG_CSE View( AL, A0 ); Merge1x2( AR, A1, A2 ); } template<typename T> void SlidePartitionLeft ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, ElementalMatrix<T>& A0, ElementalMatrix<T>& A1, ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AL, AR, A0, A1, A2 ); AssertSameDists( AL, AR, A0, A1, A2 ); ) View( AL, A0 ); Merge1x2( AR, A1, A2 ); } template<typename T> void SlideLockedPartitionLeft ( Matrix<T>& AL, Matrix<T>& AR, const Matrix<T>& A0, const Matrix<T>& A1, const Matrix<T>& A2 ) { DEBUG_CSE LockedView( AL, A0 ); LockedMerge1x2( AR, A1, A2 ); } template<typename T> void SlideLockedPartitionLeft ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, const ElementalMatrix<T>& A0, const ElementalMatrix<T>& A1, const ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AL, AR, A0, A1, A2 ); AssertSameDists( AL, AR, A0, A1, A2 ); ) LockedView( AL, A0 ); LockedMerge1x2( AR, A1, A2 ); } // Slide a partition rightward // =========================== template<typename T> void SlidePartitionRight ( Matrix<T>& AL, Matrix<T>& AR, Matrix<T>& A0, Matrix<T>& A1, Matrix<T>& A2 ) { DEBUG_CSE Merge1x2( AL, A0, A1 ); View( AR, A2 ); } template<typename T> void SlidePartitionRight ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, ElementalMatrix<T>& A0, ElementalMatrix<T>& A1, ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AL, AR, A0, A1, A2 ); AssertSameDists( AL, AR, A0, A1, A2 ); ) Merge1x2( AL, A0, A1 ); View( AR, A2 ); } template<typename T> void SlideLockedPartitionRight ( Matrix<T>& AL, Matrix<T>& AR, const Matrix<T>& A0, const Matrix<T>& A1, const Matrix<T>& A2 ) { DEBUG_CSE LockedMerge1x2( AL, A0, A1 ); LockedView( AR, A2 ); } template<typename T> void SlideLockedPartitionRight ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, const ElementalMatrix<T>& A0, const ElementalMatrix<T>& A1, const ElementalMatrix<T>& A2 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids( AL, AR, A0, A1, A2 ); AssertSameDists( AL, AR, A0, A1, A2 ); ) LockedMerge1x2( AL, A0, A1 ); LockedView( AR, A2 ); } // Slide a partition upward on a diagonal // ====================================== template<typename T> void SlidePartitionUpDiagonal ( Matrix<T>& ATL, Matrix<T>& ATR, Matrix<T>& A00, Matrix<T>& A01, Matrix<T>& A02, Matrix<T>& A10, Matrix<T>& A11, Matrix<T>& A12, Matrix<T>& ABL, Matrix<T>& ABR, Matrix<T>& A20, Matrix<T>& A21, Matrix<T>& A22 ) { DEBUG_CSE View( ATL, A00 ); Merge1x2( ATR, A01, A02 ); Merge2x1( ABL, A10, A20 ); Merge2x2( ABR, A11, A12, A21, A22 ); } template<typename T> void SlidePartitionUpDiagonal ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, ElementalMatrix<T>& A00, ElementalMatrix<T>& A01, ElementalMatrix<T>& A02, ElementalMatrix<T>& A10, ElementalMatrix<T>& A11, ElementalMatrix<T>& A12, ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, ElementalMatrix<T>& A20, ElementalMatrix<T>& A21, ElementalMatrix<T>& A22 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); AssertSameDists ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); ) View( ATL, A00 ); Merge1x2( ATR, A01, A02 ); Merge2x1( ABL, A10, A20 ); Merge2x2( ABR, A11, A12, A21, A22 ); } template<typename T> void SlideLockedPartitionUpDiagonal ( Matrix<T>& ATL, Matrix<T>& ATR, const Matrix<T>& A00, const Matrix<T>& A01, const Matrix<T>& A02, const Matrix<T>& A10, const Matrix<T>& A11, const Matrix<T>& A12, Matrix<T>& ABL, Matrix<T>& ABR, const Matrix<T>& A20, const Matrix<T>& A21, const Matrix<T>& A22 ) { DEBUG_CSE LockedView( ATL, A00 ); LockedMerge1x2( ATR, A01, A02 ); LockedMerge2x1( ABL, A10, A20 ); LockedMerge2x2( ABR, A11, A12, A21, A22 ); } template<typename T> void SlideLockedPartitionUpDiagonal ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, const ElementalMatrix<T>& A00, const ElementalMatrix<T>& A01, const ElementalMatrix<T>& A02, const ElementalMatrix<T>& A10, const ElementalMatrix<T>& A11, const ElementalMatrix<T>& A12, ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, const ElementalMatrix<T>& A20, const ElementalMatrix<T>& A21, const ElementalMatrix<T>& A22 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); AssertSameDists ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); ) LockedView( ATL, A00 ); LockedMerge1x2( ATR, A01, A02 ); LockedMerge2x1( ABL, A10, A20 ); LockedMerge2x2( ABR, A11, A12, A21, A22 ); } // Slide a partition downward on a diagonal // ======================================== template<typename T> void SlidePartitionDownDiagonal ( Matrix<T>& ATL, Matrix<T>& ATR, Matrix<T>& A00, Matrix<T>& A01, Matrix<T>& A02, Matrix<T>& A10, Matrix<T>& A11, Matrix<T>& A12, Matrix<T>& ABL, Matrix<T>& ABR, Matrix<T>& A20, Matrix<T>& A21, Matrix<T>& A22 ) { DEBUG_CSE Merge2x2( ATL, A00, A01, A10, A11 ); Merge2x1( ATR, A02, A12 ); Merge1x2( ABL, A20, A21 ); View( ABR, A22 ); } template<typename T> void SlidePartitionDownDiagonal ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, ElementalMatrix<T>& A00, ElementalMatrix<T>& A01, ElementalMatrix<T>& A02, ElementalMatrix<T>& A10, ElementalMatrix<T>& A11, ElementalMatrix<T>& A12, ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, ElementalMatrix<T>& A20, ElementalMatrix<T>& A21, ElementalMatrix<T>& A22 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); AssertSameDists ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); ) Merge2x2( ATL, A00, A01, A10, A11 ); Merge2x1( ATR, A02, A12 ); Merge1x2( ABL, A20, A21 ); View( ABR, A22 ); } template<typename T> void SlideLockedPartitionDownDiagonal ( Matrix<T>& ATL, Matrix<T>& ATR, const Matrix<T>& A00, const Matrix<T>& A01, const Matrix<T>& A02, const Matrix<T>& A10, const Matrix<T>& A11, const Matrix<T>& A12, Matrix<T>& ABL, Matrix<T>& ABR, const Matrix<T>& A20, const Matrix<T>& A21, const Matrix<T>& A22 ) { DEBUG_CSE LockedMerge2x2( ATL, A00, A01, A10, A11 ); LockedMerge2x1( ATR, A02, A12 ); LockedMerge1x2( ABL, A20, A21 ); LockedView( ABR, A22 ); } template<typename T> void SlideLockedPartitionDownDiagonal ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, const ElementalMatrix<T>& A00, const ElementalMatrix<T>& A01, const ElementalMatrix<T>& A02, const ElementalMatrix<T>& A10, const ElementalMatrix<T>& A11, const ElementalMatrix<T>& A12, ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, const ElementalMatrix<T>& A20, const ElementalMatrix<T>& A21, const ElementalMatrix<T>& A22 ) { DEBUG_CSE DEBUG_ONLY( AssertSameGrids ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); AssertSameDists ( ATL, ATR, ABL, ABR, A00, A01, A02, A10, A11, A12, A20, A21, A22 ); ) LockedMerge2x2( ATL, A00, A01, A10, A11 ); LockedMerge2x1( ATR, A02, A12 ); LockedMerge1x2( ABL, A20, A21 ); LockedView( ABR, A22 ); } #define PROTO(T) \ /* Downward */ \ template void SlidePartitionDown \ ( Matrix<T>& AT, Matrix<T>& A0, \ Matrix<T>& A1, \ Matrix<T>& AB, Matrix<T>& A2 ); \ template void SlidePartitionDown \ ( ElementalMatrix<T>& AT, ElementalMatrix<T>& A0, \ ElementalMatrix<T>& A1, \ ElementalMatrix<T>& AB, ElementalMatrix<T>& A2 ); \ template void SlideLockedPartitionDown \ ( Matrix<T>& AT, const Matrix<T>& A0, \ const Matrix<T>& A1, \ Matrix<T>& AB, const Matrix<T>& A2 ); \ template void SlideLockedPartitionDown \ ( ElementalMatrix<T>& AT, const ElementalMatrix<T>& A0, \ const ElementalMatrix<T>& A1, \ ElementalMatrix<T>& AB, const ElementalMatrix<T>& A2 ); \ /* Upward */ \ template void SlidePartitionUp \ ( Matrix<T>& AT, Matrix<T>& A0, \ Matrix<T>& A1, \ Matrix<T>& AB, Matrix<T>& A2 ); \ template void SlidePartitionUp \ ( ElementalMatrix<T>& AT, ElementalMatrix<T>& A0, \ ElementalMatrix<T>& A1, \ ElementalMatrix<T>& AB, ElementalMatrix<T>& A2 ); \ template void SlideLockedPartitionUp \ ( Matrix<T>& AT, const Matrix<T>& A0, \ const Matrix<T>& A1, \ Matrix<T>& AB, const Matrix<T>& A2 ); \ template void SlideLockedPartitionUp \ ( ElementalMatrix<T>& AT, const ElementalMatrix<T>& A0, \ const ElementalMatrix<T>& A1, \ ElementalMatrix<T>& AB, const ElementalMatrix<T>& A2 ); \ /* Right */ \ template void SlidePartitionRight \ ( Matrix<T>& AL, Matrix<T>& AR, \ Matrix<T>& A0, Matrix<T>& A1, Matrix<T>& A2 ); \ template void SlidePartitionRight \ ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, \ ElementalMatrix<T>& A0, ElementalMatrix<T>& A1, ElementalMatrix<T>& A2 ); \ template void SlideLockedPartitionRight \ ( Matrix<T>& AL, Matrix<T>& AR, \ const Matrix<T>& A0, const Matrix<T>& A1, const Matrix<T>& A2 ); \ template void SlideLockedPartitionRight \ ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, \ const ElementalMatrix<T>& A0, const ElementalMatrix<T>& A1, const ElementalMatrix<T>& A2 ); \ /* Left */ \ template void SlidePartitionLeft \ ( Matrix<T>& AL, Matrix<T>& AR, \ Matrix<T>& A0, Matrix<T>& A1, Matrix<T>& A2 ); \ template void SlidePartitionLeft \ ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, \ ElementalMatrix<T>& A0, ElementalMatrix<T>& A1, ElementalMatrix<T>& A2 ); \ template void SlideLockedPartitionLeft \ ( Matrix<T>& AL, Matrix<T>& AR, \ const Matrix<T>& A0, const Matrix<T>& A1, const Matrix<T>& A2 ); \ template void SlideLockedPartitionLeft \ ( ElementalMatrix<T>& AL, ElementalMatrix<T>& AR, \ const ElementalMatrix<T>& A0, const ElementalMatrix<T>& A1, const ElementalMatrix<T>& A2 ); \ /* Down diagonal */ \ template void SlidePartitionDownDiagonal \ ( Matrix<T>& ATL, Matrix<T>& ATR, \ Matrix<T>& A00, Matrix<T>& A01, Matrix<T>& A02, \ Matrix<T>& A10, Matrix<T>& A11, Matrix<T>& A12, \ Matrix<T>& ABL, Matrix<T>& ABR, \ Matrix<T>& A20, Matrix<T>& A21, Matrix<T>& A22 ); \ template void SlidePartitionDownDiagonal \ ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, \ ElementalMatrix<T>& A00, ElementalMatrix<T>& A01, ElementalMatrix<T>& A02, \ ElementalMatrix<T>& A10, ElementalMatrix<T>& A11, ElementalMatrix<T>& A12, \ ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, \ ElementalMatrix<T>& A20, ElementalMatrix<T>& A21, ElementalMatrix<T>& A22 ); \ template void SlideLockedPartitionDownDiagonal \ ( Matrix<T>& ATL, Matrix<T>& ATR, \ const Matrix<T>& A00, const Matrix<T>& A01, const Matrix<T>& A02, \ const Matrix<T>& A10, const Matrix<T>& A11, const Matrix<T>& A12, \ Matrix<T>& ABL, Matrix<T>& ABR, \ const Matrix<T>& A20, const Matrix<T>& A21, const Matrix<T>& A22 ); \ template void SlideLockedPartitionDownDiagonal \ ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, \ const ElementalMatrix<T>& A00, const ElementalMatrix<T>& A01, const ElementalMatrix<T>& A02, \ const ElementalMatrix<T>& A10, const ElementalMatrix<T>& A11, const ElementalMatrix<T>& A12, \ ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, \ const ElementalMatrix<T>& A20, const ElementalMatrix<T>& A21, const ElementalMatrix<T>& A22 ); \ /* Up diagonal */ \ template void SlidePartitionUpDiagonal \ ( Matrix<T>& ATL, Matrix<T>& ATR, \ Matrix<T>& A00, Matrix<T>& A01, Matrix<T>& A02, \ Matrix<T>& A10, Matrix<T>& A11, Matrix<T>& A12, \ Matrix<T>& ABL, Matrix<T>& ABR, \ Matrix<T>& A20, Matrix<T>& A21, Matrix<T>& A22 ); \ template void SlidePartitionUpDiagonal \ ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, \ ElementalMatrix<T>& A00, ElementalMatrix<T>& A01, ElementalMatrix<T>& A02, \ ElementalMatrix<T>& A10, ElementalMatrix<T>& A11, ElementalMatrix<T>& A12, \ ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, \ ElementalMatrix<T>& A20, ElementalMatrix<T>& A21, ElementalMatrix<T>& A22 ); \ template void SlideLockedPartitionUpDiagonal \ ( Matrix<T>& ATL, Matrix<T>& ATR, \ const Matrix<T>& A00, const Matrix<T>& A01, const Matrix<T>& A02, \ const Matrix<T>& A10, const Matrix<T>& A11, const Matrix<T>& A12, \ Matrix<T>& ABL, Matrix<T>& ABR, \ const Matrix<T>& A20, const Matrix<T>& A21, const Matrix<T>& A22 ); \ template void SlideLockedPartitionUpDiagonal \ ( ElementalMatrix<T>& ATL, ElementalMatrix<T>& ATR, \ const ElementalMatrix<T>& A00, const ElementalMatrix<T>& A01, const ElementalMatrix<T>& A02, \ const ElementalMatrix<T>& A10, const ElementalMatrix<T>& A11, const ElementalMatrix<T>& A12, \ ElementalMatrix<T>& ABL, ElementalMatrix<T>& ABR, \ const ElementalMatrix<T>& A20, const ElementalMatrix<T>& A21, const ElementalMatrix<T>& A22 ); #define EL_ENABLE_DOUBLEDOUBLE #define EL_ENABLE_QUADDOUBLE #define EL_ENABLE_QUAD #define EL_ENABLE_BIGINT #define EL_ENABLE_BIGFLOAT #include <El/macros/Instantiate.h> } // namespace El
32.154286
100
0.622949
jeffhammond
d07a4198198787828a7b5b9c0a702f82fb336dbf
8,746
cpp
C++
src/Network/msgitem.cpp
COPS-Projects/COPS-v7-Emulator
ccf377023b0399dc55675577c713ca7440000a80
[ "BSD-2-Clause" ]
2
2019-02-09T20:55:32.000Z
2021-08-12T12:15:03.000Z
src/Network/msgitem.cpp
COPS-Projects/COPS-v7-Emulator
ccf377023b0399dc55675577c713ca7440000a80
[ "BSD-2-Clause" ]
null
null
null
src/Network/msgitem.cpp
COPS-Projects/COPS-v7-Emulator
ccf377023b0399dc55675577c713ca7440000a80
[ "BSD-2-Clause" ]
5
2016-06-27T04:17:38.000Z
2021-08-12T12:15:04.000Z
/** * ****** COPS v7 Emulator - Open Source ****** * Copyright (C) 2012 - 2014 Jean-Philippe Boivin * * Please read the WARNING, DISCLAIMER and PATENTS * sections in the LICENSE file. */ #include "msgitem.h" #include "client.h" #include "entity.h" #include "player.h" #include "npc.h" #include "item.h" #include "gamemap.h" #include "world.h" #include "database.h" #include "msgiteminfo.h" #include <algorithm> // max using namespace std; MsgItem :: MsgItem(uint32_t aUID, Action aAction) : Msg(sizeof(MsgInfo)), mInfo((MsgInfo*)mBuf) { create(aUID, 0, 0, aAction); } MsgItem :: MsgItem(uint32_t aUID, uint32_t aData, Action aAction) : Msg(sizeof(MsgInfo)), mInfo((MsgInfo*)mBuf) { create(aUID, aData, 0, aAction); } MsgItem :: MsgItem(uint8_t** aBuf, size_t aLen) : Msg(aBuf, aLen), mInfo((MsgInfo*)mBuf) { ASSERT(aLen >= sizeof(MsgInfo)); #if BYTE_ORDER == BIG_ENDIAN swap(mBuf); #endif } MsgItem :: ~MsgItem() { } void MsgItem :: create(uint32_t aUID, uint32_t aData, uint32_t aTargetUID, Action aAction) { mInfo->Header.Length = mLen; mInfo->Header.Type = MSG_ITEM; mInfo->UniqId = aUID; mInfo->Data = aData; mInfo->Action = (uint16_t)aAction; mInfo->Timestamp = timeGetTime(); mInfo->TargetUID = aTargetUID; } void MsgItem :: process(Client* aClient) { ASSERT(aClient != nullptr); ASSERT(aClient->getPlayer() != nullptr); static const World& world = World::getInstance(); // singleton static const Database& db = Database::getInstance(); // singleton // Client& client = *aClient; Player& player = *aClient->getPlayer(); switch (mInfo->Action) { case ACTION_BUY: { Npc* npc = nullptr; if (!world.queryNpc(&npc, mInfo->UniqId)) return; if (!npc->isShopNpc()) return; if (player.getMapId() != npc->getMapId()) return; if (GameMap::distance(player.getPosX(), player.getPosY(), npc->getPosX(), npc->getPosY()) > Entity::CELLS_PER_VIEW) return; // TODO ? shop instead of query ? const Item::Info* info = nullptr; uint8_t moneytype = 0; if (IS_SUCCESS(db.getItemFromShop(&info, moneytype, mInfo->UniqId, mInfo->Data))) { switch (moneytype) { case 0: // money { uint32_t price = info->Price; if (player.getMoney() < price) { player.sendSysMsg(STR_NOT_SO_MUCH_MONEY); return; } if (player.awardItem(*info, true)) ASSERT(player.spendMoney(price, true)); break; } case 1: // CPs { uint32_t price = info->CPs; if (player.getCPs() < price) { player.sendSysMsg(STR_NOT_SO_MUCH_MONEY); return; } if (player.awardItem(*info, true)) ASSERT(player.spendMoney(price, true)); break; } default: ASSERT(false); break; } } break; } case ACTION_SELL: { Npc* npc = nullptr; if (!world.queryNpc(&npc, mInfo->UniqId)) return; if (!npc->isShopNpc()) return; if (player.getMapId() != npc->getMapId()) return; if (GameMap::distance(player.getPosX(), player.getPosY(), npc->getPosX(), npc->getPosY()) > Entity::CELLS_PER_VIEW) return; Item* item = player.getItem(mInfo->Data); if (item == nullptr) { player.sendSysMsg(STR_ITEM_NOT_FOUND); return; } if (!item->isSellEnable()) { player.sendSysMsg(STR_NOT_SELL_ENABLE); return; } uint32_t money = item->getSellPrice(); if (!player.eraseItem(mInfo->Data, true)) { player.sendSysMsg(STR_ITEM_INEXIST); return; } if (!player.gainMoney(money, true)) player.sendSysMsg(STR_MONEYBAG_FULL); break; } case ACTION_USE: { if (mInfo->TargetUID == 0 || mInfo->TargetUID == player.getUID()) { Item* item = player.getItem(mInfo->UniqId); if (item != nullptr) { if (!player.useItem(*item, (Item::Position)mInfo->Data, true)) player.sendSysMsg(STR_UNABLE_USE_ITEM); } else player.sendSysMsg(STR_ITEM_INEXIST); } else { printf("MsgItem::use() -> useItemTo(%u, %u)\n", mInfo->TargetUID, mInfo->UniqId); ASSERT(false); } break; } case ACTION_EQUIP: { ASSERT(false); break; } case ACTION_REPAIR: { Item* item = player.getItem(mInfo->UniqId); if (item == nullptr) { player.sendSysMsg(STR_ITEM_NOT_FOUND); return; } if (!item->isRepairEnable() || item->getAmount() > item->getAmountLimit()) { player.sendSysMsg(STR_REPAIR_FAILED); return; } uint32_t money = item->getRepairCost(); int32_t repair = item->getAmountLimit() - item->getAmount(); if (money == 0 || repair <= 0) return; if (!player.spendMoney(money, true)) { player.sendSysMsg(STR_REPAIR_NO_MONEY, money); return; // not enough money } // max durability changed if (item->isEquipment()) { if (item->getAmount() < item->getAmountLimit() / 2) { if (random(0, 100) < 5) item->setAmountLimit(max(1, item->getAmountLimit() - 1)); } else if (item->getAmount() < item->getAmountLimit() / 10) { if (random(0, 100) < 10) item->setAmountLimit(max(1, item->getAmountLimit() - 1)); } else { if (random(0, 100) < 80) item->setAmountLimit(max(1, item->getAmountLimit() - 1)); } } item->setAmount(item->getAmountLimit(), true); MsgItemInfo msg(*item, MsgItemInfo::ACTION_UPDATE); player.send(&msg); break; } case ACTION_REPAIRALL: { ASSERT(false); break; } case ACTION_COMPLETE_TASK: { player.send(this); break; } default: { fprintf(stdout, "Unknown action[%04u], data=[%d]\n", mInfo->Action, mInfo->Data); break; } } } void MsgItem :: swap(uint8_t* aBuf) const { ASSERT(aBuf != nullptr); MsgInfo* info = (MsgInfo*)aBuf; info->UniqId = bswap32(info->UniqId); info->Data = bswap32(info->Data); info->Action = bswap32(info->Action); info->Timestamp = bswap32(info->Timestamp); info->TargetUID = bswap32(info->TargetUID); }
30.58042
101
0.424194
COPS-Projects
4eda6495f881722d448fbca2b594ae7fcc2292f0
361
cpp
C++
imgui-binding/src/main/native/jni_binding_struct.cpp
zgoethel/imgui-java
4824bd523c98b987d3cb347550d0548bb7880180
[ "Apache-2.0" ]
245
2019-12-29T21:02:12.000Z
2022-03-30T09:31:22.000Z
imgui-binding/src/main/native/jni_binding_struct.cpp
abvadabra/imgui-java
6bb046c43303f871318963df83e393063137c824
[ "Apache-2.0" ]
103
2020-01-26T06:29:54.000Z
2022-03-30T17:08:31.000Z
imgui-binding/src/main/native/jni_binding_struct.cpp
abvadabra/imgui-java
6bb046c43303f871318963df83e393063137c824
[ "Apache-2.0" ]
55
2020-01-03T09:58:01.000Z
2022-03-24T13:06:04.000Z
#include "jni_binding_struct.h" jfieldID imGuiStructPtrID; namespace Jni { void InitBindingStruct(JNIEnv* env) { jclass jImGuiStructClass = env->FindClass("imgui/binding/ImGuiStruct"); imGuiStructPtrID = env->GetFieldID(jImGuiStructClass, "ptr", "J"); } jfieldID GetBindingStructPtrID() { return imGuiStructPtrID; } }
22.5625
79
0.695291
zgoethel
4edc6303ac53d563e269047ebedbb45641bebf87
4,704
cpp
C++
Examples/Basics/Particles/Combined/ParticlesCombined.cpp
SuperflyJon/VulkanPlayground
891b88227b66fc1e933ff77c1603e5d685d89047
[ "MIT" ]
2
2021-01-25T16:59:56.000Z
2021-02-14T21:11:05.000Z
Examples/Basics/Particles/Combined/ParticlesCombined.cpp
SuperflyJon/VulkanPlayground
891b88227b66fc1e933ff77c1603e5d685d89047
[ "MIT" ]
null
null
null
Examples/Basics/Particles/Combined/ParticlesCombined.cpp
SuperflyJon/VulkanPlayground
891b88227b66fc1e933ff77c1603e5d685d89047
[ "MIT" ]
1
2021-04-23T10:20:53.000Z
2021-04-23T10:20:53.000Z
#include <VulkanPlayground\Includes.h> #include <random> #include "..\ParticleSystem.h" class ParticlesCombinedApp : public VulkanApplication3DLight { struct VertInfo { glm::vec3 lightPos; float pad1; glm::vec3 viewPos; }; public: ParticlesCombinedApp() { TidyObjectOnExit(particles); } void ResetScene() override { CalcPositionMatrix({ 0.0f, 0.0f, 0.0f }, { -70.0f, -45.0f, 0 }, 0, 30); SetupLighting({ 0.0f, -35.0f, 0.0f }, 0.0f, 0.5f, 0.1f, 32.0f, model.GetModelSize()); } glm::vec4 GetClearColour() const override { return { 0, 0, 0, 1 }; } void SetupObjects(VulkanSystem& system, RenderPass& renderPass, VkExtent2D workingExtent) override { model.CorrectDodgyModelOnLoad(); model.LoadToGpu(system, VulkanPlayground::GetModelFile("Basics", "fireplace.obj"), Attribs::PosNormTexTanBitan); descriptor.AddUniformBuffer(system, 0, mvpUBO, "MVP"); descriptor.AddUniformBuffer(system, 1, vertInfo, "vertInfo"); descriptor.AddTexture(system, 3, texture, VulkanPlayground::GetModelFile("Basics", "fireplace_colormap_bc3_unorm.ktx"), VK_FORMAT_BC3_UNORM_BLOCK); descriptor.AddTexture(system, 4, normalMap, VulkanPlayground::GetModelFile("Basics", "fireplace_normalmap_bc3_unorm.ktx"), VK_FORMAT_BC3_UNORM_BLOCK); descriptor.AddUniformBuffer(system, 2, lightUBO, "Lighting", VK_SHADER_STAGE_FRAGMENT_BIT); CreateDescriptor(system, descriptor, "Draw"); pipeline.SetupVertexDescription(Attribs::PosNormTexTanBitan); pipeline.LoadShader(system, "NormalMap"); CreatePipeline(system, renderPass, pipeline, descriptor, workingExtent, "Main"); smoke.SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER); // Avoid edges bleeding over flame.SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER); fireDescriptor.AddUniformBuffer(system, 0, fireUniformBuffer, "Fire"); fireDescriptor.AddUniformBuffer(system, 3, viewport, "size"); fireDescriptor.AddTexture(system, 1, flame, VulkanPlayground::GetModelFile("Basics", "particle_flame.ktx")); fireDescriptor.AddTexture(system, 2, smoke, VulkanPlayground::GetModelFile("Basics", "particle_smoke.ktx")); CreateDescriptor(system, fireDescriptor, "Fire"); std::vector<Attribs::Attrib> fireAttribs{ {0, Attribs::Type::Position, VK_FORMAT_R32G32B32_SFLOAT}, {1, Attribs::Type::Misc, VK_FORMAT_R32_SFLOAT}, // Alpha {2, Attribs::Type::Misc, VK_FORMAT_R32_SFLOAT}, // Size {3, Attribs::Type::Misc, VK_FORMAT_R32_SFLOAT}, // Rotation {4, Attribs::Type::Misc, VK_FORMAT_R32_SINT} // Type }; fireGraphicsPipeline.SetupVertexDescription(fireAttribs); fireGraphicsPipeline.AddPushConstant(system, sizeof(int), VK_SHADER_STAGE_FRAGMENT_BIT); fireGraphicsPipeline.SetTopology(VK_PRIMITIVE_TOPOLOGY_POINT_LIST); fireGraphicsPipeline.SetDepthWriteEnabled(false); fireGraphicsPipeline.EnableBlending(VK_BLEND_FACTOR_DST_ALPHA, VK_BLEND_FACTOR_ONE); fireGraphicsPipeline.LoadShaderDiffNames(system, "Particles", "Fire"); CreatePipeline(system, renderPass, fireGraphicsPipeline, fireDescriptor, workingExtent, "Fire"); constexpr auto PARTICLE_COUNT = 500; particles.Prepare(system, PARTICLE_COUNT); viewport().X = (float)windowWidth; viewport.CopyToDevice(system); }; void DrawScene(VkCommandBuffer commandBuffer) override { pipeline.Bind(commandBuffer, descriptor); model.Draw(commandBuffer); // Draw fire in 2 passes to get the blending okay fireGraphicsPipeline.Bind(commandBuffer, fireDescriptor.GetDescriptorSet()); int draw = FLAME_PARTICLE; fireGraphicsPipeline.PushConstant(commandBuffer, &draw); particles.Draw(commandBuffer); draw = SMOKE_PARTICLE; fireGraphicsPipeline.PushConstant(commandBuffer, &draw); particles.Draw(commandBuffer); } void UpdateScene(VulkanSystem& system, float frameTime) override { fireUniformBuffer() = mvpUBO(); fireUniformBuffer().model = glm::translate(fireUniformBuffer().model, glm::vec3(-1.4f, 5.0f, 0.4f)); // Center fire on logs fireUniformBuffer.CopyToDevice(system); mvpUBO().model = glm::scale(mvpUBO().model, glm::vec3(10.0f)); particles.Update(frameTime); vertInfo().lightPos = lightUBO().lightPos; vertInfo().lightPos.x += jitterX.Vary(frameTime) * 25.0f; vertInfo().lightPos.z += jitterZ.Vary(frameTime) * 25.0f; vertInfo().viewPos = lightUBO().viewPos; vertInfo.CopyToDevice(system); } private: Descriptor descriptor; Pipeline pipeline; Model model; Texture texture, normalMap; UBO<VertInfo> vertInfo; UBO<MVP> fireUniformBuffer; Texture flame, smoke; Particles particles; Pipeline fireGraphicsPipeline; Descriptor fireDescriptor; struct Viewport { float X; }; UBO<Viewport> viewport; Jitter jitterX, jitterZ; }; DECLARE_APP(ParticlesCombined)
35.636364
152
0.764456
SuperflyJon
4edc78cd9acce413332ebc186c7039492aaece2a
1,038
cc
C++
src/congestion/util.cc
codefan-byte/supersim
38bd445dcd21fdb78fd28819e0d4dfaa6d1fd651
[ "Apache-2.0" ]
17
2017-05-09T07:08:41.000Z
2021-08-03T01:22:09.000Z
src/congestion/util.cc
codefan-byte/supersim
38bd445dcd21fdb78fd28819e0d4dfaa6d1fd651
[ "Apache-2.0" ]
32
2020-02-26T00:02:29.000Z
2022-01-20T23:23:55.000Z
src/congestion/util.cc
codefan-byte/supersim
38bd445dcd21fdb78fd28819e0d4dfaa6d1fd651
[ "Apache-2.0" ]
13
2016-12-02T22:01:04.000Z
2020-03-23T16:44:04.000Z
/* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 "congestion/util.h" #include <cmath> bool congestionEqualTo(f64 _cong1, f64 _cong2) { return std::abs(_cong1 - _cong2) < CONGESTION_TOLERANCE; } bool congestionLessThan(f64 _cong1, f64 _cong2) { return (_cong2 - _cong1) >= CONGESTION_TOLERANCE; } bool congestionGreaterThan(f64 _cong1, f64 _cong2) { return (_cong1 - _cong2) >= CONGESTION_TOLERANCE; }
34.6
76
0.753372
codefan-byte
4ede16040c950c977ea300c47c8b20d60029d32f
486
cpp
C++
sycl/test/esimd/nbarriers.cpp
MikeDvorskiy/llvm
8213321ebb90110bf4f3d04fa0dc8e131a464a19
[ "Apache-2.0" ]
null
null
null
sycl/test/esimd/nbarriers.cpp
MikeDvorskiy/llvm
8213321ebb90110bf4f3d04fa0dc8e131a464a19
[ "Apache-2.0" ]
null
null
null
sycl/test/esimd/nbarriers.cpp
MikeDvorskiy/llvm
8213321ebb90110bf4f3d04fa0dc8e131a464a19
[ "Apache-2.0" ]
null
null
null
// RUN: %clangxx -fsycl -c -fsycl-device-only -Xclang -emit-llvm %s -o %t #include <CL/sycl.hpp> #include <sycl/ext/intel/experimental/esimd.hpp> using namespace sycl::ext::intel::experimental::esimd; template <typename name, typename Func> __attribute__((sycl_kernel)) void kernel(Func kernelFunc) { kernelFunc(); } void caller(int x) { kernel<class kernel_esimd>([=]() SYCL_ESIMD_KERNEL { nbarrier_init<7>(); nbarrier_wait(2); nbarrier_signal(0, 0, 4, 4); }); }
24.3
73
0.693416
MikeDvorskiy
4ede4bf6a196bc6187236dd980b7e27d12b5a8a3
329
hpp
C++
src/Game.hpp
rainstormstudio/Rainstorm-Engine
f27ead834d93343aff22d8fc304cc8e91b19ac6e
[ "MIT" ]
1
2020-05-03T16:26:32.000Z
2020-05-03T16:26:32.000Z
src/Game.hpp
rainstormstudio/Rainstorm-Engine
f27ead834d93343aff22d8fc304cc8e91b19ac6e
[ "MIT" ]
null
null
null
src/Game.hpp
rainstormstudio/Rainstorm-Engine
f27ead834d93343aff22d8fc304cc8e91b19ac6e
[ "MIT" ]
null
null
null
#pragma once #include "Timer.hpp" #include "WindowManager.hpp" class Game { private: bool mIsRunning; Timer *timer; WindowManager mainWindow; public: Game(); bool isRunning(); void initialize(int initWidth, int initHeight); void processEvent(); void update(); void render(); void destroy(); ~Game(); };
14.304348
49
0.680851
rainstormstudio
4edfcef15cf2a3eecb9233fa094776dde2dd24b1
786
cpp
C++
practical16.cpp
ChaitanyaJoshiX/1-PU-Programs
44934140b63660f66d15da6d76b06530a4a714b9
[ "MIT" ]
null
null
null
practical16.cpp
ChaitanyaJoshiX/1-PU-Programs
44934140b63660f66d15da6d76b06530a4a714b9
[ "MIT" ]
null
null
null
practical16.cpp
ChaitanyaJoshiX/1-PU-Programs
44934140b63660f66d15da6d76b06530a4a714b9
[ "MIT" ]
null
null
null
/* WAP to generate the Fibonacci sequence up to a limit using for statement. @ChaitanyaJoshiX */ #include <iostream> using namespace std; main() { int i, limit; cout << "Enter limit for sequence : "; cin >> limit; int numlist[limit]; numlist[0] = 0; numlist[1] = 1; cout << "Fibonacci Sequence : "; for(i=0; numlist[i] <= limit; i++) { if(i==0) { cout << numlist[i] << " "; } else { if(i != limit-1) { cout << numlist[i] << " "; numlist[i+1] = numlist[i-1] + numlist[i]; } else { cout << numlist[i] << "." << endl;; } } } }
18.27907
63
0.398219
ChaitanyaJoshiX
4ee2e694d6fd1e5aacae17acd46f3528def3fd0e
587
hpp
C++
src/net/Serialize.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
81
2018-12-11T20:48:41.000Z
2022-03-18T22:24:11.000Z
src/net/Serialize.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
7
2020-04-19T11:50:39.000Z
2021-11-12T16:08:53.000Z
src/net/Serialize.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
4
2019-04-24T11:51:29.000Z
2021-03-10T05:26:33.000Z
#pragma once #include <Meta.h> namespace ari::net { template<typename Class, typename Stream, typename = std::enable_if_t <meta::isRegistered<Class>()>> bool Serialize(Stream & stream, Class & obj, const int& member_index = -1); template <typename Class, typename Stream, typename = std::enable_if_t <!meta::isRegistered<Class>()>, typename = void> bool Serialize(Stream & stream, Class & obj, const int& member_index = -1); template <typename Class, typename Stream> bool SerializeBasic(Stream& stream, Class& obj); } // namespace ari::net #include "Serialize.inl"
25.521739
76
0.715503
kochol
4ee3a6be0ead88efed4827d7f6c00783b1e9a1f0
3,171
hpp
C++
Core/History/HistoryTreeView.hpp
Feldrise/SieloNavigateurBeta
faa5fc785271b49d26237a5e9985d6fa22565076
[ "MIT" ]
89
2018-04-26T14:28:13.000Z
2019-07-03T03:58:17.000Z
Core/History/HistoryTreeView.hpp
inviu/webBrowser
37b24eded2e168e43b3f9c9ccc0487ee59410332
[ "MIT" ]
51
2018-04-26T12:43:00.000Z
2019-04-24T20:39:59.000Z
Core/History/HistoryTreeView.hpp
inviu/webBrowser
37b24eded2e168e43b3f9c9ccc0487ee59410332
[ "MIT" ]
34
2018-05-11T07:09:36.000Z
2019-04-19T08:12:40.000Z
/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@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. ** ***********************************************************************************/ #pragma once #ifndef SIELOBROWSER_HistoryTreeView_HPP #define SIELOBROWSER_HistoryTreeView_HPP #include "SharedDefines.hpp" #include <QWidget> #include <QTreeView> #include <QMouseEvent> namespace Sn { class History; class HistoryFilterModel; class SIELO_SHAREDLIB HistoryTreeView: public QTreeView { Q_OBJECT public: HistoryTreeView(QWidget* parent = nullptr); QUrl selectedUrl() const; signals: // Open url in current tab void urlActivated(const QUrl& url); // Open url in new tab void urlCtrlActivated(const QUrl& url); // Open url in new window void urlShiftActivated(const QUrl& url); // Context menu signal with point mapped to global void contextMenuRequested(const QPoint& point); public slots: void search(const QString& string); void removeSelectedItems(); protected: void contextMenuEvent(QContextMenuEvent* event); void mousePressEvent(QMouseEvent* event); void mouseDoubleClickEvent(QMouseEvent* event); void keyPressEvent(QKeyEvent* event); void drawRow(QPainter* painter, const QStyleOptionViewItem& options, const QModelIndex& index) const; private: History* m_history{nullptr}; HistoryFilterModel* m_filter{nullptr}; }; } #endif //SIELOBROWSER_HistoryTreeView_HPP
40.139241
102
0.580259
Feldrise
4ee3c47758de2eaafa89072d1db180806ada90d2
13,552
cc
C++
test/gtest/ucs/test_conn_match.cc
ironMann/ucx
4bb5c6892c7958a64378c5137e279e8250261a56
[ "BSD-3-Clause" ]
2
2021-09-15T22:50:14.000Z
2021-11-11T15:36:06.000Z
test/gtest/ucs/test_conn_match.cc
ironMann/ucx
4bb5c6892c7958a64378c5137e279e8250261a56
[ "BSD-3-Clause" ]
48
2019-03-22T09:41:47.000Z
2022-03-31T18:54:57.000Z
test/gtest/ucs/test_conn_match.cc
ironMann/ucx
4bb5c6892c7958a64378c5137e279e8250261a56
[ "BSD-3-Clause" ]
2
2020-07-25T23:48:33.000Z
2020-07-30T20:14:53.000Z
/** * Copyright (C) Mellanox Technologies Ltd. 2020. ALL RIGHTS RESERVED. * See file LICENSE for terms. */ #include <common/test.h> #include <ucs/datastruct/conn_match.h> #include <ucs/sys/sys.h> #include <vector> class test_conn_match : public ucs::test { public: typedef struct { ucs_conn_match_elem_t elem; ucs_conn_match_queue_type_t queue_type; const void *dest_address; ucs_conn_sn_t conn_sn; } conn_elem_t; test_conn_match() { m_address_length = 0; m_added_elems = 0; m_removed_elems = 0; m_purged_elems = 0; } private: void conn_match_init(size_t address_length) { ucs_conn_match_ops_t conn_match_ops; conn_match_ops.get_address = get_address; conn_match_ops.get_conn_sn = get_conn_sn; conn_match_ops.address_str = address_str; conn_match_ops.purge_cb = purge_cb; ucs_conn_match_init(&m_conn_match_ctx, address_length, &conn_match_ops); m_address_length = address_length; } void check_conn_elem(const conn_elem_t *conn_elem, const void *dest_address, ucs_conn_sn_t conn_sn) { EXPECT_EQ(conn_sn, conn_elem->conn_sn); EXPECT_TRUE(!memcmp(dest_address, conn_elem->dest_address, m_address_length)); } protected: static inline conn_elem_t* conn_elem_from_match_elem(const ucs_conn_match_elem_t *conn_match) { return ucs_container_of(conn_match, conn_elem_t, elem); } static const void *get_address(const ucs_conn_match_elem_t *conn_match) { return conn_elem_from_match_elem(conn_match)->dest_address; } static ucs_conn_sn_t get_conn_sn(const ucs_conn_match_elem_t *conn_match) { return conn_elem_from_match_elem(conn_match)->conn_sn; } static const char *address_str(const ucs_conn_match_ctx_t *conn_match_ctx, const void *address, char *str, size_t max_size) { EXPECT_EQ(&m_conn_match_ctx, conn_match_ctx); return ucs_strncpy_safe(str, static_cast<const char*>(address), ucs_min(m_conn_match_ctx.address_length, max_size)); } static void purge_cb(ucs_conn_match_ctx_t *conn_match_ctx, ucs_conn_match_elem_t *conn_match) { EXPECT_EQ(&m_conn_match_ctx, conn_match_ctx); m_purged_elems++; delete conn_elem_from_match_elem(conn_match); } void init_new_address_length(size_t address_length) { ucs_conn_match_cleanup(&m_conn_match_ctx); conn_match_init(address_length); } void *alloc_address(size_t idx, size_t address_length) { void *address = new uint8_t[address_length]; std::string idx_str = ucs::to_string(idx); memcpy(address, idx_str.c_str(), idx_str.size()); memset(UCS_PTR_BYTE_OFFSET(address, idx_str.size()), 'x', address_length - idx_str.size()); return address; } void init() { conn_match_init(m_default_address_length); } void cleanup() { ucs_conn_match_cleanup(&m_conn_match_ctx); EXPECT_EQ(m_added_elems - m_removed_elems, m_purged_elems); } void insert(const void *dest_address, ucs_conn_sn_t conn_sn, ucs_conn_match_queue_type_t queue_type, conn_elem_t &elem) { ucs_conn_match_insert(&m_conn_match_ctx, dest_address, conn_sn, &elem.elem, queue_type); elem.queue_type = queue_type; elem.conn_sn = conn_sn; m_added_elems++; } conn_elem_t *retrieve(const void *dest_address, ucs_conn_sn_t conn_sn, ucs_conn_match_queue_type_t queue_type) { ucs_conn_match_elem_t *conn_match = ucs_conn_match_get_elem(&m_conn_match_ctx, dest_address, conn_sn, queue_type, 1); if (conn_match == NULL) { return NULL; } conn_elem_t *conn_elem = conn_elem_from_match_elem(conn_match); EXPECT_EQ(queue_type, conn_elem->queue_type); check_conn_elem(conn_elem, dest_address, conn_sn); m_removed_elems++; return conn_elem; } conn_elem_t *lookup(const void *dest_address, ucs_conn_sn_t conn_sn, ucs_conn_match_queue_type_t queue_type) { ucs_conn_match_elem_t *conn_match = ucs_conn_match_get_elem(&m_conn_match_ctx, dest_address, conn_sn, queue_type, 0); if (conn_match == NULL) { return NULL; } ucs_conn_match_elem_t *test_conn_match = ucs_conn_match_get_elem(&m_conn_match_ctx, dest_address, conn_sn, UCS_CONN_MATCH_QUEUE_ANY, 0); EXPECT_EQ(conn_match, test_conn_match); conn_elem_t *conn_elem = conn_elem_from_match_elem(conn_match); check_conn_elem(conn_elem, dest_address, conn_sn); return conn_elem; } void remove_conn(conn_elem_t &elem) { ucs_conn_match_remove_elem(&m_conn_match_ctx, &elem.elem, elem.queue_type); m_removed_elems++; } ucs_conn_sn_t get_next_sn(const void *dest_address) { return ucs_conn_match_get_next_sn(&m_conn_match_ctx, dest_address); } private: static ucs_conn_match_ctx_t m_conn_match_ctx; size_t m_address_length; static const size_t m_default_address_length; size_t m_added_elems; size_t m_removed_elems; static size_t m_purged_elems; }; const size_t test_conn_match::m_default_address_length = 64; size_t test_conn_match::m_purged_elems = 0; ucs_conn_match_ctx_t test_conn_match::m_conn_match_ctx = {}; UCS_TEST_F(test_conn_match, random_insert_retrieve) { const size_t max_addresses = 128; const ucs_conn_sn_t max_conns = 128; const size_t max_address_length = 2048 / ucs::test_time_multiplier(); const size_t min_address_length = ucs::to_string(max_addresses).size(); const size_t max_iters = 4; for (size_t it = 0; it < max_iters; it++) { size_t address_length = ucs::rand() % (max_address_length - min_address_length + 1) + min_address_length; std::vector<std::vector<conn_elem_t> > conn_elems(max_addresses); init_new_address_length(address_length); UCS_TEST_MESSAGE << "address length: " << address_length; for (size_t i = 0; i < max_addresses; i++) { ucs_conn_sn_t num_conns = (ucs::rand() % max_conns) + 1; void *dest_address = alloc_address(i, address_length); conn_elems[i].resize(num_conns); for (ucs_conn_sn_t conn = 0; conn < num_conns; conn++) { conn_elem_t *conn_elem = &conn_elems[i][conn]; EXPECT_EQ(conn, get_next_sn(dest_address)); conn_elem->dest_address = dest_address; ucs_conn_match_queue_type_t queue_type = (ucs::rand() & 1) ? UCS_CONN_MATCH_QUEUE_EXP : UCS_CONN_MATCH_QUEUE_UNEXP; insert(dest_address, conn, queue_type, *conn_elem); EXPECT_EQ(queue_type, conn_elem->queue_type); EXPECT_EQ(conn, conn_elem->conn_sn); } } for (size_t i = 0; i < max_addresses; i++) { for (ucs_conn_sn_t conn = 0; conn < conn_elems[i].size(); conn++) { conn_elem_t *conn_elem = &conn_elems[i][conn]; ucs_conn_match_queue_type_t another_queue_type = (conn_elem->queue_type == UCS_CONN_MATCH_QUEUE_EXP) ? UCS_CONN_MATCH_QUEUE_UNEXP : UCS_CONN_MATCH_QUEUE_EXP; conn_elem_t *test_conn_elem; /* must not find this element in the another queue */ test_conn_elem = lookup(conn_elem->dest_address, conn_elem->conn_sn, another_queue_type); EXPECT_EQ(NULL, test_conn_elem); test_conn_elem = retrieve(conn_elem->dest_address, conn_elem->conn_sn, another_queue_type); EXPECT_EQ(NULL, test_conn_elem); test_conn_elem = lookup(conn_elem->dest_address, conn_elem->conn_sn, conn_elem->queue_type); EXPECT_EQ(conn_elem, test_conn_elem); test_conn_elem = retrieve(conn_elem->dest_address, conn_elem->conn_sn, conn_elem->queue_type); EXPECT_EQ(conn_elem, test_conn_elem); /* subsequent retrieving/lookup of the same connection element * must return NULL */ test_conn_elem = lookup(conn_elem->dest_address, conn_elem->conn_sn, conn_elem->queue_type); EXPECT_EQ(NULL, test_conn_elem); test_conn_elem = retrieve(conn_elem->dest_address, conn_elem->conn_sn, conn_elem->queue_type); EXPECT_EQ(NULL, test_conn_elem); insert(conn_elem->dest_address, conn_elem->conn_sn, another_queue_type, *conn_elem); } } for (size_t i = 0; i < max_addresses; i++) { for (unsigned conn = 0; conn < conn_elems[i].size(); conn++) { conn_elem_t *conn_elem = &conn_elems[i][conn]; conn_elem_t *test_conn_elem; test_conn_elem = lookup(conn_elem->dest_address, conn_elem->conn_sn, conn_elem->queue_type); EXPECT_EQ(conn_elem, test_conn_elem); EXPECT_EQ(conn, conn_elem->conn_sn); remove_conn(*conn_elem); /* subsequent retrieving/lookup of the same connection element * must return NULL */ test_conn_elem = lookup(conn_elem->dest_address, conn_elem->conn_sn, UCS_CONN_MATCH_QUEUE_EXP); EXPECT_EQ(NULL, test_conn_elem); test_conn_elem = lookup(conn_elem->dest_address, conn_elem->conn_sn, UCS_CONN_MATCH_QUEUE_UNEXP); EXPECT_EQ(NULL, test_conn_elem); test_conn_elem = retrieve(conn_elem->dest_address, conn_elem->conn_sn, UCS_CONN_MATCH_QUEUE_EXP); EXPECT_EQ(NULL, test_conn_elem); test_conn_elem = retrieve(conn_elem->dest_address, conn_elem->conn_sn, UCS_CONN_MATCH_QUEUE_UNEXP); EXPECT_EQ(NULL, test_conn_elem); } delete[] (uint8_t*)conn_elems[i][0].dest_address; } } } UCS_TEST_F(test_conn_match, purge_elems) { const size_t max_addresses = 128; const ucs_conn_sn_t max_conns = 128; const size_t address_length = 8; std::vector<std::vector<conn_elem_t*> > conn_elems(max_addresses); init_new_address_length(address_length); for (size_t i = 0; i < max_addresses; i++) { ucs_conn_sn_t num_conns = (ucs::rand() % max_conns) + 1; void *dest_address = alloc_address(i, address_length); conn_elems[i].resize(num_conns); for (ucs_conn_sn_t conn = 0; conn < num_conns; conn++) { conn_elems[i][conn] = new conn_elem_t; conn_elem_t *conn_elem = conn_elems[i][conn]; EXPECT_EQ(conn, get_next_sn(dest_address)); conn_elem->dest_address = dest_address; ucs_conn_match_queue_type_t queue_type = (ucs::rand() & 1) ? UCS_CONN_MATCH_QUEUE_EXP : UCS_CONN_MATCH_QUEUE_UNEXP; insert(dest_address, conn, queue_type, *conn_elem); EXPECT_EQ(queue_type, conn_elem->queue_type); EXPECT_EQ(conn, conn_elem->conn_sn); } } /* remove some elements */ for (size_t i = 0; i < max_addresses; i++) { const void *dest_address = conn_elems[i][0]->dest_address; for (ucs_conn_sn_t conn = 0; conn < conn_elems[i].size(); conn++) { conn_elem_t *conn_elem = conn_elems[i][conn]; if (ucs::rand() & 1) { conn_elem_t *test_conn_elem = retrieve(conn_elem->dest_address, conn_elem->conn_sn, conn_elem->queue_type); EXPECT_EQ(conn_elem, test_conn_elem); delete test_conn_elem; } else { /* the elements that will be purged don't need the destination * address anymore, so, the address will be deleted below */ conn_elem->dest_address = NULL; } } delete[] (uint8_t*)dest_address; } }
39.976401
87
0.579029
ironMann
4ee61f1ccc807a821a4b6ff20cba9e8ab0c50228
490
cpp
C++
test/opencv/opencv5.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
1
2020-10-01T14:52:45.000Z
2020-10-01T14:52:45.000Z
test/opencv/opencv5.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
3
2020-06-19T01:24:51.000Z
2020-07-16T14:00:30.000Z
test/opencv/opencv5.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
null
null
null
#include <opencv2/opencv.hpp> #include <iostream> using namespace std; using namespace cv; int main(int argc, char const *argv[]) { Mat data = (Mat_<double>(2, 2) << 1, 2, 2, 1); Mat eigen_values, eigen_vector; eigen(data, eigen_values, eigen_vector); for(int i = 0; i < eigen_values.rows; i++) { printf("eigen value %d: %.3f\n", i, eigen_values.at<double>(i)); } cout << "eigen vector: " << endl << eigen_vector << endl; waitKey(0); return 0; }
27.222222
72
0.610204
6923403
4eeba18e6b11a8e639882f194f6a9da4548eff7c
5,422
cpp
C++
src/parseosg.cpp
strawlab/flyvr
335892cae740e53e82e07b526e1ba53fbd34b0ce
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2015-01-29T14:09:25.000Z
2016-04-24T04:25:49.000Z
src/parseosg.cpp
strawlab/flyvr
335892cae740e53e82e07b526e1ba53fbd34b0ce
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2016-08-05T12:56:12.000Z
2016-08-09T14:20:09.000Z
src/parseosg.cpp
strawlab/flyvr
335892cae740e53e82e07b526e1ba53fbd34b0ce
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
#include <iostream> #include <osg/io_utils> #include <osg/Geometry> #include <osg/MatrixTransform> #include <osg/Geode> #include <osgDB/ReadFile> #include <osgAnimation/AnimationManagerBase> #include <osgAnimation/BasicAnimationManager> #include <osgAnimation/Bone> class MatrixNodeFinder : public osg::NodeVisitor { public: MatrixNodeFinder( void ) : osg::NodeVisitor( osg::NodeVisitor::TRAVERSE_ALL_CHILDREN ) {} virtual void apply( osg::Node& node ) { if (typeid(node) == typeid(osg::MatrixTransform)) { _nodeList.push_back(&node); } traverse( node ); } osg::NodeList* getNodeList() { return &_nodeList; } protected: osg::NodeList _nodeList; }; class AnimController { public: typedef std::vector<std::string> AnimationMapVector; AnimController(): _model(0), _focus(0) {} bool setModel(osgAnimation::BasicAnimationManager* model) { _model = model; _map.clear(); _amv.clear(); for (osgAnimation::AnimationList::const_iterator it = _model->getAnimationList().begin(); it != _model->getAnimationList().end(); it++) _map[(*it)->getName()] = *it; for(osgAnimation::AnimationMap::iterator it = _map.begin(); it != _map.end(); it++) _amv.push_back(it->first); return true; } bool list(std::ostream &output) { for(osgAnimation::AnimationMap::iterator it = _map.begin(); it != _map.end(); it++) output << "Animation=" << it->first << std::endl; return true; } bool play() { if(_focus < _amv.size()) { //std::cout << "Play " << _amv[_focus] << std::endl; _model->playAnimation(_map[_amv[_focus]].get()); return true; } return false; } bool play(const std::string& name) { for(unsigned int i = 0; i < _amv.size(); i++) if(_amv[i] == name) _focus = i; _model->playAnimation(_map[name].get()); return true; } bool stop() { if(_focus < _amv.size()) { //std::cout << "Stop " << _amv[_focus] << std::endl; _model->stopAnimation(_map[_amv[_focus]].get()); return true; } return false; } bool stop(const std::string& name) { for(unsigned int i = 0; i < _amv.size(); i++) if(_amv[i] == name) _focus = i; _model->stopAnimation(_map[name].get()); return true; } bool next() { _focus = (_focus + 1) % _map.size(); //std::cout << "Current now is " << _amv[_focus] << std::endl; return true; } bool previous() { _focus = (_map.size() + _focus - 1) % _map.size(); //std::cout << "Current now is " << _amv[_focus] << std::endl; return true; } const std::string& getCurrentAnimationName() const { return _amv[_focus]; } const AnimationMapVector& getAnimationMap() const { return _amv; } private: osg::ref_ptr<osgAnimation::BasicAnimationManager> _model; osgAnimation::AnimationMap _map; AnimationMapVector _amv; unsigned int _focus; }; struct AnimationManagerFinder : public osg::NodeVisitor { osg::ref_ptr<osgAnimation::BasicAnimationManager> _am; AnimationManagerFinder() : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {} void apply(osg::Node& node) { if (_am.valid()) return; if (node.getUpdateCallback()) { osgAnimation::AnimationManagerBase* b = dynamic_cast<osgAnimation::AnimationManagerBase*>(node.getUpdateCallback()); if (b) { _am = new osgAnimation::BasicAnimationManager(*b); return; } } traverse(node); } }; int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc, argv); arguments.getApplicationUsage()->setApplicationName("parseosg"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","List command line options."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename.osg"); if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::COMMAND_LINE_OPTION); return 0; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } std::string osgfile = arguments[1]; osg::Node* node = dynamic_cast<osg::Node*>(osgDB::readNodeFile(osgfile)); if(!node) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // list MatrixTranform nodes MatrixNodeFinder fmn; node->accept( fmn ); osg::NodeList* nl = fmn.getNodeList(); for (osg::NodeList::iterator it = nl->begin() ; it != nl->end(); ++it) std::cout << "MatrixTransformNode=" << it->get()->getName() << std::endl; // list animatable nodes AnimController anim; AnimationManagerFinder finder; node->accept(finder); if (finder._am.valid()) { node->setUpdateCallback(finder._am.get()); anim.setModel(finder._am.get()); anim.list(std::cout); } return 0; }
27.383838
143
0.588897
strawlab
4eec0fe0a57a75decb70a9ee2366c941c54b3963
1,163
cc
C++
src/tm_ncc/tm_ncc_generator.cc
fixstars/Halide-elements
0e9d1f27628c2626a4f4468fcacac8f71d70f525
[ "MIT" ]
76
2017-10-19T07:16:55.000Z
2022-03-23T00:04:39.000Z
src/tm_ncc/tm_ncc_generator.cc
tufei/Halide-elements
d9354213920441d4d3e1b0757e9354db48c9fbcc
[ "MIT" ]
3
2017-11-17T19:50:38.000Z
2021-08-07T07:39:05.000Z
src/tm_ncc/tm_ncc_generator.cc
tufei/Halide-elements
d9354213920441d4d3e1b0757e9354db48c9fbcc
[ "MIT" ]
15
2017-11-09T18:52:10.000Z
2021-12-11T03:33:23.000Z
#include <cstdint> #include "Halide.h" #include "Element.h" using namespace Halide; using Halide::Element::schedule; template<typename T> class TmNcc : public Halide::Generator<TmNcc<T>> { public: ImageParam src0{type_of<T>(), 2, "src0"}; ImageParam src1{type_of<T>(), 2, "src1"}; GeneratorParam<int32_t> img_width{"img_width", 1024}; GeneratorParam<int32_t> img_height{"img_height", 768}; GeneratorParam<int32_t> tmp_width{"tmp_width", 16}; GeneratorParam<int32_t> tmp_height{"tmp_height", 16}; Func build() { Func dst{"dst"}; dst = Element::tm_ncc<T>(src0, src1, img_width, img_height, tmp_width, tmp_height); const int32_t res_width = img_width.value() - tmp_width.value() + 1; const int32_t res_height = img_height.value() - tmp_height.value() + 1; schedule(src0, {img_width, img_height}); schedule(src1, {tmp_width, tmp_height}); schedule(dst, {res_width, res_height}); return dst; } }; HALIDE_REGISTER_GENERATOR(TmNcc<uint8_t>, tm_ncc_u8); HALIDE_REGISTER_GENERATOR(TmNcc<uint16_t>, tm_ncc_u16); HALIDE_REGISTER_GENERATOR(TmNcc<uint32_t>, tm_ncc_u32);
30.605263
91
0.689596
fixstars
4eec2ad0bc960df37cf3eb7f215f5205e6109939
1,846
cpp
C++
ParticlePlay/IMS/Format/EmptyFormat.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/IMS/Format/EmptyFormat.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/IMS/Format/EmptyFormat.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
#include "EmptyFormat.hpp" ppEmptyFormat::ppEmptyFormat(ppIMS* ims, Sint64 length, ppFormat* audioFormat) : ppFormat(ims){ this->length = length; this->sourceAudioFormat = audioFormat; } int ppEmptyFormat::Init(const char *filename, bool stereo){ int status = ppFormat::Init(filename, stereo); if(status>0){ return status; } this->audioChannels = (stereo?2:1); this->audioTracks = 1; this->bitPerSample = 16; this->audioFormat = (stereo?AL_FORMAT_STEREO16:AL_FORMAT_MONO16); return 0; } Sint64 ppEmptyFormat::Read(char *bufferData, Sint64 position, Sint64 size, int track){ for(Sint64 i=0;i<size;i++){ bufferData[i] = 0; } return size; } Sint64 ppEmptyFormat::ActualPosition(Sint64 relativePosition){ return this->sourceAudioFormat->ActualPosition(relativePosition); // return relativePosition*this->audioChannels/(this->stereo?2:1); } Sint64 ppEmptyFormat::RelativePosition(Sint64 actualPosition){ return this->sourceAudioFormat->RelativePosition(actualPosition); // return actualPosition/this->audioChannels*(this->stereo?2:1); } Sint64 ppEmptyFormat::GetPositionLength(){ return this->length; } float ppEmptyFormat::PositionToTime(Sint64 position){ return this->sourceAudioFormat->PositionToTime(position); // float sampleLength = position * 8 / (this->audioChannels * this->bitPerSample); // return sampleLength / this->sourceAudioFormat->GetSampleRate(); } Sint64 ppEmptyFormat::TimeToPosition(float time){ return this->sourceAudioFormat->TimeToPosition(time); float sampleLength = time * this->sourceAudioFormat->GetSampleRate(); return sampleLength * this->audioChannels * this->bitPerSample / 8; } int ppEmptyFormat::GetSampleRate(){ return this->sourceAudioFormat->GetSampleRate(); } ALuint ppEmptyFormat::GetFormat(){ return this->audioFormat; } int ppEmptyFormat::GetTotalTrack(){ return 1; }
28.84375
95
0.762189
spywhere
4eefd196764276bef5cbb19a5747c1548be3ec0c
90,979
cpp
C++
picoc/assumption_expr.cpp
moves-rwth/nitwit-validator
8819d537b30360ed267f6950dc5219af4abc5bad
[ "BSD-3-Clause" ]
4
2019-10-02T10:15:51.000Z
2019-11-24T12:00:18.000Z
picoc/assumption_expr.cpp
moves-rwth/nitwit-validator
8819d537b30360ed267f6950dc5219af4abc5bad
[ "BSD-3-Clause" ]
null
null
null
picoc/assumption_expr.cpp
moves-rwth/nitwit-validator
8819d537b30360ed267f6950dc5219af4abc5bad
[ "BSD-3-Clause" ]
2
2019-10-04T10:19:11.000Z
2020-05-31T06:58:40.000Z
/* picoc expression evaluator - a stack-based expression evaluation system * which handles operator precedence */ #include "interpreter.hpp" /* whether evaluation is left to right for a given precedence level */ #define IS_LEFT_TO_RIGHT(p) ((p) != 2 && (p) != 14) #define BRACKET_PRECEDENCE 20 /* If the destination is not float, we can't assign a floating value to it, we need to convert it to integer instead */ #define ASSIGN_FP_OR_INT(value) \ if (IS_FP(BottomValue)) { ResultFP = AssignFP(Parser, BottomValue, value); } \ else { ResultInt = AssignLongLong(Parser, BottomValue, (long long)(value), FALSE); ResultIsInt = TRUE; } \ #define DEEP_PRECEDENCE (BRACKET_PRECEDENCE*1000) #ifdef DEBUG_EXPRESSIONS #define debugff printf #else void debugff(char *Format, ...) { } #endif /* local prototypes */ enum OperatorOrder { OrderNone, OrderPrefix, OrderInfix, OrderPostfix }; /* a stack of expressions we use in evaluation */ struct ExpressionStack { struct ExpressionStack *Next; /* the next lower item on the stack */ Value *Val; /* the value for this stack node */ enum LexToken Op; /* the operator */ short unsigned int Precedence; /* the operator precedence of this node */ unsigned char Order; /* the evaluation order of this operator */ }; /* operator precedence definitions */ struct OpPrecedence { unsigned int PrefixPrecedence:4; unsigned int PostfixPrecedence:4; unsigned int InfixPrecedence:4; char *Name; }; /* NOTE: the order of this array must correspond exactly to the order of these tokens in enum LexToken */ static struct OpPrecedence OperatorPrecedence[] = { /* TokenNone, */ { 0, 0, 0, "none" }, /* TokenComma, */ { 0, 0, 0, "," }, /* TokenAssign, */ { 0, 0, 2, "=" }, /* TokenAddAssign, */ { 0, 0, 2, "+=" }, /* TokenSubtractAssign, */ { 0, 0, 2, "-=" }, /* TokenMultiplyAssign, */ { 0, 0, 2, "*=" }, /* TokenDivideAssign, */ { 0, 0, 2, "/=" }, /* TokenModulusAssign, */ { 0, 0, 2, "%=" }, /* TokenShiftLeftAssign, */ { 0, 0, 2, "<<=" }, /* TokenShiftRightAssign, */ { 0, 0, 2, ">>=" }, /* TokenArithmeticAndAssign, */ { 0, 0, 2, "&=" }, /* TokenArithmeticOrAssign, */ { 0, 0, 2, "|=" }, /* TokenArithmeticExorAssign, */ { 0, 0, 2, "^=" }, /* TokenQuestionMark, */ { 0, 0, 3, "?" }, /* TokenColon, */ { 0, 0, 3, ":" }, /* TokenLogicalOr, */ { 0, 0, 4, "||" }, /* TokenLogicalAnd, */ { 0, 0, 5, "&&" }, /* TokenArithmeticOr, */ { 0, 0, 6, "|" }, /* TokenArithmeticExor, */ { 0, 0, 7, "^" }, /* TokenAmpersand, */ { 14, 0, 8, "&" }, /* TokenEqual, */ { 0, 0, 9, "==" }, /* TokenNotEqual, */ { 0, 0, 9, "!=" }, /* TokenLessThan, */ { 0, 0, 10, "<" }, /* TokenGreaterThan, */ { 0, 0, 10, ">" }, /* TokenLessEqual, */ { 0, 0, 10, "<=" }, /* TokenGreaterEqual, */ { 0, 0, 10, ">=" }, /* TokenShiftLeft, */ { 0, 0, 11, "<<" }, /* TokenShiftRight, */ { 0, 0, 11, ">>" }, /* TokenPlus, */ { 14, 0, 12, "+" }, /* TokenMinus, */ { 14, 0, 12, "-" }, /* TokenAsterisk, */ { 14, 0, 13, "*" }, /* TokenSlash, */ { 0, 0, 13, "/" }, /* TokenModulus, */ { 0, 0, 13, "%" }, /* TokenIncrement, */ { 14, 15, 0, "++" }, /* TokenDecrement, */ { 14, 15, 0, "--" }, /* TokenUnaryNot, */ { 14, 0, 0, "!" }, /* TokenUnaryExor, */ { 14, 0, 0, "~" }, /* TokenSizeof, */ { 14, 0, 0, "sizeof" }, /* TokenCast, */ { 14, 0, 0, "cast" }, /* TokenLeftSquareBracket, */ { 0, 0, 15, "[" }, /* TokenRightSquareBracket, */ { 0, 15, 0, "]" }, /* TokenDot, */ { 0, 0, 15, "." }, /* TokenArrow, */ { 0, 0, 15, "->" }, /* TokenOpenBracket, */ { 15, 0, 15, "(" }, /* TokenCloseBracket, */ { 0, 15, 0, ")" } }; void AssumptionExpressionParseFunctionCall(struct ParseState *Parser, struct ExpressionStack **StackTop, const char *FuncName, int RunIt); #ifdef DEBUG_EXPRESSIONS /* show the contents of the expression stack */ void ExpressionStackShow(Picoc *pc, struct ExpressionStack *StackTop) { printf("Expression stack [0x%lx,0x%lx]: ", (long long)pc->HeapStackTop, (long long)StackTop); while (StackTop != nullptr) { if (StackTop->Order == OrderNone) { /* it's a value */ if (StackTop->Val->IsLValue) printf("lvalue="); else printf("value="); switch (StackTop->Val->Typ->Base) { case TypeVoid: printf("void"); break; case TypeInt: printf("%d:int", StackTop->Val->Val->Integer); break; case TypeShort: printf("%d:short", StackTop->Val->Val->ShortInteger); break; case TypeChar: printf("%d:char", StackTop->Val->Val->Character); break; case TypeLong: printf("%ld:long long", StackTop->Val->Val->LongInteger); break; case TypeUnsignedShort: printf("%d:unsigned short", StackTop->Val->Val->UnsignedShortInteger); break; case TypeUnsignedInt: printf("%d:unsigned int", StackTop->Val->Val->UnsignedInteger); break; case TypeUnsignedLong: printf("%ld:unsigned long long", StackTop->Val->Val->UnsignedLongInteger); break; case TypeDouble: printf("%f:fp", StackTop->Val->Val->Double); break; case TypeFunction: printf("%s:function", StackTop->Val->Val->Identifier); break; case TypeMacro: printf("%s:macro", StackTop->Val->Val->Identifier); break; case TypePointer: if (StackTop->Val->Val->Pointer == nullptr) printf("ptr(nullptr)"); else if (StackTop->Val->Typ->FromType->Base == TypeChar) printf("\"%s\":string", (char *)StackTop->Val->Val->Pointer); else printf("ptr(0x%lx)", (long long)StackTop->Val->Val->Pointer); break; case TypeArray: printf("array"); break; case TypeStruct: printf("%s:struct", StackTop->Val->Val->Identifier); break; case TypeUnion: printf("%s:union", StackTop->Val->Val->Identifier); break; case TypeEnum: printf("%s:enum", StackTop->Val->Val->Identifier); break; case Type_Type: PrintType(StackTop->Val->Val->Typ, pc->CStdOut); printf(":type"); break; default: printf("unknown"); break; } printf("[0x%lx,0x%lx]", (long long)StackTop, (long long)StackTop->Val); } else { /* it's an operator */ printf("op='%s' %s %d", OperatorPrecedence[(int)StackTop->Op].Name, (StackTop->Order == OrderPrefix) ? "prefix" : ((StackTop->Order == OrderPostfix) ? "postfix" : "infix"), StackTop->Precedence); printf("[0x%lx]", (long long)StackTop); } StackTop = StackTop->Next; if (StackTop != nullptr) printf(", "); } printf("\n"); } #endif // int AssumptionIsTypeToken(struct ParseState *Parser, enum LexToken t, Value *LexValue) { if (t >= TokenIntType && t <= TokenUnsignedType) return 1; /* base type */ /* typedef'ed type? */ if (t == TokenIdentifier) /* see TypeParseFront, case TokenIdentifier and ParseTypedef */ { Value * VarValue; if (VariableDefined(Parser->pc, (const char*) LexValue->Val->Pointer)) { VariableGet(Parser->pc, Parser,(const char*) LexValue->Val->Pointer, &VarValue); if (VarValue->Typ->Base == Type_Type) return 1; } } return 0; } /* push a node on to the expression stack */ void AssumptionExpressionStackPushValueNode(struct ParseState *Parser, struct ExpressionStack **StackTop, Value *ValueLoc) { auto *StackNode = static_cast<ExpressionStack *>(VariableAlloc(Parser->pc, Parser, sizeof(struct ExpressionStack),FALSE)); StackNode->Next = *StackTop; StackNode->Val = ValueLoc; *StackTop = StackNode; #ifdef FANCY_ERROR_MESSAGES StackNode->Line = Parser->Line; StackNode->CharacterPos = Parser->CharacterPos; #endif #ifdef DEBUG_EXPRESSIONS ExpressionStackShow(Parser->pc, *StackTop); #endif } /* push a blank value on to the expression stack by type */ Value *AssumptionExpressionStackPushValueByType(struct ParseState *Parser, struct ExpressionStack **StackTop, struct ValueType *PushType) { Value *ValueLoc = VariableAllocValueFromType(Parser->pc, Parser, PushType, FALSE, nullptr, FALSE); AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); return ValueLoc; } /* push a value on to the expression stack */ void AssumptionExpressionStackPushValue(struct ParseState *Parser, struct ExpressionStack **StackTop, Value *PushValue) { Value *ValueLoc = VariableAllocValueAndCopy(Parser->pc, Parser, PushValue, FALSE); AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } void AssumptionExpressionStackPushLValue(struct ParseState *Parser, struct ExpressionStack **StackTop, Value *PushValue, int Offset) { Value *ValueLoc = VariableAllocValueShared(Parser, PushValue); ValueLoc->Val = static_cast<AnyValue *>((void *) ((char *) ValueLoc->Val + Offset)); AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } void AssumptionExpressionStackPushDereference(struct ParseState *Parser, struct ExpressionStack **StackTop, Value *DereferenceValue) { Value *DerefVal; Value *ValueLoc; int Offset; struct ValueType *DerefType; int DerefIsLValue; void *DerefDataLoc = VariableDereferencePointer(Parser, DereferenceValue, &DerefVal, &Offset, &DerefType, &DerefIsLValue); if (DerefDataLoc == nullptr) ProgramFail(Parser, "nullptr pointer dereference"); ValueLoc = VariableAllocValueFromExistingData(Parser, DerefType, (union AnyValue *) DerefDataLoc, DerefIsLValue, DerefVal, nullptr); AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } void AssumptionExpressionPushLongLong(struct ParseState *Parser, struct ExpressionStack **StackTop, long long IntValue) { Value *ValueLoc = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->LongLongType, FALSE, nullptr, FALSE); ValueLoc->Val->LongLongInteger = IntValue; AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } void AssumptionExpressionPushUnsignedLongLong(struct ParseState *Parser, struct ExpressionStack **StackTop, unsigned long long IntValue) { Value *ValueLoc = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->UnsignedLongLongType, FALSE, nullptr, FALSE); ValueLoc->Val->UnsignedLongLongInteger = IntValue; AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } void AssumptionExpressionPushInt(struct ParseState *Parser, struct ExpressionStack **StackTop, long IntValue) { Value *ValueLoc = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->LongType, FALSE, nullptr, FALSE); ValueLoc->Val->LongInteger = IntValue; AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } void AssumptionExpressionPushUnsignedInt(struct ParseState *Parser, struct ExpressionStack **StackTop, unsigned long IntValue) { Value *ValueLoc = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->UnsignedLongType, FALSE, nullptr, FALSE); ValueLoc->Val->UnsignedLongInteger = IntValue; AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } #ifndef NO_FP void AssumptionExpressionPushDouble(struct ParseState *Parser, struct ExpressionStack **StackTop, double FPValue) { Value *ValueLoc = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->DoubleType, FALSE, nullptr, FALSE); ValueLoc->Val->Double = FPValue; AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } void AssumptionExpressionPushFloat(struct ParseState *Parser, struct ExpressionStack **StackTop, float FPValue) { Value *ValueLoc = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->FloatType, FALSE, nullptr, FALSE); ValueLoc->Val->Float = FPValue; AssumptionExpressionStackPushValueNode(Parser, StackTop, ValueLoc); } #endif /* assign to a pointer */ void AssumptionExpressionAssignToPointer(struct ParseState *Parser, Value *ToValue, Value *FromValue, const char *FuncName, int ParamNo, int AllowPointerCoercion) { struct ValueType *PointedToType = ToValue->Typ->FromType; if (FromValue->Typ == ToValue->Typ || FromValue->Typ == Parser->pc->VoidPtrType || (ToValue->Typ == Parser->pc->VoidPtrType && FromValue->Typ->Base == TypePointer)) ToValue->Val->Pointer = FromValue->Val->Pointer; /* plain old pointer assignment */ else if (FromValue->Typ->Base == TypeArray && (PointedToType == FromValue->Typ->FromType || ToValue->Typ == Parser->pc->VoidPtrType)) { /* the form is: blah *x = array of blah */ ToValue->Val->Pointer = (void *)&FromValue->Val->ArrayMem[0]; } else if (FromValue->Typ->Base == TypePointer && FromValue->Typ->FromType->Base == TypeArray && (PointedToType == FromValue->Typ->FromType->FromType || ToValue->Typ == Parser->pc->VoidPtrType) ) { /* the form is: blah *x = pointer to array of blah */ ToValue->Val->Pointer = VariableDereferencePointer(Parser, FromValue, nullptr, nullptr, nullptr, nullptr); } else if (IS_NUMERIC_COERCIBLE(FromValue) && CoerceInteger(FromValue) == 0) { /* null pointer assignment */ ToValue->Val->Pointer = nullptr; } else if (AllowPointerCoercion && IS_NUMERIC_COERCIBLE(FromValue)) { /* assign integer to native pointer */ ToValue->Val->Pointer = (void *)(unsigned long) CoerceUnsignedInteger(FromValue); } else if (AllowPointerCoercion && FromValue->Typ->Base == TypePointer) { /* assign a pointer to a pointer to a different type */ ToValue->Val->Pointer = FromValue->Val->Pointer; } else AssignFail(Parser, "%t from %t", ToValue->Typ, FromValue->Typ, 0, 0, FuncName, ParamNo); } /* assign any kind of value */ void AssumptionExpressionAssign(struct ParseState *Parser, Value *DestValue, Value *SourceValue, int Force, const char *FuncName, int ParamNo, int AllowPointerCoercion) { if (!DestValue->IsLValue && !Force) AssignFail(Parser, "not an lvalue", nullptr, nullptr, 0, 0, FuncName, ParamNo); if (IS_NUMERIC_COERCIBLE(DestValue) && !IS_NUMERIC_COERCIBLE_PLUS_POINTERS(SourceValue, AllowPointerCoercion)) AssignFail(Parser, "%t from %t", DestValue->Typ, SourceValue->Typ, 0, 0, FuncName, ParamNo); switch (DestValue->Typ->Base) { case TypeInt: DestValue->Val->Integer = CoerceInteger(SourceValue); break; case TypeShort: DestValue->Val->ShortInteger = (short) CoerceInteger(SourceValue); break; case TypeChar: DestValue->Val->Character = (char) CoerceInteger(SourceValue); break; case TypeLong: DestValue->Val->LongInteger = CoerceInteger(SourceValue); break; case TypeUnsignedInt: DestValue->Val->UnsignedInteger = CoerceUnsignedInteger( SourceValue); break; case TypeUnsignedShort: DestValue->Val->UnsignedShortInteger = (unsigned short) CoerceUnsignedInteger( SourceValue); break; case TypeUnsignedChar: DestValue->Val->UnsignedCharacter = (unsigned char) CoerceUnsignedInteger( SourceValue); break; case TypeLongLong: DestValue->Val->LongLongInteger = CoerceLongLong(SourceValue); break; case TypeUnsignedLongLong: DestValue->Val->UnsignedLongLongInteger = CoerceUnsignedLongLong( SourceValue); break; #ifndef NO_FP case TypeDouble: if (!IS_NUMERIC_COERCIBLE_PLUS_POINTERS(SourceValue, AllowPointerCoercion)) AssignFail(Parser, "%t from %t", DestValue->Typ, SourceValue->Typ, 0, 0, FuncName, ParamNo); DestValue->Val->Double = CoerceDouble(SourceValue); break; case TypeFloat: if (!IS_NUMERIC_COERCIBLE_PLUS_POINTERS(SourceValue, AllowPointerCoercion)) AssignFail(Parser, "%t from %t", DestValue->Typ, SourceValue->Typ, 0, 0, FuncName, ParamNo); DestValue->Val->Float = CoerceFloat(SourceValue); break; #endif case TypePointer: AssumptionExpressionAssignToPointer(Parser, DestValue, SourceValue, FuncName, ParamNo, AllowPointerCoercion); break; case TypeArray: if (SourceValue->Typ->Base == TypeArray && DestValue->Typ->ArraySize == 0) { /* destination array is unsized - need to resize the destination array to the same size as the source array */ DestValue->Typ = SourceValue->Typ; VariableRealloc(Parser, DestValue, TypeSizeValue(DestValue, FALSE)); if (DestValue->LValueFrom != nullptr) { /* copy the resized value back to the LValue */ DestValue->LValueFrom->Val = DestValue->Val; DestValue->LValueFrom->AnyValOnHeap = DestValue->AnyValOnHeap; } } /* char array = "abcd" */ if (DestValue->Typ->FromType->Base == TypeChar && SourceValue->Typ->Base == TypePointer && SourceValue->Typ->FromType->Base == TypeChar) { if (DestValue->Typ->ArraySize == 0) /* char x[] = "abcd", x is unsized */ { int Size = strlen((const char*)SourceValue->Val->Pointer) + 1; #ifdef DEBUG_ARRAY_INITIALIZER PRINT_SOURCE_POS; fprintf(stderr, "str size: %d\n", Size); #endif DestValue->Typ = TypeGetMatching(Parser->pc, Parser, DestValue->Typ->FromType, DestValue->Typ->Base, Size, DestValue->Typ->Identifier, TRUE, nullptr); VariableRealloc(Parser, DestValue, TypeSizeValue(DestValue, FALSE)); } /* else, it's char x[10] = "abcd" */ #ifdef DEBUG_ARRAY_INITIALIZER PRINT_SOURCE_POS; fprintf(stderr, "char[%d] from char* (len=%d)\n", DestValue->Typ->ArraySize, strlen(SourceValue->Val->Pointer)); #endif memcpy((void *)DestValue->Val, SourceValue->Val->Pointer, TypeSizeValue(DestValue, FALSE)); break; } if (DestValue->Typ != SourceValue->Typ) AssignFail(Parser, "%t from %t", DestValue->Typ, SourceValue->Typ, 0, 0, FuncName, ParamNo); if (DestValue->Typ->ArraySize != SourceValue->Typ->ArraySize) AssignFail(Parser, "from an array of size %d to one of size %d", nullptr, nullptr, DestValue->Typ->ArraySize, SourceValue->Typ->ArraySize, FuncName, ParamNo); memcpy((void *)DestValue->Val, (void *)SourceValue->Val, TypeSizeValue(DestValue, FALSE)); break; case TypeStruct: case TypeUnion: if (DestValue->Typ != SourceValue->Typ) AssignFail(Parser, "%t from %t", DestValue->Typ, SourceValue->Typ, 0, 0, FuncName, ParamNo); memcpy((void *)DestValue->Val, (void *)SourceValue->Val, TypeSizeValue(SourceValue, FALSE)); break; case TypeFunctionPtr: if (DestValue->Typ->Base != SourceValue->Typ->Base && !(SourceValue->Typ->Base == TypeInt && CoerceLongLong(SourceValue) == 0)) AssignFail(Parser, "%t from %t", DestValue->Typ, SourceValue->Typ, 0, 0, FuncName, ParamNo); if (SourceValue->Typ->Base == TypeInt) DestValue->Val->Identifier = nullptr; else DestValue->Val->Identifier = SourceValue->Val->Identifier; break; default: AssignFail(Parser, "%t", DestValue->Typ, nullptr, 0, 0, FuncName, ParamNo); break; } } /* evaluate the first half of a ternary operator x ? y : z */ void AssumptionExpressionQuestionMarkOperator(struct ParseState *Parser, struct ExpressionStack **StackTop, Value *BottomValue, Value *TopValue) { if (!IS_NUMERIC_COERCIBLE(TopValue)) ProgramFail(Parser, "first argument to '?' should be a number"); if (CoerceInteger(TopValue)) { /* the condition's true, return the BottomValue */ AssumptionExpressionStackPushValue(Parser, StackTop, BottomValue); } else { /* the condition's false, return void */ AssumptionExpressionStackPushValueByType(Parser, StackTop, &Parser->pc->VoidType); } } /* evaluate the second half of a ternary operator x ? y : z */ void AssumptionExpressionColonOperator(struct ParseState *Parser, struct ExpressionStack **StackTop, Value *BottomValue, Value *TopValue) { if (TopValue->Typ->Base == TypeVoid) { /* invoke the "else" part - return the BottomValue */ AssumptionExpressionStackPushValue(Parser, StackTop, BottomValue); } else { /* it was a "then" - return the TopValue */ AssumptionExpressionStackPushValue(Parser, StackTop, TopValue); } } /* evaluate a prefix operator */ void AssumptionExpressionPrefixOperator(struct ParseState *Parser, struct ExpressionStack **StackTop, enum LexToken Op, Value *TopValue) { Value *Result; union AnyValue *ValPtr; // debugff("ExpressionPrefixOperator()\n"); switch (Op) { case TokenAmpersand: if (!TopValue->IsLValue) ProgramFail(Parser, "can't get the address of this"); if (TopValue->Typ->Base == TypeFunctionPtr) { char * id = TopValue->Val->Identifier; Result = VariableAllocValueFromType(Parser->pc, Parser, TopValue->Typ, FALSE, nullptr, FALSE); Result->Val->Identifier = id; } else { ValPtr = TopValue->Val; Result = VariableAllocValueFromType(Parser->pc, Parser, TypeGetMatching(Parser->pc, Parser, TopValue->Typ, TypePointer, 0, Parser->pc->StrEmpty, TRUE, nullptr), FALSE, nullptr, FALSE); Result->Val->Pointer = (void *)ValPtr; } AssumptionExpressionStackPushValueNode(Parser, StackTop, Result); break; case TokenAsterisk: if (TopValue->Typ->Base == TypeFunctionPtr || (TopValue->Typ->Base == TypeArray && TopValue->Typ->FromType->Base == TypeFunctionPtr)) { AssumptionExpressionStackPushValue(Parser, StackTop, TopValue); break; } AssumptionExpressionStackPushDereference(Parser, StackTop, TopValue); break; case TokenSizeof: /* return the size of the argument */ if (TopValue->Typ->Base == Type_Type) AssumptionExpressionPushLongLong(Parser, StackTop, TypeSize(TopValue->Val->Typ, TopValue->Val->Typ->ArraySize, TRUE)); else AssumptionExpressionPushLongLong(Parser, StackTop, TypeSize(TopValue->Typ, TopValue->Typ->ArraySize, TRUE)); break; default: /* an arithmetic operator */ #ifndef NO_FP if (TopValue->Typ->Base == TypeDouble) { /* floating point prefix arithmetic */ double ResultFP = 0.0; switch (Op) { case TokenPlus: ResultFP = TopValue->Val->Double; break; case TokenMinus: ResultFP = -TopValue->Val->Double; break; case TokenIncrement: ResultFP = AssignFP(Parser, TopValue, TopValue->Val->Double + 1); break; case TokenDecrement: ResultFP = AssignFP(Parser, TopValue, TopValue->Val->Double - 1); break; case TokenUnaryNot: ResultFP = !TopValue->Val->Double; break; default: ProgramFail(Parser, "invalid operation"); break; } AssumptionExpressionPushDouble(Parser, StackTop, ResultFP); } else if (TopValue->Typ->Base == TypeFloat) { /* floating point prefix arithmetic */ float ResultFP = 0.0; switch (Op) { case TokenPlus: ResultFP = TopValue->Val->Float; break; case TokenMinus: ResultFP = -TopValue->Val->Float; break; case TokenIncrement: ResultFP = AssignFP(Parser, TopValue, TopValue->Val->Float + 1); break; case TokenDecrement: ResultFP = AssignFP(Parser, TopValue, TopValue->Val->Float - 1); break; case TokenUnaryNot: ResultFP = !TopValue->Val->Float; break; default: ProgramFail(Parser, "invalid operation"); break; } AssumptionExpressionPushFloat(Parser, StackTop, ResultFP); } else #endif if (IS_NUMERIC_COERCIBLE(TopValue) && !IS_UNSIGNED(TopValue)) { /* integer prefix arithmetic */ long ResultInt = 0; long TopInt = CoerceInteger(TopValue); switch (Op) { case TokenPlus: ResultInt = TopInt; break; case TokenMinus: ResultInt = -TopInt; break; case TokenIncrement: ResultInt = AssignInt(Parser, TopValue, TopInt + 1, FALSE); break; case TokenDecrement: ResultInt = AssignInt(Parser, TopValue, TopInt - 1, FALSE); break; case TokenUnaryNot: ResultInt = !TopInt; break; case TokenUnaryExor: ResultInt = ~TopInt; break; default: ProgramFail(Parser, "invalid operation"); break; } AssumptionExpressionPushInt(Parser, StackTop, ResultInt); } else if (IS_NUMERIC_COERCIBLE(TopValue) && IS_UNSIGNED(TopValue)) { /* integer prefix arithmetic */ long long ResultInt = 0; long long TopInt = CoerceLongLong(TopValue); switch (Op) { case TokenPlus: ResultInt = TopInt; break; case TokenMinus: ResultInt = -TopInt; break; case TokenIncrement: ResultInt = AssignLongLong(Parser, TopValue, TopInt + 1, FALSE); break; case TokenDecrement: ResultInt = AssignLongLong(Parser, TopValue, TopInt - 1, FALSE); break; case TokenUnaryNot: ResultInt = !TopInt; break; case TokenUnaryExor: ResultInt = ~TopInt; break; default: ProgramFail(Parser, "invalid operation"); break; } AssumptionExpressionPushLongLong(Parser, StackTop, ResultInt); } else if (TopValue->Typ->Base == TypePointer) { /* pointer prefix arithmetic */ int Size = TypeSize(TopValue->Typ->FromType, 0, TRUE); Value *StackValue; void *ResultPtr; if (TopValue->Val->Pointer == nullptr) ProgramFail(Parser, "invalid use of a nullptr pointer"); if (!TopValue->IsLValue) ProgramFail(Parser, "can't assign to this"); switch (Op) { case TokenIncrement: TopValue->Val->Pointer = (void *)((char *)TopValue->Val->Pointer + Size); break; case TokenDecrement: TopValue->Val->Pointer = (void *)((char *)TopValue->Val->Pointer - Size); break; default: ProgramFail(Parser, "invalid operation"); break; } ResultPtr = TopValue->Val->Pointer; StackValue = AssumptionExpressionStackPushValueByType(Parser, StackTop, TopValue->Typ); StackValue->Val->Pointer = ResultPtr; } else ProgramFail(Parser, "invalid operation"); break; } } /* evaluate a postfix operator */ void AssumptionExpressionPostfixOperator(struct ParseState *Parser, struct ExpressionStack **StackTop, enum LexToken Op, Value *TopValue) { debugff("ExpressionPostfixOperator()\n"); #ifndef NO_FP if (TopValue->Typ->Base == TypeDouble) { /* floating point prefix arithmetic */ double ResultFP = 0.0; switch (Op) { case TokenIncrement: ResultFP = AssignFP(Parser, TopValue, TopValue->Val->Double + 1); break; case TokenDecrement: ResultFP = AssignFP(Parser, TopValue, TopValue->Val->Double - 1); break; default: ProgramFail(Parser, "invalid operation"); break; } AssumptionExpressionPushDouble(Parser, StackTop, ResultFP); } else #endif if (IS_NUMERIC_COERCIBLE(TopValue) && !IS_UNSIGNED(TopValue)) { long ResultInt = 0; long TopInt = CoerceInteger(TopValue); switch (Op) { case TokenIncrement: ResultInt = AssignInt(Parser, TopValue, TopInt + 1, TRUE); break; case TokenDecrement: ResultInt = AssignInt(Parser, TopValue, TopInt - 1, TRUE); break; case TokenRightSquareBracket: ProgramFail(Parser, "not supported"); break; /* XXX */ case TokenCloseBracket: ProgramFail(Parser, "not supported"); break; /* XXX */ default: ProgramFail(Parser, "invalid operation"); break; } AssumptionExpressionPushInt(Parser, StackTop, ResultInt); } else if (IS_NUMERIC_COERCIBLE(TopValue)) { long long ResultInt = 0; long long TopInt = CoerceLongLong(TopValue); switch (Op) { case TokenIncrement: ResultInt = AssignLongLong(Parser, TopValue, TopInt + 1, TRUE); break; case TokenDecrement: ResultInt = AssignLongLong(Parser, TopValue, TopInt - 1, TRUE); break; case TokenRightSquareBracket: ProgramFail(Parser, "not supported"); break; /* XXX */ case TokenCloseBracket: ProgramFail(Parser, "not supported"); break; /* XXX */ default: ProgramFail(Parser, "invalid operation"); break; } AssumptionExpressionPushLongLong(Parser, StackTop, ResultInt); } else if (TopValue->Typ->Base == TypePointer) { /* pointer postfix arithmetic */ int Size = TypeSize(TopValue->Typ->FromType, 0, TRUE); Value *StackValue; void *OrigPointer = TopValue->Val->Pointer; if (TopValue->Val->Pointer == nullptr) ProgramFail(Parser, "invalid use of a nullptr pointer"); if (!TopValue->IsLValue) ProgramFail(Parser, "can't assign to this"); switch (Op) { case TokenIncrement: TopValue->Val->Pointer = (void *)((char *)TopValue->Val->Pointer + Size); break; case TokenDecrement: TopValue->Val->Pointer = (void *)((char *)TopValue->Val->Pointer - Size); break; default: ProgramFail(Parser, "invalid operation"); break; } StackValue = AssumptionExpressionStackPushValueByType(Parser, StackTop, TopValue->Typ); StackValue->Val->Pointer = OrigPointer; } else ProgramFail(Parser, "invalid operation"); } void ResolvedVariable(struct ParseState *Parser, const char *Identifier, Value *VariableValue) { auto * vl = static_cast<ValueList *>(malloc(sizeof(ValueList))); vl->Identifier = Identifier; vl->Next = Parser->ResolvedNonDetVars; Parser->ResolvedNonDetVars = vl; VariableValue->Typ = TypeGetDeterministic(Parser, VariableValue->Typ); } /* evaluate an infix operator */ void AssumptionExpressionInfixOperator(struct ParseState *Parser, struct ExpressionStack **StackTop, enum LexToken Op, Value *BottomValue, Value *TopValue) { long ResultInt = 0; long long ResultLLInt = 0; Value *StackValue; void *Pointer; debugff("ExpressionInfixOperator()\n"); if (BottomValue == nullptr || TopValue == nullptr) ProgramFail(Parser, "invalid expression"); if (BottomValue->Val == nullptr || TopValue->Val == nullptr){ AssumptionExpressionPushLongLong(Parser, StackTop, 0); return; } if (Op == TokenLeftSquareBracket) { /* array index */ int ArrayIndex; Value *Result = nullptr; if (!IS_NUMERIC_COERCIBLE(TopValue)) ProgramFail(Parser, "array index must be an integer"); ArrayIndex = CoerceLongLong(TopValue); // set nondet value for BottomValue when it is a nondet array if(BottomValue->Typ->NDList != NULL) { BottomValue->Typ->IsNonDet = getNonDetListElement(BottomValue->Typ->NDList, ArrayIndex); } /* make the array element result */ switch (BottomValue->Typ->Base) { case TypeArray: Result = VariableAllocValueFromExistingData(Parser, TypeIsNonDeterministic(BottomValue->Typ) ? TypeGetNonDeterministic(Parser, BottomValue->Typ->FromType) : BottomValue->Typ->FromType, (union AnyValue *) ( &BottomValue->Val->ArrayMem[0] + TypeSize(BottomValue->Typ, ArrayIndex, TRUE)), BottomValue->IsLValue, BottomValue->LValueFrom, nullptr); break; case TypePointer: Result = VariableAllocValueFromExistingData(Parser, BottomValue->Typ->FromType, (union AnyValue *) ( (char *) BottomValue->Val->Pointer + TypeSize(BottomValue->Typ->FromType, 0, TRUE) * ArrayIndex), BottomValue->IsLValue, BottomValue->LValueFrom, nullptr); break; default: ProgramFail(Parser, "this %t is not an array", BottomValue->Typ); } /* push new value node, no value set yet */ AssumptionExpressionStackPushValueNode(Parser, StackTop, Result); } else if (Op == TokenQuestionMark) AssumptionExpressionQuestionMarkOperator(Parser, StackTop, TopValue, BottomValue); else if (Op == TokenColon) AssumptionExpressionColonOperator(Parser, StackTop, TopValue, BottomValue); #ifndef NO_FP else if ( (IS_FP(TopValue) && IS_FP(BottomValue)) || (IS_FP(TopValue) && IS_NUMERIC_COERCIBLE(BottomValue)) || (IS_NUMERIC_COERCIBLE(TopValue) && IS_FP(BottomValue)) ) { /* floating point infix arithmetic */ int ResultIsInt = FALSE; double ResultFP = 0.0; if (TypeIsNonDeterministic(TopValue->Typ) != TypeIsNonDeterministic(BottomValue->Typ)) { /* one of the values is nondet */ Value *NonDetValue = TypeIsNonDeterministic(TopValue->Typ) ? TopValue : BottomValue; char * Identifier = NonDetValue->VarIdentifier; /* integer nondet resolution */ double AssignedDouble = TypeIsNonDeterministic(TopValue->Typ) ? (BottomValue->Typ == &Parser->pc->DoubleType) ? BottomValue->Val->Double : (double) CoerceLongLong( BottomValue) : (TopValue->Typ == &Parser->pc->DoubleType) ? TopValue->Val->Double : (double) CoerceLongLong( TopValue); if (NonDetValue->IsLValue && NonDetValue->LValueFrom != nullptr && NonDetValue->LValueFrom->Typ->Base != TypeArray) NonDetValue = NonDetValue->LValueFrom; if (IS_FP(NonDetValue)) { ResultFP = AssignFP(Parser, NonDetValue, AssignedDouble); } else { ResultInt = AssignLongLong(Parser, NonDetValue, (long long) (AssignedDouble), FALSE); ResultIsInt = TRUE; } switch (Op) { case TokenAssign: case TokenEqual: ResultInt = 1; ResultIsInt = TRUE; break; default: ProgramFailWithExitCode(Parser, 247,"unsupported operation for nondet resolution"); break; } ResolvedVariable(Parser, Identifier, NonDetValue); } else { double TopFP = (IS_FP(TopValue)) ? CoerceDouble(TopValue) : (double) CoerceLongLong(TopValue); double BottomFP = (IS_FP(BottomValue)) ? CoerceDouble(BottomValue) : (double) CoerceLongLong(BottomValue); switch (Op) { case TokenAssign: ASSIGN_FP_OR_INT(TopFP); break; case TokenAddAssign: ASSIGN_FP_OR_INT(BottomFP + TopFP); break; case TokenSubtractAssign: ASSIGN_FP_OR_INT(BottomFP - TopFP); break; case TokenMultiplyAssign: ASSIGN_FP_OR_INT(BottomFP * TopFP); break; case TokenDivideAssign: ASSIGN_FP_OR_INT(BottomFP / TopFP); break; case TokenEqual: ResultInt = BottomFP == TopFP; ResultIsInt = TRUE; if (isnan(TopFP) || isnan(BottomFP)) ResultInt = isnan(TopFP) == isnan(BottomFP); break; case TokenNotEqual: ResultInt = BottomFP != TopFP; ResultIsInt = TRUE; break; case TokenLessThan: ResultInt = BottomFP < TopFP; ResultIsInt = TRUE; break; case TokenGreaterThan: ResultInt = BottomFP > TopFP; ResultIsInt = TRUE; break; case TokenLessEqual: ResultInt = BottomFP <= TopFP; ResultIsInt = TRUE; break; case TokenGreaterEqual: ResultInt = BottomFP >= TopFP; ResultIsInt = TRUE; break; case TokenPlus: ResultFP = BottomFP + TopFP; break; case TokenMinus: ResultFP = BottomFP - TopFP; break; case TokenAsterisk: ResultFP = BottomFP * TopFP; break; case TokenSlash: ResultFP = BottomFP / TopFP; break; default: ProgramFail(Parser, "invalid operation"); break; } } if (ResultIsInt) AssumptionExpressionPushLongLong(Parser, StackTop, ResultInt); else AssumptionExpressionPushDouble(Parser, StackTop, ResultFP); } #endif else if (IS_NUMERIC_COERCIBLE(TopValue) && IS_NUMERIC_COERCIBLE(BottomValue) && !IS_UNSIGNED(TopValue) && !IS_UNSIGNED(BottomValue)) { /* integer operation */ if (TypeIsNonDeterministic(TopValue->Typ) != TypeIsNonDeterministic(BottomValue->Typ)) { /* one of the values is nondet */ Value * NonDetValue = TypeIsNonDeterministic(TopValue->Typ) ? TopValue : BottomValue; char * Identifier = NonDetValue->VarIdentifier; /* integer nondet resolution */ long long AssignedInt = TypeIsNonDeterministic(TopValue->Typ) ? CoerceLongLong(BottomValue) : CoerceLongLong(TopValue); if (NonDetValue->IsLValue && NonDetValue->LValueFrom != nullptr && NonDetValue->LValueFrom->Typ->Base != TypeArray) NonDetValue = NonDetValue->LValueFrom; AssignLongLong(Parser, NonDetValue, AssignedInt, FALSE); switch (Op) { case TokenAssign: case TokenEqual: ResultLLInt = 1; break; default: ProgramFailWithExitCode(Parser, 247,"unsupported operation for nondet resolution"); break; } ResolvedVariable(Parser, Identifier, NonDetValue); } else { long long TopInt = CoerceLongLong(TopValue); long long BottomInt = CoerceLongLong(BottomValue); switch (Op) { case TokenAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, TopInt, FALSE); break; case TokenAddAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt + TopInt, FALSE); break; case TokenSubtractAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt - TopInt, FALSE); break; case TokenMultiplyAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt * TopInt, FALSE); break; case TokenDivideAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt / TopInt, FALSE); break; #ifndef NO_MODULUS case TokenModulusAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt % TopInt, FALSE); break; #endif case TokenShiftLeftAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt << TopInt, FALSE); break; case TokenShiftRightAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt >> TopInt, FALSE); break; case TokenArithmeticAndAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt & TopInt, FALSE); break; case TokenArithmeticOrAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt | TopInt, FALSE); break; case TokenArithmeticExorAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt ^ TopInt, FALSE); break; case TokenLogicalOr: ResultLLInt = BottomInt || TopInt; break; case TokenLogicalAnd: ResultLLInt = BottomInt && TopInt; break; case TokenArithmeticOr: ResultLLInt = BottomInt | TopInt; break; case TokenArithmeticExor: ResultLLInt = BottomInt ^ TopInt; break; case TokenAmpersand: ResultLLInt = BottomInt & TopInt; break; case TokenEqual: ResultLLInt = BottomInt == TopInt; break; case TokenNotEqual: ResultLLInt = BottomInt != TopInt; break; case TokenLessThan: ResultLLInt = BottomInt < TopInt; break; case TokenGreaterThan: ResultLLInt = BottomInt > TopInt; break; case TokenLessEqual: ResultLLInt = BottomInt <= TopInt; break; case TokenGreaterEqual: ResultLLInt = BottomInt >= TopInt; break; case TokenShiftLeft: ResultLLInt = BottomInt << TopInt; break; case TokenShiftRight: ResultLLInt = BottomInt >> TopInt; break; case TokenPlus: ResultLLInt = BottomInt + TopInt; break; case TokenMinus: ResultLLInt = BottomInt - TopInt; break; case TokenAsterisk: ResultLLInt = BottomInt * TopInt; break; case TokenSlash: ResultLLInt = BottomInt / TopInt; break; #ifndef NO_MODULUS case TokenModulus: ResultLLInt = BottomInt % TopInt; break; #endif default: ProgramFail(Parser, "invalid operation"); break; } } if (TopValue->Typ->Base == TypeLongLong || TopValue->Typ->Base == TypeUnsignedLongLong || BottomValue->Typ->Base == TypeLongLong || BottomValue->Typ->Base == TypeUnsignedLongLong){ AssumptionExpressionPushLongLong(Parser, StackTop, ResultLLInt); } else { AssumptionExpressionPushInt(Parser, StackTop, ResultLLInt); } } else if (IS_NUMERIC_COERCIBLE(TopValue) && IS_NUMERIC_COERCIBLE(BottomValue)) { /* integer operation */ if (TypeIsNonDeterministic(TopValue->Typ) != TypeIsNonDeterministic(BottomValue->Typ)) { /* one of the values is nondet */ Value * NonDetValue = TypeIsNonDeterministic(TopValue->Typ) ? TopValue : BottomValue; char * Identifier = NonDetValue->VarIdentifier; /* integer nondet resolution */ unsigned long long AssignedInt = TypeIsNonDeterministic(TopValue->Typ) ? CoerceUnsignedLongLong( BottomValue) : CoerceUnsignedLongLong(TopValue); if (NonDetValue->IsLValue && NonDetValue->LValueFrom != nullptr && NonDetValue->LValueFrom->Typ->Base != TypeArray) NonDetValue = NonDetValue->LValueFrom; AssignLongLong(Parser, NonDetValue, AssignedInt, FALSE); switch (Op) { case TokenAssign: case TokenEqual: ResultLLInt = 1; break; default: ProgramFailWithExitCode(Parser, 247,"unsupported operation for nondet resolution"); break; } ResolvedVariable(Parser, Identifier, NonDetValue); } else { unsigned long long TopInt = CoerceUnsignedLongLong(TopValue); unsigned long long BottomInt = CoerceUnsignedLongLong(BottomValue); switch (Op) { case TokenAssign: ResultLLInt = BottomInt == TopInt; break; case TokenAddAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt + TopInt, FALSE); break; case TokenSubtractAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt - TopInt, FALSE); break; case TokenMultiplyAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt * TopInt, FALSE); break; case TokenDivideAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt / TopInt, FALSE); break; #ifndef NO_MODULUS case TokenModulusAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt % TopInt, FALSE); break; #endif case TokenShiftLeftAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt << TopInt, FALSE); break; case TokenShiftRightAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt >> TopInt, FALSE); break; case TokenArithmeticAndAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt & TopInt, FALSE); break; case TokenArithmeticOrAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt | TopInt, FALSE); break; case TokenArithmeticExorAssign: ResultLLInt = AssignLongLong(Parser, BottomValue, BottomInt ^ TopInt, FALSE); break; case TokenLogicalOr: ResultLLInt = BottomInt || TopInt; break; case TokenLogicalAnd: ResultLLInt = BottomInt && TopInt; break; case TokenArithmeticOr: ResultLLInt = BottomInt | TopInt; break; case TokenArithmeticExor: ResultLLInt = BottomInt ^ TopInt; break; case TokenAmpersand: ResultLLInt = BottomInt & TopInt; break; case TokenEqual: ResultLLInt = BottomInt == TopInt; break; case TokenNotEqual: ResultLLInt = BottomInt != TopInt; break; case TokenLessThan: ResultLLInt = BottomInt < TopInt; break; case TokenGreaterThan: ResultLLInt = BottomInt > TopInt; break; case TokenLessEqual: ResultLLInt = BottomInt <= TopInt; break; case TokenGreaterEqual: ResultLLInt = BottomInt >= TopInt; break; case TokenShiftLeft: ResultLLInt = BottomInt << TopInt; break; case TokenShiftRight: ResultLLInt = BottomInt >> TopInt; break; case TokenPlus: ResultLLInt = BottomInt + TopInt; break; case TokenMinus: ResultLLInt = BottomInt - TopInt; break; case TokenAsterisk: ResultLLInt = BottomInt * TopInt; break; case TokenSlash: ResultLLInt = BottomInt / TopInt; break; #ifndef NO_MODULUS case TokenModulus: ResultLLInt = BottomInt % TopInt; break; #endif default: ProgramFail(Parser, "invalid operation"); break; } } if (TopValue->Typ->Base == TypeLongLong || TopValue->Typ->Base == TypeUnsignedLongLong || BottomValue->Typ->Base == TypeLongLong || BottomValue->Typ->Base == TypeUnsignedLongLong){ AssumptionExpressionPushUnsignedLongLong(Parser, StackTop, ResultLLInt); } else { AssumptionExpressionPushUnsignedInt(Parser, StackTop, ResultLLInt); } } else if (BottomValue->Typ->Base == TypeFunctionPtr && TopValue->Typ->Base == TypeFunctionPtr) { AssumptionExpressionPushLongLong(Parser, StackTop, BottomValue->Val->Identifier == TopValue->Val->Identifier); } else if (BottomValue->Typ->Base == TypePointer && IS_NUMERIC_COERCIBLE(TopValue)) { /* pointer/integer infix arithmetic */ long long TopInt = CoerceInteger(TopValue); if (Op == TokenEqual || Op == TokenNotEqual) { /* comparison to a nullptr pointer */ if (TopInt != 0) ProgramFail(Parser, "invalid operation"); if (Op == TokenEqual) AssumptionExpressionPushInt(Parser, StackTop, BottomValue->Val->Pointer == nullptr); else AssumptionExpressionPushInt(Parser, StackTop, BottomValue->Val->Pointer != nullptr); } else if (Op == TokenPlus || Op == TokenMinus) { /* pointer arithmetic */ int Size = TypeSize(BottomValue->Typ->FromType, 0, TRUE); Pointer = BottomValue->Val->Pointer; if (Pointer == nullptr) ProgramFail(Parser, "invalid use of a nullptr pointer"); if (Op == TokenPlus) Pointer = (void *)((char *)Pointer + TopInt * Size); else Pointer = (void *)((char *)Pointer - TopInt * Size); StackValue = AssumptionExpressionStackPushValueByType(Parser, StackTop, BottomValue->Typ); StackValue->Val->Pointer = Pointer; } else if (Op == TokenAssign && TopInt == 0) { /* assign a nullptr pointer */ HeapUnpopStack(Parser->pc, sizeof(Value)); AssumptionExpressionAssign(Parser, BottomValue, TopValue, FALSE, nullptr, 0, FALSE); AssumptionExpressionStackPushValueNode(Parser, StackTop, BottomValue); } else if (Op == TokenAddAssign || Op == TokenSubtractAssign) { /* pointer arithmetic */ int Size = TypeSize(BottomValue->Typ->FromType, 0, TRUE); Pointer = BottomValue->Val->Pointer; if (Pointer == nullptr) ProgramFail(Parser, "invalid use of a nullptr pointer"); if (Op == TokenAddAssign) Pointer = (void *)((char *)Pointer + TopInt * Size); else Pointer = (void *)((char *)Pointer - TopInt * Size); HeapUnpopStack(Parser->pc, sizeof(Value)); BottomValue->Val->Pointer = Pointer; AssumptionExpressionStackPushValueNode(Parser, StackTop, BottomValue); } else ProgramFail(Parser, "invalid operation"); } else if (BottomValue->Typ->Base == TypeFunctionPtr && IS_NUMERIC_COERCIBLE(TopValue)) { /* pointer/integer infix arithmetic */ long long TopInt = CoerceLongLong(TopValue); if (Op == TokenEqual || Op == TokenNotEqual) { /* comparison to a nullptr pointer */ if (TopInt != 0) ProgramFail(Parser, "invalid operation"); if (Op == TokenEqual) AssumptionExpressionPushLongLong(Parser, StackTop, BottomValue->Val->Identifier == nullptr); else AssumptionExpressionPushLongLong(Parser, StackTop, BottomValue->Val->Identifier != nullptr); } else if (Op == TokenAssign && TopInt == 0) { /* checking if func ptr is a nullptr pointer (allow usage of * assigns instead of equal) */ HeapUnpopStack(Parser->pc, sizeof(Value)); AssumptionExpressionPushLongLong(Parser, StackTop, BottomValue->Val->Identifier == nullptr); } else ProgramFail(Parser, "invalid operation"); } else if (BottomValue->Typ->Base == TypePointer && TopValue->Typ->Base == TypePointer && Op != TokenAssign) { /* pointer/pointer operations */ char *TopLoc = (char *)TopValue->Val->Pointer; char *BottomLoc = (char *)BottomValue->Val->Pointer; switch (Op) { case TokenEqual: AssumptionExpressionPushInt(Parser, StackTop, BottomLoc == TopLoc); break; case TokenNotEqual: AssumptionExpressionPushInt(Parser, StackTop, BottomLoc != TopLoc); break; case TokenMinus: AssumptionExpressionPushInt(Parser, StackTop, BottomLoc - TopLoc); break; default: ProgramFail(Parser, "invalid operation"); break; } } else if (Op == TokenAssign) { /* assign a non-numeric type */ HeapUnpopStack(Parser->pc, MEM_ALIGN(sizeof(Value))); /* XXX - possible bug if lvalue is a temp value and takes more than sizeof(Value) */ AssumptionExpressionAssign(Parser, BottomValue, TopValue, FALSE, nullptr, 0, FALSE); if (BottomValue->Typ->Base == TypeFunctionPtr) { AssumptionExpressionPushInt(Parser, StackTop, !strcmp(BottomValue->Val->Identifier, TopValue->Val->Identifier)); } else { AssumptionExpressionStackPushValueNode(Parser, StackTop, BottomValue); } } else if (Op == TokenCast) { /* cast a value to a different type */ /* XXX - possible bug if the destination type takes more than sizeof(Value) + sizeof(struct ValueType *) */ Value *ValueLoc = AssumptionExpressionStackPushValueByType(Parser, StackTop, BottomValue->Val->Typ); AssumptionExpressionAssign(Parser, ValueLoc, TopValue, TRUE, nullptr, 0, TRUE); } else if (Op == TokenOpenBracket){ // called a function AssumptionExpressionStackPushValue(Parser, StackTop, TopValue); } else ProgramFail(Parser, "invalid operation"); } /* take the contents of the expression stack and compute the top until there's nothing greater than the given precedence */ void AssumptionExpressionStackCollapse(struct ParseState *Parser, struct ExpressionStack **StackTop, int Precedence, int *IgnorePrecedence) { int FoundPrecedence = Precedence; Value *TopValue; Value *BottomValue; struct ExpressionStack *TopStackNode = *StackTop; struct ExpressionStack *TopOperatorNode; debugff("AssumptionExpressionStackCollapse(%d):\n", Precedence); #ifdef DEBUG_EXPRESSIONS ExpressionStackShow(Parser->pc, *StackTop); #endif while (TopStackNode != nullptr && TopStackNode->Next != nullptr && FoundPrecedence >= Precedence) { /* find the top operator on the stack */ if (TopStackNode->Order == OrderNone) TopOperatorNode = TopStackNode->Next; else TopOperatorNode = TopStackNode; FoundPrecedence = TopOperatorNode->Precedence; /* does it have a high enough precedence? */ if (FoundPrecedence >= Precedence && TopOperatorNode != nullptr) { /* execute this operator */ switch (TopOperatorNode->Order) { case OrderPrefix: /* prefix evaluation */ debugff("prefix evaluation\n"); TopValue = TopStackNode->Val; /* pop the value and then the prefix operator - assume they'll still be there until we're done */ HeapPopStack(Parser->pc, nullptr, sizeof(struct ExpressionStack) + MEM_ALIGN(sizeof(Value)) + TypeStackSizeValue(TopValue)); HeapPopStack(Parser->pc, TopOperatorNode, sizeof(struct ExpressionStack)); *StackTop = TopOperatorNode->Next; /* do the prefix operation */ if (Parser->Mode == RunModeRun /* && FoundPrecedence < *IgnorePrecedence */) { /* run the operator */ AssumptionExpressionPrefixOperator(Parser, StackTop, TopOperatorNode->Op, TopValue); } else { /* we're not running it so just return 0 */ AssumptionExpressionPushLongLong(Parser, StackTop, 0); } break; case OrderPostfix: /* postfix evaluation */ debugff("postfix evaluation\n"); TopValue = TopStackNode->Next->Val; /* pop the postfix operator and then the value - assume they'll still be there until we're done */ HeapPopStack(Parser->pc, nullptr, sizeof(struct ExpressionStack)); HeapPopStack(Parser->pc, TopValue, sizeof(struct ExpressionStack) + MEM_ALIGN(sizeof(Value)) + TypeStackSizeValue(TopValue)); *StackTop = TopStackNode->Next->Next; /* do the postfix operation */ if (Parser->Mode == RunModeRun /* && FoundPrecedence < *IgnorePrecedence */) { /* run the operator */ AssumptionExpressionPostfixOperator(Parser, StackTop, TopOperatorNode->Op, TopValue); } else { /* we're not running it so just return 0 */ AssumptionExpressionPushLongLong(Parser, StackTop, 0); } break; case OrderInfix: /* infix evaluation */ debugff("infix evaluation\n"); TopValue = TopStackNode->Val; if (TopValue != nullptr) { BottomValue = TopOperatorNode->Next->Val; /* pop a value, the operator and another value - assume they'll still be there until we're done */ HeapPopStack(Parser->pc, nullptr, sizeof(struct ExpressionStack) + MEM_ALIGN(sizeof(Value)) + TypeStackSizeValue(TopValue)); HeapPopStack(Parser->pc, nullptr, sizeof(struct ExpressionStack)); HeapPopStack(Parser->pc, BottomValue, sizeof(struct ExpressionStack) + MEM_ALIGN(sizeof(Value)) + TypeStackSizeValue(BottomValue)); *StackTop = TopOperatorNode->Next->Next; /* do the infix operation */ if (Parser->Mode == RunModeRun /* && FoundPrecedence <= *IgnorePrecedence */) { /* run the operator */ AssumptionExpressionInfixOperator(Parser, StackTop, TopOperatorNode->Op, BottomValue, TopValue); } else { /* we're not running it so just return 0 */ AssumptionExpressionPushLongLong(Parser, StackTop, 0); } } else FoundPrecedence = -1; break; case OrderNone: /* this should never happen */ assert(TopOperatorNode->Order != OrderNone); break; } /* if we've returned above the ignored precedence level turn ignoring off */ if (FoundPrecedence <= *IgnorePrecedence) *IgnorePrecedence = DEEP_PRECEDENCE; } #ifdef DEBUG_EXPRESSIONS ExpressionStackShow(Parser->pc, *StackTop); #endif TopStackNode = *StackTop; } debugff("AssumptionExpressionStackCollapse() finished\n"); #ifdef DEBUG_EXPRESSIONS ExpressionStackShow(Parser->pc, *StackTop); #endif } /* push an operator on to the expression stack */ void AssumptionExpressionStackPushOperator(struct ParseState *Parser, struct ExpressionStack **StackTop, enum OperatorOrder Order, enum LexToken Token, int Precedence) { auto *StackNode = static_cast<ExpressionStack *>(VariableAlloc(Parser->pc, Parser, sizeof(struct ExpressionStack), FALSE)); StackNode->Next = *StackTop; StackNode->Order = Order; StackNode->Op = Token; StackNode->Precedence = Precedence; *StackTop = StackNode; // debugff("AssumptionExpressionStackPushOperator()\n"); #ifdef FANCY_ERROR_MESSAGES StackNode->Line = Parser->Line; StackNode->CharacterPos = Parser->CharacterPos; #endif #ifdef DEBUG_EXPRESSIONS ExpressionStackShow(Parser->pc, *StackTop); #endif } /* do the '.' and '->' operators */ void AssumptionExpressionGetStructElement(struct ParseState *Parser, struct ExpressionStack **StackTop, enum LexToken Token) { Value *Ident; /* get the identifier following the '.' or '->' */ if (LexGetToken(Parser, &Ident, TRUE) != TokenIdentifier) ProgramFail(Parser, "need an structure or union member after '%s'", (Token == TokenDot) ? "." : "->"); if (Parser->Mode == RunModeRun) { /* look up the struct element */ Value *ParamVal = (*StackTop)->Val; Value *StructVal = ParamVal; struct ValueType *StructType = ParamVal->Typ; char *DerefDataLoc = (char *)ParamVal->Val; Value *MemberValue = nullptr; Value *Result; /* if we're doing '->' dereference the struct pointer first */ if (Token == TokenArrow) DerefDataLoc = static_cast<char *>(VariableDereferencePointer(Parser, ParamVal, &StructVal, nullptr, &StructType, nullptr)); if (DerefDataLoc == nullptr) ProgramFail(Parser, "the struct hasn't been initialized yet"); if (StructType->Base != TypeStruct && StructType->Base != TypeUnion) ProgramFail(Parser, "can't use '%s' on something that's not a struct or union %s : it's a %t", (Token == TokenDot) ? "." : "->", (Token == TokenArrow) ? "pointer" : "", ParamVal->Typ); if (!TableGet(StructType->Members, Ident->Val->Identifier, &MemberValue, nullptr, nullptr, nullptr)) ProgramFail(Parser, "doesn't have a member called '%s'", Ident->Val->Identifier); /* pop the value - assume it'll still be there until we're done */ HeapPopStack(Parser->pc, ParamVal, sizeof(struct ExpressionStack) + MEM_ALIGN(sizeof(Value)) + TypeStackSizeValue(StructVal)); *StackTop = (*StackTop)->Next; /* make the result value for this member only */ Result = VariableAllocValueFromExistingData(Parser, MemberValue->Typ, (AnyValue *) (DerefDataLoc + MemberValue->Val->Integer), TRUE, (StructVal != nullptr) ? StructVal->LValueFrom : nullptr, nullptr); AssumptionExpressionStackPushValueNode(Parser, StackTop, Result); } } /* parse an expression with operator precedence */ int AssumptionExpressionParse(struct ParseState *Parser, Value **Result) { Value *LexValue; int PrefixState = TRUE; int Done = FALSE; int BracketPrecedence = 0; int LocalPrecedence; int Precedence = 0; int IgnorePrecedence = DEEP_PRECEDENCE; struct ExpressionStack *StackTop = nullptr; int TernaryDepth = 0; // debugff("AssumptionExpressionParse():\n"); do { struct ParseState PreState; enum LexToken Token; ParserCopy(&PreState, Parser); Token = LexGetToken(Parser, &LexValue, TRUE); /* if we're debugging, check for a breakpoint */ if (Parser->DebugMode && Parser->Mode == RunModeRun) { DebugCheckStatement(Parser); } if ( ( ( (int)Token > TokenComma && (int)Token <= (int)TokenOpenBracket) || (Token == TokenCloseBracket && BracketPrecedence != 0)) && (Token != TokenColon || TernaryDepth > 0) ) { /* it's an operator with precedence */ if (PrefixState) { /* expect a prefix operator */ if (OperatorPrecedence[(int)Token].PrefixPrecedence == 0) ProgramFail(Parser, "operator not expected here"); LocalPrecedence = OperatorPrecedence[(int)Token].PrefixPrecedence; Precedence = BracketPrecedence + LocalPrecedence; if (Token == TokenOpenBracket) { /* it's either a new bracket level or a cast */ enum LexToken BracketToken = LexGetToken(Parser, &LexValue, FALSE); if (AssumptionIsTypeToken(Parser, BracketToken, LexValue) && (StackTop == nullptr || StackTop->Op != TokenSizeof) ) { /* it's a cast - get the new type */ struct ValueType *CastType; char *CastIdentifier; Value *CastTypeValue; TypeParse(Parser, &CastType, &CastIdentifier, nullptr, nullptr, 0); if (LexGetToken(Parser, &LexValue, TRUE) != TokenCloseBracket) ProgramFail(Parser, "brackets not closed"); /* scan and collapse the stack to the precedence of this infix cast operator, then push */ Precedence = BracketPrecedence + OperatorPrecedence[(int)TokenCast].PrefixPrecedence; AssumptionExpressionStackCollapse(Parser, &StackTop, Precedence+1, &IgnorePrecedence); CastTypeValue = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->TypeType, FALSE, nullptr, FALSE); CastTypeValue->Val->Typ = CastType; AssumptionExpressionStackPushValueNode(Parser, &StackTop, CastTypeValue); AssumptionExpressionStackPushOperator(Parser, &StackTop, OrderInfix, TokenCast, Precedence); } else { /* boost the bracket operator precedence */ BracketPrecedence += BRACKET_PRECEDENCE; } } else { /* scan and collapse the stack to the precedence of this operator, then push */ /* take some extra care for double prefix operators, e.g. x = - -5, or x = **y */ int NextToken = LexGetToken(Parser, nullptr, FALSE); int TempPrecedenceBoost = 0; if (NextToken > TokenComma && NextToken < TokenOpenBracket) { int NextPrecedence = OperatorPrecedence[(int)NextToken].PrefixPrecedence; /* two prefix operators with equal precedence? make sure the innermost one runs first */ /* FIXME - probably not correct, but can't find a test that fails at this */ if (LocalPrecedence == NextPrecedence) TempPrecedenceBoost = -1; } AssumptionExpressionStackCollapse(Parser, &StackTop, Precedence, &IgnorePrecedence); AssumptionExpressionStackPushOperator(Parser, &StackTop, OrderPrefix, Token, Precedence + TempPrecedenceBoost); } } else { /* expect an infix or postfix operator */ if (OperatorPrecedence[(int)Token].PostfixPrecedence != 0) { switch (Token) { case TokenCloseBracket: case TokenRightSquareBracket: if (BracketPrecedence == 0) { /* assume this bracket is after the end of the expression */ ParserCopy(Parser, &PreState); Done = TRUE; } else { /* collapse to the bracket precedence */ AssumptionExpressionStackCollapse(Parser, &StackTop, BracketPrecedence, &IgnorePrecedence); BracketPrecedence -= BRACKET_PRECEDENCE; } break; default: /* scan and collapse the stack to the precedence of this operator, then push */ Precedence = BracketPrecedence + OperatorPrecedence[(int)Token].PostfixPrecedence; AssumptionExpressionStackCollapse(Parser, &StackTop, Precedence, &IgnorePrecedence); AssumptionExpressionStackPushOperator(Parser, &StackTop, OrderPostfix, Token, Precedence); break; } } else if (OperatorPrecedence[(int)Token].InfixPrecedence != 0) { /* scan and collapse the stack, then push */ Precedence = BracketPrecedence + OperatorPrecedence[(int)Token].InfixPrecedence; /* for right to left order, only go down to the next higher precedence so we evaluate it in reverse order */ /* for left to right order, collapse down to this precedence so we evaluate it in forward order */ if (IS_LEFT_TO_RIGHT(OperatorPrecedence[(int)Token].InfixPrecedence)) AssumptionExpressionStackCollapse(Parser, &StackTop, Precedence, &IgnorePrecedence); else AssumptionExpressionStackCollapse(Parser, &StackTop, Precedence+1, &IgnorePrecedence); if (Token == TokenDot || Token == TokenArrow) { AssumptionExpressionGetStructElement(Parser, &StackTop, Token); /* this operator is followed by a struct element so handle it as a special case */ } else { /* if it's a && or || operator we may not need to evaluate the right hand side of the expression */ if ( (Token == TokenLogicalOr || Token == TokenLogicalAnd) && IS_NUMERIC_COERCIBLE(StackTop->Val)) { long long LHSInt = CoerceLongLong(StackTop->Val); if ( ( (Token == TokenLogicalOr && LHSInt) || (Token == TokenLogicalAnd && !LHSInt) ) && (IgnorePrecedence > Precedence) ) IgnorePrecedence = Precedence; } /* push the operator on the stack */ AssumptionExpressionStackPushOperator(Parser, &StackTop, OrderInfix, Token, Precedence); PrefixState = TRUE; switch (Token) { case TokenQuestionMark: TernaryDepth++; break; case TokenColon: TernaryDepth--; break; default: break; } } /* treat an open square bracket as an infix array index operator followed by an open bracket */ if (Token == TokenLeftSquareBracket) { /* boost the bracket operator precedence, then push */ BracketPrecedence += BRACKET_PRECEDENCE; } } else ProgramFail(Parser, "operator not expected here"); } } else if (Token == TokenIdentifier) { /* it's a variable, function or a macro */ if (!PrefixState) ProgramFail(Parser, "identifier not expected here"); if (LexGetToken(Parser, nullptr, FALSE) == TokenOpenBracket) { AssumptionExpressionParseFunctionCall(Parser, &StackTop, LexValue->Val->Identifier, Parser->Mode == RunModeRun && Precedence < IgnorePrecedence); } else { if (Parser->Mode == RunModeRun /* && Precedence < IgnorePrecedence */) { Value *VariableValue = nullptr; VariableGet(Parser->pc, Parser, LexValue->Val->Identifier, &VariableValue); if (VariableValue->Typ->Base == TypeMacro) { /* evaluate a macro as a kind of simple subroutine */ struct ParseState MacroParser; Value *MacroResult; ParserCopy(&MacroParser, &VariableValue->Val->MacroDef.Body); MacroParser.Mode = Parser->Mode; if (VariableValue->Val->MacroDef.NumParams != 0) ProgramFail(&MacroParser, "macro arguments missing"); if (!AssumptionExpressionParse(&MacroParser, &MacroResult) || LexGetToken(&MacroParser, nullptr, FALSE) != TokenEndOfFunction) ProgramFail(&MacroParser, "expression expected"); AssumptionExpressionStackPushValueNode(Parser, &StackTop, MacroResult); } else if (VariableValue->Typ->Base == TypeVoid) ProgramFail(Parser, "a void value isn't much use here"); else if (VariableValue->Typ->Base == TypeFunction){ // it's a func ptr identifier Value * FPtr = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->FunctionPtrType, TRUE, FALSE, TRUE); FPtr->Val->Identifier = LexValue->Val->Identifier; AssumptionExpressionStackPushValue(Parser, &StackTop, FPtr); VariableFree(Parser->pc, FPtr); } else { /* it's a value variable */ VariableValue->VarIdentifier = LexValue->Val->Identifier; AssumptionExpressionStackPushLValue(Parser, &StackTop, VariableValue, 0); } } else /* push a dummy value */ AssumptionExpressionPushLongLong(Parser, &StackTop, 0); } /* if we've successfully ignored the RHS turn ignoring off */ if (Precedence <= IgnorePrecedence) IgnorePrecedence = DEEP_PRECEDENCE; PrefixState = FALSE; } else if ((int)Token > TokenCloseBracket && (int)Token <= TokenCharacterConstant) { /* it's a value of some sort, push it */ if (!PrefixState) ProgramFail(Parser, "value not expected here"); PrefixState = FALSE; AssumptionExpressionStackPushValue(Parser, &StackTop, LexValue); } else if (AssumptionIsTypeToken(Parser, Token, LexValue)) { /* it's a type. push it on the stack like a value. this is used in sizeof() */ struct ValueType *Typ; char *Identifier; Value *TypeValue; if (!PrefixState) ProgramFail(Parser, "type not expected here"); PrefixState = FALSE; ParserCopy(Parser, &PreState); TypeParse(Parser, &Typ, &Identifier, nullptr, nullptr, 0); TypeValue = VariableAllocValueFromType(Parser->pc, Parser, &Parser->pc->TypeType, FALSE, nullptr, FALSE); TypeValue->Val->Typ = Typ; AssumptionExpressionStackPushValueNode(Parser, &StackTop, TypeValue); } else { /* it isn't a token from an expression */ ParserCopy(Parser, &PreState); Done = TRUE; } } while (!Done); /* check that brackets have been closed */ if (BracketPrecedence > 0) ProgramFail(Parser, "brackets not closed"); /* scan and collapse the stack to precedence 0 */ AssumptionExpressionStackCollapse(Parser, &StackTop, 0, &IgnorePrecedence); /* fix up the stack and return the result if we're in run mode */ if (StackTop != nullptr) { /* all that should be left is a single value on the stack */ if (Parser->Mode == RunModeRun) { if (StackTop->Order != OrderNone || StackTop->Next != nullptr) ProgramFail(Parser, "invalid expression"); *Result = StackTop->Val; HeapPopStack(Parser->pc, StackTop, sizeof(struct ExpressionStack)); } else HeapPopStack(Parser->pc, StackTop->Val, sizeof(struct ExpressionStack) + MEM_ALIGN(sizeof(Value)) + TypeStackSizeValue(StackTop->Val)); } // debugff("AssumptionExpressionParse() done\n\n"); #ifdef DEBUG_EXPRESSIONS ExpressionStackShow(Parser->pc, StackTop); #endif return StackTop != nullptr; } /* do a parameterised macro call */ void AssumptionExpressionParseMacroCall(struct ParseState *Parser, struct ExpressionStack **StackTop, const char *MacroName, struct MacroDef *MDef) { Value *ReturnValue = nullptr; Value *Param; Value **ParamArray = nullptr; int ArgCount; enum LexToken Token; if (Parser->Mode == RunModeRun) { /* create a stack frame for this macro */ #ifndef NO_FP AssumptionExpressionStackPushValueByType(Parser, StackTop, &Parser->pc->DoubleType); /* largest return type there is */ #else AssumptionExpressionStackPushValueByType(Parser, StackTop, &Parser->pc->IntType); /* largest return type there is */ #endif ReturnValue = (*StackTop)->Val; HeapPushStackFrame(Parser->pc); ParamArray = static_cast<Value **>(HeapAllocStack(Parser->pc, sizeof(Value *) * MDef->NumParams)); if (ParamArray == nullptr) ProgramFail(Parser, "out of memory"); } else AssumptionExpressionPushLongLong(Parser, StackTop, 0); /* parse arguments */ ArgCount = 0; do { if (AssumptionExpressionParse(Parser, &Param)) { if (Parser->Mode == RunModeRun) { if (ArgCount < MDef->NumParams) ParamArray[ArgCount] = Param; else ProgramFail(Parser, "too many arguments to %s()", MacroName); } ArgCount++; Token = LexGetToken(Parser, nullptr, TRUE); if (Token != TokenComma && Token != TokenCloseBracket) ProgramFail(Parser, "comma expected"); } else { /* end of argument list? */ Token = LexGetToken(Parser, nullptr, TRUE); if (Token != TokenCloseBracket) ProgramFail(Parser, "bad argument"); } } while (Token != TokenCloseBracket); if (Parser->Mode == RunModeRun) { /* evaluate the macro */ struct ParseState MacroParser{}; int Count; Value *EvalValue; if (ArgCount < MDef->NumParams) ProgramFail(Parser, "not enough arguments to '%s'", MacroName); if (MDef->Body.Pos == nullptr) ProgramFail(Parser, "'%s' is undefined", MacroName); ParserCopy(&MacroParser, &MDef->Body); MacroParser.Mode = Parser->Mode; VariableStackFrameAdd(Parser, MacroName, 0); Parser->pc->TopStackFrame->NumParams = ArgCount; Parser->pc->TopStackFrame->ReturnValue = ReturnValue; for (Count = 0; Count < MDef->NumParams; Count++) VariableDefine(Parser->pc, Parser, MDef->ParamName[Count], ParamArray[Count], nullptr, TRUE, false); AssumptionExpressionParse(&MacroParser, &EvalValue); AssumptionExpressionAssign(Parser, ReturnValue, EvalValue, TRUE, MacroName, 0, FALSE); VariableStackFramePop(Parser); HeapPopStackFrame(Parser->pc); } } /* do a function call */ void AssumptionExpressionParseFunctionCall(struct ParseState *Parser, struct ExpressionStack **StackTop, const char *FuncName, int RunIt) { Value *ReturnValue = nullptr; Value *FuncValue = nullptr; Value *Param; Value **ParamArray = nullptr; int ArgCount; enum LexToken Token = LexGetToken(Parser, nullptr, TRUE); /* open bracket */ enum RunMode OldMode = Parser->Mode; if (RunIt) { /* get the function definition */ VariableGet(Parser->pc, Parser, FuncName, &FuncValue); if (FuncValue->Typ->Base == TypeMacro) { /* this is actually a macro, not a function */ AssumptionExpressionParseMacroCall(Parser, StackTop, FuncName, &FuncValue->Val->MacroDef); return; } if (FuncValue->Typ->Base != TypeFunction) ProgramFail(Parser, "%t is not a function - can't call", FuncValue->Typ); AssumptionExpressionStackPushValueByType(Parser, StackTop, FuncValue->Val->FuncDef.ReturnType); ReturnValue = (*StackTop)->Val; HeapPushStackFrame(Parser->pc); ParamArray = static_cast<Value **>(HeapAllocStack(Parser->pc, sizeof(Value *) * FuncValue->Val->FuncDef.NumParams)); if (ParamArray == nullptr) ProgramFail(Parser, "out of memory"); } else { AssumptionExpressionPushLongLong(Parser, StackTop, 0); Parser->Mode = RunModeSkip; } /* parse arguments */ ArgCount = 0; do { if (RunIt && ArgCount < FuncValue->Val->FuncDef.NumParams) ParamArray[ArgCount] = VariableAllocValueFromType(Parser->pc, Parser, FuncValue->Val->FuncDef.ParamType[ArgCount], FALSE, nullptr, FALSE); if (AssumptionExpressionParse(Parser, &Param)) { if (RunIt) { if (ArgCount < FuncValue->Val->FuncDef.NumParams) { AssumptionExpressionAssign(Parser, ParamArray[ArgCount], Param, TRUE, FuncName, ArgCount+1, FALSE); VariableStackPop(Parser, Param); } else { if (!FuncValue->Val->FuncDef.VarArgs) ProgramFail(Parser, "too many arguments to %s()", FuncName); } } ArgCount++; Token = LexGetToken(Parser, nullptr, TRUE); if (Token != TokenComma && Token != TokenCloseBracket) ProgramFail(Parser, "comma expected"); } else { /* end of argument list? */ Token = LexGetToken(Parser, nullptr, TRUE); if (Token != TokenCloseBracket) ProgramFail(Parser, "bad argument"); } } while (Token != TokenCloseBracket); if (RunIt) { /* run the function */ if (ArgCount < FuncValue->Val->FuncDef.NumParams) ProgramFail(Parser, "not enough arguments to '%s'", FuncName); if (FuncValue->Val->FuncDef.Intrinsic == nullptr) { /* run a user-defined function */ struct ParseState FuncParser{}; int Count; int OldScopeID = Parser->ScopeID; if (FuncValue->Val->FuncDef.Body.Pos == nullptr) ProgramFail(Parser, "'%s' is undefined", FuncName); ParserCopy(&FuncParser, &FuncValue->Val->FuncDef.Body); VariableStackFrameAdd(Parser, FuncName, FuncValue->Val->FuncDef.Intrinsic ? FuncValue->Val->FuncDef.NumParams : 0); Parser->pc->TopStackFrame->NumParams = ArgCount; Parser->pc->TopStackFrame->ReturnValue = ReturnValue; /* Function parameters should not go out of scope */ Parser->ScopeID = -1; for (Count = 0; Count < FuncValue->Val->FuncDef.NumParams; Count++) VariableDefine(Parser->pc, Parser, FuncValue->Val->FuncDef.ParamName[Count], ParamArray[Count], nullptr, TRUE, false); Parser->ScopeID = OldScopeID; if (ParseStatement(&FuncParser, TRUE) != ParseResultOk) ProgramFail(&FuncParser, "function body expected"); if (RunIt) { if (FuncParser.Mode == RunModeRun && FuncValue->Val->FuncDef.ReturnType != &Parser->pc->VoidType) { fprintf(stderr, "no value returned from a function returning "); PrintType(FuncValue->Val->FuncDef.ReturnType, stderr); fprintf(stderr, "\n"); } else if (FuncParser.Mode == RunModeGoto) ProgramFail(&FuncParser, "couldn't find goto label '%s'", FuncParser.SearchGotoLabel); } VariableStackFramePop(Parser); } else FuncValue->Val->FuncDef.Intrinsic(Parser, ReturnValue, ParamArray, ArgCount); HeapPopStackFrame(Parser->pc); } Parser->Mode = OldMode; } /* parse an expression */ long long AssumptionExpressionParseLongLong(struct ParseState *Parser) { Value *Val; long long Result = 0; if (!AssumptionExpressionParse(Parser, &Val)) ProgramFail(Parser, "expression expected"); if (Parser->Mode == RunModeRun) { if (!IS_NUMERIC_COERCIBLE(Val)) ProgramFail(Parser, "integer value expected instead of %t", Val->Typ); Result = CoerceLongLong(Val); VariableStackPop(Parser, Val); } return Result; }
48.834675
252
0.555183
moves-rwth
4ef2dd0809b01540dc32e00190485998b5af75b9
18,778
cc
C++
src/Tools.cc
ceremcem/node-occ
100a08bbf6f65ef02d53e08581f5f591fd21a96b
[ "MIT" ]
1
2021-01-15T00:00:47.000Z
2021-01-15T00:00:47.000Z
src/Tools.cc
ceremcem/node-occ
100a08bbf6f65ef02d53e08581f5f591fd21a96b
[ "MIT" ]
null
null
null
src/Tools.cc
ceremcem/node-occ
100a08bbf6f65ef02d53e08581f5f591fd21a96b
[ "MIT" ]
null
null
null
#include "Tools.h" #include "IFSelect_ReturnStatus.hxx" #include "Shape.h" #include "Solid.h" #include <list> #include <sstream> #include "AsyncWorkerWithProgress.h" // // ref : http://nikhilm.github.io/uvbook/threads.html // void extractShapes(v8::Local<v8::Value> value, std::list<Shape*>& shapes) { if (value->IsArray()) { v8::Array* arr = v8::Array::Cast(*value); for (uint32_t i = 0; i < arr->Length(); i++) { extractShapes(arr->Get(i), shapes); } } else if (value->IsObject()) { // it must be of type v8::Handle<v8::Object> obj = value->ToObject(); if (IsInstanceOf<Solid>(obj)) { shapes.push_back(Nan::ObjectWrap::Unwrap<Shape>(obj)); } } } static bool extractFileName(const v8::Handle<v8::Value>& value, std::string& filename) { // first argument is filename if (!value->IsString()) { return false; } v8::String::Utf8Value str(value); filename = ToCString(str); return true; } static bool extractCallback(const v8::Handle<v8::Value>& value, v8::Handle<v8::Function>& callback) { if (!value->IsFunction()) { return false; } callback = v8::Handle<v8::Function>::Cast(value->ToObject()); assert(!callback.IsEmpty()); return true; } NAN_METHOD(writeSTEP) { std::string filename; if (!extractFileName(info[0], filename)) { return Nan::ThrowError("expecting a file name"); } std::list<Shape*> shapes; for (int i = 1; i < info.Length(); i++) { extractShapes(info[i], shapes); } if (shapes.size() == 0) { return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false)); } try { STEPControl_Writer writer; IFSelect_ReturnStatus status; //xx Interface_Static::SetCVal("xstep.cascade.unit","M"); //xx Interface_Static::SetIVal("read.step.nonmanifold", 1); for (std::list<Shape*>::iterator it = shapes.begin(); it != shapes.end(); it++) { status = writer.Transfer((*it)->shape(), STEPControl_AsIs); if (status != IFSelect_RetDone) { return Nan::ThrowError("Failed to write STEP file"); } } status = writer.Write(filename.c_str()); } CATCH_AND_RETHROW("Failed to write STEP file "); info.GetReturnValue().Set(Nan::New<v8::Boolean>(true)); } NAN_METHOD(writeBREP) { std::string filename; if (!extractFileName(info[0], filename)) { return Nan::ThrowError("expecting a file name"); } std::list<Shape*> shapes; for (int i = 1; i < info.Length(); i++) { extractShapes(info[i], shapes); } if (shapes.size() == 0) { info.GetReturnValue().Set(Nan::New<v8::Boolean>(false)); return; } try { BRep_Builder B; TopoDS_Compound C; B.MakeCompound(C); for (std::list<Shape*>::iterator it = shapes.begin(); it != shapes.end(); it++) { TopoDS_Shape shape = (*it)->shape(); B.Add(C, shape); } BRepTools::Write(C, filename.c_str()); } CATCH_AND_RETHROW("Failed to write BREP file "); info.GetReturnValue().Set(Nan::New<v8::Boolean>(true)); } NAN_METHOD(writeSTL) { std::string filename; if (!extractFileName(info[0], filename)) { return Nan::ThrowError("expecting a file name"); } std::list<Shape*> shapes; for (int i = 1; i < info.Length(); i++) { extractShapes(info[i], shapes); } if (shapes.size() == 0) { info.GetReturnValue().Set(Nan::New<v8::Boolean>(false)); return; } try { BRep_Builder B; TopoDS_Compound C; B.MakeCompound(C); for (std::list<Shape*>::iterator it = shapes.begin(); it != shapes.end(); it++) { TopoDS_Shape shape = (*it)->shape(); B.Add(C, shape); } StlAPI_Writer writer; writer.ASCIIMode() = Standard_False; writer.Write(C, filename.c_str()); } CATCH_AND_RETHROW("Failed to write STL file "); info.GetReturnValue().Set(Nan::New<v8::Boolean>(true)); } static int extractSubShape(const TopoDS_Shape& shape, std::list<v8::Local<v8::Object> >& shapes) { TopAbs_ShapeEnum type = shape.ShapeType(); switch (type) { case TopAbs_COMPOUND: return 0; case TopAbs_COMPSOLID: case TopAbs_SOLID: { shapes.push_back(Solid::NewInstance(shape)->ToObject()); break; } case TopAbs_FACE: case TopAbs_SHELL: { break; } case TopAbs_WIRE: { break; } case TopAbs_EDGE: { break; } case TopAbs_VERTEX: { break; } default: return 0; } return 1; } static int extractShape(const TopoDS_Shape& shape, std::list<v8::Local<v8::Object> >& shapes) { TopAbs_ShapeEnum type = shape.ShapeType(); if (type != TopAbs_COMPOUND) { extractSubShape(shape, shapes); return 0; } TopExp_Explorer ex; int ret = 0; // extract compund for (ex.Init(shape, TopAbs_COMPOUND); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); // extract solids for (ex.Init(shape, TopAbs_COMPSOLID); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); for (ex.Init(shape, TopAbs_SOLID); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); // extract free faces for (ex.Init(shape, TopAbs_SHELL, TopAbs_SOLID); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); for (ex.Init(shape, TopAbs_FACE, TopAbs_SOLID); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); // extract free wires for (ex.Init(shape, TopAbs_WIRE, TopAbs_FACE); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); // extract free edges for (ex.Init(shape, TopAbs_EDGE, TopAbs_WIRE); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); // extract free vertices for (ex.Init(shape, TopAbs_VERTEX, TopAbs_EDGE); ex.More(); ex.Next()) ret += extractSubShape(ex.Current(), shapes); return ret; } static v8::Local<v8::Array> convert(std::list<v8::Local<v8::Object> > & shapes) { v8::Local<v8::Array> arr = Nan::New<v8::Array>((int)shapes.size()); int i = 0; for (std::list<v8::Local<v8::Object> >::iterator it = shapes.begin(); it != shapes.end(); it++) { arr->Set(i, *it); i++; } return arr; } bool mutex_initialised = false; uv_mutex_t stepOperation_mutex = { 0 }; class MutexLocker { uv_mutex_t& m_mutex; public: MutexLocker(uv_mutex_t& mutex) :m_mutex(mutex) { uv_mutex_lock(&m_mutex); } ~MutexLocker() { uv_mutex_unlock(&m_mutex); } }; class MyProgressIndicator : public Message_ProgressIndicator { ProgressData* m_data; AsyncWorkerWithProgress* _worker; public: MyProgressIndicator(AsyncWorkerWithProgress* worker); void notify_progress(); virtual Standard_Boolean Show(const Standard_Boolean force); }; MyProgressIndicator::MyProgressIndicator(AsyncWorkerWithProgress* worker) :Message_ProgressIndicator(), _worker(worker) { m_data = &_worker->m_data; } Standard_Boolean MyProgressIndicator::Show(const Standard_Boolean force) { double value = this->GetPosition(); double delta = (value - this->m_data->m_lastValue); if (delta > 0.01) { this->m_data->m_percent = value; this->m_data->m_progress = int(delta * 1000);// this->GetPosition(); this->m_data->m_lastValue = value; _worker->send_notify_progress(); } return Standard_False; } //http://free-cad.sourceforge.net/SrcDocu/df/d7b/ImportStep_8cpp_source.html class StepAsyncReadWorker : public AsyncWorkerWithProgress { public: StepAsyncReadWorker(Nan::Callback *callback, Nan::Callback* progressCallback, std::string* pfilename) : AsyncWorkerWithProgress(callback, progressCallback, pfilename) { } ~StepAsyncReadWorker() { } virtual void Execute(); virtual void HandleOKCallback(); protected: int _retValue; std::list<TopoDS_Shape > shapes; }; void StepAsyncReadWorker::HandleOKCallback() { if (this->_retValue == 0) { try { std::list<v8::Local<v8::Object> > jsshapes; for (std::list<TopoDS_Shape >::iterator it = shapes.begin(); it != shapes.end(); it++) { const TopoDS_Shape& aShape = (*it); extractShape(aShape, jsshapes); } v8::Local<v8::Array> arr = convert(jsshapes); v8::Local<v8::Value> err = Nan::Null(); v8::Local<v8::Value> argv[2] = { err, arr }; callback->Call(2, argv); } catch (...) { this->SetErrorMessage(" exception in trying to build shapes"); return this->HandleErrorCallback(); } } else { return this->HandleErrorCallback(); } } void StepAsyncReadWorker::Execute() { MutexLocker _locker(stepOperation_mutex); void* data = request.data; this->_retValue = 0; occHandle(Message_ProgressIndicator) progress = new MyProgressIndicator(this); progress->SetScale(1, 100, 1); progress->Show(); try { STEPControl_Reader aReader; Interface_Static::SetCVal("xstep.cascade.unit", "mm"); Interface_Static::SetIVal("read.step.nonmanifold", 1); Interface_Static::SetIVal("read.step.product.mode", 1); progress->NewScope(5, "reading"); if (aReader.ReadFile(_filename.c_str()) != IFSelect_RetDone) { std::stringstream str; str << " (1) cannot read STEP file " << _filename << std::ends; this->SetErrorMessage(str.str().c_str()); // Local<Value> argv[] = { Local<Value>(String::New()) }; // Local<Value> res = callback->Call(global, 1, argv); // NanReturnUndefined(); progress->EndScope(); progress->SetValue(105.0); progress->Show(); this->_retValue = 1; return; } progress->EndScope(); progress->Show(); progress->NewScope(95, "transfert"); progress->Show(); aReader.WS()->MapReader()->SetProgress(progress); // Root transfers int nbr = aReader.NbRootsForTransfer(); Standard_Boolean failsonly = Standard_False; aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity); progress->SetRange(0, nbr); int mod = nbr / 10 + 1; for (int n = 1; n <= nbr; n++) { Standard_Boolean ok = aReader.TransferRoot(n); Standard_Integer nbs = aReader.NbShapes(); if (!ok || nbs == 0) { continue; // skip empty root } if ((n + 1) % mod == 0) { progress->Increment(); } } aReader.WS()->MapReader()->SetProgress(0); progress->SetValue(100); progress->EndScope(); progress->Show(true); TopoDS_Shape aResShape; BRep_Builder B; TopoDS_Compound compound; B.MakeCompound(compound); int nbs = aReader.NbShapes(); for (int i = 1; i <= nbs; i++) { const TopoDS_Shape& aShape = aReader.Shape(i); if (aShape.ShapeType() == TopAbs_SOLID) { ShapeFix_Solid fix((const TopoDS_Solid&)aShape); fix.Perform(); } B.Add(compound, aShape); this->shapes.push_back(aShape); } aResShape = compound; TopTools_IndexedMapOfShape anIndices; TopExp::MapShapes(aResShape, anIndices); occHandle(Interface_InterfaceModel) Model = aReader.WS()->Model(); occHandle(XSControl_TransferReader) TR = aReader.WS()->TransferReader(); if (!TR.IsNull()) { occHandle(Transfer_TransientProcess) TP = TR->TransientProcess(); occHandle(Standard_Type) tPD = STANDARD_TYPE(StepBasic_ProductDefinition); occHandle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence); occHandle(Standard_Type) tShape = STANDARD_TYPE(StepShape_TopologicalRepresentationItem); occHandle(Standard_Type) tGeom = STANDARD_TYPE(StepGeom_GeometricRepresentationItem); Standard_Integer nb = Model->NbEntities(); //xx cout << " nb entities =" << nb << std::endl; for (Standard_Integer ie = 1; ie <= nb; ie++) { occHandle(Standard_Transient) enti = Model->Value(ie); occHandle(TCollection_HAsciiString) aName; if (enti->DynamicType() == tNAUO) { occHandle(StepRepr_NextAssemblyUsageOccurrence) NAUO = occHandle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti); if (NAUO.IsNull()) continue; // Interface_EntityIterator subs = aReader.WS()->Graph().Sharings(NAUO); auto subs = aReader.WS()->Graph().Sharings(NAUO); for (subs.Start(); subs.More(); subs.Next()) { occHandle(StepRepr_ProductDefinitionShape) PDS = occHandle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value()); if (PDS.IsNull()) continue; occHandle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship(); if (PDR.IsNull()) continue; if (PDR->HasDescription() && PDR->Description()->Length() > 0) { aName = PDR->Description(); } else if (PDR->Name()->Length() > 0) { aName = PDR->Name(); } else { aName = PDR->Id(); } } // find proper label TCollection_ExtendedString str(aName->String()); } else if (enti->IsKind(tShape) || enti->IsKind(tGeom)) { aName = occHandle(StepRepr_RepresentationItem)::DownCast(enti)->Name(); } else if (enti->DynamicType() == tPD) { occHandle(StepBasic_ProductDefinition) PD = occHandle(StepBasic_ProductDefinition)::DownCast(enti); if (PD.IsNull()) continue; occHandle(StepBasic_Product) Prod = PD->Formation()->OfProduct(); aName = Prod->Name(); } else { continue; } if (aName->UsefullLength() < 1) continue; // skip 'N0NE' name if (aName->UsefullLength() == 4 && toupper(aName->Value(1)) == 'N' &&toupper(aName->Value(2)) == 'O' && toupper(aName->Value(3)) == 'N' && toupper(aName->Value(4)) == 'E') continue; /* // special check to pass names like "Open CASCADE STEP translator 6.3 1" TCollection_AsciiString aSkipName ("Open CASCADE STEP translator"); if (aName->Length() >= aSkipName.Length()) { if (aName->String().SubString(1, aSkipName.Length()).IsEqual(aSkipName)) continue; } */ TCollection_ExtendedString aNameExt(aName->ToCString()); //xx cout << " name of part =" << aName->ToCString() << std::endl; // find target shape occHandle(Transfer_Binder) binder = TP->Find(enti); if (binder.IsNull()) continue; TopoDS_Shape S = TransferBRep::ShapeResult(binder); if (S.IsNull()) continue; //xx cout << " name of part = ---------" << std::endl; // as PRODUCT can be included in the main shape // several times, we look here for all inclusions. Standard_Integer isub, nbSubs = anIndices.Extent(); for (isub = 1; isub <= nbSubs; isub++) { TopoDS_Shape aSub = anIndices.FindKey(isub); if (aSub.IsPartner(S)) { //xx cout << " name of part =" << aName->ToCString() << " shape " << HashCode(aSub, -1) << " " << aSub.ShapeType() << endl; #if 0 // create label and set shape if (L.IsNull()) { TDF_TagSource aTag; L = aTag.NewChild(theShapeLabel); TNaming_Builder tnBuild(L); //tnBuild.Generated(S); tnBuild.Generated(aSub); } // set a name TDataStd_Name::Set(L, aNameExt); #endif } } } // END: Store names } } catch (...) { std::cerr << " EXCEPTION in READ STEP" << std::endl; this->SetErrorMessage("2 - caught C++ exception in readStep"); this->_retValue = 2; return; } } void readStepAsync(const std::string& filename, v8::Local<v8::Function> _callback, v8::Local<v8::Function> _progressCallback) { Nan::Callback* callback = new Nan::Callback(_callback); Nan::Callback* progressCallback = _progressCallback.IsEmpty() ? NULL : new Nan::Callback(_progressCallback); std::string* pfilename = new std::string(filename); Nan::AsyncQueueWorker(new StepAsyncReadWorker(callback, progressCallback, pfilename)); } NAN_METHOD(readSTEP) { if (!mutex_initialised) { uv_mutex_init(&stepOperation_mutex); mutex_initialised = true; } std::string filename; if (!extractFileName(info[0], filename)) { return Nan::ThrowError("expecting a file name"); } v8::Local<v8::Function> callback; if (!extractCallback(info[1], callback)) { return Nan::ThrowError("expecting a callback function"); } v8::Local<v8::Function> progressCallback; if (!extractCallback(info[2], progressCallback)) { // OPTIONAL !!! // Nan::ThrowError("expecting a callback function"); } readStepAsync(filename, callback, progressCallback); } class BRepAsyncReadWorker : public StepAsyncReadWorker { public: BRepAsyncReadWorker(Nan::Callback *callback, Nan::Callback* progressCallback, std::string* pfilename) : StepAsyncReadWorker(callback, progressCallback, pfilename) { } ~BRepAsyncReadWorker() { } void Execute(); }; void BRepAsyncReadWorker::Execute() { this->_retValue = 0; std::string filename = this->_filename; try { occHandle(Message_ProgressIndicator) progress = new MyProgressIndicator(this); progress->SetScale(1, 100, 1); progress->Show(); // read brep-file TopoDS_Shape shape; BRep_Builder aBuilder; if (!BRepTools::Read(shape, filename.c_str(), aBuilder, progress)) { std::stringstream str; str << "1- cannot read BREP file : '" << filename << "'" << std::ends; this->SetErrorMessage(str.str().c_str()); this->_retValue = 1; progress->SetValue(100.0); progress->Show(); return; } this->shapes.push_back(shape); progress->SetValue(100.0); progress->Show(); } catch (...) { this->SetErrorMessage("2 ( caught C++ exception in _readBREPAsync"); this->_retValue = 2; return; } } void readBREPAsync(const std::string& filename, v8::Local<v8::Function> _callback, v8::Local<v8::Function> _progressCallback) { Nan::Callback* callback = new Nan::Callback(_callback); Nan::Callback* progressCallback = _progressCallback.IsEmpty() ? NULL : new Nan::Callback(_progressCallback); std::string* pfilename = new std::string(filename); Nan::AsyncQueueWorker(new BRepAsyncReadWorker(callback, progressCallback, pfilename)); } NAN_METHOD(readBREP) { std::string filename; if (!extractFileName(info[0], filename)) { return Nan::ThrowError("expecting a file name"); } v8::Local<v8::Function> callback; if (!extractCallback(info[1], callback)) { return Nan::ThrowError("expecting a callback function"); } v8::Local<v8::Function> progressCallback; if (!extractCallback(info[2], progressCallback)) { // OPTIONAL !!! // return Nan::ThrowError("expecting a callback function"); } readBREPAsync(filename, callback, progressCallback); } #undef Handle
27.214493
179
0.635584
ceremcem
4ef31f129f5fd7c09f77d47d9932abae6cf4339e
2,711
cpp
C++
src/Heimdall/Gatekeeper.cpp
andoma/rainbow
ed1e70033217450457e52b90276e41a746d5086a
[ "MIT" ]
null
null
null
src/Heimdall/Gatekeeper.cpp
andoma/rainbow
ed1e70033217450457e52b90276e41a746d5086a
[ "MIT" ]
null
null
null
src/Heimdall/Gatekeeper.cpp
andoma/rainbow
ed1e70033217450457e52b90276e41a746d5086a
[ "MIT" ]
1
2018-09-20T19:34:36.000Z
2018-09-20T19:34:36.000Z
// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #include "Heimdall/Gatekeeper.h" #if USE_LUA_SCRIPT # include "Common/Data.h" # include "Common/String.h" # include "FileSystem/File.h" # include "FileSystem/FileSystem.h" # include "Lua/LuaHelper.h" # include "Lua/LuaScript.h" using rainbow::LuaScript; #endif // USE_LUA_SCRIPT using heimdall::Gatekeeper; using rainbow::Data; using rainbow::File; using rainbow::Vec2i; using rainbow::czstring; namespace { #if USE_LUA_SCRIPT auto open_module(const rainbow::filesystem::Path& path) -> Data { #if defined(RAINBOW_OS_MACOS) return Data{File::open(path)}; #elif defined(RAINBOW_OS_WINDOWS) return Data::load_asset(path.string().c_str()); #else NOT_USED(path); return {}; #endif // RAINBOW_OS_MACOS } #endif // USE_LUA_SCRIPT } Gatekeeper::Gatekeeper() : overlay_(director_.render_queue()), overlay_activator_(&overlay_) #if USE_LUA_SCRIPT , monitor_(rainbow::filesystem::assets_path()) #endif // USE_LUA_SCRIPT { } void Gatekeeper::init(const Vec2i& screen) { overlay_.initialize(); director_.input().subscribe(overlay_); director_.input().subscribe(overlay_activator_); director_.init(screen); if (director_.terminated()) return; #if USE_LUA_SCRIPT monitor_.set_callback([this](czstring path) { auto p = rainbow::filesystem::absolute(path); std::string filename = p.filename(); if (filename.length() < 5 || !rainbow::ends_with(filename, ".lua")) return; changed_files_->emplace([ this, path = std::move(p), module = std::move(filename) ]() mutable { LOGI("Reloading '%s'...", module.c_str()); module.erase(module.length() - 4, 4); auto L = static_cast<LuaScript*>(director_.script())->state(); rainbow::lua::reload(L, open_module(path), module.c_str()); }); }); #endif // USE_LUA_SCRIPT } void Gatekeeper::update(uint64_t dt) { #if USE_LUA_SCRIPT changed_files_.invoke([](auto& changed_files) { while (!changed_files->empty()) { std::function<void()> reload_module = std::move(changed_files->front()); changed_files->pop(); changed_files.invoke_unlocked( [&reload_module](auto&) { reload_module(); }); } }); #endif // USE_LUA_SCRIPT director_.update(dt); if (!overlay_.is_enabled()) overlay_activator_.update(dt); overlay_.update(dt); }
26.578431
80
0.637403
andoma
4ef66a017f5cbe0b68b52bcd2b27db4e9445e468
7,882
cxx
C++
smtk/attribute/FileItem.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/attribute/FileItem.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/attribute/FileItem.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.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 notice for more information. //========================================================================= #include "smtk/attribute/FileItem.h" #include "smtk/attribute/FileItemDefinition.h" #include "smtk/attribute/Attribute.h" #include <algorithm> // for std::find #include <iostream> #include <stdio.h> using namespace smtk::attribute; //---------------------------------------------------------------------------- FileItem::FileItem(Attribute *owningAttribute, int itemPosition): Item(owningAttribute, itemPosition) { } //---------------------------------------------------------------------------- FileItem::FileItem(Item *inOwningItem, int itemPosition, int inSubGroupPosition): Item(inOwningItem, itemPosition, inSubGroupPosition) { } //---------------------------------------------------------------------------- bool FileItem:: setDefinition(smtk::attribute::ConstItemDefinitionPtr adef) { // Note that we do a dynamic cast here since we don't // know if the proper definition is being passed const FileItemDefinition *def = dynamic_cast<const FileItemDefinition *>(adef.get()); // Call the parent's set definition - similar to constructor calls // we call from base to derived if ((def == NULL) || (!Item::setDefinition(adef))) { return false; } // Find out how many values this item is suppose to have // if the size is 0 then its unbounded std::size_t n = def->numberOfRequiredValues(); if (n) { if (def->hasDefault()) { this->m_values.resize(n, def->defaultValue()); this->m_isSet.resize(n, true); } else { this->m_isSet.resize(n, false); this->m_values.resize(n); } this->m_recentValues.clear(); } return true; } //---------------------------------------------------------------------------- FileItem::~FileItem() { } //---------------------------------------------------------------------------- Item::Type FileItem::type() const { return FILE; } //---------------------------------------------------------------------------- std::size_t FileItem::numberOfRequiredValues() const { const FileItemDefinition *def = static_cast<const FileItemDefinition*>(this->m_definition.get()); if (def == NULL) { return 0; } return def->numberOfRequiredValues(); } //---------------------------------------------------------------------------- bool FileItem::shouldBeRelative() const { const FileItemDefinition *def = static_cast<const FileItemDefinition *>(this->definition().get()); if (def != NULL) { return def->shouldBeRelative(); } return true; } //---------------------------------------------------------------------------- bool FileItem::shouldExist() const { const FileItemDefinition *def = static_cast<const FileItemDefinition *>(this->definition().get()); if (def != NULL) { return def->shouldExist(); } return true; } //---------------------------------------------------------------------------- bool FileItem::setValue(std::size_t element, const std::string &val) { const FileItemDefinition *def = static_cast<const FileItemDefinition *>(this->definition().get()); if ((def == NULL) || (def->isValueValid(val))) { this->m_values[element] = val; this->m_isSet[element] = true; if(std::find(this->m_recentValues.begin(), this->m_recentValues.end(), val) == this->m_recentValues.end()) this->m_recentValues.push_back(val); return true; } return false; } //---------------------------------------------------------------------------- std::string FileItem::valueAsString(std::size_t element, const std::string &format) const { // For the initial design we will use sprintf and force a limit of 300 char char dummy[300]; if (format != "") { sprintf(dummy, format.c_str(), this->m_values[element].c_str()); } else { sprintf(dummy, "%s", this->m_values[element].c_str()); } return dummy; } //---------------------------------------------------------------------------- bool FileItem::appendValue(const std::string &val) { //First - are we allowed to change the number of values? const FileItemDefinition *def = static_cast<const FileItemDefinition *>(this->definition().get()); if (def->numberOfRequiredValues() != 0) { return false; // The number of values is fixed } if (def->isValueValid(val)) { this->m_values.push_back(val); this->m_isSet.push_back(true); return true; } return false; } //---------------------------------------------------------------------------- bool FileItem::removeValue(std::size_t element) { //First - are we allowed to change the number of values? const FileItemDefinition *def = static_cast<const FileItemDefinition *>(this->definition().get()); if ( def->numberOfRequiredValues() != 0 ) { return false; // The number of values is fixed } this->m_values.erase(this->m_values.begin()+element); this->m_isSet.erase(this->m_isSet.begin()+element); return true; } //---------------------------------------------------------------------------- bool FileItem::setNumberOfValues(std::size_t newSize) { // If the current size is the same just return if (this->numberOfValues() == newSize) { return true; } //Next - are we allowed to change the number of values? const FileItemDefinition *def = static_cast<const FileItemDefinition *>(this->definition().get()); std::size_t n = def->numberOfRequiredValues(); if (n != 0) { return false; // The number of values is fixed } this->m_values.resize(newSize); this->m_isSet.resize(newSize, false); //Any added values are not set return true; } //---------------------------------------------------------------------------- void FileItem::reset() { const FileItemDefinition *def = static_cast<const FileItemDefinition *>(this->definition().get()); // Was the initial size 0? std::size_t i, n = def->numberOfRequiredValues(); if (n == 0) { this->m_values.clear(); this->m_isSet.clear(); return; } for (i = 0; i < n; i++) { this->unset(i); } } //---------------------------------------------------------------------------- bool FileItem::assign(ConstItemPtr &sourceItem, unsigned int options) { // Assigns my contents to be same as sourceItem smtk::shared_ptr<const FileItem > sourceFileItem = smtk::dynamic_pointer_cast<const FileItem>(sourceItem); if (!sourceFileItem) { return false; // Source is not a file item } // copy all recentValues list this->m_recentValues.clear(); this->m_recentValues.insert(m_recentValues.end(), sourceFileItem->recentValues().begin(), sourceFileItem->recentValues().end()); for (std::size_t i=0; i<sourceFileItem->numberOfValues(); ++i) { if (sourceFileItem->isSet(i)) { this->setValue(i, sourceFileItem->value(i)); } else { this->unset(i); } } return Item::assign(sourceItem, options); } //---------------------------------------------------------------------------- void FileItem::addRecentValue(const std::string& val) { if(std::find(this->m_recentValues.begin(), this->m_recentValues.end(), val) == this->m_recentValues.end()) this->m_recentValues.push_back(val); } //----------------------------------------------------------------------------
29.856061
79
0.530576
yumin
4ef7c5554c5f2f72dfef5cc3fda3c84fb4d92d85
778
hpp
C++
modules/event/shiva/event/change_scene.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
176
2018-06-06T12:20:21.000Z
2022-01-27T02:54:34.000Z
modules/event/shiva/event/change_scene.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
11
2018-06-09T21:30:02.000Z
2019-09-14T16:03:12.000Z
modules/event/shiva/event/change_scene.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
19
2018-08-15T11:40:02.000Z
2020-08-31T11:00:44.000Z
// // Created by roman Sztergbaum on 06/08/2018. // #pragma once #include <shiva/reflection/reflection.hpp> #include <shiva/event/invoker.hpp> namespace shiva::event { struct change_scene { static constexpr const shiva::event::invoker_dispatcher<change_scene, const char *> invoker{}; reflect_class(change_scene) change_scene(const char *scene_name_ = nullptr) noexcept : scene_name(scene_name_) { } static constexpr auto reflected_functions() noexcept { return meta::makeMap(); } static constexpr auto reflected_members() noexcept { return meta::makeMap(reflect_member(&change_scene::scene_name)); } const char *scene_name{nullptr}; }; }
22.882353
102
0.640103
Milerius
4efd58df76a0570e6c33bcf2ae94ba2bb45c1684
1,183
hpp
C++
include/gbVk/config.hpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
include/gbVk/config.hpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
include/gbVk/config.hpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_GBVK_CONFIG_HPP #define GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_GBVK_CONFIG_HPP /** @file * * @brief General configuration for Vulkan. * @author Andreas Weis (der_ghulbus@ghulbus-inc.de) */ #include <gbVk/gbVk_Export.hpp> /** Specifies the API for a function declaration. * When building as a dynamic library, this is used to mark the functions that will be exported by the library. */ #define GHULBUS_VULKAN_API GHULBUS_LIBRARY_GBVK_EXPORT /** \namespace GhulbusVulkan Namespace for the GhulbusVulkan library. * The implementation internally always uses this macro `GHULBUS_VULKAN_NAMESPACE` to refer to the namespace. * When building GhulbusVulkan yourself, you can globally redefine this macro to move to a different namespace. */ #ifndef GHULBUS_VULKAN_NAMESPACE # define GHULBUS_VULKAN_NAMESPACE GhulbusVulkan #endif // Vulkan SDK 1.2.154.1 #define GHULBUS_VULKAN_EXPECTED_VK_HEADER_VERSION 154 #ifdef GHULBUS_CONFIG_VULKAN_PLATFORM_WIN32 # define VK_USE_PLATFORM_WIN32_KHR # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif #endif #endif
30.333333
111
0.800507
ComicSansMS
4efebeb26fd1be374f48f4883c6ad81a4f048c9d
1,045
cpp
C++
c++/EggDroppingProblem.cpp
parizadas/HacktoberFest2020-3
48cb0c7f2d43d38cb7d8343df18035c9288c63ea
[ "MIT" ]
51
2020-09-27T15:28:05.000Z
2021-09-29T02:07:25.000Z
c++/EggDroppingProblem.cpp
parizadas/HacktoberFest2020-3
48cb0c7f2d43d38cb7d8343df18035c9288c63ea
[ "MIT" ]
152
2020-09-27T12:12:12.000Z
2021-10-03T18:22:15.000Z
c++/EggDroppingProblem.cpp
parizadas/HacktoberFest2020-3
48cb0c7f2d43d38cb7d8343df18035c9288c63ea
[ "MIT" ]
453
2020-09-27T12:34:35.000Z
2021-10-16T08:33:33.000Z
#include <bits/stdc++.h> using namespace std; //egg dropping problem void eggdroppingpuzzle(int eggs,int floors) { int **T=(int **)malloc(eggs*sizeof(int *)); for(int i=0;i<eggs;i++) T[i]=(int *)malloc((floors+1)*sizeof(int)); for(int i=0;i<eggs;i++) T[i][0]=0; for(int i=1;i<=floors;i++) T[0][i]=i; for(int i=1;i<eggs;i++) { for(int j=1;j<=floors;j++) { if((i+1)>j) T[i][j]=T[i-1][j]; else { vector<int> v; for(int k=1;k<=j;k++) { v.push_back(1+max(T[i-1][k-1],T[i][j-k])); } T[i][j]=*(min_element(v.begin(),v.end())); } } } printf("Minimum number of attempts to find which floor egg breaks from is %d\n",T[eggs-1][floors]); return ; } int main() { int eggs,floors; printf("Enter number of floors and eggs\n"); cin>>floors>>eggs; eggdroppingpuzzle(eggs,floors); return 0; }
24.302326
103
0.466029
parizadas
f60127fab3d565dccf2af1994d07743f9b972a1e
6,346
cpp
C++
ramp_14890.cpp
goongg/SamSung
d07f8ca06fa21c2c26f63f89978b79a204373262
[ "CECILL-B" ]
null
null
null
ramp_14890.cpp
goongg/SamSung
d07f8ca06fa21c2c26f63f89978b79a204373262
[ "CECILL-B" ]
null
null
null
ramp_14890.cpp
goongg/SamSung
d07f8ca06fa21c2c26f63f89978b79a204373262
[ "CECILL-B" ]
null
null
null
// 7시 32분 #include <iostream> #include <vector> #include <queue> using namespace std; #define debug 0 class ramp { int n, l; vector<int> t; vector<bool> poss_r;// 가능 행 조사 vector<bool> poss_c;// 가능 열 조사 vector<bool> v; public: void input() { cin>>n >>l; t = vector<int>(n*n); poss_r = vector<bool>(n); poss_c = vector<bool>(n); v = vector<bool>(n); for(int i=0; i<n*n; i++) cin>>t[i]; } int check() { int ret=0; vector<bool> visit ; for(int i=0; i<n; i++) { poss_r[i] =1; visit = v; //행 조사 for(int j=0; j<n-1; j++) { int cur= t[i*n+j]; int next= t[i*n+j+1]; if(cur == next) { //do noting } else if( cur == next -1) { if(l==n) { poss_r[i] =0; break; } if(visit[j]) { poss_r[i] =0; break; } visit[j]=1; for(int k =1 ; k<l; k++) { if( j-k >=0 && visit[j-k]) { poss_r[i] =0; break; } if( !(j-k >=0 && cur == t[i*n +j-k]) ) { poss_r[i] =0; break; } visit[j-k]=1; } } else if( cur == next +1){ if(l==n) { poss_r[i] =0; break; } if(visit[j+1]) { poss_r[i] =0; break; } visit[j+1]=1; for(int k =1 ; k<l; k++) { if( j+1+k < n && visit[j+1+k]) { poss_r[i] =0; break; } if( !(j+1+k < n && next == t[i*n +j+1+k])) { poss_r[i] =0; break; } visit[j+1+k]=1; } } else { poss_r[i] =0; break; } } if(poss_r[i]) ret++; #if debug cout<<i<<"행:"<<poss_r[i]<<endl; #endif } #if debug cout<<endl; #endif //열 조사 for(int j=0; j<n; j++) { poss_c[j] =1; visit = v; for(int i=0; i<n-1; i++) { int cur= t[i*n+j]; int next= t[(i+1)*n+j]; if(cur == next) { //do noting } else if( cur == next -1) { if(l==n) { poss_c[j] =0; break; } if(visit[i]) { poss_c[j] =0; break; } visit[i]=1; for(int k =1 ; k<l; k++){ if( i-k >=0 && visit[i-k ]) { poss_c[j] =0; break; } if( !(i-k >=0 && cur == t[(i-k)*n +j])) { poss_c[j] =0; break; } visit[i-k ]=1; } } else if( cur == next +1) { if(l==n) { poss_c[j] =0; break; } if(visit[i+1]) { poss_c[j] =0; break; } visit[i+1]=1; for(int k =1 ; k<l; k++){ if( i+1+k <n && visit[i+1+k ]) { poss_c[i] =0; break; } if( !(i+1+k < n && next == t[(i+1+k)*n +j])) { poss_c[j] =0; break; } visit[i+1+k ]=1; } } else { poss_c[j] =0; break; } } if(poss_c[j]) ret++; #if debug cout<<j<<"열:"<<poss_c[j]<<endl; #endif } return ret; } }; int main() { ramp r; r.input(); cout<<r.check(); return 0; }
29.793427
73
0.180586
goongg
f601c002dc84eb5f812cf6abd865d61c25b26fd4
4,725
hpp
C++
src/lib/include/black/internal/formula/alphabet.hpp
black-sat/black
80902240987312fb0e6f00227a06e9f9c9728a67
[ "MIT" ]
4
2020-09-30T15:16:22.000Z
2021-09-20T15:02:39.000Z
src/lib/include/black/internal/formula/alphabet.hpp
teodorov/black
4de280ded5e99cc515141b4acc35137ba32c2469
[ "MIT" ]
42
2020-07-15T13:46:11.000Z
2022-03-10T09:42:43.000Z
src/lib/include/black/internal/formula/alphabet.hpp
teodorov/black
4de280ded5e99cc515141b4acc35137ba32c2469
[ "MIT" ]
3
2020-03-30T14:39:17.000Z
2022-03-18T14:05:33.000Z
// // BLACK - Bounded Ltl sAtisfiability ChecKer // // (C) 2019 Nicola Gigante // // 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. #ifndef BLACK_ALPHABET_IMPL_HPP #define BLACK_ALPHABET_IMPL_HPP #include <black/support/meta.hpp> #include <black/logic/formula.hpp> namespace black::internal { // // Out-of-line definitions of methods of class `alphabet` // template<typename T, REQUIRES_OUT_OF_LINE(internal::is_hashable<T>)> inline atom alphabet::var(T&& label) { if constexpr(std::is_constructible_v<std::string,T>) { return atom{this, allocate_atom(std::string{FWD(label)})}; } else { return atom{this, allocate_atom(FWD(label))}; } } // Out-of-line implementations from the handle_base class in formula.hpp, // placed here to have a complete alphabet type template<typename H, typename F> template<typename FType, typename Arg> std::pair<alphabet *, unary_t *> handle_base<H, F>::allocate_unary(FType type, Arg const&arg) { // The type is templated only because of circularity problems static_assert(std::is_same_v<FType, unary::type>); // Get the alphabet from the argument class alphabet *sigma = arg._alphabet; // Ask the alphabet to actually allocate the formula unary_t *object = sigma->allocate_unary(type, arg._formula); return {sigma, object}; } template<typename H, typename F> template<typename FType, typename Arg1, typename Arg2> std::pair<alphabet *, binary_t *> handle_base<H, F>::allocate_binary(FType type, Arg1 const&arg1, Arg2 const&arg2) { // The type is templated only because of circularity problems static_assert(std::is_same_v<FType, binary::type>); // Check that both arguments come from the same alphabet black_assert(arg1._alphabet == arg2._alphabet); // Get the alphabet from the first argument (same as the second, by now) class alphabet *sigma = arg1._alphabet; // Ask the alphabet to actually allocate the formula binary_t *object = sigma->allocate_binary( type, arg1._formula, arg2._formula ); return {sigma, object}; } } // namespace black::internal /* * Functions from formula.hpp that need the alphabet class */ namespace black::internal { // Conjunct multiple formulas generated from a range, // avoiding useless true formulas at the beginning of the fold template<typename Iterator, typename EndIterator, typename F> formula big_and(alphabet &sigma, Iterator b, EndIterator e, F&& f) { formula acc = sigma.top(); while(b != e) { formula elem = std::forward<F>(f)(*b++); if(elem == sigma.top()) continue; else if(acc == sigma.top()) acc = elem; else acc = acc && elem; } return acc; } template<typename Range, typename F> formula big_and(alphabet &sigma, Range r, F&& f) { return big_and(sigma, begin(r), end(r), std::forward<F>(f)); } // Disjunct multiple formulas generated from a range, // avoiding useless true formulas at the beginning of the fold template<typename Iterator, typename EndIterator, typename F> formula big_or(alphabet &sigma, Iterator b, EndIterator e, F&& f) { formula acc = sigma.bottom(); while(b != e) { formula elem = std::forward<F>(f)(*b++); if(elem == sigma.bottom()) continue; else if(acc == sigma.bottom()) acc = elem; else acc = acc || elem; } return acc; } template<typename Range, typename F> formula big_or(alphabet &sigma, Range r, F&& f) { return big_or(sigma, begin(r), end(r), std::forward<F>(f)); } } #endif // BLACK_ALPHABET_IMPL_HPP
32.363014
80
0.685714
black-sat
f6051e9c65fa8d7bd0a127758e0a25fb0e44b0f4
15,312
cc
C++
src/core/analysis/rnn_scorer_gbeam.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
1
2018-03-18T15:53:27.000Z
2018-03-18T15:53:27.000Z
src/core/analysis/rnn_scorer_gbeam.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
null
null
null
src/core/analysis/rnn_scorer_gbeam.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
null
null
null
// // Created by Arseny Tolmachev on 2017/11/20. // #include "rnn_scorer_gbeam.h" #include "rnn/mikolov_rnn.h" #include "rnn_id_resolver.h" #include "util/stl_util.h" namespace jumanpp { namespace core { namespace analysis { struct GbeamRnnFactoryState { rnn::RnnIdResolver resolver; jumanpp::rnn::mikolov::MikolovRnn rnn; util::ConstSliceable<float> embeddings; util::ConstSliceable<float> nceEmbeddings; rnn::RnnInferenceConfig config; jumanpp::rnn::mikolov::MikolovModelReader rnnReader; util::CodedBuffer codedBuf_; u32 embedSize() const { return rnn.modelHeader().layerSize; } util::ArraySlice<float> embedOf(size_t idx) const { return embeddings.row(idx); } util::ArraySlice<float> nceEmbedOf(size_t idx) const { return nceEmbeddings.row(idx); } util::memory::Manager mgr{64 * 1024}; util::Sliceable<float> bosState{}; void computeBosState(i32 bosId) { auto alloc = mgr.core(); auto zeros = alloc->allocate2d<float>(1, embedSize(), 64); util::fill(zeros, 0); bosState = alloc->allocate2d<float>(1, embedSize(), 64); auto embed = embeddings.row(bosId); util::ConstSliceable<float> embedSlice{embed, embedSize(), 1}; jumanpp::rnn::mikolov::ParallelContextData pcd{zeros, embedSlice, bosState}; rnn.computeNewParCtx(&pcd); } StringPiece rnnMatrix() const { return rnn.matrixAsStringpiece(); } StringPiece embeddingData() const { return StringPiece{ reinterpret_cast<StringPiece::pointer_t>(embeddings.begin()), embeddings.size() * sizeof(float)}; } StringPiece nceEmbedData() const { return StringPiece{ reinterpret_cast<StringPiece::pointer_t>(nceEmbeddings.begin()), nceEmbeddings.size() * sizeof(float)}; } StringPiece maxentWeightData() const { return rnn.maxentWeightsAsStringpiece(); } }; struct GbeamRnnState { const GbeamRnnFactoryState* shared; util::memory::Manager manager{2 * 1024 * 1024}; // 2M std::unique_ptr<util::memory::PoolAlloc> alloc{manager.core()}; rnn::RnnIdContainer container{alloc.get()}; Lattice* lat; const ExtraNodesContext* xtra; u32 scorerIdx; util::Sliceable<i32> ctxIdBuf; util::MutableArraySlice<i32> rightIdBuf; util::Sliceable<float> contextBuf; util::Sliceable<float> embBuf; util::MutableArraySlice<float> scoreBuf; util::MutableArraySlice<util::Sliceable<float>> contexts; void allocateState() { auto numBnd = lat->createdBoundaryCount(); auto gbeamSize = lat->config().globalBeamSize; auto embedSize = shared->rnn.modelHeader().layerSize; contexts = alloc->allocateBuf<util::Sliceable<float>>(numBnd); ctxIdBuf = alloc->allocate2d<i32>( gbeamSize, shared->rnn.modelHeader().maxentOrder - 1); rightIdBuf = alloc->allocateBuf<i32>(gbeamSize); contextBuf = alloc->allocate2d<float>(gbeamSize, embedSize, 64); embBuf = alloc->allocate2d<float>(gbeamSize, embedSize, 64); scoreBuf = alloc->allocateBuf<float>(gbeamSize, 64); contexts.at(1) = shared->bosState; } util::ArraySlice<i32> gatherIds(const rnn::RnnBoundary& rbnd) { size_t nodeCnt = static_cast<size_t>(rbnd.nodeCnt); util::MutableArraySlice<i32> subset{rightIdBuf, 0, nodeCnt}; JPP_INDEBUG(int count = rbnd.nodeCnt); for (auto node = rbnd.node; node != nullptr; node = node->nextInBnd) { subset.at(node->idx) = node->id; JPP_INDEBUG(--count); } JPP_DCHECK_EQ(count, 0); return subset; } util::ConstSliceable<float> gatherContext(const rnn::RnnBoundary& rbnd) { auto subset = contextBuf.topRows(rbnd.nodeCnt); for (auto node = rbnd.node; node != nullptr; node = node->nextInBnd) { auto prev = node->prev; JPP_DCHECK_NE(prev, nullptr); auto ctxRow = subset.row(node->idx); auto present = contexts.at(prev->boundary).row(prev->idx); util::copy_buffer(present, ctxRow); } return subset; } util::ConstSliceable<float> gatherLeftEmbeds(util::ArraySlice<i32> ids) { auto subset = embBuf.topRows(ids.size()); for (int i = 0; i < ids.size(); ++i) { auto embedId = ids[i]; if (embedId == -1) { embedId = 0; } auto embed = shared->embedOf(embedId); auto target = subset.row(i); util::copy_buffer(embed, target); } return subset; } util::Sliceable<float> allocContext(u32 bndIdx, size_t size) { auto buf = alloc->allocate2d<float>(size, shared->embedSize(), 64); contexts.at(bndIdx) = buf; return buf; } Status computeContext(u32 bndIdx) { auto& rbnd = container.rnnBoundary(bndIdx); if (rbnd.nodeCnt == 0) { return Status::Ok(); } auto rnnIds = gatherIds(rbnd); auto inCtx = gatherContext(rbnd); auto embs = gatherLeftEmbeds(rnnIds); auto outCtx = allocContext(bndIdx, rnnIds.size()); jumanpp::rnn::mikolov::ParallelContextData pcd{inCtx, embs, outCtx}; shared->rnn.computeNewParCtx(&pcd); return Status::Ok(); } util::ArraySlice<i32> gatherScoreIds(const rnn::RnnBoundary& rbnd) { size_t scoreCnt = static_cast<size_t>(rbnd.scoreCnt); util::MutableArraySlice<i32> subset{rightIdBuf, 0, scoreCnt}; u32 scoreIdx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto node = sc->rnn; subset.at(scoreIdx) = node->id; scoreIdx += 1; } JPP_DCHECK_EQ(scoreIdx, scoreCnt); return subset; } util::ConstSliceable<i32> gatherPrevStateIds(const rnn::RnnBoundary& rbnd) { auto subset = ctxIdBuf.topRows(rbnd.scoreCnt); auto cnt = ctxIdBuf.rowSize(); u32 scoreIdx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto node = sc->rnn; int idx = 0; auto row = subset.row(scoreIdx); auto prev = node->prev; for (; idx < cnt; ++idx) { JPP_DCHECK_NE(prev, nullptr); row.at(idx) = prev->id; } scoreIdx += 1; } JPP_DCHECK_EQ(scoreIdx, rbnd.scoreCnt); return subset; } util::ConstSliceable<float> gatherScoreContext(const rnn::RnnBoundary& rbnd) { auto subset = contextBuf.topRows(rbnd.scoreCnt); u32 idx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto node = sc->rnn; auto prev = node->prev; JPP_DCHECK_NE(prev, nullptr); auto ctxRow = subset.row(idx); auto present = contexts.at(prev->boundary).row(prev->idx); util::copy_buffer(present, ctxRow); idx += 1; } JPP_DCHECK_EQ(idx, rbnd.scoreCnt); return subset; } util::ConstSliceable<float> gatherNceEmbeds(util::ArraySlice<i32> ids) { auto subset = embBuf.topRows(ids.size()); for (int i = 0; i < ids.size(); ++i) { auto embedId = ids[i]; if (embedId == -1) { embedId = 0; } auto embed = shared->nceEmbedOf(embedId); auto target = subset.row(i); util::copy_buffer(embed, target); } return subset; } util::MutableArraySlice<float> resizeScores(i32 size) { size_t sz = static_cast<size_t>(size); util::MutableArraySlice<float> res{scoreBuf, 0, sz}; return res; } void copyScoresToLattice(util::MutableArraySlice<float> slice, const rnn::RnnBoundary& rbnd, u32 bndIdx) { auto bnd = lat->boundary(bndIdx); auto scoreStorage = bnd->scores(); u32 scoreIdx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto ptr = sc->latPtr; JPP_DCHECK_EQ(bndIdx, ptr->boundary); auto nodeScores = scoreStorage->nodeScores(ptr->right); float score; auto rnnId = sc->rnn->id; if (rnnId == shared->resolver.unkId()) { auto& cfg = shared->config; score = cfg.unkConstantTerm + cfg.unkLengthPenalty * sc->rnn->length; } else { score = slice.at(scoreIdx); } scoreIdx += 1; nodeScores.beamLeft(ptr->beam, ptr->left).at(scorerIdx) = score; } JPP_DCHECK_EQ(scoreIdx, rbnd.scoreCnt); } Status scoreBoundary(u32 bndIdx) { auto& rbnd = container.rnnBoundary(bndIdx); if (rbnd.nodeCnt == 0) { return Status::Ok(); } auto rnnIds = gatherScoreIds(rbnd); auto scores = resizeScores(rbnd.scoreCnt); jumanpp::rnn::mikolov::ParallelStepData psd{ gatherPrevStateIds(rbnd), rnnIds, gatherScoreContext(rbnd), gatherNceEmbeds(rnnIds), scores}; shared->rnn.applyParallel(&psd); copyScoresToLattice(scores, rbnd, bndIdx); return Status::Ok(); } Status scoreLattice(Lattice* l, const ExtraNodesContext* xtra) { this->lat = l; this->xtra = xtra; manager.reset(); alloc->reset(); auto numBnd = l->createdBoundaryCount() - 1; allocateState(); JPP_RETURN_IF_ERROR( shared->resolver.resolveIdsAtGbeam(&container, l, xtra)); for (u32 bndIdx = 2; bndIdx < numBnd; ++bndIdx) { JPP_RIE_MSG(computeContext(bndIdx), "bnd=" << bndIdx); } for (u32 bndIdx = 2; bndIdx <= numBnd; ++bndIdx) { JPP_RIE_MSG(scoreBoundary(bndIdx), "bnd=" << bndIdx); } return Status::Ok(); } }; RnnScorerGbeam::RnnScorerGbeam() = default; Status RnnScorerGbeam::scoreLattice(Lattice* l, const ExtraNodesContext* xtra, u32 scorerIdx) { state_->scorerIdx = scorerIdx; return state_->scoreLattice(l, xtra); } RnnScorerGbeam::~RnnScorerGbeam() = default; RnnScorerGbeamFactory::RnnScorerGbeamFactory() = default; Status RnnScorerGbeamFactory::makeInstance( std::unique_ptr<ScoreComputer>* result) { auto ptr = new RnnScorerGbeam; result->reset(ptr); ptr->state_.reset(new GbeamRnnState); ptr->state_->shared = state_.get(); return Status::Ok(); } Status RnnScorerGbeamFactory::make(StringPiece rnnModelPath, const dic::DictionaryHolder& dic, const rnn::RnnInferenceConfig& config) { state_.reset(new GbeamRnnFactoryState); JPP_RETURN_IF_ERROR(state_->rnnReader.open(rnnModelPath)); JPP_RETURN_IF_ERROR(state_->rnnReader.parse()); JPP_RETURN_IF_ERROR(state_->rnn.init(state_->rnnReader.header(), state_->rnnReader.rnnMatrix(), state_->rnnReader.maxentWeights())); setConfig(config); JPP_RETURN_IF_ERROR( state_->resolver.build(dic, state_->config, state_->rnnReader.words())); auto& h = state_->rnnReader.header(); state_->embeddings = {state_->rnnReader.embeddings(), h.layerSize, h.vocabSize}; state_->nceEmbeddings = {state_->rnnReader.nceEmbeddings(), h.layerSize, h.vocabSize}; if (h.layerSize > 64 * 1024) { return JPPS_NOT_IMPLEMENTED << "we don't support embed sizes > 64k"; } state_->computeBosState(0); return Status::Ok(); } const rnn::RnnInferenceConfig& RnnScorerGbeamFactory::config() const { return state_->config; } void RnnScorerGbeamFactory::setConfig(const rnn::RnnInferenceConfig& config) { JPP_DCHECK(state_); state_->config.mergeWith(config); if (!state_->config.nceBias.isDefault()) { state_->rnn.setNceConstant(state_->config.nceBias); } } struct RnnModelHeader { rnn::RnnInferenceConfig& config; i32 unkIdx; std::vector<u32> fields; jumanpp::rnn::mikolov::MikolovRnnModelHeader rnnHeader; }; template <typename Arch> void Serialize(Arch& a, RnnModelHeader& o) { a& o.config.nceBias; a& o.config.unkConstantTerm; a& o.config.unkLengthPenalty; a& o.config.perceptronWeight; a& o.config.rnnWeight; a& o.config.eosSymbol; a& o.config.unkSymbol; a& o.config.rnnFields; a& o.config.fieldSeparator; a& o.unkIdx; a& o.fields; a& o.rnnHeader.layerSize; a& o.rnnHeader.maxentOrder; a& o.rnnHeader.maxentSize; a& o.rnnHeader.vocabSize; a& o.rnnHeader.nceLnz; } Status RnnScorerGbeamFactory::makeInfo(model::ModelInfo* info, StringPiece comment) { if (!state_) { return JPPS_INVALID_STATE << "RnnScorerGbeamFactory was not initialized"; } RnnModelHeader header{ state_->config, state_->resolver.unkId(), {}, state_->rnn.modelHeader()}; util::copy_insert(state_->resolver.targets(), header.fields); util::serialization::Saver s{&state_->codedBuf_}; s.save(header); info->parts.emplace_back(); auto& part = info->parts.back(); part.comment = comment.str(); part.kind = model::ModelPartKind::Rnn; part.data.push_back(s.result()); part.data.push_back(state_->resolver.knownIndex()); part.data.push_back(state_->resolver.unkIndex()); part.data.push_back(state_->rnnMatrix()); part.data.push_back(state_->embeddingData()); part.data.push_back(state_->nceEmbedData()); part.data.push_back(state_->maxentWeightData()); return Status::Ok(); } Status arr2d(StringPiece data, size_t nrows, size_t ncols, util::ConstSliceable<float>* result) { if (nrows * ncols * sizeof(float) < data.size()) { return JPPS_INVALID_PARAMETER << "failed to create ConstSliceable from memory buffer of " << data.size() << " need at least " << nrows * ncols * sizeof(float); } util::ArraySlice<float> wrap{reinterpret_cast<const float*>(data.data()), nrows * ncols}; *result = util::ConstSliceable<float>{wrap, ncols, nrows}; return Status::Ok(); } Status arr1d(StringPiece data, size_t expected, util::ArraySlice<float>* result) { if (expected * sizeof(float) < data.size()) { return JPPS_INVALID_PARAMETER << "failed to create ConstSliceable from memory buffer of " << data.size() << " need at least " << expected * sizeof(float); } *result = util::ArraySlice<float>{reinterpret_cast<const float*>(data.data()), expected}; return Status::Ok(); } Status RnnScorerGbeamFactory::load(const model::ModelInfo& model) { state_.reset(new GbeamRnnFactoryState); auto p = model.firstPartOf(model::ModelPartKind::Rnn); if (p == nullptr) { return JPPS_INVALID_PARAMETER << "model file did not contain RNN"; } RnnModelHeader header{state_->config, {}, {}, {}}; util::serialization::Loader l{p->data[0]}; if (!l.load(&header)) { return JPPS_INVALID_PARAMETER << "failed to read RNN header"; } JPP_RETURN_IF_ERROR(state_->resolver.setState(header.fields, p->data[1], p->data[2], header.unkIdx)); auto& rnnhdr = header.rnnHeader; util::ArraySlice<float> rnnMatrix; util::ArraySlice<float> maxentWeights; JPP_RIE_MSG( arr1d(p->data[3], rnnhdr.layerSize * rnnhdr.vocabSize, &rnnMatrix), "failed to read matrix"); JPP_RIE_MSG(arr2d(p->data[4], rnnhdr.vocabSize, rnnhdr.layerSize, &state_->embeddings), "failed to read embeddings"); JPP_RIE_MSG(arr2d(p->data[5], rnnhdr.vocabSize, rnnhdr.layerSize, &state_->nceEmbeddings), "failed to read NCE embeddings"); JPP_RIE_MSG(arr1d(p->data[6], rnnhdr.maxentSize, &maxentWeights), "failed to read NCE embeddings"); JPP_RETURN_IF_ERROR(state_->rnn.init(rnnhdr, rnnMatrix, maxentWeights)); state_->computeBosState(0); return Status::Ok(); } RnnScorerGbeamFactory::~RnnScorerGbeamFactory() = default; } // namespace analysis } // namespace core } // namespace jumanpp
32.929032
80
0.655499
5003
f60bc96391cc2c3004599c52dec37ec03c42b482
11,188
hpp
C++
mjolnir/forcefield/external/RectangularBoxInteraction.hpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
12
2017-02-01T08:28:38.000Z
2018-08-25T15:47:51.000Z
mjolnir/forcefield/external/RectangularBoxInteraction.hpp
Mjolnir-MD/Mjolnir
043df4080720837042c6b67a5495ecae198bc2b3
[ "MIT" ]
60
2019-01-14T08:11:33.000Z
2021-07-29T08:26:36.000Z
mjolnir/forcefield/external/RectangularBoxInteraction.hpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
8
2019-01-13T11:03:31.000Z
2021-08-01T11:38:00.000Z
#ifndef MJOLNIR_INTERACTION_EXTERNAL_RECTANGULAR_BOX_INTERACTION_HPP #define MJOLNIR_INTERACTION_EXTERNAL_RECTANGULAR_BOX_INTERACTION_HPP #include <mjolnir/core/ExternalForceInteractionBase.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/math/math.hpp> #include <mjolnir/util/format_nth.hpp> namespace mjolnir { /*! @brief Interaction between particle and a box. */ template<typename traitsT, typename potentialT> class RectangularBoxInteraction final : public ExternalForceInteractionBase<traitsT> { public: using traits_type = traitsT; using potential_type = potentialT; using base_type = ExternalForceInteractionBase<traitsT>; using real_type = typename base_type::real_type; using coordinate_type = typename base_type::coordinate_type; using system_type = typename base_type::system_type; using boundary_type = typename base_type::boundary_type; public: RectangularBoxInteraction( const coordinate_type& lower, const coordinate_type& upper, const real_type margin, potential_type&& pot) : cutoff_(-1), margin_(margin), current_margin_(-1), lower_(lower), upper_(upper), neighbors_{}, potential_(std::move(pot)) { MJOLNIR_GET_DEFAULT_LOGGER(); if(!is_unlimited_boundary<boundary_type>::value) { const auto msg = "RectangularBox cannot be used under the periodic " "boundary condition. Use unlimited boundary."; MJOLNIR_LOG_ERROR(msg); throw std::runtime_error(msg); } assert(math::X(lower_) < math::X(upper_)); assert(math::Y(lower_) < math::Y(upper_)); assert(math::Z(lower_) < math::Z(upper_)); } ~RectangularBoxInteraction() override {} // calculate force, update spatial partition (reduce margin) inside. void calc_force (system_type&) const noexcept override; real_type calc_energy(system_type const&) const noexcept override; real_type calc_force_and_energy(system_type&) const noexcept override; /*! @brief initialize spatial partition (e.g. CellList) * * @details before calling `calc_(force|energy)`, this should be called. */ void initialize(const system_type& sys) override { this->potential_.update(sys); // update system parameters this->cutoff_ = this->potential_.max_cutoff_length(); this->make(sys); // update neighbor list return; } /*! @brief update parameters (e.g. temperature, ionic strength, ...) * * @details A method that change system parameters (e.g. Annealing), * * the method is bound to call this function after changing * * parameters. */ void update(const system_type& sys) override { this->potential_.update(sys); // update system parameters this->make(sys); // update neighbor list } void reduce_margin(const real_type dmargin, const system_type& sys) override { this->current_margin_ -= dmargin; if(this->current_margin_ < 0) { this->make(sys); } return; } void scale_margin(const real_type scale, const system_type& sys) override { this->current_margin_ = (cutoff_ + current_margin_) * scale - cutoff_; if(this->current_margin_ < 0) { this->make(sys); } return; } std::string name() const override {return "RectangularBox:"_s + potential_.name();} base_type* clone() const override { return new RectangularBoxInteraction(lower_, upper_, margin_, potential_type(potential_)); } // for tests coordinate_type const& upper() const noexcept {return upper_;} coordinate_type const& lower() const noexcept {return lower_;} potential_type const& potential() const noexcept {return potential_;} private: // construct a neighbor-list. // Also, check if all the particles are inside of the box. void make(const system_type& sys) { MJOLNIR_GET_DEFAULT_LOGGER(); const real_type threshold = this->cutoff_ * (1 + this->margin_); this->neighbors_.clear(); for(std::size_t i : this->potential_.participants()) { const auto& pos = sys.position(i); // Assuming that PBC and Box interaction will not be used together const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; // check if all the particles are inside of the box. if(math::X(dr_u) < 0 || math::Y(dr_u) < 0 || math::Z(dr_u) < 0) { MJOLNIR_LOG_ERROR(format_nth(i), " particle, ", pos, " exceeds the upper bound, ", this->upper_); throw_exception<std::runtime_error>(format_nth(i), " particle ", pos, " exceeds the upper bound, ", this->upper_); } if(math::X(dr_l) < 0 || math::Y(dr_l) < 0 || math::Z(dr_l) < 0) { MJOLNIR_LOG_ERROR(format_nth(i), " particle, ", pos, " exceeds the lower bound, ", this->lower_); throw_exception<std::runtime_error>(format_nth(i), " particle ", pos, " exceeds the lower bound, ", this->lower_); } // assign particles that are within the cutoff range. if(math::X(dr_u) <= threshold || math::X(dr_l) <= threshold || math::Y(dr_u) <= threshold || math::Y(dr_l) <= threshold || math::Z(dr_u) <= threshold || math::Z(dr_l) <= threshold) { neighbors_.push_back(i); } } this->current_margin_ = this->cutoff_ * this->margin_; return; } private: real_type cutoff_, margin_, current_margin_; coordinate_type lower_, upper_; std::vector<std::size_t> neighbors_; potential_type potential_; // #ifdef MJOLNIR_WITH_OPENMP // // OpenMP implementation uses its own implementation to run it in parallel. // // So this implementation should not be instanciated with OpenMP Traits. // static_assert(!is_openmp_simulator_traits<traits_type>::value, // "this is the default implementation, not for OpenMP"); // #endif }; template<typename traitsT, typename potT> void RectangularBoxInteraction<traitsT, potT>::calc_force( system_type& sys) const noexcept { // Here we assume that all the particles are inside of the box. // Also we assume that no boundary condition is applied. for(const std::size_t i : this->neighbors_) { const auto& pos = sys.position(i); const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; const auto dx_u = this->potential_.derivative(i, math::X(dr_u)); const auto dx_l = this->potential_.derivative(i, math::X(dr_l)); const auto dy_u = this->potential_.derivative(i, math::Y(dr_u)); const auto dy_l = this->potential_.derivative(i, math::Y(dr_l)); const auto dz_u = this->potential_.derivative(i, math::Z(dr_u)); const auto dz_l = this->potential_.derivative(i, math::Z(dr_l)); sys.force(i) += math::make_coordinate<coordinate_type>( dx_u - dx_l, dy_u - dy_l, dz_u - dz_l); } return ; } template<typename traitsT, typename potT> typename RectangularBoxInteraction<traitsT, potT>::real_type RectangularBoxInteraction<traitsT, potT>::calc_energy( const system_type& sys) const noexcept { real_type E = 0.0; for(const std::size_t i : this->neighbors_) { const auto& pos = sys.position(i); const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; E += this->potential_.potential(i, math::X(dr_u)) + this->potential_.potential(i, math::X(dr_l)) + this->potential_.potential(i, math::Y(dr_u)) + this->potential_.potential(i, math::Y(dr_l)) + this->potential_.potential(i, math::Z(dr_u)) + this->potential_.potential(i, math::Z(dr_l)); } return E; } template<typename traitsT, typename potT> typename RectangularBoxInteraction<traitsT, potT>::real_type RectangularBoxInteraction<traitsT, potT>::calc_force_and_energy( system_type& sys) const noexcept { real_type E = 0.0; for(const std::size_t i : this->neighbors_) { const auto& pos = sys.position(i); const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; const auto dx_u = this->potential_.derivative(i, math::X(dr_u)); const auto dx_l = this->potential_.derivative(i, math::X(dr_l)); const auto dy_u = this->potential_.derivative(i, math::Y(dr_u)); const auto dy_l = this->potential_.derivative(i, math::Y(dr_l)); const auto dz_u = this->potential_.derivative(i, math::Z(dr_u)); const auto dz_l = this->potential_.derivative(i, math::Z(dr_l)); sys.force(i) += math::make_coordinate<coordinate_type>( dx_u - dx_l, dy_u - dy_l, dz_u - dz_l); E += this->potential_.potential(i, math::X(dr_u)) + this->potential_.potential(i, math::X(dr_l)) + this->potential_.potential(i, math::Y(dr_u)) + this->potential_.potential(i, math::Y(dr_l)) + this->potential_.potential(i, math::Z(dr_u)) + this->potential_.potential(i, math::Z(dr_l)); } return E; } } // mjolnir #ifdef MJOLNIR_SEPARATE_BUILD #include <mjolnir/forcefield/external/ExcludedVolumeWallPotential.hpp> #include <mjolnir/forcefield/external/LennardJonesWallPotential.hpp> namespace mjolnir { extern template class RectangularBoxInteraction<SimulatorTraits<double, UnlimitedBoundary>, ExcludedVolumeWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, UnlimitedBoundary>, ExcludedVolumeWallPotential<float >>; extern template class RectangularBoxInteraction<SimulatorTraits<double, CuboidalPeriodicBoundary>, ExcludedVolumeWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, CuboidalPeriodicBoundary>, ExcludedVolumeWallPotential<float >>; extern template class RectangularBoxInteraction<SimulatorTraits<double, UnlimitedBoundary>, LennardJonesWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, UnlimitedBoundary>, LennardJonesWallPotential<float >>; extern template class RectangularBoxInteraction<SimulatorTraits<double, CuboidalPeriodicBoundary>, LennardJonesWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, CuboidalPeriodicBoundary>, LennardJonesWallPotential<float >>; } // mjolnir #endif // MJOLNIR_SEPARATE_BUILD #endif//MJOLNIR_BOX_INTEARACTION_BASE
41.437037
136
0.642653
yutakasi634
f60d8f801c3ac8ed0863421791d74c5702f9b223
1,836
hpp
C++
src/bwt.hpp
SebWouters/aiss4
f46ea04e573b77abec74459f018d32bd0bdc8865
[ "BSD-3-Clause" ]
null
null
null
src/bwt.hpp
SebWouters/aiss4
f46ea04e573b77abec74459f018d32bd0bdc8865
[ "BSD-3-Clause" ]
null
null
null
src/bwt.hpp
SebWouters/aiss4
f46ea04e573b77abec74459f018d32bd0bdc8865
[ "BSD-3-Clause" ]
null
null
null
/* aiss4: suffix array via induced sorting Copyright (c) 2020, Sebastian Wouters All rights reserved. This file is part of aiss4, licensed under the BSD 3-Clause License. A copy of the License can be found in the file LICENSE in the root folder of this project. */ #pragma once #include <stdint.h> #include <stdlib.h> namespace aiss4 { void decode(const int32_t pointer, const uint8_t * encoded, uint8_t * decoded, const int32_t size) { if (pointer < 0 || size < 1 || encoded == NULL || decoded == NULL) return; int32_t * map = new int32_t[size]; int32_t * head = new int32_t[256]; for (int32_t sym = 0; sym < 256; ++sym) head[sym] = 0; for (int32_t idx = 0; idx < size; ++idx) map[idx] = head[encoded[idx]]++; int32_t total = 1; // Sentinel '$' for (int32_t sym = 0; sym < 256; ++sym) { int32_t tmp = head[sym]; head[sym] = total; total += tmp; } int32_t idx = 0; // map[pointer] + head[$] = 0 for (int32_t cnt = 0; cnt < size; ++cnt) { idx = idx < pointer ? idx : idx - 1; // Sentinel '$' not represented in encoded uint8_t sym = encoded[idx]; decoded[size - 1 - cnt] = sym; idx = map[idx] + head[sym]; } delete [] map; delete [] head; } int32_t encode(const uint8_t * orig, const int32_t * suffix, uint8_t * encoded, const int32_t size) { if (size < 1 || orig == NULL || suffix == NULL || encoded == NULL) return -1; encoded[0] = orig[size - 1]; int32_t target = 1; int32_t pointer = -1; for (int32_t idx = 0; idx < size; ++idx) { if (suffix[idx] == 0) pointer = idx + 1; else encoded[target++] = orig[suffix[idx] - 1]; } return pointer; } } // End of namespace aiss4
23.844156
99
0.562092
SebWouters
f610e7915dfa37bc2766ed278f867b9770dbb6dd
8,779
inl
C++
include/hfsm/detail/machine_composite_methods.inl
kgreenek/HFSM
4a6f5bf6fb868c05ea797f1b8d33073eee461a0b
[ "MIT" ]
74
2017-04-11T20:54:20.000Z
2021-09-01T06:31:01.000Z
include/hfsm/detail/machine_composite_methods.inl
kgreenek/HFSM
4a6f5bf6fb868c05ea797f1b8d33073eee461a0b
[ "MIT" ]
14
2018-01-04T03:54:00.000Z
2018-07-02T22:34:12.000Z
include/hfsm/detail/machine_composite_methods.inl
kgreenek/HFSM
4a6f5bf6fb868c05ea797f1b8d33073eee461a0b
[ "MIT" ]
33
2017-04-12T13:11:37.000Z
2022-01-06T02:06:07.000Z
namespace hfsm { //////////////////////////////////////////////////////////////////////////////// template <typename TC, unsigned TMS> template <typename TH, typename... TS> M<TC, TMS>::_C<TH, TS...>::_C(StateRegistry& stateRegistry, const Parent parent, Parents& stateParents, Parents& forkParents, ForkPointers& forkPointers) : _fork(static_cast<Index>(forkPointers << &_fork), parent, forkParents) , _state(stateRegistry, parent, stateParents, forkParents, forkPointers) , _subStates(stateRegistry, _fork.self, stateParents, forkParents, forkPointers) {} //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepForwardSubstitute(Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.requested != INVALID_INDEX); if (_fork.requested == _fork.active) _subStates.wideForwardSubstitute(_fork.requested, control, context, logger); else _subStates.wideSubstitute (_fork.requested, control, context, logger); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepSubstitute(Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.active == INVALID_INDEX && _fork.requested != INVALID_INDEX); if (!_state .deepSubstitute( control, context, logger)) _subStates.wideSubstitute(_fork.requested, control, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepEnterInitial(Context& context, LoggerInterface* const logger) { assert(_fork.active == INVALID_INDEX && _fork.resumable == INVALID_INDEX && _fork.requested == INVALID_INDEX); HSFM_IF_DEBUG(_fork.activeType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.active = 0; _state .deepEnter (context, logger); _subStates.wideEnterInitial(context, logger); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepEnter(Context& context, LoggerInterface* const logger) { assert(_fork.active == INVALID_INDEX && _fork.requested != INVALID_INDEX); HSFM_IF_DEBUG(_fork.activeType = _fork.requestedType); _fork.active = _fork.requested; HSFM_IF_DEBUG(_fork.requestedType.clear()); _fork.requested = INVALID_INDEX; _state .deepEnter( context, logger); _subStates.wideEnter(_fork.active, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> bool M<TC, TMS>::_C<TH, TS...>::deepUpdateAndTransition(Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); if (_state.deepUpdateAndTransition(control, context, logger)) { _subStates.wideUpdate(_fork.active, context, logger); return true; } else return _subStates.wideUpdateAndTransition(_fork.active, control, context, logger); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepUpdate(Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); _state .deepUpdate( context, logger); _subStates.wideUpdate(_fork.active, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> template <typename TEvent> void M<TC, TMS>::_C<TH, TS...>::deepReact(const TEvent& event, Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); _state .deepReact( event, control, context, logger); _subStates.wideReact(_fork.active, event, control, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepLeave(Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); _subStates.wideLeave(_fork.active, context, logger); _state .deepLeave( context, logger); HSFM_IF_DEBUG(_fork.resumableType = _fork.activeType); _fork.resumable = _fork.active; HSFM_IF_DEBUG(_fork.activeType.clear()); _fork.active = INVALID_INDEX; } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepForwardRequest(const enum Transition::Type transition) { if (_fork.requested != INVALID_INDEX) _subStates.wideForwardRequest(_fork.requested, transition); else switch (transition) { case Transition::Remain: deepRequestRemain(); break; case Transition::Restart: deepRequestRestart(); break; case Transition::Resume: deepRequestResume(); break; default: assert(false); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepRequestRemain() { if (_fork.active == INVALID_INDEX) { HSFM_IF_DEBUG(_fork.requestedType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.requested = 0; } _subStates.wideRequestRemain(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepRequestRestart() { HSFM_IF_DEBUG(_fork.requestedType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.requested = 0; _subStates.wideRequestRestart(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepRequestResume() { if (_fork.resumable != INVALID_INDEX) { HSFM_IF_DEBUG(_fork.requestedType = _fork.resumableType); _fork.requested = _fork.resumable; } else { HSFM_IF_DEBUG(_fork.requestedType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.requested = 0; } _subStates.wideRequestResume(_fork.requested); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepChangeToRequested(Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); if (_fork.requested == _fork.active) _subStates.wideChangeToRequested(_fork.requested, context, logger); else if (_fork.requested != INVALID_INDEX) { _subStates.wideLeave(_fork.active, context, logger); HSFM_IF_DEBUG(_fork.resumableType = _fork.activeType); _fork.resumable = _fork.active; HSFM_IF_DEBUG(_fork.activeType = _fork.requestedType); _fork.active = _fork.requested; HSFM_IF_DEBUG(_fork.requestedType.clear()); _fork.requested = INVALID_INDEX; _subStates.wideEnter(_fork.active, context, logger); } } //------------------------------------------------------------------------------ #ifdef HFSM_ENABLE_STRUCTURE_REPORT template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepGetNames(const unsigned parent, const enum StateInfo::RegionType region, const unsigned depth, StateInfos& _stateInfos) const { _state.deepGetNames(parent, region, depth, _stateInfos); _subStates.wideGetNames(_stateInfos.count() - 1, depth + 1, _stateInfos); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepIsActive(const bool isActive, unsigned& index, MachineStructure& structure) const { _state.deepIsActive(isActive, index, structure); _subStates.wideIsActive(isActive ? _fork.active : INVALID_INDEX, index, structure); } #endif //////////////////////////////////////////////////////////////////////////////// }
30.065068
90
0.598929
kgreenek
f61211199fcc49d95fc860f04c824dacf4dbf7e4
1,033
cpp
C++
src/system/boot/platform/next_m68k/devices.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/system/boot/platform/next_m68k/devices.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/system/boot/platform/next_m68k/devices.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2008-2010, François Revol, revol@free.fr. All rights reserved. * Copyright 2003-2006, Axel Dörfler, axeld@pinc-software.de. * Distributed under the terms of the MIT License. */ #include <KernelExport.h> #include <boot/platform.h> #include <boot/partitions.h> #include <boot/stdio.h> #include <boot/stage2.h> #include <string.h> #include "nextrom.h" //#define TRACE_DEVICES #ifdef TRACE_DEVICES # define TRACE(x) dprintf x #else # define TRACE(x) ; #endif static bool sBlockDevicesAdded = false; // #pragma mark - status_t platform_add_boot_device(struct stage2_args *args, NodeList *devicesList) { return B_UNSUPPORTED; } status_t platform_get_boot_partitions(struct stage2_args *args, Node *device, NodeList *list, NodeList *partitionList) { return B_ENTRY_NOT_FOUND; } status_t platform_add_block_devices(stage2_args *args, NodeList *devicesList) { return B_UNSUPPORTED; } status_t platform_register_boot_device(Node *device) { return B_UNSUPPORTED; } void platform_cleanup_devices() { }
15.892308
75
0.760891
Yn0ga
f612765de4f9bd0c76d35caea168de5b8a018dc8
9,805
cpp
C++
source/details/StackTraceGnu-inl.cpp
aminya/cppassert
a686985e16698dfbcfa60e512c33a2eedf240892
[ "BSD-3-Clause" ]
3
2016-05-12T13:21:26.000Z
2019-02-06T14:00:24.000Z
source/details/StackTraceGnu-inl.cpp
aminya/cppassert
a686985e16698dfbcfa60e512c33a2eedf240892
[ "BSD-3-Clause" ]
1
2022-02-17T23:07:54.000Z
2022-02-17T23:07:54.000Z
source/details/StackTraceGnu-inl.cpp
DariuszOstolski/cppassert
3b0c3f800297e368a7c452ec039c3eba268fbfd3
[ "BSD-3-Clause" ]
null
null
null
#include <cppassert/details/StackTrace.hpp> #include <cstdlib> #include <cstring> #include <execinfo.h> #include <cxxabi.h> #include <sstream> namespace cppassert { namespace internal { /** * Provides C++ symbol demangling */ class CppDemangler { CppDemangler(const CppDemangler &) = delete; CppDemangler &operator=(const CppDemangler &) = delete; public: CppDemangler() { funcName_ = static_cast<char *>(std::malloc(funcNameSize_)); } ~CppDemangler() { if(funcName_) { std::free(funcName_); } } /** * Demangle C++ symbol name * @param funcName C++ mangled symbol name * @return Demangled name for immediate use only */ const char *demangle(const char *funcName) { std::int32_t status = 0; //malloc failed to allocate if(funcName_==nullptr) { return nullptr; } char* result = abi::__cxa_demangle(funcName, funcName_, &funcNameSize_, &status); if (status == 0) { //use value that could have been reallocated funcName_ = result; } else { //demangling failed, just return null result = nullptr; } return result; } private: std::size_t funcNameSize_ = 256; char* funcName_ = nullptr; }; /** * An intelligent wrapper around symbols that may need or may not need * to be deallocated. If symbol was not demangled we shouldn't allocate/deallocate * any space just copy a pointer to it. If demangling was successfull it allocates * required space and manages lifetime for that space. * */ class BackTraceSymbol { BackTraceSymbol(const BackTraceSymbol &) = delete; BackTraceSymbol &operator=(const BackTraceSymbol &) = delete; static constexpr const char *UnkownSymbol = "<unkown>"; public: BackTraceSymbol() { } ~BackTraceSymbol() { deallocate(); } /** * Set values for demangled symbols. It allocates required space * and makes a deep copy * * @param backtrace String returned from backtrace_symbol * @param demangledName Demangled symbol name as string * @param offset Symbol offset */ void setSymbol(const char *backtrace , const char *demangledName , const char *offset) { deallocate(); std::size_t backTraceLength = std::strlen(backtrace); std::size_t nameLength = std::strlen(demangledName); std::size_t offsetLength = std::strlen(offset)+1; allocated_ = static_cast<char *>( std::malloc(backTraceLength+nameLength+offsetLength+2)); if(!allocated_) { return; } char *begin = allocated_; std::strcpy(allocated_, backtrace); begin += backTraceLength; std::strcpy(begin, "("); begin += 1; std::strcpy(begin, demangledName); begin += nameLength; std::strcpy(begin, "+"); begin += 1; std::strcpy(begin, offset); symbol_ = allocated_; } /** * Set value to symbol. It's a pointer returned by `backtrace_symbols` * function. Only pointer value is copied, life time of this pointer * is managed by class that will manage life time of this class * * @param symbol String returned from `backtrace_symbols` function * */ void setSymbol(const char *symbol) { deallocate(); symbol_ = symbol; } /** * Searches for a symbol in a string returned by backrace function * @param[in] backTraceSymbol String returned from backtrace function * @param[out] beginNamePtr Position where symbol name begins * @param[out] beginOffsetPtr Position where offset begins * @param[out] endOffsetPtr Position where offset ends */ static void findSymbolInBacktraceStr( char *backTraceSymbol , char **beginNamePtr , char **beginOffsetPtr , char **endOffsetPtr) { char *beginName = 0, *beginOffset = 0, *endOffset = 0; for (char *position = backTraceSymbol; *position; ++position) { if (*position == '(') { beginName = position; } else if (*position == '+') { beginOffset = position; } else if (*position == ')' && beginOffset) { endOffset = position; break; } } *beginNamePtr = beginName; *beginOffsetPtr = beginOffset; *endOffsetPtr = endOffset; } /** * Parses \p backTraceSymbol string and returns corresponding C++ object * @param backTraceSymbol String returned by `backtrace_symbol` function * @param demangler Object that will be used to demangle names * @return BackTraceSymbol object */ static BackTraceSymbol createFromBacktraceStr(char *backTraceSymbol , CppDemangler *demangler) { BackTraceSymbol result; char *beginName = 0, *beginOffset = 0, *endOffset = 0; findSymbolInBacktraceStr(backTraceSymbol , &beginName , &beginOffset , &endOffset); if (beginName && beginOffset && endOffset && beginName < beginOffset) { *beginName++ = '\0'; *beginOffset++ = '\0'; const char *demangledSymbol = demangler->demangle(beginName); if(demangledSymbol) { result.setSymbol(backTraceSymbol, demangledSymbol, beginOffset); } else { //restore previous state --beginName; --beginOffset; *beginName = '('; *beginOffset = '+'; result.setSymbol(backTraceSymbol); } } else { result.setSymbol(backTraceSymbol); } return result; } /** * Returns value of symbol * @return Symbol as string */ const char *symbol() const { return symbol_; } /** * Move assignment constructor * @param other Object to be moved */ BackTraceSymbol(BackTraceSymbol && other) { allocated_ = other.allocated_; symbol_ = other.symbol_; other.allocated_ = nullptr; other.symbol_ = nullptr; } /** * Move assignment operator * @param other Object to be moved */ BackTraceSymbol &operator=(BackTraceSymbol &&other) { deallocate(); allocated_ = other.allocated_; symbol_ = other.symbol_; other.allocated_ = nullptr; other.symbol_ = nullptr; return (*this); } private: void deallocate() { if(allocated_) { std::free(allocated_); allocated_ = nullptr; } } const char *symbol_ = UnkownSymbol; char *allocated_ = nullptr; }; /** * StackTrace implementation for platforms where backtrace/backtrace_symbols * functions are available */ class StackTraceImpl { StackTraceImpl(const StackTraceImpl &) = delete; StackTraceImpl &operator=(const StackTraceImpl &) = delete; public: StackTraceImpl() { } ~StackTraceImpl() { freeSymbols(); } /** * Collects current stack trace */ void collect() { freeSymbols(); CppDemangler demangler; backtraceSize_ = ::backtrace(backtrace_, BufferSize); symbols_ = ::backtrace_symbols(backtrace_, backtraceSize_); for(std::size_t i=cFramesToSkip; i<backtraceSize_; ++i) { if(symbols_) { demangledSymbols_[i] = BackTraceSymbol::createFromBacktraceStr(symbols_[i] , &demangler); } else { demangledSymbols_[i] = BackTraceSymbol(); } frames_[i-cFramesToSkip] = StackTrace::StackFrame(backtrace_[i] , demangledSymbols_[i].symbol()); } } /** * Returns number of frames * @return Number of frames */ std::size_t size() const { return (backtraceSize_-cFramesToSkip); } /** * Returns stack frame at \p position, if position is greater * that size `std::out_of_range` exception is thrown * @param position Number of frame to be returned * @return StackFrame at \p position */ const StackTrace::StackFrame &at(std::size_t position) const { if(position<(backtraceSize_-cFramesToSkip)) { return frames_[position]; } std::stringstream msg; msg << "StackFrame::at: Position "<<position << " is out of range: 0 and "<<size(); throw std::out_of_range(msg.str()); //make compiler happy return frames_[0]; } private: enum { BufferSize = 256 }; enum { cFramesToSkip = 2 }; void freeSymbols() { if(symbols_) { std::free(symbols_); } } char **symbols_ = nullptr; void *backtrace_[BufferSize]; StackTrace::StackFrame frames_[BufferSize]; BackTraceSymbol demangledSymbols_[BufferSize]; std::size_t backtraceSize_ = 0; }; } //internal } //asrt
26.077128
82
0.550025
aminya
f614c01aaa6ff892bbee02b8ba5a14cca3d9c155
450
cpp
C++
series2_workbench/hyp_sys_1d/src/ancse/boundary_condition.cpp
BeatHubmann/19H-AdvNCSE
3979f768da933de82bd6ab29bbf31ea9fc31e501
[ "MIT" ]
1
2020-01-05T22:38:47.000Z
2020-01-05T22:38:47.000Z
series2_handout/hyp_sys_1d/src/ancse/boundary_condition.cpp
BeatHubmann/19H-AdvNCSE
3979f768da933de82bd6ab29bbf31ea9fc31e501
[ "MIT" ]
null
null
null
series2_handout/hyp_sys_1d/src/ancse/boundary_condition.cpp
BeatHubmann/19H-AdvNCSE
3979f768da933de82bd6ab29bbf31ea9fc31e501
[ "MIT" ]
1
2019-12-08T20:43:27.000Z
2019-12-08T20:43:27.000Z
#include <ancse/boundary_condition.hpp> #include <fmt/format.h> std::shared_ptr<BoundaryCondition> make_boundary_condition(int n_ghost, const std::string &bc_key) { if (bc_key == "periodic") { return std::make_shared<PeriodicBC>(n_ghost); } if (bc_key == "outflow") { return std::make_shared<OutflowBC>(n_ghost); } throw std::runtime_error( fmt::format("Unknown boundary condition. [{}]", bc_key)); }
23.684211
65
0.66
BeatHubmann
f61a2e86ccbfdb9510471373060b43b0ef035805
1,778
cpp
C++
modules/fsio/tests/src/disk_device.cpp
hfarrow/Fissura
0ccc319b55f8dc99af712c95580342430444bc29
[ "MIT" ]
null
null
null
modules/fsio/tests/src/disk_device.cpp
hfarrow/Fissura
0ccc319b55f8dc99af712c95580342430444bc29
[ "MIT" ]
null
null
null
modules/fsio/tests/src/disk_device.cpp
hfarrow/Fissura
0ccc319b55f8dc99af712c95580342430444bc29
[ "MIT" ]
null
null
null
#include <cstdio> #include <boost/test/unit_test.hpp> #include "global_fixture.h" #include "fstest.h" #include "fscore.h" #include "fsmem.h" #include "fsio.h" using namespace fs; using FileArena = MemoryArena<Allocator<HeapAllocator, AllocationHeaderU32>, MultiThread<MutexPrimitive>, SimpleBoundsChecking, FullMemoryTracking, MemoryTagging>; struct DiskDeviceFixture { DiskDeviceFixture() : area(FS_SIZE_OF_MB * 4), arena(area, "FileArena"), gf(GlobalFixture::instance()) { } ~DiskDeviceFixture() { } HeapArea area; FileArena arena; GlobalFixture* gf; }; BOOST_AUTO_TEST_SUITE(io) BOOST_FIXTURE_TEST_SUITE(disk_device, DiskDeviceFixture) BOOST_AUTO_TEST_CASE(create_device) { FileSystem<FileArena> filesys(&arena); DiskDevice device; BOOST_CHECK(device.getType() == "disk"); } BOOST_AUTO_TEST_CASE(open_file_and_close) { FileSystem<FileArena> filesys(&arena); DiskDevice device; auto file = device.open(&filesys, nullptr, gf->path("content/empty.bin"), IFileSystem::Mode::READ); BOOST_REQUIRE(file); BOOST_REQUIRE(file->opened()); BOOST_CHECK(strcmp(file->getName(), gf->path("content/empty.bin")) == 0); filesys.close(file); BOOST_REQUIRE(!file->opened()); } BOOST_AUTO_TEST_CASE(open_with_invalid_device_list) { FileSystem<FileArena> filesys(&arena); DiskDevice device; auto lambda = [&]() { auto file = device.open(&filesys, "some:other:devices", gf->path("content/empty.bin"), IFileSystem::Mode::READ); }; FS_REQUIRE_ASSERT(lambda); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
22.794872
120
0.652981
hfarrow
f61d2dfd00d13a3a9778cff498e45fc067422dad
20,005
hpp
C++
modules/cudafeatures2d/include/opencv2/cudafeatures2d.hpp
liuhuanjim013/opencv
ac5e5adb6fbefa16bb48257cf534f1d55811603e
[ "BSD-3-Clause" ]
1
2020-11-12T03:37:51.000Z
2020-11-12T03:37:51.000Z
modules/cudafeatures2d/include/opencv2/cudafeatures2d.hpp
liuhuanjim013/opencv
ac5e5adb6fbefa16bb48257cf534f1d55811603e
[ "BSD-3-Clause" ]
null
null
null
modules/cudafeatures2d/include/opencv2/cudafeatures2d.hpp
liuhuanjim013/opencv
ac5e5adb6fbefa16bb48257cf534f1d55811603e
[ "BSD-3-Clause" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #ifndef __OPENCV_CUDAFEATURES2D_HPP__ #define __OPENCV_CUDAFEATURES2D_HPP__ #ifndef __cplusplus # error cudafeatures2d.hpp header must be compiled as C++ #endif #include "opencv2/core/cuda.hpp" #include "opencv2/cudafilters.hpp" /** @addtogroup cuda @{ @defgroup cudafeatures2d Feature Detection and Description @} */ namespace cv { namespace cuda { //! @addtogroup cudafeatures2d //! @{ /** @brief Brute-force descriptor matcher. For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. This descriptor matcher supports masking permissible matches between descriptor sets. The class BFMatcher_CUDA has an interface similar to the class DescriptorMatcher. It has two groups of match methods: for matching descriptors of one image with another image or with an image set. Also, all functions have an alternative to save results either to the GPU memory or to the CPU memory. @sa DescriptorMatcher, BFMatcher */ class CV_EXPORTS BFMatcher_CUDA { public: explicit BFMatcher_CUDA(int norm = cv::NORM_L2); //! Add descriptors to train descriptor collection void add(const std::vector<GpuMat>& descCollection); //! Get train descriptors collection const std::vector<GpuMat>& getTrainDescriptors() const; //! Clear train descriptors collection void clear(); //! Return true if there are not train descriptors in collection bool empty() const; //! Return true if the matcher supports mask in match methods bool isMaskSupported() const; //! Find one best match for each query descriptor void matchSingle(const GpuMat& query, const GpuMat& train, GpuMat& trainIdx, GpuMat& distance, const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx and distance and convert it to CPU vector with DMatch static void matchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector<DMatch>& matches); //! Convert trainIdx and distance to vector with DMatch static void matchConvert(const Mat& trainIdx, const Mat& distance, std::vector<DMatch>& matches); //! Find one best match for each query descriptor void match(const GpuMat& query, const GpuMat& train, std::vector<DMatch>& matches, const GpuMat& mask = GpuMat()); //! Make gpu collection of trains and masks in suitable format for matchCollection function void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const std::vector<GpuMat>& masks = std::vector<GpuMat>()); //! Find one best match from train collection for each query descriptor void matchCollection(const GpuMat& query, const GpuMat& trainCollection, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, const GpuMat& masks = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx, imgIdx and distance and convert it to vector with DMatch static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector<DMatch>& matches); //! Convert trainIdx, imgIdx and distance to vector with DMatch static void matchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector<DMatch>& matches); //! Find one best match from train collection for each query descriptor. void match(const GpuMat& query, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>()); //! Find k best matches for each query descriptor (in increasing order of distances) void knnMatchSingle(const GpuMat& query, const GpuMat& train, GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k, const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx and distance and convert it to vector with DMatch //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. static void knnMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx and distance to vector with DMatch static void knnMatchConvert(const Mat& trainIdx, const Mat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find k best matches for each query descriptor (in increasing order of distances). //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. void knnMatch(const GpuMat& query, const GpuMat& train, std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(), bool compactResult = false); //! Find k best matches from train collection for each query descriptor (in increasing order of distances) void knnMatch2Collection(const GpuMat& query, const GpuMat& trainCollection, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, const GpuMat& maskCollection = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx and distance and convert it to vector with DMatch //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. //! @see BFMatcher_CUDA::knnMatchDownload static void knnMatch2Download(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx and distance to vector with DMatch //! @see BFMatcher_CUDA::knnMatchConvert static void knnMatch2Convert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find k best matches for each query descriptor (in increasing order of distances). //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. void knnMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, int k, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); //! Find best matches for each query descriptor which have distance less than maxDistance. //! nMatches.at<int>(0, queryIdx) will contain matches count for queryIdx. //! carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches, //! because it didn't have enough memory. //! If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10), //! otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches //! Matches doesn't sorted. void radiusMatchSingle(const GpuMat& query, const GpuMat& train, GpuMat& trainIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance, const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx, nMatches and distance and convert it to vector with DMatch. //! matches will be sorted in increasing order of distances. //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, const GpuMat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx, nMatches and distance to vector with DMatch. static void radiusMatchConvert(const Mat& trainIdx, const Mat& distance, const Mat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find best matches for each query descriptor which have distance less than maxDistance //! in increasing order of distances). void radiusMatch(const GpuMat& query, const GpuMat& train, std::vector< std::vector<DMatch> >& matches, float maxDistance, const GpuMat& mask = GpuMat(), bool compactResult = false); //! Find best matches for each query descriptor which have distance less than maxDistance. //! If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10), //! otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches //! Matches doesn't sorted. void radiusMatchCollection(const GpuMat& query, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); //! Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch. //! matches will be sorted in increasing order of distances. //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, const GpuMat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx, nMatches and distance to vector with DMatch. static void radiusMatchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, const Mat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find best matches from train collection for each query descriptor which have distance less than //! maxDistance (in increasing order of distances). void radiusMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); int norm; private: std::vector<GpuMat> trainDescCollection; }; /** @brief Class used for corner detection using the FAST algorithm. : */ class CV_EXPORTS FAST_CUDA { public: enum { LOCATION_ROW = 0, RESPONSE_ROW, ROWS_COUNT }; //! all features have same size static const int FEATURE_SIZE = 7; /** @brief Constructor. @param threshold Threshold on difference between intensity of the central pixel and pixels on a circle around this pixel. @param nonmaxSuppression If it is true, non-maximum suppression is applied to detected corners (keypoints). @param keypointsRatio Inner buffer size for keypoints store is determined as (keypointsRatio \* image_width \* image_height). */ explicit FAST_CUDA(int threshold, bool nonmaxSuppression = true, double keypointsRatio = 0.05); /** @brief Finds the keypoints using FAST detector. @param image Image where keypoints (corners) are detected. Only 8-bit grayscale images are supported. @param mask Optional input mask that marks the regions where we should detect features. @param keypoints The output vector of keypoints. Can be stored both in CPU and GPU memory. For GPU memory: - keypoints.ptr\<Vec2s\>(LOCATION_ROW)[i] will contain location of i'th point - keypoints.ptr\<float\>(RESPONSE_ROW)[i] will contain response of i'th point (if non-maximum suppression is applied) */ void operator ()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints); /** @overload */ void operator ()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints); /** @brief Download keypoints from GPU to CPU memory. */ static void downloadKeypoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints); /** @brief Converts keypoints from CUDA representation to vector of KeyPoint. */ static void convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints); /** @brief Releases inner buffer memory. */ void release(); bool nonmaxSuppression; int threshold; //! max keypoints = keypointsRatio * img.size().area() double keypointsRatio; /** @brief Find keypoints and compute it's response if nonmaxSuppression is true. @param image Image where keypoints (corners) are detected. Only 8-bit grayscale images are supported. @param mask Optional input mask that marks the regions where we should detect features. The function returns count of detected keypoints. */ int calcKeyPointsLocation(const GpuMat& image, const GpuMat& mask); /** @brief Gets final array of keypoints. @param keypoints The output vector of keypoints. The function performs non-max suppression if needed and returns final count of keypoints. */ int getKeyPoints(GpuMat& keypoints); private: GpuMat kpLoc_; int count_; GpuMat score_; GpuMat d_keypoints_; }; /** @brief Class for extracting ORB features and descriptors from an image. : */ class CV_EXPORTS ORB_CUDA { public: enum { X_ROW = 0, Y_ROW, RESPONSE_ROW, ANGLE_ROW, OCTAVE_ROW, SIZE_ROW, ROWS_COUNT }; enum { DEFAULT_FAST_THRESHOLD = 20 }; /** @brief Constructor. @param nFeatures The number of desired features. @param scaleFactor Coefficient by which we divide the dimensions from one scale pyramid level to the next. @param nLevels The number of levels in the scale pyramid. @param edgeThreshold How far from the boundary the points should be. @param firstLevel The level at which the image is given. If 1, that means we will also look at the image scaleFactor times bigger. @param WTA_K @param scoreType @param patchSize */ explicit ORB_CUDA(int nFeatures = 500, float scaleFactor = 1.2f, int nLevels = 8, int edgeThreshold = 31, int firstLevel = 0, int WTA_K = 2, int scoreType = 0, int patchSize = 31); /** @overload */ void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints); /** @overload */ void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints); /** @brief Detects keypoints and computes descriptors for them. @param image Input 8-bit grayscale image. @param mask Optional input mask that marks the regions where we should detect features. @param keypoints The input/output vector of keypoints. Can be stored both in CPU and GPU memory. For GPU memory: - keypoints.ptr\<float\>(X_ROW)[i] contains x coordinate of the i'th feature. - keypoints.ptr\<float\>(Y_ROW)[i] contains y coordinate of the i'th feature. - keypoints.ptr\<float\>(RESPONSE_ROW)[i] contains the response of the i'th feature. - keypoints.ptr\<float\>(ANGLE_ROW)[i] contains orientation of the i'th feature. - keypoints.ptr\<float\>(OCTAVE_ROW)[i] contains the octave of the i'th feature. - keypoints.ptr\<float\>(SIZE_ROW)[i] contains the size of the i'th feature. @param descriptors Computed descriptors. if blurForDescriptor is true, image will be blurred before descriptors calculation. */ void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors); /** @overload */ void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors); /** @brief Download keypoints from GPU to CPU memory. */ static void downloadKeyPoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints); /** @brief Converts keypoints from CUDA representation to vector of KeyPoint. */ static void convertKeyPoints(const Mat& d_keypoints, std::vector<KeyPoint>& keypoints); //! returns the descriptor size in bytes inline int descriptorSize() const { return kBytes; } inline void setFastParams(int threshold, bool nonmaxSuppression = true) { fastDetector_.threshold = threshold; fastDetector_.nonmaxSuppression = nonmaxSuppression; } /** @brief Releases inner buffer memory. */ void release(); //! if true, image will be blurred before descriptors calculation bool blurForDescriptor; private: enum { kBytes = 32 }; void buildScalePyramids(const GpuMat& image, const GpuMat& mask); void computeKeyPointsPyramid(); void computeDescriptors(GpuMat& descriptors); void mergeKeyPoints(GpuMat& keypoints); int nFeatures_; float scaleFactor_; int nLevels_; int edgeThreshold_; int firstLevel_; int WTA_K_; int scoreType_; int patchSize_; //! The number of desired features per scale std::vector<size_t> n_features_per_level_; //! Points to compute BRIEF descriptors from GpuMat pattern_; std::vector<GpuMat> imagePyr_; std::vector<GpuMat> maskPyr_; GpuMat buf_; std::vector<GpuMat> keyPointsPyr_; std::vector<int> keyPointsCount_; FAST_CUDA fastDetector_; Ptr<cuda::Filter> blurFilter; GpuMat d_keypoints_; }; //! @} }} // namespace cv { namespace cuda { #endif /* __OPENCV_CUDAFEATURES2D_HPP__ */
44.654018
140
0.713322
liuhuanjim013
f61f0fb6f3804c88c2d74049dd4488714d94af28
547
cpp
C++
0119 Pascals Triangle II/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
1
2019-12-19T04:13:15.000Z
2019-12-19T04:13:15.000Z
0119 Pascals Triangle II/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
0119 Pascals Triangle II/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { //The basic idea is to iteratively update the array from the end to the beginning. vector<int> res(rowIndex+1, 0); res[0] = 1; for(int i = 1; i<=rowIndex; i++){ for(int j = i; j>=1; j--){ res[j] = res[j] + res[j-1]; } } return res; } }; int main(){ vector<int> res = Solution().getRow(5); for (int n : res) cout << n << " "; }
22.791667
90
0.493601
Aden-Tao
f61f4fac644e64b9beeecde0907d014d6c7cb7ae
1,174
cpp
C++
IntroductionToCpp/Arrays/main.cpp
Trey0303/IntroToCpp
6aea72df60a1dfa80dbeb0d4f90a37fdaf3721b7
[ "MIT" ]
null
null
null
IntroductionToCpp/Arrays/main.cpp
Trey0303/IntroToCpp
6aea72df60a1dfa80dbeb0d4f90a37fdaf3721b7
[ "MIT" ]
null
null
null
IntroductionToCpp/Arrays/main.cpp
Trey0303/IntroToCpp
6aea72df60a1dfa80dbeb0d4f90a37fdaf3721b7
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include "arrayh.h" int main() { //create array //index 0 ,1,2 ,3,4 ,5, 6,7,8,9 //array size: 1 ,2,3 ,4,5 ,6, 7,8,9,10 int array[10]{10,1,25,4,33,4,26,7,6,9}; //get size of array int size = 0; for (int i : array) { size++; } //add first 5 numbers in array int result = sum(array, 5); //print full array printNumbers(array, size); //print sum of array int sum = sumNumbers(array, size); std::cout << std::endl << sum; //print largest num in array int largestNumFinal = largestValue(array, size); std::cout << std::endl << largestNumFinal; //find value in array, return index of value // array[],size,value,start int returnValue = findIndex(array, size, 6, 2); std::cout << std::endl << returnValue; //count number of times value is found in array from starting point // array[],size,value,start int count = countElement(array, size, 4, 2); std::cout << std::endl << count; //if array has two or more of the same number say no to being unique, else yes ArrayUniqueness(array, size); //Reverse reverse(array, size, 1, 10); return 0; }
22.150943
79
0.623509
Trey0303
f621ad6f82b11b939ba955b08fe55e539277e5dd
7,326
cpp
C++
packages/geometry/legacy/src/Geometry_SurfaceInputValidatorHelpers.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/geometry/legacy/src/Geometry_SurfaceInputValidatorHelpers.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/geometry/legacy/src/Geometry_SurfaceInputValidatorHelpers.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file Geometry_SurfaceInputValidatorHelpers.cpp //! \author Alex Robinson //! \brief Surface input validator helper function definitions. //! //---------------------------------------------------------------------------// // Std Lib Includes #include <stdexcept> // Trilinos Includes #include <Teuchos_ParameterListExceptions.hpp> // FRENSIE Includes #include "Geometry_SurfaceInputValidatorHelpers.hpp" namespace Geometry{ // Validate the surface name /*! \details No empty spaces, (, ) or - characters are allowed in surface * names. If one is found, a std::invalid_argument exception is thrown. In * addition, the surface cannot be named "n" or "u". A * std::invalid_argument exception will be thrown if so. */ void validateSurfaceName( const std::string& surface_name ) { std::string error_message; // No empty spaces are allowed in surface names std::string::size_type empty_space_pos = surface_name.find( " " ); if( empty_space_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": spaces are not allowed in surface names.\n"; } // No ( or ) characters are allowed in surface names std::string::size_type left_paren_pos = surface_name.find( "(" ); std::string::size_type right_paren_pos = surface_name.find( ")" ); if( left_paren_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": ( characters are not allowed in surface names.\n"; } if( right_paren_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": ) characters are not allowed in surface names.\n"; } // No - characters are allowed in surface names std::string::size_type minus_pos = surface_name.find( "-" ); if( minus_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": - characters are not allowed in surface names.\n"; } // The name cannot be "n" or "u" if( surface_name.compare( "n" ) == 0 || surface_name.compare( "u" ) == 0 ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": the name is reserved.\n"; } // If any errors have occured, throw if( error_message.size() > 0 ) { throw std::invalid_argument( error_message ); } } // Validate the surface type /*! \details Only the following surface types are valid: * <ul> * <li> x plane * <li> y plane * <li> z plane * <li> general plane * <li> x cylinder * <li> y cylinder * <li> z cylinder * <li> sphere * <li> general surface * </ul> * If any other type is specified, a std::invalid_argument excpetion is thrown. */ void validateSurfaceType( const std::string& surface_type, const std::string& surface_name ) { bool valid_surface_type = false; if( surface_type.compare( "x plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "y plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "z plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "general plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "x cylinder" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "y cylinder" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "z cylinder" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "sphere" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "general surface" ) == 0 ) valid_surface_type = true; // The surface type specified is invalid if( !valid_surface_type ) { std::string error_message = "Error in surface \""; error_message += surface_name.c_str(); error_message += "\": \""; error_message += surface_type.c_str(); error_message += "\" does not name a surface type.\n"; throw std::invalid_argument( error_message ); } } // Validate the surface definition /*! \details This function does not check if the surface is physically * reasonable - only that the correct number of arguments are specified for * the particular surface type. The required number of arguments are as * follows: * <ul> * <li> x plane: 1 * <li> y plane: 1 * <li> z plane: 1 * <li> general plane: 4 * <li> x cylinder: 3 * <li> y cylinder: 3 * <li> z cylinder: 3 * <li> sphere: 4 * <li> general surface: 10 * </ul> * If the number of parameters is not correct, a std::invalid_argument * exception is thrown. */ void validateSurfaceDefinition( const Teuchos::Array<double>& surface_definition, const std::string& surface_type, const std::string& surface_name ) { // Create the potential error message template std::string error_message = "Error in surface \""; error_message += surface_name.c_str(); error_message += "\": \""; error_message += surface_type.c_str(); error_message += "\" "; // axis aligned planes only require a single input value if( surface_type.compare( "x plane" ) == 0 || surface_type.compare( "y plane" ) == 0 || surface_type.compare( "z plane" ) == 0 ) { if( surface_definition.size() != 1 ) { error_message += "requires 1 argument.\n"; throw std::invalid_argument( error_message ); } } else if( surface_type.compare( "x cylinder" ) == 0 || surface_type.compare( "y cylinder" ) == 0 || surface_type.compare( "z cylinder" ) == 0 ) { if( surface_definition.size() != 3 ) { error_message += "requires 3 arguments.\n"; throw std::invalid_argument( error_message ); } } else if( surface_type.compare( "general plane" ) == 0 || surface_type.compare( "sphere" ) == 0 ) { if( surface_definition.size() != 4 ) { error_message += "requires 4 arguments.\n"; throw std::invalid_argument( error_message ); } } else if( surface_type.compare( "general surface" ) == 0 ) { if( surface_definition.size() != 10 ) { error_message += "requires 10 arguments.\n"; throw std::invalid_argument( error_message ); } } } // Validate the surface special attribute /*! \details Only one special attribute is currently accepted: reflecting. * Anything else will cause a std::invalid_argument exception to be thrown. */ void validateSurfaceSpecialAttribute( const std::string& surface_attribute, const std::string& surface_name ) { if( surface_attribute.compare( "reflecting" ) != 0) { std::string error_message = "Error in surface \""; error_message += surface_name.c_str(); error_message += "\": \""; error_message += surface_attribute.c_str(); error_message += "\" is not a valid special attribute.\n"; throw std::invalid_argument( error_message ); } } } // end Geometry namespace //---------------------------------------------------------------------------// // end Geometry_SurfaceInputValidatorHelpers.cpp //---------------------------------------------------------------------------//
31.307692
79
0.627355
lkersting
f62686765a2bf341306311cfa01096943efba6ad
6,362
cpp
C++
Meitner/Application/Example/Testbench/ProcessorTest/main.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Meitner/Application/Example/Testbench/ProcessorTest/main.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Meitner/Application/Example/Testbench/ProcessorTest/main.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
//================================================================================ // Copyright (c) 2013 ~ 2021. HyungKi Jeong(clonextop@gmail.com) // Freely available under the terms of the 3-Clause BSD License // (https://opensource.org/licenses/BSD-3-Clause) // // 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. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. // // Title : Testbench // Rev. : 12/28/2021 Tue (clonextop@gmail.com) //================================================================================ #include "Testbench.h" #include "hw/DUT.h" class Testbench : public TestbenchFramework { DUT* m_pDUT; // Processor (Design Under Testing) DDKMemory* m_pBuff; virtual bool OnInitialize(int argc, char** argv) { m_pDUT = NULL; m_pBuff = NULL; // H/W system equality check if(!CheckSimulation("Processor axi wrapper")) return false; m_pDUT = new DUT(m_pDDK); m_pDUT->SetClock(300.f); // set processor clock to 300MHz (High speed.) for performance m_pBuff = CreateDDKMemory(1024 * 8, 32); // 8KB, 256bit alignment MemoryLog(m_pBuff, "Test buffer memory"); return true; } virtual void OnRelease(void) { if(m_pDUT) m_pDUT->SetClock(50.f); // set processor clock to 50MHz (Low speed.) for IDLE status SAFE_RELEASE(m_pBuff); SAFE_DELETE(m_pDUT); } virtual bool OnTestBench(void) { //----------------------------------------------------- // slave R/W test //----------------------------------------------------- printf("\nAsynchronous slave FIFO R/W test...\n"); printf("\tDUT_CLOCK_GEN STATUS : 0x%X\n", m_pDDK->RegRead(DUT_CLOCKGEN_BASE)); printf("\tWrite slave fifo 5 times...\n"); for(int i = 0; i < 5; i++) { DWORD dwData = 0xABCD0000 | i; printf("\tWrite : 0x%X\n", dwData); m_pDDK->RegWrite(DUT_BASE | (3 << 2), dwData); } printf("\tDUT_CLOCK_GEN STATUS : 0x%X\n", m_pDDK->RegRead(DUT_CLOCKGEN_BASE)); printf("\tRead slave fifo 5 times...\n"); for(int i = 0; i < 5; i++) printf("\tRead : 0x%X\n", m_pDDK->RegRead(DUT_BASE)); //----------------------------------------------------- // master R/W test //----------------------------------------------------- //// ***** write test ***** printf("\nAsynchronous master write test...\n"); // clear memory printf("\tClear memory...\n"); memset(m_pBuff->Virtual(), 0xCC, m_pBuff->ByteSize()); // write to system memory m_pBuff->Flush(); // write m_pDDK->RegWrite(DUT_BASE | (0 << 2), m_pBuff->Physical()); // set target memory address m_pDDK->RegWrite(DUT_BASE | (1 << 2), 8); // set transfer size = 8 m_pDDK->RegWrite(DUT_BASE | (2 << 2), 1); // do write // wait for master bus write done // s/w is too fast in the h/w simulation mode, so we will wait a while. for(int i = 0; i < 20; i++) m_pDDK->RegRead(DUT_BASE); // read from system memory m_pBuff->Flush(FALSE); { DWORD* pData = (DWORD*)m_pBuff->Virtual(); for(int i = 0; i < 20; i++) printf("\tRead : [%d] %08X %08X %08X %08X %08X %08X %08X %08X\n", i, pData[i * 8], pData[i * 8 + 1], pData[i * 8 + 2], pData[i * 8 + 3], pData[i * 8 + 4], pData[i * 8 + 5], pData[i * 8 + 6], pData[i * 8 + 7]); } //// ***** read test ***** printf("\nAsynchronous master read test...\n"); { printf("\tInitiailze memory : 0x%X\n", m_pBuff->Physical()); DWORD* pData = (DWORD*)m_pBuff->Virtual(); for(int i = 0; i < 16; i++) { pData[i * 8] = 0xABC00000 | (i * 8 + 0); pData[i * 8 + 1] = 0xABC10000 | (i * 8 + 1); pData[i * 8 + 2] = 0xABC20000 | (i * 8 + 2); pData[i * 8 + 3] = 0xABC30000 | (i * 8 + 3); pData[i * 8 + 4] = 0xABC40000 | (i * 8 + 4); pData[i * 8 + 5] = 0xABC50000 | (i * 8 + 5); pData[i * 8 + 6] = 0xABC60000 | (i * 8 + 6); pData[i * 8 + 7] = 0xABC70000 | (i * 8 + 7); } // write to system memory m_pBuff->Flush(TRUE); } m_pDDK->RegWrite(DUT_BASE | (0 << 2), m_pBuff->Physical()); // set target memory address m_pDDK->RegWrite(DUT_BASE | (1 << 2), 8); // set transfer size = 8 m_pDDK->RegWrite(DUT_BASE | (2 << 2), 0); // do read // wait for master bus read done // s/w is too fast in the h/w simulation mode, so we will wait a while. for(int i = 0; i < 20; i++) m_pDDK->RegRead(DUT_BASE); // check out~~ printf("\tCheck out processor's valid read operation from simulation's waveform...\n"); //// ***** interrupt test ***** printf("\nInterrupt test...\n"); m_pDDK->RegWrite((DUT_BASE | (4 << 2)), 1); m_pDDK->WaitInterruptDone(); printf("\tInterrupt Counted = 0x%X\n", (m_pDDK->RegRead((DUT_CLOCKGEN_BASE | (4 << 2))) >> 18) & 0x3FF); // clear & get interrupt counter printf("process is done!\n"); return true; } }; int main(int argc, char** argv) { Testbench tb; if(tb.Initialize(argc, argv)) { if(!tb.DoTestbench()) printf("Testbench is failed.\n"); } else { printf("Initialization is failed.\n"); } }
36.774566
139
0.602012
testdrive-profiling-master
f626edbdcefd3f42a5ebe6d3b779ad4cc955d7da
19,938
hpp
C++
src/core/tb2clause.hpp
nrousse/toulbar2
ae79b8b05d7a57d7563ed6d497107b2e77cdd49c
[ "MIT" ]
33
2018-08-16T18:14:35.000Z
2022-03-14T10:26:18.000Z
src/core/tb2clause.hpp
nrousse/toulbar2
ae79b8b05d7a57d7563ed6d497107b2e77cdd49c
[ "MIT" ]
13
2018-08-09T06:53:08.000Z
2022-03-28T10:26:24.000Z
src/core/tb2clause.hpp
nrousse/toulbar2
ae79b8b05d7a57d7563ed6d497107b2e77cdd49c
[ "MIT" ]
12
2018-06-06T15:19:46.000Z
2022-02-11T17:09:27.000Z
#ifndef TB2WCLAUSE_HPP_ #define TB2WCLAUSE_HPP_ #include "tb2abstractconstr.hpp" #include "tb2ternaryconstr.hpp" #include "tb2enumvar.hpp" #include "tb2wcsp.hpp" #include <numeric> //TODO: avoid enumeration on all variables if they are already assigned and removed (using backtrackable domain data structure). //in order to speed-up propagate function if the support variable has a zero unary cost // warning! we assume binary variables class WeightedClause : public AbstractNaryConstraint { Cost cost; // clause weight Tuple tuple; // forbidden assignment corresponding to the negation of the clause StoreCost lb; // projected cost to problem lower bound (if it is zero then all deltaCosts must be zero) vector<StoreCost> deltaCosts; // extended costs from unary costs to the cost function int support; // index of a variable in the scope with a zero unary cost on its value which satisfies the clause StoreInt nonassigned; // number of non-assigned variables during search, must be backtrackable! vector<Long> conflictWeights; // used by weighted degree heuristics bool zeros; // true if all deltaCosts are zero (temporally used by first/next) bool done; // should be true after one call to next Value getTuple(int i) { return scope[i]->toValue(tuple[i]); } Value getClause(int i) { return scope[i]->toValue(!(tuple[i])); } void projectLB(Cost c) { lb += c; assert(lb <= cost); Constraint::projectLB(c); } void extend(Cost c) { for (int i = 0; i < arity_; i++) { EnumeratedVariable* x = scope[i]; if (x->unassigned()) { deltaCosts[i] += c; Value v = getClause(i); TreeDecomposition* td = wcsp->getTreeDec(); if (td) td->addDelta(cluster, x, v, -c); x->extend(v, c); } else assert(x->getValue() == getTuple(i)); } projectLB(c); } void satisfied(int varIndex) { nonassigned = 0; assert(scope[varIndex]->assigned()); assert(scope[varIndex]->getValue() == getClause(varIndex)); assert(deltaCosts[varIndex] == lb); for (int i = 0; i < arity_; i++) { EnumeratedVariable* x = scope[i]; assert(deconnected(i)); if (i != varIndex) { Cost c = deltaCosts[i]; Value v = getClause(i); if (c > MIN_COST) { deltaCosts[i] = MIN_COST; if (x->unassigned()) { if (!CUT(c + wcsp->getLb(), wcsp->getUb())) { TreeDecomposition* td = wcsp->getTreeDec(); if (td) td->addDelta(cluster, x, v, c); } x->project(v, c, true); x->findSupport(); } else { if (x->canbe(v)) { Constraint::projectLB(c); } } } } } } public: // warning! give the negation of the clause as input WeightedClause(WCSP* wcsp, EnumeratedVariable** scope_in, int arity_in, Cost cost_in = MIN_COST, Tuple tuple_in = Tuple()) : AbstractNaryConstraint(wcsp, scope_in, arity_in) , cost(cost_in) , tuple(tuple_in) , lb(MIN_COST) , support(0) , nonassigned(arity_in) , zeros(true) , done(false) { if (tuple_in.empty() && arity_in > 0) tuple = Tuple(arity_in, 0); deltaCosts = vector<StoreCost>(arity_in, StoreCost(MIN_COST)); for (int i = 0; i < arity_in; i++) { assert(scope_in[i]->getDomainInitSize() == 2); conflictWeights.push_back(0); } } virtual ~WeightedClause() {} void setTuple(const Tuple& tin, Cost c) FINAL { cost = c; tuple = tin; } bool extension() const FINAL { return false; } // TODO: allows functional variable elimination but not other preprocessing Long size() const FINAL { Cost sumdelta = ((lb > MIN_COST) ? accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) : MIN_COST); if (sumdelta == MIN_COST) return 1; return getDomainSizeProduct(); } void reconnect() { if (deconnected()) { nonassigned = arity_; AbstractNaryConstraint::reconnect(); } } int getNonAssigned() const { return nonassigned; } Long getConflictWeight() const { return Constraint::getConflictWeight(); } Long getConflictWeight(int varIndex) const { assert(varIndex >= 0); assert(varIndex < arity_); return conflictWeights[varIndex] + Constraint::getConflictWeight(); } void incConflictWeight(Constraint* from) { assert(from!=NULL); if (from == this) { if (deconnected() || nonassigned==arity_) { Constraint::incConflictWeight(1); } else { for (int i = 0; i < arity_; i++) { if (connected(i)) { conflictWeights[i]++; } } } } else if (deconnected()) { for (int i = 0; i < from->arity(); i++) { int index = getIndex(from->getVar(i)); if (index >= 0) { // the last conflict constraint may be derived from two binary constraints (boosting search), each one derived from an n-ary constraint with a scope which does not include parameter constraint from assert(index < arity_); conflictWeights[index]++; } } } } void resetConflictWeight() { conflictWeights.assign(conflictWeights.size(), 0); Constraint::resetConflictWeight(); } bool universal() { if (cost != MIN_COST || lb != MIN_COST) return false; for (int i = 0; i < arity_; i++) if (deltaCosts[i] != MIN_COST) return false; return true; } Cost eval(const Tuple& s) { if (lb == MIN_COST && tuple[support] != s[support]) { assert(accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) == MIN_COST); return MIN_COST; } else { Cost res = -lb; bool istuple = true; for (int i = 0; i < arity_; i++) { if (tuple[i] != s[i]) { res += deltaCosts[i]; istuple = false; } } if (istuple) res += cost; assert(res >= MIN_COST); return res; } } Cost evalsubstr(const Tuple& s, Constraint* ctr) FINAL { return evalsubstrAny(s, ctr); } Cost evalsubstr(const Tuple& s, NaryConstraint* ctr) FINAL { return evalsubstrAny(s, ctr); } template <class T> Cost evalsubstrAny(const Tuple& s, T* ctr) { int count = 0; for (int i = 0; i < arity_; i++) { int ind = ctr->getIndex(getVar(i)); if (ind >= 0) { evalTuple[i] = s[ind]; count++; } } assert(count <= arity_); Cost cost; if (count == arity_) cost = eval(evalTuple); else cost = MIN_COST; return cost; } Cost getCost() FINAL { for (int i = 0; i < arity_; i++) { EnumeratedVariable* var = (EnumeratedVariable*)getVar(i); evalTuple[i] = var->toIndex(var->getValue()); } return eval(evalTuple); } double computeTightness() { return 1.0 * cost / getDomainSizeProduct(); } pair<pair<Cost, Cost>, pair<Cost, Cost>> getMaxCost(int index, Value a, Value b) { Cost sumdelta = ((lb > MIN_COST) ? accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) : MIN_COST); bool supporta = (getClause(index) == a); Cost maxcosta = max((supporta) ? MIN_COST : (cost - lb), sumdelta - ((supporta) ? MIN_COST : (Cost)deltaCosts[index])); Cost maxcostb = max((supporta) ? (cost - lb) : MIN_COST, sumdelta - ((supporta) ? (Cost)deltaCosts[index] : MIN_COST)); return make_pair(make_pair(maxcosta, maxcosta), make_pair(maxcostb, maxcostb)); } void first() { zeros = all_of(deltaCosts.begin(), deltaCosts.end(), [](Cost c) { return c == MIN_COST; }); done = false; if (!zeros) firstlex(); } bool next(Tuple& t, Cost& c) { if (!zeros) return nextlex(t, c); if (done) return false; t = tuple; c = cost - lb; done = true; return true; } Cost getMaxFiniteCost() { Cost sumdelta = ((lb > MIN_COST) ? accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) : MIN_COST); if (CUT(sumdelta, wcsp->getUb())) return MAX_COST; if (CUT(cost, wcsp->getUb())) return sumdelta; else return max(sumdelta, cost - lb); } void setInfiniteCost(Cost ub) { Cost mult_ub = ((ub < (MAX_COST / MEDIUM_COST)) ? (max(LARGE_COST, ub * MEDIUM_COST)) : ub); if (CUT(cost, ub)) cost = mult_ub; } void assign(int varIndex) { if (connected(varIndex)) { deconnect(varIndex); nonassigned = nonassigned - 1; assert(nonassigned >= 0); if (scope[varIndex]->getValue() == getClause(varIndex)) { deconnect(); satisfied(varIndex); return; } if (nonassigned <= 3) { deconnect(); projectNary(); } else { if (ToulBar2::FullEAC) reviseEACGreedySolution(); } } } // propagates the minimum between the remaining clause weight and unary costs of all literals to the problem lower bound void propagate() { Cost mincost = (connected() && scope[support]->unassigned()) ? scope[support]->getCost(getClause(support)) : MAX_COST; for (int i = 0; connected() && i < arity_; i++) { EnumeratedVariable* x = scope[i]; if (x->assigned()) { assign(i); } else if (mincost > MIN_COST) { Cost ucost = x->getCost(getClause(i)); if (ucost < mincost) { mincost = ucost; support = i; } } } if (connected() && mincost < MAX_COST && mincost > MIN_COST && cost > lb) { extend(min(cost - lb, mincost)); } }; bool verify() { Tuple t; Cost c; firstlex(); while (nextlex(t, c)) { if (c == MIN_COST) return true; } return false; } void increase(int index) {} void decrease(int index) {} void remove(int index) {} void projectFromZero(int index) { if (index == support && cost > lb) propagate(); } bool checkEACGreedySolution(int index = -1, Value supportValue = 0) FINAL { bool zerolb = (lb == MIN_COST); if (zerolb && getTuple(support) != ((support == index) ? supportValue : getVar(support)->getSupport())) { assert(accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) == MIN_COST); return true; } else { Cost res = -lb; bool istuple = true; for (int i = 0; i < arity_; i++) { if (getTuple(i) != ((i == index) ? supportValue : getVar(i)->getSupport())) { res += deltaCosts[i]; istuple = false; if (zerolb) { assert(res == MIN_COST); assert(accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) == MIN_COST); return true; } } } if (istuple) res += cost; assert(res >= MIN_COST); return (res == MIN_COST); } } bool reviseEACGreedySolution(int index = -1, Value supportValue = 0) FINAL { bool result = checkEACGreedySolution(index, supportValue); if (!result) { if (index >= 0) { getVar(index)->unsetFullEAC(); } else { int a = arity(); for (int i = 0; i < a; i++) { getVar(i)->unsetFullEAC(); } } } return result; } void print(ostream& os) { os << endl << this << " clause("; int unassigned_ = 0; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) unassigned_++; if (getClause(i) == 0) os << "-"; os << wcsp->getName(scope[i]->wcspIndex); if (i < arity_ - 1) os << ","; } os << ") s:" << support << " / " << cost << " - " << lb << " ("; for (int i = 0; i < arity_; i++) { os << deltaCosts[i]; if (i < arity_ - 1) os << ","; } os << ") "; if (ToulBar2::weightedDegree) { os << "/" << getConflictWeight(); for (int i = 0; i < arity_; i++) { os << "," << conflictWeights[i]; } } os << " arity: " << arity_; os << " unassigned: " << (int)nonassigned << "/" << unassigned_ << endl; } void dump(ostream& os, bool original = true) { Cost maxdelta = MIN_COST; for (vector<StoreCost>::iterator it = deltaCosts.begin(); it != deltaCosts.end(); ++it) { Cost d = (*it); if (d > maxdelta) maxdelta = d; } if (original) { os << arity_; for (int i = 0; i < arity_; i++) os << " " << scope[i]->wcspIndex; if (maxdelta == MIN_COST) { os << " " << 0 << " " << 1 << endl; for (int i = 0; i < arity_; i++) { os << scope[i]->toValue(tuple[i]) << " "; } os << cost << endl; } else { os << " " << 0 << " " << getDomainSizeProduct() << endl; Tuple t; Cost c; firstlex(); while (nextlex(t, c)) { for (int i = 0; i < arity_; i++) { os << scope[i]->toValue(t[i]) << " "; } os << c << endl; } } } else { os << nonassigned; for (int i = 0; i < arity_; i++) if (scope[i]->unassigned()) os << " " << scope[i]->getCurrentVarId(); if (maxdelta == MIN_COST) { os << " " << 0 << " " << 1 << endl; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) os << scope[i]->toCurrentIndex(scope[i]->toValue(tuple[i])) << " "; } os << min(wcsp->getUb(), cost) << endl; } else { os << " " << 0 << " " << getDomainSizeProduct() << endl; Tuple t; Cost c; firstlex(); while (nextlex(t, c)) { for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) os << scope[i]->toCurrentIndex(scope[i]->toValue(t[i])) << " "; } os << min(wcsp->getUb(), c) << endl; } } } } void dump_CFN(ostream& os, bool original = true) { bool printed = false; os << "\"F_"; Cost maxdelta = MIN_COST; for (vector<StoreCost>::iterator it = deltaCosts.begin(); it != deltaCosts.end(); ++it) { Cost d = (*it); if (d > maxdelta) maxdelta = d; } if (original) { printed = false; for (int i = 0; i < arity_; i++) { if (printed) os << "_"; os << scope[i]->wcspIndex; printed = true; } os << "\":{\"scope\":["; printed = false; for (int i = 0; i < arity_; i++) { if (printed) os << ","; os << "\"" << scope[i]->getName() << "\""; printed = true; } os << "],\"defaultcost\":" << wcsp->Cost2RDCost(MIN_COST) << ",\n\"costs\":["; if (maxdelta == MIN_COST) { printed = false; for (int i = 0; i < arity_; i++) { if (printed) os << ","; os << tuple[i]; printed = true; } os << "," << wcsp->Cost2RDCost(cost); } else { Tuple t; Cost c; printed = false; firstlex(); while (nextlex(t, c)) { os << endl; for (int i = 0; i < arity_; i++) { if (printed) os << ","; os << t[i]; printed = true; } os << "," << wcsp->Cost2RDCost(c); } } } else { for (int i = 0; i < arity_; i++) if (scope[i]->unassigned()) { if (printed) os << "_"; os << scope[i]->getCurrentVarId(); printed = true; } os << "\":{\"scope\":["; printed = false; for (int i = 0; i < arity_; i++) if (scope[i]->unassigned()) { if (printed) os << ","; os << "\"" << scope[i]->getName() << "\""; printed = true; } os << "],\"defaultcost\":" << wcsp->Cost2RDCost(MIN_COST) << ",\n\"costs\":["; if (maxdelta == MIN_COST) { printed = false; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) { if (printed) os << ","; os << scope[i]->toCurrentIndex(scope[i]->toValue(tuple[i])); printed = true; } } os << "," << wcsp->Cost2RDCost(min(wcsp->getUb(), cost)); } else { Tuple t; Cost c; printed = false; firstlex(); while (nextlex(t, c)) { os << endl; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) { if (printed) os << ","; os << scope[i]->toCurrentIndex(scope[i]->toValue(t[i])); printed = true; } } os << "," << wcsp->Cost2RDCost(min(wcsp->getUb(), c)); } } } os << "]},\n"; } }; #endif /*TB2WCLAUSE_HPP_*/ /* Local Variables: */ /* c-basic-offset: 4 */ /* tab-width: 4 */ /* indent-tabs-mode: nil */ /* c-default-style: "k&r" */ /* End: */
34.023891
231
0.440716
nrousse
f628fb8cbac669d14b03e8cca499eb4e042514e0
1,870
cpp
C++
src/light_effects.cpp
ljmerza/mqtt-msgeq7-led-strip
cd7574efbb1c4a2ba465cba51abe6fbeef5ac875
[ "MIT" ]
1
2019-05-16T01:49:14.000Z
2019-05-16T01:49:14.000Z
src/light_effects.cpp
ljmerza/mqtt-msgeq7-led-strip
cd7574efbb1c4a2ba465cba51abe6fbeef5ac875
[ "MIT" ]
1
2019-01-24T02:04:06.000Z
2019-01-28T17:51:22.000Z
src/light_effects.cpp
ljmerza/mqtt-msgeq7-led-strip
cd7574efbb1c4a2ba465cba51abe6fbeef5ac875
[ "MIT" ]
null
null
null
#include "common.h" #include "config.h" void fill_led_colors(CRGBPalette16 current_palette){ for(int i=0; i<NUM_LEDS; i++) { leds[i] = ColorFromPalette(current_palette, 0, brightness, LINEARBLEND); } } CRGBPalette16 lamp_light(uint8_t red, uint8_t green, uint8_t blue){ CRGB rgb = CRGB(red, green, blue); CRGBPalette16 current_palette = CRGBPalette16( rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb ); return current_palette; } void lamp_candle(){ CRGBPalette16 current_palette = lamp_light(255, 147, 41); fill_led_colors(current_palette); } void lamp_tungsten_40w(){ CRGBPalette16 current_palette = lamp_light(255, 197, 143); fill_led_colors(current_palette); } void lamp_tungsten_100w(){ CRGBPalette16 current_palette = lamp_light(255, 214, 170); fill_led_colors(current_palette); } void lamp_high_pressure_sodium() { CRGBPalette16 current_palette = lamp_light(255, 183, 76); fill_led_colors(current_palette); } void cloudColors_p() { CRGBPalette16 current_palette = CloudColors_p; fill_led_colors(current_palette); } void oceanColors_p() { CRGBPalette16 current_palette = OceanColors_p; fill_led_colors(current_palette); } void forestColors_p() { CRGBPalette16 current_palette = ForestColors_p; fill_led_colors(current_palette); } void lavaColors_p() { CRGBPalette16 current_palette = LavaColors_p; fill_led_colors(current_palette); } void rainbowStripeColors_p() { CRGBPalette16 current_palette = RainbowStripeColors_p; fill_led_colors(current_palette); } void partyColors_p() { CRGBPalette16 current_palette = PartyColors_p; fill_led_colors(current_palette); } void heatColors_p() { CRGBPalette16 current_palette = HeatColors_p; fill_led_colors(current_palette); }
24.605263
80
0.728877
ljmerza
f62a2d735236ec7886e7eca2fd5ecc23a7f9cb5f
1,498
cpp
C++
Src/ai/zealotgroup.cpp
jjuiddong/AI-Practice
ebd3423c6684b6978c0d68cc9b29ab69acb1c545
[ "MIT" ]
1
2019-01-04T16:34:45.000Z
2019-01-04T16:34:45.000Z
Src/ai/zealotgroup.cpp
jjuiddong/AI-Practice
ebd3423c6684b6978c0d68cc9b29ab69acb1c545
[ "MIT" ]
null
null
null
Src/ai/zealotgroup.cpp
jjuiddong/AI-Practice
ebd3423c6684b6978c0d68cc9b29ab69acb1c545
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "zealotgroup.h" #include "groupmove.h" #include "formation.h" #include "formationmove.h" using namespace graphic; //---------------------------------------------------------------- cGroup::cGroup() { m_brain = new cZealotGroupBrain(this); } cGroup::~cGroup() { SAFE_DELETE(m_brain); } //---------------------------------------------------------------- cZealotGroupBrain::cZealotGroupBrain(cGroup *agent) : ai::cBrain<cGroup>(agent) { } cZealotGroupBrain::~cZealotGroupBrain() { } void cZealotGroupBrain::Move(const Vector3 &dest) { ClearAction(); PushAction(new ai::cGroupMove<cGroup>(m_agent, dest)); //Vector3 center; //for (auto &p : m_children.m_Seq) //{ // cBrain<cZealot> *actor = dynamic_cast<cBrain<cZealot>*>(p); // center += actor->m_agent->m_transform.pos; //} //center /= m_children.size(); //ai::cNavigationMesh &navi = g_ai.m_navi; //vector<Vector3> path; //vector<int> nodePath; //for (auto &p : m_children.m_Seq) //{ // cBrain<cZealot> *actor = dynamic_cast<cBrain<cZealot>*>(p); // if (!actor->m_agent->m_isSelect) // continue; // path.clear(); // nodePath.clear(); // if (navi.Find(actor->m_agent->m_transform.pos, dest, path, nodePath)) // actor->SetAction(new ai::cUnitMove<cZealot>(actor->m_agent, path, Vector3(0,0,0))); //} //m_agent->m_nodePath = nodePath; } void cZealotGroupBrain::FormationMove(const Vector3 &dest) { ClearAction(); PushAction(new ai::cFormationMove<cGroup>(m_agent, dest)); }
20.805556
88
0.625501
jjuiddong
f62b9446cb6a8084b843648adfd65d222d4df16f
5,861
cpp
C++
IP.cpp
keewon/winter-source-beta-3
6fb5d1f524119344785b3587ecb71dff74120b91
[ "FSFAP" ]
null
null
null
IP.cpp
keewon/winter-source-beta-3
6fb5d1f524119344785b3587ecb71dff74120b91
[ "FSFAP" ]
null
null
null
IP.cpp
keewon/winter-source-beta-3
6fb5d1f524119344785b3587ecb71dff74120b91
[ "FSFAP" ]
null
null
null
#include "IP.h" #include <set> #define LOG_ERR 3 unsigned int IP::counter(0); SOCKET IP:: UDP(int (*const function)(const SOCKET), const u_short port) { struct sockaddr_in address; size_t length(sizeof(struct sockaddr)); SOCKET socketID(socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "socket in IP::UDP\n"); return INVALID_SOCKET; } memset((void *) & address, 0, length); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(port); if (bind(socketID, (struct sockaddr *) & address, length) == SOCKET_ERROR) { syslog(LOG_ERR, "bind in IP::UDP\n"); closesocket(socketID); return INVALID_SOCKET; } client[socketID] = function; return socketID; } SOCKET IP:: TCP(int (*const function)(const SOCKET), const u_short port) { struct sockaddr_in address; size_t length(sizeof(struct sockaddr)); SOCKET socketID(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "socket in IP::TCP\n"); return INVALID_SOCKET; } memset((void *) & address, 0, length); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(port); if (bind(socketID, (struct sockaddr *) & address, length) == SOCKET_ERROR) { syslog(LOG_ERR, "bind in IP::TCP\n"); closesocket(socketID); return INVALID_SOCKET; } if (listen(socketID, SOMAXCONN) == SOCKET_ERROR) { syslog(LOG_ERR, "listen in IP::TCP\n"); closesocket(socketID); return INVALID_SOCKET; } server[socketID] = function; return socketID; } SOCKET IP:: TCP(int (*const function)(const SOCKET), const u_short port, const char *const server) { struct sockaddr_in address; size_t length(sizeof(struct sockaddr)); SOCKET socketID(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "socket in IP::TCP\n"); return INVALID_SOCKET; } memset((void *) & address, 0, length); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(server); address.sin_port = htons(port); if (connect(socketID, (struct sockaddr *) & address, length) == SOCKET_ERROR) { syslog(LOG_ERR, "connect in IP::TCP\n"); closesocket(socketID); return INVALID_SOCKET; } client[socketID] = function; return socketID; } bool IP:: empty(void) { if (client.find(INVALID_SOCKET) != client.end()) client.erase(INVALID_SOCKET); return server.empty() && client.empty(); } void IP:: erase(const SOCKET socketID) { if (server.find(socketID) != server.end()) server.erase(socketID); if (client.find(socketID) != client.end()) client.erase(socketID); closesocket(socketID); } int IP:: operator ()(const struct timeval *const timeout) { SOCKET maxID(0); fd_set FileDescriptors; FD_ZERO(& FileDescriptors); if (client.find(INVALID_SOCKET) != client.end()) client.erase(INVALID_SOCKET); for (map::const_iterator i(server.begin()); i != server.end(); ++i) { FD_SET(i->first, & FileDescriptors); if (maxID < i->first) maxID = i->first; } for (map::const_iterator i(client.begin()); i != client.end(); ++i) { FD_SET(i->first, & FileDescriptors); if (maxID < i->first) maxID = i->first; } if (select(maxID + 1, & FileDescriptors, 0, 0, const_cast <struct timeval *>(timeout)) == SOCKET_ERROR) { syslog(LOG_ERR, "select in IP::operator ()\n"); return SOCKET_ERROR; } std::set <SOCKET> sockets; for (map::const_iterator i(client.begin()); i != client.end(); ++i) if (FD_ISSET(i->first, & FileDescriptors) && i->second != 0) if ((* i->second)(i->first) == SOCKET_ERROR) sockets.insert(i->first); for (map::const_iterator i(server.begin()); i != server.end(); ++i) if (FD_ISSET(i->first, & FileDescriptors)) { struct sockaddr_in address; size_t length(sizeof(address)); SOCKET socketID(accept(i->first, (struct sockaddr *) & address, (int *) & length)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "accept in IP::operator ()\n"); continue; } if (maxID < socketID) maxID = socketID; client[socketID] = i->second; if (i->second != 0 && (* i->second)(socketID) == SOCKET_ERROR) sockets.insert(socketID); } for (std::set <SOCKET>::const_iterator i(sockets.begin()); i != sockets.end(); ++i) erase(* i); FD_ZERO(& FileDescriptors); return 0; } IP::map::referent_type & IP:: operator [](const SOCKET socketID) { if (server.find(socketID) != server.end()) return server[socketID]; if (client.find(socketID) != client.end()) return client[socketID]; return client[INVALID_SOCKET]; } IP:: IP(HWND hWnd) { if (counter++ == 0) { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR) { if (hWnd != 0) MessageBox(hWnd, "WSAStartup", "Winsock", MB_OK); WSACleanup(); } } } IP:: ~IP(void) { std::set <SOCKET> sockets; for (map::const_iterator i(server.begin()); i != server.end(); ++i) { closesocket(i->first); sockets.insert(i->first); } for (std::set <SOCKET>::const_iterator i(sockets.begin()); i != sockets.end(); ++i) server.erase(* i); sockets.clear(); for (map::const_iterator i(client.begin()); i != client.end(); ++i) { closesocket(i->first); sockets.insert(i->first); } for (std::set <SOCKET>::const_iterator i(sockets.begin()); i != sockets.end(); ++i) client.erase(* i); if (--counter == 0) WSACleanup(); }
25.819383
108
0.615765
keewon