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
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 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
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e20b87d157a78176c84ed496f2c412af7f8767c | 258 | cpp | C++ | LeetCode/100/26.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/26.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/26.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int left = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (!i or nums[i] != nums[i - 1]) {
nums[left++] = nums[i];
}
}
return left;
}
}; | 19.846154 | 43 | 0.468992 | K-ona |
3e275fe2ecb58bd94d4f90d23f99042a646a300b | 2,400 | cpp | C++ | source/pump.cpp | MuellerA/Led-Lamp | f54bd267e0e2b2d1d205f4bce3088e9081b22238 | [
"MIT"
] | null | null | null | source/pump.cpp | MuellerA/Led-Lamp | f54bd267e0e2b2d1d205f4bce3088e9081b22238 | [
"MIT"
] | null | null | null | source/pump.cpp | MuellerA/Led-Lamp | f54bd267e0e2b2d1d205f4bce3088e9081b22238 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// pump.cpp
// (c) Andreas Müller
// see LICENSE.md
////////////////////////////////////////////////////////////////////////////////
#include "ledMatrix.h"
////////////////////////////////////////////////////////////////////////////////
class Pump
{
public:
Pump(unsigned char mode) ;
void Update() ;
void Display() ;
void Config(unsigned char type, unsigned char value) ;
private:
unsigned char _mode ;
Rgb &_curRgb ;
Rgb _deltaRgb ;
Rgb _rgb[LedMatrix::kX/2] ;
unsigned char _brightness ;
unsigned char _state ;
} ;
static_assert(sizeof(Pump) < (RAMSIZE - 0x28), "not enough RAM") ;
////////////////////////////////////////////////////////////////////////////////
Pump::Pump(unsigned char mode) : _mode(mode), _curRgb(_rgb[LedMatrix::kX/2 - 1]), _brightness(0x7f), _state(0)
{
for (Rgb *iRgb = _rgb, *eRgb = _rgb + LedMatrix::kX/2 ; iRgb < eRgb ; ++iRgb)
iRgb->Clr(0x10) ;
_deltaRgb.Rnd(_brightness) ;
_deltaRgb.Sub(_curRgb) ;
_deltaRgb.DivX() ;
}
void Pump::Update()
{
if (_state == 0)
{
_deltaRgb.Rnd(_brightness) ;
_deltaRgb.Sub(_curRgb) ;
_deltaRgb.DivX() ;
}
if (_state < LedMatrix::kX)
{
for (unsigned char x2 = 0 ; x2 < LedMatrix::kX/2 - 1 ; ++x2)
_rgb[x2] = _rgb[x2+1] ;
_curRgb.Add(_deltaRgb) ;
}
else if (_state < LedMatrix::kX * 2)
{
for (unsigned char x2 = 0 ; x2 < LedMatrix::kX/2 - 1 ; ++x2)
_rgb[x2] = _rgb[x2+1] ;
}
if (++_state == LedMatrix::kX * 3)
_state = 0 ;
}
void Pump::Display()
{
for (unsigned short idx = 0 ; idx < LedMatrix::kSize ; ++idx)
{
switch (_mode)
{
case 1:
{
unsigned char x, y ;
LedMatrix::IdxToCoord(idx, x, y) ;
if (x >= LedMatrix::kX/2)
x = LedMatrix::kX-1 - x ;
if (y >= LedMatrix::kY/2)
y = LedMatrix::kY-1 - y ;
if (y < x)
x = y ;
_rgb[x].Send() ;
}
break ;
default:
{
_curRgb.Send() ;
}
break ;
}
}
}
void Pump::Config(unsigned char type, unsigned char value)
{
switch (type)
{
case LedMatrix::ConfigBrightness:
_brightness = value ;
break ;
case LedMatrix::ConfigForceRedraw:
break ;
}
}
////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////
| 21.428571 | 110 | 0.4625 | MuellerA |
3e2881dde342fe9a9f569feb0af115f140186669 | 3,034 | hpp | C++ | src/contrib/mlir/core/compiler.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/core/compiler.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/core/compiler.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 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.
//*****************************************************************************
// NOTE: This file follows nGraph format style.
// Follows nGraph naming convention for public APIs only, else MLIR naming
// convention.
#pragma once
#include <mlir/IR/Builders.h>
#include <mlir/IR/Module.h>
#include <mlir/IR/Types.h>
#include <typeindex>
#include <unordered_map>
#include <vector>
#include "contrib/mlir/runtime/cpu/memory_manager.hpp"
#include "ngraph/check.hpp"
#include "ngraph/descriptor/tensor.hpp"
#include "ngraph/function.hpp"
#include "ngraph/log.hpp"
#include "ngraph/node.hpp"
#include "ngraph/op/experimental/compiled_kernel.hpp"
namespace ngraph
{
namespace runtime
{
namespace ngmlir
{
/// MLIR Compiler. Given an nGraph sub-graph, represented as CompiledKernel
/// node, it
/// translates the graph down to nGraph dialect and applies core optimizations.
///
/// The compiler owns the MLIR module until compilation is done. After that,
/// the module can be grabbed and plugged into MLIR backends.
class MLIRCompiler
{
public:
/// Initializes MLIR environment. It must be called only once.
static void init();
public:
MLIRCompiler(std::shared_ptr<ngraph::Function> function,
::mlir::MLIRContext& context);
/// Compiles a subgraph with MLIR
void compile();
::mlir::OwningModuleRef& get_module() { return m_module; }
private:
// Converts an nGraph sub-graph to MLIR nGraph dialect.
void buildNgDialectModule();
// Applies any nGraph dialect optimizations
void optimizeNgDialect();
private:
// Sub-graph to be compiled and executed with MLIR.
std::shared_ptr<ngraph::Function> m_function;
// MLIR context that holds all the MLIR information related to the sub-graph
// compilation.
::mlir::MLIRContext& m_context;
::mlir::OwningModuleRef m_module;
// Global initialization for MLIR compiler
static bool initialized;
};
}
}
}
| 35.694118 | 92 | 0.591628 | pqLee |
3e2c8a71eebd064e23fb673f96a6d5e7ea409572 | 8,915 | cpp | C++ | src/StatusBar.cpp | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 6 | 2018-04-08T06:30:27.000Z | 2021-12-19T12:52:28.000Z | src/StatusBar.cpp | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 32 | 2017-11-03T09:39:48.000Z | 2021-12-23T18:27:20.000Z | src/StatusBar.cpp | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 1 | 2021-09-13T08:38:56.000Z | 2021-09-13T08:38:56.000Z | /*
* $Header: /Book/StatusBar.cpp 14 16.07.04 10:42 Oslph312 $
*
* NOTE: Both Toolbar and Statusbar are tailored to TextEdit.
* A more general approach would be to derive both from base classes.
*/
#include "precomp.h"
#include "Statusbar.h"
#include "MenuFont.h"
#include "HTML.h"
#include "InstanceSubclasser.h"
#include "formatMessage.h"
#include "formatNumber.h"
#include "graphics.h"
#include "utils.h"
#include "resource.h"
#ifndef SB_SETICON
#define SB_SETICON (WM_USER+15)
#endif
PRIVATE bool sm_bHighlight = false;
PRIVATE LRESULT CALLBACK statusbarParentSpy(
HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
PRIVATE InstanceSubclasser s_parentSubclasser( statusbarParentSpy );
/**
* Recalculates the sizes of the various status bar parts.
*/
PRIVATE void recalcParts( HWND hwndStatusbar, int nTotalWidth = -1 ) {
assert( IsWindow( hwndStatusbar ) );
if ( -1 == nTotalWidth ) {
const Rect rc = getWindowRect( hwndStatusbar );
nTotalWidth = rc.width();
}
const int nBorder = GetSystemMetrics( SM_CXEDGE );
const int nWidth =
nTotalWidth - GetSystemMetrics( SM_CXVSCROLL ) - nBorder - 1;
const int nExtra = 4 * nBorder;
const int nWidthUnicode =
measureString( _T( "Unicode" ) ).cx + nExtra;
const int nWidthPosition =
measureString( _T( "Ln 99,999 Col 999 100%" ) ).cx + nExtra;
const int nWidthToolbarButton = GetSystemMetrics(
MenuFont::isLarge() ? SM_CXICON : SM_CXSMICON );
const int nWidthIcon = nWidthToolbarButton + nExtra;
const int aParts[] = {
nWidth - nWidthPosition - nWidthUnicode - nWidthIcon,
nWidth - nWidthUnicode - nWidthIcon,
nWidth - nWidthIcon,
nWidth - 0, // If we use -1, we overflow into the sizing grip.
};
SNDMSG( hwndStatusbar, SB_SETPARTS,
dim( aParts ), reinterpret_cast< LPARAM >( aParts ) );
}
PRIVATE void drawItem( DRAWITEMSTRUCT *pDIS ) {
// This returns a pointer to the static
// szMessageBuffer used in setMessageV:
LPCTSTR pszText = reinterpret_cast< LPCTSTR >(
SNDMSG( pDIS->hwndItem, SB_GETTEXT, 0, 0 ) );
const int nSavedDC = SaveDC( pDIS->hDC );
if ( sm_bHighlight ) {
SetTextColor( pDIS->hDC, GetSysColor( COLOR_HIGHLIGHTTEXT ) );
SetBkColor ( pDIS->hDC, GetSysColor( COLOR_HIGHLIGHT ) );
fillSysColorSolidRect( pDIS->hDC,
&pDIS->rcItem, COLOR_HIGHLIGHT );
pDIS->rcItem.left += GetSystemMetrics( SM_CXEDGE );
} else {
SetTextColor( pDIS->hDC, GetSysColor( COLOR_BTNTEXT ) );
SetBkColor ( pDIS->hDC, GetSysColor( COLOR_BTNFACE ) );
}
const int nHeight = Rect( pDIS->rcItem ).height();
const int nExtra = nHeight - MenuFont::getHeight();
pDIS->rcItem.top += nExtra / 2 - 1;
pDIS->rcItem.left += GetSystemMetrics( SM_CXEDGE );
paintHTML( pDIS->hDC, pszText, &pDIS->rcItem,
GetWindowFont( pDIS->hwndItem ), PHTML_SINGLE_LINE );
verify( RestoreDC( pDIS->hDC, nSavedDC ) );
}
PRIVATE LRESULT CALLBACK statusbarParentSpy(
HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
const LRESULT lResult =
s_parentSubclasser.callOldProc( hwnd, msg, wParam, lParam );
if ( WM_SIZE == msg ) {
HWND hwndStatusbar =
s_parentSubclasser.getUserDataAsHwnd( hwnd );
assert( IsWindow( hwndStatusbar ) );
const int cx = LOWORD( lParam );
recalcParts( hwndStatusbar, cx );
SNDMSG( hwndStatusbar, WM_SIZE, wParam, lParam );
} else if ( WM_DRAWITEM == msg ) {
drawItem( reinterpret_cast< DRAWITEMSTRUCT * >( lParam ) );
}
return lResult;
}
Statusbar::Statusbar( HWND hwndParent, UINT uiID )
: m_hicon( 0 )
, m_nIndex( 0 )
, zoomPercentage( 100 )
{
assert( 0 != this );
const HINSTANCE hinst = getModuleHandle();
attach( CreateWindowEx(
0, STATUSCLASSNAME, _T( "" ),
SBARS_SIZEGRIP | WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hwndParent, (HMENU) uiID, hinst, 0 ) );
assert( IsWindow( *this ) );
if ( !IsWindow( *this ) ) {
throwException( _T( "Unable to create status bar" ) );
}
onSettingChange( 0 ); // Sets the font and the parts.
verify( s_parentSubclasser.subclass( hwndParent, m_hwnd ) );
setMessage( IDS_READY );
}
Statusbar::~Statusbar() {
if ( 0 != m_hicon ) {
DestroyIcon( m_hicon );
}
}
void __cdecl Statusbar::setMessageV( LPCTSTR pszFmt, va_list vl ) {
// This *must* be a static buffer. Since the first pane is
// SBT_OWNERDRAW, the status bar control doesn't know that
// this is text; the lParam is merely 32 arbitrary bits of
// application data, and the status bar doesn't retain the
// text, just the pointer.
static TCHAR szMessageBuffer[ 512 ];
assert( isGoodStringPtr( pszFmt ) );
if ( isGoodStringPtr( pszFmt ) ) {
const String strMessage = formatMessageV( pszFmt, vl );
_tcsncpy_s( szMessageBuffer, strMessage.c_str(), _TRUNCATE );
} else {
_tcscpy_s( szMessageBuffer, _T( "Internal Error" ) );
}
int nPart = message_part | SBT_OWNERDRAW;
if ( sm_bHighlight ) {
nPart |= SBT_NOBORDERS; // SBT_POPOUT
// This invalidation is necessary for SBT_NOBORDERS.
// With SBT_POPOUT, it is not necessary.
Rect rc;
sendMessage( SB_GETRECT, message_part, reinterpret_cast< LPARAM >( &rc ) );
InvalidateRect( *this, &rc, TRUE );
}
setText( nPart, szMessageBuffer );
}
void __cdecl Statusbar::setMessage( LPCTSTR pszFmt, ... ) {
sm_bHighlight = false;
va_list vl;
va_start( vl, pszFmt );
setMessageV( pszFmt, vl );
va_end( vl );
}
void __cdecl Statusbar::setMessage( UINT idFmt, ... ) {
sm_bHighlight = false;
const String strFmt = loadString( idFmt );
va_list vl;
va_start( vl, idFmt );
setMessageV( strFmt.c_str(), vl );
va_end( vl );
}
void __cdecl Statusbar::setHighlightMessage( UINT idFmt, ... ) {
sm_bHighlight = true;
const String strFmt = loadString( idFmt );
va_list vl;
va_start( vl, idFmt );
setMessageV( strFmt.c_str(), vl );
va_end( vl );
}
void __cdecl Statusbar::setErrorMessage(
UINT idFlags, UINT idFmt, ... )
{
va_list vl;
va_start( vl, idFmt );
MessageBeep( idFlags );
const String strFmt = loadString( idFmt );
if ( IsWindowVisible( *this ) ) {
sm_bHighlight = true;
setMessageV( strFmt.c_str(), vl );
} else {
messageBoxV( GetParent( *this ), MB_OK | idFlags, strFmt.c_str(), vl );
}
va_end( vl );
}
void Statusbar::update( void ) {
#if 0 // TODO: Unit test of formatNumber
trace( _T( "testing formatNumber: %d = %s\n" ), 0, formatNumber( 0 ).c_str() );
trace( _T( "testing formatNumber: %d = %s\n" ), 123, formatNumber( 123 ).c_str() );
trace( _T( "testing formatNumber: %d = %s\n" ), 12345, formatNumber( 12345 ).c_str() );
trace( _T( "testing formatNumber: %d = %s\n" ), 1234567890, formatNumber( 1234567890 ).c_str() );
#endif
const String strLine = formatNumber( position.y + 1 );
const String strColumn = formatNumber( position.x + 1 );
const String strPos = formatMessage( IDS_POSITION, strLine.c_str(), strColumn.c_str() );
const String strZoom = formatMessage( _T( " %1!d!%%\t" ), this->zoomPercentage );
const String str = strPos + strZoom;
setText( position_part, str.c_str() );
const HWND hwndEditWnd = GetDlgItem( GetParent( *this ), IDC_EDIT );
if ( GetFocus() == hwndEditWnd ) {
setMessage( IDS_READY );
}
}
void Statusbar::update( const Point& updatedPosition ) {
this->position = updatedPosition;
update();
}
void Statusbar::update( const int updatedZoomPercentage ) {
this->zoomPercentage = updatedZoomPercentage;
update();
}
void Statusbar::setFileType( const bool isUnicode ) {
setText( filetype_part, isUnicode ? _T( "\tUnicode\t" ) : _T( "\tANSI\t" ) );
}
void Statusbar::setIcon( int nIndex ) {
const int nResource = MenuFont::isLarge() ? 121 : 120;
const HINSTANCE hinst = GetModuleHandle(_T("COMCTL32"));
const HIMAGELIST hImageList = ImageList_LoadImage(hinst,
MAKEINTRESOURCE(nResource),
0, 0, CLR_DEFAULT, IMAGE_BITMAP,
LR_DEFAULTSIZE | LR_LOADMAP3DCOLORS);
setIcon(hImageList, nIndex);
if (0 != hImageList) {
verify(ImageList_Destroy(hImageList));
}
}
void Statusbar::setIcon( HIMAGELIST hImageList, int nIndex ) {
if ( 0 != m_hicon ) {
DestroyIcon( m_hicon );
m_hicon = 0;
}
m_nIndex = nIndex;
if ( 0 != m_nIndex ) {
m_hicon = ImageList_GetIcon( hImageList, m_nIndex, ILD_NORMAL );
}
sendMessage( SB_SETICON, action_part, reinterpret_cast< LPARAM >( m_hicon ) );
UpdateWindow( *this );
}
void Statusbar::onSettingChange( LPCTSTR pszSection ) {
const HFONT hfont = MenuFont::getFont();
assert( 0 != hfont );
SetWindowFont( *this, hfont, true );
setIcon( m_nIndex );
recalcParts( *this );
}
// end of file
| 27.686335 | 100 | 0.654627 | petterh |
3e2f773e4ced7fe9781102528f0edfd009668136 | 7,427 | cpp | C++ | SysLib/Demand/Data/Trip_Length_Data.cpp | kravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | 2 | 2018-04-27T11:07:02.000Z | 2020-04-24T06:53:21.000Z | SysLib/Demand/Data/Trip_Length_Data.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | SysLib/Demand/Data/Trip_Length_Data.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | //*********************************************************
// Trip_Length_Data.cpp - trip length data class
//*********************************************************
#include "Trip_Length_Data.hpp"
//---------------------------------------------------------
// Trip_Length_Data constructor
//---------------------------------------------------------
Trip_Length_Data::Trip_Length_Data (void) : Class2_Index (0, 0)
{
Count (0);
}
//---------------------------------------------------------
// Trip_Length_Array constructor
//---------------------------------------------------------
Trip_Length_Array::Trip_Length_Array (int max_records) :
Class2_Array (sizeof (Trip_Length_Data), max_records), Static_Service ()
{
increment = 0;
output_flag = false;
}
//---- Add Trip ----
bool Trip_Length_Array::Add_Trip (int mode, int purpose1, int purpose2, int length, int count)
{
Trip_Length_Data *data_ptr, data_rec;
if (increment <= 0 || length < 0) return (false);
data_rec.Mode (mode);
if (purpose1 > purpose2) {
data_rec.Purpose1 (purpose2);
data_rec.Purpose2 (purpose1);
} else {
data_rec.Purpose1 (purpose1);
data_rec.Purpose2 (purpose2);
}
length /= increment;
if (length >= 0xFFFF) length = 0xFFFE;
data_rec.Increment (length);
data_ptr = (Trip_Length_Data *) Get (&data_rec);
if (data_ptr == NULL) {
data_ptr = New_Record (true);
if (data_ptr == NULL) return (false);
data_rec.Count (0);
if (!Add (&data_rec)) return (false);
}
data_ptr->Add_Count (count);
return (true);
}
//---- Open_Trip_Length_File ----
bool Trip_Length_Array::Open_Trip_Length_File (char *filename, char *label)
{
if (filename != NULL) {
output_flag = true;
exe->Print (1);
if (label == NULL) {
length_file.File_Type ("New Trip Length File");
} else {
length_file.File_Type (label);
}
length_file.File_Access (Db_Code::CREATE);
if (!length_file.Open (exe->Project_Filename (filename, exe->Extension ()))) {
exe->File_Error ("Creating New Trip Length File", length_file.Filename ());
return (false);
}
}
return (true);
}
//---- Write_Trip_Length_File ----
void Trip_Length_Array::Write_Trip_Length_File (void)
{
if (!output_flag) return;
int num_out;
Trip_Length_Data *data_ptr;
FILE *file;
exe->Show_Message ("Writing %s -- Record", length_file.File_Type ());
exe->Set_Progress ();
file = length_file.File ();
//---- write the header ----
fprintf (file, "MODE\tPURPOSE1\tPURPOSE2\tLENGTH\tTRIPS\n");
//---- write each record ----
num_out = 0;
for (data_ptr = First_Key (); data_ptr; data_ptr = Next_Key ()) {
exe->Show_Progress ();
fprintf (file, "%d\t%d\t%d\t%d\t%d\n", data_ptr->Mode (), data_ptr->Purpose1 (),
data_ptr->Purpose2 (), data_ptr->Increment () * increment, data_ptr->Count ());
num_out++;
}
exe->End_Progress ();
length_file.Close ();
exe->Print (2, "Number of %s Records = %d", length_file.File_Type (), num_out);
}
//
////---- Report ----
//
//void Trip_Length_Array::Report (int number, char *_title, char *_key1, char *_key2)
//{
// int size;
// Trip_Length_Data *data_ptr, total;
//
// //---- set header values ----
//
// keys = 0;
// if (_title != NULL) {
// size = (int) strlen (_title) + 1;
// title = new char [size];
// str_cpy (title, size, _title);
//
// exe->Show_Message (title);
// }
// if (_key1 != NULL) {
// size = (int) strlen (_key1) + 1;
// key1 = new char [size];
// str_cpy (key1, size, _key1);
// keys++;
// }
// if (_key2 != NULL) {
// size = (int) strlen (_key2) + 1;
// key2 = new char [size];
// str_cpy (key2, size, _key2);
// keys++;
// }
//
// //---- print the report ----
//
// exe->Header_Number (number);
//
// if (!exe->Break_Check (Num_Records () + 7)) {
// exe->Print (1);
// Header ();
// }
//
// for (data_ptr = First_Key (); data_ptr; data_ptr = Next_Key ()) {
// if (data_ptr->Count () == 0) continue;
//
// if (keys == 2) {
// exe->Print (1, "%3d-%-3d", (data_ptr->Group () >> 16), (data_ptr->Group () & 0x00FF));
// } else {
// exe->Print (1, "%5d ", data_ptr->Group ());
// }
//
// exe->Print (0, " %9d %8d %8d %8d %8d %8.2lf %8.2lf %8.2lf %8.2lf",
// data_ptr->Count (), (int) (data_ptr->Min_Distance () + 0.5),
// (int) (data_ptr->Max_Distance () + 0.5), (int) (data_ptr->Average_Distance () + 0.5),
// (int) (data_ptr->StdDev_Distance () + 0.5), data_ptr->Min_Time () / 60.0,
// data_ptr->Max_Time () / 60.0, data_ptr->Average_Time () / 60.0,
// data_ptr->StdDev_Time () / 60.0);
//
// if (total.Count () == 0) {
// total.Count (data_ptr->Count ());
// total.Distance (data_ptr->Distance ());
// total.Time (data_ptr->Time ());
// total.Distance_Sq (data_ptr->Distance_Sq ());
// total.Time_Sq (data_ptr->Time_Sq ());
//
// total.Min_Distance (data_ptr->Min_Distance ());
// total.Max_Distance (data_ptr->Max_Distance ());
//
// total.Min_Time (data_ptr->Min_Time ());
// total.Max_Time (data_ptr->Max_Time ());
// } else {
// total.Count (total.Count () + data_ptr->Count ());
// total.Distance (total.Distance () + data_ptr->Distance ());
// total.Time (total.Time () + data_ptr->Time ());
// total.Distance_Sq (total.Distance_Sq () + data_ptr->Distance_Sq ());
// total.Time_Sq (total.Time_Sq () + data_ptr->Time_Sq ());
//
// if (total.Min_Distance () > data_ptr->Min_Distance ()) total.Min_Distance (data_ptr->Min_Distance ());
// if (total.Max_Distance () < data_ptr->Max_Distance ()) total.Max_Distance (data_ptr->Max_Distance ());
//
// if (total.Min_Time () > data_ptr->Min_Time ()) total.Min_Time (data_ptr->Min_Time ());
// if (total.Max_Time () < data_ptr->Max_Time ()) total.Max_Time (data_ptr->Max_Time ());
// }
// }
// exe->Print (2, "Total %9d %8d %8d %8d %8d %8.2lf %8.2lf %8.2lf %8.2lf",
// total.Count (), (int) (total.Min_Distance () + 0.5), (int) (total.Max_Distance () + 0.5),
// (int) (total.Average_Distance () + 0.5), (int) (total.StdDev_Distance () + 0.5),
// total.Min_Time () / 60.0, total.Max_Time () / 60.0, total.Average_Time () / 60.0,
// total.StdDev_Time () / 60.0);
//
// exe->Header_Number (0);
//}
//
////---- Header ----
//
//void Trip_Length_Array::Header (void)
//{
// if (title != NULL) {
// exe->Print (1, title);
// } else {
// exe->Print (1, "Trip Length Summary Report");
// }
// if (keys < 2 || key1 == NULL) {
// exe->Print (2, "%19c", BLANK);
// } else {
// exe->Print (2, "%-7.7s%12c", key1, BLANK);
// }
// exe->Print (0, "------- Distance (meters) -------- --------- Time (minutes) ---------");
//
// if (keys == 2 && key2 != NULL) {
// exe->Print (1, "%-7.7s", key2);
// } else if (keys == 1 && key1 != NULL) {
// exe->Print (1, "%-7.7s", key1);
// } else {
// exe->Print (1, "Group ");
// }
// exe->Print (0, " Trips Minimum Maximum Average StdDev Minimum Maximum Average StdDev");
// exe->Print (1);
//}
//
///*********************************************|***********************************************
//
// [title]
//
// [key1] ------- Distance (meters) -------- --------- Time (minutes) ---------
// [key2] Trips Minimum Maximum Average StdDev Minimum Maximum Average StdDev
//
// ddd-ddd ddddddddd ddddddd ddddddd ddddddd ddddddd ffff.ff ffff.ff ffff.ff ffff.ff
//
// Total ddddddddd ddddddd ddddddd ddddddd ddddddd ffff.ff ffff.ff ffff.ff ffff.ff
//
//**********************************************|***********************************************/
| 29.355731 | 107 | 0.555271 | kravitz |
3e2f9520d1a6f948b0f0f5cfdbcdee95bb6006bc | 3,692 | cpp | C++ | src/blood.cpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | src/blood.cpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | src/blood.cpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
//
// blood.cpp
//
#include "blood.hpp"
#include "context.hpp"
#include "info-region.hpp"
#include "level.hpp"
#include "random.hpp"
#include "screen-regions.hpp"
#include "settings.hpp"
#include "util.hpp"
namespace halloween
{
Blood::Blood()
: m_texture()
, m_textureCoords1()
, m_textureCoords2()
, m_isUsingFirstAnim(true)
, m_timePerFrame(0.05f)
, m_elapsedTimeSec(0.0f)
, m_textureIndex(0)
, m_sprite()
, m_isFinished(true)
{
// there are two blood splat animation in the same texture
m_textureCoords1.emplace_back(0, 0, 128, 128);
m_textureCoords1.emplace_back(128, 0, 128, 128);
m_textureCoords1.emplace_back(256, 0, 128, 128);
m_textureCoords1.emplace_back(384, 0, 128, 128);
m_textureCoords1.emplace_back(512, 0, 128, 128);
m_textureCoords1.emplace_back(640, 0, 128, 128);
m_textureCoords1.emplace_back(768, 0, 128, 128);
m_textureCoords1.emplace_back(896, 0, 128, 128);
m_textureCoords1.emplace_back(1024, 0, 128, 128);
m_textureCoords2.emplace_back(0, 128, 128, 128);
m_textureCoords2.emplace_back(128, 128, 128, 128);
m_textureCoords2.emplace_back(256, 128, 128, 128);
m_textureCoords2.emplace_back(384, 128, 128, 128);
m_textureCoords2.emplace_back(512, 128, 128, 128);
m_textureCoords2.emplace_back(640, 128, 128, 128);
m_textureCoords2.emplace_back(768, 128, 128, 128);
m_textureCoords2.emplace_back(896, 128, 128, 128);
m_textureCoords2.emplace_back(1024, 128, 128, 128);
}
void Blood::setup(const Settings & settings)
{
const std::string PATH = (settings.media_path / "image" / "blood.png").string();
m_texture.loadFromFile(PATH);
m_texture.setSmooth(true);
m_sprite.setTexture(m_texture);
}
void
Blood::start(Context & context, const sf::Vector2f & POSITION, const bool WILL_SPLASH_RIGHT)
{
m_isFinished = false;
m_elapsedTimeSec = 0.0f;
m_textureIndex = 0;
m_isUsingFirstAnim = context.random.boolean();
m_sprite.setPosition(POSITION);
if (m_isUsingFirstAnim)
{
m_sprite.setTextureRect(m_textureCoords1.at(0));
}
else
{
m_sprite.setTextureRect(m_textureCoords2.at(0));
}
if (WILL_SPLASH_RIGHT)
{
m_sprite.setScale(1.0f, 1.0f);
}
else
{
m_sprite.setScale(-1.0f, 1.0f);
}
}
void Blood::update(Context &, const float FRAME_TIME_SEC)
{
if (m_isFinished)
{
return;
}
m_elapsedTimeSec += FRAME_TIME_SEC;
if (m_elapsedTimeSec < m_timePerFrame)
{
return;
}
m_elapsedTimeSec -= m_timePerFrame;
++m_textureIndex;
if (m_textureIndex >= m_textureCoords1.size())
{
m_textureIndex = 0;
m_isFinished = true;
return;
}
if (m_isUsingFirstAnim)
{
m_sprite.setTextureRect(m_textureCoords1.at(m_textureIndex));
}
else
{
m_sprite.setTextureRect(m_textureCoords2.at(m_textureIndex));
}
}
void Blood::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
if (!m_isFinished)
{
target.draw(m_sprite, states);
}
}
} // namespace halloween
| 28.183206 | 100 | 0.596425 | tilnewman |
3e2fc78edccb4cd465baf813018cec64967a8d19 | 3,996 | cpp | C++ | src/GUI/Button.cpp | zachtepper/project-awful | 59e2e9261100a2b4449022725435d21b17c6f5b4 | [
"MIT"
] | null | null | null | src/GUI/Button.cpp | zachtepper/project-awful | 59e2e9261100a2b4449022725435d21b17c6f5b4 | [
"MIT"
] | null | null | null | src/GUI/Button.cpp | zachtepper/project-awful | 59e2e9261100a2b4449022725435d21b17c6f5b4 | [
"MIT"
] | null | null | null | #include "Button.hpp"
Button::Button( sf::Vector2f position, sf::Vector2f dimensions,
sf::Font* font, std::string text, unsigned character_size, bool hasBorder,
sf::Color text_idle_color, sf::Color text_hover_color, sf::Color text_active_color,
sf::Color idle_color, sf::Color hover_color, sf::Color active_color)
{
/*
while (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
continue;
}
*/
this->buttonState = BTN_IDLE;
this->setBackdrop(sf::Vector2f(dimensions.x, dimensions.y), idle_color, sf::Vector2f(position.x, position.y), active_color, 1);
this->setFont(*font);
this->setString(text);
this->setFillColor(text_idle_color);
this->setCharacterSize(character_size);
this->setPosition(position.x + ((dimensions.x - this->getGlobalBounds().width) / 2 - 1),
position.y + ((dimensions.y - character_size) / 2) - 5);
if (hasBorder) {
this->backdrop.setOutlineColor(sf::Color::Black);
this->setOutlineColor(sf::Color::Black);
}
// Update Private Variables
this->assignColors(text_idle_color, text_hover_color, text_active_color, idle_color, hover_color, active_color);
}
Button::~Button () {
while (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
continue;
}
}
const bool Button::isPressed() const
{
if ( this->buttonState == BTN_ACTIVE )
{
return true;
}
return false;
}
vector <sf::Color> Button::getStateColors (int state) {
vector <sf::Color> colors;
if (state == BTN_IDLE) {
colors.push_back(this->textIdleColor);
colors.push_back(this->idleColor);
} else if (state == BTN_HOVER) {
colors.push_back(this->textHoverColor);
colors.push_back(this->hoverColor);
} else {
colors.push_back(this->textActiveColor);
colors.push_back(this->activeColor);
}
return colors;
}
void Button::assignColors (sf::Color text_idle_color, sf::Color text_hover_color, sf::Color text_active_color,
sf::Color idle_color, sf::Color hover_color, sf::Color active_color) {
this->textIdleColor = text_idle_color;
this->textHoverColor = text_hover_color;
this->textActiveColor = text_active_color;
this->idleColor = idle_color;
this->hoverColor = hover_color;
this->activeColor = active_color;
}
void Button::update(const sf::Vector2f& mousePos)
{
// update booleans for hover and pressed
this->buttonState = BTN_IDLE;
if ( this->backdrop.getGlobalBounds().contains(mousePos) )
{
this->buttonState = BTN_HOVER;
if ( sf::Mouse::isButtonPressed(sf::Mouse::Left) )
{
this->buttonState = BTN_ACTIVE;
}
}
switch ( this->buttonState )
{
case BTN_IDLE:
this->backdrop.setFillColor(this->idleColor);
this->setFillColor(this->textIdleColor);
this->backdrop.setOutlineThickness(0);
this->setOutlineThickness(0);
break;
case BTN_HOVER:
this->backdrop.setFillColor(this->hoverColor);
this->setFillColor(this->textHoverColor);
this->backdrop.setOutlineThickness(1);
this->setOutlineThickness(1);
break;
case BTN_ACTIVE:
this->backdrop.setFillColor(this->activeColor);
this->setFillColor(this->textActiveColor);
this->backdrop.setOutlineThickness(1.5);
this->setOutlineThickness(0.5);
break;
default:
this->backdrop.setFillColor(sf::Color::Red);
this->setFillColor(sf::Color::Blue);
break;
}
}
void Button::render(sf::RenderTarget& target)
{
if (this->checkBackdrop()) {
target.draw(this->backdrop);
}
target.draw(*this);
}
| 30.738462 | 132 | 0.603103 | zachtepper |
3e3d18964d0cbea8c9ca9770575265e7b935b368 | 9,084 | cpp | C++ | Project/Dev_class11_handout/Motor2D/j1Pathfinding.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/j1Pathfinding.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/j1Pathfinding.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | #include "j1Pathfinding.h"
#include "j1App.h"
#include "j1Textures.h"
#include "p2Log.h"
#include"Character.h"
#include"j1Map.h"
#include"j1Enemy.h"
#include "Brofiler/Brofiler.h"
///class Pathfinding ------------------
// Constructors =======================
j1Pathfinding::j1Pathfinding()
{
}
// Destructors ========================
j1Pathfinding::~j1Pathfinding()
{
}
//Game Loop ===========================
bool j1Pathfinding::Start()
{
//Generate map cluster abstraction
j1Timer timer;
//cluster_abstraction = new ClusterAbstraction(App->map, 10);
LOG("Cluster abstraction generated in %.3f", timer.ReadSec());
//Load debug tiles trexture
//path_texture = App->tex->Load("maps/path_tex.png");
return true;
}
bool j1Pathfinding::CleanUp()
{
RELEASE_ARRAY(path_nodes);
return true;
}
void j1Pathfinding::SetMap(uint width, uint height)
{
this->width = width;
this->height = height;
map_min_x = 0;
map_min_y = 0;
map_max_x = width;
map_max_y = height;
RELEASE_ARRAY(path_nodes);
int size = width*height;
path_nodes = new PathNode[size];
}
void j1Pathfinding::SetMapLimits(int position_x, int position_y, int width, int height)
{
map_min_x = position_x;
map_min_y = position_y;
map_max_x = position_x + width;
map_max_y = position_y + height;
}
//Functionality =======================
//Methods used during the paths creation to work with map data
bool j1Pathfinding::IsWalkable(const iPoint & destination) const
{
bool ret = false;
uchar t = GetTileAt(destination);
if (t)
int x = 0;
return (t == NOT_COLISION_ID);
}
bool j1Pathfinding::CheckBoundaries(const iPoint & pos) const
{
return (pos.x >= map_min_x && pos.x < map_max_x && pos.y >= map_min_y && pos.y < map_max_y);
}
uchar j1Pathfinding::GetTileAt(const iPoint & pos) const
{
if (CheckBoundaries(pos))
return GetValueMap(pos.x, pos.y);
return NOT_COLISION_ID;
}
uchar j1Pathfinding::GetValueMap(int x, int y) const
{
//In future we will have to adapt because with this enemies only can be in logic 0
return App->map->V_Colision[0]->data[(y*width) + x];
}
PathNode* j1Pathfinding::GetPathNode(int x, int y)
{
return &path_nodes[(y*width) + x];
}
std::vector<iPoint>* j1Pathfinding::SimpleAstar(const iPoint& origin, const iPoint& destination)
{
BROFILER_CATEGORY("A star", Profiler::Color::LightYellow);
int size = width*height;
std::fill(path_nodes, path_nodes + size, PathNode(-1, -1, iPoint(-1, -1), nullptr));
iPoint dest_point(destination.x, destination.y);
int ret = -1;
//iPoint mouse_position = App->map->FixPointMap(destination.x, destination.y);
/*iPoint map_origin = App->map->WorldToMap(origin.x, origin.y);
iPoint map_goal = App->map->WorldToMap(dest_point.x, dest_point.y);*/
/* if (map_origin == map_goal)
{
std::vector<iPoint>* path = new std::vector<iPoint>;
path->push_back(mouse_position);
return path;
}*/
if (IsWalkable(origin) && IsWalkable(dest_point))
{
ret = 1;
OpenList open;
PathNode* firstNode = GetPathNode(origin.x, origin.y);
firstNode->SetPosition(origin);
firstNode->g = 0;
firstNode->h = origin.DistanceManhattan(dest_point);
open.queue.push(firstNode);
PathNode* current = nullptr;
while (open.queue.size() != 0)
{
current = open.queue.top();
open.queue.top()->on_close = true;
open.queue.pop();
if (current->pos == dest_point)
{
std::vector<iPoint>* path = new std::vector<iPoint>;
last_path.clear();
path->push_back(dest_point);
iPoint mouse_cell = App->map->WorldToMap(dest_point.x, dest_point.y);
if (mouse_cell == current->pos)
current = GetPathNode(current->parent->pos.x, current->parent->pos.y);
for (; current->parent != nullptr; current = GetPathNode(current->parent->pos.x, current->parent->pos.y))
{
last_path.push_back(current->pos);
path->push_back({ current->pos.x, current->pos.y });
}
last_path.push_back(current->pos);
return path;
}
else
{
PathList neightbords;
current->FindWalkableAdjacents(&neightbords);
for (std::list<PathNode*>::iterator item = neightbords.list.begin(); item != neightbords.list.end(); item++) {
PathNode* temp = item._Mynode()->_Myval;
if (temp->on_close == true)
{
continue;
}
else if (temp->on_open == true)
{
int last_g_value = (int)temp->g;
temp->CalculateF(dest_point);
if (last_g_value <temp->g)
{
temp->parent = GetPathNode(current->pos.x, current->pos.y);
}
else {
temp->g = (float)last_g_value;
}
}
else
{
temp->on_open = true;
temp->CalculateF(dest_point);
open.queue.push(temp);
}
}
neightbords.list.clear();
}
}
}
return nullptr;
}
/// -----------------------------------
/// Struct PathNode -------------------
//Constructors ==============
PathNode::PathNode()
{
}
PathNode::PathNode(int g, int h, const iPoint & pos, const PathNode * parent) : g((float)g), h(h), pos(pos), parent(parent), on_close(false), on_open(false)
{
int x = 0;
}
PathNode::PathNode(const PathNode & node) : g(node.g), h(node.h), pos(node.pos), parent(node.parent)
{
int x = 0;
}
//Functionality =============
uint PathNode::FindWalkableAdjacents(PathList* list_to_fill) const
{
iPoint cell(0,0);
uint before = list_to_fill->list.size();
bool northClose = false, southClose = false, eastClose = false, westClose = false;
// south
cell.create(pos.x, pos.y + 1);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
southClose = true;
}
// north
cell.create(pos.x, pos.y - 1);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
northClose = true;
}
// east
cell.create(pos.x + 1, pos.y);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
eastClose = true;
}
// west
cell.create(pos.x - 1, pos.y);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
westClose = true;
}
return list_to_fill->list.size();
}
float PathNode::Score() const
{
return g + h;
}
int PathNode::CalculateF(const iPoint & destination)
{
g = parent->g + parent->pos.DistanceManhattan(pos);
h = pos.DistanceManhattan(destination) * 10;
return (int)g + h;
}
void PathNode::SetPosition(const iPoint & value)
{
pos = value;
}
//Operators =================
bool PathNode::operator==(const PathNode & node) const
{
return pos == node.pos;
}
bool PathNode::operator!=(const PathNode & node) const
{
return !operator==(node);
}
/// -----------------------------------
///Struct PathList --------------------
//Functionality =============
/*
std::list<PathNode>::iterator PathList::Find(const iPoint & point)
{
std::list<PathNode*>::iterator item = list.begin();
while (item != list.end())
{
if (item->pos == point) {
return item;
}
++item;
}
}
PathNode* PathList::GetNodeLowestScore() const
{
PathNode* ret = nullptr;
std::list<PathNode>::const_reverse_iterator item = list.crbegin();
float min = 65535;
while (item != list.crend())
{
if (item->Score() < min)
{
min = item->Score();
ret = &item.base()._Ptr->_Prev->_Myval;
}
++item;
}
return ret;
}*/
void j1Pathfinding::Move(Enemy * enemy, Character* player)
{
if (enemy->green_enemy_path.size()) {
static int i = 1;
int temp = enemy->green_enemy_path[enemy->green_enemy_path.size() - i].x;
int temp2 = enemy->green_enemy_path[enemy->green_enemy_path.size() - i].y;
int x = 0;
int y = 0;
x = x + (enemy->green_enemy_path[enemy->green_enemy_path.size()-i].x - enemy->tile_pos.x);
y = y + (enemy->green_enemy_path[enemy->green_enemy_path.size()- i].y - enemy->tile_pos.y);
/*
if (last_path.size() > 1) {
x = x + (last_path[i + 1].x - enemy->array_pos.x);
y = y + (last_path[i + 1].y - enemy->array_pos.y);
}*/
//enemy->actual_event = move;
//Change this
if (x >= 1) { x = 1; enemy->Enemy_Orientation = OrientationEnemy::right_enemy; }
if (x <= -1) { x = -1; enemy->Enemy_Orientation = OrientationEnemy::left_enemy; }
if (y >= 1) { y = 1; enemy->Enemy_Orientation = OrientationEnemy::down_enemy; }
if (y <= -1) { y = -1; enemy->Enemy_Orientation = OrientationEnemy::up_enemy; }
enemy->pos.x += x;
enemy->pos.y += y;
if (enemy->tile_pos == enemy->green_enemy_path[enemy->green_enemy_path.size()-i]) {
i++;
}
if (i == enemy->green_enemy_path.size() || enemy->tile_pos == player->tilepos) {
i = 0;
enemy->green_enemy_path.clear();
}
}
} | 22.597015 | 156 | 0.637274 | Guille1406 |
3e4629739ad02c3678733e95fe64f9aa544d2627 | 3,633 | cpp | C++ | src/chat.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | src/chat.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | src/chat.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chat.h"
#include "base58.h"
#include "clientversion.h"
#include "net.h"
#include "pubkey.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "rpcpog.h"
#include <stdint.h>
#include <algorithm>
#include <map>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
map<uint256, CChat> mapChats;
CCriticalSection cs_mapChats;
void CChat::SetNull()
{
nVersion = 1;
nTime = 0;
nID = 0;
bPrivate = false;
nPriority = 0;
sPayload.clear();
sFromNickName.clear();
sToNickName.clear();
sDestination.clear();
}
std::string CChat::ToString() const
{
return strprintf(
"CChat(\n"
" nVersion = %d\n"
" nTime = %d\n"
" nID = %d\n"
" bPrivate = %d\n"
" nPriority = %d\n"
" sDestination = %s\n"
" sPayload = \"%s\"\n"
" sFromNickName= \"%s\"\n"
" sToNickName = \"%s\"\n"
")\n",
nVersion,
nTime,
nID,
bPrivate,
nPriority,
sDestination,
sPayload,
sFromNickName,
sToNickName);
}
std::string CChat::Serialized() const
{
return strprintf(
"%d<COL>%d<COL>%d<COL>%d<COL>%d<COL>%s<COL>%s<COL>%s<COL>%s",
nVersion,
nTime,
nID,
bPrivate,
nPriority,
sDestination,
sPayload,
sFromNickName,
sToNickName);
}
void CChat::Deserialize(std::string sData)
{
std::vector<std::string> vInput = Split(sData.c_str(),"<COL>");
if (vInput.size() > 7)
{
this->nVersion = cdbl(vInput[0], 0);
this->nTime = cdbl(vInput[1], 0);
this->nID = cdbl(vInput[2], 0);
this->bPrivate = (bool)(cdbl(vInput[3], 0));
this->nPriority = cdbl(vInput[4], 0);
this->sDestination = vInput[5];
this->sPayload = vInput[6];
this->sFromNickName = vInput[7];
this->sToNickName = vInput[8];
}
}
bool CChat::IsNull() const
{
return (nTime == 0);
}
uint256 CChat::GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << nTime;
ss << nPriority;
ss << sPayload;
ss << sFromNickName;
ss << sToNickName;
ss << sDestination;
return ss.GetHash();
}
bool CChat::RelayTo(CNode* pnode) const
{
if (pnode->nVersion == 0) return false;
// returns true if wasn't already contained in the set
if (pnode->setKnown.insert(GetHash()).second)
{
pnode->PushMessage(NetMsgType::CHAT, *this);
return true;
}
return false;
}
CChat CChat::getChatByHash(const uint256 &hash)
{
CChat retval;
{
LOCK(cs_mapChats);
map<uint256, CChat>::iterator mi = mapChats.find(hash);
if(mi != mapChats.end())
retval = mi->second;
}
return retval;
}
bool CChat::ProcessChat()
{
map<uint256, CChat>::iterator mi = mapChats.find(GetHash());
if(mi != mapChats.end()) return false;
// Never seen this chat record
mapChats.insert(make_pair(GetHash(), *this));
// Notify UI
std::string sNickName = GetArg("-nickname", "");
if (boost::iequals(sNickName, sToNickName) && sPayload == "<RING>" && bPrivate == true)
{
msPagedFrom = sFromNickName;
mlPaged++;
}
uiInterface.NotifyChatEvent(Serialized());
return true;
}
| 22.70625 | 88 | 0.613543 | Mart1250 |
3e46eb3d32a6c9436a26fded7473f982d169cfb2 | 432 | cpp | C++ | src/apps/AlexMachine/stateMachine/states/SteppingRight.cpp | TomMinuzzo/CSALEX2022 | 28513f5e60cee890913c0c5d63fd9e3fcdf4039c | [
"Apache-2.0"
] | null | null | null | src/apps/AlexMachine/stateMachine/states/SteppingRight.cpp | TomMinuzzo/CSALEX2022 | 28513f5e60cee890913c0c5d63fd9e3fcdf4039c | [
"Apache-2.0"
] | null | null | null | src/apps/AlexMachine/stateMachine/states/SteppingRight.cpp | TomMinuzzo/CSALEX2022 | 28513f5e60cee890913c0c5d63fd9e3fcdf4039c | [
"Apache-2.0"
] | null | null | null | #include "SteppingRight.h"
void SteppingRight::entry(void) {
spdlog::info(" Stepping RIGHT");
trajectoryGenerator->initialiseTrajectory(robot->getCurrentMotion(), Foot::Left, robot->getJointStates());
robot->startNewTraj();
robot->setCurrentState(AlexState::StepR);
}
void SteppingRight::during(void) {
robot->moveThroughTraj();
}
void SteppingRight::exit(void) {
spdlog::debug("EXITING STEPPING RIGHT");
}
| 28.8 | 110 | 0.719907 | TomMinuzzo |
3e49c8455ad03eb0ee43530510402b5ff5e0c931 | 43,621 | cpp | C++ | 099/graysvr/CClientUse.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | 2 | 2020-12-22T17:03:14.000Z | 2021-07-31T23:59:05.000Z | 099/graysvr/CClientUse.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | null | null | null | 099/graysvr/CClientUse.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | 4 | 2021-04-21T19:43:48.000Z | 2021-10-07T00:38:23.000Z | // CClientUse.cpp
// Copyright Menace Software (www.menasoft.com).
//
#include "graysvr.h" // predef header.
#include "cclient.h"
bool CClient::Cmd_Use_Item( CItem * pItem, bool fTestTouch )
{
// Assume we can see the target.
// called from Event_DoubleClick
if ( pItem == NULL )
return false;
if ( fTestTouch )
{
// CanTouch handles priv level compares for chars
if ( ! m_pChar->CanUse( pItem, false ))
{
if ( ! m_pChar->CanTouch( pItem ))
{
SysMessage(( m_pChar->IsStatFlag( STATF_DEAD )) ?
"Your ghostly hand passes through the object." :
"You can't reach that." );
return false;
}
SysMessage( "You can't use this where it is." );
return false;
}
}
CItemBase * pItemDef = pItem->Item_GetDef();
// Must equip the item ?
if ( pItemDef->IsTypeEquippable() && pItem->GetParent() != m_pChar )
{
DEBUG_CHECK( pItemDef->GetEquipLayer());
switch ( pItem->GetType())
{
case IT_LIGHT_LIT:
case IT_SPELLBOOK:
// can be equipped, but don't need to be
break;
case IT_LIGHT_OUT:
if ( ! pItem->IsItemInContainer())
break;
default:
if ( ! m_pChar->CanMove( pItem ) ||
! m_pChar->ItemEquip( pItem ))
{
SysMessage( "The item should be equipped to use." );
return false;
}
break;
}
}
SetTargMode();
m_Targ_UID = pItem->GetUID(); // probably already set anyhow.
m_tmUseItem.m_pParent = pItem->GetParent(); // Cheat Verify.
if ( pItem->OnTrigger( ITRIG_DCLICK, m_pChar ) == TRIGRET_RET_TRUE )
{
return true;
}
// Use types of items. (specific to client)
switch ( pItem->GetType() )
{
case IT_TRACKER:
{
DIR_TYPE dir = (DIR_TYPE) ( DIR_QTY + 1 ); // invalid value.
if ( ! m_pChar->Skill_Tracking( pItem->m_uidLink, dir ))
{
if ( pItem->m_uidLink.IsValidUID())
{
SysMessage( "You cannot locate your target" );
}
m_Targ_UID = pItem->GetUID();
addTarget( CLIMODE_TARG_LINK, "Who do you want to attune to ?" );
}
}
return true;
case IT_TRACK_ITEM: // 109 - track a id or type of item.
case IT_TRACK_CHAR: // 110 = track a char or range of char id's
// Track a type of item or creature.
{
// Look in the local area for this item or char.
}
break;
case IT_SHAFT:
case IT_FEATHER:
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_bolts" ));
return true;
case IT_FISH_POLE: // Just be near water ?
addTarget( CLIMODE_TARG_USE_ITEM, "Where would you like to fish?", true );
return true;
case IT_DEED:
addTargetDeed( pItem );
return true;
case IT_METRONOME:
pItem->OnTick();
return true;
case IT_EQ_BANK_BOX:
case IT_EQ_VENDOR_BOX:
g_Log.Event( LOGL_WARN|LOGM_CHEAT,
"%x:Cheater '%s' is using 3rd party tools to open bank box\n",
m_Socket.GetSocket(), (LPCTSTR) GetAccount()->GetName());
return false;
case IT_CONTAINER_LOCKED:
case IT_SHIP_HOLD_LOCK:
if ( ! m_pChar->GetPackSafe()->ContentFindKeyFor( pItem ))
{
SysMessage( "This item is locked.");
if ( ! IsPriv( PRIV_GM ))
return false;
}
case IT_CORPSE:
case IT_SHIP_HOLD:
case IT_CONTAINER:
case IT_TRASH_CAN:
{
CItemContainer * pPack = dynamic_cast <CItemContainer *>(pItem);
if ( ! m_pChar->Skill_Snoop_Check( pPack ))
{
if ( ! addContainerSetup( pPack ))
return false;
}
}
return true;
case IT_GAME_BOARD:
if ( ! pItem->IsTopLevel())
{
SysMessage( "Can't open game board in a container" );
return false;
}
{
CItemContainer* pBoard = dynamic_cast <CItemContainer *>(pItem);
ASSERT(pBoard);
pBoard->Game_Create();
addContainerSetup( pBoard );
}
return true;
case IT_BBOARD:
addBulletinBoard( dynamic_cast<CItemContainer *>(pItem));
return true;
case IT_SIGN_GUMP:
// Things like grave stones and sign plaques.
// Need custom gumps.
{
GUMP_TYPE gumpid = pItemDef->m_ttContainer.m_gumpid;
if ( ! gumpid )
{
return false;
}
addGumpTextDisp( pItem, gumpid, pItem->GetName(),
( pItem->IsIndividualName()) ? pItem->GetName() : NULL );
}
return true;
case IT_BOOK:
case IT_MESSAGE:
case IT_EQ_NPC_SCRIPT:
case IT_EQ_MESSAGE:
if ( ! addBookOpen( pItem ))
{
SysMessage( "The book apears to be ruined!" );
}
return true;
case IT_STONE_GUILD:
case IT_STONE_TOWN:
case IT_STONE_ROOM:
// Guild and town stones.
{
CItemStone * pStone = dynamic_cast<CItemStone*>(pItem);
if ( pStone == NULL )
break;
pStone->Use_Item( this );
}
return true;
case IT_ADVANCE_GATE:
// Upgrade the player to the skills of the selected NPC script.
m_pChar->Use_AdvanceGate( pItem );
return true;
case IT_POTION:
if ( ! m_pChar->CanMove( pItem )) // locked down decoration.
{
SysMessage( "You can't move the item." );
return false;
}
if ( RES_GET_INDEX(pItem->m_itPotion.m_Type) == SPELL_Poison )
{
// ask them what they want to use the poison on ?
// Poisoning or poison self ?
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, true );
return true;
}
else if ( RES_GET_INDEX(pItem->m_itPotion.m_Type) == SPELL_Explosion )
{
// Throw explode potion.
if ( ! m_pChar->ItemPickup( pItem, 1 ))
return true;
m_tmUseItem.m_pParent = pItem->GetParent(); // Cheat Verify FIX.
addTarget( CLIMODE_TARG_USE_ITEM, "Where do you want to throw the potion?", true, true );
// Put the potion in our hand as well. (and set it's timer)
pItem->m_itPotion.m_tick = 4; // countdown to explode purple.
pItem->SetTimeout( TICK_PER_SEC );
pItem->m_uidLink = m_pChar->GetUID();
return true;
}
if ( m_pChar->Use_Drink( pItem ))
return true;
break;
case IT_ANIM_ACTIVE:
SysMessage( "The item is in use" );
return false;
case IT_CLOCK:
addObjMessage( m_pChar->GetTopSector()->GetLocalGameTime(), pItem );
return true;
case IT_SPAWN_CHAR:
SysMessage( "You negate the spawn" );
pItem->Spawn_KillChildren();
return true;
case IT_SPAWN_ITEM:
SysMessage( "You trigger the spawn." );
pItem->Spawn_OnTick( true );
return true;
case IT_SHRINE:
if ( m_pChar->OnSpellEffect( SPELL_Resurrection, m_pChar, 1000, pItem ))
return true;
SysMessage( "You have a feeling of holiness" );
return true;
case IT_SHIP_TILLER:
// dclick on tiller man.
pItem->Speak( "Arrg stop that.", 0, TALKMODE_SAY, FONT_NORMAL );
return true;
// A menu or such other action ( not instantanious)
case IT_WAND:
case IT_SCROLL: // activate the scroll.
return Cmd_Skill_Magery( (SPELL_TYPE)RES_GET_INDEX(pItem->m_itWeapon.m_spell), pItem );
case IT_RUNE:
// name the rune.
if ( ! m_pChar->CanMove( pItem, true ))
{
return false;
}
addPromptConsole( CLIMODE_PROMPT_NAME_RUNE, "What is the new name of the rune ?" );
return true;
case IT_CARPENTRY:
// Carpentry type tool
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_carpentry" ));
return true;
// Solve for the combination of this item with another.
case IT_FORGE:
addTarget( CLIMODE_TARG_USE_ITEM, "Select ore to smelt." );
return true;
case IT_ORE:
// just use the nearest forge.
return m_pChar->Skill_Mining_Smelt( pItem, NULL );
case IT_INGOT:
return Cmd_Skill_Smith( pItem );
case IT_KEY:
case IT_KEYRING:
if ( pItem->GetTopLevelObj() != m_pChar && ! m_pChar->IsPriv(PRIV_GM))
{
SysMessage( "The key must be on your person" );
return false;
}
addTarget( CLIMODE_TARG_USE_ITEM, "Select item to use the key on.", false, true );
return true;
case IT_BANDAGE: // SKILL_HEALING, or SKILL_VETERINARY
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, false );
return true;
case IT_BANDAGE_BLOOD: // Clean the bandages.
case IT_COTTON: // use on a spinning wheel.
case IT_WOOL: // use on a spinning wheel.
case IT_YARN: // Use this on a loom.
case IT_THREAD: // Use this on a loom.
case IT_COMM_CRYSTAL:
case IT_SCISSORS:
case IT_LOCKPICK: // Use on a locked thing.
case IT_CARPENTRY_CHOP:
case IT_WEAPON_MACE_STAFF:
case IT_WEAPON_MACE_SMITH: // Can be used for smithing ?
case IT_WEAPON_MACE_SHARP: // war axe can be used to cut/chop trees.
case IT_WEAPON_SWORD: // 23 =
case IT_WEAPON_FENCE: // 24 = can't be used to chop trees.
case IT_WEAPON_AXE:
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, true );
return true;
case IT_MEAT_RAW:
case IT_FOOD_RAW:
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to cook this on?" );
return true;
case IT_FISH:
SysMessage( "Use a knife to cut this up" );
return true;
case IT_TELESCOPE:
// Big telescope.
SysMessage( "Wow you can see the sky!" );
return true;
case IT_MAP:
case IT_MAP_BLANK:
if ( ! pItem->m_itMap.m_right && ! pItem->m_itMap.m_bottom )
{
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_cartography" ));
}
else if ( ! IsPriv(PRIV_GM) && pItem->GetTopLevelObj() != m_pChar ) // must be on your person.
{
SysMessage( "You must possess the map to get a good look at it." );
}
else
{
addMap( dynamic_cast <CItemMap*>( pItem ));
}
return true;
case IT_CANNON_BALL:
{
CGString sTmp;
sTmp.Format( "What do you want to use the %s on?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp );
}
return true;
case IT_CANNON_MUZZLE:
// Make sure the cannon is loaded.
if ( ! m_pChar->CanUse( pItem, false ))
return( false );
if ( ! ( pItem->m_itCannon.m_Load & 1 ))
{
addTarget( CLIMODE_TARG_USE_ITEM, "The cannon needs powder" );
return true;
}
if ( ! ( pItem->m_itCannon.m_Load & 2 ))
{
addTarget( CLIMODE_TARG_USE_ITEM, "The cannon needs shot" );
return true;
}
addTarget( CLIMODE_TARG_USE_ITEM, "Armed and ready. What is the target?", false, true );
return true;
case IT_CRYSTAL_BALL:
// Gaze into the crystal ball.
return true;
case IT_WEAPON_MACE_CROOK:
addTarget( CLIMODE_TARG_USE_ITEM, "What would you like to herd?", false, true );
return true;
case IT_SEED:
case IT_PITCHER_EMPTY:
{ // not a crime.
CGString sTmp;
sTmp.Format( "Where do you want to use the %s?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp, true );
}
return true;
case IT_WEAPON_MACE_PICK:
{ // Mine at the location. (possible crime?)
CGString sTmp;
sTmp.Format( "Where do you want to use the %s?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp, true, true );
}
return true;
case IT_SPELLBOOK:
addSpellbookOpen( pItem );
return true;
case IT_HAIR_DYE:
if (!m_pChar->LayerFind( LAYER_BEARD ) && !m_pChar->LayerFind( LAYER_HAIR ))
{
SysMessage("You have no hair to dye!");
return true;
}
Dialog_Setup( CLIMODE_DIALOG_HAIR_DYE, g_Cfg.ResourceGetIDType( RES_DIALOG, "d_HAIR_DYE" ), m_pChar );
return true;
case IT_DYE:
addTarget( CLIMODE_TARG_USE_ITEM, "Which dye vat will you use this on?" );
return true;
case IT_DYE_VAT:
addTarget( CLIMODE_TARG_USE_ITEM, "Select the object to use this on.", false, true );
return true;
case IT_MORTAR:
// If we have a mortar then do alchemy.
addTarget( CLIMODE_TARG_USE_ITEM, "What reagent you like to make a potion out of?" );
return true;
case IT_POTION_EMPTY:
if ( ! m_pChar->ContentFind(RESOURCE_ID(RES_TYPEDEF,IT_MORTAR)))
{
SysMessage( "You have no mortar and pestle." );
return( false );
}
addTarget( CLIMODE_TARG_USE_ITEM, "What reagent you like to make a potion out of?" );
return true;
case IT_REAGENT:
// Make a potion with this. (The best type we can)
if ( ! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_MORTAR)))
{
SysMessage( "You have no mortar and pestle." );
return false;
}
Cmd_Skill_Alchemy( pItem );
return true;
// Put up menus to better decide what to do.
case IT_TINKER_TOOLS: // Tinker tools.
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_tinker" ));
return true;
case IT_SEWING_KIT: // IT_SEWING_KIT Sew with materials we have on hand.
{
CGString sTmp;
sTmp.Format( "What do you want to use the %s on?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp );
}
return true;
case IT_SCROLL_BLANK:
Cmd_Skill_Inscription();
return true;
default:
// An NPC could use it this way.
if ( m_pChar->Use_Item( pItem ))
return( true );
break;
}
SysMessage( "You can't think of a way to use that item.");
return( false );
}
void CClient::Cmd_EditItem( CObjBase * pObj, int iSelect )
{
// ARGS:
// iSelect == -1 = setup.
// m_Targ_Text = what are we doing to it ?
//
if ( pObj == NULL )
return;
CContainer * pContainer = dynamic_cast <CContainer *> (pObj);
if ( pContainer == NULL )
{
addGumpDialogProps( pObj->GetUID());
return;
}
if ( iSelect == 0 )
return; // cancelled.
if ( iSelect > 0 )
{
// We selected an item.
if ( iSelect >= COUNTOF(m_tmMenu.m_Item))
return;
if ( m_Targ_Text.IsEmpty())
{
addGumpDialogProps( m_tmMenu.m_Item );
}
else
{
OnTarg_Obj_Set( CGrayUID( m_tmMenu.m_Item ).ObjFind() );
}
return;
}
CMenuItem item; // Most as we want to display at one time.
item.m_sText.Format( "Contents of %s", (LPCTSTR) pObj->GetName());
int count=0;
for ( CItem * pItem = pContainer->GetContentHead(); pItem != NULL; pItem = pItem->GetNext())
{
if ( count >= COUNTOF( item ))
break;
m_tmMenu.m_Item = pItem->GetUID();
item.m_sText = pItem->GetName();
ITEMID_TYPE idi = pItem->GetDispID();
item.m_id = idi;
}
addItemMenu( CLIMODE_MENU_EDIT, item, count, pObj );
}
bool CClient::Cmd_CreateItem( ITEMID_TYPE id, bool fStatic )
{
// make an item near by.
m_tmAdd.m_id = id;
m_tmAdd.m_fStatic = fStatic;
return addTargetItems( CLIMODE_TARG_ADDITEM, m_tmAdd.m_id );
}
bool CClient::Cmd_CreateChar( CREID_TYPE id, SPELL_TYPE iSpell, bool fPet )
{
// make a creature near by. (GM or script used only)
// "ADDNPC"
// spell = SPELL_Summon
ASSERT(m_pChar);
m_tmSkillMagery.m_Spell = iSpell; // m_atMagery.m_Spell
m_tmSkillMagery.m_SummonID = id; // m_atMagery.m_SummonID
m_tmSkillMagery.m_fSummonPet = fPet;
if ( ! m_Targ_PrvUID.IsValidUID())
{
m_Targ_PrvUID = m_pChar->GetUID(); // what id this was already a scroll.
}
const CSpellDef * pSpellDef = g_Cfg.GetSpellDef( iSpell );
ASSERT( pSpellDef );
return addTargetChars( CLIMODE_TARG_SKILL_MAGERY, id, pSpellDef->IsSpellType( SPELLFLAG_HARM ));
}
bool CClient::Cmd_Skill_Menu( RESOURCE_ID_BASE rid, int iSelect )
{
// Build the skill menu for the curent active skill.
// Only list the things we have skill and ingrediants to make.
//
// ARGS:
// m_Targ_UID = the object used to get us here.
// rid = which menu ?
// iSelect = -2 = Just a test of the whole menu.,
// iSelect = -1 = 1st setup.
// iSelect = 0 = cancel
// iSelect = x = execute the selection.
//
// RETURN: false = fail/cancel the skill.
// m_tmMenu.m_Item = the menu entries.
ASSERT(m_pChar);
if ( iSelect == 0 || rid.GetResType() != RES_SKILLMENU )
return( false );
int iDifficulty = 0;
// Find section.
CResourceLock s;
if ( ! g_Cfg.ResourceLock( s, rid ))
{
return false;
}
// Get title line
if ( ! s.ReadKey())
return( false );
CMenuItem item;
if ( iSelect < 0 )
{
item.m_sText = s.GetKey();
if ( iSelect == -1 )
{
m_tmMenu.m_ResourceID = rid;
}
}
bool fSkip = false; // skip this if we lack resources or skill.
bool fSuccess = false;
int iOnCount = 0;
int iShowCount = 0;
bool fShowMenu = false; // are we showing a menu?
while ( s.ReadKeyParse())
{
if ( s.IsKeyHead( "ON", 2 ))
{
// a new option to look at.
fSkip = false;
iOnCount ++;
if ( iSelect < 0 ) // building up the list.
{
if ( iSelect < -1 && iShowCount >= 1 ) // just a test. so we are done.
{
return( true );
}
iShowCount ++;
if ( ! item.ParseLine( s.GetArgRaw(), NULL, m_pChar ))
{
// remove if the item is invalid.
iShowCount --;
fSkip = true;
continue;
}
if ( iSelect == -1 )
{
m_tmMenu.m_Item = iOnCount;
}
if ( iShowCount >= COUNTOF( item )-1 )
break;
}
else
{
if ( iOnCount > iSelect ) // we are done.
break;
}
continue;
}
if ( fSkip ) // we have decided we cant do this option.
continue;
if ( iSelect > 0 && iOnCount != iSelect ) // only interested in the selected option
continue;
// Check for a skill / non-consumables required.
if ( s.IsKey("TEST"))
{
CResourceQtyArray skills( s.GetArgStr());
if ( ! skills.IsResourceMatchAll(m_pChar))
{
iShowCount--;
fSkip = true;
}
continue;
}
if ( s.IsKey("TESTIF"))
{
m_pChar->ParseText( s.GetArgRaw(), m_pChar );
if ( ! s.GetArgVal())
{
iShowCount--;
fSkip = true;
}
continue;
}
// select to execute any entries here ?
if ( iOnCount == iSelect )
{
m_pChar->m_Act_Targ = m_Targ_UID;
// Execute command from script
TRIGRET_TYPE tRet = m_pChar->OnTriggerRun( s, TRIGRUN_SINGLE_EXEC, m_pChar );
if ( tRet == TRIGRET_RET_TRUE )
{
return( false );
}
fSuccess = true; // we are good. but continue til the end
}
else
{
ASSERT( iSelect < 0 );
if ( s.IsKey("SKILLMENU"))
{
// Test if there is anything in this skillmenu we can do.
if ( ! Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, s.GetArgStr()), iSelect-1 ))
{
iShowCount--;
fSkip = true;
}
else
{
fShowMenu = true;
ASSERT( ! fSkip );
}
continue;
}
if ( s.IsKey("MAKEITEM"))
{
// test if i can make this item using m_Targ_UID.
// There should ALWAYS be a valid id here.
if ( ! m_pChar->Skill_MakeItem( (ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, s.GetArgS
tr()),
m_Targ_UID, SKTRIG_SELECT ))
{
iShowCount--;
fSkip = true;
}
continue;
}
}
}
if ( iSelect < -1 ) // just a test.
{
return( iShowCount ? true : false );
}
if ( iSelect > 0 ) // seems our resources disappeared.
{
if ( ! fSuccess )
{
SysMessage( "You can't make that." );
}
return( fSuccess );
}
if ( ! iShowCount )
{
SysMessage( "You can't make anything with what you have." );
return( false );
}
if ( iShowCount == 1 && fShowMenu )
{
// If there is just one menu then select it.
return( Cmd_Skill_Menu( rid, m_tmMenu.m_Item ));
}
addItemMenu( CLIMODE_MENU_SKILL, item, iShowCount );
return( true );
}
bool CClient::Cmd_Skill_Magery( SPELL_TYPE iSpell, CObjBase * pSrc )
{
// start casting a spell. prompt for target.
// pSrc = you the char.
// pSrc = magic object is source ?
static const TCHAR sm_Txt_Summon = "Where would you like to summon the creature ?";
// Do we have the regs ? etc.
ASSERT(m_pChar);
if ( ! m_pChar->Spell_CanCast( iSpell, true, pSrc, true ))
return false;
const CSpellDef * pSpellDef = g_Cfg.GetSpellDef( iSpell );
ASSERT(pSpellDef);
if ( g_Log.IsLogged( LOGL_TRACE ))
{
DEBUG_MSG(( "%x:Cast Spell %d='%s'\n", m_Socket.GetSocket(), iSpell, pSpellDef->GetName()));
}
SetTargMode();
m_tmSkillMagery.m_Spell = iSpell; // m_atMagery.m_Spell
m_Targ_UID = m_pChar->GetUID(); // default target.
m_Targ_PrvUID = pSrc->GetUID(); // source of the spell.
LPCTSTR pPrompt = "Select Target";
switch ( iSpell )
{
case SPELL_Recall:
pPrompt = "Select rune to recall from.";
break;
case SPELL_Blade_Spirit:
pPrompt = sm_Txt_Summon;
break;
case SPELL_Summon:
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_summon" ));
case SPELL_Mark:
pPrompt = "Select rune to mark.";
break;
case SPELL_Gate_Travel: // gate travel
pPrompt = "Select rune to gate from.";
break;
case SPELL_Polymorph:
// polymorph creature menu.
if ( IsPriv(PRIV_GM))
{
pPrompt = "Select creature to polymorph.";
break;
}
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_polymorph" ));
case SPELL_Earthquake:
// cast immediately with no targetting.
m_pChar->m_atMagery.m_Spell = SPELL_Earthquake;
m_pChar->m_Act_Targ = m_Targ_UID;
m_pChar->m_Act_TargPrv = m_Targ_PrvUID;
m_pChar->m_Act_p = m_pChar->GetTopPoint();
return( m_pChar->Skill_Start( SKILL_MAGERY ));
case SPELL_Resurrection:
pPrompt = "Select ghost to resurrect.";
break;
case SPELL_Vortex:
case SPELL_Air_Elem:
case SPELL_Daemon:
case SPELL_Earth_Elem:
case SPELL_Fire_Elem:
case SPELL_Water_Elem:
pPrompt = sm_Txt_Summon;
break;
// Necro spells
case SPELL_Summon_Undead: // Summon an undead
pPrompt = sm_Txt_Summon;
break;
case SPELL_Animate_Dead: // Corpse to zombie
pPrompt = "Choose a corpse";
break;
case SPELL_Bone_Armor: // Skeleton corpse to bone armor
pPrompt = "Chose a skeleton";
break;
}
addTarget( CLIMODE_TARG_SKILL_MAGERY, pPrompt,
! pSpellDef->IsSpellType( SPELLFLAG_TARG_OBJ | SPELLFLAG_TARG_CHAR ),
pSpellDef->IsSpellType( SPELLFLAG_HARM ));
return( true );
}
bool CClient::Cmd_Skill_Tracking( int track_sel, bool fExec )
{
// look around for stuff.
ASSERT(m_pChar);
if ( track_sel < 0 )
{
// Initial pre-track setup.
if ( m_pChar->m_pArea->IsFlag( REGION_FLAG_SHIP ) &&
! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_SPY_GLASS)) )
{
SysMessage( "You need a Spyglass to use tracking here." );
return( false );
}
// Tacking (unlike other skills) is used during menu setup.
m_pChar->Skill_Fail( true ); // Kill previous skill.
CMenuItem item;
item.m_sText = "Tracking";
item.m_id = ITEMID_TRACK_HORSE;
item.m_sText = "Animals";
item.m_id = ITEMID_TRACK_OGRE;
item.m_sText = "Monsters";
item.m_id = ITEMID_TRACK_MAN;
item.m_sText = "Humans";
item.m_id = ITEMID_TRACK_MAN_NAKED;
item.m_sText = "Players";
item.m_id = ITEMID_TRACK_WISP;
item.m_sText = "Anything that moves";
m_tmMenu.m_Item = 0;
addItemMenu( CLIMODE_MENU_SKILL_TRACK_SETUP, item, 5 );
return( true );
}
if ( track_sel ) // Not Cancelled
{
ASSERT( ((WORD)track_sel) < COUNTOF( m_tmMenu.m_Item ));
if ( fExec )
{
// Tracking menu got us here. Start tracking the selected creature.
m_pChar->SetTimeout( 1*TICK_PER_SEC );
m_pChar->m_Act_Targ = m_tmMenu.m_Item; // selected UID
m_pChar->Skill_Start( SKILL_TRACKING );
return true;
}
bool fGM = IsPriv(PRIV_GM);
static const NPCBRAIN_TYPE sm_Track_Brain =
{
NPCBRAIN_QTY, // not used here.
NPCBRAIN_ANIMAL,
NPCBRAIN_MONSTER,
NPCBRAIN_HUMAN,
NPCBRAIN_NONE, // players
NPCBRAIN_QTY, // anything.
};
if ( track_sel >= COUNTOF(sm_Track_Brain))
track_sel = COUNTOF(sm_Track_Brain)-1;
NPCBRAIN_TYPE track_type = sm_Track_Brain;
CMenuItem item;
int count = 0;
item.m_sText = "Tracking";
m_tmMenu.m_Item = track_sel;
CWorldSearch AreaChars( m_pChar->GetTopPoint(), m_pChar->Skill_GetBase(SKILL_TRACKING)/20 + 10 );
while (true)
{
CChar * pChar = AreaChars.GetChar();
if ( pChar == NULL )
break;
if ( m_pChar == pChar )
continue;
if ( ! m_pChar->CanDisturb( pChar ))
continue;
CCharBase * pCharDef = pChar->Char_GetDef();
NPCBRAIN_TYPE basic_type = pChar->GetCreatureType();
if ( track_type != basic_type && track_type != NPCBRAIN_QTY )
{
if ( track_type != NPCBRAIN_NONE ) // no match.
{
continue;
}
// players
if ( ! pChar->m_pPlayer )
continue;
if ( ! fGM && basic_type != NPCBRAIN_HUMAN ) // can't track polymorphed person.
continue;
}
if ( ! fGM && ! pCharDef->Can( CAN_C_WALK )) // never moves or just swims.
continue;
count ++;
item.m_id = pCharDef->m_trackID;
item.m_sText = pChar->GetName();
m_tmMenu.m_Item = pChar->GetUID();
if ( count >= COUNTOF( item )-1 )
break;
}
if ( count )
{
// Some credit for trying.
m_pChar->Skill_UseQuick( SKILL_TRACKING, 20 + Calc_GetRandVal( 30 ));
addItemMenu( CLIMODE_MENU_SKILL_TRACK, item, count );
return( true );
}
else
{
// Some credit for trying.
m_pChar->Skill_UseQuick( SKILL_TRACKING, 10 + Calc_GetRandVal( 30 ));
}
}
// Tracking failed or was cancelled .
static LPCTSTR const sm_Track_FailMsg =
{
"Tracking Cancelled",
"You see no signs of animals to track.",
"You see no signs of monsters to track.",
"You see no signs of humans to track.",
"You see no signs of players to track.",
"You see no signs to track."
};
SysMessage( sm_Track_FailMsg );
return( false );
}
bool CClient::Cmd_Skill_Smith( CItem * pIngots )
{
ASSERT(m_pChar);
if ( pIngots == NULL || ! pIngots->IsType(IT_INGOT))
{
SysMessage( "You need ingots for smithing." );
return( false );
}
ASSERT( m_Targ_UID == pIngots->GetUID());
if ( pIngots->GetTopLevelObj() != m_pChar )
{
SysMessage( "The ingots must be on your person" );
return( false );
}
// must have hammer equipped.
CItem * pHammer = m_pChar->LayerFind( LAYER_HAND1 );
if ( pHammer == NULL || ! pHammer->IsType(IT_WEAPON_MACE_SMITH))
{
SysMessage( "You must weild a smith hammer of some sort." );
return( false );
}
// Select the blacksmith item type.
// repair items or make type of items.
if ( ! g_World.IsItemTypeNear( m_pChar->GetTopPoint(), IT_FORGE, 3 ))
{
SysMessage( "You must be near a forge to smith ingots" );
return( false );
}
// Select the blacksmith item type.
// repair items or make type of items.
return( Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU,"sm_blacksmith" )));
}
bool CClient::Cmd_Skill_Inscription()
{
// Select the scroll type to make.
// iSelect = -1 = 1st setup.
// iSelect = 0 = cancel
// iSelect = x = execute the selection.
// we should already be in inscription skill mode.
ASSERT(m_pChar);
CItem * pBlank = m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_SCROLL_BLANK));
if ( pBlank == NULL )
{
SysMessage( "You have no blank scrolls" );
return( false );
}
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_inscription" ) );
}
bool CClient::Cmd_Skill_Alchemy( CItem * pReag )
{
// SKILL_ALCHEMY
if ( pReag == NULL )
return( false );
ASSERT(m_pChar);
if ( ! m_pChar->CanUse( pReag, true ))
return( false );
if ( ! pReag->IsType(IT_REAGENT))
{
// That is not a reagent.
SysMessage( "That is not a reagent." );
return( false );
}
// Find bottles to put potions in.
if ( ! m_pChar->ContentFind(RESOURCE_ID(RES_TYPEDEF,IT_POTION_EMPTY)))
{
SysMessage( "You have no bottles for your potion." );
return( false );
}
m_Targ_UID = pReag->GetUID();
// Put up a menu to decide formula ?
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_alchemy" ));
}
bool CClient::Cmd_Skill_Cartography( int iLevel )
{
// select the map type.
ASSERT(m_pChar);
if ( m_pChar->Skill_Wait(SKILL_CARTOGRAPHY))
return( false );
if ( ! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_MAP_BLANK)))
{
SysMessage( "You have no blank parchment to draw on" );
return( false );
}
return( Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_cartography" )));
}
bool CClient::Cmd_SecureTrade( CChar * pChar, CItem * pItem )
{
// Begin secure trading with a char. (Make the initial offer)
ASSERT(m_pChar);
// Trade window only if another PC.
if ( ! pChar->IsClient())
{
return( pChar->NPC_OnItemGive( m_pChar, pItem ));
}
// Is there already a trade window open for this client ?
CItem * pItemCont = m_pChar->GetContentHead();
for ( ; pItemCont != NULL; pItemCont = pItemCont->GetNext())
{
if ( ! pItemCont->IsType(IT_EQ_TRADE_WINDOW))
continue; // found it
CItem * pItemPartner = pItemCont->m_uidLink.ItemFind(); // counterpart trade window.
if ( pItemPartner == NULL )
continue;
CChar * pCharPartner = dynamic_cast <CChar*>( pItemPartner->GetParent());
if ( pCharPartner != pChar )
continue;
CItemContainer * pCont = dynamic_cast <CItemContainer *>( pItemCont );
ASSERT(pCont);
pCont->ContentAdd( pItem );
return( true );
}
// Open a new one.
CItemContainer* pCont1 = dynamic_cast <CItemContainer*> (CItem::CreateBase( ITEMID_Bulletin1 ));
ASSERT(pCont1);
pCont1->SetType( IT_EQ_TRADE_WINDOW );
CItemContainer* pCont2 = dynamic_cast <CItemContainer*> (CItem::CreateBase( ITEMID_Bulletin1 ));
ASSERT(pCont2);
pCont2->SetType( IT_EQ_TRADE_WINDOW );
pCont1->m_itEqTradeWindow.m_fCheck = false;
pCont1->m_uidLink = pCont2->GetUID();
pCont2->m_itEqTradeWindow.m_fCheck = false;
pCont2->m_uidLink = pCont1->GetUID();
m_pChar->LayerAdd( pCont1, LAYER_SPECIAL );
pChar->LayerAdd( pCont2, LAYER_SPECIAL );
CCommand cmd;
int len = sizeof(cmd.SecureTrade);
cmd.SecureTrade.m_Cmd = XCMD_SecureTrade;
cmd.SecureTrade.m_len = len;
cmd.SecureTrade.m_action = SECURE_TRADE_OPEN; // init
cmd.SecureTrade.m_UID = pChar->GetUID();
cmd.SecureTrade.m_UID1 = pCont1->GetUID();
cmd.SecureTrade.m_UID2 = pCont2->GetUID();
cmd.SecureTrade.m_fname = 1;
strcpy( cmd.SecureTrade.m_charname, pChar->GetName());
xSendPkt( &cmd, len );
cmd.SecureTrade.m_UID = m_pChar->GetUID();
cmd.SecureTrade.m_UID1 = pCont2->GetUID();
cmd.SecureTrade.m_UID2 = pCont1->GetUID();
strcpy( cmd.SecureTrade.m_charname, m_pChar->GetName());
pChar->GetClient()->xSendPkt( &cmd, len );
CPointMap pt( 30, 30, 9 );
pCont1->ContentAdd( pItem, pt );
return( true );
} | 37.997387 | 128 | 0.448683 | Jhobean |
3e501e3c663f32cc489b740f08f77dc1f38e4164 | 131 | cpp | C++ | 2DGame/logger.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | 3 | 2015-08-18T12:59:29.000Z | 2015-12-15T08:11:10.000Z | 2DGame/logger.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | null | null | null | 2DGame/logger.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | null | null | null | #include "logger.h"
//Mutex for cout
//Prevent interleaving of output
pthread_mutex_t coutMutex = PTHREAD_MUTEX_INITIALIZER;
| 21.833333 | 55 | 0.778626 | Cimera42 |
3e55deb2f76b90a3e2244497e79be0b1d0a04be3 | 2,269 | cpp | C++ | src/framework/shared/irphandlers/pnp/um/fxpkgpdoum.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 994 | 2015-03-18T21:37:07.000Z | 2019-04-26T04:04:14.000Z | src/framework/shared/irphandlers/pnp/um/fxpkgpdoum.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 13 | 2019-06-13T15:58:03.000Z | 2022-02-18T22:53:35.000Z | src/framework/shared/irphandlers/pnp/um/fxpkgpdoum.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 350 | 2015-03-19T04:29:46.000Z | 2019-05-05T23:26:50.000Z | /*++
Copyright (c) Microsoft Corporation
Module Name:
FxPkgPdoUM.cpp
Abstract:
This module implements the Pnp package for Pdo devices.
Author:
Environment:
User mode only
Revision History:
--*/
#include "pnppriv.hpp"
#include <wdmguid.h>
// Tracing support
#if defined(EVENT_TRACING)
extern "C" {
#include "FxPkgPdoUM.tmh"
}
#endif
_Must_inspect_result_
NTSTATUS
FxPkgPdo::_PnpQueryResources(
__inout FxPkgPnp* This,
__inout FxIrp *Irp
)
{
return ((FxPkgPdo*) This)->PnpQueryResources(Irp);
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::PnpQueryResources(
__inout FxIrp *Irp
)
/*++
Routine Description:
This method is invoked in response to a Pnp QueryResources IRP. We return
the resources that the device is currently consuming.
Arguments:
Irp - a pointer to the FxIrp
Returns:
NTSTATUS
--*/
{
UNREFERENCED_PARAMETER(Irp);
ASSERTMSG("Not implemented for UMDF\n", FALSE);
return STATUS_NOT_IMPLEMENTED;
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::_PnpQueryResourceRequirements(
__inout FxPkgPnp* This,
__inout FxIrp *Irp
)
{
return ((FxPkgPdo*) This)->PnpQueryResourceRequirements(Irp);
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::PnpQueryResourceRequirements(
__inout FxIrp *Irp
)
/*++
Routine Description:
This method is invoked in response to a Pnp QueryResourceRequirements IRP.
We return the set (of sets) of possible resources that we could accept
which would allow our device to work.
Arguments:
Irp - a pointer to the FxIrp
Returns:
NTSTATUS
--*/
{
UNREFERENCED_PARAMETER(Irp);
ASSERTMSG("Not implemented for UMDF\n", FALSE);
return STATUS_NOT_IMPLEMENTED;
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::_PnpFilterResourceRequirements(
__inout FxPkgPnp* This,
__inout FxIrp *Irp
)
/*++
Routine Description:
Filter resource requirements for the PDO. A chance to further muck with
the resources assigned to the device.
Arguments:
This - the package
Irp - the request
Return Value:
NTSTATUS
--*/
{
UNREFERENCED_PARAMETER(This);
UNREFERENCED_PARAMETER(Irp);
ASSERTMSG("Not implemented for UMDF\n", FALSE);
return STATUS_NOT_IMPLEMENTED;
}
| 15.648276 | 78 | 0.710886 | IT-Enthusiast-Nepal |
3e60f0c93c5f3058bd47f74a589677c04595a867 | 185 | cpp | C++ | client/test/test.cpp | gary920209/LightDance-RPi | 41d3ef536f3874fd5dbe092f5c9be42f7204427d | [
"MIT"
] | 2 | 2020-11-14T17:13:55.000Z | 2020-11-14T17:42:39.000Z | client/test/test.cpp | gary920209/LightDance-RPi | 41d3ef536f3874fd5dbe092f5c9be42f7204427d | [
"MIT"
] | null | null | null | client/test/test.cpp | gary920209/LightDance-RPi | 41d3ef536f3874fd5dbe092f5c9be42f7204427d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
string s;
cout << "Other Successfully initiated." << endl;
while (cin >> s)
cout << "Success " << s << endl;
} | 20.555556 | 52 | 0.567568 | gary920209 |
3e617d24eb2fce1d74a7555c8417b1541b47b226 | 2,489 | cpp | C++ | Chapter 5/5.34.cpp | root113/C-How-To-Program-Deitel | fe1ced3fb1efd88f00264cb03c873474e62ed450 | [
"Unlicense"
] | 4 | 2019-02-22T09:38:01.000Z | 2020-02-02T19:13:30.000Z | Chapter 5/5.34.cpp | root113/C-How-To-Program-Deitel | fe1ced3fb1efd88f00264cb03c873474e62ed450 | [
"Unlicense"
] | null | null | null | Chapter 5/5.34.cpp | root113/C-How-To-Program-Deitel | fe1ced3fb1efd88f00264cb03c873474e62ed450 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int getRandomNum( void );
void correctAnswer();
void wrongAnswer();
int answerTheQuestion( int, int );
void askQuestions( int );
int main()
{
srand( (time(NULL)) );
askQuestions(10);
return 0;
}
int getRandomNum()
{
int res = 1 + rand()%12;
return res;
}
void correctAnswer()
{
int response = getRandomNum();
switch(response) {
case 1: case 2: case 3:
printf("Very good!\n");
break;
case 4: case 5: case 6:
printf("Excellent!\n");
break;
case 7: case 8: case 9:
printf("Nice Work!\n");
break;
case 10: case 11: case 12:
printf("Keep up the good work!\n");
break;
default:
printf("Congrats!\n");
}
}
void wrongAnswer()
{
int response = getRandomNum();
switch(response) {
case 1: case 2: case 3:
printf("No. Please try again!\n");
break;
case 4: case 5: case 6:
printf("Wrong. Try once more!\n");
break;
case 7: case 8: case 9:
printf("Don't give up!\n");
break;
case 10: case 11: case 12:
printf("No. Keep trying!\n");
break;
default:
printf("So wrong, dude!\n");
}
}
int answerTheQuestion(int a, int b)
{
int guess;
int wrongGuesses = 0;
int correct=0;
int result = a*b;
do {
printf("What is %d x %d? ",a, b);
scanf("%d", &guess);
if(guess==result) {
correct = 1;
correctAnswer();
} else {
wrongAnswer();
wrongGuesses++;
}
} while(!correct);
return wrongGuesses;
}
void askQuestions(int n)
{
int i, a, b;
int wrong=0;
for(i=0; i<n; i++) {
a = getRandomNum();
b = getRandomNum();
wrong += answerTheQuestion(a, b);
}
float percentage = (10.0/(10.0 + wrong)) * 100.0;
if(percentage < 75.0) {
printf("\nOnly %.2f%% of your guesses were correct\n", percentage);
printf("Please ask your instructor for extra help\n");
}
else {
printf("\nCongratulations %.2f%% of your guesses were correct\n", percentage);
}
}
| 21.09322 | 87 | 0.470068 | root113 |
3e62b622fa9c7c742cb7339b55e218a652eac506 | 1,920 | cpp | C++ | fdbclient/AutoPublicAddress.cpp | TheBenCollins/foundationdb | e6950abae6914dab989ec00a4b4b648bb9d8af52 | [
"Apache-2.0"
] | null | null | null | fdbclient/AutoPublicAddress.cpp | TheBenCollins/foundationdb | e6950abae6914dab989ec00a4b4b648bb9d8af52 | [
"Apache-2.0"
] | null | null | null | fdbclient/AutoPublicAddress.cpp | TheBenCollins/foundationdb | e6950abae6914dab989ec00a4b4b648bb9d8af52 | [
"Apache-2.0"
] | null | null | null | /*
* AutoPublicAddress.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flow/Platform.h"
#include <algorithm>
#define BOOST_SYSTEM_NO_LIB
#define BOOST_DATE_TIME_NO_LIB
#define BOOST_REGEX_NO_LIB
#include "boost/asio.hpp"
#include "fdbclient/CoordinationInterface.h"
// Determine public IP address by calling the first coordinator.
IPAddress determinePublicIPAutomatically(ClusterConnectionString& ccs) {
try {
using namespace boost::asio;
io_service ioService;
ip::udp::socket socket(ioService);
ccs.resolveHostnamesBlocking();
const auto& coordAddr = ccs.coordinators()[0];
const auto boostIp = coordAddr.ip.isV6() ? ip::address(ip::address_v6(coordAddr.ip.toV6()))
: ip::address(ip::address_v4(coordAddr.ip.toV4()));
ip::udp::endpoint endpoint(boostIp, coordAddr.port);
socket.connect(endpoint);
IPAddress ip = coordAddr.ip.isV6() ? IPAddress(socket.local_endpoint().address().to_v6().to_bytes())
: IPAddress(socket.local_endpoint().address().to_v4().to_ulong());
socket.close();
return ip;
} catch (boost::system::system_error e) {
fprintf(stderr, "Error determining public address: %s\n", e.what());
throw bind_failed();
}
}
| 34.285714 | 103 | 0.7125 | TheBenCollins |
3e63a2481b8e9a04f9ed9679745bdf6c04cb6fb0 | 2,853 | hpp | C++ | library/src/blas1/rocblas_copy.hpp | zjunweihit/rocBLAS | c8bda2d15a7772d810810492ebed616eec0959a5 | [
"MIT"
] | null | null | null | library/src/blas1/rocblas_copy.hpp | zjunweihit/rocBLAS | c8bda2d15a7772d810810492ebed616eec0959a5 | [
"MIT"
] | 1 | 2019-09-26T01:51:09.000Z | 2019-09-26T18:09:56.000Z | library/src/blas1/rocblas_copy.hpp | mahmoodw/rocBLAS | 53b1271e4881ef7473b78e8783e4d55740e9b933 | [
"MIT"
] | null | null | null | /* ************************************************************************
* Copyright 2016-2019 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "handle.h"
#include "logging.h"
#include "rocblas.h"
#include "utility.h"
template <typename T, typename U, typename V>
__global__ void copy_kernel(rocblas_int n,
const U xa,
ptrdiff_t shiftx,
rocblas_int incx,
rocblas_stride stridex,
V ya,
ptrdiff_t shifty,
rocblas_int incy,
rocblas_stride stridey)
{
ptrdiff_t tid = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
// bound
if(tid < n)
{
const T* x = load_ptr_batch(xa, hipBlockIdx_y, shiftx, stridex);
T* y = load_ptr_batch(ya, hipBlockIdx_y, shifty, stridey);
y[tid * incy] = x[tid * incx];
}
}
template <rocblas_int NB, typename T, typename U, typename V>
rocblas_status rocblas_copy_template(rocblas_handle handle,
rocblas_int n,
U x,
rocblas_int offsetx,
rocblas_int incx,
rocblas_stride stridex,
V y,
rocblas_int offsety,
rocblas_int incy,
rocblas_stride stridey,
rocblas_int batch_count)
{
// Quick return if possible.
if(n <= 0 || !batch_count)
return rocblas_status_success;
if(!x || !y)
return rocblas_status_invalid_pointer;
if(batch_count < 0)
return rocblas_status_invalid_size;
// in case of negative inc shift pointer to end of data for negative indexing tid*inc
ptrdiff_t shiftx = offsetx - ((incx < 0) ? ptrdiff_t(incx) * (n - 1) : 0);
ptrdiff_t shifty = offsety - ((incy < 0) ? ptrdiff_t(incy) * (n - 1) : 0);
int blocks = (n - 1) / NB + 1;
dim3 grid(blocks, batch_count);
dim3 threads(NB);
hipLaunchKernelGGL((copy_kernel<T>),
grid,
threads,
0,
handle->rocblas_stream,
n,
x,
shiftx,
incx,
stridex,
y,
shifty,
incy,
stridey);
return rocblas_status_success;
}
| 36.113924 | 89 | 0.416404 | zjunweihit |
3e63b5c5a2d70d42a9c0b6ff8e1e73da50f7dc83 | 4,523 | cpp | C++ | code/libImmCore/src/libCompression/basic/piBitInterlacer.cpp | andybak/IMM | c725dcb28a1638dea726381a7189c3b031967d58 | [
"Apache-2.0",
"MIT"
] | 33 | 2021-09-16T18:37:08.000Z | 2022-03-22T23:02:44.000Z | code/libImmCore/src/libCompression/basic/piBitInterlacer.cpp | andybak/IMM | c725dcb28a1638dea726381a7189c3b031967d58 | [
"Apache-2.0",
"MIT"
] | 5 | 2021-09-17T10:10:07.000Z | 2022-03-28T12:33:29.000Z | code/libImmCore/src/libCompression/basic/piBitInterlacer.cpp | andybak/IMM | c725dcb28a1638dea726381a7189c3b031967d58 | [
"Apache-2.0",
"MIT"
] | 5 | 2021-09-19T07:49:01.000Z | 2021-12-12T21:25:35.000Z | //
// Branched off piLibs (Copyright © 2015 Inigo Quilez, The MIT License), in 2015. See THIRD_PARTY_LICENSES.txt
//
#include <malloc.h>
#include "../../libBasics/piTypes.h"
#include "piBitInterlacer.h"
namespace ImmCore
{
namespace piBitInterlacer
{
BitStream::BitStream()
{
mBits = 0;
mState = 0;
}
bool BitStream::output(int bit, uint8_t *res)
{
mState |= (bit << mBits);
mBits++;
if (mBits == 8)
{
*res = mState;
mBits = 0;
mState = 0;
return true;
}
return false;
}
bool BitStream::flush(uint8_t *val)
{
if (mBits != 0)
{
*val = mState;
return true;
}
return false;
}
uint64_t interlace8(uint8_t *dst, const uint8_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits)
{
if (numPoints == 0) return 0;
// interlace all bits, sort bits from lower to higher bits across channels
uint64_t num = 0;
BitStream bit;
for (int b = 0; b < numBits; b++)
for (int j = 0; j < numChannels; j++)
for (int i = 0; i < numPoints; i++)
{
uint8_t res;
if (bit.output((data[numChannels*i + j] >> b) & 1, &res))
dst[num++] = res;
}
uint8_t res; if (bit.flush(&res)) dst[num++] = res;
// remove trailing zeroes
uint64_t len = 0;
for (int64_t i = num - 1; i >= 0; i--)
{
if (dst[i] != 0)
{
len = i + 1;
break;
}
}
return len;
}
uint64_t interlace16(uint8_t *dst, const uint16_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits)
{
if (numPoints == 0) return 0;
// interlace all bits, sort bits from lower to higher bits across channels
uint64_t num = 0;
BitStream bit;
for (int b = 0; b < numBits; b++)
for (int j = 0; j < numChannels; j++)
for (int i = 0; i < numPoints; i++)
{
uint8_t res;
if (bit.output((data[numChannels*i + j] >> b) & 1, &res))
dst[num++] = res;
}
uint8_t res; if (bit.flush(&res)) dst[num++] = res;
// remove trailing zeroes
uint64_t len = 0;
for (int64_t i = num - 1; i >= 0; i--)
{
if (dst[i] != 0)
{
len = i + 1;
break;
}
}
return len;
}
uint64_t interlace32(uint8_t *dst, const uint32_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits)
{
if (numPoints == 0) return 0;
// interlace all bits, sort bits from lower to higher bits across channels
uint64_t num = 0;
BitStream bit;
for (int b = 0; b < numBits; b++)
for (int j = 0; j < numChannels; j++)
for (int i = 0; i < numPoints; i++)
{
uint8_t res;
if (bit.output((data[numChannels*i + j] >> b) & 1, &res))
dst[num++] = res;
}
uint8_t res; if (bit.flush(&res)) dst[num++] = res;
// remove trailing zeroes
uint64_t len = 0;
for (int64_t i = num - 1; i >= 0; i--)
{
if (dst[i] != 0)
{
len = i + 1;
break;
}
}
return len;
}
void deinterlace8(const uint8_t *src, uint8_t *data, uint64_t numBytes, uint64_t numPoints, unsigned int numChannels, unsigned int numBits)
{
for (uint64_t i = 0, num = numPoints*numChannels; i < num; i++)
{
data[i] = 0;
}
unsigned int bit = 0;
unsigned int channel = 0;
uint64_t point = 0;
for (uint64_t i = 0; i < numBytes; i++)
{
const uint8_t byte = src[i];
for (int j = 0; j < 8; j++)
{
const int b = (byte >> j) & 1;
data[numChannels*point + channel] |= (b << bit);
point++;
if (point >= numPoints)
{
point = 0;
channel++;
if (channel >= numChannels)
{
channel = 0;
bit++;
if (bit >= numBits)
{
bit = 0;
return;
}
}
}
}
}
}
void deinterlace16(const uint8_t *src, uint16_t *data, uint64_t numBytes, uint64_t numPoints, unsigned int numChannels, unsigned int numBits)
{
for (uint64_t i = 0, num = numPoints*numChannels; i < num; i++)
{
data[i] = 0;
}
unsigned int bit = 0;
unsigned int channel = 0;
uint64_t point = 0;
for (uint64_t i = 0; i < numBytes; i++)
{
const uint8_t byte = src[i];
for (int j = 0; j < 8; j++)
{
const unsigned int b = (byte >> j) & 1;
data[numChannels*point + channel] |= (b << bit);
point++;
if (point >= numPoints)
{
point = 0;
channel++;
if (channel >= numChannels)
{
channel = 0;
bit++;
if (bit >= numBits)
{
bit = 0;
return;
}
}
}
}
}
}
}
}
| 20.282511 | 143 | 0.539244 | andybak |
3e6826654152115df8c0fc784ee1a1f39c51edf1 | 1,462 | hpp | C++ | streambox/Nexmark/NexmarkFilterEvaluator.hpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 3 | 2019-07-03T14:03:31.000Z | 2021-12-19T10:18:49.000Z | streambox/Nexmark/NexmarkFilterEvaluator.hpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | null | null | null | streambox/Nexmark/NexmarkFilterEvaluator.hpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | null | null | null | #ifndef NEXMARK_FILTER_EVALUATOR_HPP
#define NEXMARK_FILTER_EVALUATOR_HPP
#include "core/SingleInputTransformEvaluator.h"
#include "Nexmark/NexmarkFilter.hpp"
/* convert a stream of records to a stream of <NexmarkRecord> records */
template <typename InputT,
typename OutputT,
template<class> class BundleT_>
class NexmarkFilterEvaluator
: public SingleInputTransformEvaluator<NexmarkFilter<InputT, OutputT>,
BundleT_<InputT>, BundleT_<OutputT>
> {
using TransformT = NexmarkFilter<InputT, OutputT>;
using InputBundleT = BundleT_<InputT>;
using OutputBundleT = BundleT_<OutputT>;
public:
bool evaluateSingleInput (TransformT* trans,
shared_ptr<InputBundleT> input_bundle,
shared_ptr<OutputBundleT> output_bundle) override {
for (auto && it = input_bundle->begin(); it != input_bundle->end(); ++it) {
if(trans->do_map(*it)) {
output_bundle->add_record(*it);
}
}
trans->record_counter_.fetch_add(input_bundle->size(), std::memory_order_relaxed);
return true;
// return false;
}
NexmarkFilterEvaluator(int node)
: SingleInputTransformEvaluator<TransformT,
InputBundleT, OutputBundleT>(node) {}
};
#endif //NEXMARK_FILTER_EVALUATOR_HPP
| 34.809524 | 90 | 0.618331 | chenzongxiong |
3e6894e42d658ddbbde6d9446022b905eadec8c9 | 645 | hpp | C++ | Layer.hpp | kaitokidi/JacobsHack | 6662dc32a91a964f6080470627398bfa0f36573e | [
"MIT"
] | 4 | 2015-10-21T06:49:16.000Z | 2016-08-17T07:59:07.000Z | Layer.hpp | kaitokidi/JacobsHack | 6662dc32a91a964f6080470627398bfa0f36573e | [
"MIT"
] | null | null | null | Layer.hpp | kaitokidi/JacobsHack | 6662dc32a91a964f6080470627398bfa0f36573e | [
"MIT"
] | null | null | null | #ifndef LAYER_HPP
#define LAYER_HPP
#include "utils.hpp"
class Layer
{
public:
Layer();
Layer(float speed);
void setSpeed(float speed);
float getSpeed();
void setFactor(float factor);
float getFactor();
void setTexture(std::vector<sf::Texture>& textures, int qtty);/*, sf::Texture& texture2);*/
void draw(sf::RenderTarget* renderTarget, sf::Transform* t);
void update(float deltatime);
private:
float _speed, _factor;
std::vector<sf::Sprite> _sprites;
// sf::Sprite _sprite1;
// sf::Sprite _sprite2;
};
#endif // LAYER_HPP
| 18.428571 | 99 | 0.595349 | kaitokidi |
3e6a80fe95718bf7f96b04325fdda25e6f9b9508 | 4,083 | cp | C++ | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Alerts_Panels/CPrefsAlertsAttachment.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Alerts_Panels/CPrefsAlertsAttachment.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Alerts_Panels/CPrefsAlertsAttachment.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Source for CPrefsAlertsAttachment class
#include "CPrefsAlertsAttachment.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CSoundPopup.h"
#include "CTextFieldX.h"
#include <LCheckBox.h>
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CPrefsAlertsAttachment::CPrefsAlertsAttachment()
{
}
// Constructor from stream
CPrefsAlertsAttachment::CPrefsAlertsAttachment(LStream *inStream)
: CPrefsTabSubPanel(inStream)
{
}
// Default destructor
CPrefsAlertsAttachment::~CPrefsAlertsAttachment()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CPrefsAlertsAttachment::FinishCreateSelf(void)
{
// Do inherited
CPrefsTabSubPanel::FinishCreateSelf();
mAttachmentAlert = (LCheckBox*) FindPaneByID(paneid_AttachmentAlert);
mAttachmentPlaySound = (LCheckBox*) FindPaneByID(paneid_AttachmentPlaySound);
mAttachmentSound = (CSoundPopup*) FindPaneByID(paneid_AttachmentSound);
mAttachmentSpeak = (LCheckBox*) FindPaneByID(paneid_AttachmentSpeak);
mAttachmentSpeakText = (CTextFieldX*) FindPaneByID(paneid_AttachmentSpeakText);
// Link controls to this window
UReanimator::LinkListenerToBroadcasters(this, this, RidL_CPrefsAlertsAttachmentBtns);
}
// Handle buttons
void CPrefsAlertsAttachment::ListenToMessage(
MessageT inMessage,
void *ioParam)
{
switch (inMessage)
{
case msg_AttachmentPlaySound:
if (*((long*) ioParam))
{
mAttachmentSound->Enable();
cdstring title;
mAttachmentSound->GetName(title);
::PlayNamedSound(title);
}
else
mAttachmentSound->Disable();
break;
case msg_AttachmentSound:
{
cdstring title;
mAttachmentSound->GetName(title);
::PlayNamedSound(title);
}
break;
case msg_AttachmentSpeak:
if (*((long*) ioParam))
mAttachmentSpeakText->Enable();
else
mAttachmentSpeakText->Disable();
break;
}
}
// Set prefs
void CPrefsAlertsAttachment::SetData(void* data)
{
CPreferences* copyPrefs = (CPreferences*) data;
StopListening();
const CNotification& attachment_notify = copyPrefs->mAttachmentNotification.GetValue();
mAttachmentAlert->SetValue(attachment_notify.DoShowAlert() ? 1 : 0);
mAttachmentPlaySound->SetValue(attachment_notify.DoPlaySound());
mAttachmentSound->SetName(attachment_notify.GetSoundID());
if (!attachment_notify.DoPlaySound())
mAttachmentSound->Disable();
mAttachmentSpeak->SetValue(attachment_notify.DoSpeakText() ? 1 : 0);
mAttachmentSpeakText->SetText(attachment_notify.GetTextToSpeak());
if (!attachment_notify.DoSpeakText())
mAttachmentSpeakText->Disable();
StartListening();
}
// Force update of prefs
void CPrefsAlertsAttachment::UpdateData(void* data)
{
CPreferences* copyPrefs = (CPreferences*) data;
// Make copy to look for changes
CNotification& attachment_notify = copyPrefs->mAttachmentNotification.Value();
CNotification attach_copy(attachment_notify);
attachment_notify.SetShowAlert(mAttachmentAlert->GetValue()==1);
attachment_notify.SetPlaySound(mAttachmentPlaySound->GetValue());
cdstring snd;
mAttachmentSound->GetName(snd);
attachment_notify.SetSoundID(snd);
attachment_notify.SetSpeakText(mAttachmentSpeak->GetValue());
attachment_notify.SetTextToSpeak(mAttachmentSpeakText->GetText());
// Set dirty if required
if (!(attach_copy == attachment_notify))
copyPrefs->mAttachmentNotification.SetDirty();
}
| 28.354167 | 104 | 0.76096 | mulberry-mail |
3e6df5d5553799540f4fb1fc9a85b8eac66e4035 | 53 | hpp | C++ | src/boost_mpl_aux__preprocessed_plain_and.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_aux__preprocessed_plain_and.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_aux__preprocessed_plain_and.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/aux_/preprocessed/plain/and.hpp>
| 26.5 | 52 | 0.792453 | miathedev |
3e710f3056c9ebcdae67b44afdbe1a11d0522df3 | 1,144 | cpp | C++ | src/topfd/dp/dp.cpp | toppic-suite/toppic-suite | b5f0851f437dde053ddc646f45f9f592c16503ec | [
"Apache-2.0"
] | 8 | 2018-05-23T14:37:31.000Z | 2022-02-04T23:48:38.000Z | src/topfd/dp/dp.cpp | toppic-suite/toppic-suite | b5f0851f437dde053ddc646f45f9f592c16503ec | [
"Apache-2.0"
] | 9 | 2019-08-31T08:17:45.000Z | 2022-02-11T20:58:06.000Z | src/topfd/dp/dp.cpp | toppic-suite/toppic-suite | b5f0851f437dde053ddc646f45f9f592c16503ec | [
"Apache-2.0"
] | 4 | 2018-04-25T01:39:38.000Z | 2020-05-20T19:25:07.000Z | //Copyright (c) 2014 - 2020, The Trustees of Indiana University.
//
//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 "topfd/dp/dp.hpp"
namespace toppic {
Dp::Dp (DeconvDataPtr data_ptr, MatchEnvPtr2D &win_envs,
DpParaPtr dp_para_ptr, double score_error_tolerance):
data_ptr_(data_ptr),
dp_para_ptr_(dp_para_ptr),
score_error_tolerance_(score_error_tolerance),
win_envs_(win_envs) {
win_num_ = data_ptr_->getWinNum();
}
// add an envelope list to result list
void Dp::addEnv(MatchEnvPtrVec &result, MatchEnvPtrVec &prev_env) {
result.insert(result.end(), prev_env.begin(), prev_env.end());
}
}
| 32.685714 | 74 | 0.738636 | toppic-suite |
3e71219676943218c86f87e1c79384451f5e6a23 | 1,011 | cpp | C++ | 2021F/CS203/lab4/a.cpp | HeZean/SUSTech-Archive | 0c89d78f232fdef427ca17b7e508881b782d7826 | [
"MIT"
] | null | null | null | 2021F/CS203/lab4/a.cpp | HeZean/SUSTech-Archive | 0c89d78f232fdef427ca17b7e508881b782d7826 | [
"MIT"
] | null | null | null | 2021F/CS203/lab4/a.cpp | HeZean/SUSTech-Archive | 0c89d78f232fdef427ca17b7e508881b782d7826 | [
"MIT"
] | null | null | null | #include <iostream>
struct Node {
long coe;
int exp;
Node* next;
};
int main() {
int n, m;
scanf("%d %d", &n, &m);
Node head{0, INT32_MAX, nullptr};
Node* cur = &head;
while (n--) {
int coe, exp;
scanf("%d %d", &coe, &exp);
Node* node = new Node{coe, exp, nullptr};
cur->next = node;
cur = cur->next;
}
cur->next = new Node{0, INT32_MIN, nullptr};
cur = &head;
while (m--) {
int coe, exp;
scanf("%d %d", &coe, &exp);
while (cur->next && cur->next->exp >= exp) cur = cur->next;
if (cur->exp == exp)
cur->coe += coe;
else
cur->next = new Node{coe, exp, cur->next};
}
cur = head.next;
int cnt = 0;
while (cur->next) {
if (cur->coe) cnt++;
cur = cur->next;
}
printf("%d\n", cnt);
cur = head.next;
while (cur->next) {
if (cur->coe) printf("%ld %d\n", cur->coe, cur->exp);
cur = cur->next;
}
}
| 21.978261 | 67 | 0.452028 | HeZean |
3e74a3c7eb15f4f63d3047dd8653fb9be94c3a6f | 1,838 | cpp | C++ | src/MCPDAC.cpp | MajenkoLibraries/MCPDAC | 7c271022ced7db0b15b5bfaa904e4a3112780e67 | [
"BSD-3-Clause"
] | 11 | 2016-07-24T21:40:14.000Z | 2021-12-29T13:54:18.000Z | src/MCPDAC.cpp | MajenkoLibraries/MCPDAC | 7c271022ced7db0b15b5bfaa904e4a3112780e67 | [
"BSD-3-Clause"
] | 3 | 2015-08-15T13:03:43.000Z | 2018-05-11T13:26:33.000Z | src/MCPDAC.cpp | MajenkoLibraries/MCPDAC | 7c271022ced7db0b15b5bfaa904e4a3112780e67 | [
"BSD-3-Clause"
] | 8 | 2016-08-02T00:38:14.000Z | 2022-03-31T16:19:38.000Z | /***********************************************
* Microchip DAC library
* (c) 2012 Majenko Technologies
*
* This library is offered without any warranty as to
* fitness for purpose, either explicitly or implicitly
* implied.
***********************************************/
/*
* Microchip DAC library. This works with the MCP4822 chip and
* similar chips that work with the same protocol.
*/
#include <Arduino.h>
#include <SPI.h>
#include "MCPDAC.h"
MCPDACClass MCPDAC;
void MCPDACClass::begin()
{
this->begin(10);
}
void MCPDACClass::begin(uint8_t cspin)
{
this->ldac = false;
this->cspin = cspin;
pinMode(this->cspin,OUTPUT);
digitalWrite(this->cspin,HIGH);
SPI.begin();
}
void MCPDACClass::begin(uint8_t cspin, uint8_t ldacpin)
{
this->begin(cspin);
this->ldac = true;
this->ldacpin = ldacpin;
pinMode(this->ldacpin,OUTPUT);
digitalWrite(this->ldacpin,HIGH);
}
void MCPDACClass::setGain(bool chan, bool gain)
{
this->gain[chan] = gain;
}
void MCPDACClass::shutdown(bool chan, bool sd)
{
this->shdn[chan] = sd;
}
void MCPDACClass::setVoltage(bool chan, uint16_t mv)
{
this->value[chan] = mv;
this->updateRegister(chan);
}
void MCPDACClass::update()
{
if(this->ldac==false)
return;
digitalWrite(this->ldacpin,LOW);
digitalWrite(this->ldacpin,HIGH);
}
void MCPDACClass::updateRegister(bool chan)
{
uint16_t command = 0;
command |= (chan << REGAB); // set channel in register
command |= (!this->gain[chan] << REGGA); // set gain in register
command |= (!this->shdn[chan] << REGSHDN); // set shutdown in register
command |= (this->value[chan] & 0x0FFF); // set input data bits (strip everything greater than 12 bit)
SPI.setDataMode(SPI_MODE0);
digitalWrite(this->cspin,LOW);
SPI.transfer(command>>8);
SPI.transfer(command&0xFF);
digitalWrite(this->cspin,HIGH);
}
| 22.414634 | 106 | 0.658868 | MajenkoLibraries |
3e768ef280774aab172fbe3521b0be896c0ad6a6 | 3,916 | cpp | C++ | build/include/nodes/internal/moc_FlowView.cpp | similas/nodeeditor | 06efa504cc11de8f941308fe45e6e77030fcd295 | [
"BSD-3-Clause"
] | null | null | null | build/include/nodes/internal/moc_FlowView.cpp | similas/nodeeditor | 06efa504cc11de8f941308fe45e6e77030fcd295 | [
"BSD-3-Clause"
] | null | null | null | build/include/nodes/internal/moc_FlowView.cpp | similas/nodeeditor | 06efa504cc11de8f941308fe45e6e77030fcd295 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'FlowView.hpp'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.15.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../../../include/nodes/internal/FlowView.hpp"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'FlowView.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.15.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_QtNodes__FlowView_t {
QByteArrayData data[5];
char stringdata0[57];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QtNodes__FlowView_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QtNodes__FlowView_t qt_meta_stringdata_QtNodes__FlowView = {
{
QT_MOC_LITERAL(0, 0, 17), // "QtNodes::FlowView"
QT_MOC_LITERAL(1, 18, 7), // "scaleUp"
QT_MOC_LITERAL(2, 26, 0), // ""
QT_MOC_LITERAL(3, 27, 9), // "scaleDown"
QT_MOC_LITERAL(4, 37, 19) // "deleteSelectedNodes"
},
"QtNodes::FlowView\0scaleUp\0\0scaleDown\0"
"deleteSelectedNodes"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QtNodes__FlowView[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x0a /* Public */,
3, 0, 30, 2, 0x0a /* Public */,
4, 0, 31, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void QtNodes::FlowView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<FlowView *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->scaleUp(); break;
case 1: _t->scaleDown(); break;
case 2: _t->deleteSelectedNodes(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject QtNodes::FlowView::staticMetaObject = { {
QMetaObject::SuperData::link<QGraphicsView::staticMetaObject>(),
qt_meta_stringdata_QtNodes__FlowView.data,
qt_meta_data_QtNodes__FlowView,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *QtNodes::FlowView::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QtNodes::FlowView::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_QtNodes__FlowView.stringdata0))
return static_cast<void*>(this);
return QGraphicsView::qt_metacast(_clname);
}
int QtNodes::FlowView::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGraphicsView::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 30.356589 | 97 | 0.624106 | similas |
3e77d2779e9191eec5c0f1c329de57d850a58178 | 3,593 | hpp | C++ | hpp/Compare.impl.hpp | Ivy233/simple_diff | 970bf8a0a624fc89b9c016fab44a87162feb2465 | [
"MIT"
] | 1 | 2021-11-30T07:47:52.000Z | 2021-11-30T07:47:52.000Z | hpp/Compare.impl.hpp | Ivy233/simple_diff | 970bf8a0a624fc89b9c016fab44a87162feb2465 | [
"MIT"
] | null | null | null | hpp/Compare.impl.hpp | Ivy233/simple_diff | 970bf8a0a624fc89b9c016fab44a87162feb2465 | [
"MIT"
] | null | null | null | /*
* File name: Compare.impl.hpp
* Description: 顶层类实现
* Author: 王锦润
* Version: 2
* Date: 2019.6.11
* History: 此程序被纳入git,可以直接使用git查询。
*/
//防卫式声明,必须要有
//就算没有重复包含也建议有,这是代码习惯
#ifndef _COMPARE_IMPL_HPP_
#define _COMPARE_IMPL_HPP_
#include "Compare.hpp"
/*
* Function: 构造函数
* Description: 构建文件夹,匹配并获得差异
* Input: 两个文件(夹)路径,cmd输入
* Calls: _M_link
*/
Compare::Compare(const string &_A, const string &_B, const bool *_cmds)
{
_M_need_merge = 0;
_M_folder[0] = new Folder(_A);
_M_folder[1] = new Folder(_B);
for (int i = 0; i < _M_cnt_cmds; i++)
_M_cmds[i] = _cmds[i]; //复制一份cmd,一个类对象一个cmd命令,方便后续窗口化管理
_M_link();
}
/*
* Function: 构造函数
* Description: 构建文件夹,匹配并获得差异,最后合并,忽视最初输入的cmd选项
* Input: 两个文件(夹)路径,cmd输入
* Calls: _M_link,_M_merge
*/
Compare::Compare(const string &_A, const string &_B, const string &_C)
{
_M_dir_merge = _C;
_M_need_merge = 1;
_M_folder[0] = new Folder(_A);
_M_folder[1] = new Folder(_B);
for (int i = 0; i < _M_cnt_cmds; i++)
_M_cmds[i] = 0;
_M_link();
_M_merge();
}
/*
* Function: _M_link
* Description: 匹配文件夹,对每一对匹配成功的进行LCS
*/
void Compare::_M_link()
{
_M_results.clear(); //清空
if (_M_folder[0]->_M_only_file && _M_folder[1]->_M_only_file) //如果都是单一文件,则无视文件名强制比较
_M_results.push_back(new LCS(
_M_folder[0]->_M_base_dir + _M_folder[0]->_M_ext_dirs[0],
_M_folder[1]->_M_base_dir + _M_folder[1]->_M_ext_dirs[0],
_M_cmds));
else
{
//取两者交集进行LCS比较
vector<string> diff_A_B;
//STL求交集
std::set_intersection(
_M_folder[0]->_M_ext_dirs.begin(), _M_folder[0]->_M_ext_dirs.end(),
_M_folder[1]->_M_ext_dirs.begin(), _M_folder[1]->_M_ext_dirs.end(),
std::inserter(_M_file_intersection, _M_file_intersection.begin()));
for (const string &ext_file : _M_file_intersection)
_M_results.push_back(new LCS(
_M_folder[0]->_M_base_dir + ext_file,
_M_folder[1]->_M_base_dir + ext_file, _M_cmds));
//在A但是不在B中,直接给出结果
std::set_difference(
_M_folder[0]->_M_ext_dirs.begin(), _M_folder[0]->_M_ext_dirs.end(),
_M_folder[1]->_M_ext_dirs.begin(), _M_folder[1]->_M_ext_dirs.end(),
std::inserter(diff_A_B, diff_A_B.begin())); //STL直接求差集
for (const string &ext_file : diff_A_B)
cout << "File in A but not in B: " << _M_folder[0]->_M_base_dir << ext_file << endl;
//在B但不在A中,直接给出结果
diff_A_B.clear(); //复用空间
std::set_difference(
_M_folder[1]->_M_ext_dirs.begin(), _M_folder[1]->_M_ext_dirs.end(),
_M_folder[0]->_M_ext_dirs.begin(), _M_folder[0]->_M_ext_dirs.end(),
std::inserter(diff_A_B, diff_A_B.begin())); //STL直接求差集
for (const string &ext_file : diff_A_B)
cout << "File not in A but in B: " << _M_folder[1]->_M_base_dir << ext_file << endl;
}
}
/*
* Function: _M_merge
* Description: 合并文件夹内部匹配的内容
*/
void Compare::_M_merge()
{
//单个文件则直接输出
if (_M_folder[0]->_M_only_file && _M_folder[1]->_M_only_file)
for (LCS *result : _M_results)
result->merge(_M_dir_merge);
//很多文件则依照公共路径一起输出
else
{
size_type siz = _M_results.size(); //公共集的大小
if (_M_dir_merge.back() != '/' || _M_dir_merge.back() != '\\')
_M_dir_merge.append("\\"); //防止最后路径d:\tmp\section之类
for (size_type i = 0; i < siz; i++)
_M_results[i]->merge(_M_dir_merge + _M_file_intersection[i]); //合并
}
}
#endif | 32.663636 | 96 | 0.605344 | Ivy233 |
3e7a4e44ca7e1385d3b922bff4ded9006411e401 | 84 | cpp | C++ | 002_DESIGN_PATTERN/Abstract_Factory/Abstract_Factory/Wall.cpp | JooHyeon-Roh/Cpp | 09410fef092428739c1cad3f15faa4b5cf0b4b76 | [
"MIT"
] | null | null | null | 002_DESIGN_PATTERN/Abstract_Factory/Abstract_Factory/Wall.cpp | JooHyeon-Roh/Cpp | 09410fef092428739c1cad3f15faa4b5cf0b4b76 | [
"MIT"
] | null | null | null | 002_DESIGN_PATTERN/Abstract_Factory/Abstract_Factory/Wall.cpp | JooHyeon-Roh/Cpp | 09410fef092428739c1cad3f15faa4b5cf0b4b76 | [
"MIT"
] | null | null | null | #include "Wall.h"
CWall::CWall()
{
}
CWall::~CWall()
{
}
void CWall::Enter()
{
}
| 6 | 19 | 0.547619 | JooHyeon-Roh |
3e7b9b08a6abb87111adf9ccf8abab0884ea124a | 5,349 | cpp | C++ | cops/live/stitcher.cpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 115 | 2019-09-28T13:39:41.000Z | 2022-03-24T11:08:53.000Z | cops/live/stitcher.cpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 113 | 2019-10-08T23:51:29.000Z | 2021-12-12T06:47:38.000Z | cops/live/stitcher.cpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 44 | 2019-09-28T07:53:21.000Z | 2022-02-13T23:21:12.000Z | // This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#include "stitcher.hpp"
#include <fstream>
#include "lgedgeiter.hpp"
Live_stitcher::Live_stitcher(Stitch_pass_options &pack) {
std::ifstream invariant_file(pack.boundaries_name);
if (!invariant_file.good()) {
Pass::error(fmt::format("Live_stitcher: Error reading boundaries file {}", pack.boundaries_name));
return;
}
boundaries = Invariant_boundaries::deserialize(invariant_file);
invariant_file.close();
original = Lgraph::open(pack.osynth_lgdb, boundaries->top);
if (!original) {
Pass::error(fmt::format("Live_stitcher: I was not able to open original synthesized netlist {} in {}",
boundaries->top,
pack.osynth_lgdb));
}
}
void Live_stitcher::stitch(Lgraph *nsynth, const std::set<Net_ID> &diffs) {
std::map<Index_id, Index_id> nsynth2originalid;
std::map<Index_id, Index_id> inp2originalid;
std::map<Index_id, Index_id> out2originalid;
// add new cells
for (auto &idx : nsynth->fast()) {
if (nsynth->node_type_get(idx).op == GraphIO_Op) {
// FIXME: how to check if there are new global IOs?
// FIXME: how to check if I need to delete global IOs?
auto name = nsynth->get_node_wirename(idx);
if (original->has_graph_input(name)) {
inp2originalid[idx] = original->get_graph_input(name).get_idx();
} else if (original->has_graph_output(name)) {
out2originalid[idx] = original->get_graph_output(name).get_idx();
} else {
if (original->has_wirename(name)) {
inp2originalid[idx] = original->get_node_id(name);
} else {
// Pass::>error("Wire {} not found in original synthesized graph\n",name);
}
}
else {
Index_id nidx = original->create_node().get_nid();
nsynth2originalid[idx] = nidx;
switch (nsynth->node_type_get(idx).op) {
case TechMap_Op: original->node_tmap_set(nidx, nsynth->tmap_id_get(idx)); break;
case Join_Op:
case Pick_Op: original->node_type_set(nidx, nsynth->node_type_get(idx).op); break;
case U32Const_Op: original->node_u32type_set(nidx, nsynth->node_value_get(idx)); break;
case StrConst_Op: original->node_const_type_set(nidx, nsynth->node_const_value_get(idx)); break;
default: Pass::error("live.stitcher: unsupported synthesized type");
}
}
}
// connect new cells
for (auto &idx : nsynth->fast()) {
if (!nsynth->has_graph_output(idx)) {
for (auto &c : nsynth->inp_edges(idx)) {
// if driver is in the delta region
if (nsynth2originalid.find(nsynth->get_node(c.get_out_pin()).get_nid()) != nsynth2originalid.end()) {
auto dnode = original->get_node(nsynth2originalid[nsynth->get_node(c.get_out_pin()).get_nid()]);
auto snode = original->get_node(nsynth2originalid[nsynth->get_node(c.get_inp_pin()).get_nid()]);
auto dpin = dnode.setup_driver_pin(c.get_out_pin().get_pid());
auto spin = snode.setup_sink_pin(c.get_inp_pin().get_pid());
original->add_edge(dpin, spin);
} else {
if (inp2originalid.find(idx) != inp2originalid.end()) {
auto dnode = original->get_node(inp2originalid[idx]);
auto snode = original->get_node(nsynth2originalid[nsynth->get_node(c.get_inp_pin()).get_nid()]);
auto spin = snode.setup_sink_pin(c.get_inp_pin().get_pid());
auto dpin = dnode.setup_driver_pin(); // FIXME: is there a case where I need to consider the out pid?
original->add_edge(dpin, spin);
}
}
}
} else {
if (out2originalid.find(idx) != out2originalid.end()) {
// global output
// FIXME: I need to consider the inp PID
for (auto &c : nsynth->inp_edges(idx)) {
Node_pin dpin = original->get_node(nsynth2originalid[nsynth->get_node(c.get_out_pin()).get_nid()])
.setup_driver_pin(c.get_out_pin().get_pid());
Node_pin spin = original->get_node(out2originalid[idx]).setup_sink_pin(out2originalid[idx]);
original->add_edge(dpin, spin);
}
} else {
// invariant boundary
auto name = nsynth->get_node_wirename(idx);
if (!original->has_wirename(name))
continue;
Index_id oidx = original->get_node_id(name);
for (auto &edge : original->out_edges(oidx)) {
Node_pin dpin = original->get_node(nsynth2originalid[idx]).setup_driver_pin(edge.get_out_pin().get_pid());
original->add_edge(dpin, edge.get_inp_pin());
original->del_edge(edge);
}
}
}
}
// removed original graph
for (auto &diff : diffs) {
I(boundaries->invariant_cone_cells.find(diff) != boundaries->invariant_cone_cells.end());
for (auto &gate : boundaries->invariant_cone_cells[diff]) {
I(boundaries->gate_appearances.find(gate) != boundaries->gate_appearances.end());
boundaries->gate_appearances[gate]--;
if (boundaries->gate_appearances[gate] <= 0) {
// original->del_node(gate);
}
}
}
original->sync();
}
| 40.832061 | 118 | 0.621051 | jesec |
3e7ccc6a681a1c231e4b59721ccb012140da6ba9 | 3,882 | hpp | C++ | include/boost/sql/sqlite3/statement.hpp | purpleKarrot/async-db | 172124e5657e3085e8ac7729c4e578c0d766bf7b | [
"BSL-1.0"
] | 5 | 2016-09-19T01:02:33.000Z | 2019-10-23T07:15:00.000Z | include/boost/sql/sqlite3/statement.hpp | purpleKarrot/async-db | 172124e5657e3085e8ac7729c4e578c0d766bf7b | [
"BSL-1.0"
] | null | null | null | include/boost/sql/sqlite3/statement.hpp | purpleKarrot/async-db | 172124e5657e3085e8ac7729c4e578c0d766bf7b | [
"BSL-1.0"
] | null | null | null | /**************************************************************
* Copyright (c) 2008-2009 Daniel Pfeifer *
* *
* Distributed under the Boost Software License, Version 1.0. *
**************************************************************/
#ifndef BOOST_SQL_SQLITE3_STATEMENT_HPP
#define BOOST_SQL_SQLITE3_STATEMENT_HPP
#include <boost/sql/sqlite3/connection.hpp>
#include <boost/sql/sqlite3/detail/bind_params.hpp>
#include <boost/sql/sqlite3/detail/bind_result.hpp>
#include <boost/sql/sqlite3/detail/error.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/sql/detail/callable.hpp>
#include <boost/sql/detail/handler.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <string>
namespace boost
{
namespace sql
{
namespace sqlite3
{
template<typename Param, typename Result>
class statement
{
enum
{
param_count = mpl::size<Param>::value,
result_count = mpl::size<Result>::value
};
public:
statement(connection& c, const std::string& query) :
stmt(0), conn(c), query_str(query), prepared(false)
{
}
~statement()
{
sqlite3_finalize(stmt);
}
std::string error_message() const
{
return sqlite3_errmsg(conn.implementation());
}
void prepare(boost::system::error_code& error)
{
error.assign(sqlite3_prepare_v2(conn.implementation(),
query_str.c_str(), query_str.size(), &stmt, 0),
get_error_category());
if (error)
return;
BOOST_ASSERT(sqlite3_bind_parameter_count(stmt) == param_count);
BOOST_ASSERT(sqlite3_column_count(stmt) == result_count);
prepared = true;
}
void prepare()
{
boost::system::error_code error;
prepare(error);
if (error)
throw std::runtime_error(error_message());
}
template<typename Handler>
void async_prepare(Handler handler)
{
post(boost::bind(statement::prepare, this, _1), handler);
}
void execute(const Param& params, boost::system::error_code& error)
{
if (!prepared)
{
prepare(error);
if (error)
return;
}
error.assign(sqlite3_reset(stmt), get_error_category());
if (error)
return;
error.assign(detail::bind_params(stmt, params), get_error_category());
if (error)
return;
typedef int(*step_or_reset_function)(sqlite3_stmt*);
step_or_reset_function step_or_reset = //
sqlite3_column_count(stmt) ? sqlite3_reset : sqlite3_step;
error.assign(step_or_reset(stmt), get_error_category());
if (error.value() == SQLITE_DONE)
error = boost::system::error_code();
}
void execute(const Param& params)
{
boost::system::error_code error;
execute(params, error);
if (error)
throw std::runtime_error(error_message());
}
template<typename Handler>
void async_execute(const Param& params, Handler handler)
{
post(boost::bind(&statement::execute, this, params, _1), handler);
}
bool fetch(Result& result)
{
switch (sqlite3_step(stmt))
{
case SQLITE_ROW:
fusion::for_each(result, detail::bind_result(stmt));
return true;
case SQLITE_DONE:
sqlite3_reset(stmt);
return false;
case SQLITE_ERROR:
// SQLITE_ERROR is a generic error code.
// must call sqlite3_reset() to get the specific error message.
sqlite3_reset(stmt);
}
throw std::runtime_error(error_message());
}
// template<typename Handler>
// void async_fetch(Result& result, Handler handler)
// {
// post(boost::bind(statement::prepare, this, _1), handler);
// }
private:
template<typename Function, typename Callback>
void post(Function function, Callback callback)
{
conn.get_io_service().post(sql::detail::handler<Function, Callback>(
conn.get_io_service(), function, callback));
}
sqlite3_stmt* stmt;
connection& conn;
std::string query_str;
bool prepared;
};
} // end namespace sqlite3
} // end namespace sql
} // end namespace boost
#endif /*BOOST_SQL_SQLITE3_STATEMENT_HPP*/
| 23.245509 | 72 | 0.679289 | purpleKarrot |
3e7f594166631fda651944638352170b813f1bff | 4,640 | cc | C++ | ThirdParty/webrtc/src/webrtc/modules/module_common_types_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 8 | 2018-12-27T14:57:13.000Z | 2021-04-07T07:03:15.000Z | ThirdParty/webrtc/src/webrtc/modules/module_common_types_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 1 | 2019-03-13T01:35:03.000Z | 2020-10-08T04:13:04.000Z | ThirdParty/webrtc/src/webrtc/modules/module_common_types_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 9 | 2018-12-28T11:45:12.000Z | 2021-05-11T02:15:31.000Z | /*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/interface/module_common_types.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace webrtc {
TEST(IsNewerSequenceNumber, Equal) {
EXPECT_FALSE(IsNewerSequenceNumber(0x0001, 0x0001));
}
TEST(IsNewerSequenceNumber, NoWrap) {
EXPECT_TRUE(IsNewerSequenceNumber(0xFFFF, 0xFFFE));
EXPECT_TRUE(IsNewerSequenceNumber(0x0001, 0x0000));
EXPECT_TRUE(IsNewerSequenceNumber(0x0100, 0x00FF));
}
TEST(IsNewerSequenceNumber, ForwardWrap) {
EXPECT_TRUE(IsNewerSequenceNumber(0x0000, 0xFFFF));
EXPECT_TRUE(IsNewerSequenceNumber(0x0000, 0xFF00));
EXPECT_TRUE(IsNewerSequenceNumber(0x00FF, 0xFFFF));
EXPECT_TRUE(IsNewerSequenceNumber(0x00FF, 0xFF00));
}
TEST(IsNewerSequenceNumber, BackwardWrap) {
EXPECT_FALSE(IsNewerSequenceNumber(0xFFFF, 0x0000));
EXPECT_FALSE(IsNewerSequenceNumber(0xFF00, 0x0000));
EXPECT_FALSE(IsNewerSequenceNumber(0xFFFF, 0x00FF));
EXPECT_FALSE(IsNewerSequenceNumber(0xFF00, 0x00FF));
}
TEST(IsNewerSequenceNumber, HalfWayApart) {
EXPECT_TRUE(IsNewerSequenceNumber(0x8000, 0x0000));
EXPECT_FALSE(IsNewerSequenceNumber(0x0000, 0x8000));
}
TEST(IsNewerTimestamp, Equal) {
EXPECT_FALSE(IsNewerTimestamp(0x00000001, 0x000000001));
}
TEST(IsNewerTimestamp, NoWrap) {
EXPECT_TRUE(IsNewerTimestamp(0xFFFFFFFF, 0xFFFFFFFE));
EXPECT_TRUE(IsNewerTimestamp(0x00000001, 0x00000000));
EXPECT_TRUE(IsNewerTimestamp(0x00010000, 0x0000FFFF));
}
TEST(IsNewerTimestamp, ForwardWrap) {
EXPECT_TRUE(IsNewerTimestamp(0x00000000, 0xFFFFFFFF));
EXPECT_TRUE(IsNewerTimestamp(0x00000000, 0xFFFF0000));
EXPECT_TRUE(IsNewerTimestamp(0x0000FFFF, 0xFFFFFFFF));
EXPECT_TRUE(IsNewerTimestamp(0x0000FFFF, 0xFFFF0000));
}
TEST(IsNewerTimestamp, BackwardWrap) {
EXPECT_FALSE(IsNewerTimestamp(0xFFFFFFFF, 0x00000000));
EXPECT_FALSE(IsNewerTimestamp(0xFFFF0000, 0x00000000));
EXPECT_FALSE(IsNewerTimestamp(0xFFFFFFFF, 0x0000FFFF));
EXPECT_FALSE(IsNewerTimestamp(0xFFFF0000, 0x0000FFFF));
}
TEST(IsNewerTimestamp, HalfWayApart) {
EXPECT_TRUE(IsNewerTimestamp(0x80000000, 0x00000000));
EXPECT_FALSE(IsNewerTimestamp(0x00000000, 0x80000000));
}
TEST(LatestSequenceNumber, NoWrap) {
EXPECT_EQ(0xFFFFu, LatestSequenceNumber(0xFFFF, 0xFFFE));
EXPECT_EQ(0x0001u, LatestSequenceNumber(0x0001, 0x0000));
EXPECT_EQ(0x0100u, LatestSequenceNumber(0x0100, 0x00FF));
EXPECT_EQ(0xFFFFu, LatestSequenceNumber(0xFFFE, 0xFFFF));
EXPECT_EQ(0x0001u, LatestSequenceNumber(0x0000, 0x0001));
EXPECT_EQ(0x0100u, LatestSequenceNumber(0x00FF, 0x0100));
}
TEST(LatestSequenceNumber, Wrap) {
EXPECT_EQ(0x0000u, LatestSequenceNumber(0x0000, 0xFFFF));
EXPECT_EQ(0x0000u, LatestSequenceNumber(0x0000, 0xFF00));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0x00FF, 0xFFFF));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0x00FF, 0xFF00));
EXPECT_EQ(0x0000u, LatestSequenceNumber(0xFFFF, 0x0000));
EXPECT_EQ(0x0000u, LatestSequenceNumber(0xFF00, 0x0000));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0xFFFF, 0x00FF));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0xFF00, 0x00FF));
}
TEST(LatestTimestamp, NoWrap) {
EXPECT_EQ(0xFFFFFFFFu, LatestTimestamp(0xFFFFFFFF, 0xFFFFFFFE));
EXPECT_EQ(0x00000001u, LatestTimestamp(0x00000001, 0x00000000));
EXPECT_EQ(0x00010000u, LatestTimestamp(0x00010000, 0x0000FFFF));
}
TEST(LatestTimestamp, Wrap) {
EXPECT_EQ(0x00000000u, LatestTimestamp(0x00000000, 0xFFFFFFFF));
EXPECT_EQ(0x00000000u, LatestTimestamp(0x00000000, 0xFFFF0000));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0x0000FFFF, 0xFFFFFFFF));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0x0000FFFF, 0xFFFF0000));
EXPECT_EQ(0x00000000u, LatestTimestamp(0xFFFFFFFF, 0x00000000));
EXPECT_EQ(0x00000000u, LatestTimestamp(0xFFFF0000, 0x00000000));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0xFFFFFFFF, 0x0000FFFF));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0xFFFF0000, 0x0000FFFF));
}
TEST(ClampToInt16, TestCases) {
EXPECT_EQ(0x0000, ClampToInt16(0x00000000));
EXPECT_EQ(0x0001, ClampToInt16(0x00000001));
EXPECT_EQ(0x7FFF, ClampToInt16(0x00007FFF));
EXPECT_EQ(0x7FFF, ClampToInt16(0x7FFFFFFF));
EXPECT_EQ(-0x0001, ClampToInt16(-0x00000001));
EXPECT_EQ(-0x8000, ClampToInt16(-0x8000));
EXPECT_EQ(-0x8000, ClampToInt16(-0x7FFFFFFF));
}
} // namespace webrtc
| 36.825397 | 71 | 0.794397 | JokeJoe8806 |
3e81eef6789f12a9471266f36902585d12d47230 | 979 | cpp | C++ | N0504-Base-7/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0504-Base-7/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0504-Base-7/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | 2 | 2022-01-25T05:31:31.000Z | 2022-02-26T07:22:23.000Z | //
// main.cpp
// LeetCode-Solution
//
// Created by Loyio Hex on 3/7/22.
//
#include <iostream>
#include <chrono>
#include <vector>
using namespace std;
using namespace std::chrono;
class Solution {
public:
string convertToBase7(int num) {
if(num == 0){
return "0";
}
string res;
string negative = num < 0 ? "-" : "";
num = abs(num);
while(num){
res += to_string(num%7);
num = num/7;
}
reverse(res.begin(), res.end());
return negative+res;
}
};
int main(int argc, const char * argv[]) {
auto start = high_resolution_clock::now();
// Main Start
int num = -7;
Solution solution;
cout<< solution.convertToBase7(num);
// Main End
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << endl << "Runnig time : " << duration.count() << "ms;" << endl;
return 0;
}
| 19.58 | 74 | 0.551583 | loyio |
3e83fbf1a50a5bcb95581fece8933e56120375c7 | 1,137 | hpp | C++ | Piscines/CPP/rush01/includes/CPUInfoModule.hpp | SpeedFireSho/42-1 | 5d7ce17910794a28ca44d937651b961feadcff11 | [
"MIT"
] | 84 | 2020-10-13T14:50:11.000Z | 2022-01-11T11:19:36.000Z | Piscines/CPP/rush01/includes/CPUInfoModule.hpp | SpeedFireSho/42-1 | 5d7ce17910794a28ca44d937651b961feadcff11 | [
"MIT"
] | null | null | null | Piscines/CPP/rush01/includes/CPUInfoModule.hpp | SpeedFireSho/42-1 | 5d7ce17910794a28ca44d937651b961feadcff11 | [
"MIT"
] | 43 | 2020-09-10T19:26:37.000Z | 2021-12-28T13:53:55.000Z | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* CPUInfoModule.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaleman <jaleman@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/15 18:52:02 by jaleman #+# #+# */
/* Updated: 2017/07/15 18:52:03 by jaleman ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CPUINFOMODULE_HPP
# define CPUINFOMODULE_HPP
class CPUInfoModule
{
CPUInfoModule(void);
CPUInfoModule(const CPUInfoModule &rhs);
~CPUInfoModule(void);
CPUInfoModule &operator= (const CPUInfoModule &rhs);
};
#endif
| 42.111111 | 80 | 0.252419 | SpeedFireSho |
3e8a7bd062a12fc5eb6e1ef04fb28d58c0dc7fd6 | 8,268 | cpp | C++ | src/polybench/POLYBENCH_3MM-Hip.cpp | ajpowelsnl/RAJAPerf | f44641695203cd3bd3058315f356359f1b492ea3 | [
"BSD-3-Clause"
] | null | null | null | src/polybench/POLYBENCH_3MM-Hip.cpp | ajpowelsnl/RAJAPerf | f44641695203cd3bd3058315f356359f1b492ea3 | [
"BSD-3-Clause"
] | null | null | null | src/polybench/POLYBENCH_3MM-Hip.cpp | ajpowelsnl/RAJAPerf | f44641695203cd3bd3058315f356359f1b492ea3 | [
"BSD-3-Clause"
] | null | null | null | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2017-21, Lawrence Livermore National Security, LLC
// and RAJA Performance Suite project contributors.
// See the RAJAPerf/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "POLYBENCH_3MM.hpp"
#include "RAJA/RAJA.hpp"
#if defined(RAJA_ENABLE_HIP)
#include "common/HipDataUtils.hpp"
#include <iostream>
namespace rajaperf
{
namespace polybench
{
#define POLYBENCH_3MM_DATA_SETUP_HIP \
allocAndInitHipDeviceData(A, m_A, m_ni * m_nk); \
allocAndInitHipDeviceData(B, m_B, m_nk * m_nj); \
allocAndInitHipDeviceData(C, m_C, m_nj * m_nm); \
allocAndInitHipDeviceData(D, m_D, m_nm * m_nl); \
allocAndInitHipDeviceData(E, m_E, m_ni * m_nj); \
allocAndInitHipDeviceData(F, m_F, m_nj * m_nl); \
allocAndInitHipDeviceData(G, m_G, m_ni * m_nl);
#define POLYBENCH_3MM_TEARDOWN_HIP \
getHipDeviceData(m_G, G, m_ni * m_nl); \
deallocHipDeviceData(A); \
deallocHipDeviceData(B); \
deallocHipDeviceData(C); \
deallocHipDeviceData(D); \
deallocHipDeviceData(E); \
deallocHipDeviceData(F); \
deallocHipDeviceData(G);
__global__ void poly_3mm_1(Real_ptr E, Real_ptr A, Real_ptr B,
Index_type nj, Index_type nk)
{
Index_type i = blockIdx.y;
Index_type j = threadIdx.x;
POLYBENCH_3MM_BODY1;
for (Index_type k=0; k < nk; ++k) {
POLYBENCH_3MM_BODY2;
}
POLYBENCH_3MM_BODY3;
}
__global__ void poly_3mm_2(Real_ptr F, Real_ptr C, Real_ptr D,
Index_type nl, Index_type nm)
{
Index_type j = blockIdx.y;
Index_type l = threadIdx.x;
POLYBENCH_3MM_BODY4;
for (Index_type m=0; m < nm; ++m) {
POLYBENCH_3MM_BODY5;
}
POLYBENCH_3MM_BODY6;
}
__global__ void poly_3mm_3(Real_ptr G, Real_ptr E, Real_ptr F,
Index_type nl, Index_type nj)
{
Index_type i = blockIdx.y;
Index_type l = threadIdx.x;
POLYBENCH_3MM_BODY7;
for (Index_type j=0; j < nj; ++j) {
POLYBENCH_3MM_BODY8;
}
POLYBENCH_3MM_BODY9;
}
void POLYBENCH_3MM::runHipVariant(VariantID vid)
{
const Index_type run_reps = getRunReps();
POLYBENCH_3MM_DATA_SETUP;
if ( vid == Base_HIP ) {
POLYBENCH_3MM_DATA_SETUP_HIP;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
dim3 nblocks1(1, ni, 1);
dim3 nthreads_per_block1(nj, 1, 1);
hipLaunchKernelGGL((poly_3mm_1), dim3(nblocks1) , dim3(nthreads_per_block1), 0, 0,
E, A, B,
nj, nk);
hipErrchk( hipGetLastError() );
dim3 nblocks2(1, nj, 1);
dim3 nthreads_per_block2(nl, 1, 1);
hipLaunchKernelGGL((poly_3mm_2), dim3(nblocks2), dim3(nthreads_per_block2), 0, 0,
F, C, D,
nl, nm);
hipErrchk( hipGetLastError() );
dim3 nblocks3(1, ni, 1);
dim3 nthreads_per_block3(nl, 1, 1);
hipLaunchKernelGGL((poly_3mm_3), dim3(nblocks3), dim3(nthreads_per_block3), 0, 0,
G, E, F,
nl, nj);
hipErrchk( hipGetLastError() );
}
stopTimer();
POLYBENCH_3MM_TEARDOWN_HIP;
} else if (vid == Lambda_HIP) {
POLYBENCH_3MM_DATA_SETUP_HIP;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
auto poly_3mm_1_lambda = [=] __device__ (Index_type i, Index_type j) {
POLYBENCH_3MM_BODY1;
for (Index_type k=0; k < nk; ++k) {
POLYBENCH_3MM_BODY2;
}
POLYBENCH_3MM_BODY3;
};
dim3 nblocks1(1, ni, 1);
dim3 nthreads_per_block1(nj, 1, 1);
auto kernel1 = lambda_hip_kernel<RAJA::hip_block_y_direct, RAJA::hip_thread_x_direct, decltype(poly_3mm_1_lambda)>;
hipLaunchKernelGGL(kernel1,
nblocks1, nthreads_per_block1, 0, 0,
0, ni, 0, nj, poly_3mm_1_lambda);
hipErrchk( hipGetLastError() );
auto poly_3mm_2_lambda = [=] __device__ (Index_type j, Index_type l) {
POLYBENCH_3MM_BODY4;
for (Index_type m=0; m < nm; ++m) {
POLYBENCH_3MM_BODY5;
}
POLYBENCH_3MM_BODY6;
};
dim3 nblocks2(1, nj, 1);
dim3 nthreads_per_block2(nl, 1, 1);
auto kernel2 = lambda_hip_kernel<RAJA::hip_block_y_direct, RAJA::hip_thread_x_direct, decltype(poly_3mm_2_lambda)>;
hipLaunchKernelGGL(kernel2,
nblocks2, nthreads_per_block2, 0, 0,
0, nj, 0, nl, poly_3mm_2_lambda);
hipErrchk( hipGetLastError() );
auto poly_3mm_3_lambda = [=] __device__ (Index_type i, Index_type l) {
POLYBENCH_3MM_BODY7;
for (Index_type j=0; j < nj; ++j) {
POLYBENCH_3MM_BODY8;
}
POLYBENCH_3MM_BODY9;
};
dim3 nblocks3(1, ni, 1);
dim3 nthreads_per_block3(nl, 1, 1);
auto kernel3 = lambda_hip_kernel<RAJA::hip_block_y_direct, RAJA::hip_thread_x_direct, decltype(poly_3mm_3_lambda)>;
hipLaunchKernelGGL(kernel3,
nblocks3, nthreads_per_block3, 0, 0,
0, ni, 0, nl, poly_3mm_3_lambda);
hipErrchk( hipGetLastError() );
}
stopTimer();
POLYBENCH_3MM_TEARDOWN_HIP;
} else if (vid == RAJA_HIP) {
POLYBENCH_3MM_DATA_SETUP_HIP;
POLYBENCH_3MM_VIEWS_RAJA;
using EXEC_POL =
RAJA::KernelPolicy<
RAJA::statement::HipKernelAsync<
RAJA::statement::For<0, RAJA::hip_block_x_direct,
RAJA::statement::For<1, RAJA::hip_thread_y_direct,
RAJA::statement::Lambda<0, RAJA::Params<0>>,
RAJA::statement::For<2, RAJA::seq_exec,
RAJA::statement::Lambda<1, RAJA::Segs<0,1,2>, RAJA::Params<0>>
>,
RAJA::statement::Lambda<2, RAJA::Segs<0,1>, RAJA::Params<0>>
>
>
>
>;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
RAJA::kernel_param<EXEC_POL>(
RAJA::make_tuple(RAJA::RangeSegment{0, ni},
RAJA::RangeSegment{0, nj},
RAJA::RangeSegment{0, nk}),
RAJA::tuple<Real_type>{0.0},
[=] __device__ ( Real_type &dot) {
POLYBENCH_3MM_BODY1_RAJA;
},
[=] __device__ (Index_type i, Index_type j, Index_type k,
Real_type &dot) {
POLYBENCH_3MM_BODY2_RAJA;
},
[=] __device__ (Index_type i, Index_type j,
Real_type &dot) {
POLYBENCH_3MM_BODY3_RAJA;
}
);
RAJA::kernel_param<EXEC_POL>(
RAJA::make_tuple(RAJA::RangeSegment{0, nj},
RAJA::RangeSegment{0, nl},
RAJA::RangeSegment{0, nm}),
RAJA::tuple<Real_type>{0.0},
[=] __device__ ( Real_type &dot) {
POLYBENCH_3MM_BODY4_RAJA;
},
[=] __device__ (Index_type j, Index_type l, Index_type m,
Real_type &dot) {
POLYBENCH_3MM_BODY5_RAJA;
},
[=] __device__ (Index_type j, Index_type l,
Real_type &dot) {
POLYBENCH_3MM_BODY6_RAJA;
}
);
RAJA::kernel_param<EXEC_POL>(
RAJA::make_tuple(RAJA::RangeSegment{0, ni},
RAJA::RangeSegment{0, nl},
RAJA::RangeSegment{0, nj}),
RAJA::tuple<Real_type>{0.0},
[=] __device__ ( Real_type &dot) {
POLYBENCH_3MM_BODY7_RAJA;
},
[=] __device__ (Index_type i, Index_type l, Index_type j,
Real_type &dot) {
POLYBENCH_3MM_BODY8_RAJA;
},
[=] __device__ (Index_type i, Index_type l,
Real_type &dot) {
POLYBENCH_3MM_BODY9_RAJA;
}
);
}
stopTimer();
POLYBENCH_3MM_TEARDOWN_HIP;
} else {
std::cout << "\n POLYBENCH_3MM : Unknown Hip variant id = " << vid << std::endl;
}
}
} // end namespace polybench
} // end namespace rajaperf
#endif // RAJA_ENABLE_HIP
| 28.909091 | 121 | 0.572085 | ajpowelsnl |
3e8f42c0c5e2dc5056d9a7224973c90c72e28838 | 1,557 | cpp | C++ | source/Irrlicht/rtc/impl/verifiedtlstransport.cpp | MagicAtom/irrlicht-ce | b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d | [
"IJG"
] | null | null | null | source/Irrlicht/rtc/impl/verifiedtlstransport.cpp | MagicAtom/irrlicht-ce | b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d | [
"IJG"
] | null | null | null | source/Irrlicht/rtc/impl/verifiedtlstransport.cpp | MagicAtom/irrlicht-ce | b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d | [
"IJG"
] | null | null | null | /**
* Copyright (c) 2020 Paul-Louis Ageneau
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "verifiedtlstransport.hpp"
#include "common.hpp"
#if RTC_ENABLE_WEBSOCKET
namespace rtc::impl {
VerifiedTlsTransport::VerifiedTlsTransport(shared_ptr<TcpTransport> lower, string host,
certificate_ptr certificate, state_callback callback)
: TlsTransport(std::move(lower), std::move(host), std::move(certificate), std::move(callback)) {
#if USE_GNUTLS
PLOG_DEBUG << "Setting up TLS certificate verification";
gnutls_session_set_verify_cert(mSession, mHost->c_str(), 0);
#else
PLOG_DEBUG << "Setting up TLS certificate verification";
SSL_set_verify(mSsl, SSL_VERIFY_PEER, NULL);
SSL_set_verify_depth(mSsl, 4);
#endif
}
VerifiedTlsTransport::~VerifiedTlsTransport() {}
} // namespace rtc::impl
#endif
| 34.6 | 100 | 0.739884 | MagicAtom |
3e8fd59645d671523f3ae245584a7fe10e48a5ef | 346 | cc | C++ | src/pks/flow/test/Main.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/pks/flow/test/Main.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | src/pks/flow/test/Main.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | #include <UnitTest++.h>
#include "Teuchos_GlobalMPISession.hpp"
#include "VerboseObject_objs.hh"
#include "state_evaluators_registration.hh"
#include "wrm_flow_registration.hh"
int main(int argc, char *argv[])
{
int res = 0;
{
Teuchos::GlobalMPISession mpiSession(&argc, &argv);
res = UnitTest::RunAllTests();
}
return res;
}
| 18.210526 | 55 | 0.710983 | ajkhattak |
3e8fe50456914315af4f30b59c7229f4e01bb099 | 119 | cpp | C++ | ares/sfc/coprocessor/obc1/serialization.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/sfc/coprocessor/obc1/serialization.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/sfc/coprocessor/obc1/serialization.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | auto OBC1::serialize(serializer& s) -> void {
s(ram);
s(status.address);
s(status.baseptr);
s(status.shift);
}
| 17 | 45 | 0.638655 | CasualPokePlayer |
3e92c5dca9298e99d41b3d6c905fdae5661588e3 | 1,271 | hpp | C++ | GLSL-Pipeline/Toolkits/include/System/Action.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Action.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Action.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <functional>
#include "DLL.hpp"
namespace System
{
/**
* \brief Encapsulates a method that has specified parameters and does not return a value.
* \tparam Args The type of the parameters of the method that this delegate encapsulates.
*/
template<typename ...Args>
class DLLExport Action final
{
public:
typedef std::function<void(Args...)> ActionType;
#pragma region Public Constructors
Action(ActionType action);
#pragma endregion
#pragma region Public Destructor
~Action();
#pragma endregion
#pragma region Public Instance Methods
void Invoke(Args&&... args);
#pragma endregion
private:
ActionType action;
};
#pragma region Public Constructors
template <typename ... Args>
Action<Args...>::Action(ActionType action)
{
this->action = action;
}
#pragma endregion
#pragma region Public Destructor
template <typename ... Args>
Action<Args...>::~Action() {}
#pragma endregion
#pragma region Public Instance Methods
template <typename ... Args>
void Action<Args...>::Invoke(Args&&... args)
{
if (&action != nullptr)
{
action(args...);
}
}
#pragma endregion
}
| 18.157143 | 94 | 0.631786 | GilFerraz |
3e9942ab0f2b963ee67db148deacdfce161447d1 | 2,188 | cc | C++ | flare/rpc/details/has_epollrdhup.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | 3 | 2022-01-23T17:55:24.000Z | 2022-03-23T12:55:18.000Z | flare/rpc/details/has_epollrdhup.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | null | null | null | flare/rpc/details/has_epollrdhup.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "flare/base/profile.h"
#if defined(FLARE_PLATFORM_LINUX)
#include <sys/epoll.h> // epoll_create
#include <sys/types.h> // socketpair
#include <sys/socket.h> // ^
#include "flare/base/fd_guard.h" // fd_guard
#include "flare/rpc/details/has_epollrdhup.h"
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0x2000
#endif
namespace flare::rpc {
static unsigned int check_epollrdhup() {
flare::base::fd_guard epfd(epoll_create(16));
if (epfd < 0) {
return 0;
}
flare::base::fd_guard fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, (int*)fds) < 0) {
return 0;
}
epoll_event evt = { static_cast<uint32_t>(EPOLLIN | EPOLLRDHUP | EPOLLET),
{ NULL }};
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fds[0], &evt) < 0) {
return 0;
}
if (close(fds[1].release()) < 0) {
return 0;
}
epoll_event e;
int n;
while ((n = epoll_wait(epfd, &e, 1, -1)) == 0);
if (n < 0) {
return 0;
}
return (e.events & EPOLLRDHUP) ? EPOLLRDHUP : static_cast<EPOLL_EVENTS>(0);
}
extern const unsigned int has_epollrdhup = check_epollrdhup();
} // namespace flare::rpc
#else
namespace flare::rpc {
extern const unsigned int has_epollrdhup = false;
}
#endif // defined(FLARE_PLATFORM_LINUX)
| 30.388889 | 79 | 0.644424 | flare-rpc |
3e9a07746cfa9d86e5e733d2ccdf9beed64c1a60 | 6,354 | cpp | C++ | examples/11_locmesh/locsvcmesh/src/ServiceClient.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 70 | 2021-07-20T11:26:16.000Z | 2022-03-27T11:17:43.000Z | examples/11_locmesh/locsvcmesh/src/ServiceClient.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 32 | 2021-07-31T05:20:44.000Z | 2022-03-20T10:11:52.000Z | examples/11_locmesh/locsvcmesh/src/ServiceClient.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 40 | 2021-11-02T09:45:38.000Z | 2022-03-27T11:17:46.000Z | /************************************************************************
* \file ServiceClient.cpp
* \ingroup AREG Asynchronous Event-Driven Communication Framework examples
* \author Artak Avetyan
* \brief Collection of AREG SDK examples.
* This file contains simple implementation of service client to
* request message output
************************************************************************/
/************************************************************************
* Include files.
************************************************************************/
#include "ServiceClient.hpp"
#include "areg/trace/GETrace.h"
#include "areg/component/Component.hpp"
#include "areg/component/ComponentThread.hpp"
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_serviceConnected);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onConnectedClientsUpdate);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onRemainOutputUpdate);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastHelloClients);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastServiceUnavailable);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_responseHelloWorld);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestHelloWorldFailed);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestClientShutdownFailed);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_processTimer);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_ServiceClient);
const unsigned int ServiceClient::TIMEOUT_VALUE = 237;
ServiceClient::ServiceClient(const String & roleName, Component & owner)
: HelloWorldClientBase ( roleName, owner )
, IETimerConsumer ( )
, mTimer ( static_cast<IETimerConsumer &>(self()), timerName( owner ) )
, mID ( 0 )
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_ServiceClient);
TRACE_DBG("Client: roleName [ %s ] of service [ %s ] owner [ %s ] in thread [ %s ] has timer [ %s ]"
, roleName.getString()
, getServiceName().getString()
, owner.getRoleName().getString()
, owner.getMasterThread().getName().getString()
, mTimer.getName().getString());
TRACE_DBG("Proxy: [ %s ]", ProxyAddress::convAddressToPath(getProxy()->getProxyAddress()).getString());
}
bool ServiceClient::serviceConnected(bool isConnected, ProxyBase & proxy)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_serviceConnected);
bool result = HelloWorldClientBase::serviceConnected(isConnected, proxy);
TRACE_DBG("Proxy [ %s ] is [ %s ]"
, ProxyAddress::convAddressToPath(proxy.getProxyAddress()).getString()
, isConnected ? "connected" : "disconnected");
if (isConnected)
{
// dynamic subscribe.
notifyOnRemainOutputUpdate(true);
notifyOnBroadcastServiceUnavailable(true);
mTimer.startTimer(ServiceClient::TIMEOUT_VALUE);
}
else
{
mTimer.stopTimer();
// clear all subscriptions.
clearAllNotifications();
}
return result;
}
void ServiceClient::onConnectedClientsUpdate(const NEHelloWorld::ConnectionList & ConnectedClients, NEService::eDataStateType state)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onConnectedClientsUpdate);
TRACE_DBG("Active client list of [ %s ] service is updated, active clients [ %d ], data is [ %s ]"
, getServiceRole().getString()
, ConnectedClients.getSize()
, NEService::getString(state));
}
void ServiceClient::onRemainOutputUpdate(short RemainOutput, NEService::eDataStateType state)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onRemainOutputUpdate);
TRACE_DBG("Service [ %s ]: Remain greeting outputs [ %d ], data is [ %s ]", getServiceRole().getString(), RemainOutput, NEService::getString(state));
}
void ServiceClient::responseHelloWorld(const NEHelloWorld::sConnectedClient & clientInfo)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_responseHelloWorld);
TRACE_DBG("Service [ %s ]: Made output of [ %s ], client ID [ %d ]", getServiceRole().getString(), clientInfo.ccName.getString(), clientInfo.ccID);
ASSERT(clientInfo.ccName == mTimer.getName());
mID = clientInfo.ccID;
if (isNotificationAssigned(NEHelloWorld::eMessageIDs::MsgId_broadcastHelloClients) == false)
{
notifyOnBroadcastHelloClients(true);
notifyOnConnectedClientsUpdate(true);
}
}
void ServiceClient::broadcastHelloClients(const NEHelloWorld::ConnectionList & clientList)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastHelloClients);
TRACE_DBG("[ %d ] clients use service [ %s ]", clientList.getSize(), getServiceName().getString());
}
void ServiceClient::broadcastServiceUnavailable(void)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastServiceUnavailable);
TRACE_WARN("Service notify reached message output maximum, starting shutdown procedure");
requestClientShutdown(mID, mTimer.getName());
}
void ServiceClient::requestHelloWorldFailed(NEService::eResultType FailureReason)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestHelloWorldFailed);
TRACE_ERR("Request to output greetings failed with reason [ %s ]", NEService::getString(FailureReason));
}
void ServiceClient::requestClientShutdownFailed(NEService::eResultType FailureReason)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestClientShutdownFailed);
TRACE_ERR("Request to notify client shutdown failed with reason [ %s ]", NEService::getString(FailureReason));
}
void ServiceClient::processTimer(Timer & timer)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_processTimer);
ASSERT(&timer == &mTimer);
TRACE_DBG("Timer [ %s ] expired, send request to output message.", timer.getName().getString());
requestHelloWorld(timer.getName(), "");
}
inline String ServiceClient::timerName( Component & owner ) const
{
String result = "";
result += owner.getRoleName();
result += NECommon::DEFAULT_SPECIAL_CHAR.data();
result += getServiceRole();
result += NECommon::DEFAULT_SPECIAL_CHAR.data();
result += getServiceName();
return result;
}
| 42.644295 | 153 | 0.700661 | Ali-Nasrolahi |
3ea2676657baf94909ab0c33131c9da3eddbb632 | 7,324 | cpp | C++ | src/ai/weapons/missile.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 8 | 2018-04-03T23:06:33.000Z | 2021-12-28T18:04:19.000Z | src/ai/weapons/missile.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | null | null | null | src/ai/weapons/missile.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 1 | 2020-07-31T00:23:27.000Z | 2020-07-31T00:23:27.000Z | #include "missile.h"
#include "weapons.h"
#include "../../ObjManager.h"
#include "../../caret.h"
#include "../../trig.h"
#include "../../sound/sound.h"
#include "../../common/misc.h"
#include "../../game.h"
#include "../../player.h"
#include "../../autogen/sprites.h"
#define STATE_WAIT_RECOIL_OVER 1
#define STATE_RECOIL_OVER 2
#define STATE_MISSILE_CAN_EXPLODE 3
struct MissileSettings
{
int maxspeed; // max speed of missile
int hitrange; //
int lifetime; // number of boomflashes to create on impact
int boomrange; // max dist away to create the boomflashes
int boomdamage; // damage dealt by contact with a boomflash (AoE damage)
}
missile_settings[] =
{
// Level 1-3 regular missile
// maxspd hit, life, range, bmdmg
{0xA00, 16, 10, 16, 1},
{0xA00, 16, 15, 32, 1},
{0xA00, 16, 5, 40, 1},
// Level 1-3 super missile
// maxspd hit, life, range, bmdmg
{0x1400, 12, 10, 16, 2},
{0x1400, 12, 14, 32, 2},
{0x1400, 12, 6, 40, 2}
};
INITFUNC(AIRoutines)
{
AFTERMOVE(OBJ_MISSILE_SHOT, ai_missile_shot);
AFTERMOVE(OBJ_SUPERMISSILE_SHOT, ai_missile_shot);
ONTICK(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner_tick);
AFTERMOVE(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner);
}
/*
void c------------------------------() {}
*/
void ai_missile_shot(Object *o)
{
int index = o->shot.level + ((o->type == OBJ_SUPERMISSILE_SHOT) ? 3 : 0);
MissileSettings *settings = &missile_settings[index];
if (o->state == 0)
{
o->shot.damage = 0;
if (o->shot.level == 2)
{
// initialize wavey effect
o->xmark = o->x;
o->ymark = o->y;
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
// don't let it explode until the "recoil" effect is over.
o->state = STATE_WAIT_RECOIL_OVER;
// record position we were fired at (we won't explode until we pass it)
o->xmark2 = player->x;
o->ymark2 = player->y;
}
else
{
o->state = STATE_MISSILE_CAN_EXPLODE;
}
}
// accelerate according to current type and level of missile
// don't use LIMITX here as it can mess up recoil of level 3 super missiles
switch(o->shot.dir)
{
case RIGHT:
o->xinertia += o->shot.accel;
if (o->xinertia > settings->maxspeed) o->xinertia = settings->maxspeed;
break;
case LEFT:
o->xinertia -= o->shot.accel;
if (o->xinertia < -settings->maxspeed) o->xinertia = -settings->maxspeed;
break;
case UP:
o->yinertia -= o->shot.accel;
if (o->yinertia < -settings->maxspeed) o->yinertia = -settings->maxspeed;
break;
case DOWN:
o->yinertia += o->shot.accel;
if (o->yinertia > settings->maxspeed) o->yinertia = settings->maxspeed;
break;
}
// wavey effect for level 3
// (markx/y is used as a "speed" value here)
if (o->shot.level == 2)
{
if (o->shot.dir == LEFT || o->shot.dir == RIGHT)
{
if (o->y >= o->ymark) o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->yinertia += o->speed;
}
else
{
if (o->x >= o->xmark) o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->xinertia += o->speed;
}
}
// check if we hit an enemy
// level 3 missiles can not blow up while they are "recoiling"
// what we do is first wait until they're traveling in the direction
// they're pointing, then wait till they pass the player's original position.
switch(o->state)
{
case STATE_WAIT_RECOIL_OVER:
switch(o->shot.dir)
{
case LEFT: if (o->xinertia <= 0) o->state = STATE_RECOIL_OVER; break;
case RIGHT: if (o->xinertia >= 0) o->state = STATE_RECOIL_OVER; break;
case UP: if (o->yinertia <= 0) o->state = STATE_RECOIL_OVER; break;
case DOWN: if (o->yinertia >= 0) o->state = STATE_RECOIL_OVER; break;
}
if (o->state != STATE_RECOIL_OVER)
break;
case STATE_RECOIL_OVER:
switch(o->shot.dir)
{
case LEFT: if (o->x <= o->xmark2-(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
case RIGHT: if (o->x >= o->xmark2+(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
case UP: if (o->y <= o->ymark2-(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
case DOWN: if (o->y >= o->ymark2+(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
}
if (o->state != STATE_MISSILE_CAN_EXPLODE)
break;
case STATE_MISSILE_CAN_EXPLODE:
{
bool blow_up = false;
if (damage_enemies(o))
{
blow_up = true;
}
else
{ // check if we hit a wall
if (o->shot.dir==LEFT && o->blockl) blow_up = true;
else if (o->shot.dir==RIGHT && o->blockr) blow_up = true;
else if (o->shot.dir==UP && o->blocku) blow_up = true;
else if (o->shot.dir==DOWN && o->blockd) blow_up = true;
}
if (blow_up)
{
sound(SND_MISSILE_HIT);
// create the boom-spawner object for the flashes, smoke, and AoE damage
int y = o->CenterY();
if (o->shot.dir==LEFT || o->shot.dir==RIGHT) y-=3*CSFI;
Object *sp = CreateBullet(o->CenterX(), y, OBJ_MISSILE_BOOM_SPAWNER);
sp->shot.boomspawner.range = settings->hitrange;
sp->shot.boomspawner.booms_left = settings->lifetime;
sp->shot.damage = settings->boomdamage;
sp->shot.level = settings->boomdamage;
o->Delete();
return;
}
}
break;
}
if (--o->shot.ttl < 0)
shot_dissipate(o, EFFECT_STARPOOF);
// smoke trails
if (++o->timer > 2)
{
o->timer = 0;
Caret *trail = effect(o->CenterX() - o->xinertia, \
o->CenterY() - o->yinertia, EFFECT_SMOKETRAIL);
const int trailspd = 0x400;
switch(o->shot.dir)
{
case LEFT: trail->xinertia = trailspd; trail->y -= (2 * CSFI); break;
case RIGHT: trail->xinertia = -trailspd; trail->y -= (2 * CSFI); break;
case UP: trail->yinertia = trailspd; trail->x -= (1 * CSFI); break;
case DOWN: trail->yinertia = -trailspd; trail->x -= (1 * CSFI); break;
}
}
}
void ai_missile_boom_spawner(Object *o)
{
if (o->state == 0)
{
o->state = 1;
o->timer = 0;
o->xmark = o->x;
o->ymark = o->y;
// give us the same bounding box as the boomflash effects
o->sprite = SPR_BOOMFLASH;
o->invisible = true;
}
if (!(o->shot.boomspawner.booms_left % 3))
{
int range = 0;
switch (o->shot.level)
{
case 1:
range = 16;
break;
case 2:
range = 32;
break;
case 3:
range = 40;
break;
}
int x = o->CenterX() + (random(-range, range) * CSFI);
int y = o->CenterY() + (random(-range, range) * CSFI);
effect(x,y, EFFECT_BOOMFLASH);
missilehitsmoke(x,y, o->shot.boomspawner.range);
}
if (--o->shot.boomspawner.booms_left < 0)
o->Delete();
}
void ai_missile_boom_spawner_tick(Object *o)
{
damage_all_enemies_in_bb(o, FLAG_INVULNERABLE, o->CenterX(), o->CenterY(), o->shot.boomspawner.range);
}
static void missilehitsmoke(int x, int y, int range)
{
int smokex = x + (random(-range, range) * CSFI);
int smokey = y + (random(-range, range) * CSFI);
Object *smoke;
for(int i=0;i<2;i++)
{
smoke = CreateObject(smokex, smokey, OBJ_SMOKE_CLOUD);
smoke->sprite = SPR_MISSILEHITSMOKE;
vector_from_angle(random(0,255), random(0x100,0x3ff), &smoke->xinertia, &smoke->yinertia);
}
}
| 26.157143 | 103 | 0.613736 | sodomon2 |
3ea41cb0ef6c7267287783073d38fa2857e83765 | 16,310 | hpp | C++ | Software/STM32CubeDemo/RotaryEncoderWithDisplay/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/Circle.hpp | MitkoDyakov/RED | 3bacb4df47867bbbf23c3c02d0ea1f8faa8d5779 | [
"MIT"
] | 15 | 2021-09-21T13:55:54.000Z | 2022-03-08T14:05:39.000Z | Software/STM32CubeDemo/RotaryEncoderWithDisplay/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/Circle.hpp | DynamixYANG/Roendi | 2f6703d63922071fd0dfc8e4d2c9bba95ea04f08 | [
"MIT"
] | 7 | 2021-09-22T07:56:52.000Z | 2022-03-21T17:39:34.000Z | Software/STM32CubeDemo/RotaryEncoderWithDisplay/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/Circle.hpp | DynamixYANG/Roendi | 2f6703d63922071fd0dfc8e4d2c9bba95ea04f08 | [
"MIT"
] | 1 | 2022-03-07T07:51:50.000Z | 2022-03-07T07:51:50.000Z | /******************************************************************************
* Copyright (c) 2018(-2021) STMicroelectronics.
* All rights reserved.
*
* This file is part of the TouchGFX 4.17.0 distribution.
*
* This software is licensed under terms that can be found in the LICENSE file in
* the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
*******************************************************************************/
/**
* @file touchgfx/widgets/canvas/Circle.hpp
*
* Declares the touchgfx::Circle class.
*/
#ifndef TOUCHGFX_CIRCLE_HPP
#define TOUCHGFX_CIRCLE_HPP
#include <touchgfx/hal/Types.hpp>
#include <touchgfx/widgets/canvas/CWRUtil.hpp>
#include <touchgfx/widgets/canvas/Canvas.hpp>
#include <touchgfx/widgets/canvas/CanvasWidget.hpp>
namespace touchgfx
{
/**
* Simple widget capable of drawing a circle, or part of a circle (an arc). The Circle can be
* filled or be drawn as a simple line along the circumference of the circle. Several
* parameters of the circle can be changed: Center, radius, line width, line cap, start
* angle and end angle.
*
* @note Since the underlying CanwasWidgetRenderer only supports straight lines, the circle is
* drawn using many small straight lines segments. The granularity can be adjusted to
* match the requirements - large circles need more line segments, small circles need
* fewer line segments, to look smooth and round.
* @note All circle parameters are internally handled as CWRUtil::Q5 which means that floating
* point values are rounded down to a fixed number of binary digits, for example:
* @code
* Circle circle;
* circle.setCircle(1.1f, 1.1f, 0.9); // Will use (35/32, 35/32, 28/32) = (1.09375f, 1.09375f, 0.875f)
* int x, y, r;
* circle.getCenter(&x, &y); // Will return (1, 1)
* circle.getRadius(&r); // Will return 0
* @endcode.
*/
class Circle : public CanvasWidget
{
public:
Circle();
/**
* Sets the center and radius of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param x The x coordinate of center.
* @param y The y coordinate of center.
* @param r The radius.
*
* @see setCenter, setRadius
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setCircle(const T x, const T y, const T r)
{
setCenter<T>(x, y);
setRadius<T>(r);
}
/**
* Sets the center and radius of the Circle.
*
* @param x The x coordinate of center.
* @param y The y coordinate of center.
* @param r The radius.
*
* @see setCenter, setRadius
*
* @note The area containing the Circle is not invalidated.
*/
void setCircle(const int16_t x, const int16_t y, const int16_t r)
{
setCircle<int>(x, y, r);
}
/**
* Sets the center of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param x The x coordinate of center.
* @param y The y coordinate of center.
*
* @see setRadius, setCircle, getCenter
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setCenter(const T x, const T y)
{
this->circleCenterX = CWRUtil::toQ5(x);
this->circleCenterY = CWRUtil::toQ5(y);
}
/**
* Sets the center of the Circle.
*
* @param x The x coordinate of center.
* @param y The y coordinate of center.
*
* @see setRadius, setCircle, getCenter
*
* @note The area containing the Circle is not invalidated.
*/
void setCenter(const int16_t x, const int16_t y)
{
setCenter<int>(x, y);
}
/**
* Sets the center of the circle / arc in the middle of a pixel. Normally the coordinate is
* between pixel number x and x+1 horizontally and between pixel y and y+1 vertically. This
* function will set the center in the middle of the pixel by adding 0.5 to both x and y.
*
* @param x The x coordinate of the center of the circle.
* @param y The y coordinate of the center of the circle.
*/
void setPixelCenter(int x, int y)
{
int32_t half = (int32_t)CWRUtil::toQ5(1) / 2;
setCenter<CWRUtil::Q5>(CWRUtil::Q5((int32_t)CWRUtil::toQ5(x) + half), CWRUtil::Q5((int32_t)CWRUtil::toQ5(y) + half));
}
/**
* Gets the center coordinates of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] x The x coordinate of the center rounded down to the precision of T.
* @param [out] y The y coordinate of the center rounded down to the precision of T.
*
* @see setCenter
*/
template <typename T>
void getCenter(T& x, T& y) const
{
x = circleCenterX.to<T>();
y = circleCenterY.to<T>();
}
/**
* Sets the radius of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param r The radius.
*
* @see setCircle, setCenter, getRadius
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setRadius(const T r)
{
this->circleRadius = CWRUtil::toQ5(r);
}
/**
* Gets the radius of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] r The radius rounded down to the precision of T.
*/
template <typename T>
void getRadius(T& r) const
{
r = circleRadius.to<T>();
}
/**
* Sets the start and end angles in degrees of the Circle arc. 0 degrees is straight up
* (12 o'clock) and 90 degrees is to the left (3 o'clock). Any positive or negative
* degrees can be used to specify the part of the Circle to draw.
*
* @tparam T Generic type parameter, either int or float.
* @param startAngle The start degrees.
* @param endAngle The end degrees.
*
* @see getArc, updateArcStart, updateArcEnd, updateArc
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setArc(const T startAngle, const T endAngle)
{
circleArcAngleStart = CWRUtil::toQ5(startAngle);
circleArcAngleEnd = CWRUtil::toQ5(endAngle);
}
/**
* Sets the start and end angles in degrees of the Circle arc. 0 degrees is straight up
* (12 o'clock) and 90 degrees is to the left (3 o'clock). Any positive or negative
* degrees can be used to specify the part of the Circle to draw.
*
* @param startAngle The start degrees.
* @param endAngle The end degrees.
*
* @see getArc, updateArcStart, updateArcEnd, updateArc
*
* @note The area containing the Circle is not invalidated.
*/
void setArc(const int16_t startAngle, const int16_t endAngle)
{
setArc<int>(startAngle, endAngle);
}
/**
* Gets the start and end angles in degrees for the circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] startAngle The start angle rounded down to the precision of T.
* @param [out] endAngle The end angle rounded down to the precision of T.
*
* @see setArc
*/
template <typename T>
void getArc(T& startAngle, T& endAngle) const
{
startAngle = circleArcAngleStart.to<T>();
endAngle = circleArcAngleEnd.to<T>();
}
/**
* Gets the start angle in degrees for the arc.
*
* @return The starting angle for the arc rounded down to an integer.
*
* @see getArc, setArc
*/
int16_t getArcStart() const
{
return circleArcAngleStart.to<int>();
}
/**
* Gets the start angle in degrees for the arc.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] angle The starting angle rounded down to the precision of T.
*
* @see getArc, setArc
*/
template <typename T>
void getArcStart(T& angle) const
{
angle = circleArcAngleStart.to<T>();
}
/**
* Gets the end angle in degrees for the arc.
*
* @return The end angle for the arc rounded down to an integer.
*
* @see getArc, setArc
*/
int16_t getArcEnd() const
{
return circleArcAngleEnd.to<int>();
}
/**
* Gets the end angle in degrees for the arc.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] angle The end angle rounded down to the precision of T.
*/
template <typename T>
void getArcEnd(T& angle) const
{
angle = circleArcAngleEnd.to<T>();
}
/**
* Updates the start angle in degrees for this Circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param startAngle The start angle in degrees.
*
* @see setArc, updateArcEnd, updateArc
*
* @note The area containing the updated Circle arc is invalidated.
*/
template <typename T>
void updateArcStart(const T startAngle)
{
CWRUtil::Q5 startAngleQ5 = CWRUtil::toQ5(startAngle);
if (circleArcAngleStart == startAngleQ5)
{
return;
}
Rect minimalRect = getMinimalRectForUpdatedStartAngle(startAngleQ5);
circleArcAngleStart = startAngleQ5;
invalidateRect(minimalRect);
}
/**
* Updates the end angle in degrees for this Circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param endAngle The end angle in degrees.
*
* @see setArc, updateArcStart, updateArc
*
* @note The area containing the updated Circle arc is invalidated.
*/
template <typename T>
void updateArcEnd(const T endAngle)
{
CWRUtil::Q5 endAngleQ5 = CWRUtil::toQ5(endAngle);
if (circleArcAngleEnd == endAngleQ5)
{
return;
}
Rect minimalRect = getMinimalRectForUpdatedEndAngle(endAngleQ5);
circleArcAngleEnd = endAngleQ5;
invalidateRect(minimalRect);
}
/**
* Updates the start and end angle in degrees for this Circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param startAngle The new start angle in degrees.
* @param endAngle The new end angle in degrees.
*
* @see setArc, getArc, updateArcStart, updateArcEnd
*
* @note The areas containing the updated Circle arcs are invalidated. As little as possible
* will be invalidated for best performance.
*/
template <typename T>
void updateArc(const T startAngle, const T endAngle)
{
updateArc(CWRUtil::toQ5(startAngle), CWRUtil::toQ5(endAngle));
}
/**
* Sets the line width for this Circle. If the line width is set to zero, the circle
* will be filled.
*
* @tparam T Generic type parameter, either int or float.
* @param width The width of the line measured in pixels.
*
* @note The area containing the Circle is not invalidated.
* @note if the new line with is smaller than the old width, the circle should be invalidated
* before updating the width to ensure that the old circle is completely erased.
*/
template <typename T>
void setLineWidth(const T width)
{
this->circleLineWidth = CWRUtil::toQ5(width);
}
/**
* Gets line width.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] width The line width rounded down to the precision of T.
*
* @see setLineWidth
*/
template <typename T>
void getLineWidth(T& width) const
{
width = circleLineWidth.to<T>();
}
/**
* Sets precision of the Circle drawing function. The number given as precision is the
* number of degrees used as step counter when drawing the line fragments around the
* circumference of the circle, five being a reasonable value. Higher values results in
* less nice circles but faster rendering and possibly sufficient for very small
* circles. Large circles might require a precision smaller than five to make the edge
* of the circle look nice and smooth.
*
* @param precision The precision measured in degrees.
*
* @note The circle is not invalidated.
*/
void setPrecision(const int precision);
/**
* Gets the precision of the circle drawing function. The precision is the number of
* degrees used as step counter when drawing smaller line fragments around the
* circumference of the circle, the default being 5.
*
* @return The precision.
*
* @see setPrecision
*/
int getPrecision() const;
/**
* Sets the precision of the ends of the Circle arc. The precision is given in degrees
* where 180 is the default which results in a square ended arc (aka "butt cap"). 90
* will draw "an arrow head" and smaller values gives a round cap. Larger values of
* precision results in faster rendering of the circle.
*
* @param precision The new cap precision.
*
* @note The circle is not invalidated.
* @note The cap precision is not used if the circle is filled (if line width is zero) or when
* a full circle is drawn.
*/
void setCapPrecision(const int precision);
/**
* Gets the precision of the ends of the Circle arc.
*
* @return The cap precision in degrees.
*
* @see getCapPrecision
*/
int getCapPrecision() const;
virtual bool drawCanvasWidget(const Rect& invalidatedArea) const;
virtual Rect getMinimalRect() const;
/**
* Gets minimal rectangle containing a given circle arc using the set line width.
*
* @param arcStart The arc start.
* @param arcEnd The arc end.
*
* @return The minimal rectangle.
*/
Rect getMinimalRect(int16_t arcStart, int16_t arcEnd) const;
/**
* Gets minimal rectangle containing a given circle arc using the set line width.
*
* @param arcStart The arc start.
* @param arcEnd The arc end.
*
* @return The minimal rectangle.
*/
Rect getMinimalRect(CWRUtil::Q5 arcStart, CWRUtil::Q5 arcEnd) const;
protected:
/**
* Updates the start and end angle in degrees for this Circle arc.
*
* @param setStartAngleQ5 The new start angle in degrees.
* @param setEndAngleQ5 The new end angle in degrees.
*
* @see setArc, getArc, updateArcStart, updateArcEnd
*
* @note The areas containing the updated Circle arcs are invalidated. As little as possible
* will be invalidated for best performance.
*/
void updateArc(const CWRUtil::Q5 setStartAngleQ5, const CWRUtil::Q5 setEndAngleQ5);
private:
CWRUtil::Q5 circleCenterX;
CWRUtil::Q5 circleCenterY;
CWRUtil::Q5 circleRadius;
CWRUtil::Q5 circleArcAngleStart;
CWRUtil::Q5 circleArcAngleEnd;
CWRUtil::Q5 circleLineWidth;
uint8_t circleArcIncrement;
uint8_t circleCapArcIncrement;
void moveToAR2(Canvas& canvas, const CWRUtil::Q5& angle, const CWRUtil::Q5& r2) const;
void lineToAR2(Canvas& canvas, const CWRUtil::Q5& angle, const CWRUtil::Q5& r2) const;
void lineToXYAR2(Canvas& canvas, const CWRUtil::Q5& x, const CWRUtil::Q5& y, const CWRUtil::Q5& angle, const CWRUtil::Q5& r2) const;
void updateMinMaxAR(const CWRUtil::Q5& a, const CWRUtil::Q5& r2, CWRUtil::Q5& xMin, CWRUtil::Q5& xMax, CWRUtil::Q5& yMin, CWRUtil::Q5& yMax) const;
void updateMinMaxXY(const CWRUtil::Q5& xNew, const CWRUtil::Q5& yNew, CWRUtil::Q5& xMin, CWRUtil::Q5& xMax, CWRUtil::Q5& yMin, CWRUtil::Q5& yMax) const;
void calculateMinimalRect(CWRUtil::Q5 arcStart, CWRUtil::Q5 arcEnd, CWRUtil::Q5& xMin, CWRUtil::Q5& xMax, CWRUtil::Q5& yMin, CWRUtil::Q5& yMax) const;
Rect getMinimalRectForUpdatedStartAngle(const CWRUtil::Q5& startAngleQ5) const;
Rect getMinimalRectForUpdatedEndAngle(const CWRUtil::Q5& endAngleQ5) const;
};
} // namespace touchgfx
#endif // TOUCHGFX_CIRCLE_HPP
| 33.150407 | 156 | 0.633415 | MitkoDyakov |
3ea66c0035b7a7c05090e3317f1862b8f5d21564 | 53,873 | cc | C++ | proto/rpc.pb.cc | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | null | null | null | proto/rpc.pb.cc | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | 5 | 2018-05-30T03:09:10.000Z | 2018-06-02T22:56:05.000Z | proto/rpc.pb.cc | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: rpc.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "rpc.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 paxoskv {
class KVOperatorDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<KVOperator>
_instance;
} _KVOperator_default_instance_;
class KVDataDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<KVData>
_instance;
} _KVData_default_instance_;
class KVResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<KVResponse>
_instance;
} _KVResponse_default_instance_;
namespace protobuf_rpc_2eproto {
namespace {
::google::protobuf::Metadata file_level_metadata[3];
} // namespace
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField
const TableStruct::entries[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField
const TableStruct::aux[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
::google::protobuf::internal::AuxillaryParseTableField(),
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const
TableStruct::schema[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
};
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, key_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, version_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, operator__),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, sid_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, version_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, isdeleted_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, data_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, ret_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, master_nodeid_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(KVOperator)},
{ 10, -1, sizeof(KVData)},
{ 18, -1, sizeof(KVResponse)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_KVOperator_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_KVData_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_KVResponse_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"rpc.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3);
}
} // namespace
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
_KVOperator_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_KVOperator_default_instance_);_KVData_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_KVData_default_instance_);_KVResponse_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_KVResponse_default_instance_);_KVResponse_default_instance_._instance.get_mutable()->data_ = const_cast< ::paxoskv::KVData*>(
::paxoskv::KVData::internal_default_instance());
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
namespace {
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\trpc.proto\022\007paxoskv\"X\n\nKVOperator\022\013\n\003ke"
"y\030\001 \001(\t\022\r\n\005value\030\002 \001(\014\022\017\n\007version\030\003 \001(\004\022"
"\020\n\010operator\030\004 \001(\r\022\013\n\003sid\030\005 \001(\r\";\n\006KVData"
"\022\r\n\005value\030\001 \001(\014\022\017\n\007version\030\002 \001(\004\022\021\n\tisde"
"leted\030\003 \001(\010\"O\n\nKVResponse\022\035\n\004data\030\001 \001(\0132"
"\017.paxoskv.KVData\022\013\n\003ret\030\002 \001(\005\022\025\n\rmaster_"
"nodeid\030\003 \001(\0042\345\001\n\tKVService\0221\n\003Put\022\023.paxo"
"skv.KVOperator\032\023.paxoskv.KVResponse\"\000\0226\n"
"\010GetLocal\022\023.paxoskv.KVOperator\032\023.paxoskv"
".KVResponse\"\000\0227\n\tGetGlobal\022\023.paxoskv.KVO"
"perator\032\023.paxoskv.KVResponse\"\000\0224\n\006Delete"
"\022\023.paxoskv.KVOperator\032\023.paxoskv.KVRespon"
"se\"\000b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 492);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"rpc.proto", &protobuf_RegisterTypes);
}
} // anonymous namespace
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_rpc_2eproto
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int KVOperator::kKeyFieldNumber;
const int KVOperator::kValueFieldNumber;
const int KVOperator::kVersionFieldNumber;
const int KVOperator::kOperatorFieldNumber;
const int KVOperator::kSidFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
KVOperator::KVOperator()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_rpc_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:paxoskv.KVOperator)
}
KVOperator::KVOperator(const KVOperator& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.key().size() > 0) {
key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_);
}
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
::memcpy(&version_, &from.version_,
static_cast<size_t>(reinterpret_cast<char*>(&sid_) -
reinterpret_cast<char*>(&version_)) + sizeof(sid_));
// @@protoc_insertion_point(copy_constructor:paxoskv.KVOperator)
}
void KVOperator::SharedCtor() {
key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sid_) -
reinterpret_cast<char*>(&version_)) + sizeof(sid_));
_cached_size_ = 0;
}
KVOperator::~KVOperator() {
// @@protoc_insertion_point(destructor:paxoskv.KVOperator)
SharedDtor();
}
void KVOperator::SharedDtor() {
key_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVOperator::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* KVOperator::descriptor() {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const KVOperator& KVOperator::default_instance() {
protobuf_rpc_2eproto::InitDefaults();
return *internal_default_instance();
}
KVOperator* KVOperator::New(::google::protobuf::Arena* arena) const {
KVOperator* n = new KVOperator;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void KVOperator::Clear() {
// @@protoc_insertion_point(message_clear_start:paxoskv.KVOperator)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sid_) -
reinterpret_cast<char*>(&version_)) + sizeof(sid_));
_internal_metadata_.Clear();
}
bool KVOperator::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:paxoskv.KVOperator)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string key = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_key()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->key().data(), static_cast<int>(this->key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"paxoskv.KVOperator.key"));
} else {
goto handle_unusual;
}
break;
}
// bytes value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
goto handle_unusual;
}
break;
}
// uint64 version = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &version_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 operator = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &operator__)));
} else {
goto handle_unusual;
}
break;
}
// uint32 sid = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &sid_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:paxoskv.KVOperator)
return true;
failure:
// @@protoc_insertion_point(parse_failure:paxoskv.KVOperator)
return false;
#undef DO_
}
void KVOperator::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:paxoskv.KVOperator)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string key = 1;
if (this->key().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->key().data(), static_cast<int>(this->key().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"paxoskv.KVOperator.key");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->key(), output);
}
// bytes value = 2;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->value(), output);
}
// uint64 version = 3;
if (this->version() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(3, this->version(), output);
}
// uint32 operator = 4;
if (this->operator_() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(4, this->operator_(), output);
}
// uint32 sid = 5;
if (this->sid() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->sid(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:paxoskv.KVOperator)
}
::google::protobuf::uint8* KVOperator::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:paxoskv.KVOperator)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string key = 1;
if (this->key().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->key().data(), static_cast<int>(this->key().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"paxoskv.KVOperator.key");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->key(), target);
}
// bytes value = 2;
if (this->value().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
2, this->value(), target);
}
// uint64 version = 3;
if (this->version() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(3, this->version(), target);
}
// uint32 operator = 4;
if (this->operator_() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(4, this->operator_(), target);
}
// uint32 sid = 5;
if (this->sid() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(5, this->sid(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:paxoskv.KVOperator)
return target;
}
size_t KVOperator::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:paxoskv.KVOperator)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// string key = 1;
if (this->key().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->key());
}
// bytes value = 2;
if (this->value().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->value());
}
// uint64 version = 3;
if (this->version() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->version());
}
// uint32 operator = 4;
if (this->operator_() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->operator_());
}
// uint32 sid = 5;
if (this->sid() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->sid());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void KVOperator::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:paxoskv.KVOperator)
GOOGLE_DCHECK_NE(&from, this);
const KVOperator* source =
::google::protobuf::internal::DynamicCastToGenerated<const KVOperator>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:paxoskv.KVOperator)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:paxoskv.KVOperator)
MergeFrom(*source);
}
}
void KVOperator::MergeFrom(const KVOperator& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:paxoskv.KVOperator)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.key().size() > 0) {
key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_);
}
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
if (from.version() != 0) {
set_version(from.version());
}
if (from.operator_() != 0) {
set_operator_(from.operator_());
}
if (from.sid() != 0) {
set_sid(from.sid());
}
}
void KVOperator::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:paxoskv.KVOperator)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void KVOperator::CopyFrom(const KVOperator& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:paxoskv.KVOperator)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool KVOperator::IsInitialized() const {
return true;
}
void KVOperator::Swap(KVOperator* other) {
if (other == this) return;
InternalSwap(other);
}
void KVOperator::InternalSwap(KVOperator* other) {
using std::swap;
key_.Swap(&other->key_);
value_.Swap(&other->value_);
swap(version_, other->version_);
swap(operator__, other->operator__);
swap(sid_, other->sid_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata KVOperator::GetMetadata() const {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// KVOperator
// string key = 1;
void KVOperator::clear_key() {
key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& KVOperator::key() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.key)
return key_.GetNoArena();
}
void KVOperator::set_key(const ::std::string& value) {
key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.key)
}
#if LANG_CXX11
void KVOperator::set_key(::std::string&& value) {
key_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:paxoskv.KVOperator.key)
}
#endif
void KVOperator::set_key(const char* value) {
GOOGLE_DCHECK(value != NULL);
key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:paxoskv.KVOperator.key)
}
void KVOperator::set_key(const char* value, size_t size) {
key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:paxoskv.KVOperator.key)
}
::std::string* KVOperator::mutable_key() {
// @@protoc_insertion_point(field_mutable:paxoskv.KVOperator.key)
return key_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* KVOperator::release_key() {
// @@protoc_insertion_point(field_release:paxoskv.KVOperator.key)
return key_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVOperator::set_allocated_key(::std::string* key) {
if (key != NULL) {
} else {
}
key_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), key);
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVOperator.key)
}
// bytes value = 2;
void KVOperator::clear_value() {
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& KVOperator::value() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.value)
return value_.GetNoArena();
}
void KVOperator::set_value(const ::std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.value)
}
#if LANG_CXX11
void KVOperator::set_value(::std::string&& value) {
value_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:paxoskv.KVOperator.value)
}
#endif
void KVOperator::set_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:paxoskv.KVOperator.value)
}
void KVOperator::set_value(const void* value, size_t size) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:paxoskv.KVOperator.value)
}
::std::string* KVOperator::mutable_value() {
// @@protoc_insertion_point(field_mutable:paxoskv.KVOperator.value)
return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* KVOperator::release_value() {
// @@protoc_insertion_point(field_release:paxoskv.KVOperator.value)
return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVOperator::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
}
value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVOperator.value)
}
// uint64 version = 3;
void KVOperator::clear_version() {
version_ = GOOGLE_ULONGLONG(0);
}
::google::protobuf::uint64 KVOperator::version() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.version)
return version_;
}
void KVOperator::set_version(::google::protobuf::uint64 value) {
version_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.version)
}
// uint32 operator = 4;
void KVOperator::clear_operator_() {
operator__ = 0u;
}
::google::protobuf::uint32 KVOperator::operator_() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.operator)
return operator__;
}
void KVOperator::set_operator_(::google::protobuf::uint32 value) {
operator__ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.operator)
}
// uint32 sid = 5;
void KVOperator::clear_sid() {
sid_ = 0u;
}
::google::protobuf::uint32 KVOperator::sid() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.sid)
return sid_;
}
void KVOperator::set_sid(::google::protobuf::uint32 value) {
sid_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.sid)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int KVData::kValueFieldNumber;
const int KVData::kVersionFieldNumber;
const int KVData::kIsdeletedFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
KVData::KVData()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_rpc_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:paxoskv.KVData)
}
KVData::KVData(const KVData& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
::memcpy(&version_, &from.version_,
static_cast<size_t>(reinterpret_cast<char*>(&isdeleted_) -
reinterpret_cast<char*>(&version_)) + sizeof(isdeleted_));
// @@protoc_insertion_point(copy_constructor:paxoskv.KVData)
}
void KVData::SharedCtor() {
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&isdeleted_) -
reinterpret_cast<char*>(&version_)) + sizeof(isdeleted_));
_cached_size_ = 0;
}
KVData::~KVData() {
// @@protoc_insertion_point(destructor:paxoskv.KVData)
SharedDtor();
}
void KVData::SharedDtor() {
value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVData::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* KVData::descriptor() {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const KVData& KVData::default_instance() {
protobuf_rpc_2eproto::InitDefaults();
return *internal_default_instance();
}
KVData* KVData::New(::google::protobuf::Arena* arena) const {
KVData* n = new KVData;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void KVData::Clear() {
// @@protoc_insertion_point(message_clear_start:paxoskv.KVData)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&isdeleted_) -
reinterpret_cast<char*>(&version_)) + sizeof(isdeleted_));
_internal_metadata_.Clear();
}
bool KVData::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:paxoskv.KVData)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes value = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
goto handle_unusual;
}
break;
}
// uint64 version = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &version_)));
} else {
goto handle_unusual;
}
break;
}
// bool isdeleted = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &isdeleted_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:paxoskv.KVData)
return true;
failure:
// @@protoc_insertion_point(parse_failure:paxoskv.KVData)
return false;
#undef DO_
}
void KVData::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:paxoskv.KVData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes value = 1;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->value(), output);
}
// uint64 version = 2;
if (this->version() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(2, this->version(), output);
}
// bool isdeleted = 3;
if (this->isdeleted() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->isdeleted(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:paxoskv.KVData)
}
::google::protobuf::uint8* KVData::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:paxoskv.KVData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes value = 1;
if (this->value().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->value(), target);
}
// uint64 version = 2;
if (this->version() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(2, this->version(), target);
}
// bool isdeleted = 3;
if (this->isdeleted() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->isdeleted(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:paxoskv.KVData)
return target;
}
size_t KVData::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:paxoskv.KVData)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// bytes value = 1;
if (this->value().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->value());
}
// uint64 version = 2;
if (this->version() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->version());
}
// bool isdeleted = 3;
if (this->isdeleted() != 0) {
total_size += 1 + 1;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void KVData::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:paxoskv.KVData)
GOOGLE_DCHECK_NE(&from, this);
const KVData* source =
::google::protobuf::internal::DynamicCastToGenerated<const KVData>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:paxoskv.KVData)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:paxoskv.KVData)
MergeFrom(*source);
}
}
void KVData::MergeFrom(const KVData& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:paxoskv.KVData)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
if (from.version() != 0) {
set_version(from.version());
}
if (from.isdeleted() != 0) {
set_isdeleted(from.isdeleted());
}
}
void KVData::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:paxoskv.KVData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void KVData::CopyFrom(const KVData& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:paxoskv.KVData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool KVData::IsInitialized() const {
return true;
}
void KVData::Swap(KVData* other) {
if (other == this) return;
InternalSwap(other);
}
void KVData::InternalSwap(KVData* other) {
using std::swap;
value_.Swap(&other->value_);
swap(version_, other->version_);
swap(isdeleted_, other->isdeleted_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata KVData::GetMetadata() const {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// KVData
// bytes value = 1;
void KVData::clear_value() {
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& KVData::value() const {
// @@protoc_insertion_point(field_get:paxoskv.KVData.value)
return value_.GetNoArena();
}
void KVData::set_value(const ::std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:paxoskv.KVData.value)
}
#if LANG_CXX11
void KVData::set_value(::std::string&& value) {
value_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:paxoskv.KVData.value)
}
#endif
void KVData::set_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:paxoskv.KVData.value)
}
void KVData::set_value(const void* value, size_t size) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:paxoskv.KVData.value)
}
::std::string* KVData::mutable_value() {
// @@protoc_insertion_point(field_mutable:paxoskv.KVData.value)
return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* KVData::release_value() {
// @@protoc_insertion_point(field_release:paxoskv.KVData.value)
return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVData::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
}
value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVData.value)
}
// uint64 version = 2;
void KVData::clear_version() {
version_ = GOOGLE_ULONGLONG(0);
}
::google::protobuf::uint64 KVData::version() const {
// @@protoc_insertion_point(field_get:paxoskv.KVData.version)
return version_;
}
void KVData::set_version(::google::protobuf::uint64 value) {
version_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVData.version)
}
// bool isdeleted = 3;
void KVData::clear_isdeleted() {
isdeleted_ = false;
}
bool KVData::isdeleted() const {
// @@protoc_insertion_point(field_get:paxoskv.KVData.isdeleted)
return isdeleted_;
}
void KVData::set_isdeleted(bool value) {
isdeleted_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVData.isdeleted)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int KVResponse::kDataFieldNumber;
const int KVResponse::kRetFieldNumber;
const int KVResponse::kMasterNodeidFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
KVResponse::KVResponse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_rpc_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:paxoskv.KVResponse)
}
KVResponse::KVResponse(const KVResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_data()) {
data_ = new ::paxoskv::KVData(*from.data_);
} else {
data_ = NULL;
}
::memcpy(&master_nodeid_, &from.master_nodeid_,
static_cast<size_t>(reinterpret_cast<char*>(&ret_) -
reinterpret_cast<char*>(&master_nodeid_)) + sizeof(ret_));
// @@protoc_insertion_point(copy_constructor:paxoskv.KVResponse)
}
void KVResponse::SharedCtor() {
::memset(&data_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&ret_) -
reinterpret_cast<char*>(&data_)) + sizeof(ret_));
_cached_size_ = 0;
}
KVResponse::~KVResponse() {
// @@protoc_insertion_point(destructor:paxoskv.KVResponse)
SharedDtor();
}
void KVResponse::SharedDtor() {
if (this != internal_default_instance()) delete data_;
}
void KVResponse::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* KVResponse::descriptor() {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const KVResponse& KVResponse::default_instance() {
protobuf_rpc_2eproto::InitDefaults();
return *internal_default_instance();
}
KVResponse* KVResponse::New(::google::protobuf::Arena* arena) const {
KVResponse* n = new KVResponse;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void KVResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:paxoskv.KVResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == NULL && data_ != NULL) {
delete data_;
}
data_ = NULL;
::memset(&master_nodeid_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&ret_) -
reinterpret_cast<char*>(&master_nodeid_)) + sizeof(ret_));
_internal_metadata_.Clear();
}
bool KVResponse::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:paxoskv.KVResponse)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .paxoskv.KVData data = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_data()));
} else {
goto handle_unusual;
}
break;
}
// int32 ret = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &ret_)));
} else {
goto handle_unusual;
}
break;
}
// uint64 master_nodeid = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &master_nodeid_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:paxoskv.KVResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:paxoskv.KVResponse)
return false;
#undef DO_
}
void KVResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:paxoskv.KVResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .paxoskv.KVData data = 1;
if (this->has_data()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->data_, output);
}
// int32 ret = 2;
if (this->ret() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->ret(), output);
}
// uint64 master_nodeid = 3;
if (this->master_nodeid() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(3, this->master_nodeid(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:paxoskv.KVResponse)
}
::google::protobuf::uint8* KVResponse::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:paxoskv.KVResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .paxoskv.KVData data = 1;
if (this->has_data()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->data_, deterministic, target);
}
// int32 ret = 2;
if (this->ret() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->ret(), target);
}
// uint64 master_nodeid = 3;
if (this->master_nodeid() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(3, this->master_nodeid(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:paxoskv.KVResponse)
return target;
}
size_t KVResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:paxoskv.KVResponse)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// .paxoskv.KVData data = 1;
if (this->has_data()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->data_);
}
// uint64 master_nodeid = 3;
if (this->master_nodeid() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->master_nodeid());
}
// int32 ret = 2;
if (this->ret() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->ret());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void KVResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:paxoskv.KVResponse)
GOOGLE_DCHECK_NE(&from, this);
const KVResponse* source =
::google::protobuf::internal::DynamicCastToGenerated<const KVResponse>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:paxoskv.KVResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:paxoskv.KVResponse)
MergeFrom(*source);
}
}
void KVResponse::MergeFrom(const KVResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:paxoskv.KVResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_data()) {
mutable_data()->::paxoskv::KVData::MergeFrom(from.data());
}
if (from.master_nodeid() != 0) {
set_master_nodeid(from.master_nodeid());
}
if (from.ret() != 0) {
set_ret(from.ret());
}
}
void KVResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:paxoskv.KVResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void KVResponse::CopyFrom(const KVResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:paxoskv.KVResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool KVResponse::IsInitialized() const {
return true;
}
void KVResponse::Swap(KVResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void KVResponse::InternalSwap(KVResponse* other) {
using std::swap;
swap(data_, other->data_);
swap(master_nodeid_, other->master_nodeid_);
swap(ret_, other->ret_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata KVResponse::GetMetadata() const {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// KVResponse
// .paxoskv.KVData data = 1;
bool KVResponse::has_data() const {
return this != internal_default_instance() && data_ != NULL;
}
void KVResponse::clear_data() {
if (GetArenaNoVirtual() == NULL && data_ != NULL) delete data_;
data_ = NULL;
}
const ::paxoskv::KVData& KVResponse::data() const {
const ::paxoskv::KVData* p = data_;
// @@protoc_insertion_point(field_get:paxoskv.KVResponse.data)
return p != NULL ? *p : *reinterpret_cast<const ::paxoskv::KVData*>(
&::paxoskv::_KVData_default_instance_);
}
::paxoskv::KVData* KVResponse::mutable_data() {
if (data_ == NULL) {
data_ = new ::paxoskv::KVData;
}
// @@protoc_insertion_point(field_mutable:paxoskv.KVResponse.data)
return data_;
}
::paxoskv::KVData* KVResponse::release_data() {
// @@protoc_insertion_point(field_release:paxoskv.KVResponse.data)
::paxoskv::KVData* temp = data_;
data_ = NULL;
return temp;
}
void KVResponse::set_allocated_data(::paxoskv::KVData* data) {
delete data_;
data_ = data;
if (data) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVResponse.data)
}
// int32 ret = 2;
void KVResponse::clear_ret() {
ret_ = 0;
}
::google::protobuf::int32 KVResponse::ret() const {
// @@protoc_insertion_point(field_get:paxoskv.KVResponse.ret)
return ret_;
}
void KVResponse::set_ret(::google::protobuf::int32 value) {
ret_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVResponse.ret)
}
// uint64 master_nodeid = 3;
void KVResponse::clear_master_nodeid() {
master_nodeid_ = GOOGLE_ULONGLONG(0);
}
::google::protobuf::uint64 KVResponse::master_nodeid() const {
// @@protoc_insertion_point(field_get:paxoskv.KVResponse.master_nodeid)
return master_nodeid_;
}
void KVResponse::set_master_nodeid(::google::protobuf::uint64 value) {
master_nodeid_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVResponse.master_nodeid)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace paxoskv
// @@protoc_insertion_point(global_scope)
| 34.600514 | 168 | 0.700704 | Phantomape |
3ea9ac90846e2a08614dbdf1312acaaeb792fc77 | 204 | hpp | C++ | 01-brickbreaker/src/brickbreaker/Entity.hpp | fmenozzi/games | f52dbfaf9c7bea76ad91c9ab104ac9d05e0d4b36 | [
"MIT"
] | 2 | 2015-05-23T04:33:56.000Z | 2016-01-29T08:19:49.000Z | 01-brickbreaker/src/brickbreaker/Entity.hpp | fmenozzi/games | f52dbfaf9c7bea76ad91c9ab104ac9d05e0d4b36 | [
"MIT"
] | 2 | 2015-05-23T03:33:36.000Z | 2015-05-23T04:22:26.000Z | 01-brickbreaker/src/brickbreaker/Entity.hpp | fmenozzi/games | f52dbfaf9c7bea76ad91c9ab104ac9d05e0d4b36 | [
"MIT"
] | 2 | 2015-05-23T03:39:12.000Z | 2020-05-04T13:03:02.000Z | #pragma once
#include <SFML/Graphics.hpp>
class Entity
{
public:
bool destroyed{false};
virtual ~Entity() {}
virtual void update() {}
virtual void draw(sf::RenderWindow& mTarget) {}
}; | 15.692308 | 51 | 0.651961 | fmenozzi |
3eaaa8a7c5ea3cb3670d3bf86a69676fd620cf89 | 204 | cpp | C++ | Source/RegionGrowing/Algorithm/SpaceMapping.cpp | timdecode/InteractiveElementPalettes | ea5b7fcd78f8413aa9c770788259fbb944d4778d | [
"MIT"
] | 1 | 2018-09-05T20:55:42.000Z | 2018-09-05T20:55:42.000Z | Source/RegionGrowing/Algorithm/SpaceMapping.cpp | timdecode/InteractiveDiscreteElementPalettes | ea5b7fcd78f8413aa9c770788259fbb944d4778d | [
"MIT"
] | null | null | null | Source/RegionGrowing/Algorithm/SpaceMapping.cpp | timdecode/InteractiveDiscreteElementPalettes | ea5b7fcd78f8413aa9c770788259fbb944d4778d | [
"MIT"
] | null | null | null | //
// SpaceMapping.cpp
// RegionGrowing
//
// Created by Timothy Davison on 2015-09-10.
// Copyright © 2015 EpicGames. All rights reserved.
//
#include "RegionGrowing.h"
#include "SpaceMapping.hpp"
| 17 | 52 | 0.70098 | timdecode |
3eacf107d174a21181edeca324594fd06fc1b4a7 | 1,980 | cpp | C++ | level_zero/tools/source/sysman/firmware/linux/os_firmware_imp_helper_prelim.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | level_zero/tools/source/sysman/firmware/linux/os_firmware_imp_helper_prelim.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | level_zero/tools/source/sysman/firmware/linux/os_firmware_imp_helper_prelim.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2021-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/tools/source/sysman/firmware/linux/os_firmware_imp.h"
const std::string iafPath = "device/";
const std::string iafDirectory = "iaf.";
const std::string pscbin_version = "/pscbin_version";
namespace L0 {
ze_result_t LinuxFirmwareImp::getFirmwareVersion(std::string fwType, zes_firmware_properties_t *pProperties) {
std::string fwVersion;
if (fwType == "PSC") {
std::string path;
path.clear();
std::vector<std::string> list;
// scans the directories present in /sys/class/drm/cardX/device/
ze_result_t result = pSysfsAccess->scanDirEntries(iafPath, list);
if (ZE_RESULT_SUCCESS != result) {
// There should be a device directory
return result;
}
for (const auto &entry : list) {
if (!iafDirectory.compare(entry.substr(0, iafDirectory.length()))) {
// device/iaf.X/pscbin_version, where X is the hardware slot number
path = iafPath + entry + pscbin_version;
}
}
if (path.empty()) {
// This device does not have a PSC Version
return ZE_RESULT_ERROR_NOT_AVAILABLE;
}
std::string pscVersion;
pscVersion.clear();
result = pSysfsAccess->read(path, pscVersion);
if (ZE_RESULT_SUCCESS != result) {
// not able to read PSC version from iaf.x
return result;
}
strncpy_s(static_cast<char *>(pProperties->version), ZES_STRING_PROPERTY_SIZE, pscVersion.c_str(), ZES_STRING_PROPERTY_SIZE);
return result;
}
ze_result_t result = pFwInterface->getFwVersion(fwType, fwVersion);
if (result == ZE_RESULT_SUCCESS) {
strncpy_s(static_cast<char *>(pProperties->version), ZES_STRING_PROPERTY_SIZE, fwVersion.c_str(), ZES_STRING_PROPERTY_SIZE);
}
return result;
}
} // namespace L0 | 35.357143 | 133 | 0.638889 | mattcarter2017 |
3eadd062b33b0c5fa6b004190c0220295624b71a | 2,221 | hpp | C++ | include/gui/pl_report.hpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 4 | 2016-07-05T07:42:07.000Z | 2020-07-15T15:27:22.000Z | include/gui/pl_report.hpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 1 | 2020-05-07T20:58:21.000Z | 2020-05-07T20:58:21.000Z | include/gui/pl_report.hpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013 Matthew Harvey
*
* 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 GUARD_pl_report_hpp_03798236466850264
#define GUARD_pl_report_hpp_03798236466850264
#include "report.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/decimal.hpp>
#include <wx/gdicmn.h>
#include <unordered_map>
namespace dcm
{
// begin forward declarations
class DcmDatabaseConnection;
namespace gui
{
class ReportPanel;
// end forward declarations
class PLReport: public Report
{
public:
PLReport
( ReportPanel* p_parent,
wxSize const& p_size,
DcmDatabaseConnection& p_database_connection,
boost::optional<boost::gregorian::date> const& p_maybe_min_date,
boost::optional<boost::gregorian::date> const& p_maybe_max_date
);
PLReport(PLReport const&) = delete;
PLReport(PLReport&&) = delete;
PLReport& operator=(PLReport const&) = delete;
PLReport& operator=(PLReport&&) = delete;
virtual ~PLReport();
private:
virtual void do_generate() override;
/**
* @returns an initialized optional only if there is a max_date().
*/
boost::optional<int> maybe_num_days_in_period() const;
/**
* Displays "N/A" or the like if p_count is zero. Displays in
* current_row().
*/
void display_mean
( int p_column,
jewel::Decimal const& p_total = jewel::Decimal(0, 0),
int p_count = 0
);
void refresh_map();
void display_body();
typedef std::unordered_map<sqloxx::Id, jewel::Decimal> Map;
Map m_map;
}; // class PLReport
} // namespace gui
} // namespace dcm
#endif // GUARD_pl_report_hpp_03798236466850264
| 24.955056 | 75 | 0.700585 | skybaboon |
3ebdc77b7c2396f6677a1575351482bc9ea52be5 | 2,820 | cpp | C++ | src/historywork/test/HistoryWorkTests.cpp | STORP-Inc/POGchain | 3cf3de0498947fb5d2cf9d985d93a1d4d84ca831 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/historywork/test/HistoryWorkTests.cpp | STORP-Inc/POGchain | 3cf3de0498947fb5d2cf9d985d93a1d4d84ca831 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/historywork/test/HistoryWorkTests.cpp | STORP-Inc/POGchain | 3cf3de0498947fb5d2cf9d985d93a1d4d84ca831 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 POGchain Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "history/HistoryArchiveManager.h"
#include "history/test/HistoryTestsUtils.h"
#include "historywork/CheckSingleLedgerHeaderWork.h"
#include "historywork/WriteVerifiedCheckpointHashesWork.h"
#include "test/TestUtils.h"
#include "test/test.h"
#include "util/Logging.h"
#include "util/Timer.h"
#include "work/WorkScheduler.h"
#include <lib/catch.hpp>
#include <lib/json/json.h>
using namespace POGchain;
using namespace historytestutils;
TEST_CASE("write verified checkpoint hashes", "[historywork]")
{
CatchupSimulation catchupSimulation{};
uint32_t nestedBatchSize = 4;
auto checkpointLedger =
catchupSimulation.getLastCheckpointLedger(5 * nestedBatchSize);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger,
5 * nestedBatchSize);
std::vector<LedgerNumHashPair> pairs =
catchupSimulation.getAllPublishedCheckpoints();
LedgerNumHashPair pair = pairs.back();
auto tmpDir = catchupSimulation.getApp().getTmpDirManager().tmpDir(
"write-checkpoint-hashes-test");
auto file = tmpDir.getName() + "/verified-ledgers.json";
auto& wm = catchupSimulation.getApp().getWorkScheduler();
{
auto w = wm.executeWork<WriteVerifiedCheckpointHashesWork>(
pair, file, nestedBatchSize);
REQUIRE(w->getState() == BasicWork::State::WORK_SUCCESS);
}
// Make sure w is destroyed.
wm.shutdown();
while (wm.getState() != BasicWork::State::WORK_ABORTED)
{
catchupSimulation.getClock().crank();
}
for (auto const& p : pairs)
{
LOG_DEBUG(DEFAULT_LOG, "Verified {} with hash {}", p.first,
hexAbbrev(*p.second));
Hash h = WriteVerifiedCheckpointHashesWork::loadHashFromJsonOutput(
p.first, file);
REQUIRE(h == *p.second);
}
}
TEST_CASE("check single ledger header work", "[historywork]")
{
CatchupSimulation catchupSimulation{};
auto l1 = catchupSimulation.getLastCheckpointLedger(2);
auto l2 = catchupSimulation.getLastCheckpointLedger(4);
catchupSimulation.ensureOfflineCatchupPossible(l1);
auto& app = catchupSimulation.getApp();
auto& lm = app.getLedgerManager();
auto lhhe = lm.getLastClosedLedgerHeader();
catchupSimulation.ensureOfflineCatchupPossible(l2);
auto arch =
app.getHistoryArchiveManager().selectRandomReadableHistoryArchive();
auto& wm = app.getWorkScheduler();
auto w = wm.executeWork<CheckSingleLedgerHeaderWork>(arch, lhhe);
REQUIRE(w->getState() == BasicWork::State::WORK_SUCCESS);
} | 38.630137 | 76 | 0.70461 | STORP-Inc |
3ebe999113f9644e936e78eb1428666558156cdf | 46,533 | hpp | C++ | SimdMask/Intrinscs/sse2.hpp | Const-me/SimdMask | 53f12bae6fb0ded4d9e548400f7bb59cb952b226 | [
"MIT"
] | 1 | 2019-12-08T14:49:58.000Z | 2019-12-08T14:49:58.000Z | SimdMask/Intrinscs/sse2.hpp | Const-me/SimdMask | 53f12bae6fb0ded4d9e548400f7bb59cb952b226 | [
"MIT"
] | null | null | null | SimdMask/Intrinscs/sse2.hpp | Const-me/SimdMask | 53f12bae6fb0ded4d9e548400f7bb59cb952b226 | [
"MIT"
] | null | null | null | // This file is generated automatically by a tool, please don't edit.
#pragma once
#include <emmintrin.h>
#include <immintrin.h>
#include "Implementation/utils.hpp"
namespace Intrinsics
{
namespace Sse
{
// Add packed 8-bit integers in "a" and "b", and store the results in "dst"
inline __m128i XM_CALLCONV add_epi8( __m128i a, __m128i b )
{
return _mm_add_epi8( a, b );
}
// Add packed 16-bit integers in "a" and "b", and store the results in "dst"
inline __m128i XM_CALLCONV add_epi16( __m128i a, __m128i b )
{
return _mm_add_epi16( a, b );
}
// Add packed 32-bit integers in "a" and "b", and store the results in "dst"
inline __m128i XM_CALLCONV add_epi32( __m128i a, __m128i b )
{
return _mm_add_epi32( a, b );
}
// Add packed 64-bit integers in "a" and "b", and store the results in "dst"
inline __m128i XM_CALLCONV add_epi64( __m128i a, __m128i b )
{
return _mm_add_epi64( a, b );
}
// Add packed double-precision floating-point elements in "a" and "b"
inline __m128d XM_CALLCONV add_pd( __m128d a, __m128d b )
{
return _mm_add_pd( a, b );
}
// Add the lower double-precision floating-point element in "a" and "b"
inline __m128d XM_CALLCONV add_sd( __m128d a, __m128d b )
{
return _mm_add_sd( a, b );
}
// Add packed 8-bit integers in "a" and "b" using saturation, and store the results in "dst"
inline __m128i XM_CALLCONV adds_epi8( __m128i a, __m128i b )
{
return _mm_adds_epi8( a, b );
}
// Add packed 16-bit integers in "a" and "b" using saturation, and store the results in "dst"
inline __m128i XM_CALLCONV adds_epi16( __m128i a, __m128i b )
{
return _mm_adds_epi16( a, b );
}
// Add packed unsigned 8-bit integers in "a" and "b" using saturation
inline __m128i XM_CALLCONV adds_epu8( __m128i a, __m128i b )
{
return _mm_adds_epu8( a, b );
}
// Add packed unsigned 16-bit integers in "a" and "b" using saturation
inline __m128i XM_CALLCONV adds_epu16( __m128i a, __m128i b )
{
return _mm_adds_epu16( a, b );
}
// Compute the bitwise AND of packed double-precision floating-point elements in "a" and "b"
inline __m128d XM_CALLCONV and_pd( __m128d a, __m128d b )
{
return _mm_and_pd( a, b );
}
// Compute the bitwise AND of 128 bits (representing integer data) in "a" and "b"
inline __m128i XM_CALLCONV and_all( __m128i a, __m128i b )
{
return _mm_and_si128( a, b );
}
// Compute the bitwise NOT of packed double-precision floating-point elements in "a" and then AND with "b"
inline __m128d XM_CALLCONV andnot_pd( __m128d a, __m128d b )
{
return _mm_andnot_pd( a, b );
}
// Compute the bitwise NOT of 128 bits (representing integer data) in "a" and then AND with "b"
inline __m128i XM_CALLCONV andnot_all( __m128i a, __m128i b )
{
return _mm_andnot_si128( a, b );
}
// Average packed unsigned 8-bit integers in "a" and "b", and store the results in "dst"
inline __m128i XM_CALLCONV avg_epu8( __m128i a, __m128i b )
{
return _mm_avg_epu8( a, b );
}
// Average packed unsigned 16-bit integers in "a" and "b", and store the results in "dst"
inline __m128i XM_CALLCONV avg_epu16( __m128i a, __m128i b )
{
return _mm_avg_epu16( a, b );
}
// Shift "a" left by "imm8" bytes while shifting in zeros, and store the results in "dst"
template<int imm8>
inline __m128i XM_CALLCONV bslli_all( __m128i a )
{
return _mm_bslli_si128( a, imm8 );
}
// Shift "a" right by "imm8" bytes while shifting in zeros, and store the results in "dst"
template<int imm8>
inline __m128i XM_CALLCONV bsrli_all( __m128i a )
{
return _mm_bsrli_si128( a, imm8 );
}
// Cast vector of type __m128d to type __m128. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency.
inline __m128 XM_CALLCONV castpd_ps( __m128d a )
{
return _mm_castpd_ps( a );
}
// Cast vector of type __m128d to type __m128i. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency.
inline __m128i XM_CALLCONV castpd_all( __m128d a )
{
return _mm_castpd_si128( a );
}
// Cast vector of type __m128 to type __m128d. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency.
inline __m128d XM_CALLCONV castps_pd( __m128 a )
{
return _mm_castps_pd( a );
}
// Cast vector of type __m128 to type __m128i. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency.
inline __m128i XM_CALLCONV castps_all( __m128 a )
{
return _mm_castps_si128( a );
}
// Cast vector of type __m128i to type __m128d. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency.
inline __m128d XM_CALLCONV castsi128_pd( __m128i a )
{
return _mm_castsi128_pd( a );
}
// Cast vector of type __m128i to type __m128. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency.
inline __m128 XM_CALLCONV castsi128_ps( __m128i a )
{
return _mm_castsi128_ps( a );
}
// Compare packed 8-bit integers in "a" and "b" for equality, and store the results in "dst"
inline __m128i XM_CALLCONV cmpeq_epi8( __m128i a, __m128i b )
{
return _mm_cmpeq_epi8( a, b );
}
// Compare packed 16-bit integers in "a" and "b" for equality, and store the results in "dst"
inline __m128i XM_CALLCONV cmpeq_epi16( __m128i a, __m128i b )
{
return _mm_cmpeq_epi16( a, b );
}
// Compare packed 32-bit integers in "a" and "b" for equality, and store the results in "dst"
inline __m128i XM_CALLCONV cmpeq_epi32( __m128i a, __m128i b )
{
return _mm_cmpeq_epi32( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for equality
inline __m128d XM_CALLCONV cmpeq_pd( __m128d a, __m128d b )
{
return _mm_cmpeq_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for equality
inline __m128d XM_CALLCONV cmpeq_sd( __m128d a, __m128d b )
{
return _mm_cmpeq_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for greater-than-or-equal
inline __m128d XM_CALLCONV cmpge_pd( __m128d a, __m128d b )
{
return _mm_cmpge_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for greater-than-or-equal
inline __m128d XM_CALLCONV cmpge_sd( __m128d a, __m128d b )
{
return _mm_cmpge_sd( a, b );
}
// Compare packed 8-bit integers in "a" and "b" for greater-than, and store the results in "dst"
inline __m128i XM_CALLCONV cmpgt_epi8( __m128i a, __m128i b )
{
return _mm_cmpgt_epi8( a, b );
}
// Compare packed 16-bit integers in "a" and "b" for greater-than, and store the results in "dst"
inline __m128i XM_CALLCONV cmpgt_epi16( __m128i a, __m128i b )
{
return _mm_cmpgt_epi16( a, b );
}
// Compare packed 32-bit integers in "a" and "b" for greater-than, and store the results in "dst"
inline __m128i XM_CALLCONV cmpgt_epi32( __m128i a, __m128i b )
{
return _mm_cmpgt_epi32( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for greater-than
inline __m128d XM_CALLCONV cmpgt_pd( __m128d a, __m128d b )
{
return _mm_cmpgt_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for greater-than
inline __m128d XM_CALLCONV cmpgt_sd( __m128d a, __m128d b )
{
return _mm_cmpgt_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for less-than-or-equal
inline __m128d XM_CALLCONV cmple_pd( __m128d a, __m128d b )
{
return _mm_cmple_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for less-than-or-equal
inline __m128d XM_CALLCONV cmple_sd( __m128d a, __m128d b )
{
return _mm_cmple_sd( a, b );
}
// Compare packed 8-bit integers in "a" and "b" for less-than, and store the results in "dst"
inline __m128i XM_CALLCONV cmplt_epi8( __m128i a, __m128i b )
{
return _mm_cmplt_epi8( a, b );
}
// Compare packed 16-bit integers in "a" and "b" for less-than, and store the results in "dst"
inline __m128i XM_CALLCONV cmplt_epi16( __m128i a, __m128i b )
{
return _mm_cmplt_epi16( a, b );
}
// Compare packed 32-bit integers in "a" and "b" for less-than, and store the results in "dst"
inline __m128i XM_CALLCONV cmplt_epi32( __m128i a, __m128i b )
{
return _mm_cmplt_epi32( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for less-than
inline __m128d XM_CALLCONV cmplt_pd( __m128d a, __m128d b )
{
return _mm_cmplt_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for less-than
inline __m128d XM_CALLCONV cmplt_sd( __m128d a, __m128d b )
{
return _mm_cmplt_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for not-equal
inline __m128d XM_CALLCONV cmpneq_pd( __m128d a, __m128d b )
{
return _mm_cmpneq_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for not-equal
inline __m128d XM_CALLCONV cmpneq_sd( __m128d a, __m128d b )
{
return _mm_cmpneq_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for not-greater-than-or-equal
inline __m128d XM_CALLCONV cmpnge_pd( __m128d a, __m128d b )
{
return _mm_cmpnge_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for not-greater-than-or-equal
inline __m128d XM_CALLCONV cmpnge_sd( __m128d a, __m128d b )
{
return _mm_cmpnge_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for not-greater-than
inline __m128d XM_CALLCONV cmpngt_pd( __m128d a, __m128d b )
{
return _mm_cmpngt_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for not-greater-than
inline __m128d XM_CALLCONV cmpngt_sd( __m128d a, __m128d b )
{
return _mm_cmpngt_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for not-less-than-or-equal
inline __m128d XM_CALLCONV cmpnle_pd( __m128d a, __m128d b )
{
return _mm_cmpnle_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for not-less-than-or-equal
inline __m128d XM_CALLCONV cmpnle_sd( __m128d a, __m128d b )
{
return _mm_cmpnle_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" for not-less-than
inline __m128d XM_CALLCONV cmpnlt_pd( __m128d a, __m128d b )
{
return _mm_cmpnlt_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" for not-less-than
inline __m128d XM_CALLCONV cmpnlt_sd( __m128d a, __m128d b )
{
return _mm_cmpnlt_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" to see if neither is NaN
inline __m128d XM_CALLCONV cmpord_pd( __m128d a, __m128d b )
{
return _mm_cmpord_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" to see if neither is NaN
inline __m128d XM_CALLCONV cmpord_sd( __m128d a, __m128d b )
{
return _mm_cmpord_sd( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b" to see if either is NaN
inline __m128d XM_CALLCONV cmpunord_pd( __m128d a, __m128d b )
{
return _mm_cmpunord_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b" to see if either is NaN
inline __m128d XM_CALLCONV cmpunord_sd( __m128d a, __m128d b )
{
return _mm_cmpunord_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for equality
inline int XM_CALLCONV comieq_sd( __m128d a, __m128d b )
{
return _mm_comieq_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for greater-than-or-equal
inline int XM_CALLCONV comige_sd( __m128d a, __m128d b )
{
return _mm_comige_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for greater-than
inline int XM_CALLCONV comigt_sd( __m128d a, __m128d b )
{
return _mm_comigt_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for less-than-or-equal
inline int XM_CALLCONV comile_sd( __m128d a, __m128d b )
{
return _mm_comile_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for less-than
inline int XM_CALLCONV comilt_sd( __m128d a, __m128d b )
{
return _mm_comilt_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for not-equal
inline int XM_CALLCONV comineq_sd( __m128d a, __m128d b )
{
return _mm_comineq_sd( a, b );
}
// Convert packed 32-bit integers in "a" to packed double-precision floating-point elements
inline __m128d XM_CALLCONV cvtepi32_pd( __m128i a )
{
return _mm_cvtepi32_pd( a );
}
// Convert packed 32-bit integers in "a" to packed single-precision floating-point elements
inline __m128 XM_CALLCONV cvtepi32_ps( __m128i a )
{
return _mm_cvtepi32_ps( a );
}
// Convert packed double-precision floating-point elements in "a" to packed 32-bit integers
inline __m128i XM_CALLCONV cvtpd_epi32( __m128d a )
{
return _mm_cvtpd_epi32( a );
}
// Convert packed double-precision floating-point elements in "a" to packed single-precision floating-point elements
inline __m128 XM_CALLCONV cvtpd_ps( __m128d a )
{
return _mm_cvtpd_ps( a );
}
// Convert packed single-precision floating-point elements in "a" to packed 32-bit integers
inline __m128i XM_CALLCONV cvtps_epi32( __m128 a )
{
return _mm_cvtps_epi32( a );
}
// Convert packed single-precision floating-point elements in "a" to packed double-precision floating-point elements
inline __m128d XM_CALLCONV cvtps_pd( __m128 a )
{
return _mm_cvtps_pd( a );
}
// Copy the lower double-precision floating-point element of "a" to "dst"
inline double XM_CALLCONV cvtsd_f64( __m128d a )
{
return _mm_cvtsd_f64( a );
}
// Convert the lower double-precision floating-point element in "a" to a 32-bit integer
inline int XM_CALLCONV cvtsd_si32( __m128d a )
{
return _mm_cvtsd_si32( a );
}
// Convert the lower double-precision floating-point element in "b" to a single-precision floating-point element
inline __m128 XM_CALLCONV cvtsd_ss( __m128 a, __m128d b )
{
return _mm_cvtsd_ss( a, b );
}
// Copy the lower 32-bit integer in "a" to "dst".
inline int XM_CALLCONV cvtsi128_si32( __m128i a )
{
return _mm_cvtsi128_si32( a );
}
// Convert the 32-bit integer "b" to a double-precision floating-point element
inline __m128d XM_CALLCONV cvtsi32_sd( __m128d a, int b )
{
return _mm_cvtsi32_sd( a, b );
}
// Copy 32-bit integer "a" to the lower elements of "dst", and zero the upper elements of "dst"
inline __m128i XM_CALLCONV cvtsi32_all( int a )
{
return _mm_cvtsi32_si128( a );
}
// Convert the lower single-precision floating-point element in "b" to a double-precision floating-point element
inline __m128d XM_CALLCONV cvtss_sd( __m128d a, __m128 b )
{
return _mm_cvtss_sd( a, b );
}
// Convert packed double-precision floating-point elements in "a" to packed 32-bit integers with truncation
inline __m128i XM_CALLCONV cvttpd_epi32( __m128d a )
{
return _mm_cvttpd_epi32( a );
}
// Convert packed single-precision floating-point elements in "a" to packed 32-bit integers with truncation
inline __m128i XM_CALLCONV cvttps_epi32( __m128 a )
{
return _mm_cvttps_epi32( a );
}
// Convert the lower double-precision floating-point element in "a" to a 32-bit integer with truncation
inline int XM_CALLCONV cvttsd_si32( __m128d a )
{
return _mm_cvttsd_si32( a );
}
// Divide packed double-precision floating-point elements in "a" by packed elements in "b"
inline __m128d XM_CALLCONV div_pd( __m128d a, __m128d b )
{
return _mm_div_pd( a, b );
}
// Divide the lower double-precision floating-point element in "a" by the lower double-precision floating-point element in "b"
inline __m128d XM_CALLCONV div_sd( __m128d a, __m128d b )
{
return _mm_div_sd( a, b );
}
// Extract a 16-bit integer from "a", selected with "imm8", and store the result in the lower element of "dst"
template<int imm8>
inline int XM_CALLCONV extract_epi16( __m128i a )
{
return _mm_extract_epi16( a, imm8 );
}
// Copy "a" to "dst", and insert the 16-bit integer "i" into "dst" at the location specified by "imm8"
template<int imm8>
inline __m128i XM_CALLCONV insert_epi16( __m128i a, int i )
{
return _mm_insert_epi16( a, i, imm8 );
}
// Perform a serializing operation on all load-from-memory instructions that were issued prior to this instruction
inline void XM_CALLCONV lfence()
{
_mm_lfence();
}
// Load 128-bits (composed of 2 packed double-precision floating-point elements) from memory into "dst"
inline __m128d XM_CALLCONV load_pd( const double *mem_addr )
{
return _mm_load_pd( mem_addr );
}
// Load a double-precision floating-point element from memory into the lower of "dst", and zero the upper element
inline __m128d XM_CALLCONV load_sd( const double *mem_addr )
{
return _mm_load_sd( mem_addr );
}
// Load 128-bits of integer data from memory into "dst". "mem_addr" must be aligned on a 16-byte boundary or a general-protection exception may be generated.
inline __m128i XM_CALLCONV load_all( const __m128i *mem_addr )
{
return _mm_load_si128( mem_addr );
}
// Load a double-precision floating-point element from memory into both elements of "dst"
inline __m128d XM_CALLCONV load1_pd( const double *mem_addr )
{
return _mm_load1_pd( mem_addr );
}
// Load a double-precision floating-point element from memory into the upper element of "dst", and copy the lower element from "a" to "dst"
inline __m128d XM_CALLCONV loadh_pd( __m128d a, const double *mem_addr )
{
return _mm_loadh_pd( a, mem_addr );
}
// Load 64-bit integer from memory into the first element of "dst".
inline __m128i XM_CALLCONV loadl_epi64( const __m128i *mem_addr )
{
return _mm_loadl_epi64( mem_addr );
}
// Load a double-precision floating-point element from memory into the lower element of "dst", and copy the upper element from "a" to "dst"
inline __m128d XM_CALLCONV loadl_pd( __m128d a, const double *mem_addr )
{
return _mm_loadl_pd( a, mem_addr );
}
// Load 2 double-precision floating-point elements from memory into "dst" in reverse order
inline __m128d XM_CALLCONV loadr_pd( const double *mem_addr )
{
return _mm_loadr_pd( mem_addr );
}
// Load 128-bits (composed of 2 packed double-precision floating-point elements) from memory into "dst"
inline __m128d XM_CALLCONV loadu_pd( const double *mem_addr )
{
return _mm_loadu_pd( mem_addr );
}
// Load 128-bits of integer data from memory into "dst". "mem_addr" does not need to be aligned on any particular boundary.
inline __m128i XM_CALLCONV loadu_all( const __m128i *mem_addr )
{
return _mm_loadu_si128( mem_addr );
}
// Multiply packed signed 16-bit integers in "a" and "b", producing intermediate signed 32-bit integers
inline __m128i XM_CALLCONV madd_epi16( __m128i a, __m128i b )
{
return _mm_madd_epi16( a, b );
}
// Conditionally store 8-bit integer elements from "a" into memory using "mask" (elements are not stored when the highest bit is not set in the corresponding element) and a non-temporal memory hint
inline void XM_CALLCONV maskmoveu_all( __m128i a, __m128i mask, char *mem_addr )
{
_mm_maskmoveu_si128( a, mask, mem_addr );
}
// Compare packed 16-bit integers in "a" and "b", and store packed maximum values in "dst"
inline __m128i XM_CALLCONV max_epi16( __m128i a, __m128i b )
{
return _mm_max_epi16( a, b );
}
// Compare packed unsigned 8-bit integers in "a" and "b", and store packed maximum values in "dst"
inline __m128i XM_CALLCONV max_epu8( __m128i a, __m128i b )
{
return _mm_max_epu8( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b", and store packed maximum values in "dst"
inline __m128d XM_CALLCONV max_pd( __m128d a, __m128d b )
{
return _mm_max_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b", store the maximum value in the lower element of "dst", and copy the upper element from "a" to the upper element of "dst"
inline __m128d XM_CALLCONV max_sd( __m128d a, __m128d b )
{
return _mm_max_sd( a, b );
}
// Perform a serializing operation on all load-from-memory and store-to-memory instructions that were issued prior to this instruction
inline void XM_CALLCONV mfence()
{
_mm_mfence();
}
// Compare packed 16-bit integers in "a" and "b", and store packed minimum values in "dst"
inline __m128i XM_CALLCONV min_epi16( __m128i a, __m128i b )
{
return _mm_min_epi16( a, b );
}
// Compare packed unsigned 8-bit integers in "a" and "b", and store packed minimum values in "dst"
inline __m128i XM_CALLCONV min_epu8( __m128i a, __m128i b )
{
return _mm_min_epu8( a, b );
}
// Compare packed double-precision floating-point elements in "a" and "b", and store packed minimum values in "dst"
inline __m128d XM_CALLCONV min_pd( __m128d a, __m128d b )
{
return _mm_min_pd( a, b );
}
// Compare the lower double-precision floating-point elements in "a" and "b", store the minimum value in the lower element of "dst", and copy the upper element from "a" to the upper element of "dst"
inline __m128d XM_CALLCONV min_sd( __m128d a, __m128d b )
{
return _mm_min_sd( a, b );
}
// Copy the lower 64-bit integer in "a" to the lower element of "dst", and zero the upper element
inline __m128i XM_CALLCONV move_epi64( __m128i a )
{
return _mm_move_epi64( a );
}
// Move the lower double-precision floating-point element from "b" to the lower element of "dst", and copy the upper element from "a" to the upper element of "dst"
inline __m128d XM_CALLCONV move_sd( __m128d a, __m128d b )
{
return _mm_move_sd( a, b );
}
// Create mask from the most significant bit of each 8-bit element in "a"
inline int XM_CALLCONV movemask_epi8( __m128i a )
{
return _mm_movemask_epi8( a );
}
// Set each bit of mask "dst" based on the most significant bit of the corresponding packed double-precision floating-point element in "a"
inline int XM_CALLCONV movemask_pd( __m128d a )
{
return _mm_movemask_pd( a );
}
// Multiply the low unsigned 32-bit integers from each packed 64-bit element in "a" and "b", and store the unsigned 64-bit results in "dst"
inline __m128i XM_CALLCONV mul_epu32( __m128i a, __m128i b )
{
return _mm_mul_epu32( a, b );
}
// Multiply packed double-precision floating-point elements in "a" and "b"
inline __m128d XM_CALLCONV mul_pd( __m128d a, __m128d b )
{
return _mm_mul_pd( a, b );
}
// Multiply the lower double-precision floating-point element in "a" and "b"
inline __m128d XM_CALLCONV mul_sd( __m128d a, __m128d b )
{
return _mm_mul_sd( a, b );
}
// Multiply the packed 16-bit integers in "a" and "b", producing intermediate 32-bit integers, and store the high 16 bits of the intermediate integers in "dst"
inline __m128i XM_CALLCONV mulhi_epi16( __m128i a, __m128i b )
{
return _mm_mulhi_epi16( a, b );
}
// Multiply the packed unsigned 16-bit integers in "a" and "b", producing intermediate 32-bit integers, and store the high 16 bits of the intermediate integers in "dst"
inline __m128i XM_CALLCONV mulhi_epu16( __m128i a, __m128i b )
{
return _mm_mulhi_epu16( a, b );
}
// Multiply the packed 16-bit integers in "a" and "b", producing intermediate 32-bit integers, and store the low 16 bits of the intermediate integers in "dst"
inline __m128i XM_CALLCONV mullo_epi16( __m128i a, __m128i b )
{
return _mm_mullo_epi16( a, b );
}
// Compute the bitwise OR of packed double-precision floating-point elements in "a" and "b"
inline __m128d XM_CALLCONV or_pd( __m128d a, __m128d b )
{
return _mm_or_pd( a, b );
}
// Compute the bitwise OR of 128 bits (representing integer data) in "a" and "b"
inline __m128i XM_CALLCONV or_all( __m128i a, __m128i b )
{
return _mm_or_si128( a, b );
}
// Convert packed 16-bit integers from "a" and "b" to packed 8-bit integers using signed saturation
inline __m128i XM_CALLCONV packs_epi16( __m128i a, __m128i b )
{
return _mm_packs_epi16( a, b );
}
// Convert packed 32-bit integers from "a" and "b" to packed 16-bit integers using signed saturation
inline __m128i XM_CALLCONV packs_epi32( __m128i a, __m128i b )
{
return _mm_packs_epi32( a, b );
}
// Convert packed 16-bit integers from "a" and "b" to packed 8-bit integers using unsigned saturation
inline __m128i XM_CALLCONV packus_epi16( __m128i a, __m128i b )
{
return _mm_packus_epi16( a, b );
}
// Provide a hint to the processor that the code sequence is a spin-wait loop
inline void XM_CALLCONV pause()
{
_mm_pause();
}
// Compute the absolute differences of packed unsigned 8-bit integers in "a" and "b", then horizontally sum each consecutive 8 differences to produce two unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low 16 bits of 64-bit elements in "dst"
inline __m128i XM_CALLCONV sad_epu8( __m128i a, __m128i b )
{
return _mm_sad_epu8( a, b );
}
// Set packed 8-bit integers in "dst" with the supplied values
inline __m128i XM_CALLCONV set_epi8( char e0, char e1, char e2, char e3, char e4, char e5, char e6, char e7, char e8, char e9, char e10, char e11, char e12, char e13, char e14, char e15 )
{
return _mm_set_epi8( e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0 );
}
// Set packed 8-bit integers in "dst" with the supplied values
inline __m128i XM_CALLCONV set_epu8( uint8_t e0, uint8_t e1, uint8_t e2, uint8_t e3, uint8_t e4, uint8_t e5, uint8_t e6, uint8_t e7, uint8_t e8, uint8_t e9, uint8_t e10, uint8_t e11, uint8_t e12, uint8_t e13, uint8_t e14, uint8_t e15 )
{
return _mm_set_epi8( (char)e15, (char)e14, (char)e13, (char)e12, (char)e11, (char)e10, (char)e9, (char)e8, (char)e7, (char)e6, (char)e5, (char)e4, (char)e3, (char)e2, (char)e1, (char)e0 );
}
// Set packed 16-bit integers in "dst" with the supplied values.
inline __m128i XM_CALLCONV set_epi16( short e0, short e1, short e2, short e3, short e4, short e5, short e6, short e7 )
{
return _mm_set_epi16( e7, e6, e5, e4, e3, e2, e1, e0 );
}
// Set packed 16-bit integers in "dst" with the supplied values.
inline __m128i XM_CALLCONV set_epu16( uint16_t e0, uint16_t e1, uint16_t e2, uint16_t e3, uint16_t e4, uint16_t e5, uint16_t e6, uint16_t e7 )
{
return _mm_set_epi16( (short)e7, (short)e6, (short)e5, (short)e4, (short)e3, (short)e2, (short)e1, (short)e0 );
}
// Set packed 32-bit integers in "dst" with the supplied values.
inline __m128i XM_CALLCONV set_epi32( int e0, int e1, int e2, int e3 )
{
return _mm_set_epi32( e3, e2, e1, e0 );
}
// Set packed 32-bit integers in "dst" with the supplied values.
inline __m128i XM_CALLCONV set_epu32( uint32_t e0, uint32_t e1, uint32_t e2, uint32_t e3 )
{
return _mm_set_epi32( (int)e3, (int)e2, (int)e1, (int)e0 );
}
// Set packed 64-bit integers in "dst" with the supplied values.
inline __m128i XM_CALLCONV set_epi64x( int64_t e0, int64_t e1 )
{
return _mm_set_epi64x( (real_int64_t)e1, (real_int64_t)e0 );
}
// Set packed 64-bit integers in "dst" with the supplied values.
inline __m128i XM_CALLCONV set_epu64x( uint64_t e0, uint64_t e1 )
{
return _mm_set_epi64x( (real_int64_t)e1, (real_int64_t)e0 );
}
// Set packed double-precision floating-point elements in "dst" with the supplied values
inline __m128d XM_CALLCONV set_pd( double e0, double e1 )
{
return _mm_set_pd( e1, e0 );
}
// Copy double-precision floating-point element "a" to the lower element of "dst", and zero the upper element
inline __m128d XM_CALLCONV set_sd( double a )
{
return _mm_set_sd( a );
}
// Broadcast 8-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastb".
inline __m128i XM_CALLCONV set1_epi8( char a )
{
return _mm_set1_epi8( a );
}
// Broadcast 8-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastb".
inline __m128i XM_CALLCONV set1_epu8( uint8_t a )
{
return _mm_set1_epi8( (char)a );
}
// Broadcast 16-bit integer "a" to all all elements of "dst". This intrinsic may generate "vpbroadcastw".
inline __m128i XM_CALLCONV set1_epi16( short a )
{
return _mm_set1_epi16( a );
}
// Broadcast 16-bit integer "a" to all all elements of "dst". This intrinsic may generate "vpbroadcastw".
inline __m128i XM_CALLCONV set1_epu16( uint16_t a )
{
return _mm_set1_epi16( (short)a );
}
// Broadcast 32-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastd".
inline __m128i XM_CALLCONV set1_epi32( int a )
{
return _mm_set1_epi32( a );
}
// Broadcast 32-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastd".
inline __m128i XM_CALLCONV set1_epu32( uint32_t a )
{
return _mm_set1_epi32( (int)a );
}
// Broadcast 64-bit integer "a" to all elements of "dst". This intrinsic may generate the "vpbroadcastq".
inline __m128i XM_CALLCONV set1_epi64x( int64_t a )
{
return _mm_set1_epi64x( (real_int64_t)a );
}
// Broadcast 64-bit integer "a" to all elements of "dst". This intrinsic may generate the "vpbroadcastq".
inline __m128i XM_CALLCONV set1_epu64x( uint64_t a )
{
return _mm_set1_epi64x( (real_int64_t)a );
}
// Broadcast double-precision floating-point value "a" to all elements of "dst"
inline __m128d XM_CALLCONV set1_pd( double a )
{
return _mm_set1_pd( a );
}
// Return vector of type __m128d with all elements set to zero.
inline __m128d XM_CALLCONV setzero_pd()
{
return _mm_setzero_pd();
}
// Return vector of type __m128i with all elements set to zero.
inline __m128i XM_CALLCONV setzero_all()
{
return _mm_setzero_si128();
}
// Shuffle 32-bit integers in "a" using the control in "imm8", and store the results in "dst"
template<int imm8>
inline __m128i XM_CALLCONV shuffle_epi32( __m128i a )
{
return _mm_shuffle_epi32( a, imm8 );
}
// Shuffle double-precision floating-point elements using the control in "imm8"
template<int imm8>
inline __m128d XM_CALLCONV shuffle_pd( __m128d a, __m128d b )
{
return _mm_shuffle_pd( a, b, imm8 );
}
// Shuffle 16-bit integers in the high 64 bits of "a" using the control in "imm8"
template<int imm8>
inline __m128i XM_CALLCONV shufflehi_epi16( __m128i a )
{
return _mm_shufflehi_epi16( a, imm8 );
}
// Shuffle 16-bit integers in the low 64 bits of "a" using the control in "imm8"
template<int imm8>
inline __m128i XM_CALLCONV shufflelo_epi16( __m128i a )
{
return _mm_shufflelo_epi16( a, imm8 );
}
// Shift packed 16-bit integers in "a" left by "count" while shifting in zeros
inline __m128i XM_CALLCONV sll_epi16( __m128i a, __m128i count )
{
return _mm_sll_epi16( a, count );
}
// Shift packed 32-bit integers in "a" left by "count" while shifting in zeros
inline __m128i XM_CALLCONV sll_epi32( __m128i a, __m128i count )
{
return _mm_sll_epi32( a, count );
}
// Shift packed 64-bit integers in "a" left by "count" while shifting in zeros
inline __m128i XM_CALLCONV sll_epi64( __m128i a, __m128i count )
{
return _mm_sll_epi64( a, count );
}
// Shift packed 16-bit integers in "a" left by "imm8" while shifting in zeros
template<int imm8>
inline __m128i XM_CALLCONV slli_epi16( __m128i a )
{
return _mm_slli_epi16( a, imm8 );
}
// Shift packed 32-bit integers in "a" left by "imm8" while shifting in zeros
template<int imm8>
inline __m128i XM_CALLCONV slli_epi32( __m128i a )
{
return _mm_slli_epi32( a, imm8 );
}
// Shift packed 64-bit integers in "a" left by "imm8" while shifting in zeros
template<int imm8>
inline __m128i XM_CALLCONV slli_epi64( __m128i a )
{
return _mm_slli_epi64( a, imm8 );
}
// Shift "a" left by "imm8" bytes while shifting in zeros, and store the results in "dst"
template<int imm8>
inline __m128i XM_CALLCONV slli_all( __m128i a )
{
return _mm_slli_si128( a, imm8 );
}
// Compute the square root of packed double-precision floating-point elements in "a"
inline __m128d XM_CALLCONV sqrt_pd( __m128d a )
{
return _mm_sqrt_pd( a );
}
// Compute the square root of the lower double-precision floating-point element in "b"
inline __m128d XM_CALLCONV sqrt_sd( __m128d a, __m128d b )
{
return _mm_sqrt_sd( a, b );
}
// Shift packed 16-bit integers in "a" right by "count" while shifting in sign bits
inline __m128i XM_CALLCONV sra_epi16( __m128i a, __m128i count )
{
return _mm_sra_epi16( a, count );
}
// Shift packed 32-bit integers in "a" right by "count" while shifting in sign bits
inline __m128i XM_CALLCONV sra_epi32( __m128i a, __m128i count )
{
return _mm_sra_epi32( a, count );
}
// Shift packed 16-bit integers in "a" right by "imm8" while shifting in sign bits
template<int imm8>
inline __m128i XM_CALLCONV srai_epi16( __m128i a )
{
return _mm_srai_epi16( a, imm8 );
}
// Shift packed 32-bit integers in "a" right by "imm8" while shifting in sign bits
template<int imm8>
inline __m128i XM_CALLCONV srai_epi32( __m128i a )
{
return _mm_srai_epi32( a, imm8 );
}
// Shift packed 16-bit integers in "a" right by "count" while shifting in zeros
inline __m128i XM_CALLCONV srl_epi16( __m128i a, __m128i count )
{
return _mm_srl_epi16( a, count );
}
// Shift packed 32-bit integers in "a" right by "count" while shifting in zeros
inline __m128i XM_CALLCONV srl_epi32( __m128i a, __m128i count )
{
return _mm_srl_epi32( a, count );
}
// Shift packed 64-bit integers in "a" right by "count" while shifting in zeros
inline __m128i XM_CALLCONV srl_epi64( __m128i a, __m128i count )
{
return _mm_srl_epi64( a, count );
}
// Shift packed 16-bit integers in "a" right by "imm8" while shifting in zeros
template<int imm8>
inline __m128i XM_CALLCONV srli_epi16( __m128i a )
{
return _mm_srli_epi16( a, imm8 );
}
// Shift packed 32-bit integers in "a" right by "imm8" while shifting in zeros
template<int imm8>
inline __m128i XM_CALLCONV srli_epi32( __m128i a )
{
return _mm_srli_epi32( a, imm8 );
}
// Shift packed 64-bit integers in "a" right by "imm8" while shifting in zeros
template<int imm8>
inline __m128i XM_CALLCONV srli_epi64( __m128i a )
{
return _mm_srli_epi64( a, imm8 );
}
// Shift "a" right by "imm8" bytes while shifting in zeros, and store the results in "dst"
template<int imm8>
inline __m128i XM_CALLCONV srli_all( __m128i a )
{
return _mm_srli_si128( a, imm8 );
}
// Store 128-bits (composed of 2 packed double-precision floating-point elements) from "a" into memory
inline void XM_CALLCONV store_pd( double *mem_addr, __m128d a )
{
_mm_store_pd( mem_addr, a );
}
// Store the lower double-precision floating-point element from "a" into memory
inline void XM_CALLCONV store_sd( double *mem_addr, __m128d a )
{
_mm_store_sd( mem_addr, a );
}
// Store 128-bits of integer data from "a" into memory. "mem_addr" must be aligned on a 16-byte boundary or a general-protection exception may be generated.
inline void XM_CALLCONV store_all( __m128i *mem_addr, __m128i a )
{
_mm_store_si128( mem_addr, a );
}
// Store the lower double-precision floating-point element from "a" into 2 contiguous elements in memory
inline void XM_CALLCONV store1_pd( double *mem_addr, __m128d a )
{
_mm_store1_pd( mem_addr, a );
}
// Store the upper double-precision floating-point element from "a" into memory
inline void XM_CALLCONV storeh_pd( double *mem_addr, __m128d a )
{
_mm_storeh_pd( mem_addr, a );
}
// Store 64-bit integer from the first element of "a" into memory.
inline void XM_CALLCONV storel_epi64( __m128i *mem_addr, __m128i a )
{
_mm_storel_epi64( mem_addr, a );
}
// Store the lower double-precision floating-point element from "a" into memory
inline void XM_CALLCONV storel_pd( double *mem_addr, __m128d a )
{
_mm_storel_pd( mem_addr, a );
}
// Store 2 double-precision floating-point elements from "a" into memory in reverse order
inline void XM_CALLCONV storer_pd( double *mem_addr, __m128d a )
{
_mm_storer_pd( mem_addr, a );
}
// Store 128-bits (composed of 2 packed double-precision floating-point elements) from "a" into memory
inline void XM_CALLCONV storeu_pd( double *mem_addr, __m128d a )
{
_mm_storeu_pd( mem_addr, a );
}
// Store 128-bits of integer data from "a" into memory. "mem_addr" does not need to be aligned on any particular boundary.
inline void XM_CALLCONV storeu_all( __m128i *mem_addr, __m128i a )
{
_mm_storeu_si128( mem_addr, a );
}
// Store 128-bits (composed of 2 packed double-precision floating-point elements) from "a" into memory using a non-temporal memory hint
inline void XM_CALLCONV stream_pd( double *mem_addr, __m128d a )
{
_mm_stream_pd( mem_addr, a );
}
// Store 32-bit integer "a" into memory using a non-temporal hint to minimize cache pollution
inline void XM_CALLCONV stream_si32( int *mem_addr, int a )
{
_mm_stream_si32( mem_addr, a );
}
// Store 128-bits of integer data from "a" into memory using a non-temporal memory hint
inline void XM_CALLCONV stream_all( __m128i *mem_addr, __m128i a )
{
_mm_stream_si128( mem_addr, a );
}
// Subtract packed 8-bit integers in "b" from packed 8-bit integers in "a"
inline __m128i XM_CALLCONV sub_epi8( __m128i a, __m128i b )
{
return _mm_sub_epi8( a, b );
}
// Subtract packed 16-bit integers in "b" from packed 16-bit integers in "a"
inline __m128i XM_CALLCONV sub_epi16( __m128i a, __m128i b )
{
return _mm_sub_epi16( a, b );
}
// Subtract packed 32-bit integers in "b" from packed 32-bit integers in "a"
inline __m128i XM_CALLCONV sub_epi32( __m128i a, __m128i b )
{
return _mm_sub_epi32( a, b );
}
// Subtract packed 64-bit integers in "b" from packed 64-bit integers in "a"
inline __m128i XM_CALLCONV sub_epi64( __m128i a, __m128i b )
{
return _mm_sub_epi64( a, b );
}
// Subtract packed double-precision floating-point elements in "b" from packed double-precision floating-point elements in "a"
inline __m128d XM_CALLCONV sub_pd( __m128d a, __m128d b )
{
return _mm_sub_pd( a, b );
}
// Subtract the lower double-precision floating-point element in "b" from the lower double-precision floating-point element in "a"
inline __m128d XM_CALLCONV sub_sd( __m128d a, __m128d b )
{
return _mm_sub_sd( a, b );
}
// Subtract packed 8-bit integers in "b" from packed 8-bit integers in "a" using saturation
inline __m128i XM_CALLCONV subs_epi8( __m128i a, __m128i b )
{
return _mm_subs_epi8( a, b );
}
// Subtract packed 16-bit integers in "b" from packed 16-bit integers in "a" using saturation
inline __m128i XM_CALLCONV subs_epi16( __m128i a, __m128i b )
{
return _mm_subs_epi16( a, b );
}
// Subtract packed unsigned 8-bit integers in "b" from packed unsigned 8-bit integers in "a" using saturation
inline __m128i XM_CALLCONV subs_epu8( __m128i a, __m128i b )
{
return _mm_subs_epu8( a, b );
}
// Subtract packed unsigned 16-bit integers in "b" from packed unsigned 16-bit integers in "a" using saturation
inline __m128i XM_CALLCONV subs_epu16( __m128i a, __m128i b )
{
return _mm_subs_epu16( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for equality
inline int XM_CALLCONV ucomieq_sd( __m128d a, __m128d b )
{
return _mm_ucomieq_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for greater-than-or-equal
inline int XM_CALLCONV ucomige_sd( __m128d a, __m128d b )
{
return _mm_ucomige_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for greater-than
inline int XM_CALLCONV ucomigt_sd( __m128d a, __m128d b )
{
return _mm_ucomigt_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for less-than-or-equal
inline int XM_CALLCONV ucomile_sd( __m128d a, __m128d b )
{
return _mm_ucomile_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for less-than
inline int XM_CALLCONV ucomilt_sd( __m128d a, __m128d b )
{
return _mm_ucomilt_sd( a, b );
}
// Compare the lower double-precision floating-point element in "a" and "b" for not-equal
inline int XM_CALLCONV ucomineq_sd( __m128d a, __m128d b )
{
return _mm_ucomineq_sd( a, b );
}
// Return vector of type __m128d with undefined elements.
inline __m128d XM_CALLCONV undefined_pd()
{
return _mm_undefined_pd();
}
// Return vector of type __m128i with undefined elements.
inline __m128i XM_CALLCONV undefined_all()
{
return _mm_undefined_si128();
}
// Unpack and interleave 8-bit integers from the high half of "a" and "b"
inline __m128i XM_CALLCONV unpackhi_epi8( __m128i a, __m128i b )
{
return _mm_unpackhi_epi8( a, b );
}
// Unpack and interleave 16-bit integers from the high half of "a" and "b"
inline __m128i XM_CALLCONV unpackhi_epi16( __m128i a, __m128i b )
{
return _mm_unpackhi_epi16( a, b );
}
// Unpack and interleave 32-bit integers from the high half of "a" and "b"
inline __m128i XM_CALLCONV unpackhi_epi32( __m128i a, __m128i b )
{
return _mm_unpackhi_epi32( a, b );
}
// Unpack and interleave 64-bit integers from the high half of "a" and "b"
inline __m128i XM_CALLCONV unpackhi_epi64( __m128i a, __m128i b )
{
return _mm_unpackhi_epi64( a, b );
}
// Unpack and interleave double-precision floating-point elements from the high half of "a" and "b"
inline __m128d XM_CALLCONV unpackhi_pd( __m128d a, __m128d b )
{
return _mm_unpackhi_pd( a, b );
}
// Unpack and interleave 8-bit integers from the low half of "a" and "b"
inline __m128i XM_CALLCONV unpacklo_epi8( __m128i a, __m128i b )
{
return _mm_unpacklo_epi8( a, b );
}
// Unpack and interleave 16-bit integers from the low half of "a" and "b"
inline __m128i XM_CALLCONV unpacklo_epi16( __m128i a, __m128i b )
{
return _mm_unpacklo_epi16( a, b );
}
// Unpack and interleave 32-bit integers from the low half of "a" and "b"
inline __m128i XM_CALLCONV unpacklo_epi32( __m128i a, __m128i b )
{
return _mm_unpacklo_epi32( a, b );
}
// Unpack and interleave 64-bit integers from the low half of "a" and "b"
inline __m128i XM_CALLCONV unpacklo_epi64( __m128i a, __m128i b )
{
return _mm_unpacklo_epi64( a, b );
}
// Unpack and interleave double-precision floating-point elements from the low half of "a" and "b"
inline __m128d XM_CALLCONV unpacklo_pd( __m128d a, __m128d b )
{
return _mm_unpacklo_pd( a, b );
}
// Compute the bitwise XOR of packed double-precision floating-point elements in "a" and "b"
inline __m128d XM_CALLCONV xor_pd( __m128d a, __m128d b )
{
return _mm_xor_pd( a, b );
}
// Compute the bitwise XOR of 128 bits (representing integer data) in "a" and "b"
inline __m128i XM_CALLCONV xor_all( __m128i a, __m128i b )
{
return _mm_xor_si128( a, b );
}
#if _M_X64
// Convert the lower double-precision floating-point element in "a" to a 64-bit integer
inline int64_t XM_CALLCONV cvtsd_si64( __m128d a )
{
return (int64_t)_mm_cvtsd_si64( a );
}
// Convert the lower double-precision floating-point element in "a" to a 64-bit integer
inline int64_t XM_CALLCONV cvtsd_si64x( __m128d a )
{
return (int64_t)_mm_cvtsd_si64x( a );
}
// Copy the lower 64-bit integer in "a" to "dst".
inline int64_t XM_CALLCONV cvtsi128_si64( __m128i a )
{
return (int64_t)_mm_cvtsi128_si64( a );
}
// Copy the lower 64-bit integer in "a" to "dst".
inline int64_t XM_CALLCONV cvtsi128_si64x( __m128i a )
{
return (int64_t)_mm_cvtsi128_si64x( a );
}
// Convert the 64-bit integer "b" to a double-precision floating-point element
inline __m128d XM_CALLCONV cvtsi64_sd( __m128d a, int64_t b )
{
return _mm_cvtsi64_sd( a, (real_int64_t)b );
}
// Copy 64-bit integer "a" to the lower element of "dst", and zero the upper element
inline __m128i XM_CALLCONV cvtsi64_all( int64_t a )
{
return _mm_cvtsi64_si128( (real_int64_t)a );
}
// Convert the 64-bit integer "b" to a double-precision floating-point element
inline __m128d XM_CALLCONV cvtsi64x_sd( __m128d a, int64_t b )
{
return _mm_cvtsi64x_sd( a, (real_int64_t)b );
}
// Copy 64-bit integer "a" to the lower element of "dst", and zero the upper element
inline __m128i XM_CALLCONV cvtsi64x_all( int64_t a )
{
return _mm_cvtsi64x_si128( (real_int64_t)a );
}
// Convert the lower double-precision floating-point element in "a" to a 64-bit integer with truncation
inline int64_t XM_CALLCONV cvttsd_si64( __m128d a )
{
return (int64_t)_mm_cvttsd_si64( a );
}
// Convert the lower double-precision floating-point element in "a" to a 64-bit integer with truncation
inline int64_t XM_CALLCONV cvttsd_si64x( __m128d a )
{
return (int64_t)_mm_cvttsd_si64x( a );
}
// Store 64-bit integer "a" into memory using a non-temporal hint to minimize cache pollution
inline void XM_CALLCONV stream_si64( int64_t *mem_addr, int64_t a )
{
_mm_stream_si64( (real_int64_t *)mem_addr, (real_int64_t)a );
}
#endif // _M_X64
using VecInteger = __m128i;
static constexpr int allValuesMask_epi8 = 0xFFFF;
using VecFloat64 = __m128d;
static constexpr int allValuesMask_pd = 0x3;
} // namespace Intrinsics::Sse
} // namespace Intrinsics
| 34.341697 | 268 | 0.707262 | Const-me |
3ebf0fda48088cd22f4ee0c2411c57f197ba861e | 5,838 | hpp | C++ | sycl/include/CL/sycl/detail/program_manager/program_manager.hpp | nyalloc/llvm | 2d6dcd09b6a418c05c02b7beb6bb042ec73daf43 | [
"Apache-2.0"
] | null | null | null | sycl/include/CL/sycl/detail/program_manager/program_manager.hpp | nyalloc/llvm | 2d6dcd09b6a418c05c02b7beb6bb042ec73daf43 | [
"Apache-2.0"
] | null | null | null | sycl/include/CL/sycl/detail/program_manager/program_manager.hpp | nyalloc/llvm | 2d6dcd09b6a418c05c02b7beb6bb042ec73daf43 | [
"Apache-2.0"
] | null | null | null | //==------ program_manager.hpp --- SYCL program manager---------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#pragma once
#include <CL/sycl/detail/common.hpp>
#include <CL/sycl/detail/os_util.hpp>
#include <CL/sycl/detail/pi.hpp>
#include <CL/sycl/stl.hpp>
#include <map>
#include <vector>
// +++ Entry points referenced by the offload wrapper object {
/// Executed as a part of current module's (.exe, .dll) static initialization.
/// Registers device executable images with the runtime.
extern "C" void __tgt_register_lib(pi_device_binaries desc);
/// Executed as a part of current module's (.exe, .dll) static
/// de-initialization.
/// Unregisters device executable images with the runtime.
extern "C" void __tgt_unregister_lib(pi_device_binaries desc);
// +++ }
namespace cl {
namespace sycl {
class context;
namespace detail {
using DeviceImage = pi_device_binary_struct;
// Custom deleter for the DeviceImage. Must only be called for "orphan" images
// allocated by the runtime. Those Images which are part of binaries must not
// be attempted to de-allocate.
struct ImageDeleter;
// Provides single loading and building OpenCL programs with unique contexts
// that is necessary for no interoperability cases with lambda.
class ProgramManager {
public:
// Returns the single instance of the program manager for the entire process.
// Can only be called after staticInit is done.
static ProgramManager &getInstance();
DeviceImage &getDeviceImage(OSModuleHandle M, const string_class &KernelName,
const context &Context);
RT::PiProgram createPIProgram(const DeviceImage &Img, const context &Context);
RT::PiProgram getBuiltPIProgram(OSModuleHandle M, const context &Context,
const string_class &KernelName);
RT::PiKernel getOrCreateKernel(OSModuleHandle M, const context &Context,
const string_class &KernelName);
RT::PiProgram getClProgramFromClKernel(RT::PiKernel Kernel);
void addImages(pi_device_binaries DeviceImages);
void debugDumpBinaryImages() const;
void debugDumpBinaryImage(const DeviceImage *Img) const;
static string_class getProgramBuildLog(const RT::PiProgram &Program);
private:
ProgramManager();
~ProgramManager() = default;
ProgramManager(ProgramManager const &) = delete;
ProgramManager &operator=(ProgramManager const &) = delete;
DeviceImage &getDeviceImage(OSModuleHandle M, KernelSetId KSId,
const context &Context);
void build(RT::PiProgram Program, const string_class &Options,
std::vector<RT::PiDevice> Devices);
/// Provides a new kernel set id for grouping kernel names together
KernelSetId getNextKernelSetId() const;
/// Returns the kernel set associated with the kernel, handles some special
/// cases (when reading images from file or using images with no entry info)
KernelSetId getKernelSetId(OSModuleHandle M,
const string_class &KernelName) const;
/// Returns the format of the binary image
RT::PiDeviceBinaryType getFormat(const DeviceImage &Img) const;
/// Dumps image to current directory
void dumpImage(const DeviceImage &Img, KernelSetId KSId) const;
/// The three maps below are used during kernel resolution. Any kernel is
/// identified by its name and the OS module it's coming from, allowing
/// kernels with identical names in different OS modules. The following
/// assumption is made: for any two device images in a SYCL application their
/// kernel sets are either identical or disjoint.
/// Based on this assumption, m_KernelSets is used to group kernels together
/// into sets by assigning a set ID to them during device image registration.
/// This ID is then mapped to a vector of device images containing kernels
/// from the set (m_DeviceImages).
/// An exception is made for device images with no entry information: a
/// special kernel set ID is used for them which is assigned to just the OS
/// module. These kernel set ids are stored in m_OSModuleKernelSets and device
/// images associated with them are assumed to contain all kernels coming from
/// that OS module.
/// Keeps all available device executable images added via \ref addImages.
/// Organizes the images as a map from a kernel set id to the vector of images
/// containing kernels from that set.
/// Access must be guarded by the \ref Sync::getGlobalLock()
std::map<KernelSetId, std::unique_ptr<std::vector<DeviceImage *>>> m_DeviceImages;
using StrToKSIdMap = std::map<string_class, KernelSetId>;
/// Maps names of kernels from a specific OS module (.exe .dll) to their set
/// id (the sets are disjoint).
/// Access must be guarded by the \ref Sync::getGlobalLock()
std::map<OSModuleHandle, StrToKSIdMap> m_KernelSets;
/// Keeps kernel sets for OS modules containing images without entry info.
/// Such images are assumed to contain all kernel associated with the module.
/// Access must be guarded by the \ref Sync::getGlobalLock()
std::map<OSModuleHandle, KernelSetId> m_OSModuleKernelSets;
/// Keeps device images not bound to a particular module. Program manager
/// allocated memory for these images, so they are auto-freed in destructor.
/// No image can out-live the Program manager.
std::vector<std::unique_ptr<DeviceImage, ImageDeleter>> m_OrphanDeviceImages;
/// True iff a SPIRV file has been specified with an environment variable
bool m_UseSpvFile = false;
};
} // namespace detail
} // namespace sycl
} // namespace cl
| 45.255814 | 84 | 0.721651 | nyalloc |
3ec11f59a85d7058c0f9a63261e4fa26f6725f5d | 79,527 | cpp | C++ | Source/Scene/vaSceneOld.cpp | GameTechDev/XeGTAO | 0d177ce06bfa642f64d8af4de1197ad1bcb862d4 | [
"MIT"
] | 318 | 2021-08-20T10:16:12.000Z | 2022-03-24T03:08:16.000Z | Source/Scene/vaSceneOld.cpp | s-nase/XeGTAO | 11e439c33e3dd7c1e4ea0fc73733ca840bc95bec | [
"MIT"
] | 5 | 2021-09-03T11:40:54.000Z | 2022-02-09T12:37:12.000Z | Source/Scene/vaSceneOld.cpp | s-nase/XeGTAO | 11e439c33e3dd7c1e4ea0fc73733ca840bc95bec | [
"MIT"
] | 22 | 2021-09-02T03:33:18.000Z | 2022-02-23T06:36:39.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2016-2021, Intel Corporation
//
// SPDX-License-Identifier: MIT
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Author(s): Filip Strugar (filip.strugar@intel.com)
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "vaSceneOld.h"
#if 0
#include "Rendering/vaAssetPack.h"
#include "Rendering/vaDebugCanvas.h"
#include "Core/System/vaFileTools.h"
#include "IntegratedExternals/vaImguiIntegration.h"
#include "Rendering/vaRenderMesh.h"
#include "Rendering/vaRenderMaterial.h"
#include "Core/vaApplicationBase.h"
#include <set>
using namespace Vanilla;
using namespace Vanilla::Scene;
vaSceneObject::vaSceneObject( )
{
}
vaSceneObject::~vaSceneObject( )
{
// children/parents must be disconnected!
assert( m_parent == nullptr );
assert( m_children.size() == 0 );
}
vaMatrix4x4 vaSceneObject::GetWorldTransform( ) const
{
#ifdef _DEBUG
shared_ptr<vaSceneOld> scene = GetScene();
assert( scene != nullptr );
assert( m_lastSceneTickIndex == scene->GetTickIndex( ) ); // for whatever reason, you're getting stale data
#endif
return m_computedWorldTransform;
}
void vaSceneObject::FindClosestRecursive( const vaVector3 & worldLocation, shared_ptr<vaSceneObject> & currentClosest, float & currentDistance )
{
// can't get any closer than this
if( currentDistance == 0.0f )
return;
for( int i = 0; i < m_children.size( ); i++ )
{
m_children[i]->FindClosestRecursive( worldLocation, currentClosest, currentDistance );
}
float distance = GetGlobalAABB().NearestDistanceToPoint( worldLocation );
if( distance < currentDistance )
{
currentDistance = distance;
currentClosest = this->shared_from_this();
}
}
void vaSceneObject::TickRecursive( vaSceneOld & scene, float deltaTime )
{
assert( m_scene.lock() == scene.shared_from_this() );
assert( !m_destroyedButNotYetRemovedFromScene );
assert( !m_createdButNotYetAddedToScene );
// Update transforms (OK to rely on parent's transforms, they've already been updated)
if( m_parent == nullptr )
m_computedWorldTransform = GetLocalTransform();
else
m_computedWorldTransform = GetLocalTransform() * m_parent->GetWorldTransform();
if( (m_computedLocalBoundingBox == vaBoundingBox::Degenerate || m_computedLocalBoundingBoxIncomplete ) && m_renderMeshes.size( ) > 0 )
{
UpdateLocalBoundingBox();
}
// Update tick index (transforms ok, but beware, bounding boxes not yet)
m_lastSceneTickIndex = scene.GetTickIndex();
// Our bounding box, oriented in world space
vaOrientedBoundingBox oobb = vaOrientedBoundingBox( m_computedLocalBoundingBox, m_computedWorldTransform );
//vaDebugCanvas3D::GetInstance().DrawBox( oobb, 0xFF000000, 0x20FF8080 );
m_computedGlobalBoundingBox = oobb.ComputeEnclosingAABB();
//vaDebugCanvas3D::GetInstance().DrawBox( m_computedGlobalBoundingBox, 0xFF000000, 0x20FF8080 );
for( int i = 0; i < m_children.size( ); i++ )
{
m_children[i]->TickRecursive( scene, deltaTime );
m_computedGlobalBoundingBox = vaBoundingBox::Combine( m_computedGlobalBoundingBox, m_children[i]->GetGlobalAABB() );
}
}
shared_ptr<vaRenderMesh> vaSceneObject::GetRenderMesh( int index ) const
{
if( index < 0 || index >= m_renderMeshes.size( ) )
{
assert( false );
return nullptr;
}
return vaUIDObjectRegistrar::Find<vaRenderMesh>( m_renderMeshes[index] );
}
void vaSceneObject::AddRenderMeshRef( const shared_ptr<vaRenderMesh> & renderMesh )
{
const vaGUID & uid = renderMesh->UIDObject_GetUID();
assert( std::find( m_renderMeshes.begin(), m_renderMeshes.end(), uid ) == m_renderMeshes.end() );
m_renderMeshes.push_back( uid );
//m_cachedRenderMeshes.push_back( renderMesh );
//assert( m_cachedRenderMeshes.size() == m_renderMeshes.size() );
m_computedLocalBoundingBox = vaBoundingBox::Degenerate;
}
bool vaSceneObject::RemoveRenderMeshRef( int index )
{
//assert( m_cachedRenderMeshes.size( ) == m_renderMeshes.size( ) );
if( index < 0 || index >= m_renderMeshes.size( ) )
{
assert( false );
return false;
}
m_renderMeshes[index] = m_renderMeshes.back();
m_renderMeshes.pop_back();
//m_cachedRenderMeshes[index] = m_cachedRenderMeshes.back( );
//m_cachedRenderMeshes.pop_back( );
m_computedLocalBoundingBox = vaBoundingBox::Degenerate;
return true;
}
bool vaSceneObject::RemoveRenderMeshRef( const shared_ptr<vaRenderMesh> & renderMesh )
{
//assert( m_cachedRenderMeshes.size() == m_renderMeshes.size() );
const vaGUID & uid = renderMesh->UIDObject_GetUID();
int indexRemoved = vector_find_and_remove( m_renderMeshes, uid );
if( indexRemoved == -1 )
{
assert( false );
return false;
}
//if( indexRemoved < (m_cachedRenderMeshes.size()-1) )
// m_cachedRenderMeshes[indexRemoved] = m_cachedRenderMeshes.back();
// m_cachedRenderMeshes.pop_back();
m_computedLocalBoundingBox = vaBoundingBox::Degenerate;
return true;
}
bool vaSceneObject::Serialize( vaXMLSerializer & serializer )
{
auto scene = m_scene.lock();
assert( scene != nullptr );
// element opened by the parent, just fill in attributes
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "Name", m_name ) );
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR0", m_localTransform.Row(0) ) );
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR1", m_localTransform.Row(1) ) );
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR2", m_localTransform.Row(2) ) );
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR3", m_localTransform.Row(3) ) );
// VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector3>( "AABBMin", m_boundingBox.Min ) );
// VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector3>( "AABBSize", m_boundingBox.Size ) );
assert( serializer.GetVersion() > 0 );
serializer.SerializeArray( "RenderMeshes", m_renderMeshes );
VERIFY_TRUE_RETURN_ON_FALSE( scene->SerializeObjectsRecursive( serializer, "ChildObjects", m_children, this->shared_from_this() ) );
if( serializer.IsReading( ) )
{
m_lastSceneTickIndex = -1;
m_computedWorldTransform = vaMatrix4x4::Identity;
m_computedLocalBoundingBox = vaBoundingBox::Degenerate;
m_computedGlobalBoundingBox = vaBoundingBox::Degenerate;
// m_cachedRenderMeshes.resize( m_renderMeshes.size() );
m_localTransform.Row(0).w = 0.0f;
m_localTransform.Row(1).w = 0.0f;
m_localTransform.Row(2).w = 0.0f;
m_localTransform.Row(3).w = 1.0f;
SetLocalTransform( m_localTransform );
}
return true;
}
void vaSceneObject::MarkAsDestroyed( bool markChildrenAsWell )
{
// already destroyed? this shouldn't ever happen - avoid at all cost
assert( !IsDestroyed() );
m_destroyedButNotYetRemovedFromScene = true;
if( markChildrenAsWell )
{
for( int i = 0; i < (int)m_children.size( ); i++ )
m_children[i]->MarkAsDestroyed( true );
}
}
void vaSceneObject::RegisterChildAdded( const shared_ptr<vaSceneObject> & child )
{
assert( std::find( m_children.begin(), m_children.end(), child ) == m_children.end() );
m_children.push_back( child );
}
void vaSceneObject::RegisterChildRemoved( const shared_ptr<vaSceneObject> & child )
{
bool allOk = vector_find_and_remove( m_children, child ) != -1;
assert( allOk ); // if this fires, there's a serious error somewhere!
allOk;
}
void vaSceneObject::SetParent( const shared_ptr<vaSceneObject> & parent )
{
if( parent == m_parent )
{
// nothing to change, nothing to do
return;
}
auto scene = m_scene.lock();
assert( scene != nullptr );
if( scene == nullptr )
return;
// changing parent? then unregister us from previous (either root or another object)
if( m_parent != nullptr )
m_parent->RegisterChildRemoved( this->shared_from_this() );
else
scene->RegisterRootObjectRemoved( this->shared_from_this() );
// removing parent? just register as a root object
if( parent == nullptr )
{
m_parent = nullptr;
scene->RegisterRootObjectAdded( this->shared_from_this() );
return;
}
// make sure we're not setting up a no circular dependency or breaking the max node tree depth
const int c_maxObjectTreeDepth = 32;
bool allOk = false;
shared_ptr<vaSceneObject> pp = parent;
for( int i = 0; i < c_maxObjectTreeDepth; i++ )
{
if( pp == nullptr )
{
allOk = true;
break;
}
if( pp.get( ) == this )
{
VA_LOG_ERROR( "vaSceneObject::SetParent failed - circular dependency detected" );
allOk = false;
return;
}
pp = pp->GetParent();
}
if( !allOk )
{
VA_LOG_ERROR( "vaSceneObject::SetParent failed - tree depth over the limit of %d", c_maxObjectTreeDepth );
return;
}
m_parent = parent;
m_parent->RegisterChildAdded( this->shared_from_this() );
}
// static vaBoundingSphere g_cullOutsideBS( vaVector3( 0, 0, 0 ), 0.0f );
// static vaBoundingBox g_cullInsideBox( vaVector3( 0, 0, 0 ), vaVector3( 0, 0, 0 ) );
// static bool g_doCull = false;
// static int64 g_isInside = 0;
// static int64 g_isOutside = 0;
vaDrawResultFlags vaSceneObject::SelectForRendering( vaRenderInstanceList * opaqueList, vaRenderInstanceList * transparentList, const vaRenderInstanceList::FilterSettings & filter, const SelectionFilterCallback & customFilter )
{
vaDrawResultFlags drawResults = vaDrawResultFlags::None;
// first and easy one, global filter by frustum planes
if( filter.FrustumPlanes.size() > 0 )
if( m_computedGlobalBoundingBox.IntersectFrustum( filter.FrustumPlanes ) == vaIntersectType::Outside )
return vaDrawResultFlags::None;
vaMatrix4x4 worldTransform = GetWorldTransform( );
for( int i = 0; i < m_renderMeshes.size(); i++ )
{
auto renderMesh = GetRenderMesh(i);
if( renderMesh == nullptr )
{
drawResults |= vaDrawResultFlags::AssetsStillLoading;
continue;
}
// resolve material here - both easier to manage and faster (when this gets parallelized)
auto renderMaterial = renderMesh->GetMaterial();
if( renderMaterial == nullptr )
{
drawResults |= vaDrawResultFlags::AssetsStillLoading;
renderMaterial = renderMesh->GetManager().GetRenderDevice().GetMaterialManager().GetDefaultMaterial( );
}
vaOrientedBoundingBox obb = vaOrientedBoundingBox::FromAABBAndTransform( renderMesh->GetAABB(), worldTransform );
if( filter.FrustumPlanes.size() > 0 )
if( obb.IntersectFrustum( filter.FrustumPlanes ) == vaIntersectType::Outside )
continue;
int baseShadingRate = 0;
vaVector4 emissiveAdd = {0,0,0,1};
bool doSelect = ( customFilter != nullptr )?( customFilter( *this, worldTransform, obb, *renderMesh, *renderMaterial, baseShadingRate, emissiveAdd ) ):( true );
if( !doSelect )
continue;
vaShadingRate finalShadingRate = renderMaterial->ComputeShadingRate( baseShadingRate );
vaRenderInstanceList::ItemProperties properties{ finalShadingRate, emissiveAdd, 0.0f };
vaRenderInstanceList::ItemIdentifiers identifiers{ vaRenderInstanceList::SceneRuntimeIDNull, vaRenderInstanceList::SceneEntityIDNull };
if( renderMaterial->IsTransparent() )
{
if( transparentList != nullptr )
transparentList->Insert( vaFramePtr<vaRenderMesh>(renderMesh), vaFramePtr<vaRenderMaterial>(renderMaterial), worldTransform, properties, identifiers );
}
else
{
if( opaqueList != nullptr )
opaqueList->Insert( vaFramePtr<vaRenderMesh>(renderMesh), vaFramePtr<vaRenderMaterial>(renderMaterial), worldTransform, properties, identifiers );
}
}
return drawResults;
}
void vaSceneObject::RegisterUsedAssetPacks( std::function<void( const vaAssetPack & )> registerFunction )
{
for( int i = 0; i < m_renderMeshes.size(); i++ )
{
auto renderMesh = GetRenderMesh(i);
if( renderMesh != nullptr && renderMesh->GetParentAsset() != nullptr )
registerFunction( renderMesh->GetParentAsset()->GetAssetPack() );
}
}
void vaSceneObject::UpdateLocalBoundingBox( )
{
//assert( m_cachedRenderMeshes.size() == m_renderMeshes.size() );
m_computedLocalBoundingBox = vaBoundingBox::Degenerate;
m_computedGlobalBoundingBox = vaBoundingBox::Degenerate;
m_computedLocalBoundingBoxIncomplete = false;
for( int i = 0; i < m_renderMeshes.size(); i++ )
{
auto renderMesh = GetRenderMesh(i);
if( renderMesh != nullptr )
m_computedLocalBoundingBox = vaBoundingBox::Combine( m_computedLocalBoundingBox, renderMesh->GetAABB() );
else
m_computedLocalBoundingBoxIncomplete = true;
}
}
void vaSceneObject::UIPropertiesItemTick( vaApplicationBase &, bool , bool )
{
#ifdef VA_IMGUI_INTEGRATION_ENABLED
auto scene = m_scene.lock();
assert( scene != nullptr );
if( ImGui::Button( "Rename" ) )
ImGuiEx_PopupInputStringBegin( "Rename object", m_name );
ImGuiEx_PopupInputStringTick( "Rename object", m_name );
ImGui::SameLine();
if( ImGui::Button( "Delete" ) )
{
scene->DestroyObject( this->shared_from_this(), false, true );
return;
}
bool transChanged = false;
vaMatrix4x4 localTransform = m_localTransform;
transChanged |= ImGui::InputFloat4( "LocalTransformRow0", &localTransform.m[0][0] );
transChanged |= ImGui::InputFloat4( "LocalTransformRow1", &localTransform.m[1][0] );
transChanged |= ImGui::InputFloat4( "LocalTransformRow2", &localTransform.m[2][0] );
transChanged |= ImGui::InputFloat4( "LocalTransformRow3", &localTransform.m[3][0] );
if( transChanged )
{
SetLocalTransform( localTransform );
}
/*
vaVector3 raxis; float rangle;
m_rotation.ToAxisAngle( raxis, rangle );
rangle = rangle * 180.0f / VA_PIf;
bool changed = ImGui::InputFloat3( "Rotation axis", &raxis.x );
changed |= ImGui::InputFloat( "Rotation angle", &rangle, 5.0f, 30.0f, 3 );
if( changed )
m_rotation = vaQuaternion::RotationAxis( raxis, rangle * VA_PIf / 180.0f );
*/
string parentName = (m_parent == nullptr)?("none"):(m_parent->GetName().c_str() );
ImGui::Text( "Parent: %s", parentName.c_str() );
ImGui::Text( "Child object count: %d", m_children.size() );
ImGui::Text( "Render mesh count: %d", m_renderMeshes.size() );
if( ImGui::BeginChild( "rendermeshlist", { 0, ImGui::GetFontSize() * 8 }, true ) )
{
for( int meshIndex = 0; meshIndex < m_renderMeshes.size(); meshIndex++ )
{
vaGUID & meshID = m_renderMeshes[meshIndex];
string prefix = vaStringTools::Format( "%03d - ", meshIndex );
if( meshID == vaGUID::Null )
{
ImGui::Selectable( (prefix + "[null GUID]").c_str(), false, ImGuiSelectableFlags_Disabled );
continue;
}
auto renderMesh = GetRenderMesh( meshIndex );
if( renderMesh == nullptr ) // maybe still loading
{
ImGui::Selectable( ( prefix + "[not found]" ).c_str( ), false, ImGuiSelectableFlags_Disabled );
continue;
}
vaAsset * assetPtr = renderMesh->GetParentAsset();
if( assetPtr == nullptr )
{
ImGui::Selectable( ( prefix + "[not an asset]" ).c_str( ), false, ImGuiSelectableFlags_Disabled );
continue;
}
shared_ptr<vaAsset> asset = assetPtr->GetSharedPtr( );
if( asset == nullptr )
{
ImGui::Selectable( ( prefix + "[error acquiring shared_ptr]" ).c_str( ), false, ImGuiSelectableFlags_Disabled );
continue;
}
if( ImGui::Selectable( (prefix + assetPtr->Name( )).c_str( ), false, ImGuiSelectableFlags_AllowDoubleClick ) )
{
if( ImGui::IsMouseDoubleClicked( 0 ) )
vaUIManager::GetInstance( ).SelectPropertyItem( asset );
}
if( asset->GetResource( ) != nullptr && ImGui::IsItemHovered( ) )
asset->GetResource( )->SetUIShowSelectedFrameIndex( asset->GetAssetPack().GetRenderDevice().GetCurrentFrameIndex( ) + 1 );
}
}
ImGui::EndChild( );
#endif
}
int vaSceneObject::SplitMeshes( const std::vector<vaPlane> & splitPlanes, std::vector<shared_ptr<vaRenderMesh>> & outOldMeshes, std::vector<shared_ptr<vaRenderMesh>> & outNewMeshes, const int minTriangleCountThreshold, const std::vector<shared_ptr<vaRenderMesh>> & candidateMeshes, bool splitIfIntersectingTriangles )
{
int totalSplitCount = 0;
int splitCount;
vaMatrix4x4 worldTransform = GetWorldTransform();
std::vector<uint32> newIndicesLeft, newIndicesRight;
do
{
splitCount = 0;
for( int meshIndex = 0; meshIndex < m_renderMeshes.size( ); meshIndex++ )
{
auto renderMesh = GetRenderMesh(meshIndex);
assert( renderMesh != nullptr ); // still loading?
if( renderMesh == nullptr )
continue;
// if has candidate filter, use that but also consider any newly created a candidate because they must have inherited the original one
if( candidateMeshes.size() > 0 )
{
bool found = false;
for( int cmi = 0; cmi < candidateMeshes.size() && !found; cmi++ )
found |= candidateMeshes[cmi] == renderMesh;
for( int cmi = 0; cmi < outNewMeshes.size() && !found; cmi++ )
found |= outNewMeshes[cmi] == renderMesh;
if( !found )
continue;
}
const std::vector<vaRenderMesh::StandardVertex> & vertices = renderMesh->Vertices();
const std::vector<uint32> & indices = renderMesh->Indices();
for( int planeIndex = 0; planeIndex < splitPlanes.size(); planeIndex++ )
{
const vaPlane & plane = splitPlanes[planeIndex];
newIndicesLeft.clear();
newIndicesRight.clear();
for( int triIndex = 0; triIndex < indices.size( ); triIndex += 3 )
{
const vaRenderMesh::StandardVertex & a = vertices[ indices[ triIndex + 0 ] ];
const vaRenderMesh::StandardVertex & b = vertices[ indices[ triIndex + 1 ] ];
const vaRenderMesh::StandardVertex & c = vertices[ indices[ triIndex + 2 ] ];
vaVector3 posA = vaVector3::TransformCoord( a.Position, worldTransform );
vaVector3 posB = vaVector3::TransformCoord( b.Position, worldTransform );
vaVector3 posC = vaVector3::TransformCoord( c.Position, worldTransform );
float signA = vaMath::Sign( plane.DotCoord( posA ) );
float signB = vaMath::Sign( plane.DotCoord( posB ) );
float signC = vaMath::Sign( plane.DotCoord( posC ) );
int direction = 0; // 0 means no split, -1 means goes to the left, 1 means goes to the right
// must all be on one or the other side, otherwise don't split
if( !splitIfIntersectingTriangles )
{
if( signA != signB || signA != signC )
direction = 0;
else if( signA < 0 && signB < 0 && signC < 0 )
direction = -1;
else
{
assert( signA >= 0 && signB >= 0 && signC >= 0 );
direction = 1;
}
}
else // will split towards the one with the most
{
direction = ((signA+signB+signC+1)<0)?(-1):(1);
}
if( direction == 0 )
{
//vaDebugCanvas3D::GetInstance().DrawTriangle( posA, posB, posC, 0xFFFF0000, 0x80FF0000 );
newIndicesLeft.clear();
newIndicesRight.clear();
break;
}
else if( direction == -1 )
{
//vaDebugCanvas3D::GetInstance().DrawTriangle( posA, posB, posC, 0xFF00FF00, 0x8000FF00 );
newIndicesLeft.push_back( indices[ triIndex + 0 ] );
newIndicesLeft.push_back( indices[ triIndex + 1 ] );
newIndicesLeft.push_back( indices[ triIndex + 2 ] );
}
else
{
assert( direction == 1 );
//vaDebugCanvas3D::GetInstance().DrawTriangle( posA, posB, posC, 0xFF0000FF, 0x800000FF );
newIndicesRight.push_back( indices[ triIndex + 0 ] );
newIndicesRight.push_back( indices[ triIndex + 1 ] );
newIndicesRight.push_back( indices[ triIndex + 2 ] );
}
}
if( newIndicesLeft.size( ) > (minTriangleCountThreshold*3) && newIndicesRight.size( ) > (minTriangleCountThreshold*3) )
{
vaAsset * originalRenderMeshAsset = renderMesh->GetParentAsset();
VA_LOG( "Splitting mesh '%s' (%d triangles) with a plane %d into left part with %d triangles and right part with %d triangles",
originalRenderMeshAsset->Name().c_str(), (int)renderMesh->Indices().size()/3, planeIndex, (int)newIndicesLeft.size()/3, (int)newIndicesRight.size()/3 );
// do the split!
shared_ptr<vaRenderMesh::StandardTriangleMesh> newMeshLeft = std::make_shared<vaRenderMesh::StandardTriangleMesh>( renderMesh->GetRenderDevice() );
shared_ptr<vaRenderMesh::StandardTriangleMesh> newMeshRight = std::make_shared<vaRenderMesh::StandardTriangleMesh>( renderMesh->GetRenderDevice() );
// fill up our 'left' and 'right' meshes
for( int triIndex = 0; triIndex < newIndicesLeft.size( ); triIndex += 3 )
{
const vaRenderMesh::StandardVertex & a = vertices[ newIndicesLeft[ triIndex + 0 ] ];
const vaRenderMesh::StandardVertex & b = vertices[ newIndicesLeft[ triIndex + 1 ] ];
const vaRenderMesh::StandardVertex & c = vertices[ newIndicesLeft[ triIndex + 2 ] ];
newMeshLeft->AddTriangleMergeDuplicates<vaRenderMesh::StandardVertex>( a, b, c, vaRenderMesh::StandardVertex::IsDuplicate, 512 );
}
for( int triIndex = 0; triIndex < newIndicesRight.size( ); triIndex += 3 )
{
const vaRenderMesh::StandardVertex & a = vertices[ newIndicesRight[ triIndex + 0 ] ];
const vaRenderMesh::StandardVertex & b = vertices[ newIndicesRight[ triIndex + 1 ] ];
const vaRenderMesh::StandardVertex & c = vertices[ newIndicesRight[ triIndex + 2 ] ];
newMeshRight->AddTriangleMergeDuplicates<vaRenderMesh::StandardVertex>( a, b, c, vaRenderMesh::StandardVertex::IsDuplicate, 512 );
}
// replace the current mesh with the left and the right split parts
// increment the counter
splitCount++;
// create new meshes
shared_ptr<vaRenderMesh> newRenderMeshLeft = vaRenderMesh::Create( newMeshLeft, renderMesh->GetFrontFaceWindingOrder(), renderMesh->GetMaterialID() );
shared_ptr<vaRenderMesh> newRenderMeshRight = vaRenderMesh::Create( newMeshRight, renderMesh->GetFrontFaceWindingOrder(), renderMesh->GetMaterialID() );
// add them to the original asset pack so they can get saved
originalRenderMeshAsset->GetAssetPack().Add( newRenderMeshLeft, originalRenderMeshAsset->Name() + "_l", true );
originalRenderMeshAsset->GetAssetPack().Add( newRenderMeshRight, originalRenderMeshAsset->Name() + "_r", true );
// for external tracking (& removal if needed)
outOldMeshes.push_back( renderMesh );
outNewMeshes.push_back( newRenderMeshLeft );
outNewMeshes.push_back( newRenderMeshRight );
// remove the current one and add the splits
RemoveRenderMeshRef( meshIndex );
AddRenderMeshRef( newRenderMeshLeft );
AddRenderMeshRef( newRenderMeshRight );
// ok now reset the search to the beginning so we can re-do the split meshes if there's more splitting to be done
meshIndex--;
break;
}
}
}
totalSplitCount += splitCount;
} while ( splitCount > 0 );
return totalSplitCount;
}
void vaSceneObject::ReplaceMaterialsWithXXX( )
{
string prefix = "xxx_";
for( int i = 0; i < m_renderMeshes.size( ); i++ )
{
auto renderMesh = GetRenderMesh( i );
auto renderMaterial = (renderMesh != nullptr)?(renderMesh->GetMaterial()):(nullptr);
vaAsset * renderMaterialAsset = (renderMaterial != nullptr)?(renderMaterial->GetParentAsset()):(nullptr);
if( renderMaterialAsset != nullptr )
{
string name = renderMaterialAsset->Name();
if( name.substr(0, prefix.length()) == prefix )
{
VA_LOG( "Skipping material '%s'...", name.c_str() );
continue;
}
VA_LOG( "Searching for material replacement for '%s'...", name.c_str() );
vaAssetPackManager & mgr = renderMaterial->GetRenderDevice().GetAssetPackManager( );
shared_ptr<vaAsset> replacementAsset = mgr.FindAsset( prefix+name );
if( replacementAsset == nullptr )
{
VA_LOG_WARNING( " replacement not found!" );
continue;
}
if( replacementAsset->Type != vaAssetType::RenderMaterial )
{
VA_LOG_WARNING( " replacement found but wrong type!" );
continue;
}
VA_LOG_SUCCESS(" replacement found!" );
renderMesh->SetMaterial( replacementAsset->GetResource<vaRenderMaterial>() );
}
else
{
assert( false );
}
}
}
void vaSceneObject::EnumerateUsedAssets( const std::function<void(vaAsset * asset)> & callback )
{
for( int i = 0; i < m_renderMeshes.size( ); i++ )
{
auto renderMesh = GetRenderMesh( i );
if( renderMesh != nullptr && renderMesh->GetParentAsset( ) != nullptr )
renderMesh->EnumerateUsedAssets( callback );
}
}
vaSceneOld::vaSceneOld( ) : vaUIPanel( "SceneOld", 1, true, vaUIPanel::DockLocation::DockedLeft, "SceneOlds" )
{
Clear();
}
vaSceneOld::vaSceneOld( const string & name ) : vaUIPanel( "Scene", 1, true, vaUIPanel::DockLocation::DockedLeft, "Scenes" )
{
Clear( );
m_name = name;
}
vaSceneOld::~vaSceneOld( )
{
// this might be ok or might not be ok - you've got some
assert( m_deferredObjectActions.size() == 0 );
Clear();
}
void vaSceneOld::Clear( )
{
m_deferredObjectActions.clear();
DestroyAllObjects( );
ApplyDeferredObjectActions();
m_name = "";
m_lights.clear();
assert( m_allObjects.size() == 0 );
assert( m_rootObjects.size() == 0 );
m_tickIndex = 0;
m_sceneTime = 0.0;
assert( !m_isInTick );
m_isInTick = false;
}
shared_ptr<vaSceneObject> vaSceneOld::CreateObject( const shared_ptr<vaSceneObject> & parent )
{
return CreateObject( "Unnamed", vaMatrix4x4::Identity, parent );
}
shared_ptr<vaSceneObject> vaSceneOld::CreateObject( const string & name, const vaMatrix4x4 & localTransform, const shared_ptr<vaSceneObject> & parent )
{
m_deferredObjectActions.push_back( DeferredObjectAction( std::make_shared<vaSceneObject>( ), parent, vaSceneOld::DeferredObjectAction::AddObject ) );
m_deferredObjectActions.back().Object->SetName( name );
m_deferredObjectActions.back().Object->SetScene( this->shared_from_this() );
m_deferredObjectActions.back().Object->SetLocalTransform( localTransform );
return m_deferredObjectActions.back().Object;
}
shared_ptr<vaSceneObject> vaSceneOld::CreateObject( const string & name, const vaVector3 & localScale, const vaQuaternion & localRot, const vaVector3 & localPos, const shared_ptr<vaSceneObject> & parent )
{
return CreateObject( name, vaMatrix4x4::FromScaleRotationTranslation( localScale, localRot, localPos ), parent );
}
void vaSceneOld::DestroyObject( const shared_ptr<vaSceneObject> & ptr, bool destroyChildrenRecursively, bool applyOwnTransformToChildren )
{
assert( ptr->GetScene() != nullptr );
if( applyOwnTransformToChildren )
{
// doesn't make sense to apply transform to children if you're destroying them as well
assert( !destroyChildrenRecursively );
}
// mark the object as no longer functional
ptr->MarkAsDestroyed( destroyChildrenRecursively );
if( destroyChildrenRecursively )
{
m_deferredObjectActions.push_back( DeferredObjectAction( ptr, nullptr, vaSceneOld::DeferredObjectAction::RemoveObjectAndChildren ) );
}
else
{
// we can do this right now
if( applyOwnTransformToChildren )
{
const vaMatrix4x4 & parentTransform = ptr->GetLocalTransform();
const std::vector<shared_ptr<vaSceneObject>> & children = ptr->GetChildren();
for( int i = 0; i < (int)children.size(); i++ )
{
const vaMatrix4x4 newTransform = parentTransform * children[i]->GetLocalTransform();
children[i]->SetLocalTransform( newTransform );
}
}
m_deferredObjectActions.push_back( DeferredObjectAction( ptr, nullptr, vaSceneOld::DeferredObjectAction::RemoveObject ) );
}
//assert( m_deferredObjectActions.back().Object.unique() );
}
void vaSceneOld::DestroyAllObjects( )
{
m_deferredObjectActions.push_back( DeferredObjectAction( nullptr, nullptr, vaSceneOld::DeferredObjectAction::RemoveAllObjects ) );
}
void vaSceneOld::RegisterRootObjectAdded( const shared_ptr<vaSceneObject> & object )
{
if( m_isInTick )
{
assert( false ); // Can't call this while in tick
return;
}
assert( std::find( m_rootObjects.begin(), m_rootObjects.end(), object ) == m_rootObjects.end() );
m_rootObjects.push_back( object );
}
void vaSceneOld::RegisterRootObjectRemoved( const shared_ptr<vaSceneObject> & object )
{
if( m_isInTick )
{
assert( false ); // Can't call this while in tick
return;
}
bool allOk = vector_find_and_remove( m_rootObjects, object ) != -1;
assert( allOk ); // if this fires, there's a serious error somewhere!
allOk;
}
void vaSceneOld::ApplyDeferredObjectActions( )
{
if( m_isInTick )
{
assert( false ); // Can't call this while in tick
return;
}
for( int i = 0; i < m_deferredObjectActions.size( ); i++ )
{
const DeferredObjectAction & mod = m_deferredObjectActions[i];
if( mod.Action == vaSceneOld::DeferredObjectAction::RemoveAllObjects )
{
for( int j = 0; j < (int)m_allObjects.size(); j++ )
m_allObjects[j]->NukeGraph( );
m_rootObjects.clear();
for( int j = 0; j < m_allObjects.size( ); j++ )
{
// this pointer should be unique now. otherwise you're holding a pointer somewhere although the object was destroyed - is this
// intended? if there's a case where this is intended, think it through in detail - there's a lot of potential for unforeseen
// consequences from accessing vaSceneObject-s in this state.
assert( m_allObjects[i].use_count() == 1 ); // this assert is not entirely correct for multithreaded scenarios so beware
}
m_allObjects.clear();
}
else if( mod.Action == vaSceneOld::DeferredObjectAction::AddObject )
{
// by default in root, will be removed on "add parent" - this can be optimized out if desired (no need to call if parent != nullptr) but
// it leaves the object in a broken state temporarily and SetParent needs to get adjusted and maybe something else too
m_rootObjects.push_back( mod.Object );
mod.Object->SetParent( mod.ParentObject );
m_allObjects.push_back( mod.Object );
mod.Object->SetAddedToScene();
}
else if( mod.Action == vaSceneOld::DeferredObjectAction::RemoveObject || mod.Action == vaSceneOld::DeferredObjectAction::RemoveObjectAndChildren )
{
bool destroyChildrenRecursively = mod.Action == vaSceneOld::DeferredObjectAction::RemoveObjectAndChildren;
// they should automatically remove themselves from the list as they get deleted or reattached to this object's parent
if( !destroyChildrenRecursively )
{
const std::vector<shared_ptr<vaSceneObject>> & children = mod.Object->GetChildren();
while( children.size() > 0 )
{
// we >have< to make this a temp, as the SetParent modifies the containing array!!
shared_ptr<vaSceneObject> temp = children[0];
assert( this->shared_from_this() == temp->GetScene() );
temp->SetParent( mod.Object->GetParent() );
}
}
DestroyObjectImmediate( mod.Object, destroyChildrenRecursively );
}
}
m_deferredObjectActions.clear();
}
void vaSceneOld::DestroyObjectImmediate( const shared_ptr<vaSceneObject> & obj, bool recursive )
{
assert( obj->IsDestroyed() ); // it must have already been destroyed
//assert( obj->GetScene() == nullptr ); // it must have been already set to null
obj->SetParent( nullptr );
obj->SetScene( nullptr );
bool allOk = vector_find_and_remove( m_rootObjects, obj ) != -1;
assert( allOk );
allOk = vector_find_and_remove( m_allObjects, obj ) != -1;
assert( allOk );
if( recursive )
{
const std::vector<shared_ptr<vaSceneObject>> & children = obj->GetChildren();
while( obj->GetChildren().size( ) > 0 )
{
// we >have< to make this a temp, as the DestroyObject modifies both the provided reference and the containing array!!
shared_ptr<vaSceneObject> temp = children[0];
DestroyObjectImmediate( temp, true );
}
}
// this pointer should be unique now. otherwise you're holding a pointer somewhere although the object was destroyed - is this
// intended? if there's a case where this is intended, think it through in detail - there's a lot of potential for unforeseen
// consequences from accessing vaSceneObject-s in this state.
assert( obj.use_count() == 1 ); // this assert is not entirely correct for multithreaded scenarios so beware
}
void vaSceneOld::Tick( float deltaTime )
{
VA_TRACE_CPU_SCOPE( vaScene_Tick );
ApplyDeferredObjectActions();
if( deltaTime > 0 )
{
m_sceneTime += deltaTime;
assert( !m_isInTick );
m_isInTick = true;
m_tickIndex++;
for( int i = 0; i < m_rootObjects.size( ); i++ )
{
m_rootObjects[i]->TickRecursive( *this, deltaTime );
}
assert( m_isInTick );
m_isInTick = false;
ApplyDeferredObjectActions();
m_UI_MouseClickIndicatorRemainingTime = vaMath::Max( m_UI_MouseClickIndicatorRemainingTime - deltaTime, 0.0f );
}
}
void vaSceneOld::ApplyToLighting( vaSceneLighting & lighting )
{
VA_TRACE_CPU_SCOPE( vaScene_ApplyToLighting );
lighting.SetLights( m_lights );
// lighting.SetEnvmap( m_envmapTexture, m_envmapRotation, m_envmapColorMultiplier );
lighting.FogSettings() = m_fog;
}
bool vaSceneOld::SerializeObjectsRecursive( vaXMLSerializer & serializer, const string & name, std::vector<shared_ptr<vaSceneObject>> & objectList, const shared_ptr<vaSceneObject> & parent )
{
if( m_isInTick )
{
assert( false ); // Can't call this while in tick
return false;
}
VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeOpenChildElement( name.c_str() ) );
uint32 count = (uint32)objectList.size();
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<uint32>( "count", count ) );
if( serializer.IsReading() )
{
assert( objectList.size() == 0 );
// objectList.resize( count );
}
string elementName;
for( uint32 i = 0; i < count; i++ )
{
elementName = vaStringTools::Format( "%s_%d", name.c_str(), i );
VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeOpenChildElement( elementName.c_str() ) );
shared_ptr<vaSceneObject> obj = nullptr;
if( serializer.IsReading() )
obj = CreateObject( parent );
else
obj = objectList[i];
obj->Serialize( serializer );
VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializePopToParentElement( elementName.c_str() ) );
}
// if( serializer.IsReading() )
// {
// // should have count additions
// // assert( m_deferredObjectActions.size() == count );
// }
VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializePopToParentElement( name.c_str() ) );
return true;
}
bool vaSceneOld::Serialize( vaXMLSerializer & serializer, bool mergeToExistingIfLoading )
{
if( m_isInTick )
{
assert( false ); // Can't call this while in tick
return false;
}
if( serializer.IsWriting( ) && mergeToExistingIfLoading )
{
assert( false ); // this combination makes no sense
mergeToExistingIfLoading = false;
}
// calling Serialize with non-applied changes? probably a bug somewhere (if not, just call ApplyDeferredObjectActions() before getting here)
assert( m_deferredObjectActions.size() == 0 );
if( m_deferredObjectActions.size() != 0 )
return false;
if( serializer.SerializeOpenChildElement( "VanillaScene" ) )
{
if( serializer.IsReading() && !mergeToExistingIfLoading )
Clear();
string mergingName;
if( mergeToExistingIfLoading )
{
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "Name", mergingName ) );
//vaVector3 mergingAmbientLight;
//VERIFY_TRUE_RETURN_ON_FALSE( serializer.OldSerializeValue( "AmbientLight", mergingAmbientLight ) );
std::vector<shared_ptr<vaLight>> mergingLights;
if( serializer.GetVersion() > 0 )
VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeArray( "Lights", mergingLights ) );
else
{ assert( false ); }
m_lights.insert( m_lights.end(), mergingLights.begin(), mergingLights.end() );
//serializer.Serialize<string>( "DistantIBLPath", m_IBLProbeDistantImagePath );
}
else
{
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "Name", m_name ) );
/*VERIFY_TRUE_RETURN_ON_FALSE(*/ serializer.Serialize<vaGUID>( "UID", m_UID, vaGUID::Create( ) );// );
//VERIFY_TRUE_RETURN_ON_FALSE( serializer.OldSerializeValue( "AmbientLight", m_lightAmbient ) );
if( serializer.GetVersion() > 0 )
VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeArray( "Lights", m_lights ) );
else
{ assert( false ); }
//serializer.SerializeArray( "Inputs", "Item", m_lights );
//serializer.Serialize<string>( "DistantIBLPath", m_IBLProbeDistantImagePath );
}
VERIFY_TRUE_RETURN_ON_FALSE( SerializeObjectsRecursive( serializer, "RootObjects", m_rootObjects, nullptr ) );
VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaXMLSerializable>( "FogSphere", m_fog ) );
///*VERIFY_TRUE_RETURN_ON_FALSE(*/ m_fog.Serialize( serializer );
/*VERIFY_TRUE_RETURN_ON_FALSE*/( serializer.Serialize( "IBLProbeLocal", m_IBLProbeLocal ) );
/*VERIFY_TRUE_RETURN_ON_FALSE*/( serializer.Serialize( "IBLProbeDistant", m_IBLProbeDistant ) );
// serializer.Serialize<string>( "IBLProbeDistantImagePath", m_IBLProbeDistantImagePath );
bool ok = serializer.SerializePopToParentElement( "VanillaScene" );
assert( ok );
if( serializer.IsReading() && ok )
{
return PostLoadInit();
}
return ok;
}
else
{
VA_LOG_WARNING( L"Unable to load scene, unexpected contents." );
}
return false;
}
bool vaSceneOld::PostLoadInit( )
{
ApplyDeferredObjectActions( );
return true;
}
// void vaSceneOld::UpdateUsedPackNames( )
// {
// m_assetPackNames.clear();
// for( auto sceneObject : m_allObjects )
// {
// sceneObject->RegisterUsedAssetPacks( std::bind( &vaSceneOld::RegisterUsedAssetPackNameCallback, this, std::placeholders::_1 ) );
// }
// }
void vaSceneOld::RegisterUsedAssetPackNameCallback( const vaAssetPack & assetPack )
{
for( size_t i = 0; i < m_assetPackNames.size(); i++ )
{
if( vaStringTools::ToLower( m_assetPackNames[i] ) == vaStringTools::ToLower( assetPack.GetName() ) )
{
// found, all is good
return;
}
}
// not found, add to list
m_assetPackNames.push_back( assetPack.GetName() );
}
void vaSceneOld::RemoveAllUnusedAssets( const std::vector<shared_ptr<vaAssetPack>>& assetPacks )
{
std::set<vaAsset*> allAssets;
for( size_t i = 0; i < assetPacks.size(); i++ )
{
vaAssetPack & pack = *assetPacks[i];
assert( !pack.IsBackgroundTaskActive( ) );
std::unique_lock<mutex> assetStorageMutexLock( pack.GetAssetStorageMutex( ) );
for( size_t j = 0; j < pack.Count( false ); j++ )
allAssets.insert( pack.AssetAt( j, false ).get() );
}
auto removeFromSet = [ &allAssets ]( vaAsset* asset )
{
if( asset != nullptr )
allAssets.erase( asset );
};
for( auto sceneObject : m_allObjects )
sceneObject->EnumerateUsedAssets( removeFromSet );
for( auto asset : allAssets )
asset->GetAssetPack().Remove( asset, true );
}
// void vaSceneOld::LoadAndConnectAssets( )
// {
// }
#ifdef VA_IMGUI_INTEGRATION_ENABLED
static shared_ptr<vaSceneObject> ImGuiDisplaySceneObjectTreeRecursive( const std::vector<shared_ptr<vaSceneObject>> & elements, const shared_ptr<vaSceneObject> & selectedObject )
{
ImGuiTreeNodeFlags defaultFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
shared_ptr<vaSceneObject> ret = nullptr;
for( int i = 0; i < elements.size(); i++ )
{
ImGuiTreeNodeFlags nodeFlags = defaultFlags | ((elements[i] == selectedObject)?(ImGuiTreeNodeFlags_Selected):(0)) | ((elements[i]->GetChildren().size() == 0)?(ImGuiTreeNodeFlags_Leaf):(0));
bool nodeOpen = ImGui::TreeNodeEx( elements[i]->UIPropertiesItemGetUniqueID().c_str(), nodeFlags, elements[i]->GetName().c_str() );
if( ImGui::IsItemClicked() )
{
ret = elements[i];
}
if( nodeOpen )
{
if( elements[i]->GetChildren().size() > 0 )
{
shared_ptr<vaSceneObject> retRec = ImGuiDisplaySceneObjectTreeRecursive( elements[i]->GetChildren(), selectedObject );
if( retRec != nullptr )
ret = retRec;
}
ImGui::TreePop();
}
}
return ret;
}
#endif
bool vaSceneOld::Save( const wstring & fileName )
{
// calling Save with non-applied changes? probably a bug somewhere (if not, just call ApplyDeferredObjectActions() before getting here)
assert( m_deferredObjectActions.size() == 0 );
vaFileStream fileOut;
if( fileOut.Open( fileName, FileCreationMode::OpenOrCreate, FileAccessMode::Write ) )
{
vaXMLSerializer serializer;
VA_LOG( L"Writing '%s'.", fileName.c_str() );
if( !Serialize( serializer, false ) )
{
VA_LOG_WARNING( L"Error while serializing the scene" );
fileOut.Close();
return false;
}
serializer.WriterSaveToFile( fileOut );
fileOut.Close();
VA_LOG( L"Scene successfully saved to '%s'.", fileName.c_str() );
return true;
}
else
{
VA_LOG_WARNING( L"Unable to save scene to '%s', file error.", fileName.c_str() );
return false;
}
}
bool vaSceneOld::Load( const wstring & fileName, bool mergeToExisting )
{
// calling Load with non-applied changes? probably a bug somewhere (if not, just call ApplyDeferredObjectActions() before getting here)
assert( m_deferredObjectActions.size() == 0 );
if( m_isInTick )
{
assert( false ); // Can't call this while in tick
return false;
}
vaFileStream fileIn;
if( vaFileTools::FileExists( fileName ) && fileIn.Open( fileName, FileCreationMode::Open ) )
{
vaXMLSerializer serializer( fileIn );
fileIn.Close();
if( serializer.IsReading( ) )
{
VA_LOG( L"Reading '%s'.", fileName.c_str() );
if( !Serialize( serializer, mergeToExisting ) )
{
VA_LOG_WARNING( L"Error while serializing the scene" );
fileIn.Close();
return false;
}
VA_LOG( L"Scene successfully loaded from '%s', running PostLoadInit()", fileName.c_str() );
return true;
}
else
{
VA_LOG_WARNING( L"Unable to parse xml file '%s', file error.", fileName.c_str() );
return false;
}
}
else
{
VA_LOG_WARNING( L"Unable to load scene from '%s', file error.", fileName.c_str() );
return false;
}
}
void vaSceneOld::UIPanelTick( vaApplicationBase & application )
{
application;
#ifdef VA_IMGUI_INTEGRATION_ENABLED
ImGui::PushItemWidth( 200.0f );
if( ImGui::Button( " Rename " ) )
ImGuiEx_PopupInputStringBegin( "Rename scene", m_name );
if( ImGuiEx_PopupInputStringTick( "Rename scene", m_name ) )
{
//m_name = vaStringTools::ToLower( m_name );
VA_LOG( "Scene name changed to '%s'", m_name.c_str() );
}
ImGui::SameLine();
if( ImGui::Button( " Delete all contents " ) )
{
Clear();
return;
}
if( ImGui::Button( " Save As... " ) )
{
wstring fileName = vaFileTools::SaveFileDialog( L"", vaCore::GetExecutableDirectory(), L".xml scene files\0*.xml\0\0" );
if( fileName != L"" )
{
if( vaFileTools::SplitPathExt( fileName ) == L"" ) // if no extension, add .xml
fileName += L".xml";
Save( fileName );
}
}
ImGui::SameLine();
if( ImGui::Button( " Load... " ) )
{
wstring fileName = vaFileTools::OpenFileDialog( L"", vaCore::GetExecutableDirectory(), L".xml scene files\0*.xml\0\0" );
Load( fileName, false );
}
ImGui::SameLine();
if( ImGui::Button( " Load and merge... " ) )
{
wstring fileName = vaFileTools::OpenFileDialog( L"", vaCore::GetExecutableDirectory(), L".xml scene files\0*.xml\0\0" );
Load( fileName, true );
}
ImGui::Separator();
#if 0
if( ImGui::Button( " Replace materials with xxx_" ) )
{
for( auto sceneObject : m_allObjects )
sceneObject->ReplaceMaterialsWithXXX();
}
if( ImGui::Button( " Remove all assets from all asset packs not used by this scene" ) )
{
RemoveAllUnusedAssets( application.GetRenderDevice().GetAssetPackManager().GetAllAssetPacks() );
}
ImGui::Separator( );
#endif
if( m_allObjects.size() > 0 )
{
ImGui::Text( "Scene objects: %d", m_allObjects.size() );
float uiListHeight = 120.0f;
float uiPropertiesHeight = 180.0f;
shared_ptr<vaSceneObject> selectedObject = m_UI_SelectedObject.lock();
if( m_UI_ShowObjectsAsTree )
{
std::vector<shared_ptr<vaSceneObject>> elements = m_rootObjects;
if( ImGui::BeginChild( "TreeFrame", ImVec2( 0.0f, uiListHeight ), true ) )
{
shared_ptr<vaSceneObject> objectClicked = ImGuiDisplaySceneObjectTreeRecursive( m_rootObjects, selectedObject );
if( objectClicked != nullptr )
{
if( selectedObject != objectClicked )
selectedObject = objectClicked;
else
selectedObject = nullptr;
m_UI_SelectedObject = selectedObject;
}
}
ImGui::EndChild();
if( ImGui::BeginChild( "PropFrame", ImVec2( 0.0f, uiPropertiesHeight ), true ) )
{
if( selectedObject != nullptr )
{
ImGui::PushID( selectedObject->UIPropertiesItemGetUniqueID( ).c_str( ) );
selectedObject->UIPropertiesItemTick( application, false, false );
ImGui::PopID();
}
else
{
ImGui::TextColored( ImVec4( 0.5f, 0.5f, 0.5f, 1.0f ), "Select an item to display properties" );
}
}
ImGui::EndChild();
}
else
{
vaUIPropertiesItem * ptrsToDisplay[ 65536 ]; // if this ever becomes not enough, change DrawList into a template and make it accept allObjects directly...
int countToShow = std::min( (int)m_allObjects.size(), (int)_countof(ptrsToDisplay) );
int currentObject = -1;
for( int i = 0; i < countToShow; i++ )
{
if( m_UI_SelectedObject.lock() == m_allObjects[i] )
currentObject = i;
ptrsToDisplay[i] = m_allObjects[i].get();
}
vaUIPropertiesItem::DrawList( application, "Objects", ptrsToDisplay, countToShow, currentObject, 0.0f, uiListHeight, uiPropertiesHeight );
if( currentObject >= 0 && currentObject < countToShow )
m_UI_SelectedObject = m_allObjects[currentObject];
else
m_UI_SelectedObject.reset();
}
}
else
{
ImGui::Text( "No objects" );
}
ImGui::Separator();
ImGui::Text( "Scene lights: %d", m_lights.size() );
if( m_lights.size() > 0 )
{
vaUIPropertiesItem * ptrsToDisplay[ 4096 ];
int countToShow = std::min( (int)m_lights.size(), (int)_countof(ptrsToDisplay) );
for( int i = 0; i < countToShow; i++ ) ptrsToDisplay[i] = m_lights[i].get();
int currentLight = -1;
for( int i = 0; i < countToShow; i++ )
{
if( m_UI_SelectedLight.lock() == m_lights[i] )
currentLight = i;
ptrsToDisplay[i] = m_lights[i].get();
}
vaUIPropertiesItem::DrawList( application, "Lights", ptrsToDisplay, countToShow, currentLight, 0.0f, 90, 200 );
if( currentLight >= 0 && currentLight < countToShow )
m_UI_SelectedLight = m_lights[currentLight];
if( currentLight >= 0 && currentLight < m_lights.size() )
{
if( ImGui::Button( "Duplicate" ) )
{
m_lights.push_back( std::make_shared<vaLight>( *m_lights[currentLight] ) );
m_lights.back()->Name += "_new";
m_UI_SelectedLight = m_lights.back();
}
ImGui::SameLine();
if( ImGui::Button( "Delete" ) )
{
m_lights.erase( m_lights.begin() + currentLight );
}
}
}
else
{
ImGui::Text( "No lights" );
}
if( ImGui::Button( "Add light" ) )
{
m_lights.push_back( std::make_shared<vaLight>( vaLight::MakePoint( "NewLight", 0.2f, vaVector3( 0, 0, 0 ), 0.0f, vaVector3( 0, 0, 0 ) ) ) );
}
ImGui::Checkbox( "Debug draw scene lights", &m_UI_ShowLights );
ImGui::Separator();
ImGui::Text( "Scene cleanup tools:" );
if( ImGui::Button( "Remove redundant hierarchy" ) )
{
for( int i = 0; i < m_allObjects.size(); i++ )
{
const shared_ptr<vaSceneObject> & obj = m_allObjects[i];
if( obj->GetRenderMeshCount( ) == 0 && obj->GetChildren().size() == 1 )
{
DestroyObject( obj, false, true );
}
}
}
if( ImGui::Button( "Remove missing render mesh references" ) )
{
for( int i = 0; i < m_allObjects.size( ); i++ )
{
const shared_ptr<vaSceneObject> & obj = m_allObjects[i];
for( int j = obj->GetRenderMeshCount( ) - 1; j >= 0; j-- )
{
if( obj->GetRenderMesh( j ) == nullptr )
{
obj->RemoveRenderMeshRef( j );
VA_LOG( "Removed mesh %d from scene object '%s'", j, obj->GetName().c_str() );
}
}
}
}
m_fog.UIPropertiesItemTickCollapsable( application, false, false );
ImGui::Separator( );
// IBL properties
{
vaDebugCanvas3D& canvas3D = application.GetRenderDevice( ).GetCanvas3D( ); canvas3D;
string idPrefix = m_UID.ToString( ) + "_IBL_";
Scene::IBLProbe * probes[] = { &m_IBLProbeLocal, &m_IBLProbeDistant };
string probeNames[] = { "Local IBL", "Distant IBL" };
for( int i = 0; i < countof( probes ); i++ )
{
Scene::IBLProbe & probe = *probes[i];
const string & probeName = probeNames[i];
ImGui::Text( probeName.c_str() );
switch( ImGuiEx_SameLineSmallButtons( probeName.c_str(), { "[props]" } ) )
{
case( -1 ): break;
case( 0 ):
{
string uniqueID = idPrefix + std::to_string(i);
if( vaUIManager::GetInstance( ).FindTransientPropertyItem( uniqueID, true ) == nullptr )
{
auto uiContext = std::make_shared<vaIBLProbe::UIContext>( shared_from_this( ) );
vaUIManager::GetInstance( ).CreateTransientPropertyItem( uniqueID, m_name + " : " + probeName,
[ &probe, uniqueID, probeName ]( vaApplicationBase& application, const shared_ptr<void>& drawContext ) -> bool
{
auto uiContext = std::static_pointer_cast<vaIBLProbe::UIContext>( drawContext ); assert( uiContext != nullptr );
auto aliveToken = ( uiContext != nullptr ) ? ( uiContext->AliveToken.lock( ) ) : ( shared_ptr<void>( ) );
if( !aliveToken )
return false;
vaDebugCanvas3D& canvas3D = application.GetRenderDevice( ).GetCanvas3D( ); canvas3D;
if( ImGui::InputText( "Input file", &probe.ImportFilePath ) )
probe.SetImportFilePath( probe.ImportFilePath, false );
ImGui::SameLine( );
if( ImGui::Button( "..." ) )
{
string fileName = vaFileTools::OpenFileDialog( probe.ImportFilePath, vaCore::GetExecutableDirectoryNarrow( ) );
if( fileName != "" )
probe.SetImportFilePath( probe.ImportFilePath, false );
}
ImGui::Separator();
// capture position
#if 0 // disabled due to changes in the MoveRotateScaleWidget tool
{
vaMatrix4x4 probeMat = vaMatrix4x4::FromTranslation( probe.Position );
bool mrsWidgetActive = vaUIManager::GetInstance( ).MoveRotateScaleWidget( uniqueID+"c", probeName + " [capture position]", probeMat );
if( mrsWidgetActive )
{
ImGui::Text( "<MRSWidget Active>" );
probe.Position = probeMat.GetTranslation( );
canvas3D.DrawSphere( probe.Position, 0.1f, 0xFF00FF00 );
}
else
{
vaVector3 pos = probe.Position;
if( ImGui::InputFloat3( "Translate", &pos.x, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue ) )
probe.Position = pos;
}
}
#endif
ImGui::Checkbox( "Use OBB geometry proxy", &probe.UseGeometryProxy );
if( probe.UseGeometryProxy )
{
vaMatrix4x4 probeMat = probe.GeometryProxy.ToScaledTransform( );
// activate move rotate scale widget
#if 0 // disabled due to changes in the MoveRotateScaleWidget tool
bool mrsWidgetActive = vaUIManager::GetInstance( ).MoveRotateScaleWidget( uniqueID+"p", probeName + " [geometry proxy]", probeMat );
if( mrsWidgetActive )
{
ImGui::Text( "<MRSWidget Active>" );
probe.GeometryProxy = vaOrientedBoundingBox::FromScaledTransform( probeMat );
canvas3D.DrawBox( probe.GeometryProxy, 0xFF00FF00, 0x10808000 );
}
else
{
if( ImGuiEx_Transform( uniqueID.c_str( ), probeMat, false, false ) )
probe.GeometryProxy = vaOrientedBoundingBox::FromScaledTransform( probeMat );
}
#endif
if( ImGui::Button( "Set capture center to geometry proxy center", {-1, 0} ) )
probe.Position = probe.GeometryProxy.Center;
}
if( ImGui::CollapsingHeader( "Local to Global transition region", ImGuiTreeNodeFlags_Framed /*| ImGuiTreeNodeFlags_DefaultOpen*/ ) )
{
vaMatrix4x4 transform = probe.FadeOutProxy.ToScaledTransform( );
#if 0 // disabled due to changes in the MoveRotateScaleWidget tool
bool mrsWidgetActive = vaUIManager::GetInstance( ).MoveRotateScaleWidget( uniqueID + "lgtr", "Local to global IBL transition region", transform );
if( mrsWidgetActive )
{
ImGui::Text( "<MRSWidget Active>" );
probe.FadeOutProxy = vaOrientedBoundingBox::FromScaledTransform( transform );
canvas3D.DrawBox( probe.FadeOutProxy, 0xFF00FF00, 0x10008080 );
}
else
{
if( ImGuiEx_Transform( ( uniqueID + "lgtr" ).c_str( ), transform, false, false ) )
probe.FadeOutProxy = vaOrientedBoundingBox::FromScaledTransform( transform );
}
#endif
}
ImGui::Separator();
vaVector3 colorSRGB = vaVector3::LinearToSRGB( probe.AmbientColor );
if( ImGui::ColorEdit3( "Ambient Color", &colorSRGB.x, ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float ) )
probe.AmbientColor = vaVector3::SRGBToLinear( colorSRGB );
ImGui::InputFloat( "Ambient Color Intensity", &probe.AmbientColorIntensity );
return true;
}, uiContext );
}
}; break;
default: assert( false ); break;
}
}
ImGui::Separator( );
}
DrawUI( application.GetUICamera( ), application.GetRenderDevice( ).GetCanvas2D( ), application.GetRenderDevice( ).GetCanvas3D( ) );
ImGui::PopItemWidth( );
#endif
}
void vaSceneOld::DrawUI( const vaCameraBase & camera, vaDebugCanvas2D & canvas2D, vaDebugCanvas3D & canvas3D )
{
VA_TRACE_CPU_SCOPE( vaScene_DrawUI );
canvas2D;
camera;
float pulse = 0.5f * (float)vaMath::Sin( m_sceneTime * VA_PIf * 2.0f ) + 0.5f;
auto selectedObject = m_UI_SelectedObject.lock();
if( selectedObject != nullptr )
{
canvas3D.DrawBox( selectedObject->GetGlobalAABB(), vaVector4::ToBGRA( 0.0f, 0.0f + pulse, 0.0f, 1.0f ), vaVector4::ToBGRA( 0.5f, 0.5f, 0.5f, 0.1f ) );
}
if( m_UI_MouseClickIndicatorRemainingTime > 0 )
{
float factor = vaMath::Sin( (1.0f - m_UI_MouseClickIndicatorRemainingTime / m_UI_MouseClickIndicatorTotalTime) * VA_PIf );
canvas3D.DrawSphere( m_UI_MouseClickIndicator, factor * 0.1f, 0xA0000000, 0x2000FF00 );
}
if( m_UI_ShowLights )
{
string idPrefix = m_UID.ToString( ) + "_Lights_";
for( int i = 0; i < (int)m_lights.size( ); i++ )
{
if( m_lights[i]->Type == vaLight::Type::Ambient || m_lights[i]->Type == vaLight::Type::Directional )
continue;
string uniqueID = idPrefix + std::to_string( reinterpret_cast<uint64>( m_lights[i].get() ) );
vaVector3 vecRight = vaVector3::Cross( m_lights[i]->Up, m_lights[i]->Direction );
if( vecRight.LengthSq() < VA_EPSf )
vecRight = vaVector3::Cross( vaVector3( 0, 1, 0 ), m_lights[i]->Direction );
if( vecRight.LengthSq( ) < VA_EPSf )
vecRight = vaVector3::Cross( vaVector3( 1, 0, 0 ), m_lights[i]->Direction );
vaVector3 vecUp = vaVector3::Cross( m_lights[i]->Direction, vecRight ).Normalized( );
vaMatrix3x3 lightRotation = vaMatrix3x3( m_lights[i]->Direction.Normalized(), vecRight, vecUp );
vaMatrix4x4 lightTransform = vaMatrix4x4::FromRotationTranslation( lightRotation, m_lights[i]->Position );
#if 0 // disabled due to changes in the MoveRotateScaleWidget tool
vaUIManager::GetInstance().MoveRotateScaleWidget( uniqueID, m_lights[i]->Name + "(light)", lightTransform );
#endif
}
for( int i = 0; i < (int)m_lights.size(); i++ )
{
const vaLight & light = *m_lights[i];
vaVector4 sphereColor = vaVector4( 0.5f, 0.5f, 0.5f, 0.1f );
vaVector4 wireframeColor;
switch( light.Type )
{
case( vaLight::Type::Ambient ): wireframeColor = vaVector4( 0.5f, 0.5f, 0.5f, 1.0f ); break;
case( vaLight::Type::Directional ): wireframeColor = vaVector4( 1.0f, 1.0f, 0.0f, 1.0f ); break;
case( vaLight::Type::Point ): wireframeColor = vaVector4( 0.0f, 1.0f, 0.0f, 1.0f ); break;
case( vaLight::Type::Spot ): wireframeColor = vaVector4( 0.0f, 0.0f, 1.0f, 1.0f ); break;
default: assert( false );
}
float sphereSize = light.Size;
bool isSelected = m_lights[i] == m_UI_SelectedLight.lock();
if( isSelected )
sphereColor.w += pulse * 0.2f - 0.09f;
canvas3D.DrawSphere( light.Position, sphereSize, vaVector4::ToBGRA( wireframeColor ), vaVector4::ToBGRA( sphereColor ) );
if( light.Type == vaLight::Type::Directional || light.Type == vaLight::Type::Spot )
canvas3D.DrawLine( light.Position, light.Position + 2.0f * light.Direction * sphereSize, 0xFF000000 );
if( light.Type == vaLight::Type::Spot && isSelected )
{
vaVector3 lightUp = vaVector3::Cross( vaVector3( 0.0f, 0.0f, 1.0f ), light.Direction );
if( lightUp.Length() < 1e-3f )
lightUp = vaVector3::Cross( vaVector3( 0.0f, 1.0f, 0.0f ), light.Direction );
lightUp = lightUp.Normalized();
vaVector3 coneInner = vaVector3::TransformNormal( light.Direction, vaMatrix3x3::RotationAxis( lightUp, light.SpotInnerAngle ) );
vaVector3 coneOuter = vaVector3::TransformNormal( light.Direction, vaMatrix3x3::RotationAxis( lightUp, light.SpotOuterAngle ) );
float coneRadius = 0.1f + light.Range; //light.EffectiveRadius();
const int lineCount = 50;
for( int j = 0; j < lineCount; j++ )
{
float angle = j / (float)(lineCount-1) * VA_PIf * 2.0f;
vaVector3 coneInnerR = vaVector3::TransformNormal( coneInner, vaMatrix3x3::RotationAxis( light.Direction, angle ) );
vaVector3 coneOuterR = vaVector3::TransformNormal( coneOuter, vaMatrix3x3::RotationAxis( light.Direction, angle ) );
canvas3D.DrawLine( light.Position, light.Position + coneRadius * sphereSize * coneInnerR, 0xFFFFFF00 );
canvas3D.DrawLine( light.Position, light.Position + coneRadius * sphereSize * coneOuterR, 0xFFFF0000 );
}
}
}
}
}
void vaSceneOld::SetSkybox( vaRenderDevice & device, const string & texturePath, const vaMatrix3x3 & rotation, float colorMultiplier )
{
shared_ptr<vaTexture> skyboxTexture = vaTexture::CreateFromImageFile( device, vaStringTools::SimpleNarrow(vaCore::GetExecutableDirectory()) + texturePath, vaTextureLoadFlags::Default );
if( skyboxTexture == nullptr )
{
VA_LOG_WARNING( "vaSceneOld::SetSkybox - unable to load '%'", texturePath.c_str() );
}
else
{
m_skyboxTexturePath = texturePath;
m_skyboxTexture = skyboxTexture;
m_skyboxRotation = rotation;
m_skyboxColorMultiplier = colorMultiplier;
}
}
//void vaSceneOld::SetEnvmap( vaRenderDevice & device, const string & texturePath, const vaMatrix3x3 & rotation, float colorMultiplier )
//{
// shared_ptr<vaTexture> skyboxTexture = vaTexture::CreateFromImageFile( device, vaStringTools::SimpleNarrow( vaCore::GetExecutableDirectory( ) ) + texturePath, vaTextureLoadFlags::Default );
// if( skyboxTexture == nullptr )
// {
// VA_LOG_WARNING( "vaSceneOld::SetSkybox - unable to load '%'", texturePath.c_str( ) );
// }
// else
// {
// m_envmapTexturePath = texturePath;
// m_envmapTexture = skyboxTexture;
// m_envmapRotation = rotation;
// m_envmapColorMultiplier = colorMultiplier;
// }
//}
vaDrawResultFlags vaSceneOld::SelectForRendering( vaRenderInstanceList * opaqueList, vaRenderInstanceList * transparentList, const vaRenderInstanceList::FilterSettings & filter, const SelectionFilterCallback & customFilter )
{
VA_TRACE_CPU_SCOPE( vaScene_SelectForRendering );
if( opaqueList != nullptr )
opaqueList->Start( );
if( transparentList != nullptr )
transparentList->Start( );
for( auto object : m_allObjects )
object->SelectForRendering( opaqueList, transparentList, filter, customFilter );
//renderSelection.MeshList.Insert()
vaDrawResultFlags drawResults = vaDrawResultFlags::None;
if( opaqueList != nullptr )
{
opaqueList->Stop();
drawResults |= opaqueList->ResultFlags();
}
if( transparentList != nullptr )
{
transparentList->Stop();
drawResults |= opaqueList->ResultFlags( );
}
//g_doCull = false;
return drawResults;
}
std::vector<shared_ptr<vaSceneObject>> vaSceneOld::FindObjects( std::function<bool(vaSceneObject&obj)> searchCriteria )
{
std::vector<shared_ptr<vaSceneObject>> ret;
for( auto object : m_allObjects )
{
if( searchCriteria( *object ) )
ret.push_back( object );
}
return std::move(ret);
}
void vaSceneOld::OnMouseClick( const vaVector3 & worldClickLocation )
{
worldClickLocation;
#if 0
m_UI_MouseClickIndicatorRemainingTime = m_UI_MouseClickIndicatorTotalTime;
m_UI_MouseClickIndicator = worldClickLocation;
shared_ptr<vaSceneObject> closestHitObj = nullptr;
float maxHitDist = 0.5f;
for( auto rootObj : m_rootObjects )
rootObj->FindClosestRecursive( worldClickLocation, closestHitObj, maxHitDist );
VA_LOG( "vaSceneOld - mouse clicked at (%.2f, %.2f, %.2f) world position.", worldClickLocation.x, worldClickLocation.y, worldClickLocation.z );
// if same, just de-select
if( closestHitObj != nullptr && m_UI_SelectedObject.lock() == closestHitObj )
closestHitObj = nullptr;
auto previousSel = m_UI_SelectedObject.lock();
if( previousSel != nullptr )
{
VA_LOG( "vaSceneOld - deselecting object '%s'", previousSel->GetName().c_str() );
}
if( closestHitObj != nullptr )
{
VA_LOG( "vaSceneOld - selecting object '%s'", closestHitObj->GetName().c_str() );
}
m_UI_SelectedObject = closestHitObj;
#endif
}
shared_ptr<vaSceneObject> vaSceneOld::CreateObjectWithSystemMesh( vaRenderDevice & device, const string & systemMeshName, const vaMatrix4x4 & transform )
{
auto renderMeshAsset = device.GetAssetPackManager().GetDefaultPack()->Find( systemMeshName );
if( renderMeshAsset == nullptr )
{
VA_WARN( "InsertSystemMeshByName failed - can't find system asset '%s'", systemMeshName.c_str() );
return nullptr;
}
shared_ptr<vaRenderMesh> renderMesh = dynamic_cast<vaAssetRenderMesh*>(renderMeshAsset.get())->GetRenderMesh();
auto sceneObject = CreateObject( "obj_" + systemMeshName, transform );
sceneObject->AddRenderMeshRef( renderMesh );
return sceneObject;
}
std::vector<shared_ptr<vaSceneObject>> vaSceneOld::InsertAllPackMeshesToSceneAsObjects( vaSceneOld & scene, vaAssetPack & pack, const vaMatrix4x4 & transform )
{
vaVector3 scale, translation; vaQuaternion rotation;
transform.Decompose( scale, rotation, translation );
std::vector<shared_ptr<vaSceneObject>> addedObjects;
assert( !pack.IsBackgroundTaskActive() );
std::unique_lock<mutex> assetStorageMutexLock( pack.GetAssetStorageMutex() );
for( size_t i = 0; i < pack.Count( false ); i++ )
{
auto asset = pack.AssetAt( i, false );
if( asset->Type == vaAssetType::RenderMesh )
{
shared_ptr<vaRenderMesh> renderMesh = dynamic_cast<vaAssetRenderMesh*>(asset.get())->GetRenderMesh();
if( renderMesh == nullptr )
continue;
auto sceneObject = scene.CreateObject( "obj_" + asset->Name(), transform );
sceneObject->AddRenderMeshRef( renderMesh );
addedObjects.push_back( sceneObject );
}
}
return addedObjects;
}
int vaSceneOld::SplitMeshes( const std::vector<vaPlane> & splitPlanes, std::vector<shared_ptr<vaRenderMesh>> & outOldMeshes, std::vector<shared_ptr<vaRenderMesh>> & outNewMeshes, const int minTriangleCountThreshold, const std::vector<shared_ptr<vaRenderMesh>> & candidateMeshes, bool splitIfIntersectingTriangles )
{
// use example:
// std::vector<shared_ptr<vaRenderMesh>> oldMeshes;
// std::vector<shared_ptr<vaRenderMesh>> newMeshes;
// m_currentScene->SplitMeshes( choicePlanes, oldMeshes, newMeshes );
// for( int i = 0; i < oldMeshes.size(); i++ )
// oldMeshes[i]->GetParentAsset()->GetAssetPack().Remove( oldMeshes[i]->GetParentAsset(), true );
int totalSplitCount = 0;
int splitCount;
do
{
splitCount = 0;
for( auto object : m_allObjects )
splitCount += object->SplitMeshes( splitPlanes, outOldMeshes, outNewMeshes, minTriangleCountThreshold, candidateMeshes, splitIfIntersectingTriangles );
totalSplitCount += splitCount;
} while ( splitCount > 0 );
return totalSplitCount;
}
void vaSceneObject::ToNewRecursive( vaScene & scene, vaSceneObject * parentObj, entt::entity parentEntity )
{
vaGUID singleMesh = (m_renderMeshes.size( ) == 1)?(m_renderMeshes[0]):(vaGUID::Null);
entt::entity thisEntity = scene.CreateEntity( m_name, m_localTransform, parentEntity, singleMesh );
if( m_renderMeshes.size() > 1 )
{
for( int i = 0; i < m_renderMeshes.size( ); i++ )
scene.CreateEntity( vaStringTools::Format("mesh_%04d", i), vaMatrix4x4::Identity, thisEntity, m_renderMeshes[i] );
}
for( int i = 0; i < m_children.size( ); i++ )
m_children[i]->ToNewRecursive( scene, parentObj, thisEntity );
}
shared_ptr<vaScene> vaSceneOld::ToNew( ) const
{
shared_ptr<vaScene> scene = std::make_shared<vaScene>( m_name );
entt::entity globalsParent = scene->CreateEntity( "Globals" );
if( m_fog.Enabled )
{
Scene::FogSphere fogSphere;
fogSphere.Enabled = m_fog.Enabled;
fogSphere.UseCustomCenter = m_fog.UseCustomCenter;
fogSphere.Center = m_fog.Center;
fogSphere.Color = m_fog.Color;
fogSphere.RadiusInner = m_fog.RadiusInner;
fogSphere.RadiusOuter = m_fog.RadiusOuter;
fogSphere.BlendCurvePow = m_fog.BlendCurvePow;
fogSphere.BlendMultiplier = m_fog.BlendMultiplier;
entt::entity fogEntity = scene->CreateEntity( "Fog", vaMatrix4x4::FromTranslation(fogSphere.Center), globalsParent );
scene->Registry().emplace<Scene::FogSphere>( fogEntity, fogSphere );
}
if( m_skyboxTexturePath != "" )
{
Scene::SkyboxTexture skyboxTexture;
skyboxTexture.Path = m_skyboxTexturePath;
skyboxTexture.ColorMultiplier = m_skyboxColorMultiplier;
skyboxTexture.UID = vaGUID::Null;
skyboxTexture.Enabled = true;
entt::entity skyboxEntity = scene->CreateEntity( "Skybox", vaMatrix4x4(m_skyboxRotation.Transposed()), globalsParent );
scene->Registry( ).emplace<Scene::SkyboxTexture>( skyboxEntity, skyboxTexture );
}
if( m_IBLProbeDistant.Enabled )
{
Scene::DistantIBLProbe probe; static_cast<Scene::IBLProbe&>(probe) = m_IBLProbeDistant;
entt::entity probeEntity = scene->CreateEntity( "DistantIBLProbe", vaMatrix4x4::FromTranslation( probe.Position ), globalsParent );
scene->Registry( ).emplace<Scene::DistantIBLProbe>( probeEntity, probe );
}
if( m_IBLProbeLocal.Enabled )
{
Scene::LocalIBLProbe probe; static_cast<Scene::IBLProbe&>( probe ) = m_IBLProbeLocal;
entt::entity probeEntity = scene->CreateEntity( "LocalIBLProbe", vaMatrix4x4::FromTranslation( probe.Position ), globalsParent );
scene->Registry( ).emplace<Scene::LocalIBLProbe>( probeEntity, probe );
}
for( size_t i = 0; i < m_rootObjects.size( ); i++ )
{
m_rootObjects[i]->ToNewRecursive( *scene );
}
entt::entity lightsParent = scene->CreateEntity( "Lights" );
for( size_t i = 0; i < m_lights.size( ); i++ )
{
const vaLight & light = *m_lights[i];
vaMatrix3x3 rot = vaMatrix3x3::Identity;
if( light.Type != vaLight::Type::Ambient )
{
rot.Row(0) = light.Direction;
rot.Row(1) = vaVector3::Cross( light.Up, light.Direction );
rot.Row(2) = light.Up;
if( rot.Row(1).Length() < 0.99f )
vaVector3::ComputeOrthonormalBasis( light.Direction, rot.Row(1), rot.Row(2) );
}
entt::entity lightEntity = scene->CreateEntity( /*vaStringTools::Format("light_%04d", i)*/light.Name, vaMatrix4x4::FromRotationTranslation( rot, light.Position ), lightsParent );
switch( light.Type )
{
case( vaLight::Type::Ambient ):
{
auto & newLight = scene->Registry().emplace<Scene::LightAmbient>( lightEntity );
newLight.Color = light.Color;
newLight.Intensity = light.Intensity;
newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f);
} break;
case( vaLight::Type::Directional ):
{
auto & newLight = scene->Registry().emplace<Scene::LightDirectional>( lightEntity );
newLight.Color = light.Color;
newLight.Intensity = light.Intensity;
newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f);
newLight.AngularRadius = light.AngularRadius;
newLight.HaloSize = light.HaloSize;
newLight.HaloFalloff = light.HaloFalloff;
newLight.CastShadows = light.CastShadows;
} break;
case( vaLight::Type::Point ):
{
auto & newLight = scene->Registry().emplace<Scene::LightPoint>( lightEntity );
newLight.Color = light.Color;
newLight.Intensity = light.Intensity;
newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f);
newLight.Size = light.Size;
newLight.Range = light.Range;
newLight.SpotInnerAngle = 0.0f;
newLight.SpotOuterAngle = 0.0f;
newLight.CastShadows = light.CastShadows;
} break;
case( vaLight::Type::Spot ):
{
auto & newLight = scene->Registry().emplace<Scene::LightPoint>( lightEntity );
newLight.Color = light.Color;
newLight.Intensity = light.Intensity;
newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f);
newLight.Size = light.Size;
newLight.Range = light.Range;
newLight.SpotInnerAngle = light.SpotInnerAngle;
newLight.SpotOuterAngle = light.SpotOuterAngle;
newLight.CastShadows = light.CastShadows;
} break;
default: assert( false );
}
}
return scene;
}
#endif | 40.06398 | 317 | 0.600576 | GameTechDev |
3ec33c63edbfe1fc15410e4eb9fc1645a8bda611 | 1,772 | cpp | C++ | projects/biogears/libBiogears/src/pybwrappers/cdm/patient/actions/pybSEUseInhaler.cpp | vybhavramachandran/mophy | 7271c12b85a324a4f1494e0ce15942dc25bc4931 | [
"Apache-2.0"
] | null | null | null | projects/biogears/libBiogears/src/pybwrappers/cdm/patient/actions/pybSEUseInhaler.cpp | vybhavramachandran/mophy | 7271c12b85a324a4f1494e0ce15942dc25bc4931 | [
"Apache-2.0"
] | 5 | 2020-12-23T00:19:32.000Z | 2020-12-29T20:53:58.000Z | projects/biogears/libBiogears/src/pybwrappers/cdm/patient/actions/pybSEUseInhaler.cpp | vybhavramachandran/biogears-vybhav | 7271c12b85a324a4f1494e0ce15942dc25bc4931 | [
"Apache-2.0"
] | null | null | null | // #include <biogears/cdm/utils/Logger.h>
// #include <biogears/cdm/substance/SESubstanceManager.h>
// #include <biogears/cdm/utils/DataTrack.h>
// #include <biogears/cdm/scenario/requests/SEDataRequest.h>
#include <biogears/exports.h>
#include <string>
#include <pybind11/pybind11.h>
#include <biogears/cdm/patient/actions/SEPatientAction.h>
#include <biogears/schema/cdm/PatientActions.hxx>
#include <biogears/cdm/patient/actions/SEUseInhaler.h>
// #include <biogears/cdm/patient/actions/SESubstanceAdministration.h>
// #include <biogears/cdm/CommonDataModel.h>
// #include <biogears/cdm/properties/SEScalar0To1.h>
// #include <biogears/cdm/properties/SEScalarMassPerVolume.h>
// #include <biogears/cdm/properties/SEScalarTime.h>
// #include <biogears/cdm/properties/SEScalarVolume.h>
// #include <biogears/cdm/substance/SESubstanceCompound.h>
#include <biogears/cdm/properties/SEScalarVolumePerTime.h>
#include <biogears/cdm/substance/SESubstance.h>
#include <biogears/schema/cdm/Scenario.hxx>
#include <biogears/cdm/patient/actions/SEConsciousRespirationCommand.h>
namespace py = pybind11;
PYBIND11_MODULE(pybSEUseInhaler, m) {
py::class_<biogears::SEUseInhaler, biogears::SEConsciousRespirationCommand>(m, "SEUseInhaler")
// .def(py::init<>())
.def("Clear",&biogears::SEUseInhaler::Clear)
.def("IsValid",&biogears::SEUseInhaler::IsValid)
.def("IsActive",&biogears::SEUseInhaler::IsActive)
.def("Load",&biogears::SEUseInhaler::Load)
.def("Unload",py::overload_cast<>(&biogears::SEUseInhaler::Unload,py::const_))
.def("ToString",py::overload_cast<std::ostream&>(&biogears::SEUseInhaler::ToString,py::const_));
#ifdef VERSION_INFO
m.attr("__version__") = VERSION_INFO;
#else
m.attr("__version__") = "dev";
#endif
} | 37.702128 | 100 | 0.751129 | vybhavramachandran |
3ec46d071b2cfe7d5e6c77f2940634d579514c23 | 3,453 | hpp | C++ | interfaces/IGraphicLib.hpp | rectoria/cpp_arcade | 72bff5ec97f90dcc05ff4079f7ba30d5af9fb147 | [
"MIT"
] | null | null | null | interfaces/IGraphicLib.hpp | rectoria/cpp_arcade | 72bff5ec97f90dcc05ff4079f7ba30d5af9fb147 | [
"MIT"
] | null | null | null | interfaces/IGraphicLib.hpp | rectoria/cpp_arcade | 72bff5ec97f90dcc05ff4079f7ba30d5af9fb147 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2018
** arcade
** File description:
** arcade
*/
/*!
* @file IGraphicLib.hpp
* @brief Graphic libraries dedicated class interface
* @authors https://github.com/EPITECH-Strasbourg-2021/CPP-Arcade-Spec
*
* Interface used by graphic libraries
* All functions must be implemented correctly for the kernel to handle the graphic libraries.
*
*/
#pragma once
#include <string>
#include "Vect.hpp"
#include "PixelBox.hpp"
#include "TextBox.hpp"
#include "Keys.hpp"
/*!
* @namespace Arcade
* @brief Arcade project namespace
*/
namespace Arcade {
/*!
* @class IGraphicLib
* @brief Graphic libraries virtual class
*
* Purely virtual class that serves as the basis for all graphic libraries
*
*/
class IGraphicLib {
public:
/*!
* @brief Destructor
*
* IGraphicLib class's destructor
*
*/
virtual ~IGraphicLib() = default;
/*!
* @brief Graphic library name's getter
* @return a string containing the name of the graphic library
*/
virtual std::string getName() const = 0;
/* Window handling */
/*!
* @brief Specifies whether the window is open or not
* @return true if open, otherwise returns false
*/
virtual bool isOpen() const = 0;
/*!
* @brief Closes the rendering support
*
* Usually closes a window.
* Some graphic library uses other rendering support.
*
*/
virtual void closeRenderer() = 0;
/*!
* @brief Opens the rendering support
* @param title : Title of the rendering support if supported
*
* Usually opens a window.
* Some graphic library uses other rendering support.
*
*/
virtual void openRenderer(std::string const &title) = 0;
/*!
* @brief Clears the rendering support
*/
virtual void clearWindow() = 0;
/*!
* @brief Displays the buffered frame to the screen
*/
virtual void refreshWindow() = 0;
/* Rendering functions */
/*!
* @brief Draws a PixelBox
*/
virtual void drawPixelBox(PixelBox const &) = 0;
/*!
* @brief Draws a TextBox
*/
virtual void drawText(TextBox const &) = 0;
/* EVENT HANDLING */
/*!
* @brief Fetches the events from the user and saves it
* @return true if at least one command has been fetched, otherwise returns false
*
* Fetched commands are usually stored inside a std::vector<Arcade::Keys> or std::list<Arcade::Keys>
*
*/
virtual bool pollEvents() = 0;
/*!
* @brief Getter of the oldest command in memory
* @return the first event of the list.
*
* The function deletes the command if it succeed to retrieves one,
* using front() and pop_front() methods
*
*/
virtual Keys getLastEvent() = 0;
/*!
* @brief Clears the pending commands
*
* The function deletes all the commands currently stored.
* They wont be accessible anymore, even with the getLastEvent() method.
*
*/
virtual void clearEvents() = 0;
/* Context Info */
/*!
* @brief Getter from the rendering support dimensions
* @return a two dimensions vector containing the width and the height of the rendering support
*/
virtual Vect<size_t> getScreenSize() const = 0;
/*!
* @brief Getter from the rendering support height
* @return the height of the rendering support
*/
virtual size_t getMaxY() const = 0;
/*!
* @brief Getter from the rendering support width
* @return the width of the rendering support
*/
virtual size_t getMaxX() const = 0;
};
};
| 22.717105 | 102 | 0.662612 | rectoria |
3ec495b668fb3126e7dae077dd21b64517cae81c | 3,530 | cpp | C++ | src/hip_surface.cpp | Maetveis/hipamd | f5b5c4269ed9b250f9907fbdf412e2341846369e | [
"MIT"
] | null | null | null | src/hip_surface.cpp | Maetveis/hipamd | f5b5c4269ed9b250f9907fbdf412e2341846369e | [
"MIT"
] | null | null | null | src/hip_surface.cpp | Maetveis/hipamd | f5b5c4269ed9b250f9907fbdf412e2341846369e | [
"MIT"
] | null | null | null | /* Copyright (c) 2015 - 2022 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#include <hip/hip_runtime.h>
#include "hip_internal.hpp"
#include <hip/surface_types.h>
hipError_t ihipFree(void* ptr);
struct __hip_surface {
uint32_t imageSRD[HIP_IMAGE_OBJECT_SIZE_DWORD];
amd::Image* image;
hipResourceDesc resDesc;
__hip_surface(amd::Image* image_, const hipResourceDesc& resDesc_)
: image(image_), resDesc(resDesc_) {
amd::Context& context = *hip::getCurrentDevice()->asContext();
amd::Device& device = *context.devices()[0];
device::Memory* imageMem = image->getDeviceMemory(device);
std::memcpy(imageSRD, imageMem->cpuSrd(), sizeof(imageSRD));
}
};
hipError_t ihipCreateSurfaceObject(hipSurfaceObject_t* pSurfObject,
const hipResourceDesc* pResDesc) {
amd::Device* device = hip::getCurrentDevice()->devices()[0];
const device::Info& info = device->info();
// Validate input params
if (pSurfObject == nullptr || pResDesc == nullptr) {
return hipErrorInvalidValue;
}
// the type of resource must be a HIP array
// hipResourceDesc::res::array::array must be set to a valid HIP array handle.
if ((pResDesc->resType != hipResourceTypeArray) || (pResDesc->res.array.array == nullptr)) {
return hipErrorInvalidValue;
}
amd::Image* image = nullptr;
cl_mem memObj = reinterpret_cast<cl_mem>(pResDesc->res.array.array->data);
if (!is_valid(memObj)) {
return hipErrorInvalidValue;
}
image = as_amd(memObj)->asImage();
void* surfObjectBuffer = nullptr;
hipError_t err = ihipMalloc(&surfObjectBuffer, sizeof(__hip_surface),
CL_MEM_SVM_FINE_GRAIN_BUFFER);
if (surfObjectBuffer == nullptr || err != hipSuccess) {
return hipErrorOutOfMemory;
}
*pSurfObject = new (surfObjectBuffer) __hip_surface{image, *pResDesc};
return hipSuccess;
}
hipError_t hipCreateSurfaceObject(hipSurfaceObject_t* pSurfObject,
const hipResourceDesc* pResDesc) {
HIP_INIT_API(hipCreateSurfaceObject, pSurfObject, pResDesc);
HIP_RETURN(ihipCreateSurfaceObject(pSurfObject, pResDesc));
}
hipError_t ihipDestroySurfaceObject(hipSurfaceObject_t surfaceObject) {
if (surfaceObject == nullptr) {
return hipSuccess;
}
return ihipFree(surfaceObject);
}
hipError_t hipDestroySurfaceObject(hipSurfaceObject_t surfaceObject) {
HIP_INIT_API(hipDestroySurfaceObject, surfaceObject);
HIP_RETURN(ihipDestroySurfaceObject(surfaceObject));
}
| 36.391753 | 94 | 0.737394 | Maetveis |
3ec4affc791f9b8036ba27fbbeed5635ff12a898 | 1,662 | cpp | C++ | buf/appl_bytes_custom.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | buf/appl_bytes_custom.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | buf/appl_bytes_custom.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | /* See LICENSE for license details */
/*
*/
#include <appl_status.h>
#include <appl_predefines.h>
#include <appl_types.h>
#include <object/appl_object.h>
#include <buf/appl_bytes.h>
#include <buf/appl_bytes_base.h>
#include <buf/appl_buf.h>
#include <buf/appl_bytes_descriptor.h>
#include <buf/appl_bytes_custom.h>
//
//
//
appl_bytes_custom::appl_bytes_custom(
struct appl_context * const
p_context) :
appl_bytes_base(
p_context),
m_descriptor()
{
}
//
//
//
appl_bytes_custom::~appl_bytes_custom()
{
}
//
//
//
enum appl_status
appl_bytes_custom::f_init(
struct appl_bytes_custom_descriptor const * const
p_descriptor)
{
enum appl_status
e_status;
m_descriptor =
*(
p_descriptor);
e_status =
appl_status_ok;
return
e_status;
} // f_init()
//
//
//
appl_size_t
appl_bytes_custom::v_cleanup(void)
{
return
sizeof(class appl_bytes_custom);
} // v_cleanup()
//
//
//
enum appl_status
appl_bytes_custom::v_consume(
unsigned char * const
r_value)
{
enum appl_status
e_status;
e_status =
(*(m_descriptor.p_consume))(
m_descriptor.p_void,
r_value);
return
e_status;
} // v_consume()
//
//
//
enum appl_status
appl_bytes_custom::v_produce(
unsigned char const
i_value)
{
enum appl_status
e_status;
e_status =
(*(m_descriptor.p_produce))(
m_descriptor.p_void,
i_value);
return
e_status;
} // v_produce()
/* end-of-file: appl_bytes_custom.cpp */
| 13.735537 | 57 | 0.601685 | fboucher9 |
3ec722c4dc3fa324a5993309fad30e3cc3b4c238 | 57,790 | hpp | C++ | src/signals/signal_4.hpp | Peterskhan/hydrosig | a165fb47f1caba773412ab245efcb0c35374899c | [
"MIT"
] | 2 | 2017-05-11T20:17:27.000Z | 2017-12-29T00:43:14.000Z | src/signals/signal_4.hpp | Peterskhan/hydrosig | a165fb47f1caba773412ab245efcb0c35374899c | [
"MIT"
] | null | null | null | src/signals/signal_4.hpp | Peterskhan/hydrosig | a165fb47f1caba773412ab245efcb0c35374899c | [
"MIT"
] | null | null | null | #pragma once
#ifndef HYDROSIG_SIGNAL_4_HPP_INCLUDED
#define HYDROSIG_SIGNAL_4_HPP_INCLUDED
/*
* MIT License
*
* Copyright (c) 2017 Peter Gyulai
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <type_traits>
#include "src/macros.h"
#include "src/signals/signal_base/signal_base.h"
#include "src/make_funs/make_fun_4.h"
#include "src/comp_funs/comp_fun_4.h"
#include "src/slots/slot_4.hpp"
#include "src/connections/connection_4.hpp"
HYDROSIG_NAMESPACE_BEGIN
/**
* Forward declarations:
* ---------------------
*/
HYDROSIG_TEMPLATE_4_ARG
class connection_4;
/**
* Class declarations:
* -------------------
*/
/**
* @brief This class forms the base of signal types
* with 4 arguments. It is responsible for
* implementing the connection and disconnection
* mechanism, construction and copy/move semantics.
*/
HYDROSIG_TEMPLATE_4_ARG
class signal_4_base : public signal_base
{
public:
/**< Typedef for the slot type */
typedef slot_4<HYDROSIG_4_ARG>
slot_type;
/**< Typedef for the connection type */
typedef connection_4<HYDROSIG_4_ARG>
connection_type;
/**< Typedef for the list of slots */
typedef HYDROSIG_LIST_TYPE<HYDROSIG_SHARED_PTR_TYPE<slot_type>>
slot_list;
/**
* @brief Constructs a signal_4 object.
*/
signal_4_base();
/**
* @brief Constructs a signal_4_base object by copying src.
* @details Signals with connected slots are not meant
* to be copied, and should be only done so when
* the object encapsulating it is being copied.
* Established connections are not copied into the
* new object, and it is set into a default state.
* @param src The signal object to copy.
*/
signal_4_base(const signal_4_base& /*src*/);
/**
* @brief Constructs a signal_4 by moving src.
* @details In the moving process src loses all of
* it's connections, they are transferred
* to this signal. The state of the constructed
* signal is matching the state of src before
* the move construction.
* @param src The signal to move.
*/
signal_4_base(signal_4_base&& src);
/**
* @brief Copy assigns src to this signal.
* @details Signals with connected slots are not meant
* to be copied, and should be only done so when
* the object encapsulating it is being copied.
* Established connections are not copied into the
* new object, and it is set into a default state.
* @param src The signal object to copy.
*/
signal_4_base& operator=(const signal_4_base& /*src*/);
/**
* @brief Move assigns src to this signal.
* @details In the moving process src loses all of
* it's connections, they are transferred
* to this signal. The state of the constructed
* signal is matching the state of src before
* the move assignment.
* @param src The signal to move.
*/
signal_4_base& operator=(signal_4_base&& src);
/**
* @brief Destroys the signal_4.
*/
virtual ~signal_4_base();
/**
* @brief Returns the number of connected slots.
* @return The number of connected slots.
*/
unsigned int size() const;
/**
* @brief Returns whether there are no slots
* are connected to the signal.
* @return True if there are no slots connected,
* false otherwise.
*/
bool empty() const;
/**
* @brief Removes all slots connected to the signal.
*/
void clear();
/**
* @brief Connects a free function to the signal.
* @param function Pointer to the free function.
*/
connection_type connect(Return_type(*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4));
/**
* @brief Connects an object and it's member function
* (with no specifiers) to the signal.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4));
/**
* @brief Connects an object and it's member function
* (with no specifiers) to the signal.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_TRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4));
/**
* @brief Connects an object and it's member function
* (with const specifier) to the signal.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const);
/**
* @brief Connects an object and it's member function
* (with const specifier) to the signal.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_TRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const);
/**
* @brief Connects an object and it's member function
* (with volatile specifier) to the signal.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile);
/**
* @brief Connects an object and it's member function
* (with volatile specifier) to the signal.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_TRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile);
/**
* @brief Connects an object and it's member function
* (with const volatile specifiers) to the signal.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile);
/**
* @brief Connects an object and it's member function
* (with const volatile specifiers) to the signal.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
*/
HYDROSIG_CONNECT_ENABLER_TRACKABLE
connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile);
/**
* @brief Connects a callable object to the signal.
* @details A copy of the callable object is made
* and stored in the created slot.
* @param callable The callable object.
*/
template<class Callable_type>
connection_type connect(Callable_type callable);
/**
* @brief Disconnects a free function indicated by
* a pointer to it.
* @param function Pointer to the free function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
void disconnect(Return_type(*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4),
bool disconnectAll = false);
/**
* @brief Disconnects a member function with no
* specifiers of the given object.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4),
bool disconnectAll = false);
/**
* @brief Disconnects a member function with no
* specifiers of the given object.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4),
bool disconnectAll = false);
/**
* @brief Disconnects a member function with const
* specifier of the given object.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const,
bool disconnectAll = false);
/**
* @brief Disconnects a member function with const
* specifier of the given object.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const,
bool disconnectAll = false);
/**
* @brief Disconnects a member function with volatile
* specifier of the given object.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile,
bool disconnectAll = false);
/**
* @brief Disconnects a member function with volatile
* specifier of the given object.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile,
bool disconnectAll = false);
/**
* @brief Disconnects a member function with const
* volatile specifier of the given object.
* @details This version is used for untrackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile,
bool disconnectAll = false);
/**
* @brief Disconnects a member function with const
* volatile specifier of the given object.
* @details This version is used for trackable objects.
* @param object Pointer to the object.
* @param function Pointer to the member function.
* @param disconnectAll Whether all matching connections
* should be disconnected, or only
* the first match.
*/
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile,
bool disconnectAll = false);
/**
* @brief Disconnects a slot indicated by a pointer to it.
* @details This function is not designed for client code, and
* is used for disconnection by connection objects.
* @param slot_ptr A shared pointer to the slot.
*/
void disconnect(const HYDROSIG_SHARED_PTR_TYPE<slot_type> slot_ptr);
/**
* @brief Removes all invalidated slots from the slot-list.
* @details This function is used upon signal emission, to
* remove invalidated slots before emitting. You
* may need to call this function manually when you
* have objects connected to the signal which are
* frequently destroyed without manual disconnection.
* Otherwise, such connections are automatically
* cleaned up upon the next emission.
*/
void removeInvalidated();
protected:
/**< The list of slots */
slot_list m_slots;
};
/**
* @brief This class represents signals with 4 arguments,
* using the normal (non-returning) emission mode.
*/
HYDROSIG_TEMPLATE_4_ARG
class signal_4 : public signal_4_base<HYDROSIG_4_ARG>
{
public:
/**< Typedef for the slot type */
typedef slot_4<HYDROSIG_4_ARG>
slot_type;
/**< Typedef for the list of slots */
typedef HYDROSIG_LIST_TYPE<HYDROSIG_SHARED_PTR_TYPE<slot_type>>
slot_list;
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in the exact same
* order they were connected to the signal.
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
*/
void emit(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in reverse order
* of they were connected to the signal.
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
*/
void emit_reverse(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in the exact same
* order they were connected to the signal.
* This is a convenience function, which
* calls emit().
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
*/
void operator()(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
/**< Nested class for emitting signals with collected results */
class collected;
/**< Nested class for emitting signals with combined results */
template<class Combiner_type>
class combined;
};
/**
* @brief This class represents signals with 4 arguments,
* using the collected emission mode.
* @details Collected emission means, that the emitting
* functions return a list of the return values
* of slot activations.
*/
HYDROSIG_TEMPLATE_4_ARG
class signal_4<HYDROSIG_4_ARG>::collected : public signal_4_base<HYDROSIG_4_ARG>
{
static_assert(!std::is_same<Return_type, void>::value,
"Return values with type 'void' can not be collected.");
public:
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in the exact same
* order they were connected to the signal.
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
* @return The list of returned values from each slot
* activation.
*/
HYDROSIG_LIST_TYPE<Return_type> emit(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in reverse order
* of they were connected to the signal.
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
* @return The list of returned values from each slot
* activation.
*/
HYDROSIG_LIST_TYPE<Return_type> emit_reverse(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in the exact same
* order they were connected to the signal.
* This is a convenience function, which
* calls emit().
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
* @return The list of returned values from each slot
* activation.
*/
HYDROSIG_LIST_TYPE<Return_type> operator()(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
};
/**
* @brief This class represents signals with 4 arguments,
* using the combined emission mode.
* @details Combined emission means, that the emitting
* functions return a combined result of the
* return values of slot activations using a
* custom combiner.
*/
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
class signal_4<HYDROSIG_4_ARG>::combined
: public signal_4_base<HYDROSIG_4_ARG>
{
static_assert(!std::is_same<Return_type, void>::value,
"Return values with type 'void' can not be combined.");
public:
/**
* @brief Constructs a combined signal with a
* default combiner.
*/
combined();
/**
* @brief Constructs a combined signal with a
* copy of the supplied combiner.
* @param combiner The combiner to use.
*/
combined(const Combiner_type &combiner);
/**
* @brief Constructs a combined signal by
* copying src.
* @details The combiner is being copied, for
* other members, signal_base copy
* semantics are applied.
* @param src The other combined signal to copy.
*/
combined(const combined &src);
/**
* @brief Constructs a combined signal by
* moving src.
* @details The combiner is being moved, for
* other members, signal_base move
* semantics are applied.
* @param src The other combined signal to move.
*/
combined(combined &&src);
/**
* @brief Copy assigns src to this combined signal.
* @details The combiner is being copied, for
* other members, signal_base copy
* semantics are applied.
* @param src The other combined signal to copy
* assign from.
*/
combined& operator=(const combined &src);
/**
* @brief Move assigns src to this combined signal.
* @details The combiner is being moved, for
* other members, signal_base move
* semantics are applied.
* @param src The other combined signal to move
* assign from.
*/
combined& operator=(combined &&src);
/**
* @brief Returns the combiner object used by
* the combined signal.
* @return The internal combiner.
*/
Combiner_type& getCombiner();
/**
* @brief Sets the combiner used by the
* combined signal.
* @param combiner The combiner to set.
*/
void setCombiner(const Combiner_type &combiner);
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in the exact same
* order they were connected to the signal.
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
* @return The combined result of the return values
* of slot activations.
*/
Return_type emit(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in reverse order
* of they were connected to the signal.
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
* @return The combined result of the return values
* of slot activations.
*/
Return_type emit_reverse(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
/**
* @brief Emits the signal by activating all of the
* connected slot's callback functions.
* @details The slots are activated in the exact same
* order they were connected to the signal.
* This is a convenience function, which
* calls emit().
* @param arg1 The first argument.
* @param arg2 The second argument.
* @param arg3 The third argument.
* @param arg4 The fourth argument.
* @return The combined result of the return values
* of slot activations.
*/
Return_type operator()(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4);
protected:
/**< The combiner used by the signal */
HYDROSIG_SHARED_PTR_TYPE<Combiner_type> m_combiner;
};
/**
* Member definitions:
* -------------------
*/
HYDROSIG_TEMPLATE_4_ARG
signal_4_base<HYDROSIG_4_ARG>::signal_4_base()
: signal_base()
{
;
}
HYDROSIG_TEMPLATE_4_ARG
signal_4_base<HYDROSIG_4_ARG>::signal_4_base(
const signal_4_base& /*src*/)
: signal_base()
{
// Do not copy the list of slots
}
HYDROSIG_TEMPLATE_4_ARG
signal_4_base<HYDROSIG_4_ARG>::signal_4_base(
signal_4_base&& src)
: signal_base()
{
// Move the list of slots
HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN
m_slots = std::move(src.m_slots);
m_blocked = src.m_blocked;
HYDROSIG_REMOTE_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
signal_4_base<HYDROSIG_4_ARG>& signal_4_base<HYDROSIG_4_ARG>::operator=(
const signal_4_base& /*src*/)
{
// Do not copy the list of slots
m_blocked = false;
return *this;
}
HYDROSIG_TEMPLATE_4_ARG
signal_4_base<HYDROSIG_4_ARG>& signal_4_base<HYDROSIG_4_ARG>::operator=(
signal_4_base&& src)
{
if(this == &src) return *this;
HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN
HYDROSIG_PROTECTED_BLOCK_BEGIN
// Move the list of slots
m_slots = std::move(src.m_slots);
// Copy the blocking state
m_blocked = src.m_blocked;
HYDROSIG_PROTECTED_BLOCK_END
HYDROSIG_REMOTE_PROTECTED_BLOCK_END
return *this;
}
HYDROSIG_TEMPLATE_4_ARG
signal_4_base<HYDROSIG_4_ARG>::~signal_4_base()
{
;
}
HYDROSIG_TEMPLATE_4_ARG
unsigned int signal_4_base<HYDROSIG_4_ARG>::size() const
{
return m_slots.size();
}
HYDROSIG_TEMPLATE_4_ARG
bool signal_4_base<HYDROSIG_4_ARG>::empty() const
{
return m_slots.empty();
}
HYDROSIG_TEMPLATE_4_ARG
void signal_4_base<HYDROSIG_4_ARG>::clear()
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.clear();
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
typename signal_4_base<HYDROSIG_4_ARG>::connection_type
signal_4_base<HYDROSIG_4_ARG>::connect(
Return_type(*function)(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4))
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(function), validator));
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4))
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4))
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
object->addValidator(validator);
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
object->removeValidator(validator);
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const)
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const)
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
object->addValidator(validator);
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
object->removeValidator(validator);
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile)
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile)
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
object->addValidator(validator);
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
object->removeValidator(validator);
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile)
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4
signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile)
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun(object, function), validator));
object->addValidator(validator);
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
object->removeValidator(validator);
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
template<class Callable_type>
typename signal_4_base<HYDROSIG_4_ARG>::connection_type
signal_4_base<HYDROSIG_4_ARG>::connect(Callable_type callable)
{
HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator;
try {
validator = std::make_shared<connection_validator>();
HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot(
new slot_type(make_fun<HYDROSIG_CALLABLE_4_ARG>
(callable), validator));
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_slots.push_back(newSlot);
HYDROSIG_PROTECTED_BLOCK_END
return connection_type(newSlot,this,validator);
}
catch(...)
{
throw connection_failure();
}
}
HYDROSIG_TEMPLATE_4_ARG
void signal_4_base<HYDROSIG_4_ARG>::disconnect(Return_type(*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4),
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_free_4<HYDROSIG_4_ARG> supplied(function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4),
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4),
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
object->removeValidator((*itBegin)->getValidator());
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const,
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_const_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const,
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_const_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
object->removeValidator((*itBegin)->getValidator());
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile,
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) volatile,
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
object->removeValidator((*itBegin)->getValidator());
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile,
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_const_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_DISCONNECT_ENABLER_TRACKABLE
signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object,
Return_type(Object_type::*function)(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4) const volatile,
bool disconnectAll)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
// Functor from the callable
functor_to_member_const_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function);
// Comparing functors
if(comp_fun(&supplied,(*itBegin)->get_functor()))
{
object->removeValidator((*itBegin)->getValidator());
itBegin = m_slots.erase(itBegin);
if(!disconnectAll)
{
return;
}
}
else
{
itBegin++;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
void signal_4_base<HYDROSIG_4_ARG>::disconnect(
const HYDROSIG_SHARED_PTR_TYPE<slot_type> slot_ptr)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
if(*itBegin == slot_ptr)
{
m_slots.erase(itBegin);
return;
}
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
void signal_4_base<HYDROSIG_4_ARG>::removeInvalidated()
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
typename slot_list::iterator itBegin(m_slots.begin());
typename slot_list::iterator itEnd(m_slots.end());
while(itBegin != itEnd)
{
if(!(*itBegin)->isValid())
{
itBegin = m_slots.erase(itBegin);
continue;
}
itBegin++;
}
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
void signal_4<HYDROSIG_4_ARG>::emit(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
if(this->isBlocked()) return;
this->removeInvalidated();
HYDROSIG_PROTECTED_BLOCK_BEGIN
slot_list copy = this->m_slots;
typename slot_list::iterator itBegin(copy.begin());
typename slot_list::iterator itEnd(copy.end());
HYDROSIG_PROTECTED_BLOCK_END
while(itBegin != itEnd)
{
// Skip the slot if blocked or invalid
if(!(*itBegin)->isValid()
||
(*itBegin)->isBlocked())
{
itBegin++;
continue;
}
// Activating the slot
try {
(*itBegin)->activate(arg1,arg2,arg3,
arg4);
itBegin++;
}
catch(...)
{
throw;
}
}
}
HYDROSIG_TEMPLATE_4_ARG
void signal_4<HYDROSIG_4_ARG>::emit_reverse(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
if(this->isBlocked()) return;
this->removeInvalidated();
HYDROSIG_PROTECTED_BLOCK_BEGIN
slot_list copy = this->m_slots;
typename slot_list::reverse_iterator itBegin(copy.rbegin());
typename slot_list::reverse_iterator itEnd(copy.rend());
HYDROSIG_PROTECTED_BLOCK_END
while(itBegin != itEnd)
{
// Skip the slot if blocked or invalid
if(!(*itBegin)->isValid()
||
(*itBegin)->isBlocked())
{
itBegin++;
continue;
}
// Activating the slot
try {
(*itBegin)->activate(arg1,arg2,arg3,
arg4);
itBegin++;
}
catch(...)
{
throw;
}
}
}
HYDROSIG_TEMPLATE_4_ARG
void signal_4<HYDROSIG_4_ARG>::operator()(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
try {
emit(arg1,arg2,arg3,arg4);
}
catch(...)
{
throw;
}
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_LIST_TYPE<Return_type> signal_4<HYDROSIG_4_ARG>::collected::emit(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
HYDROSIG_LIST_TYPE<Return_type> resultList;
this->removeInvalidated();
if(this->isBlocked()) return resultList;
HYDROSIG_PROTECTED_BLOCK_BEGIN
slot_list copy = this->m_slots;
typename slot_list::iterator itBegin(copy.begin());
typename slot_list::iterator itEnd(copy.end());
HYDROSIG_PROTECTED_BLOCK_END
while(itBegin != itEnd)
{
// Skip the slot if blocked or invalid
if(!(*itBegin)->isValid()
||
(*itBegin)->isBlocked())
{
itBegin++;
continue;
}
// Activating the slot
try {
resultList.push_back((*itBegin)->activate(arg1,arg2,arg3,
arg4));
itBegin++;
}
catch(...)
{
throw;
}
}
return resultList;
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_LIST_TYPE<Return_type> signal_4<HYDROSIG_4_ARG>::collected::emit_reverse(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
HYDROSIG_LIST_TYPE<Return_type> resultList;
this->removeInvalidated();
if(this->isBlocked()) return resultList;
HYDROSIG_PROTECTED_BLOCK_BEGIN
slot_list copy = this->m_slots;
typename slot_list::reverse_iterator itBegin(copy.rbegin());
typename slot_list::reverse_iterator itEnd(copy.rend());
HYDROSIG_PROTECTED_BLOCK_END
while(itBegin != itEnd)
{
// Skip the slot if blocked or invalid
if(!(*itBegin)->isValid()
||
(*itBegin)->isBlocked())
{
itBegin++;
continue;
}
// Activating the slot
try {
resultList.push_back((*itBegin)->activate(arg1,arg2,arg3,
arg4));
itBegin++;
}
catch(...)
{
throw;
}
}
return resultList;
}
HYDROSIG_TEMPLATE_4_ARG
HYDROSIG_LIST_TYPE<Return_type> signal_4<HYDROSIG_4_ARG>::collected::operator()(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
try {
return emit(arg1,arg2,arg3,
arg4);
}
catch(...)
{
throw;
}
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined()
: m_combiner(new Combiner_type())
{
;
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined(
const Combiner_type &combiner)
: m_combiner(new Combiner_type(combiner))
{
;
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined(
const combined &src)
: signal_4_base<HYDROSIG_4_ARG>(src)
{
HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN
m_combiner = HYDROSIG_SHARED_PTR_TYPE<Combiner_type>(
new Combiner_type(*(src.m_combiner)));
HYDROSIG_REMOTE_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined(
combined &&src)
: signal_4_base<HYDROSIG_4_ARG>(
std::forward<signal_4_base<HYDROSIG_4_ARG>>(src))
{
HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN
m_combiner = std::move(src.m_combiner);
HYDROSIG_REMOTE_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>&
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::operator=(
const combined &src)
{
if(this == &src) return *this;
signal_4_base<HYDROSIG_4_ARG>::operator =(src);
HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_combiner = HYDROSIG_SHARED_PTR_TYPE<Combiner_type>(
new Combiner_type(*(src.m_combiner)));
HYDROSIG_PROTECTED_BLOCK_END
HYDROSIG_REMOTE_PROTECTED_BLOCK_END
return *this;
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>&
signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::operator=(
combined &&src)
{
if(this == &src) return *this;
signal_4_base<HYDROSIG_4_ARG>::operator =(
std::forward<signal_4_base<HYDROSIG_4_ARG>>(src));
HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_combiner = std::move(src.m_combiner);
HYDROSIG_PROTECTED_BLOCK_END
HYDROSIG_REMOTE_PROTECTED_BLOCK_END
return *this;
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
Combiner_type& signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::getCombiner()
{
return *m_combiner;
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
void signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::setCombiner(
const Combiner_type &combiner)
{
HYDROSIG_PROTECTED_BLOCK_BEGIN
m_combiner = HYDROSIG_SHARED_PTR_TYPE<Combiner_type>(combiner);
HYDROSIG_PROTECTED_BLOCK_END
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
Return_type signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::emit(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
if(this->isBlocked()) return m_combiner->value();
this->removeInvalidated();
HYDROSIG_PROTECTED_BLOCK_BEGIN
HYDROSIG_SHARED_PTR_TYPE<Combiner_type> combiner(m_combiner);
slot_list copy = this->m_slots;
typename slot_list::iterator itBegin(copy.begin());
typename slot_list::iterator itEnd(copy.end());
HYDROSIG_PROTECTED_BLOCK_END
while(itBegin != itEnd)
{
// Skip the slot if blocked or invalid
if(!(*itBegin)->isValid()
||
(*itBegin)->isBlocked())
{
itBegin++;
continue;
}
// Activating the slot
try {
(*combiner)((*itBegin)->activate(arg1,arg2,arg3,
arg4));
itBegin++;
}
catch(...)
{
throw;
}
}
return combiner->value();
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
Return_type signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::emit_reverse(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
if(this->isBlocked()) return m_combiner->value();
this->removeInvalidated();
HYDROSIG_PROTECTED_BLOCK_BEGIN
HYDROSIG_SHARED_PTR_TYPE<Combiner_type> combiner(m_combiner);
slot_list copy = this->m_slots;
typename slot_list::reverse_iterator itBegin(copy.rbegin());
typename slot_list::reverse_iterator itEnd(copy.rend());
HYDROSIG_PROTECTED_BLOCK_END
while(itBegin != itEnd)
{
// Skip the slot if blocked or invalid
if(!(*itBegin)->isValid()
||
(*itBegin)->isBlocked())
{
itBegin++;
continue;
}
// Activating the slot
try {
(*combiner)((*itBegin)->activate(arg1,arg2,arg3,
arg4));
itBegin++;
}
catch(...)
{
throw;
}
}
return combiner->value();
}
HYDROSIG_TEMPLATE_4_ARG
template<class Combiner_type>
Return_type signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::operator()(
Arg1_type arg1, Arg2_type arg2, Arg3_type arg3,
Arg4_type arg4)
{
try {
return emit(arg1,arg2,arg3,
arg4);
}
catch(...)
{
throw;
}
}
HYDROSIG_NAMESPACE_END
#endif // HYDROSIG_SIGNAL_4_HPP_INCLUDED
| 30.496042 | 98 | 0.608514 | Peterskhan |
3ec7e3e0ddb3a3b21ce09317ba4f6932b8fc5271 | 453 | cpp | C++ | FangameReader/GlFont.cpp | TheBiob/DeadSplit | 2e29bae2b86fa689ed9c28d345f2e8743b10c115 | [
"MIT"
] | 3 | 2019-04-02T19:23:35.000Z | 2021-04-30T03:57:15.000Z | FangameReader/GlFont.cpp | TheBiob/DeadSplit | 2e29bae2b86fa689ed9c28d345f2e8743b10c115 | [
"MIT"
] | 1 | 2018-07-10T22:34:41.000Z | 2018-07-10T22:52:43.000Z | FangameReader/GlFont.cpp | TheBiob/DeadSplit | 2e29bae2b86fa689ed9c28d345f2e8743b10c115 | [
"MIT"
] | 3 | 2020-12-28T19:06:07.000Z | 2021-01-30T10:09:56.000Z | #include <common.h>
#pragma hdrstop
#include <GlFont.h>
namespace Fangame {
//////////////////////////////////////////////////////////////////////////
CGlFont::CGlFont( CUnicodeView fontName, int fontSize ) :
font( fontName ),
renderer( CreateOwner<CFreeTypeGlyphProvider>( font, fontSize ) )
{
renderer.LoadBasicCharSet();
}
//////////////////////////////////////////////////////////////////////////
} // namespace Fangame.
| 22.65 | 75 | 0.456954 | TheBiob |
3eca661c6f612772afd46a8fd5461d585c427bfc | 254 | cpp | C++ | resources/minimal-example.cpp | hasahmed/shape_game_cpp | 1f14ba1d3f6dc31723de827c21714bdc7bc3acaa | [
"MIT"
] | null | null | null | resources/minimal-example.cpp | hasahmed/shape_game_cpp | 1f14ba1d3f6dc31723de827c21714bdc7bc3acaa | [
"MIT"
] | null | null | null | resources/minimal-example.cpp | hasahmed/shape_game_cpp | 1f14ba1d3f6dc31723de827c21714bdc7bc3acaa | [
"MIT"
] | null | null | null | #include "shapegame.hpp"
using namespace shapegame;
int main() {
Game game(400, 400, "My New Game");
game.scene->setBackgroundColor(Color::BLUE);
game.scene->addChild(new TriangleIsosceles(100, 100, Position(100, 100), Color::BLACK));
game.run();
}
| 25.4 | 89 | 0.716535 | hasahmed |
3ecc6ba4f19740f0e490edf7bb76c3be07c09aef | 3,397 | hpp | C++ | http_server/include/op.hpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | http_server/include/op.hpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | http_server/include/op.hpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | #pragma once
//
// Copyright (c) 2015, J2 Innovations
// Copyright (c) 2012 Brian Frank
// Licensed under the Academic Free License version 3.0
// History:
// 08 Sep 2014 Radu Racariu<radur@2inn.com> Ported to C++
// 06 Jun 2011 Brian Frank Creation
//
#include "headers.hpp"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "grid.hpp"
#include "ref.hpp"
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
namespace haystack
{
class Server;
class Uri;
class Ref;
class Val;
/**
Op is the base class for server side operations exposed by the REST API.
All methods on Op must be thread safe.
@see <a href = 'http://project-haystack.org/doc/Ops'>Project Haystack< / a>
*/
class Op : boost::noncopyable
{
public:
Op() {}
/**
Programatic name of the operation.
*/
virtual const std::string name() const = 0;
/**
Short one line summary of what the operation does.
*/
virtual const std::string summary() const = 0;
/**
Service the request and return response.
This method routes to "on_service(Server& db, const Grid& req)"
*/
void on_service(Server& db, HTTPServerRequest& req, HTTPServerResponse& res);
/**
Service the request and return response.
*/
virtual Grid::auto_ptr_t on_service(Server& db, const Grid& req);
protected:
typedef boost::ptr_vector<Ref> refs_t;
refs_t grid_to_ids(const Server& db, const Grid& grid) const;
Val::auto_ptr_t val_to_id(const Server& db, const Val& val) const;
private:
// Map the GET query parameters to grid with one row
Grid::auto_ptr_t get_to_grid(HTTPServerRequest& req);
// Map the POST body to grid
Grid::auto_ptr_t post_to_grid(HTTPServerRequest& req, HTTPServerResponse& res);
};
class StdOps
{
public:
/**
List the registered operations.
*/
static const Op& about;
/**
List the registered operations.
*/
static const Op& ops;
/**
List the registered grid formats.
*/
static const Op& formats;
/**
Read entity records in database.
*/
static const Op& read;
/**
Navigate tree structure of database.
*/
static const Op& nav;
/**
Watch subscription.
*/
static const Op& watch_sub;
/**
Watch unsubscription.
*/
static const Op& watch_unsub;
/**
Watch poll cov or refresh.
*/
static const Op& watch_poll;
/**
List all Watches.
*/
static const Op& watch_list;
/**
Read/write writable point priority array.
*/
static const Op& point_write;
/**
Read time series history data.
*/
static const Op& his_read;
/**
Write time series history data.
*/
static const Op& his_write;
/**
Invoke action.
*/
static const Op& invoke_action;
typedef std::map<std::string, const Op* const> ops_map_t;
static const ops_map_t& ops_map();
private:
static ops_map_t* m_ops_map;
};
} | 25.734848 | 87 | 0.574919 | kushaldalsania |
3ecef9f340aa1eec159ea6ca6c738500fd62513d | 17,991 | cpp | C++ | BezierWeights.cpp | sereslorant/gb_patch_gpu | cb7d47c28acd11925ead7d0916de44ba051a5b10 | [
"MIT"
] | null | null | null | BezierWeights.cpp | sereslorant/gb_patch_gpu | cb7d47c28acd11925ead7d0916de44ba051a5b10 | [
"MIT"
] | null | null | null | BezierWeights.cpp | sereslorant/gb_patch_gpu | cb7d47c28acd11925ead7d0916de44ba051a5b10 | [
"MIT"
] | null | null | null |
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <string>
#include <cstring>
PFNGLGENBUFFERSPROC glGenBuffers;
PFNGLBINDBUFFERPROC glBindBuffer;
PFNGLBINDBUFFERRANGEPROC glBindBufferRange;
PFNGLBUFFERDATAPROC glBufferData;
PFNGLMAPBUFFERPROC glMapBuffer;
PFNGLUNMAPBUFFERPROC glUnmapBuffer;
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat;
PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding;
PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer;
PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex;
PFNGLCREATESHADERPROC glCreateShader;
PFNGLSHADERSOURCEPROC glShaderSource;
PFNGLCOMPILESHADERPROC glCompileShader;
PFNGLDELETESHADERPROC glDeleteShader;
PFNGLCREATEPROGRAMPROC glCreateProgram;
PFNGLATTACHSHADERPROC glAttachShader;
PFNGLLINKPROGRAMPROC glLinkProgram;
PFNGLDETACHSHADERPROC glDetachShader;
PFNGLUSEPROGRAMPROC glUseProgram;
PFNGLDELETEPROGRAMPROC glDeleteProgram;
PFNGLPATCHPARAMETERIPROC glPatchParameteri;
void GLLoadExtensions()
{
glGenBuffers = (PFNGLGENBUFFERSPROC)SDL_GL_GetProcAddress("glGenBuffers");
glBindBuffer = (PFNGLBINDBUFFERPROC)SDL_GL_GetProcAddress("glBindBuffer");
glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)SDL_GL_GetProcAddress("glBindBufferRange");
glBufferData = (PFNGLBUFFERDATAPROC)SDL_GL_GetProcAddress("glBufferData");
glMapBuffer = (PFNGLMAPBUFFERPROC)SDL_GL_GetProcAddress("glMapBuffer");
glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)SDL_GL_GetProcAddress("glUnmapBuffer");
glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)SDL_GL_GetProcAddress("glDeleteBuffers");
glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glGenVertexArrays");
glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)SDL_GL_GetProcAddress("glBindVertexArray");
glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glDeleteVertexArrays");
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray");
glVertexAttribFormat = (PFNGLVERTEXATTRIBFORMATPROC)SDL_GL_GetProcAddress("glVertexAttribFormat");
glVertexAttribBinding = (PFNGLVERTEXATTRIBBINDINGPROC)SDL_GL_GetProcAddress("glVertexAttribBinding");
glBindVertexBuffer = (PFNGLBINDVERTEXBUFFERPROC)SDL_GL_GetProcAddress("glBindVertexBuffer");
glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)SDL_GL_GetProcAddress("glDrawElementsBaseVertex");
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
glDeleteShader = (PFNGLDELETESHADERPROC)SDL_GL_GetProcAddress("glDeleteShader");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)SDL_GL_GetProcAddress("glCreateProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)SDL_GL_GetProcAddress("glAttachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)SDL_GL_GetProcAddress("glLinkProgram");
glDetachShader = (PFNGLDETACHSHADERPROC)SDL_GL_GetProcAddress("glDetachShader");
glUseProgram = (PFNGLUSEPROGRAMPROC)SDL_GL_GetProcAddress("glUseProgram");
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)SDL_GL_GetProcAddress("glDeleteProgram");
glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)SDL_GL_GetProcAddress("glPatchParameteri");
}
PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
PFNGLGETPROGRAMIVPROC glGetProgramiv;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
void GLDbgLoadExtensions()
{
glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)SDL_GL_GetProcAddress("glGetObjectParameterivARB");
glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)SDL_GL_GetProcAddress("glGetInfoLogARB");
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)SDL_GL_GetProcAddress("glGetProgramiv");
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)SDL_GL_GetProcAddress("glGetProgramInfoLog");
}
#include <iostream>
void lGLDbgPrintShaderCompileError(GLuint shader)
{
GLint compiled;
glGetObjectParameterivARB(shader,GL_COMPILE_STATUS,&compiled);
if(!compiled)
{
GLint ret_size;
char log[256];
glGetInfoLogARB(shader,sizeof(log),&ret_size,log);
std::cerr << log << std::endl;
}
}
void lGLDbgPrintProgramLinkError(GLuint program)
{
GLint linked;
glGetProgramiv(program,GL_LINK_STATUS,&linked);
if(!linked)
{
GLint ret_size;
char log[256];
glGetProgramInfoLog(program,sizeof(log),&ret_size,log);
std::cerr << log << std::endl;
}
}
std::string VertexShaderSrc = R"(
#version 400
void main()
{
}
)";
std::string TcShaderSrc = R"(
#version 400
layout(vertices = 3) out;
void main()
{
gl_TessLevelOuter[0] = 16.0;
gl_TessLevelOuter[1] = 16.0;
gl_TessLevelOuter[2] = 16.0;
gl_TessLevelInner[0] = 16.0;
}
)";
std::string TeShaderSrc = R"(
#version 400
layout(triangles,equal_spacing,ccw) in;
const uint MAX_SIDE_COUNT = 5;
out vec3 OutColor;
float BinomialCoefficient(uint k,uint n)
{
float Accumulator = 1.0;
for(uint i=1;i <= k;i++)
{
Accumulator *= (n + 1.0 - i)/i;
}
return Accumulator;
}
void main()
{
const uint SIDE_COUNT = 5;
const uint DEGREE = 5;
const uint LAYERS = (DEGREE + 1) / 2;
const float PI = 3.14159265359;
const float EPSILON = 1e-2;
uint VertexId0 = (gl_PrimitiveID % SIDE_COUNT);
uint VertexId1 = ((gl_PrimitiveID + 1) % SIDE_COUNT);
vec3 Vertices[MAX_SIDE_COUNT];
for(uint i=0;i < SIDE_COUNT;i++)
{
float SinParam = float(i)/ SIDE_COUNT;
Vertices[i] = vec3(cos(SinParam * 2.0 * PI),sin(SinParam * 2.0 * PI),0.0);
}
vec3 UvCoord = gl_TessCoord.y * Vertices[VertexId0] + gl_TessCoord.z * Vertices[VertexId1];
float SumBaryCoords = 0.0;
float BaryCoords[MAX_SIDE_COUNT];
for(uint i=0;i < SIDE_COUNT;i++)
{
uint Prev = (i-1);
uint Curr = i;
uint Next = (i+1) % SIDE_COUNT;
if(i == 0)
{Prev = SIDE_COUNT - 1;}
float A1 = length(cross(Vertices[Curr] - UvCoord,Vertices[Prev] - UvCoord))/2.0;
float A2 = length(cross(Vertices[Curr] - UvCoord,Vertices[Next] - UvCoord))/2.0;
float C = length(cross(Vertices[Prev] - Vertices[Curr],Vertices[Next] - Vertices[Curr]))/2.0;
BaryCoords[i] = C/(A1*A2);
SumBaryCoords += BaryCoords[i];
}
for(uint i=0;i < SIDE_COUNT;i++)
{
if(gl_TessCoord.x > EPSILON)
{BaryCoords[i] /= SumBaryCoords;}
else
{BaryCoords[i] = 0.0;}
}
if(gl_TessCoord.x < EPSILON)
{
BaryCoords[VertexId0] = gl_TessCoord.y;
BaryCoords[VertexId1] = gl_TessCoord.z;
}
vec2 SideCoords[MAX_SIDE_COUNT];
for(uint i=0;i < SIDE_COUNT;i++)
{
SideCoords[i] = vec2(0.0,0.0);
uint Prev = (i-1);
uint Curr = i;
if(i == 0)
{Prev = SIDE_COUNT - 1;}
float Denominator = BaryCoords[Prev] + BaryCoords[Curr];
SideCoords[i].x = BaryCoords[Curr] / Denominator;
if(Denominator < EPSILON)
{SideCoords[i].x = 0.0;}
SideCoords[i].y = 1.0 - BaryCoords[Prev] - BaryCoords[Curr];
}
float CentralCoeff = 1.0;
float BezierRibbonContrib[MAX_SIDE_COUNT];
for(uint i=0;i < SIDE_COUNT;i++)
{
BezierRibbonContrib[i] = 0.0;
uint Prev = (i-1);
uint Curr = i;
uint Next = (i+1) % SIDE_COUNT;
if(i == 0)
{Prev = SIDE_COUNT - 1;}
for(uint j=0;j <= DEGREE;j++)
{
for(uint k=0;k < LAYERS;k++)
{
float Bernstein = BinomialCoefficient(j,DEGREE)*pow(1.0-SideCoords[i].x,DEGREE-j)*pow(SideCoords[i].x,j) *
BinomialCoefficient(k,DEGREE)*pow(1.0-SideCoords[i].y,DEGREE-k)*pow(SideCoords[i].y,k);
float Weight = 1.0;
if(k < 2)
{
if(j < 2)
{
float Denominator = (SideCoords[Prev].y + SideCoords[Curr].y);
if(Denominator < EPSILON)
{Weight = 1.0;}
else
{Weight = (SideCoords[Prev].y)/Denominator;}
}
if(j > (DEGREE - 2))
{
float Denominator = (SideCoords[Next].y + SideCoords[Curr].y);
if(Denominator < EPSILON)
{Weight = 0.0;}
else
{Weight = (SideCoords[Next].y)/Denominator;}
}
}
else
{
if(j < LAYERS)
{
if(j < k)
{Weight = 0.0;}
else if(j == k)
{Weight = 0.5;}
}
else
{
if(j > (DEGREE - k))
{Weight = 0.0;}
else if(j == (DEGREE - k))
{Weight = 0.5;}
}
}
float Coeff = Bernstein * Weight;
BezierRibbonContrib[i] += Coeff;
CentralCoeff -= Coeff;
}
}
}
float ColorY = 0.0;//SideCoords[SIDE_COUNT - 1].y;
//float ColorZ = 0.0;//SideCoords[1].y;
float ColorZ = CentralCoeff;
OutColor = vec3(BezierRibbonContrib[0],BezierRibbonContrib[1],CentralCoeff);
OutColor = vec3(BezierRibbonContrib[1],BezierRibbonContrib[2],CentralCoeff);
OutColor = vec3(BezierRibbonContrib[2],BezierRibbonContrib[3],CentralCoeff);
OutColor = vec3(BezierRibbonContrib[3],BezierRibbonContrib[4],CentralCoeff);
OutColor = vec3(BezierRibbonContrib[4],BezierRibbonContrib[0],CentralCoeff);
gl_Position = vec4(UvCoord,1.0);
}
)";
std::string FragmentShaderSrc = R"(
#version 400
in vec3 OutColor;
layout(location=0) out vec4 FragColor;
void main()
{
FragColor = vec4(OutColor,1.0);
}
)";
class GLApp
{
private:
GLuint VertexBuffer = 0;
GLuint IndexBuffer = 0;
GLuint VertexArrayObject = 0;
GLuint ShaderProgram = 0;
public:
void Loop()
{
glClearColor(0.5,0.5,0.5,1.0);
glClear(GL_COLOR_BUFFER_BIT);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glUseProgram(ShaderProgram);
glBindVertexArray(VertexArrayObject);
glBindVertexBuffer(0,VertexBuffer,0,2*sizeof(float));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,IndexBuffer);
glPatchParameteri(GL_PATCH_VERTICES,3);
//glDrawElements(GL_PATCHES,9,GL_UNSIGNED_INT,0);
//glDrawElements(GL_PATCHES,12,GL_UNSIGNED_INT,0);
glDrawElements(GL_PATCHES,15,GL_UNSIGNED_INT,0);
}
GLApp()
{
std::cout << VertexShaderSrc << std::endl;
std::cout << TcShaderSrc << std::endl;
std::cout << TeShaderSrc << std::endl;
std::cout << FragmentShaderSrc << std::endl;
GLLoadExtensions();
GLDbgLoadExtensions();
{
const char *ShaderSource = VertexShaderSrc.c_str();
GLuint VertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(VertexShader,1,&ShaderSource,nullptr);
glCompileShader(VertexShader);
lGLDbgPrintShaderCompileError(VertexShader);
ShaderSource = TcShaderSrc.c_str();
GLuint TcShader = glCreateShader(GL_TESS_CONTROL_SHADER);
glShaderSource(TcShader,1,&ShaderSource,nullptr);
glCompileShader(TcShader);
lGLDbgPrintShaderCompileError(TcShader);
ShaderSource = TeShaderSrc.c_str();
GLuint TeShader = glCreateShader(GL_TESS_EVALUATION_SHADER);
glShaderSource(TeShader,1,&ShaderSource,nullptr);
glCompileShader(TeShader);
lGLDbgPrintShaderCompileError(TeShader);
ShaderSource = FragmentShaderSrc.c_str();
GLuint FragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(FragmentShader,1,&ShaderSource,nullptr);
glCompileShader(FragmentShader);
lGLDbgPrintShaderCompileError(FragmentShader);
ShaderProgram = glCreateProgram();
glAttachShader(ShaderProgram,VertexShader);
glAttachShader(ShaderProgram,TcShader);
glAttachShader(ShaderProgram,TeShader);
glAttachShader(ShaderProgram,FragmentShader);
glLinkProgram(ShaderProgram);
glDetachShader(ShaderProgram,VertexShader);
glAttachShader(ShaderProgram,TcShader);
glAttachShader(ShaderProgram,TeShader);
glDetachShader(ShaderProgram,FragmentShader);
lGLDbgPrintProgramLinkError(ShaderProgram);
glDeleteShader(VertexShader);
glDeleteShader(TcShader);
glDeleteShader(TeShader);
glDeleteShader(FragmentShader);
}
{
unsigned int NumVertices = 5;
std::size_t VertexDataSize = NumVertices * 2 * sizeof(float);
float VertexData[] =
{
-0.125,-0.125,
0.125,-0.125,
0.125, 0.125,
-0.125, 0.125,
0.375, 0.125,
};
unsigned int NumIndices = 18;
std::size_t IndexDataSize = NumIndices * sizeof(std::uint32_t);
std::uint32_t IndexData[] =
{
0,1,2,
0,2,3,
1,2,4,
0,1,2,
0,2,3,
1,2,4,
};
glGenBuffers(1,&VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer);
glBufferData(GL_ARRAY_BUFFER,VertexDataSize,VertexData,GL_STATIC_DRAW);
glGenBuffers(1,&IndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,IndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,IndexDataSize,IndexData,GL_STATIC_DRAW);
}
glGenVertexArrays(1,&VertexArrayObject);
glBindVertexArray(VertexArrayObject);
glEnableVertexAttribArray(0);
glVertexAttribFormat(0,
2,
GL_FLOAT,
GL_FALSE,
0
);
glVertexAttribBinding(0,0);
}
~GLApp()
{
glDeleteBuffers(1,&VertexBuffer);
glDeleteBuffers(1,&IndexBuffer);
glDeleteVertexArrays(1,&VertexArrayObject);
glDeleteProgram(ShaderProgram);
}
};
int main(int argc, char **argv)
{
SDL_Window *Window;
SDL_GLContext GLContext;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
Window = SDL_CreateWindow("GLRenderSample",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,600,600,SDL_WINDOW_OPENGL);
GLContext = SDL_GL_CreateContext(Window);
SDL_ShowWindow(Window);
GLApp App;
bool Running = true;
while(Running)
{
int BeginTime = SDL_GetTicks();
SDL_Event Event;
while(SDL_PollEvent(&Event))
{
if(Event.type == SDL_QUIT)
{
Running = false;
}
}
App.Loop();
SDL_GL_SwapWindow(Window);
int EndTime = SDL_GetTicks();
std::cout << "Frame time: " << (EndTime-BeginTime) << "ms\nFps: " << 1000.0/(EndTime-BeginTime) << std::endl;
}
SDL_GL_DeleteContext(GLContext);
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
| 32.950549 | 126 | 0.579901 | sereslorant |
3ed0385635d5f4369955886cb903dff9e49a0d44 | 1,729 | cpp | C++ | src/10. MinPerimeterRectangle.cpp | zooyouny/codility | 260ecc4045f8c28d3b65e9ffe56ef50f3098f7e7 | [
"Unlicense"
] | null | null | null | src/10. MinPerimeterRectangle.cpp | zooyouny/codility | 260ecc4045f8c28d3b65e9ffe56ef50f3098f7e7 | [
"Unlicense"
] | null | null | null | src/10. MinPerimeterRectangle.cpp | zooyouny/codility | 260ecc4045f8c28d3b65e9ffe56ef50f3098f7e7 | [
"Unlicense"
] | null | null | null | #include "gtest/gtest.h"
/*
정수 N이 주어졌을 때 최소 둘레(perimeter)를 찾는 문제. 여기서 N은 사각형의 넓이.
예)
N = 30 이라면 다음과 같은 조합이 있을 수 있음
(1, 30), with a perimeter of 62,
(2, 15), with a perimeter of 34,
(3, 10), with a perimeter of 26,
(5, 6), with a perimeter of 22.
여기서 최소 넓이는 22 이므로 22를 리턴하면 된다.
힌트 :
* 한 변의 길이가 정해지면 다른 한변의 길이는 자동으로 결정 된다. (w, h = 넓이 / w)
* 모든 w 에 대해 perimeter를 구해보고 최소값을 찾아 리턴하면 된다.
* w 의 범위는 [1, sqrt(넓이)] 로 한정할 수 있다.
* w 가 sqrt(넓이)에 가까울 수록 perimeter는 작아지므로 sqrt(넓이)에서 부터 1의 방향으로 순회하면 좀 더 빨리 찾을 수 있다.
** 그렇다 하더라도 O(sqrt(N)) 는 동일
주의 :
* 최소값(1), 최대값(1,000,000,000), 소수(982,451,653)와 같은 최악의 경우에 대해 테스트가 필요하다.
*/
#include <iostream>
#include <random>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <map>
#include <ctime>
#include <stack>
using namespace std;
int perimeter(int w, int h)
{
return 2 * (w + h);
}
int solution(int N) { // 1 ~ 1,000,000,000
int sol = perimeter(1, N);
int rootN = static_cast<int>(sqrt(N));
for (int i = rootN; i >= 1; i--)
{
if (N % i == 0)
{
auto ret = perimeter(i, N / i);
return ret;
}
}
return sol;
}
TEST(MinPerimeterRectangle, SimpleTest) {
EXPECT_EQ(22, solution(30));
EXPECT_EQ(4, solution(1));
EXPECT_EQ(24, solution(36));
EXPECT_EQ(28, solution(48));
EXPECT_EQ(204, solution(101));
EXPECT_EQ(1238, solution(1234));
}
TEST(MinPerimeterRectangle, ExtremeTest) {
EXPECT_EQ(27116, solution(45664320));
EXPECT_EQ(30972904, solution(15486451));
EXPECT_EQ(40000, solution(100000000));
EXPECT_EQ(1964903308, solution(982451653));
EXPECT_EQ(126500, solution(1000000000));
}
| 24.352113 | 83 | 0.59919 | zooyouny |
a7926411ae96cb4329ea491c1cf85e6d85f5b13c | 2,649 | hpp | C++ | pwm/libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/PixelDataWidget.hpp | 1162431386/RT-Thread | 55223abcf9559baf7d77faddcbcde0c99b6c880b | [
"Apache-2.0"
] | 8 | 2020-12-15T13:40:34.000Z | 2021-11-28T14:49:37.000Z | libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/PixelDataWidget.hpp | apeng2012/RT-Thread-tmc5160-demo | 2634ec85f7a050ef188ede1b23e73d0dfdce6c3e | [
"MIT"
] | null | null | null | libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/PixelDataWidget.hpp | apeng2012/RT-Thread-tmc5160-demo | 2634ec85f7a050ef188ede1b23e73d0dfdce6c3e | [
"MIT"
] | 4 | 2020-12-15T14:01:36.000Z | 2022-01-25T00:17:14.000Z | /**
******************************************************************************
* This file is part of the TouchGFX 4.15.0 distribution.
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/**
* @file touchgfx/widgets/PixelDataWidget.hpp
*
* Declares the touchgfx::PixelDataWidget class.
*/
#ifndef PIXELDATAWIDGET_HPP
#define PIXELDATAWIDGET_HPP
#include <touchgfx/Bitmap.hpp>
#include <touchgfx/hal/Types.hpp>
#include <touchgfx/widgets/Widget.hpp>
namespace touchgfx
{
/**
* A widget for displaying a buffer of pixel data. This can also be though of as a dynamic
* bitmap where the dimensions of the bitmap is the same as the dimensions of the widget
* and the actual bitmap data can be set and updated dynamically. The size of the buffer
* must match the number of bytes required for the widget calculated as WIDTH x HEIGHT x
* BYTES_PER_PIXEL. If the LCD is 16 bit per pixel the buffer must hold 2 bytes for each
* pixel. If the LCD is 24 bit the buffer must hold 3 bytes for each pixel.
*/
class PixelDataWidget : public Widget
{
public:
PixelDataWidget();
virtual void draw(const Rect& invalidatedArea) const;
virtual Rect getSolidRect() const;
/**
* Set the pixel data to display. The given pointer must contain WIDTH x HEIGHT x
* BYTES_PER_PIXEL bytes of addressable image data.
*
* @param [in] data Image data.
*
* @see setBitmapFormat
*/
void setPixelData(uint8_t* const data);
/**
* Set the format of the pixel data. The supported formats depend on the display type.
* For example grayscale displays do not support color images.
*
* @param format Describes the format to use when reading the pixel data.
*/
void setBitmapFormat(Bitmap::BitmapFormat format);
/**
* @copydoc Image::setAlpha
*/
void setAlpha(uint8_t newAlpha);
/**
* @copydoc Image::getAlpha
*/
uint8_t getAlpha() const;
protected:
uint8_t* buffer; ///< The buffer where the pixels are copied from
Bitmap::BitmapFormat format; ///< The pixel format for the data.
uint8_t alpha; ///< The Alpha for this widget.
};
} // namespace touchgfx
#endif // PIXELDATAWIDGET_HPP
| 31.535714 | 90 | 0.640997 | 1162431386 |
a794bcf13250204383df4cb226dcf0ea1d027586 | 26,790 | cpp | C++ | src/token.cpp | tnash9/chief | d633be42b6531890f5e810e0d1af06d70f106830 | [
"MIT"
] | null | null | null | src/token.cpp | tnash9/chief | d633be42b6531890f5e810e0d1af06d70f106830 | [
"MIT"
] | null | null | null | src/token.cpp | tnash9/chief | d633be42b6531890f5e810e0d1af06d70f106830 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <iostream>
#include <cctype>
#include <fstream>
#include <list>
#include "main.h"
#include "arch.h"
#include "diagnostics.h"
#include "reference.h"
#include "operation.h"
// ---------------------------------------------------------------------------------------------------------------------
// TODO:
// 1. Match boolean tokens in any case (i.e. TRUE, FaLsE)
void SkipWhiteSpace(const std::string& line, size_t& position)
{
for(; position < line.size() && line.at(position) == ' '; position++);
}
bool IsInteger(const std::string& tokenString)
{
for(size_t i=0; i<tokenString.size(); i++)
{
if(!std::isdigit(tokenString.at(i)))
return false;
}
return true;
}
bool IsDecimal(const std::string& tokenString)
{
bool foundDecimalPointAlready = false;
for(size_t i=0; i<tokenString.size(); i++)
{
if(!std::isdigit(tokenString.at(i)))
{
if(tokenString.at(i) == '.')
{
if(foundDecimalPointAlready)
return false;
foundDecimalPointAlready = true;
}
else
{
return false;
}
}
}
return true;
}
bool IsString(const std::string& tokenString)
{
return tokenString.at(0) == '"' && tokenString.at(tokenString.size()-1) == '"';
}
std::string ToLowerCase(const std::string& str)
{
std::string lowerCaseStr = "";
for(size_t i=0; i<str.size(); i++)
{
lowerCaseStr += std::tolower(str.at(i));
}
return lowerCaseStr;
}
bool IsBoolean(const std::string& tokenString)
{
return ToLowerCase(tokenString) == "true" || ToLowerCase(tokenString) == "false";
}
bool IsReference(const std::string& tokenString)
{
return (tokenString.at(0) >= 65 && tokenString.at(0) <= 90);
}
TokenType TypeOfTokenString(const std::string& tokenString)
{
if(IsInteger(tokenString))
{
return TokenType::Integer;
}
else if(IsDecimal(tokenString))
{
return TokenType::Decimal;
}
else if(IsString(tokenString))
{
return TokenType::String;
}
else if(IsBoolean(tokenString))
{
return TokenType::Boolean;
}
else if(IsReference(tokenString))
{
return TokenType::Reference;
}
else
{
return TokenType::Simple;
}
}
const String StringStartChars = "\"'";
const char DecimalPoint = '.';
const String SingletonChars = "!@#$%^*()-+=[]{}\\:;<>,./?~`&|";
const String DoubledChars = "&&||==!=";
bool IsSingleTonChar(char c)
{
for(size_t i=0; i<SingletonChars.size(); i++)
if(c == SingletonChars.at(i))
return true;
return false;
}
Token* GetSingletonCharToken(const String& line, size_t& position, int tokenNumber)
{
String tokenString = "";
tokenString += line.at(position++);
return new Token { TokenType::Simple, tokenString, tokenNumber };
}
bool IsDoubleCharToken(size_t& position, const String& line)
{
if(position + 1 >= line.size())
return false;
for(size_t i=0; i<DoubledChars.size(); i+=2)
{
if(line.at(position) == DoubledChars.at(i) && line.at(position+1) == DoubledChars.at(i+1))
return true;
}
return false;
}
Token* GetDoubleCharToken(const String& line, size_t& position, int tokenNumber)
{
String tokenString = "";
tokenString += line.at(position);
tokenString += line.at(position+1);
position += 2;
return new Token { TokenType::Simple, tokenString, tokenNumber };
}
bool IsStringStartChar(char c)
{
return c == '"';
}
Token* GetStringToken(const String& line, size_t& position, int tokenNumber)
{
String tokenString;
while(++position < line.size() && line.at(position) != '"')
{
tokenString += line.at(position);
}
position++; // get rid of end quote
return new Token { TokenType::String, tokenString, tokenNumber };
}
bool IsNumericChar(char c)
{
return 48 <= static_cast<int>(c) && 57 >= static_cast<int>(c);
}
bool IsActuallyDecimalPoint(const size_t& position, const String& line)
{
return (position > 0 && IsNumericChar(line.at(position-1))) &&
(position + 1 < line.size() && IsNumericChar(line.at(position+1)));
}
Token* GetToken(const std::string& line, size_t& position, int tokenNumber)
{
SkipWhiteSpace(line, position);
if(position >= line.size())
return nullptr;
// special case for string
if(IsStringStartChar(line.at(position)))
{
return GetStringToken(line, position, tokenNumber);
}
else if(IsDoubleCharToken(position, line))
{
return GetDoubleCharToken(line, position, tokenNumber);
}
else if(IsSingleTonChar(line.at(position)))
{
return GetSingletonCharToken(line, position, tokenNumber);
}
Token* token;
std::string tokenString = "";
for(; position < line.size() && line.at(position) != ' '; position++)
{
if(line.at(position) != DecimalPoint && IsSingleTonChar(line.at(position)))
break;
else if(line.at(position) == DecimalPoint)
{
if(!IsActuallyDecimalPoint(position, line))
break;
}
tokenString += line.at(position);
}
if(tokenString == "")
return nullptr;
token = new Token { TypeOfTokenString(tokenString), tokenString, tokenNumber };
return token;
}
TokenList LexLine(const std::string& line)
{
TokenList tokens;
size_t linePosition = 0;
int tokenNumber = 0;
while(linePosition < line.size())
{
Token* t = GetToken(line, linePosition, tokenNumber);
if(t == nullptr)
continue;
tokens.push_back(t);
tokenNumber++;
}
return tokens;
}
std::string GetStringTokenType(TokenType type)
{
std::string typeString;
switch(type)
{
case TokenType::Boolean:
typeString = "boolean ";
break;
case TokenType::Decimal:
typeString = "decimal ";
break;
case TokenType::Integer:
typeString = "integer ";
break;
case TokenType::Reference:
typeString = "reference";
break;
case TokenType::Simple:
typeString = "simple ";
break;
case TokenType::String:
typeString = "string ";
break;
default:
typeString = "unknown ";
break;
}
return typeString;
}
bool SameLetterOrChar(char c1, char c2)
{
return std::toupper(c1) == std::toupper(c2);
}
bool StringCaseInsensitiveEquals(const std::string& str1, const std::string& str2)
{
if(str1.size() != str2.size())
return false;
for(size_t pos=0; pos<str1.size(); pos++)
{
if(!SameLetterOrChar(str1.at(pos), str2.at(pos)))
return false;
}
return true;
}
Token* FindToken(const TokenList& tokens, std::string str)
{
for(Token* t: tokens)
{
if(StringCaseInsensitiveEquals(str, t->Content))
return t;
}
return nullptr;
}
void RenumberTokenList(TokenList& tokens)
{
for(int i=0; static_cast<size_t>(i)<tokens.size(); i++)
{
tokens.at(i)->Position = i;
}
}
TokenList RightOfToken(const TokenList& tokens, Token* pivotToken)
{
TokenList rightList;
rightList.reserve(tokens.size());
for(int i=pivotToken->Position + 1; static_cast<size_t>(i)<tokens.size(); i++)
rightList.push_back(tokens.at(i));
RenumberTokenList(rightList);
return rightList;
}
TokenList LeftOfToken(const TokenList& tokens, Token* pivotToken)
{
TokenList leftList;
leftList.reserve(tokens.size());
for(int i=0; i<pivotToken->Position; i++)
leftList.push_back(tokens.at(i));
RenumberTokenList(leftList);
return leftList;
}
bool TokenMatchesType(Token* token, std::vector<TokenType> types)
{
for(TokenType type: types)
{
if(type == token->Type)
return true;
}
return false;
}
bool TokenMatchesType(Token* token, TokenType type)
{
std::vector<TokenType> types = { type };
return TokenMatchesType(token, types);
}
bool TokenMatchesContent(Token* token, std::vector<String> contents)
{
for(String content: contents)
{
if(content == token->Content)
return true;
}
return false;
}
bool TokenMatchesContent(Token* token, String content)
{
std::vector<String> contents = { content };
return TokenMatchesContent(token, contents);
}
Token* NextTokenMatching(const TokenList& tokens, std::vector<TokenType> types, int& pos)
{
for(; static_cast<size_t>(pos)<tokens.size(); pos++)
{
if(TokenMatchesType(tokens.at(pos), types))
return tokens.at(pos++);
}
pos = -1;
return nullptr;
}
Token* NextTokenMatching(const TokenList& tokens, TokenType type, int& pos)
{
std::vector<TokenType> types = { type };
return NextTokenMatching(tokens, types, pos);
}
Token* NextTokenMatching(const TokenList& tokens, TokenType type)
{
int i = 0;
return NextTokenMatching(tokens, type, i);
}
Token* NextTokenMatching(const TokenList& tokens, std::vector<TokenType> types)
{
int i = 0;
return NextTokenMatching(tokens, types, i);
}
Token* NextTokenMatching(const TokenList& tokens, std::vector<String> contents, int& pos)
{
for(; static_cast<size_t>(pos)<tokens.size(); pos++)
{
if(TokenMatchesContent(tokens.at(pos), contents))
return tokens.at(pos++);
}
pos = -1;
return nullptr;
}
Token* NextTokenMatching(const TokenList& tokens, std::vector<String> contents)
{
int pos = 0;
return NextTokenMatching(tokens, contents, pos);
}
Token* NextTokenMatching(const TokenList& tokens, String content, int& pos)
{
std::vector<String> contents = { content };
return NextTokenMatching(tokens, contents, pos);
}
Token* NextTokenMatching(const TokenList& tokens, String content)
{
int pos = 0;
return NextTokenMatching(tokens, content, pos);
}
bool TokenListContainsContent(const TokenList& tokenList, std::vector<String> contents)
{
for(Token* t: tokenList)
{
if(TokenMatchesContent(t, contents))
return true;
}
return false;
}
// ---------------------------------------------------------------------------------------------------------------------
// Formal grammar parser parser (experimental)
struct CFGRule
{
String Name;
String Symbol;
int Precedence;
OperationType OpType;
std::vector<String> IntoPattern;
String FromProduction;
String ParseOperation;
};
struct PrecedenceClass
{
std::vector<String> Members;
};
OperationType StringNameToOperationType(String Name)
{
if(Name=="Add")
return OperationType::Add;
else if(Name=="Subtract")
return OperationType::Subtract;
else if(Name=="Multiply")
return OperationType::Multiply;
else if(Name=="Divide")
return OperationType::Divide;
else if(Name=="And")
return OperationType::And;
else if(Name=="Or")
return OperationType::Or;
else if(Name=="Not")
return OperationType::Not;
else if(Name=="IsEqual")
return OperationType::IsEqual;
else if(Name=="IsGreaterThan")
return OperationType::IsGreaterThan;
else if(Name=="IsLessThan")
return OperationType::IsLessThan;
else if(Name=="Evaluate")
return OperationType::Evaluate;
else if(Name=="If")
return OperationType::If;
else if(Name=="DefineMethod")
return OperationType::DefineMethod;
else if(Name=="Assign")
return OperationType::Assign;
else if(Name=="Define")
return OperationType::Define;
else if(Name=="Tuple")
return OperationType::Tuple;
else if(Name=="Print")
return OperationType::Print;
else if(Name=="Return")
return OperationType::Return;
else
return OperationType::Ref;
}
std::vector<CFGRule*> Grammar;
std::list<PrecedenceClass> PrecedenceRules;
std::vector<String> ProductionVariables = { "Ref" };
void AddProductionVariable(String newProductionVar)
{
for(auto productionVar: ProductionVariables)
{
if(productionVar == newProductionVar)
return;
}
ProductionVariables.push_back(newProductionVar);
}
// TODO: move to diagnostics
void PrintPrecedenceRules()
{
std::cout << "PRINTING\n";
for(auto rule: PrecedenceRules)
{
for(auto s: rule.Members)
{
std::cout << s << " ";
}
std::cout << "\n";
}
}
int PrecedenceOf(String opSymbol)
{
int i=1;
for(auto rule: PrecedenceRules)
{
for(auto str: rule.Members)
{
if(str == opSymbol)
{
return i;
}
}
i++;
}
LogIt(Sev3_Critical, "PrecedenceOf", Msg("unknown operation symbol %s", opSymbol));
return 0;
}
int PrecedenceOf(Token* lookaheadToken)
{
if(lookaheadToken == nullptr)
return 0;
return PrecedenceOf(lookaheadToken->Content);
}
void AssignRulePrecedences()
{
for(auto rule: Grammar)
{
rule->Precedence = PrecedenceOf(rule->Symbol);
}
}
void AddPrecedenceClass(TokenList& tokens)
{
PrecedenceClass precdence;
for(Token* t: tokens)
{
precdence.Members.push_back(t->Content);
}
PrecedenceRules.push_front(precdence);
}
void AddGrammarRule(TokenList& tokens, CFGRule** rule)
{
if(tokens.at(0)->Content == "@")
{
*rule = new CFGRule;
(*rule)->Name = tokens.at(1)->Content;
(*rule)->Symbol = tokens.at(2)->Content;
(*rule)->ParseOperation = tokens.at(3)->Content;
(*rule)->OpType = StringNameToOperationType((*rule)->Name);
}
else if(tokens.at(0)->Type == TokenType::Reference)
{
(*rule)->FromProduction = tokens.at(0)->Content;
AddProductionVariable((*rule)->FromProduction);
for(size_t i=3; i<tokens.size(); i++)
{
(*rule)->IntoPattern.push_back(tokens.at(i)->Content);
}
Grammar.push_back((*rule));
}
}
void CompileGrammar()
{
std::fstream file;
file.open(".\\assets\\grammar.txt", std::ios::in);
CFGRule* rule = nullptr;
// state: +1 upon every occurance of '###'
// 0: skip all lines
// 1: read grammar rules
// 2: read precedences
// other: skip all lines
int state = 0;
String line;
while(std::getline(file, line))
{
TokenList tokens = LexLine(line);
if(tokens.empty())
continue;
if(tokens.at(0)->Content == "#")
{
state++;
continue;
}
switch(state)
{
case 1:
AddGrammarRule(tokens, &rule);
continue;
case 2:
AddPrecedenceClass(tokens);
break;
default:
continue;
}
}
AssignRulePrecedences();
}
// ---------------------------------------------------------------------------------------------------------------------
// Formal grammar parser (experimental)
struct ParseToken
{
String TokenType;
Operation* Value;
ParseToken* Next = nullptr;
ParseToken* Prev = nullptr;
};
/// add a [newToken] to an existing [listTail]
void AddToList(ParseToken** listHead, ParseToken** listTail, ParseToken* newToken)
{
if(*listHead == nullptr)
{
*listHead = newToken;
*listTail = newToken;
return;
}
else
{
(*listTail)->Next = newToken;
newToken->Prev = *listTail;
*listTail = newToken;
}
}
ParseToken* ParseTokenConstructor(String tokenType)
{
ParseToken* gt = new ParseToken;
gt->Next = nullptr;
gt->Prev = nullptr;
gt->TokenType = tokenType;
gt->Value = nullptr;
return gt;
}
/// constructs a operation of type OperationType::Ref with either a primitive value or a named Reference stub
Operation* RefOperation(Token* refToken)
{
Reference* ref = ReferenceForPrimitive(refToken, c_operationReferenceName);
if(ref == nullptr)
{
ref = ReferenceStub(refToken->Content);
}
Operation* op = OperationConstructor(OperationType::Ref, ref);
return op;
}
CFGRule* MatchGrammarPatterns(ParseToken* listHead, ParseToken* listTail)
{
for(CFGRule* rule: Grammar)
{
bool isMatchForRule = true;
ParseToken* listItr = listTail;
for(int i=rule->IntoPattern.size()-1; i>=0; i--, listItr = listItr->Prev)
{
// false if rule is longer than the list
if(listItr == nullptr)
{
isMatchForRule = false;
break;
}
if(listItr->TokenType != rule->IntoPattern.at(i))
{
isMatchForRule = false;
break;
}
}
if(isMatchForRule)
return rule;
}
return nullptr;
}
void DestroyList(ParseToken* listHead)
{
ParseToken* prevToken;
while(listHead != nullptr)
{
prevToken = listHead;
listHead = listHead->Next;
delete prevToken;
}
}
bool ParseTokenTypeMatches(String TokenType, std::vector<String> matchTypes)
{
for(auto str: matchTypes)
{
if(TokenType == str)
return true;
}
return false;
}
/// pushes listTail back to before the [rule] pattern and sets listSnipHead to be the head (start) of [rule] in the ParseStack
void PointToHeadOfRuleAndSnip(ParseToken** listHead, ParseToken** listTail, ParseToken** listSnipHead, CFGRule* rule)
{
int backtrackAmount = rule->IntoPattern.size()-1;
for(int i=0; i<backtrackAmount; i++, *listSnipHead = (*listSnipHead)->Prev);
*listTail = (*listSnipHead)->Prev;
if(*listTail != nullptr)
{
(*listTail)->Next = nullptr;
}
else
{
// if the remaining list is empty
*listHead = nullptr;
}
}
/// assumes that the list matches [rule] and removes the rule
OperationsList GetOperandsAndRemoveRule(ParseToken** listHead, ParseToken** listTail, CFGRule* rule)
{
OperationsList operands = {};
ParseToken* listSnipHead = *listTail;
PointToHeadOfRuleAndSnip(listHead, listTail, &listSnipHead, rule);
// gets the operands
for(ParseToken* listSnipItr = listSnipHead; listSnipItr != nullptr; listSnipItr = listSnipItr->Next)
{
if(ParseTokenTypeMatches(listSnipItr->TokenType, ProductionVariables))
{
operands.push_back(listSnipItr->Value);
}
}
DestroyList(listSnipHead);
return operands;
}
/// collapse a rule by adding each component as the operand of a new operation
Operation* CollapseByReduce(CFGRule* rule, OperationsList& components)
{
return OperationConstructor(rule->OpType, components);
}
/// collapse a rule by merging all components into the first component's operand list
Operation* CollapseByMerge(CFGRule* rule, OperationsList& components)
{
OperationsList& oplist = components.at(0)->Operands;
for(size_t i=1; i< components.size(); i++)
{
oplist.push_back(components.at(i));
}
return components.at(0);
// for(auto op: components)
// {
// // direcly merge ::Ref type operations into the new operandsList
// if(op->Type == OperationType::Ref)
// mergedOperands.push_back(op);
// // for all other operation types, port the operands directly into the new operandsList
// else
// {
// for(auto opOperand: op->Operands)
// mergedOperands.push_back(opOperand);
// }
// }
// return OperationConstructor(rule->OpType, mergedOperands);
}
/// collapse a rule corresponding to defining a method
Operation* CollapseAsDefineMethod(CFGRule* rule, OperationsList& components)
{
LogItDebug("Custom type", "CollapseListByRule");
auto methodName = components.at(0)->Value->Name;
Method* m = MethodConstructor(CurrentScope());
EnterScope(m->Parameters);
{
if(components.size() > 1)
{
if(components.at(1)->Type == OperationType::Tuple)
{
for(auto op: components.at(1)->Operands)
{
NullReference(op->Value->Name);
}
}
else
{
NullReference(components.at(1)->Value->Name);
}
// // if the operand is already a return operation
// if(components.at(1)->Type == OperationType::Ref)
// NullReference(components.at(1)->Value->Name);
// // if the operand is a list of parameters
// else
// for(size_t i=0; i<components.at(1)->Operands.size(); i++)
// NullReference(components.at(1)->Operands.at(i)->Value->Name);
}
}
ExitScope();
Reference* ref = ReferenceFor(methodName, m);
return OperationConstructor(OperationType::DefineMethod, { OperationConstructor(OperationType::Ref, ref) } );
}
Operation* CollapseRuleInternal(CFGRule* rule, OperationsList& components)
{
if(rule->ParseOperation == "Reduce")
{
return CollapseByReduce(rule, components);
}
else if(rule->ParseOperation == "Retain")
{
return components.at(0);
}
else if(rule->ParseOperation == "Merge")
{
return CollapseByMerge(rule, components);
}
else if(rule->ParseOperation == "Custom")
{
return CollapseAsDefineMethod(rule, components);
}
else
{
LogIt(LogSeverityType::Sev1_Notify, "CollapseRule", "unknown collapsing procedure");
return nullptr;
}
}
/// reverses a rule in the ParseStack
void CollapseListByRule(ParseToken** listHead, ParseToken** listTail, CFGRule* rule)
{
OperationsList operands = GetOperandsAndRemoveRule(listHead, listTail, rule);
Operation* op = CollapseRuleInternal(rule, operands);
ParseToken* t = ParseTokenConstructor(rule->FromProduction);
t->Value = op;
AddToList(listHead, listTail, t);
}
/// if [op] is assigning to an undefined reference, define it
void DefineNewReferenceIfNecessary(Operation* op)
{
if(op->Type == OperationType::Assign)
{
Reference* stub = op->Operands.at(0)->Value;
auto assignToRef = ReferenceFor(stub->Name);
// creates define operation
if(assignToRef == nullptr)
{
Operation* newRefReturn = OperationConstructor(OperationType::Ref, NullReference(stub->Name));
Operation* defRef = OperationConstructor(OperationType::Define, { newRefReturn });
op->Operands[0] = defRef;
delete stub;
}
}
}
void ResolveRefOperation(Operation* refOp)
{
Reference* stub = refOp->Value;
// verify that Reference is in fact a stub
if(IsReferenceStub(stub))
{
// get the reference by name which should be defined
auto resolvedRef = ReferenceFor(stub->Name);
if(resolvedRef == nullptr)
{
ReportCompileMsg(SystemMessageType::Exception, Msg("cannot resolve reference %s. make sure it has been defined", stub->Name));
resolvedRef = NullReference(stub->Name);
}
refOp->Value = resolvedRef;
}
}
/// recursively resolves all reference stubs in [op]
void ResolveReferences(Operation* op)
{
// breaks recursion. these types are handled in the parent
if(op->Type == OperationType::Ref)
return;
if(op->Type == OperationType::DefineMethod)
return;
DefineNewReferenceIfNecessary(op);
for(auto operand: op->Operands)
{
if(operand->Type == OperationType::Ref)
{
ResolveRefOperation(operand);
}
else
{
ResolveReferences(operand);
}
}
}
void LogParseStack(ParseToken* listHead)
{
String Line;
for(ParseToken* t = listHead; t != nullptr; t = t->Next)
{
Line += t->TokenType;
Line += " ";
}
LogItDebug(Line, "LogParseStack");
}
/// add a new token for a Ref (object) to the ParseList
void AddRefToken(ParseToken** listHead, ParseToken** listTail, Token* token)
{
ParseToken* t = ParseTokenConstructor("Ref");
t->Value = RefOperation(token);
AddToList(listHead, listTail, t);
}
/// add a new token for a simple keyword/operation to the ParseList
void AddSimpleToken(ParseToken** listHead, ParseToken** listTail, Token* token)
{
ParseToken* t = ParseTokenConstructor(token->Content);
AddToList(listHead, listTail, t);
}
/// if a grammar rule matches, and the lookahead is of less precedence, then reverse the rule and update
/// the list. continue doing so until no rules match
void TryMatchingGrammarRules(ParseToken** listHead, ParseToken** listTail, Token* lookaheadToken)
{
CFGRule* match = MatchGrammarPatterns(*listHead, *listTail);
while(match != nullptr)
{
if(match != nullptr){
int currentRulePrecedence = match->Precedence;
int lookaheadPrecedence = PrecedenceOf(lookaheadToken);
if(currentRulePrecedence >= lookaheadPrecedence)
{
CollapseListByRule(listHead, listTail, match);
match = MatchGrammarPatterns(*listHead, *listTail);
}
else
{
break;
}
}
LogParseStack(*listHead);
}
}
Operation* ExpressionParser(TokenList& line)
{
ParseToken* listHead = nullptr;
ParseToken* listTail = nullptr;
int pos = 0;
while(static_cast<size_t>(pos) < line.size())
{
Token* currentToken = line.at(pos);
if(TokenMatchesType(line.at(pos), ObjectTokenTypes))
{
AddRefToken(&listHead, &listTail, currentToken);
}
else
{
AddSimpleToken(&listHead, &listTail, currentToken);
}
LogParseStack(listHead);
Token* lookaheadToken = nullptr;
if(static_cast<size_t>(pos+1) < line.size())
lookaheadToken = line.at(pos+1);
TryMatchingGrammarRules(&listHead, &listTail, lookaheadToken);
pos++;
}
// if the line could not be parsed
if(listHead != listTail)
{
ReportCompileMsg(SystemMessageType::Exception, "bad format");
}
ResolveReferences(listHead->Value);
LogItDebug("end reached", "ExpressionParser");
return listHead->Value;
} | 24.92093 | 138 | 0.600261 | tnash9 |
a7965c840339caaf98d370b6ef4abb88fdf7b186 | 17,925 | cpp | C++ | Sources/Internal/Render/Image/ImageConvert.cpp | Serviak/dava.engine | d51a26173a3e1b36403f846ca3b2e183ac298a1a | [
"BSD-3-Clause"
] | 1 | 2020-11-14T10:18:24.000Z | 2020-11-14T10:18:24.000Z | Sources/Internal/Render/Image/ImageConvert.cpp | Serviak/dava.engine | d51a26173a3e1b36403f846ca3b2e183ac298a1a | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/Render/Image/ImageConvert.cpp | Serviak/dava.engine | d51a26173a3e1b36403f846ca3b2e183ac298a1a | [
"BSD-3-Clause"
] | 1 | 2020-09-05T21:16:17.000Z | 2020-09-05T21:16:17.000Z | #include "Render/Image/ImageConvert.h"
#include "Render/Image/LibDdsHelper.h"
#include "Render/Image/LibPVRHelper.h"
#include "Render/Image/Image.h"
#include "Functional/Function.h"
namespace DAVA
{
uint32 ChannelFloatToInt(float32 ch)
{
return static_cast<uint32>(Min(ch, 1.0f) * std::numeric_limits<uint8>::max());
}
float32 ChannelIntToFloat(uint32 ch)
{
return (static_cast<float32>(ch) / std::numeric_limits<uint8>::max());
}
namespace ImageConvert
{
bool Normalize(PixelFormat format, const void* inData, uint32 width, uint32 height, uint32 pitch, void* outData)
{
if (format == FORMAT_RGBA8888)
{
ConvertDirect<uint32, uint32, NormalizeRGBA8888> convert;
convert(inData, width, height, pitch, outData, width, height, pitch);
return true;
}
Logger::Error("Normalize function not implemented for %s", PixelFormatDescriptor::GetPixelFormatString(format));
return false;
}
bool ConvertImage(const Image* srcImage, Image* dstImage)
{
DVASSERT(srcImage);
DVASSERT(dstImage);
DVASSERT(srcImage->format != dstImage->format);
DVASSERT(srcImage->width == dstImage->width);
DVASSERT(srcImage->height == dstImage->height);
PixelFormat srcFormat = srcImage->format;
PixelFormat dstFormat = dstImage->format;
Function<bool(const Image*, Image*)> decompressFn = nullptr;
if (LibDdsHelper::CanDecompressFrom(srcFormat))
{
decompressFn = &LibDdsHelper::DecompressToRGBA;
}
else if (LibPVRHelper::CanDecompressFrom(srcFormat))
{
decompressFn = &LibPVRHelper::DecompressToRGBA;
}
Function<bool(const Image*, Image*)> compressFn = nullptr;
if (LibDdsHelper::CanCompressTo(dstFormat))
{
compressFn = &LibDdsHelper::CompressFromRGBA;
}
else if (LibPVRHelper::CanCompressTo(dstFormat))
{
compressFn = &LibPVRHelper::CompressFromRGBA;
}
if (decompressFn == nullptr && compressFn == nullptr)
{
return ConvertImageDirect(srcImage, dstImage);
}
else if (decompressFn != nullptr && compressFn != nullptr)
{
ScopedPtr<Image> rgba(Image::Create(srcImage->width, srcImage->height, FORMAT_RGBA8888));
return (decompressFn(srcImage, rgba) && compressFn(rgba, dstImage));
}
else if (decompressFn != nullptr)
{
if (dstFormat == FORMAT_RGBA8888)
{
return decompressFn(srcImage, dstImage);
}
else
{
ScopedPtr<Image> rgba(Image::Create(srcImage->width, srcImage->height, FORMAT_RGBA8888));
return (decompressFn(srcImage, rgba) && ConvertImageDirect(rgba, dstImage));
}
}
else
{
if (srcFormat == FORMAT_RGBA8888)
{
return compressFn(srcImage, dstImage);
}
else
{
ScopedPtr<Image> rgba(Image::Create(srcImage->width, srcImage->height, FORMAT_RGBA8888));
return (ConvertImageDirect(srcImage, rgba) && compressFn(rgba, dstImage));
}
}
}
bool ConvertImageDirect(const Image* srcImage, Image* dstImage)
{
return ConvertImageDirect(srcImage->format, dstImage->format,
srcImage->data, srcImage->width, srcImage->height,
ImageUtils::GetPitchInBytes(srcImage->width, srcImage->format),
dstImage->data, dstImage->width, dstImage->height,
ImageUtils::GetPitchInBytes(dstImage->width, dstImage->format));
}
bool ConvertImageDirect(PixelFormat inFormat, PixelFormat outFormat,
const void* inData, uint32 inWidth, uint32 inHeight, uint32 inPitch,
void* outData, uint32 outWidth, uint32 outHeight, uint32 outPitch)
{
if (inFormat == FORMAT_RGBA5551 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<uint16, uint32, ConvertRGBA5551toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA4444 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<uint16, uint32, ConvertRGBA4444toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGB888 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<RGB888, uint32, ConvertRGB888toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGB565 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<uint16, uint32, ConvertRGB565toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_A8 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<uint8, uint32, ConvertA8toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_A16 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<uint16, uint32, ConvertA16toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_BGR888 && outFormat == FORMAT_RGB888)
{
ConvertDirect<BGR888, RGB888, ConvertBGR888toRGB888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_BGR888 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<BGR888, uint32, ConvertBGR888toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_BGRA8888 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<BGRA8888, RGBA8888, ConvertBGRA8888toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA8888 && outFormat == FORMAT_RGB888)
{
ConvertDirect<uint32, RGB888, ConvertRGBA8888toRGB888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA16161616 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<RGBA16161616, uint32, ConvertRGBA16161616toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA32323232 && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<RGBA32323232, uint32, ConvertRGBA32323232toRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA16F && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<RGBA16F, uint32, ConvertRGBA16FtoRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA32F && outFormat == FORMAT_RGBA8888)
{
ConvertDirect<RGBA32F, uint32, ConvertRGBA32FtoRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA8888 && outFormat == FORMAT_RGBA16F)
{
ConvertDirect<uint32, RGBA16F, ConvertRGBA8888toRGBA16F> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else if (inFormat == FORMAT_RGBA8888 && outFormat == FORMAT_RGBA32F)
{
ConvertDirect<uint32, RGBA32F, ConvertRGBA8888toRGBA32F> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
return true;
}
else
{
Logger::FrameworkDebug("Unsupported image conversion from format %d to %d", inFormat, outFormat);
return false;
}
}
bool CanConvertDirect(PixelFormat inFormat, PixelFormat outFormat)
{
return ConvertImageDirect(inFormat, outFormat, nullptr, 0, 0, 0, nullptr, 0, 0, 0);
}
bool CanConvertFromTo(PixelFormat inFormat, PixelFormat outFormat)
{
bool inCompressed = LibDdsHelper::CanDecompressFrom(inFormat) || LibPVRHelper::CanDecompressFrom(inFormat);
bool outCompressed = LibDdsHelper::CanCompressTo(outFormat) || LibPVRHelper::CanCompressTo(outFormat);
if (!inCompressed && !outCompressed)
{
return CanConvertDirect(inFormat, outFormat);
}
else if (inCompressed && outCompressed)
{
return true;
}
else if (inCompressed)
{
return (outFormat == FORMAT_RGBA8888 ? true : CanConvertDirect(FORMAT_RGBA8888, outFormat));
}
else
{
return (inFormat == FORMAT_RGBA8888 ? true : CanConvertDirect(outFormat, FORMAT_RGBA8888));
}
}
void SwapRedBlueChannels(const Image* srcImage, const Image* dstImage /* = nullptr*/)
{
DVASSERT(srcImage);
if (dstImage)
{
DVASSERT(PixelFormatDescriptor::GetPixelFormatSizeInBits(dstImage->format) == PixelFormatDescriptor::GetPixelFormatSizeInBits(srcImage->format));
DVASSERT(srcImage->width == dstImage->width);
DVASSERT(srcImage->height == dstImage->height);
}
SwapRedBlueChannels(srcImage->format, srcImage->data, srcImage->width, srcImage->height,
ImageUtils::GetPitchInBytes(srcImage->width, srcImage->format),
dstImage ? dstImage->data : nullptr);
}
void SwapRedBlueChannels(PixelFormat format, void* srcData, uint32 width, uint32 height, uint32 pitch, void* dstData /* = nullptr*/)
{
if (!dstData)
dstData = srcData;
switch (format)
{
case FORMAT_RGB888:
{
ConvertDirect<BGR888, RGB888, ConvertBGR888toRGB888> swap;
swap(srcData, width, height, pitch, dstData);
return;
}
case FORMAT_RGBA8888:
{
ConvertDirect<BGRA8888, RGBA8888, ConvertBGRA8888toRGBA8888> swap;
swap(srcData, width, height, pitch, dstData);
return;
}
case FORMAT_RGBA4444:
{
ConvertDirect<uint16, uint16, ConvertBGRA4444toRGBA4444> swap;
swap(srcData, width, height, pitch, dstData);
return;
}
case FORMAT_RGB565:
{
ConvertDirect<uint16, uint16, ConvertBGR565toRGB565> swap;
swap(srcData, width, height, pitch, dstData);
return;
}
case FORMAT_RGBA16161616:
{
ConvertDirect<RGBA16161616, RGBA16161616, ConvertBGRA16161616toRGBA16161616> swap;
swap(srcData, width, height, pitch, dstData);
return;
}
case FORMAT_RGBA32323232:
{
ConvertDirect<RGBA32323232, RGBA32323232, ConvertBGRA32323232toRGBA32323232> swap;
swap(srcData, width, height, pitch, dstData);
return;
}
case FORMAT_A8:
case FORMAT_A16:
{
// do nothing for grayscale images
return;
}
default:
{
Logger::Error("Image color exchanging is not supported for format %d", format);
return;
}
}
}
bool DownscaleTwiceBillinear(PixelFormat inFormat, PixelFormat outFormat,
const void* inData, uint32 inWidth, uint32 inHeight, uint32 inPitch,
void* outData, uint32 outWidth, uint32 outHeight, uint32 outPitch, bool normalize)
{
if ((inFormat == FORMAT_RGBA8888) && (outFormat == FORMAT_RGBA8888))
{
if (normalize)
{
ConvertDownscaleTwiceBillinear<uint32, uint32, uint32, UnpackRGBA8888, PackNormalizedRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else
{
ConvertDownscaleTwiceBillinear<uint32, uint32, uint32, UnpackRGBA8888, PackRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
}
else if ((inFormat == FORMAT_RGBA8888) && (outFormat == FORMAT_RGBA4444))
{
ConvertDownscaleTwiceBillinear<uint32, uint16, uint32, UnpackRGBA8888, PackRGBA4444> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_RGBA4444) && (outFormat == FORMAT_RGBA8888))
{
ConvertDownscaleTwiceBillinear<uint16, uint32, uint32, UnpackRGBA4444, PackRGBA8888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_A8) && (outFormat == FORMAT_A8))
{
ConvertDownscaleTwiceBillinear<uint8, uint8, uint32, UnpackA8, PackA8> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_RGB888) && (outFormat == FORMAT_RGB888))
{
ConvertDownscaleTwiceBillinear<RGB888, RGB888, uint32, UnpackRGB888, PackRGB888> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_RGBA5551) && (outFormat == FORMAT_RGBA5551))
{
ConvertDownscaleTwiceBillinear<uint16, uint16, uint32, UnpackRGBA5551, PackRGBA5551> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_RGBA16161616) && (outFormat == FORMAT_RGBA16161616))
{
ConvertDownscaleTwiceBillinear<RGBA16161616, RGBA16161616, uint32, UnpackRGBA16161616, PackRGBA16161616> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_RGBA32323232) && (outFormat == FORMAT_RGBA32323232))
{
ConvertDownscaleTwiceBillinear<RGBA32323232, RGBA32323232, uint64, UnpackRGBA32323232, PackRGBA32323232> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_RGBA16F) && (outFormat == FORMAT_RGBA16F))
{
ConvertDownscaleTwiceBillinear<RGBA16F, RGBA16F, float32, UnpackRGBA16F, PackRGBA16F> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else if ((inFormat == FORMAT_RGBA32F) && (outFormat == FORMAT_RGBA32F))
{
ConvertDownscaleTwiceBillinear<RGBA32F, RGBA32F, float32, UnpackRGBA32F, PackRGBA32F> convert;
convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch);
}
else
{
Logger::Error("Downscale from %s to %s is not implemented", PixelFormatDescriptor::GetPixelFormatString(inFormat), PixelFormatDescriptor::GetPixelFormatString(outFormat));
return false;
}
return true;
}
Image* DownscaleTwiceBillinear(const Image* source, bool isNormalMap /*= false*/)
{
DVASSERT(source != nullptr);
PixelFormat pixelFormat = source->GetPixelFormat();
uint32 sWidth = source->GetWidth();
uint32 sHeigth = source->GetHeight();
uint32 dWidth = sWidth >> 1;
uint32 dHeigth = sHeigth >> 1;
Image* destination = Image::Create(dWidth, dHeigth, pixelFormat);
if (destination != nullptr)
{
uint32 pitchMultiplier = PixelFormatDescriptor::GetPixelFormatSizeInBits(pixelFormat);
bool downscaled = DownscaleTwiceBillinear(pixelFormat, pixelFormat, source->GetData(), sWidth, sHeigth, sWidth * pitchMultiplier / 8, destination->GetData(), dWidth, dHeigth, dWidth * pitchMultiplier / 8, isNormalMap);
if (downscaled == false)
{
SafeRelease(destination);
}
}
return destination;
}
void ResizeRGBA8Billinear(const uint32* inPixels, uint32 w, uint32 h, uint32* outPixels, uint32 w2, uint32 h2)
{
int32 a, b, c, d, x, y, index;
float32 x_ratio = (static_cast<float32>(w - 1)) / w2;
float32 y_ratio = (static_cast<float32>(h - 1)) / h2;
float32 x_diff, y_diff, blue, red, green, alpha;
uint32 offset = 0;
for (uint32 i = 0; i < h2; i++)
{
for (uint32 j = 0; j < w2; j++)
{
x = static_cast<int32>(x_ratio * j);
y = static_cast<int32>(y_ratio * i);
x_diff = (x_ratio * j) - x;
y_diff = (y_ratio * i) - y;
index = (y * w + x);
a = inPixels[index];
b = inPixels[index + 1];
c = inPixels[index + w];
d = inPixels[index + w + 1];
blue = (a & 0xff) * (1 - x_diff) * (1 - y_diff) + (b & 0xff) * (x_diff) * (1 - y_diff) +
(c & 0xff) * (y_diff) * (1 - x_diff) + (d & 0xff) * (x_diff * y_diff);
green = ((a >> 8) & 0xff) * (1 - x_diff) * (1 - y_diff) + ((b >> 8) & 0xff) * (x_diff) * (1 - y_diff) +
((c >> 8) & 0xff) * (y_diff) * (1 - x_diff) + ((d >> 8) & 0xff) * (x_diff * y_diff);
red = ((a >> 16) & 0xff) * (1 - x_diff) * (1 - y_diff) + ((b >> 16) & 0xff) * (x_diff) * (1 - y_diff) +
((c >> 16) & 0xff) * (y_diff) * (1 - x_diff) + ((d >> 16) & 0xff) * (x_diff * y_diff);
alpha = ((a >> 24) & 0xff) * (1 - x_diff) * (1 - y_diff) + ((b >> 24) & 0xff) * (x_diff) * (1 - y_diff) +
((c >> 24) & 0xff) * (y_diff) * (1 - x_diff) + ((d >> 24) & 0xff) * (x_diff * y_diff);
outPixels[offset++] =
(((static_cast<uint32>(alpha)) << 24) & 0xff000000) |
(((static_cast<uint32>(red)) << 16) & 0xff0000) |
(((static_cast<uint32>(green)) << 8) & 0xff00) |
(static_cast<uint32>(blue));
}
}
}
} // namespace ImageConvert
} // namespace DAVA
| 39.137555 | 226 | 0.64781 | Serviak |
a7989f7e4ece026bbdc262e3111af38ca068f156 | 2,945 | cpp | C++ | samples/hwdrivers_capture_video_opencv/test.cpp | wstnturner/mrpt | b0be3557a4cded6bafff03feb28f7fa1f75762a3 | [
"BSD-3-Clause"
] | 38 | 2015-01-04T05:24:26.000Z | 2015-07-17T00:30:02.000Z | samples/hwdrivers_capture_video_opencv/test.cpp | wstnturner/mrpt | b0be3557a4cded6bafff03feb28f7fa1f75762a3 | [
"BSD-3-Clause"
] | 40 | 2015-01-03T22:43:00.000Z | 2015-07-17T18:52:59.000Z | samples/hwdrivers_capture_video_opencv/test.cpp | wstnturner/mrpt | b0be3557a4cded6bafff03feb28f7fa1f75762a3 | [
"BSD-3-Clause"
] | 41 | 2015-01-06T12:32:19.000Z | 2017-05-30T15:50:13.000Z | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2022, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <mrpt/gui/CDisplayWindow.h>
#include <mrpt/hwdrivers/CImageGrabber_OpenCV.h>
#include <mrpt/io/CFileGZOutputStream.h>
#include <mrpt/serialization/CArchive.h>
#include <mrpt/system/CTicTac.h>
#include <iostream>
using namespace mrpt::hwdrivers;
using namespace mrpt::gui;
using namespace mrpt::obs;
using namespace mrpt::system;
using namespace mrpt::io;
using namespace mrpt::serialization;
using namespace std;
// ------------------------------------------------------
// TestCaptureOpenCV
// ------------------------------------------------------
bool LIVE_CAM = true;
int N_CAM_TO_OPEN = 0;
std::string AVI_TO_OPEN;
void TestCapture_OpenCV()
{
CImageGrabber_OpenCV* capture = nullptr;
if (LIVE_CAM)
{
#if 0 // test: Select the desired resolution
mrpt::vision::TCaptureCVOptions opts;
opts.frame_width = 320;
opts.frame_height = 240;
capture = new CImageGrabber_OpenCV( 0, CAMERA_CV_AUTODETECT, opts );
#else
capture = new CImageGrabber_OpenCV(N_CAM_TO_OPEN, CAMERA_CV_AUTODETECT);
#endif
}
else
{
capture = new CImageGrabber_OpenCV(AVI_TO_OPEN);
}
CTicTac tictac;
cout << "Press any key to stop capture to 'capture.rawlog'..." << endl;
CFileGZOutputStream fil("./capture.rawlog");
CDisplayWindow win("Capturing...");
int cnt = 0;
while (!mrpt::system::os::kbhit())
{
if ((cnt++ % 20) == 0)
{
if (cnt > 0)
{
double t = tictac.Tac();
double FPS = 20 / t;
printf("\n %f FPS\n", FPS);
}
tictac.Tic();
}
CObservationImage::Ptr obs =
CObservationImage::Create(); // Memory will be
// freed by
// SF destructor in each
// loop.
if (!capture->getObservation(*obs))
{
cerr << "Error retrieving images!" << endl;
break;
}
archiveFrom(fil) << obs;
cout << ".";
cout.flush();
if (win.isOpen()) win.showImage(obs->image);
}
delete capture;
}
int main(int argc, char** argv)
{
try
{
if (argc > 1)
{
if (!strstr(argv[1], ".avi"))
{
LIVE_CAM = true;
N_CAM_TO_OPEN = atoi(argv[1]);
}
else
{
LIVE_CAM = false;
AVI_TO_OPEN = argv[1];
}
}
TestCapture_OpenCV();
return 0;
}
catch (const std::exception& e)
{
std::cerr << "MRPT error: " << mrpt::exception_to_str(e) << std::endl;
return -1;
}
catch (...)
{
printf("Another exception!!");
return -1;
}
}
| 22.653846 | 80 | 0.551104 | wstnturner |
a79aa1315719ce59f29cf99d5d635eb68d9833aa | 7,803 | cpp | C++ | source/Lib/CommonLib/x86/InitX86.cpp | 1div0/vvdec | fceca978976f7f7394df839fe31497d2299fde80 | [
"BSD-3-Clause"
] | 204 | 2020-09-08T01:46:07.000Z | 2022-03-29T23:54:49.000Z | source/Lib/CommonLib/x86/InitX86.cpp | 1div0/vvdec | fceca978976f7f7394df839fe31497d2299fde80 | [
"BSD-3-Clause"
] | 42 | 2020-09-09T04:40:13.000Z | 2022-03-08T03:52:18.000Z | source/Lib/CommonLib/x86/InitX86.cpp | 1div0/vvdec | fceca978976f7f7394df839fe31497d2299fde80 | [
"BSD-3-Clause"
] | 57 | 2020-09-08T01:46:09.000Z | 2022-03-16T07:07:38.000Z | /* -----------------------------------------------------------------------------
The copyright in this software is being made available under the BSD
License, included below. No patent rights, trademark rights and/or
other Intellectual Property Rights other than the copyrights concerning
the Software are granted under this license.
For any license concerning other Intellectual Property rights than the software,
especially patent licenses, a separate Agreement needs to be closed.
For more information please contact:
Fraunhofer Heinrich Hertz Institute
Einsteinufer 37
10587 Berlin, Germany
www.hhi.fraunhofer.de/vvc
vvc@hhi.fraunhofer.de
Copyright (c) 2018-2021, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Fraunhofer 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.
------------------------------------------------------------------------------------------- */
/*
* \ingroup CommonLib
* \file InitX86.cpp
* \brief Initialize encoder SIMD functions.
*/
#include "CommonLib/CommonDef.h"
#include "CommonLib/InterpolationFilter.h"
#include "CommonLib/TrQuant.h"
#include "CommonLib/RdCost.h"
#include "CommonLib/Buffer.h"
#include "CommonLib/TrQuant_EMT.h"
#include "CommonLib/IntraPrediction.h"
#include "CommonLib/LoopFilter.h"
#include "CommonLib/Picture.h"
#include "CommonLib/AdaptiveLoopFilter.h"
#include "CommonLib/SampleAdaptiveOffset.h"
namespace vvdec
{
#ifdef TARGET_SIMD_X86
#if ENABLE_SIMD_OPT_MCIF
void InterpolationFilter::initInterpolationFilterX86( /*int iBitDepthY, int iBitDepthC*/ )
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initInterpolationFilterX86<AVX2>(/*iBitDepthY, iBitDepthC*/);
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initInterpolationFilterX86<AVX>(/*iBitDepthY, iBitDepthC*/);
break;
case SSE42:
case SSE41:
_initInterpolationFilterX86<SSE41>(/*iBitDepthY, iBitDepthC*/);
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_BUFFER
void PelBufferOps::initPelBufOpsX86()
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initPelBufOpsX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initPelBufOpsX86<AVX>();
break;
case SSE42:
case SSE41:
_initPelBufOpsX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_DIST
void RdCost::initRdCostX86()
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initRdCostX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initRdCostX86<AVX>();
break;
case SSE42:
case SSE41:
_initRdCostX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_ALF
void AdaptiveLoopFilter::initAdaptiveLoopFilterX86()
{
auto vext = read_x86_extension_flags();
switch ( vext )
{
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initAdaptiveLoopFilterX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initAdaptiveLoopFilterX86<AVX>();
break;
case SSE42:
case SSE41:
_initAdaptiveLoopFilterX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_DBLF
void LoopFilter::initLoopFilterX86()
{
auto vext = read_x86_extension_flags();
switch ( vext )
{
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initLoopFilterX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initLoopFilterX86<AVX>();
break;
case SSE42:
case SSE41:
_initLoopFilterX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_TCOEFF_OPS
void TCoeffOps::initTCoeffOpsX86()
{
auto vext = read_x86_extension_flags();
switch( vext )
{
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initTCoeffOpsX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initTCoeffOpsX86<AVX>();
break;
case SSE42:
case SSE41:
_initTCoeffOpsX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_INTRAPRED
void IntraPrediction::initIntraPredictionX86()
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initIntraPredictionX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initIntraPredictionX86<AVX>();
break;
case SSE42:
case SSE41:
_initIntraPredictionX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_SAO
void SampleAdaptiveOffset::initSampleAdaptiveOffsetX86()
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initSampleAdaptiveOffsetX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initSampleAdaptiveOffsetX86<AVX>();
break;
case SSE42:
case SSE41:
_initSampleAdaptiveOffsetX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_INTER
void InterPrediction::initInterPredictionX86()
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initInterPredictionX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initInterPredictionX86<AVX>();
break;
case SSE42:
case SSE41:
_initInterPredictionX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_PICTURE
void Picture::initPictureX86()
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initPictureX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initPictureX86<AVX>();
break;
case SSE42:
case SSE41:
_initPictureX86<SSE41>();
break;
default:
break;
}
}
#endif
#if ENABLE_SIMD_OPT_QUANT
void Quant::initQuantX86()
{
auto vext = read_x86_extension_flags();
switch (vext){
case AVX512:
case AVX2:
#ifndef TARGET_SIMD_WASM
_initQuantX86<AVX2>();
break;
#endif // !TARGET_SIMD_WASM
case AVX:
_initQuantX86<AVX>();
break;
case SSE42:
case SSE41:
_initQuantX86<SSE41>();
break;
default:
break;
}
}
#endif
#endif
}
| 21.918539 | 94 | 0.695117 | 1div0 |
a79eec3054f3faaae30c43783dac2c20f6857966 | 521 | cpp | C++ | Structural/Bridge/src/main.cpp | craviee/design-patterns-modern-cpp | 39896c8a2491c5599f79afa65a07deda2e4e7dd7 | [
"Unlicense"
] | 3 | 2019-11-15T01:38:31.000Z | 2020-04-21T13:04:19.000Z | Structural/Bridge/src/main.cpp | craviee/design-patterns-modern-cpp | 39896c8a2491c5599f79afa65a07deda2e4e7dd7 | [
"Unlicense"
] | 23 | 2019-11-29T09:13:42.000Z | 2020-02-05T14:53:03.000Z | Structural/Bridge/src/main.cpp | craviee/design-patterns-modern-cpp | 39896c8a2491c5599f79afa65a07deda2e4e7dd7 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <memory>
#include "CompanyTraveler.hpp"
#include "PlaneTravel.hpp"
#include "TrainTravel.hpp"
int main()
{
auto plane = std::make_shared<PlaneTravel>();
auto train = std::make_shared<TrainTravel>();
CompanyTraveler traveler{std::static_pointer_cast<TravelMethod>(plane)};
CompanyTraveler anotherTraveler{std::static_pointer_cast<TravelMethod>(train)};
traveler.doTravel();
plane->price = 400;
traveler.doTravel();
anotherTraveler.doTravel();
return 0;
} | 26.05 | 83 | 0.721689 | craviee |
a79fb6fe444538eda1e8ce75a50b158177480294 | 15,180 | cpp | C++ | Source/Core/GeometryBackgroundBorder.cpp | aquawicket/RmlUi | d56f17e49ca2ee88aadeb304228cd1eae14e3f51 | [
"MIT"
] | null | null | null | Source/Core/GeometryBackgroundBorder.cpp | aquawicket/RmlUi | d56f17e49ca2ee88aadeb304228cd1eae14e3f51 | [
"MIT"
] | null | null | null | Source/Core/GeometryBackgroundBorder.cpp | aquawicket/RmlUi | d56f17e49ca2ee88aadeb304228cd1eae14e3f51 | [
"MIT"
] | null | null | null | /*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "GeometryBackgroundBorder.h"
#include "../../Include/RmlUi/Core/Box.h"
#include "../../Include/RmlUi/Core/Math.h"
#include <algorithm>
#include <float.h>
namespace Rml {
GeometryBackgroundBorder::GeometryBackgroundBorder(Vector<Vertex>& vertices, Vector<int>& indices) : vertices(vertices), indices(indices)
{}
void GeometryBackgroundBorder::Draw(Vector<Vertex>& vertices, Vector<int>& indices, CornerSizes radii, const Box& box, const Vector2f offset, const Colourb background_color, const Colourb* border_colors)
{
using Edge = Box::Edge;
EdgeSizes border_widths = {
Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::TOP)),
Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::RIGHT)),
Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::BOTTOM)),
Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::LEFT)),
};
int num_borders = 0;
if (border_colors)
{
for (int i = 0; i < 4; i++)
if (border_colors[i].alpha > 0 && border_widths[i] > 0)
num_borders += 1;
}
const Vector2f padding_size = box.GetSize(Box::PADDING).Round();
const bool has_background = (background_color.alpha > 0 && padding_size.x > 0 && padding_size.y > 0);
const bool has_border = (num_borders > 0);
if (!has_background && !has_border)
return;
// -- Find the corner positions --
const Vector2f border_position = offset.Round();
const Vector2f padding_position = border_position + Vector2f(border_widths[Edge::LEFT], border_widths[Edge::TOP]);
const Vector2f border_size = padding_size + Vector2f(border_widths[Edge::LEFT] + border_widths[Edge::RIGHT], border_widths[Edge::TOP] + border_widths[Edge::BOTTOM]);
// Border edge positions
CornerPositions positions_outer = {
border_position,
border_position + Vector2f(border_size.x, 0),
border_position + border_size,
border_position + Vector2f(0, border_size.y)
};
// Padding edge positions
CornerPositions positions_inner = {
padding_position,
padding_position + Vector2f(padding_size.x, 0),
padding_position + padding_size,
padding_position + Vector2f(0, padding_size.y)
};
// -- For curved borders, find the positions to draw ellipses around, and the scaled outer and inner radii --
const float sum_radius = (radii[TOP_LEFT] + radii[TOP_RIGHT] + radii[BOTTOM_RIGHT] + radii[BOTTOM_LEFT]);
const bool has_radius = (sum_radius > 1.f);
// Curved borders are drawn as circles (outer border) and ellipses (inner border) around the centers.
CornerPositions positions_circle_center;
// Radii of the padding edges, 2-dimensional as these can be ellipses.
// The inner radii is effectively the (signed) distance from the circle center to the padding edge.
// They can also be zero or negative, in which case a sharp corner should be drawn instead of an arc.
CornerSizes2 inner_radii;
if (has_radius)
{
// Scale the radii such that we have no overlapping curves.
float scale_factor = FLT_MAX;
scale_factor = Math::Min(scale_factor, padding_size.x / (radii[TOP_LEFT] + radii[TOP_RIGHT])); // Top
scale_factor = Math::Min(scale_factor, padding_size.y / (radii[TOP_RIGHT] + radii[BOTTOM_RIGHT])); // Right
scale_factor = Math::Min(scale_factor, padding_size.x / (radii[BOTTOM_RIGHT] + radii[BOTTOM_LEFT])); // Bottom
scale_factor = Math::Min(scale_factor, padding_size.y / (radii[BOTTOM_LEFT] + radii[TOP_LEFT])); // Left
scale_factor = Math::Min(1.0f, scale_factor);
for (float& radius : radii)
radius = Math::RoundFloat(radius * scale_factor);
// Place the circle/ellipse centers
positions_circle_center = {
positions_outer[TOP_LEFT] + Vector2f(1, 1) * radii[TOP_LEFT],
positions_outer[TOP_RIGHT] + Vector2f(-1, 1) * radii[TOP_RIGHT],
positions_outer[BOTTOM_RIGHT] + Vector2f(-1, -1) * radii[BOTTOM_RIGHT],
positions_outer[BOTTOM_LEFT] + Vector2f(1, -1) * radii[BOTTOM_LEFT]
};
inner_radii = {
Vector2f(radii[TOP_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::TOP]),
Vector2f(radii[TOP_RIGHT]) - Vector2f(border_widths[Edge::RIGHT], border_widths[Edge::TOP]),
Vector2f(radii[BOTTOM_RIGHT]) - Vector2f(border_widths[Edge::RIGHT], border_widths[Edge::BOTTOM]),
Vector2f(radii[BOTTOM_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::BOTTOM])
};
}
// -- Generate the geometry --
GeometryBackgroundBorder geometry(vertices, indices);
{
// Reserve geometry. A conservative estimate, does not take border-radii into account and assumes same-colored borders.
const int estimated_num_vertices = 4 * int(has_background) + 2 * num_borders;
const int estimated_num_triangles = 2 * int(has_background) + 2 * num_borders;
vertices.reserve((int)vertices.size() + estimated_num_vertices);
indices.reserve((int)indices.size() + 3 * estimated_num_triangles);
}
// Draw the background
if (has_background)
{
const int offset_vertices = (int)vertices.size();
for (int corner = 0; corner < 4; corner++)
geometry.DrawBackgroundCorner(Corner(corner), positions_inner[corner], positions_circle_center[corner], radii[corner], inner_radii[corner], background_color);
geometry.FillBackground(offset_vertices);
}
// Draw the border
if (has_border)
{
using Edge = Box::Edge;
const int offset_vertices = (int)vertices.size();
const bool draw_edge[4] = {
border_widths[Edge::TOP] > 0 && border_colors[Edge::TOP].alpha > 0,
border_widths[Edge::RIGHT] > 0 && border_colors[Edge::RIGHT].alpha > 0,
border_widths[Edge::BOTTOM] > 0 && border_colors[Edge::BOTTOM].alpha > 0,
border_widths[Edge::LEFT] > 0 && border_colors[Edge::LEFT].alpha > 0
};
const bool draw_corner[4] = {
draw_edge[Edge::TOP] || draw_edge[Edge::LEFT],
draw_edge[Edge::TOP] || draw_edge[Edge::RIGHT],
draw_edge[Edge::BOTTOM] || draw_edge[Edge::RIGHT],
draw_edge[Edge::BOTTOM] || draw_edge[Edge::LEFT]
};
for (int corner = 0; corner < 4; corner++)
{
const Edge edge0 = Edge((corner + 3) % 4);
const Edge edge1 = Edge(corner);
if (draw_corner[corner])
geometry.DrawBorderCorner(Corner(corner), positions_outer[corner], positions_inner[corner], positions_circle_center[corner],
radii[corner], inner_radii[corner], border_colors[edge0], border_colors[edge1]);
if (draw_edge[edge1])
{
RMLUI_ASSERTMSG(draw_corner[corner] && draw_corner[(corner + 1) % 4], "Border edges can only be drawn if both of its connected corners are drawn.");
geometry.FillEdge(edge1 == Edge::LEFT ? offset_vertices : (int)vertices.size());
}
}
}
#if 0
// Debug draw vertices
if (has_radius)
{
const int num_vertices = vertices.size();
const int num_indices = indices.size();
vertices.resize(num_vertices + 4 * num_vertices);
indices.resize(num_indices + 6 * num_indices);
for (int i = 0; i < num_vertices; i++)
{
GeometryUtilities::GenerateQuad(vertices.data() + num_vertices + 4 * i, indices.data() + num_indices + 6 * i, vertices[i].position, Vector2f(3, 3), Colourb(255, 0, (i % 2) == 0 ? 0 : 255), num_vertices + 4 * i);
}
}
#endif
#ifdef RMLUI_DEBUG
const int num_vertices = (int)vertices.size();
for (int index : indices)
{
RMLUI_ASSERT(index < num_vertices);
}
#endif
}
void GeometryBackgroundBorder::DrawBackgroundCorner(Corner corner, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color)
{
if (R == 0 || r.x <= 0 || r.y <= 0)
{
DrawPoint(pos_inner, color);
}
else if (r.x > 0 && r.y > 0)
{
const float a0 = float((int)corner + 2) * 0.5f * Math::RMLUI_PI;
const float a1 = float((int)corner + 3) * 0.5f * Math::RMLUI_PI;
const int num_points = GetNumPoints(R);
DrawArc(pos_circle_center, r, a0, a1, color, color, num_points);
}
}
void GeometryBackgroundBorder::DrawPoint(Vector2f pos, Colourb color)
{
const int offset_vertices = (int)vertices.size();
vertices.resize(offset_vertices + 1);
vertices[offset_vertices].position = pos;
vertices[offset_vertices].colour = color;
}
void GeometryBackgroundBorder::DrawArc(Vector2f pos_center, Vector2f r, float a0, float a1, Colourb color0, Colourb color1, int num_points)
{
RMLUI_ASSERT(num_points >= 2 && r.x > 0 && r.y > 0);
const int offset_vertices = (int)vertices.size();
vertices.resize(offset_vertices + num_points);
for (int i = 0; i < num_points; i++)
{
const float t = float(i) / float(num_points - 1);
const float a = Math::Lerp(t, a0, a1);
const Vector2f unit_vector(Math::Cos(a), Math::Sin(a));
vertices[offset_vertices + i].position = unit_vector * r + pos_center;
vertices[offset_vertices + i].colour = Math::RoundedLerp(t, color0, color1);
}
}
void GeometryBackgroundBorder::FillBackground(int index_start)
{
const int num_added_vertices = (int)vertices.size() - index_start;
const int offset_indices = (int)indices.size();
const int num_triangles = (num_added_vertices - 2);
indices.resize(offset_indices + 3 * num_triangles);
for (int i = 0; i < num_triangles; i++)
{
indices[offset_indices + 3 * i] = index_start;
indices[offset_indices + 3 * i + 1] = index_start + i + 2;
indices[offset_indices + 3 * i + 2] = index_start + i + 1;
}
}
void GeometryBackgroundBorder::DrawBorderCorner(Corner corner, Vector2f pos_outer, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color0, Colourb color1)
{
const float a0 = float((int)corner + 2) * 0.5f * Math::RMLUI_PI;
const float a1 = float((int)corner + 3) * 0.5f * Math::RMLUI_PI;
if (R == 0)
{
DrawPointPoint(pos_outer, pos_inner, color0, color1);
}
else if (r.x > 0 && r.y > 0)
{
DrawArcArc(pos_circle_center, R, r, a0, a1, color0, color1, GetNumPoints(R));
}
else
{
DrawArcPoint(pos_circle_center, pos_inner, R, a0, a1, color0, color1, GetNumPoints(R));
}
}
void GeometryBackgroundBorder::DrawPointPoint(Vector2f pos_outer, Vector2f pos_inner, Colourb color0, Colourb color1)
{
const bool different_color = (color0 != color1);
vertices.reserve((int)vertices.size() + (different_color ? 4 : 2));
DrawPoint(pos_inner, color0);
DrawPoint(pos_outer, color0);
if (different_color)
{
DrawPoint(pos_inner, color1);
DrawPoint(pos_outer, color1);
}
}
void GeometryBackgroundBorder::DrawArcArc(Vector2f pos_center, float R, Vector2f r, float a0, float a1, Colourb color0, Colourb color1, int num_points)
{
RMLUI_ASSERT(num_points >= 2 && R > 0 && r.x > 0 && r.y > 0);
const int num_triangles = 2 * (num_points - 1);
const int offset_vertices = (int)vertices.size();
const int offset_indices = (int)indices.size();
vertices.resize(offset_vertices + 2 * num_points);
indices.resize(offset_indices + 3 * num_triangles);
for (int i = 0; i < num_points; i++)
{
const float t = float(i) / float(num_points - 1);
const float a = Math::Lerp(t, a0, a1);
const Colourb color = Math::RoundedLerp(t, color0, color1);
const Vector2f unit_vector(Math::Cos(a), Math::Sin(a));
vertices[offset_vertices + 2 * i].position = unit_vector * r + pos_center;
vertices[offset_vertices + 2 * i].colour = color;
vertices[offset_vertices + 2 * i + 1].position = unit_vector * R + pos_center;
vertices[offset_vertices + 2 * i + 1].colour = color;
}
for (int i = 0; i < num_triangles; i += 2)
{
indices[offset_indices + 3 * i + 0] = offset_vertices + i + 0;
indices[offset_indices + 3 * i + 1] = offset_vertices + i + 2;
indices[offset_indices + 3 * i + 2] = offset_vertices + i + 1;
indices[offset_indices + 3 * i + 3] = offset_vertices + i + 1;
indices[offset_indices + 3 * i + 4] = offset_vertices + i + 2;
indices[offset_indices + 3 * i + 5] = offset_vertices + i + 3;
}
}
void GeometryBackgroundBorder::DrawArcPoint(Vector2f pos_center, Vector2f pos_inner, float R, float a0, float a1, Colourb color0, Colourb color1, int num_points)
{
RMLUI_ASSERT(R > 0 && num_points >= 2);
const int offset_vertices = (int)vertices.size();
vertices.reserve(offset_vertices + num_points + 2);
// Generate the vertices. We could also split the arc mid-way to create a sharp color transition.
DrawPoint(pos_inner, color0);
DrawArc(pos_center, Vector2f(R), a0, a1, color0, color1, num_points);
DrawPoint(pos_inner, color1);
RMLUI_ASSERT((int)vertices.size() - offset_vertices == num_points + 2);
// Swap the last two vertices such that the outer edge vertex is last, see the comment for the border drawing functions. Their colors should already be the same.
const int last_vertex = (int)vertices.size() - 1;
std::swap(vertices[last_vertex - 1].position, vertices[last_vertex].position);
// Generate the indices
const int num_triangles = (num_points - 1);
const int i_vertex_inner0 = offset_vertices;
const int i_vertex_inner1 = last_vertex - 1;
const int offset_indices = (int)indices.size();
indices.resize(offset_indices + 3 * num_triangles);
for (int i = 0; i < num_triangles; i++)
{
indices[offset_indices + 3 * i + 0] = (i > num_triangles / 2 ? i_vertex_inner1 : i_vertex_inner0);
indices[offset_indices + 3 * i + 1] = offset_vertices + i + 2;
indices[offset_indices + 3 * i + 2] = offset_vertices + i + 1;
}
// Since we swapped the last two vertices we also need to change the last triangle.
indices[offset_indices + 3 * (num_triangles - 1) + 1] = last_vertex;
}
void GeometryBackgroundBorder::FillEdge(int index_next_corner)
{
const int offset_indices = (int)indices.size();
const int num_vertices = (int)vertices.size();
RMLUI_ASSERT(num_vertices >= 2);
indices.resize(offset_indices + 6);
indices[offset_indices + 0] = num_vertices - 2;
indices[offset_indices + 1] = index_next_corner;
indices[offset_indices + 2] = num_vertices - 1;
indices[offset_indices + 3] = num_vertices - 1;
indices[offset_indices + 4] = index_next_corner;
indices[offset_indices + 5] = index_next_corner + 1;
}
int GeometryBackgroundBorder::GetNumPoints(float R) const
{
return Math::Clamp(3 + Math::RoundToInteger(R / 6.f), 2, 100);
}
} // namespace Rml
| 36.142857 | 214 | 0.713439 | aquawicket |
a7a133e38e7f26144b668b432f88a35dc2e5d172 | 1,426 | cpp | C++ | src/engine/ModelLoader.cpp | eknah/Forradia | 20ec33fd515e131cd1943e9684552961d2e1e0db | [
"MIT"
] | null | null | null | src/engine/ModelLoader.cpp | eknah/Forradia | 20ec33fd515e131cd1943e9684552961d2e1e0db | [
"MIT"
] | null | null | null | src/engine/ModelLoader.cpp | eknah/Forradia | 20ec33fd515e131cd1943e9684552961d2e1e0db | [
"MIT"
] | null | null | null | // Copyright (C) 2022 Andreas Åkerberg
// This code is licensed under MIT license (see LICENSE for details)
#include "ModelLoader.h"
#include <filesystem>
namespace Forradia
{
void ModelLoader::LoadModels()
{
models.clear();
modelNames.clear();
auto file_path = std::string(SDL_GetBasePath());
file_path.append(modelsPath);
auto entries =
std::filesystem::recursive_directory_iterator(file_path.c_str());
for (auto& file : entries)
{
auto full_filename = file.path().filename().string();
auto filename = full_filename.substr(0, full_filename.find("."));
auto image_name_hash = int();
if (file.is_directory() ||
modelNameExtension !=
full_filename.substr(full_filename.length() -
modelNameExtension.length(),
modelNameExtension.length()))
continue;
Forradia::Model3D loaded_model;
loaded_model.LoadFile(file.path().string());
image_name_hash = GetId(filename);
models[image_name_hash] = loaded_model;
modelNames[image_name_hash] = filename;
}
}
bool ModelLoader::ModelExists(std::string ModelName) const
{
auto result = modelNames.count(GetId(ModelName)) > 0;
return result;
}
} // namespace Forradia
| 27.960784 | 77 | 0.592567 | eknah |
a7a1c8bead1ac0f903421739664b49597d79f6c8 | 2,375 | hpp | C++ | Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/relate/less.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | 24 | 2015-08-25T05:35:37.000Z | 2020-10-24T14:21:59.000Z | Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/relate/less.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | 97 | 2015-08-25T16:11:16.000Z | 2019-03-17T00:54:32.000Z | Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/relate/less.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | 9 | 2015-08-26T03:11:38.000Z | 2018-03-21T07:16:29.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
// This file was modified by Oracle on 2014.
// Modifications copyright (c) 2014, Oracle and/or its affiliates.
// Use, modification and distribution is subject to 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)
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_LESS_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_LESS_HPP
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/util/math.hpp>
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry
{
#ifndef DOXYGEN_NO_DISPATCH
namespace detail_dispatch { namespace relate {
// TODO: Integrate it with geometry::less?
template <typename Point1,
typename Point2,
std::size_t I = 0,
std::size_t D = geometry::dimension<Point1>::value>
struct less
{
static inline bool apply(Point1 const& left, Point2 const& right)
{
typename geometry::coordinate_type<Point1>::type
cleft = geometry::get<I>(left);
typename geometry::coordinate_type<Point2>::type
cright = geometry::get<I>(right);
if ( geometry::math::equals(cleft, cright) )
{
return less<Point1, Point2, I + 1, D>::apply(left, right);
}
else
{
return cleft < cright;
}
}
};
template <typename Point1, typename Point2, std::size_t D>
struct less<Point1, Point2, D, D>
{
static inline bool apply(Point1 const&, Point2 const&)
{
return false;
}
};
}} // namespace detail_dispatch::relate
#endif
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace relate {
struct less
{
template <typename Point1, typename Point2>
inline bool operator()(Point1 const& point1, Point2 const& point2) const
{
return detail_dispatch::relate::less<Point1, Point2>::apply(point1, point2);
}
};
}} // namespace detail::relate
#endif // DOXYGEN_NO_DETAIL
}} // namespace geofeatures_boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_LESS_HPP
| 28.27381 | 116 | 0.703158 | xarvey |
a7a4c1fb3c934cfdca240c5f94bac17dfc69a4cc | 1,432 | cpp | C++ | jsUnits/jsAxialStiffness.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsAxialStiffness.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsAxialStiffness.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 DNV AS
//
// 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 <jsUnits/jsAxialStiffness.h>
#include <jsUnits/jsUnitClass.h>
#include <Units/AxialStiffness.h>
#include "jsRotationalStiffnessPerUnitLength.h"
#include "jsCoupledStiffness.h"
#include "jsForce.h"
using namespace DNVS::MoFa::Units;
Runtime::DynamicPhenomenon jsAxialStiffness::GetPhenomenon()
{
return AxialStiffnessPhenomenon();
}
void jsAxialStiffness::init(jsTypeLibrary& typeLibrary)
{
jsUnitClass<jsAxialStiffness, AxialStiffness> cls(typeLibrary);
if (cls.reinit()) return;
cls.ImplicitConstructorConversion(&jsUnitClass<jsAxialStiffness, AxialStiffness>::ConstructEquivalentQuantity<jsRotationalStiffnessPerUnitLength>);
cls.ImplicitConstructorConversion(&jsUnitClass<jsAxialStiffness, AxialStiffness>::ConstructEquivalentQuantity<jsCoupledStiffness>);
cls.ImplicitConstructorConversion(&jsUnitClass<jsAxialStiffness, AxialStiffness>::ConstructEquivalentQuantity<jsForce>);
cls.ImplicitConstructorConversion([](const jsAxialStiffness& val) {return RotationalStiffnessPerUnitLength(val); });
cls.ImplicitConstructorConversion([](const jsAxialStiffness& val) {return CoupledStiffness(val); });
cls.ImplicitConstructorConversion([](const jsAxialStiffness& val) {return Force(val); });
}
| 42.117647 | 151 | 0.796788 | dnv-opensource |
a7a5eb60a38c574a2984a102cedb70ddd1f7d33a | 19,537 | cc | C++ | src/nameserver/logdb.cc | spiritbrother1/bfs | f3bb0ea70e8e2bda99df742e4c0b768f6a96d57c | [
"BSD-3-Clause"
] | null | null | null | src/nameserver/logdb.cc | spiritbrother1/bfs | f3bb0ea70e8e2bda99df742e4c0b768f6a96d57c | [
"BSD-3-Clause"
] | null | null | null | src/nameserver/logdb.cc | spiritbrother1/bfs | f3bb0ea70e8e2bda99df742e4c0b768f6a96d57c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <common/logging.h>
#include <common/string_util.h>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include "nameserver/logdb.h"
namespace baidu {
namespace bfs {
LogDB::LogDB() : thread_pool_(NULL), next_index_(0), smallest_index_(-1),
write_log_(NULL), write_index_(NULL), marker_log_(NULL) {}
LogDB::~LogDB() {
if (thread_pool_) {
thread_pool_->Stop(true);
}
if (write_log_) fclose(write_log_);
for (FileCache::iterator it = read_log_.begin(); it != read_log_.end(); ++it) {
fclose((it->second).first);
fclose((it->second).second);
}
if (write_index_) fclose(write_index_);
if (marker_log_) fclose(marker_log_);
}
void LogDB::Open(const std::string& path, const DBOption& option, LogDB** dbptr) {
*dbptr = NULL;
LogDB* logdb = new LogDB();
logdb->dbpath_ = path + "/";
logdb->snapshot_interval_ = option.snapshot_interval * 1000;
logdb->log_size_ = option.log_size << 20;
mkdir(logdb->dbpath_.c_str(), 0755);
if(!logdb->RecoverMarker()) {
LOG(WARNING, "[LogDB] RecoverMarker failed reason: %s", strerror(errno));
delete logdb;
return;
}
std::map<std::string, std::string>::iterator it = logdb->markers_.find(".smallest_index_");
if (it != logdb->markers_.end()) {
logdb->smallest_index_ = boost::lexical_cast<int64_t>(it->second);
}
if (!logdb->BuildFileCache()) {
LOG(WARNING, "[LogDB] BuildFileCache failed");
delete logdb;
return;
}
logdb->thread_pool_ = new ThreadPool(10);
logdb->WriteMarkerSnapshot();
*dbptr = logdb;
return;
}
StatusCode LogDB::Write(int64_t index, const std::string& entry) {
MutexLock lock(&mu_);
if (index != next_index_ && smallest_index_ != -1) {
LOG(INFO, "[LogDB] Write with invalid index = %ld smallest_index_ = %ld next_index_ = %ld ",
index, smallest_index_, next_index_);
return kBadParameter;
}
if (smallest_index_ == -1) { // empty db
StatusCode s = WriteMarkerNoLock(".smallest_index_", common::NumToString(index));
if (s != kOK) {
return s;
}
smallest_index_ = index;
LOG(INFO, "[LogDB] Set smallest_index_ to %ld ", smallest_index_);
}
uint32_t len = entry.length();
std::string data;
data.append(reinterpret_cast<char*>(&len), 4);
data.append(entry);
if (!write_log_) {
if (!NewWriteLog(index)) {
return kWriteError;
}
}
int64_t offset = ftell(write_log_);
if (offset > log_size_) {
if (!NewWriteLog(index)) {
return kWriteError;
}
offset = 0;
}
if (fwrite(data.c_str(), 1, data.length(), write_log_) != data.length() || fflush(write_log_) != 0) {
LOG(WARNING, "[LogDB] Write log %ld failed", index);
CloseCurrent();
return kWriteError;
}
if (fwrite(reinterpret_cast<char*>(&index), 1, 8, write_index_) != 8) {
LOG(WARNING, "[LogDB] Write index %ld failed", index);
CloseCurrent();
return kWriteError;
}
if (fwrite(reinterpret_cast<char*>(&offset), 1, 8, write_index_) != 8 || fflush(write_index_) != 0) {
LOG(WARNING, "[LogDB] Write index %ld failed", index);
CloseCurrent();
return kWriteError;
}
next_index_ = index + 1;
return kOK;
}
StatusCode LogDB::Read(int64_t index, std::string* entry) {
if (read_log_.empty() || index >= next_index_ || index < smallest_index_) {
return kNsNotFound;
}
FileCache::iterator it = read_log_.lower_bound(index);
if (it == read_log_.end() || (it != read_log_.begin() && index != it->first)) {
--it;
}
if (index < it->first) {
LOG(FATAL, "[LogDB] Read cannot find index file %ld ", index);
}
FILE* idx_fp = (it->second).first;
FILE* log_fp = (it->second).second;
// find entry offset
int offset = 16 * (index - it->first);
int64_t read_index = -1;
int64_t entry_offset = -1;
{
MutexLock lock(&mu_);
if (fseek(idx_fp, offset, SEEK_SET) != 0) {
LOG(FATAL, "[LogDB] Read cannot find index file %ld ", index);
}
StatusCode s = ReadIndex(idx_fp, index, &read_index, &entry_offset);
if (s != kOK) {
return s;
}
}
// read log entry
{
MutexLock lock(&mu_);
if(fseek(log_fp, entry_offset, SEEK_SET) != 0) {
LOG(WARNING, "[LogDB] Read %ld with invalid offset %ld ", index, entry_offset);
return kReadError;
}
int ret = ReadOne(log_fp, entry);
if (ret <= 0) {
LOG(WARNING, "[LogDB] Read log error %ld ", index);
return kReadError;
}
}
return kOK;
}
StatusCode LogDB::WriteMarkerNoLock(const std::string& key, const std::string& value) {
if (marker_log_ == NULL) {
marker_log_ = fopen((dbpath_ + "marker.mak").c_str(), "a");
if (marker_log_ == NULL) {
LOG(WARNING, "[LogDB] open marker.mak failed %s", strerror(errno));
return kWriteError;
}
}
std::string data;
uint32_t len = 4 + key.length() + 4 + value.length();
data.append(reinterpret_cast<char*>(&len), 4);
EncodeMarker(MarkerEntry(key, value), &data);
if (fwrite(data.c_str(), 1, data.length(), marker_log_) != data.length()
|| fflush(marker_log_) != 0) {
LOG(WARNING, "[LogDB] WriteMarker failed key = %s value = %s", key.c_str(), value.c_str());
return kWriteError;
}
fflush(marker_log_);
markers_[key] = value;
return kOK;
}
StatusCode LogDB::WriteMarker(const std::string& key, const std::string& value) {
MutexLock lock(&mu_);
return WriteMarkerNoLock(key, value);
}
StatusCode LogDB::WriteMarker(const std::string& key, int64_t value) {
return WriteMarker(key, std::string(reinterpret_cast<char*>(&value), 8));
}
StatusCode LogDB::ReadMarker(const std::string& key, std::string* value) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::iterator it = markers_.find(key);
if (it == markers_.end()) {
return kNsNotFound;
}
*value = it->second;
return kOK;
}
StatusCode LogDB::ReadMarker(const std::string& key, int64_t* value) {
std::string v;
StatusCode status = ReadMarker(key, &v);
if (status != kOK) {
return status;
}
memcpy(value, &(v[0]), 8);
return kOK;
}
StatusCode LogDB::GetLargestIdx(int64_t* value) {
MutexLock lock(&mu_);
if (smallest_index_ == next_index_) {
*value = -1;
return kNsNotFound;
}
*value = next_index_ - 1;
return kOK;
}
StatusCode LogDB::DeleteUpTo(int64_t index) {
if (index < smallest_index_) {
return kOK;
}
if (index >= next_index_) {
LOG(INFO, "[LogDB] DeleteUpTo over limit index = %ld next_index_ = %ld", index, next_index_);
return kBadParameter;
}
MutexLock lock(&mu_);
smallest_index_ = index + 1;
WriteMarkerNoLock(".smallest_index_", common::NumToString(smallest_index_));
FileCache::reverse_iterator upto = read_log_.rbegin();
while (upto != read_log_.rend()) {
if (upto->first <= index) break;
++upto;
}
if (upto == read_log_.rend()) {
return kOK;
}
int64_t upto_index = upto->first;
FileCache::iterator it = read_log_.begin();
while (it->first != upto_index) {
fclose((it->second).first);
fclose((it->second).second);
std::string log_name, idx_name;
FormLogName(it->first, &log_name, &idx_name);
remove(log_name.c_str());
remove(idx_name.c_str());
read_log_.erase(it++);
}
LOG(INFO, "[LogDB] DeleteUpTo done smallest_index_ = %ld next_index_ = %ld",
smallest_index_, next_index_);
return kOK;
}
StatusCode LogDB::DeleteFrom(int64_t index) {
if (index >= next_index_) {
return kOK;
}
if (index < smallest_index_) {
LOG(INFO, "[LogDB] DeleteUpTo over limit index = %ld smallest_index_ = %ld next_index_ = %ld",
index, smallest_index_, next_index_);
return kBadParameter;
}
MutexLock lock(&mu_);
FileCache::iterator from = read_log_.lower_bound(index);
bool need_truncate = index != from->first;
for (FileCache::iterator it = from; it != read_log_.end(); ++it) {
fclose((it->second).first);
fclose((it->second).second);
std::string log_name, idx_name;
FormLogName(it->first, &log_name, &idx_name);
remove(log_name.c_str());
remove(idx_name.c_str());
}
CloseCurrent();
// truancate the last log and open it for read
read_log_.erase(from, read_log_.end());
if (need_truncate && !read_log_.empty()) {
FileCache::reverse_iterator it = read_log_.rbegin();
int offset = 16 * (index - it->first);
fseek((it->second).first, offset, SEEK_SET);
char buf[16];
int len = fread(buf, 1, 16, (it->second).first);
assert(len == 16);
int64_t tmp_offset;
memcpy(&tmp_offset, buf + 8, 8);
fclose((it->second).first);
fclose((it->second).second);
std::string log_name, idx_name;
FormLogName(it->first, &log_name, &idx_name);
truncate(log_name.c_str(), tmp_offset);
truncate(idx_name.c_str(), offset);
(it->second).first = fopen(idx_name.c_str(), "r");
(it->second).second = fopen(log_name.c_str(), "r");
}
next_index_ = index;
LOG(INFO, "[LogDB] DeleteFrom done smallest_index_ = %ld next_index_ = %ld",
smallest_index_, next_index_);
return kOK;
}
bool LogDB::BuildFileCache() {
// build log file cache
struct dirent *entry = NULL;
DIR *dir_ptr = opendir(dbpath_.c_str());
if (dir_ptr == NULL) {
LOG(WARNING, "[LogDB] open dir failed %s", dbpath_.c_str());
return false;
}
bool error = false;
while ((entry = readdir(dir_ptr)) != NULL) {
size_t idx = std::string(entry->d_name).find(".idx");
if (idx != std::string::npos) {
std::string file_name = std::string(entry->d_name);
int64_t index = boost::lexical_cast<int64_t>(file_name.substr(0, idx));
std::string log_name, idx_name;
FormLogName(index, &log_name, &idx_name);
FILE* idx_fp = fopen(idx_name.c_str(), "r");
if (idx_fp == NULL) {
LOG(WARNING, "[LogDB] open index file failed %s", file_name.c_str());
error = true;
break;
}
FILE* log_fp = fopen(log_name.c_str(), "r");
if (log_fp == NULL) {
LOG(WARNING, "[LogDB] open log file failed %s", file_name.c_str());
fclose(idx_fp);
error = true;
break;
}
read_log_[index] = std::make_pair(idx_fp, log_fp);
LOG(INFO, "[LogDB] Add file cache %ld to %s ", index, file_name.c_str());
}
}
closedir(dir_ptr);
// check log & idx match, build largest index
if (error || !CheckLogIdx()) {
LOG(WARNING, "[LogDB] BuildFileCache failed error = %d", error);
for (FileCache::iterator it = read_log_.begin(); it != read_log_.end(); ++it) {
fclose((it->second).first);
fclose((it->second).second);
}
read_log_.clear();
return false;
}
return true;
}
bool LogDB::CheckLogIdx() {
if (read_log_.empty()) {
if (smallest_index_ == -1) {
next_index_ = 0;
} else {
next_index_ = smallest_index_;
}
LOG(INFO, "[LogDB] No previous log, next_index_ = %ld ", next_index_);
return true;
}
FileCache::iterator it = read_log_.begin();
if (smallest_index_ < it->first) {
LOG(WARNING, "[LogDB] log does not contain smallest_index_ %ld %ld",
smallest_index_, it->first);
return false;
}
next_index_ = it->first;
bool error = false;
for (; it != read_log_.end(); ++it) {
if (it->first != next_index_) {
LOG(WARNING, "[LogDB] log is not continous, current index %ld ", it->first);
return false;
}
FILE* idx = (it->second).first;
FILE* log = (it->second).second;
fseek(idx, 0, SEEK_END);
int idx_size = ftell(idx);
if (idx_size < 16) {
LOG(WARNING, "[LogDB] index file too small %ld ", it->first);
error = true;
break;
}
int reminder = idx_size % 16;
if (reminder != 0) {
LOG(INFO, "[LogDB] incomplete index file %ld.idx ", it->first);
}
fseek(idx, idx_size - 16 - reminder, SEEK_SET);
int64_t expect_index = it->first + (idx_size / 16) - 1;
int64_t read_index = -1;
int64_t offset = -1;
StatusCode s = ReadIndex(idx, expect_index, &read_index, &offset);
if (s != kOK) {
LOG(WARNING, "[LogDB] check index file failed %ld.idx %s",
it->first, StatusCode_Name(s).c_str());
return false;
}
fseek(log, 0, SEEK_END);
int log_size = ftell(log);
fseek(log, offset, SEEK_SET);
int len;
int ret = fread(&len, 1, 4, log);
if (ret < 4 || (offset + 4 + len > log_size)) {
LOG(WARNING, "[LogDB] incomplete log %ld ", it->first);
return false;
}
next_index_ = expect_index + 1;
}
if (error) {
if (++it != read_log_.end()) {
return false;
}
FileCache::reverse_iterator rit = read_log_.rbegin();
fclose((rit->second).first);
fclose((rit->second).second);
read_log_.erase(rit->first);
}
LOG(INFO, "[LogDB] Set next_index_ to %ld", next_index_);
return true;
}
bool LogDB::RecoverMarker() {
// recover markers
FILE* fp = fopen((dbpath_ + "marker.mak").c_str(), "r");
if (fp == NULL) {
if (errno == ENOENT) {
fp = fopen((dbpath_ + "marker.tmp").c_str(), "r");
}
}
if (fp == NULL) {
LOG(INFO, "[LogDB] No marker to recover");
return errno == ENOENT;
}
std::string data;
while (true) {
int ret = ReadOne(fp, &data);
if (ret == 0) break;
if (ret < 0) {
LOG(WARNING, "[LogDB] RecoverMarker failed while reading");
fclose(fp);
return false;
}
MarkerEntry mark;
DecodeMarker(data, &mark);
markers_[mark.key] = mark.value;
}
fclose(fp);
LOG(INFO, "[LogDB] Recover markers done");
rename((dbpath_ + "marker.tmp").c_str(), (dbpath_ + "marker.mak").c_str());
return true;
}
void LogDB::WriteMarkerSnapshot() {
MutexLock lock(&mu_);
FILE* fp = fopen((dbpath_ + "marker.tmp").c_str(), "w");
if (fp == NULL) {
LOG(WARNING, "[LogDB] open marker.tmp failed %s", strerror(errno));
return;
}
std::string data;
for (std::map<std::string, std::string>::iterator it = markers_.begin();
it != markers_.end(); ++it) {
MarkerEntry marker(it->first, it->second);
uint32_t len = 4 + (it->first).length() + 4 + (it->second).length();
data.clear();
data.append(reinterpret_cast<char*>(&len), 4);
EncodeMarker(marker, &data);
if (fwrite(data.c_str(), 1, data.length(), fp) != data.length() || fflush(fp) != 0) {
LOG(WARNING, "[LogDB] write marker.tmp failed %s", strerror(errno));
fclose(fp);
return;
}
}
fclose(fp);
if (marker_log_) {
fclose(marker_log_);
marker_log_ = NULL;
}
rename((dbpath_ + "marker.tmp").c_str(), (dbpath_ + "marker.mak").c_str());
marker_log_ = fopen((dbpath_ + "marker.mak").c_str(), "a");
if (marker_log_ == NULL) {
LOG(WARNING, "[LogDB] open marker.mak failed %s", strerror(errno));
return;
}
LOG(INFO, "[LogDB] WriteMarkerSnapshot done");
thread_pool_->DelayTask(snapshot_interval_, boost::bind(&LogDB::WriteMarkerSnapshot, this));
}
void LogDB::CloseCurrent() {
if (write_log_) {
fclose(write_log_);
write_log_ = NULL;
}
if (write_index_) {
fclose(write_index_);
write_index_ = NULL;
}
}
int LogDB::ReadOne(FILE* fp, std::string* data) {
int len;
int ret = fread(&len, 1, 4, fp);
if (ret == 0) {
return 0;
}
if (ret != 4) return -1;
char* buf = new char[len];
ret = fread(buf, 1, len, fp);
if (ret != len) {
LOG(WARNING, "Read(%d) return %d", len, ret);
delete[] buf;
return -1;
}
data->clear();
data->assign(buf, len);
delete[] buf;
return len;
}
StatusCode LogDB::ReadIndex(FILE* fp, int64_t expect_index, int64_t* index, int64_t* offset) {
char buf[16];
int ret = fread(buf, 1, 16, fp);
if (ret == 0) {
return kNsNotFound;
} else if (ret != 16) {
LOG(WARNING, "[logdb] Read index file error %ld", expect_index);
return kReadError;
}
memcpy(index, buf, 8);
memcpy(offset, buf + 8, 8);
if (expect_index != *index) {
LOG(WARNING, "[LogDB] Index file mismatch %ld ", index);
return kReadError;
}
return kOK;
}
void LogDB::EncodeMarker(const MarkerEntry& marker, std::string* data) {
int klen = (marker.key).length();
int vlen = (marker.value).length();
data->append(reinterpret_cast<char*>(&klen), 4);
data->append(marker.key);
data->append(reinterpret_cast<char*>(&vlen), 4);
data->append(marker.value);
}
void LogDB::DecodeMarker(const std::string& data, MarkerEntry* marker) { // data = klen + k + vlen + v
int klen;
memcpy(&klen, &(data[0]), 4);
(marker->key).assign(data.substr(4, klen));
int vlen;
memcpy(&vlen, &(data[4 + klen]), 4);
(marker->value).assign(data.substr(4 + klen + 4, vlen));
}
bool LogDB::NewWriteLog(int64_t index) {
if (write_log_) fclose(write_log_);
if (write_index_) fclose(write_index_);
std::string log_name, idx_name;
FormLogName(index, &log_name, &idx_name);
write_log_ = fopen(log_name.c_str(), "w");
write_index_ = fopen(idx_name.c_str(), "w");
FILE* idx_fp = fopen(idx_name.c_str(), "r");
FILE* log_fp = fopen(log_name.c_str(), "r");
if (!(write_log_ && write_index_ && idx_fp && log_fp)) {
if (write_log_) fclose(write_log_);
if (write_index_) fclose(write_index_);
if (idx_fp) fclose(idx_fp);
if (log_fp) fclose(log_fp);
LOG(WARNING, "[logdb] open log/idx file failed %ld %s", index, strerror(errno));
return false;
}
read_log_[index] = std::make_pair(idx_fp, log_fp);
return true;
}
void LogDB::FormLogName(int64_t index, std::string* log_name, std::string* idx_name) {
log_name->clear();
log_name->append(dbpath_);
log_name->append(common::NumToString(index));
log_name->append(".log");
idx_name->clear();
idx_name->append(dbpath_);
idx_name->append(common::NumToString(index));
idx_name->append(".idx");
}
} // namespace bfs
} // namespace baidu
| 33.282794 | 105 | 0.575472 | spiritbrother1 |
a7a67c688924f90044804c0d16a399b57e7b7da3 | 2,870 | cpp | C++ | FdogClient/traywidget.cpp | FdogMain/FdogInstantMessaging | 4d2e9a12d90dfc79a90d8367b373df8828578f06 | [
"Apache-2.0"
] | 35 | 2021-05-01T13:39:18.000Z | 2021-07-19T12:33:51.000Z | FdogClient/traywidget.cpp | BearStar0914/FdogInstantMessaging | 4d2e9a12d90dfc79a90d8367b373df8828578f06 | [
"Apache-2.0"
] | 2 | 2021-05-05T13:26:22.000Z | 2021-07-16T01:39:03.000Z | FdogClient/traywidget.cpp | BearStar0914/FdogInstantMessaging | 4d2e9a12d90dfc79a90d8367b373df8828578f06 | [
"Apache-2.0"
] | 8 | 2021-06-02T08:02:25.000Z | 2021-07-19T06:59:04.000Z | #include "traywidget.h"
#include "ui_traywidget.h"
#include<QDebug>
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
Traywidget::Traywidget(QString name,QWidget *parent) :
QWidget(parent),
ui(new Ui::Traywidget)
{
qDebug()<<"创1";
ui->setupUi(this);
this->setWindowFlags(Qt::SplashScreen|Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
ui->listWidget->setFrameShape(QListWidget::NoFrame);
ui->label->setText(name);
qDebug()<<"创1";
}
Traywidget::~Traywidget()
{
delete ui;
}
QString Traywidget::getName() const
{
return name;
}
void Traywidget::setName(const QString &value)
{
name = value;
ui->label->setText(name);
}
void Traywidget::setTrayWidgetItem(QPixmap pixmap,const QString &str,const QString &account)
{
qDebug()<<"消息1";
QFont font;
font.setFamily("Microsoft YaHei");
font.setPointSize(10);
//font.setBold(true);
font.setStyleStrategy(QFont::PreferAntialias);
QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
horLayout->setContentsMargins(0,0,0,0);
horLayout->setSpacing(0);
QPushButton * btn = new QPushButton();
btn->setIcon(pixmap);
QSize btnsize(25,25);
btn->setIconSize(btnsize);
btn->setFixedSize(26,26);
btn->setFlat(true);
QLabel * la = new QLabel(" "+str);
la->setFont(font);
horLayout->addWidget(btn);
horLayout->addWidget(la);
QWidget * widget = new QWidget(this);
widget->setObjectName(account);
widget->setLayout(horLayout);
QListWidgetItem * Listitem = new QListWidgetItem(ui->listWidget);
Listitem->setSizeHint(QSize(270, 26)); //每次改变Item的高度
ui->listWidget->setItemWidget(Listitem,widget);
ui->listWidget->setStyleSheet("QListWidget{color:gray;font-size:12px;background:#FAFAFD;}\
QScrollBar{width:0;height:0}");
//ui->listWidget->setFixedSize(270,26*(1));
//ui->listWidget->sortItems();
}
void Traywidget::deleteItem()
{
ui->listWidget->clear();
}
void Traywidget::paintEvent(QPaintEvent *e)
{
Q_UNUSED(e)
QPainter painter(this);
QPixmap pixmap(":/lib/background.png");//做好的图
qDrawBorderPixmap(&painter, this->rect(), QMargins(0, 0, 0, 0), pixmap);
QRect rect(this->rect().x()+8, this->rect().y()+8, this->rect().width()-16, this->rect().height()-16);
painter.fillRect(rect, QColor(255, 255, 255));
}
void Traywidget::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
//获得信息,包括头像,名字,账号,传给主界面
QWidget * widget = ui->listWidget->itemWidget(item);
//从消息池找到正确的消息
emit senddata3(widget->objectName());//获取正确的消息
//删除选中消息
ui->listWidget->removeItemWidget(item);
}
void Traywidget::on_pushButton_2_clicked()//查看全部
{
emit senddata();
}
void Traywidget::on_pushButton_clicked()//忽略全部
{
emit senddata2();
}
| 28.137255 | 110 | 0.673868 | FdogMain |
a7a6a89abceae5b06c3353dd51de6c2feaae471f | 189 | hpp | C++ | DARwIn OP/Controllers/ZeroPlayer-Teleoperado/teleoperado.hpp | 99Angelrm/Webots | 036ce182aa69f5fbecd358c179ac23fd9a1c91cd | [
"MIT"
] | null | null | null | DARwIn OP/Controllers/ZeroPlayer-Teleoperado/teleoperado.hpp | 99Angelrm/Webots | 036ce182aa69f5fbecd358c179ac23fd9a1c91cd | [
"MIT"
] | null | null | null | DARwIn OP/Controllers/ZeroPlayer-Teleoperado/teleoperado.hpp | 99Angelrm/Webots | 036ce182aa69f5fbecd358c179ac23fd9a1c91cd | [
"MIT"
] | null | null | null | #ifndef TELEOPERADO_HPP
#define TELEOPERADO_HPP
#include <webots/Robot.hpp>
#include "ZeroPlayer.hpp"
#define NMOTORS 20
namespace webots
{
class Joystick;
};
void teleoperado();
#endif | 17.181818 | 27 | 0.772487 | 99Angelrm |
a7a8d47d2a498de74055c2f748b17afe12ad34f7 | 2,202 | cpp | C++ | chrgfx/src/coldef.cpp | RyogaMasaki/chrgfx | f70d78b9742546d5f38246621e32c2c834cdaf0b | [
"MIT"
] | 9 | 2019-03-25T19:28:24.000Z | 2020-06-08T06:28:09.000Z | chrgfx/src/coldef.cpp | RyogaMasaki/gfx | f70d78b9742546d5f38246621e32c2c834cdaf0b | [
"MIT"
] | 1 | 2019-11-18T12:35:58.000Z | 2019-11-18T12:35:58.000Z | chrgfx/src/coldef.cpp | RyogaMasaki/gfx | f70d78b9742546d5f38246621e32c2c834cdaf0b | [
"MIT"
] | 2 | 2019-10-12T08:22:18.000Z | 2019-11-17T19:38:09.000Z | #include "coldef.hpp"
#include <string>
#include <vector>
namespace chrgfx
{
using namespace std;
using namespace png;
coldef::coldef(string const & id, coldef_type type, bool const big_endian,
string const & description) :
gfxdef(id, description),
m_type(type), m_big_endian(big_endian)
{
}
refcoldef::refcoldef(string const & id, palette const & reftab,
bool const big_endian, string const & description) :
coldef(id, ref, big_endian, description),
m_reftab(reftab) {};
color refcoldef::by_value(ushort index) const
{
return m_reftab[index];
};
ushort refcoldef::by_color(color rgb) const
{
size_t idx { 0 };
for(auto & this_color : m_reftab)
{
if(this_color.red == rgb.red && this_color.green == rgb.green &&
this_color.blue == rgb.blue)
{
return idx;
}
++idx;
}
// this could certainly use some tuning, but it mostly works
vector<pair<int, int>> distances;
distances.reserve(this->m_reftab.size());
int pal_color_iter { 0 };
for(const auto & this_color : this->m_reftab)
{
int this_distance = (abs(this_color.red - rgb.red)) +
(abs(this_color.green - rgb.green)) +
(abs(this_color.blue - rgb.blue));
distances.push_back(pair<int, int>(pal_color_iter, this_distance));
++pal_color_iter;
}
int dist_check { distances[0].second };
idx = 0;
for(const auto & this_entry : distances)
{
if(get<1>(this_entry) < dist_check)
{
dist_check = this_entry.second;
idx = this_entry.first;
}
}
return idx;
};
png::palette const & refcoldef::reftab() const
{
return m_reftab;
}
bool coldef::big_endian() const
{
return m_big_endian;
};
coldef_type coldef::type() const
{
return m_type;
}
rgbcoldef::rgbcoldef(string const & id, ushort const bitdepth,
vector<rgb_layout> const & layout, bool const big_endian,
string const & description) :
coldef(id, rgb, big_endian, description),
m_bitdepth(bitdepth), m_layout(layout) {};
vector<rgb_layout> const & rgbcoldef::layout() const
{
return m_layout;
};
rgb_layout const & rgbcoldef::rgb_pass(ushort pass) const
{
return m_layout[pass];
}
ushort rgbcoldef::bitdepth() const
{
return m_bitdepth;
};
} // namespace chrgfx
| 21.173077 | 74 | 0.686194 | RyogaMasaki |
a7a9aba9e9b818cd099105375a2fdeb4e198523d | 271 | cpp | C++ | Project/PepEngine/BurgerTime/SprayLeftCommand.cpp | PepijnVerhaert/PepEngine | 5a5dd4d78d8217d7109c2ea6990563ef583a0be4 | [
"MIT"
] | null | null | null | Project/PepEngine/BurgerTime/SprayLeftCommand.cpp | PepijnVerhaert/PepEngine | 5a5dd4d78d8217d7109c2ea6990563ef583a0be4 | [
"MIT"
] | null | null | null | Project/PepEngine/BurgerTime/SprayLeftCommand.cpp | PepijnVerhaert/PepEngine | 5a5dd4d78d8217d7109c2ea6990563ef583a0be4 | [
"MIT"
] | null | null | null | #include "SprayLeftCommand.h"
#include "Object.h"
#include "SprayPepperComponent.h"
SprayLeftCommand::SprayLeftCommand(pep::Object* pObject)
:BaseCommand(pObject)
{
}
void SprayLeftCommand::Execute()
{
GetActor()->GetComponent<SprayPepperComponent>()->SprayLeft();
}
| 19.357143 | 63 | 0.767528 | PepijnVerhaert |
a7aa64bbaaf81a50ce5187a54103f8fd0321ca40 | 10,319 | cpp | C++ | src/nyx/features/glszm.cpp | friskluft/nyx | 338fa587a358588dc1d01ce938864c69a391cb07 | [
"MIT"
] | 1 | 2021-09-09T18:57:23.000Z | 2021-09-09T18:57:23.000Z | src/nyx/features/glszm.cpp | friskluft/nyx | 338fa587a358588dc1d01ce938864c69a391cb07 | [
"MIT"
] | null | null | null | src/nyx/features/glszm.cpp | friskluft/nyx | 338fa587a358588dc1d01ce938864c69a391cb07 | [
"MIT"
] | 1 | 2021-09-17T14:51:21.000Z | 2021-09-17T14:51:21.000Z | #include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <unordered_set>
#include "glszm.h"
GLSZM_features::GLSZM_features (int minI, int maxI, const ImageMatrix& im)
{
//==== Check if the ROI is degenerate (equal intensity)
if (minI == maxI)
{
bad_roi_data = true;
return;
}
//==== Make a list of intensity clusters (zones)
using ACluster = std::pair<PixIntens, int>;
std::vector<ACluster> Z;
//==== While scanning clusters, learn unique intensities
std::unordered_set<PixIntens> U;
int maxZoneArea = 0;
// Copy the image matrix
auto M = im;
pixData& D = M.WriteablePixels();
//M.print("initial\n");
// Number of zones
const int VISITED = -1;
for (int row=0; row<M.height; row++)
for (int col = 0; col < M.width; col++)
{
// Find a non-blank pixel
auto pi = D(row, col);
if (pi == 0 || int(pi)==VISITED)
continue;
// Found a gray pixel. Find same-intensity neighbourhood of it.
std::vector<std::tuple<int, int>> history;
int x = col, y = row;
int zoneArea = 1;
D(y,x) = VISITED;
//
for(;;)
{
if (D.safe(y,x+1) && D(y,x+1) == pi)
{
D(y,x+1) = VISITED;
zoneArea++;
//M.print("After x+1,y");
// Remember this pixel
history.push_back({x,y});
// Advance
x = x + 1;
// Proceed
continue;
}
if (D.safe(y + 1, x + 1) && D(y + 1, x+1) == pi)
{
D(y + 1, x+1) = VISITED;
zoneArea++;
//M.print("After x+1,y+1");
history.push_back({ x,y });
x = x + 1;
y = y + 1;
continue;
}
if (D.safe(y + 1, x) && D(y + 1, x) == pi)
{
D(y + 1, x) = VISITED;
zoneArea++;
//M.print("After x,y+1");
history.push_back({ x,y });
y = y + 1;
continue;
}
if (D.safe(y + 1, x - 1) && D(y + 1, x-1) == pi)
{
D(y + 1, x-1) = VISITED;
zoneArea++;
//M.print("After x-1,y+1");
history.push_back({ x,y });
x = x - 1;
y = y + 1;
continue;
}
// Return from the branch
if (history.size() > 0)
{
// Recollect the coordinate where we diverted from
std::tuple<int, int> prev = history[history.size() - 1];
history.pop_back();
}
// We are done exploring this cluster
break;
}
// Done scanning a cluster. Perform 3 actions:
// --1
U.insert(pi);
// --2
maxZoneArea = std::max(maxZoneArea, zoneArea);
//std::stringstream ss;
//ss << "End of cluster " << x << "," << y;
//M.print (ss.str());
// --3
ACluster clu = {pi, zoneArea};
Z.push_back (clu);
}
//M.print("finished");
//==== Fill the SZ-matrix
Ng = (decltype(Ng)) U.size();
Ns = maxZoneArea;
Nz = (decltype(Nz)) Z.size();
Np = 1;
// --Set to vector to be able to know each intensity's index
std::vector<PixIntens> I (U.begin(), U.end());
std::sort (I.begin(), I.end()); // Optional
// --allocate the matrix
P.allocate (Ns, Ng);
// --iterate zones and fill the matrix
for (auto& z : Z)
{
// row
auto iter = std::find(I.begin(), I.end(), z.first);
int row = int (iter - I.begin());
// col
int col = z.second - 1; // 0-based => -1
auto & k = P(col, row);
k++;
}
}
// 1. Small Area Emphasis
double GLSZM_features::calc_SAE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i=1; i<=Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
f += P.matlab(i,j) / (j * j);
}
}
double retval = f / double(Nz);
return retval;
}
// 2. Large Area Emphasis
double GLSZM_features::calc_LAE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
f += P.matlab(i, j) * double (j * j);
}
}
double retval = f / double(Nz);
return retval;
}
// 3. Gray Level Non - Uniformity
double GLSZM_features::calc_GLN()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
double sum = 0.0;
for (int j = 1; j <= Ns; j++)
{
sum += P.matlab(i,j);
}
f += sum * sum;
}
double retval = f / double(Nz);
return retval;
}
// 4. Gray Level Non - Uniformity Normalized
double GLSZM_features::calc_GLNN()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
double sum = 0.0;
for (int j = 1; j <= Ns; j++)
{
sum += P.matlab(i,j);
}
f += sum * sum;
}
double retval = f / double(Nz * Nz);
return retval;
}
// 5. Size - Zone Non - Uniformity
double GLSZM_features::calc_SZN()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ns; i++)
{
double sum = 0.0;
for (int j = 1; j <= Ng; j++)
{
sum += P.matlab(j,i);
}
f += sum * sum;
}
double retval = f / double(Nz);
return retval;
}
// 6. Size - Zone Non - Uniformity Normalized
double GLSZM_features::calc_SZNN()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ns; i++)
{
double sum = 0.0;
for (int j = 1; j <= Ng; j++)
{
sum += P.matlab(j,i);
}
f += sum * sum;
}
double retval = f / double(Nz * Nz);
return retval;
}
// 7. Zone Percentage
double GLSZM_features::calc_ZP()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double retval = double(Nz) / double(Np);
return retval;
}
// 8. Gray Level Variance
double GLSZM_features::calc_GLV()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double mu = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
mu += P.matlab(i, j) * i;
}
}
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
double mu2 = (i - mu) * (i - mu);
f += P.matlab(i,j) * mu2;
}
}
return f;
}
// 9. Zone Variance
double GLSZM_features::calc_ZV()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double mu = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
mu += P.matlab(i,j) * double(j);
}
}
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
double mu2 = (j - mu) * (j - mu);
f += P.matlab(i, j) * mu2;
}
}
return f;
}
// 10. Zone Entropy
double GLSZM_features::calc_ZE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
double entrTerm = log2(P.matlab(i,j) + EPS);
f += P.matlab(i,j) * entrTerm;
}
}
double retval = -f;
return retval;
}
// 11. Low Gray Level Zone Emphasis
double GLSZM_features::calc_LGLZE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
f += P.matlab(i,j) / double(i*i);
}
}
double retval = f / double(Nz);
return retval;
}
// 12. High Gray Level Zone Emphasis
double GLSZM_features::calc_HGLZE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j <= Ns; j++)
{
f += P.matlab(i,j) * double(i*i);
}
}
double retval = f / double(Nz);
return retval;
}
// 13. Small Area Low Gray Level Emphasis
double GLSZM_features::calc_SALGLE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i <= Ng; i++)
{
for (int j = 1; j < Ns; j++)
{
f += P.matlab(i,j) / double(i * i * j * j);
}
}
double retval = f / double(Nz);
return retval;
}
// 14. Small Area High Gray Level Emphasis
double GLSZM_features::calc_SAHGLE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i < Ng; i++)
{
for (int j = 1; j < Ns; j++)
{
f += P.matlab(i,j) * double(i * i) / double(j * j);
}
}
double retval = f / double(Nz);
return retval;
}
// 15. Large Area Low Gray Level Emphasis
double GLSZM_features::calc_LALGLE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i < Ng; i++)
{
for (int j = 1; j < Ns; j++)
{
f += P.matlab(i,j) * double(j * j) / double(i * i);
}
}
double retval = f / double(Nz);
return retval;
}
// 16. Large Area High Gray Level Emphasis
double GLSZM_features::calc_LAHGLE()
{
// Prevent using bad data
if (bad_roi_data)
return BAD_ROI_FVAL;
double f = 0.0;
for (int i = 1; i < Ng; i++)
{
for (int j = 1; j < Ns; j++)
{
f += P.matlab(i,j) * double(i * i * j * j);
}
}
double retval = f / double(Nz);
return retval;
}
void GLSZM_features::reduce (size_t start, size_t end, std::vector<int>* ptrLabels, std::unordered_map <int, LR>* ptrLabelData)
{
for (auto i = start; i < end; i++)
{
int lab = (*ptrLabels)[i];
LR& r = (*ptrLabelData)[lab];
if (r.has_bad_data())
continue;
GLSZM_features glszm ((int)r.fvals[MIN][0], (int)r.fvals[MAX][0], r.aux_image_matrix);
r.fvals[GLSZM_SAE][0] = glszm.calc_SAE();
r.fvals[GLSZM_LAE][0] = glszm.calc_LAE();
r.fvals[GLSZM_GLN][0] = glszm.calc_GLN();
r.fvals[GLSZM_GLNN][0] = glszm.calc_GLNN();
r.fvals[GLSZM_SZN][0] = glszm.calc_SZN();
r.fvals[GLSZM_SZNN][0] = glszm.calc_SZNN();
r.fvals[GLSZM_ZP][0] = glszm.calc_ZP();
r.fvals[GLSZM_GLV][0] = glszm.calc_GLV();
r.fvals[GLSZM_ZV][0] = glszm.calc_ZV();
r.fvals[GLSZM_ZE][0] = glszm.calc_ZE();
r.fvals[GLSZM_LGLZE][0] = glszm.calc_LGLZE();
r.fvals[GLSZM_HGLZE][0] = glszm.calc_HGLZE();
r.fvals[GLSZM_SALGLE][0] = glszm.calc_SALGLE();
r.fvals[GLSZM_SAHGLE][0] = glszm.calc_SAHGLE();
r.fvals[GLSZM_LALGLE][0] = glszm.calc_LALGLE();
r.fvals[GLSZM_LAHGLE][0] = glszm.calc_LAHGLE();
}
}
| 20.075875 | 128 | 0.538424 | friskluft |
a7aaf8cfe05a5bd0598bed7b56a8e10879f1d88a | 1,718 | cpp | C++ | tests/gl.cpp | Toefinder/gepetto-viewer | 5163a81991dafed7dda7a4268baa3512f2cedb78 | [
"BSD-2-Clause"
] | 18 | 2019-02-09T08:38:36.000Z | 2022-02-19T13:22:04.000Z | tests/gl.cpp | Toefinder/gepetto-viewer | 5163a81991dafed7dda7a4268baa3512f2cedb78 | [
"BSD-2-Clause"
] | 67 | 2018-10-12T13:52:04.000Z | 2022-03-16T11:25:06.000Z | tests/gl.cpp | Toefinder/gepetto-viewer | 5163a81991dafed7dda7a4268baa3512f2cedb78 | [
"BSD-2-Clause"
] | 8 | 2019-05-06T11:14:43.000Z | 2022-02-07T15:32:28.000Z | #include <iostream>
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#endif
#include <osgViewer/Viewer>
#include <osg/GLExtensions>
const int OSG_WIDTH = 1024;
const int OSG_HEIGHT = 960;
class TestSupportOperation : public osg::GraphicsOperation
{
public:
TestSupportOperation()
: osg::Referenced(true)
, osg::GraphicsOperation("TestSupportOperation", false)
, m_supported(true)
, m_errorMsg()
, m_version(1.3)
{}
virtual void operator() (osg::GraphicsContext* gc)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(m_mutex);
osg::GLExtensions* gl2ext = gc->getState()->get<osg::GLExtensions>();
if( gl2ext ){
if( !gl2ext->isGlslSupported )
{
m_supported = false;
m_errorMsg = "ERROR: GLSL not supported by OpenGL driver.";
}
else
m_version = gl2ext->glVersion;
}
else{
m_supported = false;
m_errorMsg = "ERROR: GLSL not supported.";
}
}
OpenThreads::Mutex m_mutex;
bool m_supported;
std::string m_errorMsg;
float m_version;
};
int main(int, char**)
{
#ifdef _WIN32
::SetProcessDPIAware();
#endif
osgViewer::Viewer viewer;
viewer.setUpViewInWindow(100,100,OSG_WIDTH, OSG_HEIGHT);
// openGL version:
osg::ref_ptr<TestSupportOperation> so = new TestSupportOperation;
viewer.setRealizeOperation(so.get());
viewer.realize();
if (so->m_supported)
std::cout << "GLVersion=" << so->m_version << std::endl;
else
std::cout << so->m_errorMsg << std::endl;
return viewer.run();
}
| 23.534247 | 77 | 0.593714 | Toefinder |
a7b379cfc8620d65fdd839931aee24c75dbd2c9e | 2,817 | cpp | C++ | test/selene/img/interop/ImageToDynImage.cpp | kmhofmann/selene | 11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb | [
"MIT"
] | 284 | 2017-11-20T08:23:54.000Z | 2022-03-30T12:52:00.000Z | test/selene/img/interop/ImageToDynImage.cpp | kmhofmann/selene | 11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb | [
"MIT"
] | 9 | 2018-02-14T08:21:41.000Z | 2021-07-27T19:52:12.000Z | test/selene/img/interop/ImageToDynImage.cpp | kmhofmann/selene | 11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb | [
"MIT"
] | 17 | 2018-03-10T00:01:36.000Z | 2021-06-29T10:44:27.000Z | // This file is part of the `Selene` library.
// Copyright 2017-2019 Michael Hofmann (https://github.com/kmhofmann).
// Distributed under MIT license. See accompanying LICENSE file in the top-level directory.
#include <catch2/catch.hpp>
#include <selene/img/interop/ImageToDynImage.hpp>
#include <selene/img/pixel/PixelTypeAliases.hpp>
#include <selene/img/typed/ImageTypeAliases.hpp>
using namespace sln::literals;
namespace {
template <typename PixelType>
struct PixelProducer;
template <typename T>
struct PixelProducer<sln::Pixel<T, 1>>
{
static sln::Pixel<T, 1> get(sln::PixelIndex x, sln::PixelIndex y)
{
return sln::Pixel<T, 1>(x + y);
}
};
template <typename T>
struct PixelProducer<sln::Pixel<T, 2>>
{
static sln::Pixel<T, 2> get(sln::PixelIndex x, sln::PixelIndex y)
{
return sln::Pixel<T, 2>(x + y, 2 * x + y);
}
};
template <typename T>
struct PixelProducer<sln::Pixel<T, 3>>
{
static sln::Pixel<T, 3> get(sln::PixelIndex x, sln::PixelIndex y)
{
return sln::Pixel<T, 3>(x + y, 2 * x + y, x + 2 * y);
}
};
template <typename T>
struct PixelProducer<sln::Pixel<T, 4>>
{
static sln::Pixel<T, 4> get(sln::PixelIndex x, sln::PixelIndex y)
{
return sln::Pixel<T, 4>(x + y, 2 * x + y, x + 2 * y, 2 * x + 2 * y);
}
};
template <typename PixelType>
sln::Image<PixelType> create_test_image(sln::PixelLength width, sln::PixelLength height)
{
sln::Image<PixelType> img({width, height});
for (auto y = 0_idx; y < img.height(); ++y)
{
for (auto x = 0_idx; x < img.width(); ++x)
{
img(x, y) = PixelProducer<PixelType>::get(x, y);
}
}
return img;
}
template <typename PixelType>
void test_image(sln::PixelLength width, sln::PixelLength height)
{
auto img = create_test_image<PixelType>(width, height);
auto img_data_view = sln::to_dyn_image_view(img, sln::PixelFormat::Unknown);
REQUIRE(img_data_view.width() == width);
REQUIRE(img_data_view.height() == height);
REQUIRE(img_data_view.is_packed());
REQUIRE(img_data_view.is_valid());
// TODO: Content tests
// ...
auto img_data = sln::to_dyn_image(std::move(img), sln::PixelFormat::Unknown);
REQUIRE(img_data.width() == width);
REQUIRE(img_data.height() == height);
REQUIRE(img_data.is_packed());
REQUIRE(img_data.is_valid());
// TODO: Content tests
// ...
}
} // namespace
TEST_CASE("Typed image to dynamic image", "[img]")
{
{
sln::Image_8u1 img;
sln::DynImage<> dyn_img;
REQUIRE_THROWS(dyn_img = sln::to_dyn_image(std::move(img), sln::PixelFormat::Unknown));
}
for (auto w = 1_px; w < 32_px; w += 1_px)
{
for (auto h = 1_px; h < 32_px; h += 1_px)
{
test_image<sln::Pixel_8u1>(w, h);
test_image<sln::Pixel_8u2>(w, h);
test_image<sln::Pixel_8u3>(w, h);
test_image<sln::Pixel_8u4>(w, h);
}
}
}
| 24.495652 | 91 | 0.652467 | kmhofmann |
a7b3a6eb2aa64050eedeabf66a27382e43ac24cc | 28,004 | cpp | C++ | test/test.cpp | AmonShokhinAhmed/TattleTale | b3ec96ca7831d38f2cce88f1ef02f351d9f8547f | [
"MIT"
] | 1 | 2022-03-22T16:17:45.000Z | 2022-03-22T16:17:45.000Z | test/test.cpp | AmonShokhinAhmed/TattleTale | b3ec96ca7831d38f2cce88f1ef02f351d9f8547f | [
"MIT"
] | 88 | 2022-01-31T09:16:19.000Z | 2022-03-29T19:30:50.000Z | test/test.cpp | AmonShokhinAhmed/TattleTale | b3ec96ca7831d38f2cce88f1ef02f351d9f8547f | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <memory>
#include "tale/tale.hpp"
#include <time.h>
#define GTEST_INFO std::cout << "[ INFO ] "
using namespace tattletale;
TEST(TaleKernels, IncreasingKernelId)
{
Random random;
Chronicle chronicle(random);
std::vector<Kernel *> no_reasons;
size_t tick = 0;
Setting setting;
setting.actor_count = 0;
setting.days_to_simulate = 0;
School school(chronicle, random, setting);
chronicle.Reset();
Actor *actor = chronicle.CreateActor(school, "John", "Doe");
Emotion *emotion = chronicle.CreateEmotion(EmotionType::kHappy, tick, actor, no_reasons, 1);
Goal *goal = chronicle.CreateGoal(Goal::GetRandomGoalType(random), tick, actor, no_reasons);
Relationship *relationship = chronicle.CreateRelationship(RelationshipType::kLove, tick, actor, actor, no_reasons, 1);
Resource *wealth = chronicle.CreateResource("wealth", "wealthy", "poor", tick, actor, no_reasons, 1);
EXPECT_EQ(0, emotion->id_);
EXPECT_EQ(1, goal->id_);
EXPECT_EQ(2, relationship->id_);
EXPECT_EQ(3, wealth->id_);
}
class TaleCreateAndRunSchool : public ::testing::Test
{
protected:
TaleCreateAndRunSchool() {}
virtual ~TaleCreateAndRunSchool() {}
void SetUp(const Setting &setting)
{
Random random;
Chronicle chronicle(random);
School school(chronicle, random, setting);
for (size_t i = 0; i < setting.actor_count; ++i)
{
EXPECT_EQ(school.GetActor(i)->id_, i);
}
for (size_t i = 0; i < setting.course_count(); ++i)
{
EXPECT_EQ(school.GetCourse(i).id_, i);
}
school.SimulateDays(setting.days_to_simulate);
}
virtual void TearDown() {}
};
TEST_F(TaleCreateAndRunSchool, CreateAndRunDefaultSchool)
{
Setting setting;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroActors)
{
Setting setting;
setting.actor_count = 0;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroActorsPerCourse)
{
Setting setting;
setting.actors_per_course = 0;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroCoursesPerDay)
{
Setting setting;
setting.courses_per_day = 0;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroSameCoursesPerWeek)
{
Setting setting;
setting.same_course_per_week = 0;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroFreetimeActorCount)
{
Setting setting;
setting.freetime_actor_count = 0;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroInAllSettings)
{
Setting setting;
setting.actor_count = 0;
setting.actors_per_course = 0;
setting.courses_per_day = 0;
setting.same_course_per_week = 0;
setting.freetime_actor_count = 0;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneActor)
{
Setting setting;
setting.actor_count = 1;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneActorPerCourse)
{
Setting setting;
setting.actors_per_course = 1;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneCoursePerDay)
{
Setting setting;
setting.courses_per_day = 1;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneFreetimeActorCount)
{
Setting setting;
setting.freetime_actor_count = 1;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneSameCoursePerWeek)
{
Setting setting;
setting.same_course_per_week = 1;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneInAllSettings)
{
Setting setting;
setting.actor_count = 1;
setting.actors_per_course = 1;
setting.courses_per_day = 1;
setting.same_course_per_week = 1;
setting.freetime_actor_count = 1;
SetUp(setting);
}
TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithRandomValuesInAllSettings)
{
uint32_t seconds = static_cast<uint32_t>(time(NULL));
Random random(seconds);
Setting setting;
setting.actor_count = random.GetUInt(0, 1000);
setting.actors_per_course = random.GetUInt(0, 50);
setting.courses_per_day = random.GetUInt(0, 10);
setting.same_course_per_week = random.GetUInt(0, 10);
setting.days_to_simulate = random.GetUInt(0, 50);
setting.freetime_actor_count = random.GetUInt(0, 30);
GTEST_INFO << "Actor Count = " << setting.actor_count << std::endl;
GTEST_INFO << "Actors per Course = " << setting.actors_per_course << std::endl;
GTEST_INFO << "Courses per Day = " << setting.courses_per_day << std::endl;
GTEST_INFO << "Same Course per Week = " << setting.same_course_per_week << std::endl;
GTEST_INFO << "Days to Simulate = " << setting.days_to_simulate << std::endl;
SetUp(setting);
}
TEST(TaleExtraSchoolTests, CorrectCurrentDayAfterSimulation)
{
Setting setting;
setting.actor_count = 10;
setting.days_to_simulate = 5;
Random random;
Chronicle chronicle(random);
chronicle.Reset();
School school(chronicle, random, setting);
school.SimulateDays(setting.days_to_simulate);
EXPECT_EQ(school.GetCurrentDay(), 5);
EXPECT_EQ(school.GetCurrentWeekday(), Weekday::Saturday);
}
TEST(TaleExtraSchoolTests, InitializedRelationshipsAtStart)
{
Setting setting;
setting.actor_count = 100;
setting.desired_min_start_relationships_count = 4;
setting.desired_max_start_relationships_count = 12;
Random random;
Chronicle chronicle(random);
chronicle.Reset();
School school(chronicle, random, setting);
for (size_t i = 0; i < setting.actor_count; ++i)
{
auto a = school.GetActor(i);
for (auto &b : a->GetAllKnownActors())
{
EXPECT_NE(a->CalculateRelationshipStrength(b->id_), 0);
EXPECT_NE(b->CalculateRelationshipStrength(a->id_), 0);
}
}
}
TEST(TaleInteractions, CreateRandomInteractionFromStore)
{
Random random;
Setting setting;
Chronicle chronicle(random);
InteractionStore interaction_store(random);
size_t interaction_index = interaction_store.GetRandomInteractionPrototypeIndex();
size_t participant_count = interaction_store.GetParticipantCount(interaction_index);
chronicle.Reset();
setting.actor_count = participant_count;
School school(chronicle, random, setting);
std::vector<Actor *> participants;
for (size_t i = 0; i < participant_count; ++i)
{
participants.push_back(school.GetActor(i));
}
size_t tick = 0;
std::vector<Kernel *> no_reasons;
Interaction *interaction = interaction_store.CreateInteraction(chronicle, interaction_index, 1.0f, tick, no_reasons, participants);
EXPECT_EQ(interaction->name_, interaction_store.GetInteractionName(interaction_index));
EXPECT_EQ(interaction->tick_, tick);
EXPECT_EQ(interaction->GetAllParticipants().size(), participant_count);
for (size_t i = 0; i < participant_count; ++i)
{
EXPECT_EQ(interaction->GetAllParticipants()[i], school.GetActor(i));
}
for (size_t i = 0; i < interaction->GetPrototype()->wealth_effects.size(); ++i)
{
EXPECT_EQ(interaction->GetPrototype()->wealth_effects[i], interaction_store.GetWealthEffects(interaction_index)[i]);
}
for (size_t i = 0; i < interaction->GetPrototype()->emotion_effects.size(); ++i)
{
for (size_t j = 0; j < interaction->GetPrototype()->emotion_effects[i].size(); ++j)
{
EXPECT_EQ(interaction->GetPrototype()->emotion_effects[i][j], interaction_store.GetEmotionEffects(interaction_index)[i][j]);
}
}
for (size_t i = 0; i < interaction->GetPrototype()->relationship_effects.size(); ++i)
{
for (auto &[participant, vector] : interaction->GetPrototype()->relationship_effects[i])
{
for (size_t j = 0; j < vector.size(); ++j)
{
EXPECT_EQ(vector[j], interaction_store.GetRelationshipEffects(interaction_index)[i].at(participant)[j]);
}
}
}
}
TEST(TaleInteractions, ApplyInteraction)
{
size_t tick = 0;
std::vector<Kernel *> no_reasons;
Random random;
size_t participant_count = 2;
Setting setting;
setting.actor_count = participant_count;
Chronicle chronicle(random);
School school(chronicle, random, setting);
std::vector<Actor *> participants;
participants.push_back(school.GetActor(0));
participants.push_back(school.GetActor(1));
std::vector<float> wealth_effects;
std::vector<std::vector<float>> emotion_effects;
std::vector<robin_hood::unordered_map<size_t, std::vector<float>>> relationship_effects;
std::vector<float> expected_wealth_values;
std::vector<std::vector<float>> expected_emotion_values;
std::vector<robin_hood::unordered_map<size_t, std::vector<float>>> expected_relationship_values;
std::vector<float> signs = {1.0f, -1.0f};
for (size_t participant_index = 0; participant_index < 2; ++participant_index)
{
float sign = signs[participant_index];
wealth_effects.push_back(0.5f * sign);
expected_wealth_values.push_back(0.5f * sign + school.GetActor(participant_index)->wealth_->GetValue());
std::vector<float> emotion_vector(static_cast<int>(EmotionType::kLast), 0.0f);
std::vector<float> expected_emotion_values_vector(static_cast<int>(EmotionType::kLast), 0.0f);
for (int type_index = 0; type_index < emotion_vector.size(); ++type_index)
{
emotion_vector[type_index] = type_index * 0.1f * sign;
expected_emotion_values_vector[type_index] = type_index * 0.1f * sign + school.GetActor(participant_index)->emotions_[type_index]->GetValue();
}
emotion_effects.push_back(emotion_vector);
expected_emotion_values.push_back(expected_emotion_values_vector);
std::vector<float> relationship_vector(static_cast<int>(RelationshipType::kLast), 0.0f);
std::vector<float> expected_relationship_values_vector(static_cast<int>(RelationshipType::kLast), 0.0f);
size_t other_participant = (participant_index == 0 ? 1 : 0);
for (int type_index = 0; type_index < relationship_vector.size(); ++type_index)
{
relationship_vector[type_index] = type_index * 0.1f * sign;
float existing_value = 0;
Actor *actor = school.GetActor(participant_index);
if (actor->relationships_.count(other_participant))
{
std::vector<Relationship *> existing_map = actor->relationships_.at(other_participant);
existing_value = existing_map[type_index]->GetValue();
}
expected_relationship_values_vector[type_index] = existing_value + type_index * 0.1f * sign;
}
robin_hood::unordered_map<size_t, std::vector<float>> participant_relationship_map = {{other_participant, relationship_vector}};
robin_hood::unordered_map<size_t, std::vector<float>> expected_participant_relationship_map = {{other_participant, expected_relationship_values_vector}};
relationship_effects.push_back(participant_relationship_map);
expected_relationship_values.push_back(expected_participant_relationship_map);
}
std::shared_ptr<InteractionPrototype> prototype(new InteractionPrototype());
prototype->name = "Test";
prototype->wealth_effects = wealth_effects;
prototype->emotion_effects = emotion_effects;
prototype->relationship_effects = relationship_effects;
std::shared_ptr<InteractionRequirement> requirement(new InteractionRequirement());
std::shared_ptr<InteractionTendency> tendency(new InteractionTendency());
Interaction *interaction = chronicle.CreateInteraction(prototype, requirement, tendency, 1.0f, tick, no_reasons, participants);
interaction->Apply();
for (size_t participant_index = 0; participant_index < participant_count; ++participant_index)
{
EXPECT_EQ(school.GetActor(participant_index)->wealth_->GetValue(), std::clamp(expected_wealth_values[participant_index], -1.0f, 1.0f));
for (size_t type_index = 0; type_index < expected_emotion_values[participant_index].size(); ++type_index)
{
EXPECT_EQ(school.GetActor(participant_index)->emotions_[type_index]->GetValue(), std::clamp(expected_emotion_values[participant_index][type_index], -1.0f, 1.0f));
}
for (auto &[other_participant_index, vector] : expected_relationship_values[participant_index])
{
for (size_t type_index = 0; type_index < vector.size(); ++type_index)
{
EXPECT_EQ(school.GetActor(participant_index)->relationships_[other_participant_index][type_index]->GetValue(), std::clamp(vector[type_index], -1.0f, 1.0f));
}
}
}
}
TEST(TaleInteractions, InteractionBecomesReason)
{
size_t tick = 0;
Random random;
size_t participant_count = 2;
Setting setting;
setting.desired_min_start_relationships_count = 0;
setting.desired_max_start_relationships_count = 0;
setting.actor_count = participant_count;
Chronicle chronicle(random);
School school(chronicle, random, setting);
std::vector<Actor *> participants;
participants.push_back(school.GetActor(0));
participants.push_back(school.GetActor(1));
std::vector<float> wealth_effects;
std::vector<std::vector<float>> emotion_effects;
std::vector<robin_hood::unordered_map<size_t, std::vector<float>>> relationship_effects;
for (size_t participant_index = 0; participant_index < participant_count; ++participant_index)
{
wealth_effects.push_back(0.1f);
std::vector<float> emotion_vector(static_cast<int>(EmotionType::kLast), 0.1f);
emotion_effects.push_back(emotion_vector);
std::vector<float> relationship_vector(static_cast<int>(RelationshipType::kLast), 0.1f);
size_t other_participant = (participant_index == 0 ? 1 : 0);
robin_hood::unordered_map<size_t, std::vector<float>> participant_relationship_map = {{other_participant, relationship_vector}};
relationship_effects.push_back(participant_relationship_map);
}
std::shared_ptr<InteractionPrototype> prototype(new InteractionPrototype());
prototype->name = "InteractionBecomesReason";
prototype->wealth_effects = wealth_effects;
prototype->emotion_effects = emotion_effects;
prototype->relationship_effects = relationship_effects;
prototype->description = "{} did test interaction with {}";
std::shared_ptr<InteractionRequirement> requirement(new InteractionRequirement());
requirement->SetParticipantCount(participant_count);
std::shared_ptr<InteractionTendency> tendency(new InteractionTendency());
std::vector<Kernel *> no_reasons;
Interaction *interaction = chronicle.CreateInteraction(prototype, requirement, tendency, 1.0f, tick, no_reasons, participants);
interaction->Apply();
for (size_t participant_index = 0; participant_index < participant_count; ++participant_index)
{
EXPECT_EQ(school.GetActor(participant_index)->wealth_->GetReasons()[0]->name_, prototype->name);
EXPECT_EQ(school.GetActor(participant_index)->wealth_->GetReasons()[0]->id_, interaction->id_);
for (int type_index = 0; type_index < static_cast<int>(EmotionType::kLast); ++type_index)
{
EXPECT_EQ(school.GetActor(participant_index)->emotions_[type_index]->GetReasons()[0]->name_, prototype->name);
EXPECT_EQ(school.GetActor(participant_index)->emotions_[type_index]->GetReasons()[0]->id_, interaction->id_);
}
for (auto &[other_participant, vector] : school.GetActor(participant_index)->relationships_)
{
for (int type_index = 0; type_index < static_cast<int>(EmotionType::kLast); ++type_index)
{
EXPECT_EQ(vector[type_index]->GetReasons()[0]->name_, prototype->name);
EXPECT_EQ(vector[type_index]->GetReasons()[0]->id_, interaction->id_);
}
}
}
}
TEST(TaleCourse, CreateCourse)
{
Setting setting;
Random random;
Course course(random, setting, 0, "Test");
EXPECT_EQ(course.GetSlotCount(), setting.slot_count_per_week());
}
TEST(TaleCourse, AddGroupsToSlot)
{
Setting setting;
Random random;
Course course(random, setting, 0, "Test");
setting.actor_count = 0;
Chronicle chronicle(random);
School school(chronicle, random, setting);
std::vector<Actor *> actors;
for (size_t slot = 0; slot < course.GetSlotCount(); ++slot)
{
std::list<Actor *> course_group;
Actor *actor = chronicle.CreateActor(school, "John", "Doe");
actors.push_back(actor);
course_group.push_back(actor);
course.AddToSlot(course_group, slot);
EXPECT_EQ((*course.GetCourseGroupForSlot(slot).begin())->id_, slot);
}
for (size_t slot = 0; slot < course.GetSlotCount(); ++slot)
{
EXPECT_EQ((*course.GetCourseGroupForSlot(slot).begin())->id_, slot);
}
}
TEST(TaleCourse, AreAllSlotsFilled)
{
Setting setting;
Random random;
Course course(random, setting, 0, "Test");
setting.actor_count = 0;
Chronicle chronicle(random);
School school(chronicle, random, setting);
EXPECT_FALSE(course.AllSlotsFilled());
for (size_t slot = 0; slot < setting.slot_count_per_week() - 1; ++slot)
{
std::list<Actor *> course_group;
for (size_t actor_index = 0; actor_index < setting.actors_per_course; ++actor_index)
{
Actor *actor = chronicle.CreateActor(school, "John", "Doe");
course_group.push_back(actor);
}
course.AddToSlot(course_group, slot);
EXPECT_FALSE(course.AllSlotsFilled());
}
std::list<Actor *> course_group;
for (size_t actor_index = 0; actor_index < setting.actors_per_course; ++actor_index)
{
Actor *actor = chronicle.CreateActor(school, "John", "Doe");
course_group.push_back(actor);
}
course.AddToSlot(course_group, setting.slot_count_per_week() - 1);
EXPECT_TRUE(course.AllSlotsFilled());
}
TEST(TaleCourse, GetRandomCourseSlot)
{
Setting setting;
uint32_t seconds = static_cast<uint32_t>(time(NULL));
Random random(seconds);
setting.actor_count = 300;
setting.actors_per_course = 30;
setting.courses_per_day = 6;
setting.same_course_per_week = 4;
Course course(random, setting, 0, "Test");
setting.actor_count = 0;
Chronicle chronicle(random);
School school(chronicle, random, setting);
std::vector<uint32_t> random_filled_slots;
for (size_t i = 0; i < setting.slot_count_per_week() / 2; ++i)
{
uint32_t random_slot = random.GetUInt(0, static_cast<uint32_t>(setting.slot_count_per_week() - 1));
while (std::count(random_filled_slots.begin(), random_filled_slots.end(), random_slot))
{
++random_slot;
random_slot %= setting.slot_count_per_week();
}
random_filled_slots.push_back(random_slot);
}
for (size_t i = 0; i < random_filled_slots.size(); ++i)
{
std::list<Actor *> course_group;
Actor *actor = chronicle.CreateActor(school, "John", "Doe");
course_group.push_back(actor);
course.AddToSlot(course_group, random_filled_slots[i]);
}
size_t tries = 10000;
for (size_t i = 0; i < tries; ++i)
{
uint32_t random_empty_slot = course.GetRandomEmptySlot();
for (size_t j = 0; j < random_filled_slots.size(); ++j)
{
EXPECT_NE(random_empty_slot, random_filled_slots[j]);
}
}
}
class TaleActor : public ::testing::Test
{
protected:
std::string actor_first_name_ = "John";
std::string actor_last_name_ = "Doe";
uint32_t desired_min_start_relationships_count_ = 1;
uint32_t desired_max_start_relationships_count_ = 8;
Actor *actor_;
Setting setting_;
School *school_;
Random random_;
Chronicle chronicle_;
TaleActor() : random_(), chronicle_(random_)
{
setting_.actor_count = 10;
setting_.desired_min_start_relationships_count = desired_min_start_relationships_count_;
setting_.desired_max_start_relationships_count = desired_max_start_relationships_count_;
school_ = new School(chronicle_, random_, setting_);
actor_ = chronicle_.CreateActor(*school_, actor_first_name_, actor_last_name_);
actor_->SetupRandomValues(0);
}
virtual ~TaleActor() {}
void SetUp() {}
virtual void TearDown() {}
};
TEST_F(TaleActor, CreateActor)
{
EXPECT_EQ(actor_->first_name_, actor_first_name_);
EXPECT_EQ(actor_->last_name_, actor_last_name_);
EXPECT_EQ(actor_->id_, setting_.actor_count);
}
TEST_F(TaleActor, ActorHasInitializedStartingValues)
{
EXPECT_TRUE(actor_->wealth_);
EXPECT_NE(actor_->emotions_.size(), 0);
GTEST_INFO << "Relationship Size: " << actor_->relationships_.size() << "\n";
EXPECT_LE(actor_->relationships_.size(), setting_.max_start_relationships_count());
}
TEST_F(TaleActor, AddActorToCourse)
{
size_t course_id = 5;
Course course(school_->GetRandom(), setting_, course_id, "Test");
std::list<Actor *> course_group;
std::vector<uint32_t> slots_to_check;
course_group.push_back(actor_);
EXPECT_FALSE(actor_->IsEnrolledInCourse(course_id));
EXPECT_EQ(actor_->GetFilledSlotsCount(), 0);
for (uint32_t i = 0; i < setting_.slot_count_per_week(); ++i)
{
slots_to_check.push_back(i);
EXPECT_TRUE(actor_->SlotsEmpty(slots_to_check));
}
for (size_t i = 0; i < setting_.slot_count_per_week(); ++i)
{
EXPECT_FALSE(actor_->AllSlotsFilled());
course.AddToSlot(course_group, i);
EXPECT_EQ(actor_->GetFilledSlotsCount(), i + 1);
EXPECT_TRUE(actor_->IsEnrolledInCourse(course_id));
EXPECT_FALSE(actor_->SlotsEmpty(slots_to_check));
}
EXPECT_TRUE(actor_->AllSlotsFilled());
}
TEST_F(TaleActor, DefaultTendencyChanceCalculation)
{
InteractionTendency tendency;
ContextType context = ContextType::kLast;
Kernel *reason;
float chance = actor_->CalculateInteractionChance(tendency, context, reason);
EXPECT_FLOAT_EQ(chance, 0.5f);
}
TEST_F(TaleActor, MaxTendencyChanceCalculation)
{
InteractionTendency tendency;
tendency.contexts[static_cast<int>(ContextType::kCourse)] = 1.0f;
tendency.contexts[static_cast<int>(ContextType::kFreetime)] = -1.0f;
tendency.wealth = 1.0f;
for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index)
{
tendency.emotions[type_index] = 1.0f;
}
std::vector<Kernel *> no_reasons;
actor_->wealth_ = chronicle_.CreateResource("wealth", "wealthy", "poor", 0, actor_, no_reasons, 1.0f);
for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index)
{
actor_->emotions_[type_index] = chronicle_.CreateEmotion(static_cast<EmotionType>(type_index), 0, actor_, no_reasons, 1.0f);
}
ContextType context = ContextType::kCourse;
Kernel *reason;
float chance = actor_->CalculateInteractionChance(tendency, context, reason);
EXPECT_FLOAT_EQ(chance, 1.0f);
}
TEST_F(TaleActor, RandomTendencyChanceCalculation)
{
uint32_t seconds = static_cast<uint32_t>(time(NULL));
Random random(seconds);
InteractionTendency tendency;
uint32_t tries = 1000;
for (uint32_t i = 0; i < tries; ++i)
{
tendency.contexts[static_cast<int>(ContextType::kCourse)] = random.GetFloat(-1.0f, 1.0f);
tendency.contexts[static_cast<int>(ContextType::kFreetime)] = random.GetFloat(-1.0f, 1.0f);
tendency.wealth = random.GetFloat(-1.0f, 1.0f);
for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index)
{
tendency.emotions[type_index] = random.GetFloat(-1.0f, 1.0f);
}
std::vector<Kernel *> no_reasons;
actor_->wealth_ = chronicle_.CreateResource("wealth", "wealthy", "poor", 0, actor_, no_reasons, random.GetFloat(-1.0f, 1.0f));
for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index)
{
actor_->emotions_[type_index] = chronicle_.CreateEmotion(static_cast<EmotionType>(type_index), 0, actor_, no_reasons, random.GetFloat(-1.0f, 1.0f));
}
ContextType context = (random.GetFloat(-1.0f, 1.0f) <= 0 ? ContextType::kCourse : ContextType::kFreetime);
Kernel *reason;
float chance = actor_->CalculateInteractionChance(tendency, context, reason);
EXPECT_GE(chance, 0.0f);
EXPECT_LE(chance, 1.0f);
}
}
TEST(TaleRandom, PickIndexWithHundredPercentChance)
{
uint32_t seconds = static_cast<uint32_t>(time(NULL));
Random random(seconds);
uint32_t tries = 1000;
for (uint32_t i = 0; i < tries; ++i)
{
uint32_t random_index = random.GetUInt(0, tries - 1);
std::vector<float> distribution;
distribution.reserve(tries);
for (size_t j = 0; j < tries; ++j)
{
distribution.push_back((j == random_index ? 1.0f : 0.0f));
}
EXPECT_EQ(random.PickIndex(distribution), random_index);
}
}
TEST(TaleRandom, PickBetweenFullRangeWithHundredPercentChance)
{
uint32_t seconds = static_cast<uint32_t>(time(NULL));
Random random(seconds);
uint32_t tries = 1000;
for (uint32_t i = 0; i < tries; ++i)
{
uint32_t random_index_bottom = random.GetUInt(0, (tries - 1) / 2);
uint32_t random_index_top = random.GetUInt(random_index_bottom, tries - 1);
std::vector<float> distribution(tries, 1.0f);
EXPECT_GE(random.PickIndex(distribution), 0);
EXPECT_LT(random.PickIndex(distribution), tries);
}
}
TEST(TaleRandom, PickBetweenFullRangeWithZeroPercentChance)
{
uint32_t seconds = static_cast<uint32_t>(time(NULL));
Random random(seconds);
uint32_t tries = 1000;
for (uint32_t i = 0; i < tries; ++i)
{
uint32_t random_index_bottom = random.GetUInt(0, (tries - 1) / 2);
uint32_t random_index_top = random.GetUInt(random_index_bottom, tries - 1);
std::vector<float> distribution(tries, 0.0f);
EXPECT_GE(random.PickIndex(distribution, true), 0);
EXPECT_LT(random.PickIndex(distribution, true), tries);
}
}
TEST(TaleRandom, PickBetweenRandomRange)
{
uint32_t seconds = static_cast<uint32_t>(time(NULL));
Random random(seconds);
uint32_t tries = 1000;
for (uint32_t i = 0; i < tries; ++i)
{
uint32_t random_index_bottom = random.GetUInt(0, (tries - 1) / 2);
uint32_t random_index_top = random.GetUInt(random_index_bottom, tries - 1);
std::vector<float> distribution;
distribution.reserve(tries);
for (uint32_t j = 0; j < tries; ++j)
{
distribution.push_back(((j >= random_index_bottom && j <= random_index_top) ? 1.0f : 0.0f));
}
EXPECT_GE(random.PickIndex(distribution, true), random_index_bottom);
EXPECT_LE(random.PickIndex(distribution, true), random_index_top);
}
} | 39.891738 | 175 | 0.673082 | AmonShokhinAhmed |
a7b7214dcad5af84c017b9bca86f4c7d35942a42 | 968 | cpp | C++ | problems/atcoder/abc218/d---rectangles/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/atcoder/abc218/d---rectangles/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/atcoder/abc218/d---rectangles/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#ifdef LOCAL
#include "code/formatting.hpp"
#else
#define debug(...) (void)0
#endif
using namespace std;
static_assert(sizeof(int) == 4 && sizeof(long) == 8);
using P = array<int, 2>;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int N;
cin >> N;
vector<P> pts(N);
for (auto& [x, y] : pts) {
cin >> x >> y;
}
sort(begin(pts), end(pts));
auto contains = [&](int x, int y) {
auto it = lower_bound(begin(pts), end(pts), P{x, y});
return it != end(pts) && *it == P{x, y};
};
int ans = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
auto [x0, y0] = pts[i];
auto [x1, y1] = pts[j];
if (x0 != x1 && y0 != y1) {
if (contains(x0, y1) && contains(x1, y0)) {
ans++;
}
}
}
}
ans /= 2;
cout << ans << '\n';
return 0;
}
| 23.047619 | 61 | 0.436983 | brunodccarvalho |
a7bd47760454d46cfb69247601d88f658fbe03a5 | 1,478 | cpp | C++ | QFtpServerLib/ftpretrcommand.cpp | spygg/QFtpServer | 28410fd296795d49f17d4310c992dc6e6b0c26f8 | [
"MIT"
] | null | null | null | QFtpServerLib/ftpretrcommand.cpp | spygg/QFtpServer | 28410fd296795d49f17d4310c992dc6e6b0c26f8 | [
"MIT"
] | null | null | null | QFtpServerLib/ftpretrcommand.cpp | spygg/QFtpServer | 28410fd296795d49f17d4310c992dc6e6b0c26f8 | [
"MIT"
] | null | null | null | #include "ftpretrcommand.h"
#include <QFile>
#include <QSslSocket>
FtpRetrCommand::FtpRetrCommand(QObject *parent, const QString &fileName, qint64 seekTo) :
FtpCommand(parent)
{
this->fileName = fileName;
this->seekTo = seekTo;
file = 0;
}
FtpRetrCommand::~FtpRetrCommand()
{
if (m_started) {
if (file && file->isOpen() && file->atEnd()) {
emit reply("226 Closing data connection.");
}
else {
emit reply("550 Requested action not taken; file unavailable.");
}
}
}
void FtpRetrCommand::startImplementation()
{
file = new QFile(fileName, this);
if (!file->open(QIODevice::ReadOnly)) {
deleteLater();
return;
}
emit reply("150 File status okay; about to open data connection.");
if (seekTo) {
file->seek(seekTo);
}
// For encryted SSL sockets, we need to use the encryptedBytesWritten()
// signal, see the QSslSocket documentation to for reasons why.
if (m_socket->isEncrypted()) {
connect(m_socket, SIGNAL(encryptedBytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64)));
}
else {
connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64)));
}
refillSocketBuffer(128*1024);
}
void FtpRetrCommand::refillSocketBuffer(qint64 bytes)
{
if (!file->atEnd()) {
m_socket->write(file->read(bytes));
}
else {
m_socket->disconnectFromHost();
}
}
| 25.482759 | 105 | 0.629905 | spygg |
a7be1b315b8c3828fc0f69564f11dbfb8f31648d | 2,292 | cpp | C++ | Net/testsuite/src/MailStreamTest.cpp | astlin/poco | b878152e9034b89c923bc3c97e16ae1b92c09bf4 | [
"BSL-1.0"
] | 2 | 2021-04-11T20:16:11.000Z | 2021-11-17T11:28:59.000Z | Net/testsuite/src/MailStreamTest.cpp | astlin/poco | b878152e9034b89c923bc3c97e16ae1b92c09bf4 | [
"BSL-1.0"
] | 1 | 2016-03-31T10:04:18.000Z | 2016-03-31T10:04:43.000Z | Net/testsuite/src/MailStreamTest.cpp | astlin/poco | b878152e9034b89c923bc3c97e16ae1b92c09bf4 | [
"BSL-1.0"
] | 1 | 2022-03-09T08:11:03.000Z | 2022-03-09T08:11:03.000Z | //
// MailStreamTest.cpp
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "MailStreamTest.h"
#include "Poco/CppUnit/TestCaller.h"
#include "Poco/CppUnit/TestSuite.h"
#include "Poco/Net/MailStream.h"
#include "Poco/StreamCopier.h"
#include <sstream>
using Poco::Net::MailInputStream;
using Poco::Net::MailOutputStream;
using Poco::StreamCopier;
MailStreamTest::MailStreamTest(const std::string& name): CppUnit::TestCase(name)
{
}
MailStreamTest::~MailStreamTest()
{
}
void MailStreamTest::testMailInputStream()
{
std::istringstream istr(
"From: john.doe@no.domain\r\n"
"To: jane.doe@no.domain\r\n"
"Subject: test\r\n"
"\r\n"
"This is a test.\r\n"
"\rThis.is.\ngarbage\r.\r\n"
".This line starts with a period.\r\n"
"..and this one too\r\n"
"..\r\n"
".\r\n"
);
MailInputStream mis(istr);
std::ostringstream ostr;
StreamCopier::copyStream(mis, ostr);
std::string s(ostr.str());
assertTrue (s ==
"From: john.doe@no.domain\r\n"
"To: jane.doe@no.domain\r\n"
"Subject: test\r\n"
"\r\n"
"This is a test.\r\n"
"\rThis.is.\ngarbage\r.\r\n"
".This line starts with a period.\r\n"
".and this one too\r\n"
".\r\n"
);
}
void MailStreamTest::testMailOutputStream()
{
std::string msg(
"From: john.doe@no.domain\r\n"
"To: jane.doe@no.domain\r\n"
"Subject: test\r\n"
"\r\n"
"This is a test.\r\n"
"\rThis.is.\ngarbage\r.\r\n"
".This line starts with a period.\r\n"
"\r\n"
".and this one too\r\n"
".\r\n"
);
std::ostringstream ostr;
MailOutputStream mos(ostr);
mos << msg;
mos.close();
std::string s(ostr.str());
assertTrue (s ==
"From: john.doe@no.domain\r\n"
"To: jane.doe@no.domain\r\n"
"Subject: test\r\n"
"\r\n"
"This is a test.\r\n"
"\rThis.is.\ngarbage\r.\r\n"
"..This line starts with a period.\r\n"
"\r\n"
"..and this one too\r\n"
"..\r\n"
".\r\n"
);
}
void MailStreamTest::setUp()
{
}
void MailStreamTest::tearDown()
{
}
CppUnit::Test* MailStreamTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailStreamTest");
CppUnit_addTest(pSuite, MailStreamTest, testMailInputStream);
CppUnit_addTest(pSuite, MailStreamTest, testMailOutputStream);
return pSuite;
}
| 18.786885 | 80 | 0.655323 | astlin |
a7c5144e2f50813d84e2f23d99206b08a7e1da7e | 17,985 | cpp | C++ | src/generator/protobufclassgenerator.cpp | R0ll1ngSt0ne/qtprotobuf | ce6f09ffa77fecd35fff84deb798720d870ab3e7 | [
"MIT"
] | null | null | null | src/generator/protobufclassgenerator.cpp | R0ll1ngSt0ne/qtprotobuf | ce6f09ffa77fecd35fff84deb798720d870ab3e7 | [
"MIT"
] | null | null | null | src/generator/protobufclassgenerator.cpp | R0ll1ngSt0ne/qtprotobuf | ce6f09ffa77fecd35fff84deb798720d870ab3e7 | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>, Tatyana Borisova <tanusshhka@mail.ru>
*
* This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "protobufclassgenerator.h"
#include "utils.h"
#include <iostream>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream.h>
using namespace ::QtProtobuf::generator;
using namespace ::google::protobuf;
using namespace ::google::protobuf::io;
using namespace ::google::protobuf::compiler;
ProtobufClassGenerator::ProtobufClassGenerator(const Descriptor *message, std::unique_ptr<::google::protobuf::io::ZeroCopyOutputStream> out)
: ClassGeneratorBase(message->full_name(), std::move(out))
, mMessage(message)
{
}
void ProtobufClassGenerator::printCopyFunctionality()
{
assert(mMessage != nullptr);
mPrinter.Print({{"classname", mClassName}},
Templates::CopyConstructorTemplate);
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
printField(mMessage->field(i), Templates::CopyFieldTemplate);
}
Outdent();
mPrinter.Print(Templates::SimpleBlockEnclosureTemplate);
mPrinter.Print({{"classname", mClassName}},
Templates::AssignmentOperatorTemplate);
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
printField(mMessage->field(i), Templates::CopyFieldTemplate);
}
mPrinter.Print(Templates::AssignmentOperatorReturnTemplate);
Outdent();
mPrinter.Print(Templates::SimpleBlockEnclosureTemplate);
}
void ProtobufClassGenerator::printMoveSemantic()
{
assert(mMessage != nullptr);
mPrinter.Print({{"classname", mClassName}},
Templates::MoveConstructorTemplate);
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (isComplexType(field) || field->is_repeated()) {
printField(field, Templates::MoveComplexFieldTemplate);
} else {
if (field->type() != FieldDescriptor::TYPE_ENUM) {
printField(field, Templates::MoveFieldTemplate);
}
else {
printField(field, Templates::EnumMoveFieldTemplate);
}
}
}
Outdent();
mPrinter.Print(Templates::SimpleBlockEnclosureTemplate);
mPrinter.Print({{"classname", mClassName}},
Templates::MoveAssignmentOperatorTemplate);
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (isComplexType(field) || field->is_repeated()) {
printField(field, Templates::MoveComplexFieldTemplate);
} else {
if (field->type() != FieldDescriptor::TYPE_ENUM) {
printField(field, Templates::MoveFieldTemplate);
}
else {
printField(field, Templates::EnumMoveFieldTemplate);
}
}
}
mPrinter.Print(Templates::AssignmentOperatorReturnTemplate);
Outdent();
mPrinter.Print(Templates::SimpleBlockEnclosureTemplate);
}
void ProtobufClassGenerator::printComparisonOperators()
{
assert(mMessage != nullptr);
bool isFirst = true;
PropertyMap properties;
mPrinter.Print({{"type", mClassName}}, Templates::EqualOperatorTemplate);
if (mMessage->field_count() <= 0) {
mPrinter.Print("true");
}
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (producePropertyMap(field, properties)) {
if (!isFirst) {
mPrinter.Print("\n&& ");
} else {
Indent();
Indent();
isFirst = false;
}
mPrinter.Print(properties, Templates::EqualOperatorPropertyTemplate);
}
}
//Only if at least one field "copied"
if (!isFirst) {
Outdent();
Outdent();
}
mPrinter.Print(";\n");
mPrinter.Print(Templates::SimpleBlockEnclosureTemplate);
mPrinter.Print({{"type", mClassName}}, Templates::NotEqualOperatorTemplate);
}
void ProtobufClassGenerator::printIncludes()
{
assert(mMessage != nullptr);
mPrinter.Print(Templates::DefaultProtobufIncludesTemplate);
std::set<std::string> existingIncludes;
for (int i = 0; i < mMessage->field_count(); i++) {
printInclude(mMessage->field(i), existingIncludes);
}
}
void ProtobufClassGenerator::printInclude(const FieldDescriptor *field, std::set<std::string> &existingIncludes)
{
assert(field != nullptr);
std::string newInclude;
const char *includeTemplate;
switch (field->type()) {
case FieldDescriptor::TYPE_MESSAGE:
if ( field->is_map() ) {
newInclude = "QMap";
assert(field->message_type() != nullptr);
assert(field->message_type()->field_count() == 2);
printInclude(field->message_type()->field(0), existingIncludes);
printInclude(field->message_type()->field(1), existingIncludes);
includeTemplate = Templates::ExternalIncludeTemplate;
} else {
std::string typeName = field->message_type()->name();
utils::tolower(typeName);
newInclude = typeName;
includeTemplate = Templates::InternalIncludeTemplate;
}
break;
case FieldDescriptor::TYPE_BYTES:
newInclude = "QByteArray";
includeTemplate = Templates::ExternalIncludeTemplate;
break;
case FieldDescriptor::TYPE_STRING:
newInclude = "QString";
includeTemplate = Templates::ExternalIncludeTemplate;
break;
case FieldDescriptor::TYPE_ENUM: {
EnumVisibility enumVisibily = getEnumVisibility(field, mMessage);
if (enumVisibily == GLOBAL_ENUM) {
includeTemplate = Templates::GlobalEnumIncludeTemplate;
} else if (enumVisibily == NEIGHBOUR_ENUM) {
includeTemplate = Templates::InternalIncludeTemplate;
std::string fullEnumName = field->enum_type()->full_name();
std::vector<std::string> fullEnumNameParts;
utils::split(fullEnumName, fullEnumNameParts, '.');
std::string enumTypeOwner = fullEnumNameParts.at(fullEnumNameParts.size() - 2);
utils::tolower(enumTypeOwner);
newInclude = enumTypeOwner;
} else {
return;
}
}
break;
default:
return;
}
if (existingIncludes.find(newInclude) == std::end(existingIncludes)) {
mPrinter.Print({{"include", newInclude}}, includeTemplate);
existingIncludes.insert(newInclude);
}
}
void ProtobufClassGenerator::printField(const FieldDescriptor *field, const char *fieldTemplate)
{
assert(field != nullptr);
std::map<std::string, std::string> propertyMap;
if (producePropertyMap(field, propertyMap)) {
mPrinter.Print(propertyMap, fieldTemplate);
}
}
bool ProtobufClassGenerator::producePropertyMap(const FieldDescriptor *field, PropertyMap &propertyMap)
{
assert(field != nullptr);
std::string typeName = getTypeName(field, mMessage);
if (typeName.size() <= 0) {
std::cerr << "Type "
<< field->type_name()
<< " is not supported by Qt Generator"
" please look at https://doc.qt.io/qt-5/qtqml-typesystem-basictypes.html"
" for details" << std::endl;
return false;
}
std::string typeNameLower(typeName);
utils::tolower(typeNameLower);
std::string capProperty = field->camelcase_name();
capProperty[0] = static_cast<char>(::toupper(capProperty[0]));
std::string typeNameNoList = typeName;
if (field->is_repeated() && !field->is_map()) {
if(field->type() == FieldDescriptor::TYPE_MESSAGE
|| field->type() == FieldDescriptor::TYPE_ENUM) {
typeNameNoList.resize(typeNameNoList.size() - strlen(Templates::ListSuffix));
} else {
typeNameNoList.resize(typeNameNoList.size() - strlen("List"));
}
}
propertyMap = {{"type", typeName},
{"type_lower", typeNameLower},
{"property_name", field->camelcase_name()},
{"property_name_cap", capProperty},
{"type_nolist", typeNameNoList}
};
return true;
}
bool ProtobufClassGenerator::isListType(const FieldDescriptor *field)
{
assert(field != nullptr);
return field && field->is_repeated()
&& field->type() == FieldDescriptor::TYPE_MESSAGE;
}
bool ProtobufClassGenerator::isComplexType(const FieldDescriptor *field)
{
assert(field != nullptr);
return field->type() == FieldDescriptor::TYPE_MESSAGE
|| field->type() == FieldDescriptor::TYPE_STRING
|| field->type() == FieldDescriptor::TYPE_BYTES;
}
void ProtobufClassGenerator::printConstructor()
{
std::string parameterList;
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
std::string fieldTypeName = getTypeName(field, mMessage);
std::string fieldName = field->camelcase_name();
fieldName[0] = static_cast<char>(::tolower(fieldName[0]));
if (field->is_repeated() || field->is_map()) {
parameterList += "const " + fieldTypeName + " &" + fieldName + " = {}";
} else {
switch (field->type()) {
case FieldDescriptor::TYPE_DOUBLE:
case FieldDescriptor::TYPE_FLOAT:
parameterList += fieldTypeName + " " + fieldName + " = " + "0.0";
break;
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_INT32:
case FieldDescriptor::TYPE_INT64:
case FieldDescriptor::TYPE_SINT32:
case FieldDescriptor::TYPE_SINT64:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_UINT64:
parameterList += fieldTypeName + " " + fieldName + " = " + "0";
break;
case FieldDescriptor::TYPE_BOOL:
parameterList += fieldTypeName + " " + fieldName + " = " + "false";
break;
case FieldDescriptor::TYPE_BYTES:
case FieldDescriptor::TYPE_STRING:
case FieldDescriptor::TYPE_MESSAGE:
parameterList += "const " + fieldTypeName + " &" + fieldName + " = {}";
break;
default:
parameterList += fieldTypeName + " " + fieldName + " = " + "{}";
break;
}
}
parameterList += ", ";
}
mPrinter.Print({{"classname", mClassName},
{"parameter_list", parameterList}}, Templates::ProtoConstructorTemplate);
}
void ProtobufClassGenerator::printMaps()
{
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (field->is_map()) {
std::string keyType = getTypeName(field->message_type()->field(0), mMessage);
std::string valueType = getTypeName(field->message_type()->field(1), mMessage);
const char *mapTemplate = Templates::MapTypeUsingTemplate;
if (field->message_type()->field(1)->type() == FieldDescriptor::TYPE_MESSAGE) {
mapTemplate = Templates::MessageMapTypeUsingTemplate;
}
mPrinter.Print({{"classname",field->message_type()->name()},
{"key", keyType},
{"value", valueType}}, mapTemplate);
}
}
Outdent();
}
void ProtobufClassGenerator::printLocalEmumsMetaTypesDeclaration()
{
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (field == nullptr || field->enum_type() == nullptr)
continue;
if (field->type() == FieldDescriptor::TYPE_ENUM
&& isLocalMessageEnum(mMessage, field)) {
mPrinter.Print({{"classname", mClassName + "::" + field->enum_type()->name() + Templates::ListSuffix},
{"namespaces", mNamespacesColonDelimited}}, Templates::DeclareMetaTypeTemplate);
}
}
}
void ProtobufClassGenerator::printMapsMetaTypesDeclaration()
{
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (field->is_map()) {
mPrinter.Print({{"classname", field->message_type()->name()},
{"namespaces", mNamespacesColonDelimited + "::" + mClassName}}, Templates::DeclareMetaTypeTemplate);
}
}
}
void ProtobufClassGenerator::printProperties()
{
assert(mMessage != nullptr);
//private section
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
const char *propertyTemplate = Templates::PropertyTemplate;
if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_map() && !field->is_repeated()) {
propertyTemplate = Templates::MessagePropertyTemplate;
}
printField(field, propertyTemplate);
}
//Generate extra QmlListProperty that is mapped to list
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (field->type() == FieldDescriptor::TYPE_MESSAGE && field->is_repeated() && !field->is_map()) {
printField(field, Templates::QmlListPropertyTemplate);
}
}
Outdent();
printQEnums(mMessage);
//public section
printPublic();
printMaps();
//Body
Indent();
printConstructor();
printCopyFunctionality();
printMoveSemantic();
printComparisonOperators();
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
if (!field->is_map() && !field->is_repeated()) {
printField(field, Templates::GetterMessageTemplate);
}
}
printField(field, Templates::GetterTemplate);
if (field->is_repeated()) {
printField(field, Templates::GetterContainerExtraTemplate);
if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_map()) {
printField(field, Templates::QmlListGetterTemplate);
}
}
}
for (int i = 0; i < mMessage->field_count(); i++) {
auto field = mMessage->field(i);
switch (field->type()) {
case FieldDescriptor::TYPE_MESSAGE:
if (!field->is_map() && !field->is_repeated()) {
printField(field, Templates::SetterTemplateMessageType);
}
printField(field, Templates::SetterTemplateComplexType);
break;
case FieldDescriptor::FieldDescriptor::TYPE_STRING:
case FieldDescriptor::FieldDescriptor::TYPE_BYTES:
printField(field, Templates::SetterTemplateComplexType);
break;
default:
printField(field, Templates::SetterTemplateSimpleType);
break;
}
}
Outdent();
mPrinter.Print(Templates::SignalsBlockTemplate);
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
printField(mMessage->field(i), Templates::SignalTemplate);
}
Outdent();
}
void ProtobufClassGenerator::printListType()
{
mPrinter.Print({{"classname", mClassName}}, Templates::ComplexListTypeUsingTemplate);
}
void ProtobufClassGenerator::printClassMembers()
{
Indent();
for (int i = 0; i < mMessage->field_count(); i++) {
printField(mMessage->field(i), Templates::MemberTemplate);
}
Outdent();
}
std::set<std::string> ProtobufClassGenerator::extractModels() const
{
std::set<std::string> extractedModels;
for (int i = 0; i < mMessage->field_count(); i++) {
const FieldDescriptor *field = mMessage->field(i);
if (field->is_repeated()
&& field->type() == FieldDescriptor::TYPE_MESSAGE) {
std::string typeName = field->message_type()->name();
extractedModels.insert(typeName);
}
}
return extractedModels;
}
void ProtobufClassGenerator::run()
{
printPreamble();
printIncludes();
printNamespaces();
printClassDeclaration();
printProperties();
printPrivate();
printClassMembers();
encloseClass();
printListType();
encloseNamespaces();
printMetaTypeDeclaration();
printMapsMetaTypesDeclaration();
printLocalEmumsMetaTypesDeclaration();
}
| 35.826693 | 140 | 0.619127 | R0ll1ngSt0ne |
a7c6a53c147194bd18746ddc3b384784cae07a4a | 5,302 | cpp | C++ | modules/arm_plugin/src/arm_converter/arm_converter_one_hot.cpp | IvanNovoselov/openvino_contrib | 5fe8fd389d57972bd470b447c606138679ab5d49 | [
"Apache-2.0"
] | null | null | null | modules/arm_plugin/src/arm_converter/arm_converter_one_hot.cpp | IvanNovoselov/openvino_contrib | 5fe8fd389d57972bd470b447c606138679ab5d49 | [
"Apache-2.0"
] | null | null | null | modules/arm_plugin/src/arm_converter/arm_converter_one_hot.cpp | IvanNovoselov/openvino_contrib | 5fe8fd389d57972bd470b447c606138679ab5d49 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2020-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include <details/ie_exception.hpp>
#include "arm_converter/arm_converter.hpp"
#include <ngraph/runtime/reference/one_hot.hpp>
namespace ArmPlugin {
template <typename Indices, typename OutputType>
void wrap_one_hot(const Indices* arg,
OutputType* out,
const ngraph::Shape& in_shape,
const ngraph::Shape& out_shape,
size_t one_hot_axis,
const OutputType* on_values,
const OutputType* off_values) {
ngraph::runtime::reference::one_hot(arg,
out,
in_shape,
out_shape,
one_hot_axis,
on_values[0],
off_values[0]);
}
template<> Converter::Conversion::Ptr Converter::Convert(const opset::OneHot& node) {
auto make = [&] (auto refFunction) {
return MakeConversion(refFunction,
node.input(0),
node.output(0),
node.get_input_shape(0),
node.get_output_shape(0),
static_cast<size_t>(node.get_axis()),
node.input(2),
node.input(3));
};
ngraph::element::Type_t outType = node.get_output_element_type(0);
switch (node.get_input_element_type(0)) {
case ngraph::element::Type_t::u8 :
switch (outType) {
case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint8_t, std::uint8_t>);
case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint8_t, std::int16_t>);
case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint8_t, std::uint16_t>);
case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint8_t, std::int32_t>);
case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint8_t, float>);
default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {};
}
case ngraph::element::Type_t::i16 :
switch (outType) {
case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::int16_t, std::uint8_t>);
case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::int16_t, std::int16_t>);
case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::int16_t, std::uint16_t>);
case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::int16_t, std::int32_t>);
case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::int16_t, float>);
default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {};
}
case ngraph::element::Type_t::u16 :
switch (outType) {
case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint16_t, std::uint8_t>);
case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint16_t, std::int16_t>);
case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint16_t, std::uint16_t>);
case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint16_t, std::int32_t>);
case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint16_t, float>);
default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {};
}
case ngraph::element::Type_t::u32 :
switch (outType) {
case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint32_t, std::uint8_t>);
case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint32_t, std::int16_t>);
case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint32_t, std::uint16_t>);
case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint32_t, std::int32_t>);
case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint32_t, float>);
default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {};
}
case ngraph::element::Type_t::i32 :
switch (outType) {
case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::int32_t, std::uint8_t>);
case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::int32_t, std::int16_t>);
case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::int32_t, std::uint16_t>);
case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::int32_t, std::int32_t>);
case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::int32_t, float>);
default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {};
}
default: THROW_IE_EXCEPTION << "Unsupported Type: " << node.get_input_element_type(0); return {};
}
}
} // namespace ArmPlugin
| 58.911111 | 108 | 0.570351 | IvanNovoselov |
a7c761c18ab7051ec25627e38782b52942f3409a | 2,220 | cpp | C++ | Examples/CPP/Licensing/EvaluationDateTimeLimitations.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2022-03-16T14:31:36.000Z | 2022-03-16T14:31:36.000Z | Examples/CPP/Licensing/EvaluationDateTimeLimitations.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | null | null | null | Examples/CPP/Licensing/EvaluationDateTimeLimitations.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2020-07-01T01:26:17.000Z | 2020-07-01T01:26:17.000Z | /*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference
when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using https://forum.aspose.com/c/tasks
*/
#include "EvaluationDateTimeLimitations.h"
#include <Tsk.h>
#include <TaskCollection.h>
#include <Task.h>
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object.h>
#include <system/date_time.h>
#include <saving/Enums/SaveFileFormat.h>
#include <Project.h>
#include <Key.h>
#include <enums/TaskKey.h>
#include "RunExamples.h"
using namespace Aspose::Tasks::Saving;
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace Licensing {
RTTI_INFO_IMPL_HASH(2704315891u, ::Aspose::Tasks::Examples::CPP::Licensing::EvaluationDateTimeLimitations, ThisTypeBaseTypesInfo);
void EvaluationDateTimeLimitations::Run()
{
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
// ExStart:DateTimeLimitations
// Create a prject instance
System::SharedPtr<Project> project1 = System::MakeObject<Project>();
// Define Tasks
System::SharedPtr<Task> task1 = project1->get_RootTask()->get_Children()->Add(u"Task1");
task1->Set(Tsk::ActualStart(), System::DateTime::Parse(u"06-Apr-2010"));
System::SharedPtr<Task> task2 = project1->get_RootTask()->get_Children()->Add(u"Task2");
task2->Set(Tsk::ActualStart(), System::DateTime::Parse(u"10-Apr-2010"));
// Save the Project as XML
project1->Save(u"EvalProject_out.xml", Aspose::Tasks::Saving::SaveFileFormat::XML);
// ExEnd:DateTimeLimitations
}
} // namespace Licensing
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
| 34.153846 | 164 | 0.743243 | aspose-tasks |
a7c974e4a298f7c669de3f5dcc90e888d6a23a1b | 462 | hxx | C++ | src/engine/Component.hxx | broken-bytes/Cyanite | 0392e3114c946e41b7352afd4b8eceb6f03939da | [
"MIT"
] | 1 | 2021-11-11T02:56:56.000Z | 2021-11-11T02:56:56.000Z | src/engine/Component.hxx | broken-bytes/Cyanite | 0392e3114c946e41b7352afd4b8eceb6f03939da | [
"MIT"
] | null | null | null | src/engine/Component.hxx | broken-bytes/Cyanite | 0392e3114c946e41b7352afd4b8eceb6f03939da | [
"MIT"
] | null | null | null | #pragma once
#include "EntityRegistry.hxx"
#include "EntitySet.hxx"
namespace BrokenBytes::Cyanite::Engine {
struct Component {
Component(std::string name) {
this->_name = name;
}
protected:
std::string _name;
private:
friend class EntityRegistry;
friend struct EntitySet;
friend struct Entity;
auto Name() const->std::string {
return this->_name;
}
};
}
| 20.086957 | 40 | 0.577922 | broken-bytes |
a7d449ff1d722a52d43480dffbe82ddc3253a869 | 14,209 | cpp | C++ | src/kfilter.cpp | Jamieryan/carma_pack | 347ea78818cc808e53e4a46d341829f787198df5 | [
"MIT"
] | 39 | 2015-01-25T19:24:09.000Z | 2022-02-28T11:55:28.000Z | src/kfilter.cpp | Jamieryan/carma_pack | 347ea78818cc808e53e4a46d341829f787198df5 | [
"MIT"
] | 13 | 2015-04-29T12:37:45.000Z | 2021-11-28T23:31:29.000Z | src/kfilter.cpp | Jamieryan/carma_pack | 347ea78818cc808e53e4a46d341829f787198df5 | [
"MIT"
] | 19 | 2015-09-15T00:41:28.000Z | 2021-07-28T07:28:47.000Z | //
// kfilter.cpp
// carma_pack
//
// Created by Brandon Kelly on 6/27/13.
// Copyright (c) 2013 Brandon Kelly. All rights reserved.
//
#include <random.hpp>
#include "include/kfilter.hpp"
// Global random number generator object, instantiated in random.cpp
extern boost::random::mt19937 rng;
// Object containing some common random number generators.
extern RandomGenerator RandGen;
// Reset the Kalman Filter for a CAR(1) process
void KalmanFilter1::Reset() {
mean(0) = 0.0;
var(0) = sigsqr_ / (2.0 * omega_) + yerr_(0) * yerr_(0);
yconst_ = 0.0;
yslope_ = 0.0;
current_index_ = 1;
}
// Perform one iteration of the Kalman Filter for a CAR(1) process to update it
void KalmanFilter1::Update() {
double rho, var_ratio, previous_var;
rho = exp(-1.0 * omega_ * dt_(current_index_-1));
previous_var = var(current_index_-1) - yerr_(current_index_-1) * yerr_(current_index_-1);
var_ratio = previous_var / var(current_index_-1);
// Update the Kalman filter mean
mean(current_index_) = rho * mean(current_index_-1) +
rho * var_ratio * (y_(current_index_-1) - mean(current_index_-1));
// Update the Kalman filter variance
var(current_index_) = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) +
rho * rho * previous_var * (1.0 - var_ratio);
// add in contribution to variance from measurement errors
var(current_index_) += yerr_(current_index_) * yerr_(current_index_);
current_index_++;
}
// Initialize the coefficients used for interpolation and backcasting assuming a CAR(1) process
void KalmanFilter1::InitializeCoefs(double time, unsigned int itime, double ymean, double yvar) {
yconst_ = 0.0;
yslope_ = exp(-std::abs(time_(itime) - time) * omega_);
var[itime] = sigsqr_ / (2.0 * omega_) * (1.0 - yslope_ * yslope_) + yerr_(itime) * yerr_(itime);
current_index_ = itime + 1;
}
// Update the coefficients used for interpolation and backcasting, assuming a CAR(1) process
void KalmanFilter1::UpdateCoefs() {
double rho = exp(-1.0 * dt_(current_index_-1) * omega_);
double previous_var = var(current_index_-1) - yerr_(current_index_-1) * yerr_(current_index_-1);
double var_ratio = previous_var / var(current_index_-1);
yslope_ *= rho * (1.0 - var_ratio);
yconst_ = yconst_ * rho * (1.0 - var_ratio) + rho * var_ratio * y_[current_index_-1];
var(current_index_) = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) +
rho * rho * previous_var * (1.0 - var_ratio) + yerr_(current_index_) * yerr_(current_index_);
current_index_++;
}
// Return the predicted value and its variance at time assuming a CAR(1) process
std::pair<double, double> KalmanFilter1::Predict(double time) {
double rho, var_ratio, previous_var;
double ypredict_mean, ypredict_var, yprecision;
unsigned int ipredict = 0;
while (time > time_(ipredict)) {
// find the index where time_ > time for the first time
ipredict++;
if (ipredict == time_.n_elem) {
// time is greater than last element of time_, so do forecasting
break;
}
}
// Run the Kalman filter up to the point time_[ipredict-1]
Reset();
for (int i=1; i<ipredict; i++) {
Update();
}
if (ipredict == 0) {
// backcasting, so initialize the conditional mean and variance to the stationary values
ypredict_mean = 0.0;
ypredict_var = sigsqr_ / (2.0 * omega_);
} else {
// predict the value of the time series at time, given the earlier values
double dt = time - time_[ipredict-1];
rho = exp(-dt * omega_);
previous_var = var(ipredict-1) - yerr_(ipredict-1) * yerr_(ipredict-1);
var_ratio = previous_var / var(ipredict-1);
// initialize the conditional mean and variance
ypredict_mean = rho * mean(ipredict-1) + rho * var_ratio * (y_(ipredict-1) - mean(ipredict-1));
ypredict_var = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) + rho * rho * previous_var * (1.0 - var_ratio);
}
if (ipredict == time_.n_elem) {
// Forecasting, so we're done: no need to run interpolation steps
std::pair<double, double> ypredict(ypredict_mean, ypredict_var);
return ypredict;
}
yprecision = 1.0 / ypredict_var;
ypredict_mean *= yprecision;
// Either backcasting or interpolating, so need to calculate coefficients of linear filter as a function of
// the predicted time series value, then update the running conditional mean and variance of the predicted
// time series value
InitializeCoefs(time, ipredict, 0.0, 0.0);
yprecision += yslope_ * yslope_ / var(ipredict);
ypredict_mean += yslope_ * (y_(ipredict) - yconst_) / var(ipredict);
for (int i=ipredict+1; i<time_.n_elem; i++) {
UpdateCoefs();
yprecision += yslope_ * yslope_ / var(i);
ypredict_mean += yslope_ * (y_(i) - yconst_) / var(i);
}
ypredict_var = 1.0 / yprecision;
ypredict_mean *= ypredict_var;
std::pair<double, double> ypredict(ypredict_mean, ypredict_var);
return ypredict;
}
// Reset the Kalman Filter for a CARMA(p,q) process
void KalmanFilterp::Reset() {
// Initialize the matrix of Eigenvectors. We will work with the state vector
// in the space spanned by the Eigenvectors because in this space the state
// transition matrix is diagonal, so the calculation of the matrix exponential
// is fast.
arma::cx_mat EigenMat(p_,p_);
EigenMat.row(0) = arma::ones<arma::cx_rowvec>(p_);
EigenMat.row(1) = omega_.st();
for (int i=2; i<p_; i++) {
EigenMat.row(i) = strans(arma::pow(omega_, i));
}
// Input vector under original state space representation
arma::cx_vec Rvector = arma::zeros<arma::cx_vec>(p_);
Rvector(p_-1) = 1.0;
// Transform the input vector to the rotated state space representation.
// The notation R and J comes from Belcher et al. (1994).
arma::cx_vec Jvector(p_);
Jvector = arma::solve(EigenMat, Rvector);
// Transform the moving average coefficients to the space spanned by EigenMat.
rotated_ma_coefs_ = ma_coefs_ * EigenMat;
// Calculate the stationary covariance matrix of the state vector.
for (int i=0; i<p_; i++) {
for (int j=i; j<p_; j++) {
// Only fill in upper triangle of StateVar because of symmetry
StateVar_(i,j) = -sigsqr_ * Jvector(i) * std::conj(Jvector(j)) /
(omega_(i) + std::conj(omega_(j)));
}
}
StateVar_ = arma::symmatu(StateVar_); // StateVar is symmetric
PredictionVar_ = StateVar_; // One-step state prediction error
state_vector_.zeros(); // Initial state is set to zero
// Initialize the Kalman mean and variance. These are the forecasted value
// for the measured time series values and its variance, conditional on the
// previous measurements
mean(0) = 0.0;
var(0) = std::real( arma::as_scalar(rotated_ma_coefs_ * StateVar_ * rotated_ma_coefs_.t()) );
var(0) += yerr_(0) * yerr_(0); // Add in measurement error contribution
innovation_ = y_(0); // The innovation
current_index_ = 1;
}
// Perform one iteration of the Kalman Filter for a CARMA(p,q) process to update it
void KalmanFilterp::Update() {
// First compute the Kalman Gain
kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(current_index_-1);
// Now update the state vector
state_vector_ += kalman_gain_ * innovation_;
// Update the state one-step prediction error variance
PredictionVar_ -= var(current_index_-1) * (kalman_gain_ * kalman_gain_.t());
// Predict the next state
rho_ = arma::exp(omega_ * dt_(current_index_-1));
state_vector_ = rho_ % state_vector_;
// Update the predicted state variance matrix
PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_;
// Now predict the observation and its variance.
mean(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * state_vector_) );
var(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) );
var(current_index_) += yerr_(current_index_) * yerr_(current_index_); // Add in measurement error contribution
// Finally, update the innovation
innovation_ = y_(current_index_) - mean(current_index_);
current_index_++;
}
// Predict the time series at the input time given the measured time series, assuming a CARMA(p,q) process
std::pair<double, double> KalmanFilterp::Predict(double time) {
unsigned int ipredict = 0;
while (time > time_(ipredict)) {
// find the index where time_ > time for the first time
ipredict++;
if (ipredict == time_.n_elem) {
// time is greater than last element of time_, so do forecasting
break;
}
}
// Run the Kalman filter up to the point time_[ipredict-1]
Reset();
for (int i=1; i<ipredict; i++) {
Update();
}
double ypredict_mean, ypredict_var, yprecision;
if (ipredict == 0) {
// backcasting, so initialize the conditional mean and variance to the stationary values
ypredict_mean = 0.0;
ypredict_var = std::real( arma::as_scalar(rotated_ma_coefs_ * StateVar_ * rotated_ma_coefs_.t()) );
} else {
// predict the value of the time series at time, given the earlier values
kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(ipredict-1);
state_vector_ += kalman_gain_ * innovation_;
PredictionVar_ -= var(ipredict-1) * (kalman_gain_ * kalman_gain_.t());
double dt = std::abs(time - time_(ipredict-1));
rho_ = arma::exp(omega_ * dt);
state_vector_ = rho_ % state_vector_;
PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_;
// initialize the conditional mean and variance
ypredict_mean = std::real( arma::as_scalar(rotated_ma_coefs_ * state_vector_) );
ypredict_var = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) );
}
if (ipredict == time_.n_elem) {
// Forecasting, so we're done: no need to run interpolation steps
std::pair<double, double> ypredict(ypredict_mean, ypredict_var);
return ypredict;
}
yprecision = 1.0 / ypredict_var;
ypredict_mean *= yprecision;
// Either backcasting or interpolating, so need to calculate coefficients of linear filter as a function of
// the predicted time series value, then update the running conditional mean and variance of the predicted
// time series value
InitializeCoefs(time, ipredict, ypredict_mean / yprecision, ypredict_var);
yprecision += yslope_ * yslope_ / var(ipredict);
ypredict_mean += yslope_ * (y_(ipredict) - yconst_) / var(ipredict);
for (int i=ipredict+1; i<time_.n_elem; i++) {
UpdateCoefs();
yprecision += yslope_ * yslope_ / var(i);
ypredict_mean += yslope_ * (y_(i) - yconst_) / var(i);
}
ypredict_var = 1.0 / yprecision;
ypredict_mean *= ypredict_var;
std::pair<double, double> ypredict(ypredict_mean, ypredict_var);
return ypredict;
}
// Initialize the coefficients needed for computing the Kalman Filter at future times as a function of
// the time series at time, where time_(itime-1) < time < time_(itime)
void KalmanFilterp::InitializeCoefs(double time, unsigned int itime, double ymean, double yvar) {
kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / yvar;
// initialize the coefficients for predicting the state vector at coefs(time_predict|time_predict)
state_const_ = state_vector_ - kalman_gain_ * ymean;
state_slope_ = kalman_gain_;
// update the state one-step prediction error variance
PredictionVar_ -= yvar * (kalman_gain_ * kalman_gain_.t());
// coefs(time_predict|time_predict) --> coefs(time[i+1]|time_predict)
double dt = std::abs(time_(itime) - time);
rho_ = arma::exp(omega_ * dt);
state_const_ = rho_ % state_const_;
state_slope_ = rho_ % state_slope_;
// update the predicted state covariance matrix
PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_;
// compute the coefficients for the linear filter at time[ipredict], and compute the variance in the predicted
// y[ipredict]
yconst_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_const_) );
yslope_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_slope_) );
var(itime) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) )
+ yerr_(itime) * yerr_(itime);
current_index_ = itime + 1;
}
// Update the coefficients need for computing the Kalman Filter at future times as a function of the
// time series value at some earlier time
void KalmanFilterp::UpdateCoefs() {
kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(current_index_-1);
// update the coefficients for predicting the state vector at coefs(i|i-1) --> coefs(i|i)
state_const_ += kalman_gain_ * (y_(current_index_-1) - yconst_);
state_slope_ -= kalman_gain_ * yslope_;
// update the state one-step prediction error variance
PredictionVar_ -= var(current_index_-1) * (kalman_gain_ * kalman_gain_.t());
// compute the one-step state prediction coefficients: coefs(i|i) --> coefs(i+1|i)
rho_ = arma::exp(omega_ * dt_(current_index_-1));
state_const_ = rho_ % state_const_;
state_slope_ = rho_ % state_slope_;
// update the predicted state covariance matrix
PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_;
// compute the coefficients for the linear filter at time[ipredict], and compute the variance in the predicted
// y[ipredict]
yconst_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_const_) );
yslope_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_slope_) );
var(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) )
+ yerr_(current_index_) * yerr_(current_index_);
current_index_++;
}
| 42.038462 | 115 | 0.671265 | Jamieryan |
a7d8c4e42f5e8b0f14bec65e1b38b18bc0593325 | 4,071 | cpp | C++ | src/Dicom_util.cpp | Swassie/dcmedit | ffa3052386679ac60d5373f0b33bc767aa57de04 | [
"BSD-3-Clause"
] | null | null | null | src/Dicom_util.cpp | Swassie/dcmedit | ffa3052386679ac60d5373f0b33bc767aa57de04 | [
"BSD-3-Clause"
] | null | null | null | src/Dicom_util.cpp | Swassie/dcmedit | ffa3052386679ac60d5373f0b33bc767aa57de04 | [
"BSD-3-Clause"
] | 1 | 2021-05-10T08:54:39.000Z | 2021-05-10T08:54:39.000Z | #include "Dicom_util.h"
#include "logging/Log.h"
#include <dcmtk/dcmdata/dcelem.h>
#include <dcmtk/dcmdata/dcitem.h>
#include <dcmtk/dcmdata/dcpath.h>
#include <dcmtk/dcmdata/dcsequen.h>
#include <stdexcept>
static DcmObject* get_object(DcmPath* path) {
DcmPathNode* last_element = path->back();
if(last_element == nullptr) {
throw std::runtime_error("Invalid tag path.");
}
DcmObject* object = last_element->m_obj;
if(object == nullptr) {
throw std::runtime_error("Invalid tag path.");
}
return object;
}
static void set_element_value(const OFList<DcmPath*>& paths, const std::string& value) {
bool error = false;
for(DcmPath* path : paths) {
DcmPathNode* last_element = path->back();
if(last_element == nullptr) {
error = true;
continue;
}
auto element = dynamic_cast<DcmElement*>(last_element->m_obj);
if(element == nullptr) {
error = true;
continue;
}
OFCondition status = element->putString(value.c_str());
if(status.bad()) {
Log::error(std::string("Failed to set element value. Reason: ") + status.text());
error = true;
continue;
}
}
if(error) {
throw std::runtime_error("At least one error occurred, check log for details.");
}
}
void Dicom_util::set_element(const std::string& tag_path, const std::string& value,
DcmDataset& dataset) {
DcmPathProcessor path_proc;
OFCondition status = path_proc.findOrCreatePath(&dataset, tag_path.c_str(), true);
if(status.bad()) {
throw std::runtime_error(status.text());
}
OFList<DcmPath*> foundPaths;
auto resultCount = path_proc.getResults(foundPaths);
if(resultCount == 0) {
throw std::runtime_error("Tag path not found.");
}
DcmObject* object = get_object(foundPaths.front());
if(!object->isLeaf()) {
if(!value.empty()) {
throw std::runtime_error("Can't set value for non-leaf element.");
}
return;
}
set_element_value(foundPaths, value);
}
void Dicom_util::edit_element(const std::string& tag_path, const std::string& value,
DcmDataset& dataset) {
DcmPathProcessor path_proc;
OFCondition status = path_proc.findOrCreatePath(&dataset, tag_path.c_str(), false);
if(status.bad()) {
throw std::runtime_error(status.text());
}
OFList<DcmPath*> foundPaths;
auto resultCount = path_proc.getResults(foundPaths);
if(resultCount == 0) {
throw std::runtime_error("Tag path not found.");
}
DcmObject* object = get_object(foundPaths.front());
if(!object->isLeaf()) {
throw std::runtime_error("Can't edit non-leaf element.");
}
set_element_value(foundPaths, value);
}
void Dicom_util::delete_element(const std::string& tag_path, DcmDataset& dataset) {
DcmPathProcessor path_proc;
unsigned int resultCount = 0;
OFCondition status = path_proc.findOrDeletePath(&dataset, tag_path.c_str(), resultCount);
if(status.bad()) {
throw std::runtime_error(status.text());
}
}
int Dicom_util::get_index_nr(DcmObject& object) {
DcmObject* parent = object.getParent();
if(!parent) {
return 0;
}
const DcmEVR vr = parent->ident();
if(vr == EVR_item || vr == EVR_dataset) {
auto item = static_cast<DcmItem*>(parent);
auto elementCount = item->getNumberOfValues();
for(auto i = 0u; i < elementCount; ++i) {
if(item->getElement(i) == &object) {
return i;
}
}
}
else if(vr == EVR_SQ) {
auto sq = static_cast<DcmSequenceOfItems*>(parent);
auto itemCount = sq->getNumberOfValues();
for(auto i = 0u; i < itemCount; ++i) {
if(sq->getItem(i) == &object) {
return i;
}
}
}
Log::error("Could not get index of object. Parent VR: " + std::to_string(vr));
return -1;
}
| 30.380597 | 93 | 0.603537 | Swassie |
a7d96fd91a8175ef20c22e2aaf1d3c40d7aa2122 | 21,644 | cpp | C++ | core/src/glam/jit/math_compiler.cpp | glammath/glam | 2eca0625c95ecf4ea0592f06101e13a92926c5cf | [
"Apache-2.0"
] | 3 | 2021-08-01T16:00:11.000Z | 2021-08-13T20:51:47.000Z | core/src/glam/jit/math_compiler.cpp | glammath/glam | 2eca0625c95ecf4ea0592f06101e13a92926c5cf | [
"Apache-2.0"
] | null | null | null | core/src/glam/jit/math_compiler.cpp | glammath/glam | 2eca0625c95ecf4ea0592f06101e13a92926c5cf | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 Kioshi Morosin <glam@hex.lc>
*
* 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 "math_compiler.h"
#include <wasm-stack.h>
#include <binaryen-c.h>
#include "globals.h"
#define GLAM_COMPILER_TRACE(msg) GLAM_TRACE("[compiler] " << msg)
void module_visitor::visit_module() {
GLAM_COMPILER_TRACE("visit_module");
this->module = BinaryenModuleCreate();
// we import memory and table from the core module so we can indirect-call functions
BinaryenAddMemoryImport(module, "memory", "env", "memory", 0);
BinaryenAddTableImport(module, "table", "env", "table");
}
void module_visitor::visit_export(const std::string &inner_name, const std::string &outer_name) {
GLAM_COMPILER_TRACE("visit_export " << inner_name << " -> " << outer_name);
auto exp = new wasm::Export;
exp->name = outer_name;
exp->value = inner_name;
exp->kind = wasm::ExternalKind::Function;
module->addExport(exp);
}
function_visitor *module_visitor::visit_function(const std::string &name, wasm::Signature sig) {
GLAM_COMPILER_TRACE("visit_function " << name);
auto fv = new function_visitor(this);
this->children.push_back(fv);
fv->parent = this;
fv->func->name = name;
fv->func->type = sig;
return fv;
}
template <typename T> compiled_fxn<T> module_visitor::visit_end() {
GLAM_COMPILER_TRACE("visit_end module");
uint32_t globalFlags = 0;
uint32_t totalArenaSize = 0;
std::for_each(children.begin(), children.end(), [&](function_visitor *fv) {
globalFlags |= fv->flags;
totalArenaSize += fv->arena_size;
});
// add fake function imports so binaryen is aware of the function types. increases binary size but i'm not sure
// of a better way to do this (using stack IR).
if (globalFlags & function_visitor::USES_MPCx1) {
GLAM_COMPILER_TRACE("uses mpcx1");
BinaryenType ii[2] = { BinaryenTypeInt32(), BinaryenTypeInt32() };
auto fakeType = BinaryenTypeCreate(ii, 2);
BinaryenAddFunctionImport(module, "_operator_nop1", "env", "_operator_nop1", fakeType, BinaryenTypeInt32());
}
if (globalFlags & function_visitor::USES_MPCx2) {
GLAM_COMPILER_TRACE("uses mpcx2");
BinaryenType iii[3] = { BinaryenTypeInt32(), BinaryenTypeInt32(), BinaryenTypeInt32() };
auto fakeType = BinaryenTypeCreate(iii, 3);
BinaryenAddFunctionImport(module, "_operator_nop2", "env", "_operator_nop2", fakeType, BinaryenTypeInt32());
}
if (globalFlags & function_visitor::USES_F64x2) {
GLAM_COMPILER_TRACE("uses f64x2");
BinaryenType ddi[3] = { BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeInt32() };
auto fakeType = BinaryenTypeCreate(ddi, 3);
BinaryenAddFunctionImport(module, "_operator_nop2d", "env", "_operator_nop2", fakeType, BinaryenTypeInt32());
}
if (globalFlags & function_visitor::USES_F64x4) {
GLAM_COMPILER_TRACE("uses f64x4");
BinaryenType ddddi[5] = { BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeFloat64(),
BinaryenTypeInt32() };
auto fakeType = BinaryenTypeCreate(ddddi, 5);
BinaryenAddFunctionImport(module, "_operator_nop4", "env", "_operator_nop4", fakeType, BinaryenTypeInt32());
}
if (globalFlags &
(function_visitor::USES_F64x2 | function_visitor::USES_F64x4 | function_visitor::USES_MPCx1 | function_visitor::USES_MPCx2)) {
GLAM_COMPILER_TRACE("uses arena");
BinaryenAddGlobalImport(module, "_arena", "env", "_arena", wasm::Type::i32, false);
}
auto result = BinaryenModuleAllocateAndWrite(module, nullptr);
compiled_fxn<T> fxn(entry_point, fxn_name, parameter_name, result.binary, result.binaryBytes, totalArenaSize);
BinaryenModuleDispose(module);
std::for_each(children.begin(), children.end(), [&](function_visitor *fv) {
delete fv;
});
fxn.install(result.binary, result.binaryBytes);
free(result.binary);
GLAM_COMPILER_TRACE("compilation complete");
return fxn;
}
void module_visitor::abort() {
GLAM_COMPILER_TRACE("mv: aborting early");
std::for_each(children.begin(), children.end(), [&](function_visitor *fv) {
delete fv;
});
BinaryenModuleDispose(module);
}
function_visitor::function_visitor(module_visitor *_parent): parent(_parent) {
this->func = new wasm::Function;
auto nop = parent->module->allocator.alloc<wasm::Nop>();
nop->type = wasm::Type::none;
this->func->body = nop;
this->func->stackIR = std::make_unique<wasm::StackIR>();
}
void function_visitor::visit_entry_point() {
GLAM_COMPILER_TRACE("visit_entry_point " << func->name.str);
parent->entry_point = func->name.str;
}
void function_visitor::visit_float(double d) {
GLAM_COMPILER_TRACE("visit_float " << d);
auto c = parent->module->allocator.alloc<wasm::Const>();
c->type = wasm::Type::f64;
c->value = wasm::Literal(d);
visit_basic(c);
}
void function_visitor::visit_complex(std::complex<double> z) {
visit_float(z.real());
visit_float(z.imag());
}
void function_visitor::visit_basic(wasm::Expression *inst) {
inst->finalize();
auto si = parent->module->allocator.alloc<wasm::StackInst>();
si->op = wasm::StackInst::Basic;
si->type = inst->type;
si->origin = inst;
func->stackIR->push_back(si);
}
void function_visitor::visit_complex(const mp_complex &z) {
auto ptr = std::find(local_consts.begin(), local_consts.end(), z);
if (ptr == local_consts.end()) {
local_consts.push_back(z);
}
visit_global_get("_complex_" + std::to_string(ptr - local_consts.begin()));
}
template <typename T> void function_visitor::visit_ptr(T *ptr) {
auto c = parent->module->allocator.alloc<wasm::Const>();
c->type = wasm::Type::i32;
c->value = wasm::Literal(static_cast<int32_t>(reinterpret_cast<uintptr_t>(ptr)));
visit_basic(c);
}
void function_visitor::visit_global_get(const std::string &name) {
auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>();
globalGet->type = wasm::Type::i32;
globalGet->name = name;
}
void function_visitor::visit_mpcx2(morpheme_mpcx2 *morph) {
GLAM_COMPILER_TRACE("visit_mpcx2");
arena_size += 2;
flags |= USES_MPCx2;
auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>();
globalGet->type = wasm::Type::i32;
globalGet->name = "_arena";
visit_basic(globalGet);
visit_ptr(morph);
auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>();
callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }), wasm::Type::i32); // (iii)->i
callIndirect->table = "table";
callIndirect->isReturn = false;
callIndirect->type = wasm::Type::i32;
visit_basic(callIndirect);
}
void function_visitor::visit_mpcx1(morpheme_mpcx1 *morph) {
GLAM_COMPILER_TRACE("visit_mpcx1");
arena_size++;
flags |= USES_MPCx1;
auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>();
globalGet->type = wasm::Type::i32;
globalGet->name = "_arena";
visit_basic(globalGet);
visit_ptr(morph);
auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>();
callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::i32, wasm::Type::i32 }), wasm::Type::i32); // (ii)->i
callIndirect->table = "table";
callIndirect->isReturn = false;
callIndirect->type = wasm::Type::i32;
visit_basic(callIndirect);
}
bool function_visitor::visit_variable_mp(const std::string &name) {
GLAM_COMPILER_TRACE("visit_variable_mp " << name);
if (name == parent->parameter_name) {
auto localGet = parent->module->allocator.alloc<wasm::LocalGet>();
localGet->type = wasm::Type::i32;
localGet->index = 0;
visit_basic(localGet);
return true;
} else {
auto ptr = globals::consts_mp.find(name);
if (ptr == globals::consts_mp.end()) {
return false;
} else {
visit_ptr(ptr->second);
return true;
}
}
}
void function_visitor::visit_binary_splat(wasm::BinaryOp op) {
auto localSetD = parent->module->allocator.alloc<wasm::LocalSet>();
localSetD->index = wasm::Builder::addVar(func, wasm::Type::f64);
visit_basic(localSetD);
auto localSetC = parent->module->allocator.alloc<wasm::LocalSet>();
localSetC->index = wasm::Builder::addVar(func, wasm::Type::f64);
visit_basic(localSetC);
auto localSetB = parent->module->allocator.alloc<wasm::LocalSet>();
localSetB->index = wasm::Builder::addVar(func, wasm::Type::f64);
visit_basic(localSetB);
auto localGetC = parent->module->allocator.alloc<wasm::LocalGet>();
localGetC->index = localSetC->index;
localGetC->type = wasm::Type::f64;
visit_basic(localGetC);
auto inst = parent->module->allocator.alloc<wasm::Binary>();
inst->type = wasm::Type::f64;
inst->op = op;
visit_basic(inst);
auto localGetB = parent->module->allocator.alloc<wasm::LocalGet>();
localGetB->index = localSetB->index;
localGetB->type = wasm::Type::f64;
visit_basic(localGetB);
auto localGetD = parent->module->allocator.alloc<wasm::LocalGet>();
localGetD->index = localSetD->index;
localGetD->type = wasm::Type::f64;
visit_basic(localGetD);
visit_basic(inst);
}
void function_visitor::visit_add() {
GLAM_COMPILER_TRACE("visit_add (dp)");
if (flags & GEN_SIMD) {
} else {
visit_unwrap();
visit_binary_splat(wasm::AddFloat64);
}
}
void function_visitor::visit_sub() {
GLAM_COMPILER_TRACE("visit_sub (dp)");
if (flags & GEN_SIMD) {
} else {
visit_unwrap();
visit_binary_splat(wasm::SubFloat64);
}
}
void function_visitor::visit_mul() {
GLAM_COMPILER_TRACE("visit_mul (dp)");
if (flags & GEN_SIMD) {
} else {
visit_unwrap();
wasm::Index i = visit_binary();
auto localGetC = parent->module->allocator.alloc<wasm::LocalGet>();
localGetC->index = i + 1;
localGetC->type = wasm::Type::f64;
auto mul = parent->module->allocator.alloc<wasm::Binary>();
mul->type = wasm::Type::f64;
mul->op = wasm::MulFloat64;
auto localGetB = parent->module->allocator.alloc<wasm::LocalGet>();
localGetB->index = i + 2;
localGetB->type = wasm::Type::f64;
auto localGetA = parent->module->allocator.alloc<wasm::LocalGet>();
localGetA->index = i + 3;
localGetA->type = wasm::Type::f64;
auto localGetD = parent->module->allocator.alloc<wasm::LocalGet>();
localGetD->index = i;
localGetD->type = wasm::Type::f64;
auto add = parent->module->allocator.alloc<wasm::Binary>();
add->type = wasm::Type::f64;
add->op = wasm::AddFloat64;
auto sub = parent->module->allocator.alloc<wasm::Binary>();
sub->type = wasm::Type::f64;
sub->op = wasm::SubFloat64;
visit_basic(localGetC);
visit_basic(mul);
visit_basic(localGetB);
visit_basic(localGetD);
visit_basic(mul);
visit_basic(sub);
visit_basic(localGetA);
visit_basic(localGetD);
visit_basic(mul);
visit_basic(localGetB);
visit_basic(localGetC);
visit_basic(mul);
visit_basic(add);
}
}
void function_visitor::visit_div() {
GLAM_COMPILER_TRACE("visit_div (dp)");
if (flags & GEN_SIMD) {
} else {
// we use a morpheme here because division is hard
visit_f64x4(&_fmorpheme_div);
}
}
void function_visitor::visit_f64x2(morpheme_f64x2 *morph) {
GLAM_COMPILER_TRACE("visit_f64x2");
visit_unwrap();
arena_size++;
flags |= USES_F64x2;
auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>();
globalGet->name = "_arena";
globalGet->type = wasm::Type::i32;
visit_basic(globalGet);
visit_ptr(morph);
auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>();
callIndirect->type = wasm::Type::i32;
callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::f64, wasm::Type::f64, wasm::Type::i32 }), wasm::Type::i32); // (ddi)->i
callIndirect->table = "table";
callIndirect->isReturn = false;
visit_basic(callIndirect);
needs_unwrap = true;
}
wasm::Index function_visitor::visit_binary() {
flags |= USES_BINARY;
// (a, b) (c, d)
wasm::Index var = wasm::Builder::addVar(func, wasm::Type::f64);
auto localSet1 = parent->module->allocator.alloc<wasm::LocalSet>();
localSet1->index = var;
visit_basic(localSet1);
auto localSet2 = parent->module->allocator.alloc<wasm::LocalSet>();
localSet2->index = wasm::Builder::addVar(func, wasm::Type::f64);
visit_basic(localSet2);
auto localSet3 = parent->module->allocator.alloc<wasm::LocalSet>();
localSet3->index = wasm::Builder::addVar(func, wasm::Type::f64);
visit_basic(localSet3);
auto localSet4 = parent->module->allocator.alloc<wasm::LocalSet>();
localSet4->index = wasm::Builder::addVar(func, wasm::Type::f64);
localSet4->type = wasm::Type::f64;
visit_basic(localSet4);
return var;
}
void function_visitor::visit_unwrap() {
if (needs_unwrap) {
GLAM_COMPILER_TRACE("visit_unwrap");
this->flags |= USES_UNWRAP;
visit_dupi32();
auto loadIm = parent->module->allocator.alloc<wasm::Load>();
loadIm->type = wasm::Type::f64;
loadIm->offset = 8; // get the imaginary part first
loadIm->bytes = 8;
loadIm->isAtomic = false;
visit_basic(loadIm);
auto localSet = parent->module->allocator.alloc<wasm::LocalSet>();
localSet->index = wasm::Builder::addVar(func, wasm::Type::f64);
visit_basic(localSet);
auto loadRe = parent->module->allocator.alloc<wasm::Load>();
loadRe->type = wasm::Type::f64;
loadRe->offset = 0;
loadRe->bytes = 8;
loadRe->isAtomic = false;
visit_basic(loadRe);
auto localGet1 = parent->module->allocator.alloc<wasm::LocalGet>();
localGet1->index = localSet->index;
localGet1->type = wasm::Type::f64;
visit_basic(localGet1);
needs_unwrap = false;
}
}
void function_visitor::visit_f64x4(morpheme_f64x4 *morph) {
GLAM_COMPILER_TRACE("visit_f64x4");
visit_unwrap();
arena_size++;
flags |= USES_F64x4;
auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>();
globalGet->name = "_arena";
globalGet->type = wasm::Type::i32;
visit_basic(globalGet);
visit_ptr(morph);
auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>();
callIndirect->type = wasm::Type::i32;
callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::f64, wasm::Type::f64, wasm::Type::f64, wasm::Type::f64, wasm::Type::i32 }),
wasm::Type::i32); // (ddddi)->i
callIndirect->table = "table";
callIndirect->isReturn = false;
visit_basic(callIndirect);
needs_unwrap = true;
}
void function_visitor::visit_fxncall(const std::string &name) {
uintptr_t ptr = globals::fxn_table[name];
assert(ptr); // should never fail, the parser checks first
GLAM_COMPILER_TRACE("visit_fxncall " << name << " @ " << ptr);
auto c = parent->module->allocator.alloc<wasm::Const>();
c->type = wasm::Type::i32;
c->value = wasm::Literal(static_cast<uint32_t>(ptr));
visit_basic(c);
// todo for now we assume that it's also a double-precision fxn, i.e. it is (f64, f64)->i32
auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>();
callIndirect->isReturn = false;
callIndirect->sig = wasm::Signature({ wasm::Type::f64, wasm::Type::f64 }, wasm::Type::i32);
callIndirect->table = "table";
callIndirect->type = wasm::Type::i32;
visit_basic(callIndirect);
needs_unwrap = true;
}
bool function_visitor::visit_variable_dp(const std::string &name) {
GLAM_COMPILER_TRACE("visit_variable_dp " << name);
visit_unwrap();
if (name == parent->parameter_name) {
auto localGet = parent->module->allocator.alloc<wasm::LocalGet>();
localGet->type = wasm::Type::f64;
localGet->index = 0;
visit_basic(localGet);
localGet = parent->module->allocator.alloc<wasm::LocalGet>();
localGet->type = wasm::Type::f64;
localGet->index = 1;
visit_basic(localGet);
return true;
} else {
auto z = globals::consts_dp.find(name);
if (z == globals::consts_dp.end()) {
return false;
} else {
visit_complex(z->second);
return true;
}
}
}
void function_visitor::visit_dupi32() {
// wasm doesn't have a dup opcode so this is what we have to do
auto localTee = parent->module->allocator.alloc<wasm::LocalSet>();
localTee->type = wasm::Type::i32;
localTee->index = wasm::Builder::addVar(func, wasm::Type::i32);
visit_basic(localTee);
auto localGet0 = parent->module->allocator.alloc<wasm::LocalGet>();
localGet0->type = wasm::Type::i32;
localGet0->index = localTee->index;
visit_basic(localGet0);
}
void function_visitor::visit_dupf64() {
flags |= USES_DUPF64;
auto localTee = parent->module->allocator.alloc<wasm::LocalSet>();
localTee->type = wasm::Type::f64;
localTee->index = wasm::Builder::addVar(func, wasm::Type::f64);
visit_basic(localTee);
auto localGet0 = parent->module->allocator.alloc<wasm::LocalGet>();
localGet0->type = wasm::Type::f64;
localGet0->index = localTee->index;
visit_basic(localGet0);
}
function_visitor::~function_visitor() noexcept {
delete this->func;
}
std::string function_visitor::visit_end() {
GLAM_COMPILER_TRACE("visit_end function");
if (!needs_unwrap) {
// now we actually need to wrap
GLAM_COMPILER_TRACE("wrapping complex");
visit_f64x2(&_fmorpheme_wrap);
}
auto ret = parent->module->allocator.alloc<wasm::Return>();
visit_basic(ret);
parent->module->addFunction(func);
return func->name.c_str();
}
std::map<std::string, morpheme_f64x2 *> math_compiler_dp::unary_morphemes = { std::make_pair("sin", &_fmorpheme_sin),
std::make_pair("cos", &_fmorpheme_cos), std::make_pair("tan", &_fmorpheme_tan), std::make_pair("sinh", &_fmorpheme_sinh),
std::make_pair("cosh", &_fmorpheme_cosh), std::make_pair("tanh", &_fmorpheme_tanh) };
std::map<std::string, morpheme_f64x4 *> math_compiler_dp::binary_morphemes = { std::make_pair("^", &_fmorpheme_exp) };
void math_compiler_dp::visit_operator(function_visitor *fv, const std::string &op) {
GLAM_COMPILER_TRACE("compiling operator " << op);
if (op == "+") {
fv->visit_add();
return;
} else if (op == "-") {
fv->visit_sub();
return;
} else if (op == "*") {
fv->visit_mul();
return;
} else if (op == "/") {
fv->visit_div();
return;
} else {
auto iter1 = unary_morphemes.find(op);
if (iter1 != unary_morphemes.end()) {
fv->visit_f64x2(*iter1->second);
return;
} else {
auto iter2 = binary_morphemes.find(op);
if (iter2 != binary_morphemes.end()) {
fv->visit_f64x4(*iter2->second);
return;
}
}
}
GLAM_COMPILER_TRACE("unrecognized operator");
abort();
}
fxn<std::complex<double>, compiled_fxn<std::complex<double>>> math_compiler_dp::compile(const emscripten::val &stack) {
module_visitor mv(fxn_name, parameter_name);
mv.visit_module();
auto fv = mv.visit_function(name, wasm::Signature({ wasm::Type::f64, wasm::Type::f64 }, wasm::Type::i32));
const auto len = stack["length"].as<size_t>();
assert(len > 0);
for (size_t i = 0; i < len; i++) {
emscripten::val stackObj = stack[i];
auto type = stackObj["type"].as<int32_t>();
auto value = stackObj["value"].as<std::string>();
switch (type) {
case 0: // NUMBER
// we take advantage of boost's parsing even if we don't want a multiprecision complex number
fv->visit_complex(mp_complex(value).convert_to<std::complex<double>>());
break;
case 1: // IDENTIFIER
if (!fv->visit_variable_dp(value)) {
mv.abort();
abort();
}
break;
case 2: // OPERATOR
visit_operator(fv, value);
break;
case 3: // FXNCALL
fv->visit_fxncall(value);
break;
default:
GLAM_COMPILER_TRACE("unrecognized stack object " << type);
mv.abort();
abort();
}
}
fv->visit_entry_point();
auto f_name = fv->visit_end();
mv.visit_export(f_name, name);
return mv.visit_end<std::complex<double>>();
}
| 35.022654 | 140 | 0.640362 | glammath |
a7dec0fd98ba900c1a7008a69f24db37baf08b54 | 4,543 | cpp | C++ | src/Core/src/simple_face.cpp | rosecodym/space-boundary-tool | 300db4084cd19b092bdf2e8432da065daeaa7c55 | [
"FSFAP"
] | 6 | 2016-11-01T11:09:00.000Z | 2022-02-15T06:31:58.000Z | src/Core/src/simple_face.cpp | rosecodym/space-boundary-tool | 300db4084cd19b092bdf2e8432da065daeaa7c55 | [
"FSFAP"
] | null | null | null | src/Core/src/simple_face.cpp | rosecodym/space-boundary-tool | 300db4084cd19b092bdf2e8432da065daeaa7c55 | [
"FSFAP"
] | null | null | null | #include "precompiled.h"
#include "cleanup_loop.h"
#include "equality_context.h"
#include "exceptions.h"
#include "sbt-core.h"
#include "stringification.h"
#include "simple_face.h"
namespace {
typedef std::vector<point_3> loop;
loop create_loop(const polyloop & p, equality_context * c) {
std::vector<ipoint_3> pts;
for (size_t i = 0; i < p.vertex_count; ++i) {
pts.push_back(ipoint_3(p.vertices[i].x, p.vertices[i].y, p.vertices[i].z));
}
loop res;
if (geometry_common::cleanup_loop(&pts, c->height_epsilon())) {
boost::transform(pts, std::back_inserter(res), [c](const ipoint_3 & p) { return c->request_point(p.x(), p.y(), p.z()); });
}
return res;
}
} // namespace
simple_face::simple_face(
const face & f,
bool force_planar,
equality_context * c)
{
using boost::transform;
using geometry_common::calculate_plane_and_average_point;
using geometry_common::share_sense;
auto raw_loop = create_loop(f.outer_boundary, c);
if (raw_loop.size() < 3) { throw invalid_face_exception(); }
plane_3 raw_pl;
std::tie(raw_pl, m_average_point) =
calculate_plane_and_average_point(raw_loop, *c);
if (raw_pl.is_degenerate()) { throw invalid_face_exception(); }
auto snapped_dir = c->snap(raw_pl.orthogonal_direction());
m_plane = plane_3(m_average_point, snapped_dir);
auto project = [this](const point_3 & p) { return m_plane.projection(p); };
if (force_planar) {
transform(raw_loop, std::back_inserter(m_outer), project);
}
else {
m_outer = raw_loop;
}
for (size_t i = 0; i < f.void_count; ++i) {
auto inner = create_loop(f.voids[i], c);
auto inner_pl =
std::get<0>(calculate_plane_and_average_point(inner, *c));
auto inner_dir = inner_pl.orthogonal_direction();
if (!share_sense(m_plane.orthogonal_direction(), inner_dir)) {
boost::reverse(inner);
}
if (force_planar) {
m_inners.push_back(loop());
transform(inner, std::back_inserter(m_inners.back()), project);
}
else {
m_inners.push_back(inner);
}
}
#ifndef NDEBUG
direction_3 normal = m_plane.orthogonal_direction();
debug_dx = CGAL::to_double(normal.dx());
debug_dy = CGAL::to_double(normal.dy());
debug_dz = CGAL::to_double(normal.dz());
#endif
}
simple_face & simple_face::operator = (simple_face && src) {
if (&src != this) {
m_outer = std::move(src.m_outer);
m_inners = std::move(src.m_inners);
m_plane = std::move(src.m_plane);
m_average_point = std::move(src.m_average_point);
}
return *this;
}
bool simple_face::is_planar() const {
for (auto p = m_outer.begin(); p != m_outer.end(); ++p) {
if (!m_plane.has_on(*p)) { return false; }
}
for (auto hole = m_inners.begin(); hole != m_inners.end(); ++hole) {
for (auto p = hole->begin(); p != hole->end(); ++p) {
if (!m_plane.has_on(*p)) { return false; }
}
}
return true;
}
std::string simple_face::to_string() const {
std::stringstream ss;
ss << "Outer:\n";
for (auto p = m_outer.begin(); p != m_outer.end(); ++p) {
ss << reporting::to_string(*p) << std::endl;
}
for (auto hole = m_inners.begin(); hole != m_inners.end(); ++hole) {
ss << "Hole:\n";
for (auto p = hole->begin(); p != hole->end(); ++p) {
ss << reporting::to_string(*p) << std::endl;
}
}
return ss.str();
}
simple_face simple_face::reversed() const {
typedef std::vector<point_3> loop;
std::vector<loop> inners;
boost::transform(
m_inners,
std::back_inserter(inners),
[](const loop & inner) { return loop(inner.rbegin(), inner.rend()); });
return simple_face(
m_outer | boost::adaptors::reversed,
inners,
m_plane.opposite(),
m_average_point);
}
std::vector<segment_3> simple_face::all_edges_voids_reversed() const {
std::vector<segment_3> res;
for (size_t i = 0; i < m_outer.size(); ++i) {
res.push_back(segment_3(m_outer[i], m_outer[(i+1) % m_outer.size()]));
}
res.push_back(segment_3(m_outer.back(), m_outer.front()));
boost::for_each(m_inners, [&res](const std::vector<point_3> & inner) {
for (size_t i = 0; i < inner.size(); ++i) {
res.push_back(segment_3(inner[(i+1) % inner.size()], inner[i]));
}
res.push_back(segment_3(inner.front(), inner.back()));
});
return res;
}
simple_face simple_face::transformed(const transformation_3 & t) const {
loop new_outer;
boost::transform(m_outer, std::back_inserter(new_outer), t);
std::vector<loop> new_inners;
for (auto h = m_inners.begin(); h != m_inners.end(); ++h) {
new_inners.push_back(loop());
boost::transform(*h, std::back_inserter(new_inners.back()), t);
}
return simple_face(new_outer, new_inners, t(m_plane), t(m_average_point));
} | 28.572327 | 124 | 0.673784 | rosecodym |
a7dffd0919a0fea4d1d18d9f854a2712191faf87 | 11,425 | cpp | C++ | src/mongocxx/test/sdam-monitoring.cpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/test/sdam-monitoring.cpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/test/sdam-monitoring.cpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018-present MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <set>
#include <bsoncxx/stdx/optional.hpp>
#include <bsoncxx/string/to_string.hpp>
#include <bsoncxx/test_util/catch.hh>
#include <mongocxx/client.hpp>
#include <mongocxx/exception/exception.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/test/spec/operation.hh>
#include <mongocxx/test_util/client_helpers.hh>
// Don't use SDAM Monitoring spec tests, we'd need libmongoc internals to send hello replies.
namespace {
using namespace mongocxx;
using bsoncxx::oid;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::string::to_string;
void open_and_close_client(const uri& test_uri, const options::apm& apm_opts) {
// Apply listeners and trigger connection.
options::client client_opts;
client_opts.apm_opts(apm_opts);
client client{test_uri, test_util::add_test_server_api(client_opts)};
client["admin"].run_command(make_document(kvp("ping", 1)));
}
TEST_CASE("SDAM Monitoring", "[sdam_monitoring]") {
instance::current();
std::string rs_name;
uri test_uri;
client discoverer{uri{}, test_util::add_test_server_api()};
auto topology_type = test_util::get_topology(discoverer);
if (topology_type == "replicaset") {
rs_name = test_util::replica_set_name(discoverer);
test_uri = uri{"mongodb://localhost/?replicaSet=" + rs_name};
}
options::apm apm_opts;
stdx::optional<oid> topology_id;
SECTION("Server Events") {
int server_opening_events = 0;
int server_changed_events = 0;
///////////////////////////////////////////////////////////////////////
// Begin server description listener lambdas
///////////////////////////////////////////////////////////////////////
// ServerOpeningEvent
apm_opts.on_server_opening([&](const events::server_opening_event& event) {
server_opening_events++;
if (topology_id) {
// A previous server was opened first.
REQUIRE(topology_id.value() == event.topology_id());
}
topology_id = event.topology_id();
});
// ServerDescriptionChanged
apm_opts.on_server_changed([&](const events::server_changed_event& event) {
server_changed_events++;
// A server_opening_event should have set topology_id.
REQUIRE(topology_id);
REQUIRE(topology_id.value() == event.topology_id());
auto old_sd = event.previous_description();
auto new_sd = event.new_description();
auto new_type = to_string(new_sd.type());
REQUIRE(old_sd.hello().empty());
REQUIRE(to_string(old_sd.host()) == to_string(event.host()));
REQUIRE(old_sd.port() == event.port());
REQUIRE(old_sd.round_trip_time() == -1);
REQUIRE(to_string(old_sd.type()) == "Unknown");
REQUIRE(to_string(new_sd.host()) == to_string(event.host()));
REQUIRE_FALSE(new_sd.hello().empty());
REQUIRE(new_sd.port() == event.port());
REQUIRE(new_sd.round_trip_time() >= 0);
if (topology_type == "single") {
REQUIRE(new_type == "Standalone");
} else if (topology_type == "replicaset") {
// RSPrimary, RSSecondary, etc.
REQUIRE(new_type.substr(0, 2) == "RS");
} else {
REQUIRE(topology_type == "sharded");
REQUIRE(new_type == "Mongos");
}
REQUIRE(old_sd.id() == new_sd.id());
});
// We don't expect a ServerClosedEvent unless a replica set member is removed.
///////////////////////////////////////////////////////////////////////
// End server description listener lambdas
///////////////////////////////////////////////////////////////////////
open_and_close_client(test_uri, apm_opts);
REQUIRE(server_opening_events > 0);
REQUIRE(server_changed_events > 0);
}
SECTION("Topology Events") {
int topology_opening_events = 0;
int topology_changed_events = 0;
int topology_closed_events = 0;
bool found_servers = false;
///////////////////////////////////////////////////////////////////////
// Begin topology description listener lambdas
///////////////////////////////////////////////////////////////////////
// TopologyOpeningEvent
apm_opts.on_topology_opening([&](const events::topology_opening_event& event) {
topology_opening_events++;
if (topology_id) {
// A previous server was opened first.
REQUIRE(topology_id.value() == event.topology_id());
}
topology_id = event.topology_id();
});
// TopologyDescriptionChanged
apm_opts.on_topology_changed([&](const events::topology_changed_event& event) {
topology_changed_events++;
// A topology_opening_event should have set topology_id.
REQUIRE(topology_id);
REQUIRE(topology_id.value() == event.topology_id());
auto old_td = event.previous_description();
auto new_td = event.new_description();
auto new_type = to_string(new_td.type());
auto new_servers = new_td.servers();
if (topology_changed_events == 1) {
// First event, nothing discovered yet.
REQUIRE(old_td.servers().size() == 0);
REQUIRE_FALSE(old_td.has_readable_server(read_preference{}));
REQUIRE_FALSE(old_td.has_writable_server());
}
if (topology_type == "replicaset") {
if (new_td.has_writable_server()) {
REQUIRE(new_type == "ReplicaSetWithPrimary");
} else {
REQUIRE(new_type == "ReplicaSetNoPrimary");
}
} else {
REQUIRE(new_type == "Single");
}
for (auto&& new_sd : new_servers) {
found_servers = true;
auto new_sd_type = to_string(new_sd.type());
REQUIRE(new_sd.host().length());
REQUIRE_FALSE(new_sd.hello().empty());
REQUIRE(new_sd.port() > 0);
REQUIRE(new_sd.round_trip_time() >= 0);
if (topology_type == "single") {
REQUIRE(new_sd_type == "Standalone");
} else if (topology_type == "replicaset") {
// RSPrimary, RSSecondary, etc.
REQUIRE(new_sd_type.substr(0, 2) == "RS");
} else {
REQUIRE(topology_type == "sharded");
REQUIRE(new_sd_type == "Mongos");
}
}
});
// TopologyClosedEvent
apm_opts.on_topology_closed([&](const events::topology_closed_event& event) {
topology_closed_events++;
REQUIRE(topology_id.value() == event.topology_id());
});
///////////////////////////////////////////////////////////////////////
// End topology description listener lambdas
///////////////////////////////////////////////////////////////////////
open_and_close_client(test_uri, apm_opts);
REQUIRE(topology_opening_events > 0);
REQUIRE(topology_changed_events > 0);
REQUIRE(topology_closed_events > 0);
REQUIRE(found_servers);
}
SECTION("Heartbeat Events") {
int heartbeat_started_events = 0;
int heartbeat_succeeded_events = 0;
auto mock_started_awaited =
libmongoc::apm_server_heartbeat_started_get_awaited.create_instance();
auto mock_succeeded_awaited =
libmongoc::apm_server_heartbeat_succeeded_get_awaited.create_instance();
bool started_awaited_called = false;
bool succeeded_awaited_called = false;
mock_started_awaited->visit(
[&](const mongoc_apm_server_heartbeat_started_t*) { started_awaited_called = true; });
mock_succeeded_awaited->visit([&](const mongoc_apm_server_heartbeat_succeeded_t*) {
succeeded_awaited_called = true;
});
///////////////////////////////////////////////////////////////////////
// Begin heartbeat listener lambdas
///////////////////////////////////////////////////////////////////////
// ServerHeartbeatStartedEvent
apm_opts.on_heartbeat_started([&](const events::heartbeat_started_event& event) {
heartbeat_started_events++;
REQUIRE_FALSE(event.host().empty());
REQUIRE(event.port() != 0);
// Client is single-threaded, and will never perform an awaitable hello.
REQUIRE(!event.awaited());
});
// ServerHeartbeatSucceededEvent
apm_opts.on_heartbeat_succeeded([&](const events::heartbeat_succeeded_event& event) {
heartbeat_succeeded_events++;
REQUIRE_FALSE(event.host().empty());
REQUIRE(event.port() != 0);
REQUIRE_FALSE(event.reply().empty());
// Client is single-threaded, and will never perform an awaitable hello.
REQUIRE(!event.awaited());
});
// Don't expect a ServerHeartbeatFailedEvent here, see the test below.
///////////////////////////////////////////////////////////////////////
// End heartbeat listener lambdas
///////////////////////////////////////////////////////////////////////
open_and_close_client(test_uri, apm_opts);
REQUIRE(heartbeat_started_events > 0);
REQUIRE(heartbeat_succeeded_events > 0);
REQUIRE(started_awaited_called);
REQUIRE(succeeded_awaited_called);
}
}
TEST_CASE("Heartbeat failed event", "[sdam_monitoring]") {
instance::current();
options::apm apm_opts;
bool failed_awaited_called = false;
auto mock_failed_awaited = libmongoc::apm_server_heartbeat_failed_get_awaited.create_instance();
mock_failed_awaited->visit(
[&](const mongoc_apm_server_heartbeat_failed_t*) { failed_awaited_called = true; });
int heartbeat_failed_events = 0;
// ServerHeartbeatFailedEvent
apm_opts.on_heartbeat_failed([&](const events::heartbeat_failed_event& event) {
heartbeat_failed_events++;
REQUIRE_FALSE(event.host().empty());
REQUIRE_FALSE(event.message().empty());
REQUIRE(event.port() != 0);
REQUIRE(!event.awaited());
});
REQUIRE_THROWS_AS(
open_and_close_client(uri{"mongodb://bad-host/?connectTimeoutMS=1"}, apm_opts),
mongocxx::exception);
REQUIRE(heartbeat_failed_events > 0);
REQUIRE(failed_awaited_called);
}
} // namespace
| 39.396552 | 100 | 0.569278 | lzlzymy |
a7e1429e15be464fa4e2a5469cf160ad9145f864 | 1,009 | cpp | C++ | src/Kernel/VideoDecoder.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 39 | 2016-04-21T03:25:26.000Z | 2022-01-19T14:16:38.000Z | src/Kernel/VideoDecoder.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 23 | 2016-06-28T13:03:17.000Z | 2022-02-02T10:11:54.000Z | src/Kernel/VideoDecoder.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 14 | 2016-06-22T20:45:37.000Z | 2021-07-05T12:25:19.000Z | #include "VideoDecoder.h"
#include "Kernel/AssertionMemoryPanic.h"
#include "Kernel/AssertionType.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
VideoDecoder::VideoDecoder()
{
}
//////////////////////////////////////////////////////////////////////////
VideoDecoder::~VideoDecoder()
{
}
//////////////////////////////////////////////////////////////////////////
void VideoDecoder::setCodecDataInfo( const CodecDataInfo * _dataInfo )
{
MENGINE_ASSERTION_MEMORY_PANIC( _dataInfo );
MENGINE_ASSERTION_TYPE( _dataInfo, const VideoCodecDataInfo * );
m_dataInfo = *static_cast<const VideoCodecDataInfo *>(_dataInfo);
}
//////////////////////////////////////////////////////////////////////////
const VideoCodecDataInfo * VideoDecoder::getCodecDataInfo() const
{
return &m_dataInfo;
}
//////////////////////////////////////////////////////////////////////////
}
| 32.548387 | 78 | 0.418236 | irov |
a7e395319bfdef5c234886d2b136295a3be6f8e6 | 23,974 | hpp | C++ | src/AFQMC/HamiltonianOperations/Real3IndexFactorization.hpp | kayahans/qmcpack | c25d77702e36363ff7368ded783bf31c1b1c5f17 | [
"NCSA"
] | null | null | null | src/AFQMC/HamiltonianOperations/Real3IndexFactorization.hpp | kayahans/qmcpack | c25d77702e36363ff7368ded783bf31c1b1c5f17 | [
"NCSA"
] | null | null | null | src/AFQMC/HamiltonianOperations/Real3IndexFactorization.hpp | kayahans/qmcpack | c25d77702e36363ff7368ded783bf31c1b1c5f17 | [
"NCSA"
] | null | null | null | //////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source
// License. See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by:
// Miguel A. Morales, moralessilva2@llnl.gov
// Lawrence Livermore National Laboratory
//
// File created by:
// Miguel A. Morales, moralessilva2@llnl.gov
// Lawrence Livermore National Laboratory
////////////////////////////////////////////////////////////////////////////////
#ifndef QMCPLUSPLUS_AFQMC_HAMILTONIANOPERATIONS_REAL3INDEXFACTORIZATION_HPP
#define QMCPLUSPLUS_AFQMC_HAMILTONIANOPERATIONS_REAL3INDEXFACTORIZATION_HPP
#include <vector>
#include <type_traits>
#include <random>
#include "Configuration.h"
#include "AFQMC/config.h"
#include "mpi3/shared_communicator.hpp"
#include "multi/array.hpp"
#include "multi/array_ref.hpp"
#include "AFQMC/Numerics/ma_operations.hpp"
#include "AFQMC/Utilities/type_conversion.hpp"
#include "AFQMC/Utilities/taskgroup.h"
namespace qmcplusplus
{
namespace afqmc
{
// MAM: to make the working precision of this class a template parameter,
// sed away SPComplexType by another type ( which is then defined through a template parameter)
// This should be enough, since some parts are kept at ComplexType precision
// defined through the cmake
// Custom implementation for real build
class Real3IndexFactorization
{
using sp_pointer = SPComplexType*;
using const_sp_pointer = SPComplexType const*;
using IVector = boost::multi::array<int,1>;
using CVector = boost::multi::array<ComplexType,1>;
using SpVector = boost::multi::array<SPComplexType,1>;
using CMatrix = boost::multi::array<ComplexType,2>;
using CMatrix_cref = boost::multi::array_cref<ComplexType,2>;
using CMatrix_ref = boost::multi::array_ref<ComplexType,2>;
using CVector_ref = boost::multi::array_ref<ComplexType,1>;
using RMatrix = boost::multi::array<RealType,2>;
using RMatrix_cref = boost::multi::array_cref<RealType,2>;
using RMatrix_ref = boost::multi::array_ref<RealType,2>;
using RVector_ref = boost::multi::array_ref<RealType,1>;
using SpCMatrix = boost::multi::array<SPComplexType,2>;
using SpCMatrix_cref = boost::multi::array_cref<SPComplexType,2>;
using SpCVector_ref = boost::multi::array_ref<SPComplexType,1>;
using SpCMatrix_ref = boost::multi::array_ref<SPComplexType,2>;
using SpRMatrix = boost::multi::array<SPRealType,2>;
using SpRMatrix_cref = boost::multi::array_cref<SPRealType,2>;
using SpRVector_ref = boost::multi::array_ref<SPRealType,1>;
using SpRMatrix_ref = boost::multi::array_ref<SPRealType,2>;
using C3Tensor = boost::multi::array<ComplexType,3>;
using SpC3Tensor = boost::multi::array<SPComplexType,3>;
using SpC3Tensor_ref = boost::multi::array_ref<SPComplexType,3>;
using SpC4Tensor_ref = boost::multi::array_ref<SPComplexType,4>;
using shmCVector = boost::multi::array<ComplexType,1,shared_allocator<ComplexType>>;
using shmRMatrix = boost::multi::array<RealType,2,shared_allocator<RealType>>;
using shmCMatrix = boost::multi::array<ComplexType,2,shared_allocator<ComplexType>>;
using shmC3Tensor = boost::multi::array<ComplexType,3,shared_allocator<ComplexType>>;
using shmSpRVector = boost::multi::array<SPRealType,1,shared_allocator<SPRealType>>;
using shmSpRMatrix = boost::multi::array<SPRealType,2,shared_allocator<SPRealType>>;
using shmSpCMatrix = boost::multi::array<SPComplexType,2,shared_allocator<SPComplexType>>;
using shmSpC3Tensor = boost::multi::array<SPComplexType,3,shared_allocator<SPComplexType>>;
using this_t = Real3IndexFactorization;
public:
static const HamiltonianTypes HamOpType = RealDenseFactorized;
HamiltonianTypes getHamType() const { return HamOpType; }
Real3IndexFactorization(afqmc::TaskGroup_& tg_,
WALKER_TYPES type,
shmRMatrix&& hij_,
shmCMatrix&& haj_,
shmSpRMatrix&& vik,
shmSpCMatrix&& vak,
std::vector<shmSpC3Tensor>&& vank,
shmCMatrix&& vn0_,
ValueType e0_,
int cv0,
int gncv):
TG(tg_),
walker_type(type),
global_origin(cv0),
global_nCV(gncv),
local_nCV(0),
E0(e0_),
hij(std::move(hij_)),
haj(std::move(haj_)),
Likn(std::move(vik)),
Lank(std::move(vank)),
Lakn(std::move(vak)),
vn0(std::move(vn0_)),
SM_TMats({1,1},shared_allocator<SPComplexType>{TG.TG_local()})
{
local_nCV=Likn.size(1);
TG.Node().barrier();
}
~Real3IndexFactorization() {}
Real3IndexFactorization(const Real3IndexFactorization& other) = delete;
Real3IndexFactorization& operator=(const Real3IndexFactorization& other) = delete;
Real3IndexFactorization(Real3IndexFactorization&& other) = default;
Real3IndexFactorization& operator=(Real3IndexFactorization&& other) = delete;
CMatrix getOneBodyPropagatorMatrix(TaskGroup_& TG, boost::multi::array<ComplexType,1> const& vMF)
{
int NMO = hij.size(0);
// in non-collinear case with SO, keep SO matrix here and add it
// for now, stay collinear
CMatrix H1({NMO,NMO});
// add sum_n vMF*Spvn, vMF has local contribution only!
boost::multi::array_ref<ComplexType,1> H1D(H1.origin(),{NMO*NMO});
std::fill_n(H1D.origin(),H1D.num_elements(),ComplexType(0));
vHS(vMF, H1D);
TG.TG().all_reduce_in_place_n(H1D.origin(),H1D.num_elements(),std::plus<>());
// add hij + vn0 and symmetrize
using ma::conj;
for(int i=0; i<NMO; i++) {
H1[i][i] += hij[i][i] + vn0[i][i];
for(int j=i+1; j<NMO; j++) {
H1[i][j] += hij[i][j] + vn0[i][j];
H1[j][i] += hij[j][i] + vn0[j][i];
// This is really cutoff dependent!!!
if( std::abs( H1[i][j] - ma::conj(H1[j][i]) ) > 1e-6 ) {
app_error()<<" WARNING in getOneBodyPropagatorMatrix. H1 is not hermitian. \n";
app_error()<<i <<" " <<j <<" " <<H1[i][j] <<" " <<H1[j][i] <<" "
<<hij[i][j] <<" " <<hij[j][i] <<" "
<<vn0[i][j] <<" " <<vn0[j][i] <<std::endl;
//APP_ABORT("Error in getOneBodyPropagatorMatrix. H1 is not hermitian. \n");
}
H1[i][j] = 0.5*(H1[i][j]+ma::conj(H1[j][i]));
H1[j][i] = ma::conj(H1[i][j]);
}
}
return H1;
}
template<class Mat, class MatB>
void energy(Mat&& E, MatB const& G, int k, bool addH1=true, bool addEJ=true, bool addEXX=true) {
MatB* Kr(nullptr);
MatB* Kl(nullptr);
energy(E,G,k,Kl,Kr,addH1,addEJ,addEXX);
}
// KEleft and KEright must be in shared memory for this to work correctly
template<class Mat, class MatB, class MatC, class MatD>
void energy(Mat&& E, MatB const& Gc, int nd, MatC* KEleft, MatD* KEright, bool addH1=true, bool addEJ=true, bool addEXX=true) {
assert(E.size(1)>=3);
assert(nd >= 0);
assert(nd < haj.size());
if(walker_type==COLLINEAR)
assert(2*nd+1 < Lank.size());
else
assert(nd < Lank.size());
int nwalk = Gc.size(0);
int nspin = (walker_type==COLLINEAR?2:1);
int NMO = hij.size(0);
int nel[2];
nel[0] = Lank[nspin*nd].size(0);
nel[1] = ((nspin==2)?Lank[nspin*nd+1].size(0):0);
assert(Lank[nspin*nd].size(1) == local_nCV);
assert(Lank[nspin*nd].size(2) == NMO);
if(nspin==2) {
assert(Lank[nspin*nd+1].size(1) == local_nCV);
assert(Lank[nspin*nd+1].size(2) == NMO);
}
assert(Gc.num_elements() == nwalk*(nel[0]+nel[1])*NMO);
int getKr = KEright!=nullptr;
int getKl = KEleft!=nullptr;
if(E.size(0) != nwalk || E.size(1) < 3)
APP_ABORT(" Error in AFQMC/HamiltonianOperations/Real3IndexFactorization::energy(...). Incorrect matrix dimensions \n");
// T[nwalk][nup][nup][local_nCV] + D[nwalk][nwalk][local_nCV]
size_t mem_needs(0);
size_t cnt(0);
if(addEJ) {
#if MIXED_PRECISION
mem_needs += nwalk*local_nCV;
#else
if(not getKl) mem_needs += nwalk*local_nCV;
#endif
}
if(addEXX) {
mem_needs += nwalk*nel[0]*nel[0]*local_nCV;
#if MIXED_PRECISION
mem_needs += nwalk*nel[0]*NMO;
#else
if(nspin == 2) mem_needs += nwalk*nel[0]*NMO;
#endif
}
set_shm_buffer(mem_needs);
// messy
SPComplexType *Klptr(nullptr);
long Knr=0, Knc=0;
if(addEJ) {
Knr=nwalk;
Knc=local_nCV;
if(getKr) {
assert(KEright->size(0) == nwalk && KEright->size(1) == local_nCV);
assert(KEright->stride(0) == KEright->size(1));
}
#if MIXED_PRECISION
if(getKl) {
assert(KEleft->size(0) == nwalk && KEleft->size(1) == local_nCV);
assert(KEleft->stride(0) == KEleft->size(1));
}
#else
if(getKl) {
assert(KEleft->size(0) == nwalk && KEleft->size(1) == local_nCV);
assert(KEleft->stride(0) == KEleft->size(1));
Klptr = to_address(KEleft->origin());
} else
#endif
{
Klptr = to_address(SM_TMats.origin())+cnt;
cnt += Knr*Knc;
}
if(TG.TG_local().root()) std::fill_n(Klptr,Knr*Knc,SPComplexType(0.0));
} else if(getKr or getKl) {
APP_ABORT(" Error: Kr and/or Kl can only be calculated with addEJ=true.\n");
}
SpCMatrix_ref Kl(Klptr,{long(Knr),long(Knc)});
for(int n=0; n<nwalk; n++)
std::fill_n(E[n].origin(),3,ComplexType(0.));
// one-body contribution
// haj[ndet][nocc*nmo]
// not parallelized for now, since it would require customization of Wfn
if(addH1) {
boost::multi::array_cref<ComplexType,1> haj_ref(to_address(haj[nd].origin()), iextensions<1u>{haj[nd].num_elements()});
ma::product(ComplexType(1.),Gc,haj_ref,ComplexType(1.),E(E.extension(0),0));
for(int i=0; i<nwalk; i++)
E[i][0] += E0;
}
// move calculation of H1 here
// NOTE: For CLOSED/NONCOLLINEAR, can do all walkers simultaneously to improve perf. of GEMM
// Not sure how to do it for COLLINEAR.
if(addEXX) {
SPRealType scl = (walker_type==CLOSED?2.0:1.0);
for(int ispin=0, is0=0; ispin<nspin; ispin++) {
size_t cnt_(cnt);
SPComplexType *ptr(nullptr);
#if MIXED_PRECISION
ptr = to_address(SM_TMats.origin())+cnt_;
cnt_ += nwalk*nel[ispin]*NMO;
for(int n=0; n<nwalk; ++n) {
if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue;
copy_n_cast(to_address(Gc[n].origin())+is0,nel[ispin]*NMO,ptr+n*nel[ispin]*NMO);
}
TG.TG_local().barrier();
#else
if(nspin==1) {
ptr = to_address(Gc.origin());
} else {
ptr = to_address(SM_TMats.origin())+cnt_;
cnt_ += nwalk*nel[ispin]*NMO;
for(int n=0; n<nwalk; ++n) {
if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue;
std::copy_n(to_address(Gc[n].origin())+is0,nel[ispin]*NMO,ptr+n*nel[ispin]*NMO);
}
TG.TG_local().barrier();
}
#endif
SpCMatrix_ref GF(ptr,{nwalk*nel[ispin],NMO});
SpCMatrix_ref Lan(to_address(Lank[nd*nspin + ispin].origin()),
{nel[ispin]*local_nCV,NMO});
SpCMatrix_ref Twban(to_address(SM_TMats.origin())+cnt_,{nwalk*nel[ispin],nel[ispin]*local_nCV});
SpC4Tensor_ref T4Dwban(Twban.origin(),{nwalk,nel[ispin],nel[ispin],local_nCV});
long i0, iN;
std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(nel[ispin]*local_nCV),
long(TG.TG_local().size()));
ma::product(GF,ma::T(Lan.sliced(i0,iN)),Twban(Twban.extension(0),{i0,iN}));
TG.TG_local().barrier();
for(int n=0, an=0; n<nwalk; ++n) {
ComplexType E_(0.0);
for(int a=0; a<nel[ispin]; ++a, an++) {
if( an%TG.TG_local().size() != TG.TG_local().rank() ) continue;
for(int b=0; b<nel[ispin]; ++b)
E_ += static_cast<ComplexType>(ma::dot(T4Dwban[n][a][b],T4Dwban[n][b][a]));
}
E[n][1] -= 0.5*scl*E_;
}
if(addEJ) {
for(int n=0; n<nwalk; ++n) {
if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue;
for(int a=0; a<nel[ispin]; ++a)
ma::axpy(SPComplexType(1.0),T4Dwban[n][a][a],Kl[n]);
}
}
is0 += nel[ispin]*NMO;
} // if
}
TG.TG_local().barrier();
if(addEJ) {
if(not addEXX) {
// calculate Kr
APP_ABORT(" Error: Finish addEJ and not addEXX");
}
TG.TG_local().barrier();
SPRealType scl = (walker_type==CLOSED?2.0:1.0);
for(int n=0; n<nwalk; ++n) {
if(n%TG.TG_local().size() == TG.TG_local().rank())
E[n][2] += 0.5*static_cast<ComplexType>(scl*scl*ma::dot(Kl[n],Kl[n]));
}
#if MIXED_PRECISION
if(getKl) {
long i0, iN;
std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(KEleft->num_elements()),
long(TG.TG_local().size()));
copy_n_cast(Klptr+i0,iN-i0,to_address(KEleft->origin())+i0);
}
#endif
if(getKr) {
long i0, iN;
std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(KEright->num_elements()),
long(TG.TG_local().size()));
copy_n_cast(Klptr+i0,iN-i0,to_address(KEright->origin())+i0);
}
TG.TG_local().barrier();
}
}
template<class... Args>
void fast_energy(Args&&... args)
{
APP_ABORT(" Error: fast_energy not implemented in Real3IndexFactorization. \n");
}
template<class MatA, class MatB,
typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==1)>,
typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==1)>,
typename = void
>
void vHS(MatA& X, MatB&& v, double a=1., double c=0.) {
using BType = typename std::decay<MatB>::type::element ;
using AType = typename std::decay<MatA>::type::element ;
boost::multi::array_ref<BType,2> v_(to_address(v.origin()),
{v.size(0),1});
boost::multi::array_ref<const AType,2> X_(to_address(X.origin()),
{X.size(0),1});
return vHS(X_,v_,a,c);
}
template<class MatA, class MatB,
typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==2)>,
typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==2)>
>
void vHS(MatA& X, MatB&& v, double a=1., double c=0.) {
using XType = typename std::decay_t<typename MatA::element>;
using vType = typename std::decay<MatB>::type::element ;
assert( Likn.size(1) == X.size(0) );
assert( Likn.size(0) == v.size(0) );
assert( X.size(1) == v.size(1) );
long ik0, ikN;
std::tie(ik0,ikN) = FairDivideBoundary(long(TG.TG_local().rank()),long(Likn.size(0)),long(TG.TG_local().size()));
// setup buffer space if changing precision in X or v
size_t vmem(0),Xmem(0);
if(not std::is_same<XType,SPComplexType>::value) Xmem = X.num_elements();
if(not std::is_same<vType,SPComplexType>::value) vmem = v.num_elements();
set_shm_buffer(vmem+Xmem);
sp_pointer vptr(nullptr);
const_sp_pointer Xptr(nullptr);
// setup origin of Xsp and copy_n_cast if necessary
if(std::is_same<XType,SPComplexType>::value) {
Xptr = reinterpret_cast<const_sp_pointer>(to_address(X.origin()));
} else {
long i0, iN;
std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),
long(X.num_elements()),long(TG.TG_local().size()));
copy_n_cast(to_address(X.origin())+i0,iN-i0,to_address(SM_TMats.origin())+i0);
Xptr = to_address(SM_TMats.origin());
}
// setup origin of vsp and copy_n_cast if necessary
if(std::is_same<vType,SPComplexType>::value) {
vptr = reinterpret_cast<sp_pointer>(to_address(v.origin()));
} else {
long i0, iN;
std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),
long(v.num_elements()),long(TG.TG_local().size()));
vptr = to_address(SM_TMats.origin())+Xmem;
if( std::abs(c) > 1e-12 )
copy_n_cast(to_address(v.origin())+i0,iN-i0,vptr+i0);
}
// setup array references
boost::multi::array_cref<SPComplexType const,2> Xsp(Xptr, X.extensions());
boost::multi::array_ref<SPComplexType,2> vsp(vptr, v.extensions());
TG.TG_local().barrier();
ma::product(SPValueType(a),Likn.sliced(ik0,ikN),Xsp,
SPValueType(c),vsp.sliced(ik0,ikN));
if(not std::is_same<vType,SPComplexType>::value) {
copy_n_cast(to_address(vsp[ik0].origin()),vsp.size(1)*(ikN-ik0),
to_address(v[ik0].origin()));
}
TG.TG_local().barrier();
}
template<class MatA, class MatB,
typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==1)>,
typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==1)>,
typename = void
>
void vbias(const MatA& G, MatB&& v, double a=1., double c=0., int k=0) {
using BType = typename std::decay<MatB>::type::element ;
using AType = typename std::decay<MatA>::type::element ;
boost::multi::array_ref<BType,2> v_(to_address(v.origin()),
{v.size(0),1});
if(haj.size(0) == 1) {
boost::multi::array_cref<AType,2> G_(to_address(G.origin()),
{1,G.size(0)});
return vbias(G_,v_,a,c,k);
} else {
boost::multi::array_cref<AType,2> G_(to_address(G.origin()),
{G.size(0),1});
return vbias(G_,v_,a,c,k);
}
}
// v(n,w) = sum_ak L(ak,n) G(w,ak)
template<class MatA, class MatB,
typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==2)>,
typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==2)>
>
void vbias(const MatA& G, MatB&& v, double a=1., double c=0., int k=0) {
using GType = typename std::decay_t<typename MatA::element>;
using vType = typename std::decay<MatB>::type::element ;
long ic0, icN;
// setup buffer space if changing precision in G or v
size_t vmem(0),Gmem(0);
if(not std::is_same<GType,SPComplexType>::value) Gmem = G.num_elements();
if(not std::is_same<vType,SPComplexType>::value) vmem = v.num_elements();
set_shm_buffer(vmem+Gmem);
const_sp_pointer Gptr(nullptr);
sp_pointer vptr(nullptr);
// setup origin of Gsp and copy_n_cast if necessary
if(std::is_same<GType,SPComplexType>::value) {
Gptr = reinterpret_cast<const_sp_pointer>(to_address(G.origin()));
} else {
long i0, iN;
std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),
long(G.num_elements()),long(TG.TG_local().size()));
copy_n_cast(to_address(G.origin())+i0,iN-i0,to_address(SM_TMats.origin())+i0);
Gptr = to_address(SM_TMats.origin());
}
// setup origin of vsp and copy_n_cast if necessary
if(std::is_same<vType,SPComplexType>::value) {
vptr = reinterpret_cast<sp_pointer>(to_address(v.origin()));
} else {
long i0, iN;
std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),
long(v.num_elements()),long(TG.TG_local().size()));
vptr = to_address(SM_TMats.origin())+Gmem;
if( std::abs(c) > 1e-12 )
copy_n_cast(to_address(v.origin())+i0,iN-i0,vptr+i0);
}
// setup array references
boost::multi::array_cref<SPComplexType const,2> Gsp(Gptr, G.extensions());
boost::multi::array_ref<SPComplexType,2> vsp(vptr, v.extensions());
TG.TG_local().barrier();
if(haj.size(0) == 1) {
assert( Lakn.size(0) == G.size(1) );
assert( Lakn.size(1) == v.size(0) );
assert( G.size(0) == v.size(1) );
std::tie(ic0,icN) = FairDivideBoundary(long(TG.TG_local().rank()),
long(Lakn.size(1)),long(TG.TG_local().size()));
if(walker_type==CLOSED) a*=2.0;
ma::product(SPValueType(a),ma::T(Lakn(Lakn.extension(0),{ic0,icN})),ma::T(Gsp),
SPValueType(c),vsp.sliced(ic0,icN));
} else {
// multideterminant is not half-rotated, so use Likn
assert( Likn.size(0) == G.size(0) );
assert( Likn.size(1) == v.size(0) );
assert( G.size(1) == v.size(1) );
std::tie(ic0,icN) = FairDivideBoundary(long(TG.TG_local().rank()),
long(Likn.size(1)),long(TG.TG_local().size()));
if(walker_type==CLOSED) a*=2.0;
ma::product(SPValueType(a),ma::T(Likn(Likn.extension(0),{ic0,icN})),Gsp,
SPValueType(c),vsp.sliced(ic0,icN));
}
// copy data back if changing precision
if(not std::is_same<vType,SPComplexType>::value) {
copy_n_cast(to_address(vsp[ic0].origin()),vsp.size(1)*(icN-ic0),
to_address(v[ic0].origin()));
}
TG.TG_local().barrier();
}
template<class Mat, class MatB>
void generalizedFockMatrix(Mat&& G, MatB&& Fp, MatB&& Fm)
{
APP_ABORT(" Error: generalizedFockMatrix not implemented for this hamiltonian.\n");
}
bool distribution_over_cholesky_vectors() const{ return true; }
int number_of_ke_vectors() const{ return local_nCV; }
int local_number_of_cholesky_vectors() const{ return local_nCV; }
int global_number_of_cholesky_vectors() const{ return global_nCV; }
int global_origin_cholesky_vector() const{ return global_origin; }
// transpose=true means G[nwalk][ik], false means G[ik][nwalk]
bool transposed_G_for_vbias() const{ return (haj.size(0) == 1); }
bool transposed_G_for_E() const{return true;}
// transpose=true means vHS[nwalk][ik], false means vHS[ik][nwalk]
bool transposed_vHS() const{return false;}
bool fast_ph_energy() const { return false; }
boost::multi::array<ComplexType,2> getHSPotentials()
{
return boost::multi::array<ComplexType,2>{};
}
private:
afqmc::TaskGroup_& TG;
WALKER_TYPES walker_type;
int global_origin;
int global_nCV;
int local_nCV;
ValueType E0;
// bare one body hamiltonian
shmRMatrix hij;
// (potentially half rotated) one body hamiltonian
shmCMatrix haj;
//Cholesky Tensor Lik[i][k][n]
shmSpRMatrix Likn;
// permuted half-tranformed Cholesky tensor
// Lank[ 2*idet + ispin ]
std::vector<shmSpC3Tensor> Lank;
// half-tranformed Cholesky tensor
// only used in single determinant case, haj.size(0)==1.
shmSpCMatrix Lakn;
// one-body piece of Hamiltonian factorization
shmCMatrix vn0;
// shared buffer space
// using matrix since there are issues with vectors
shmSpCMatrix SM_TMats;
myTimer Timer;
void set_shm_buffer(size_t N) {
if(SM_TMats.num_elements() < N)
SM_TMats.reextent({N,1});
}
};
}
}
#endif
| 38.918831 | 131 | 0.588888 | kayahans |
a7e41efd5bcc11619c12c326053dcccdc2c3d109 | 157 | hxx | C++ | src/Providers/UNIXProviders/AbstractIndicationSubscription/UNIX_AbstractIndicationSubscription_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/AbstractIndicationSubscription/UNIX_AbstractIndicationSubscription_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/AbstractIndicationSubscription/UNIX_AbstractIndicationSubscription_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_DARWIN
#ifndef __UNIX_ABSTRACTINDICATIONSUBSCRIPTION_PRIVATE_H
#define __UNIX_ABSTRACTINDICATIONSUBSCRIPTION_PRIVATE_H
#endif
#endif
| 13.083333 | 55 | 0.878981 | brunolauze |
a7e53e2e17e6741f7355ed71f56800248291a4b6 | 1,032 | cpp | C++ | binary-tree-zigzag-level-order-traversal.cpp | mittalnaman2706/LeetCode | ba7e1602fb70ca0063c3e5573ea0661cc5ae9856 | [
"Apache-2.0"
] | 2 | 2019-01-10T17:50:26.000Z | 2019-05-23T14:31:58.000Z | binary-tree-zigzag-level-order-traversal.cpp | mittalnaman2706/LeetCode | ba7e1602fb70ca0063c3e5573ea0661cc5ae9856 | [
"Apache-2.0"
] | null | null | null | binary-tree-zigzag-level-order-traversal.cpp | mittalnaman2706/LeetCode | ba7e1602fb70ca0063c3e5573ea0661cc5ae9856 | [
"Apache-2.0"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>>q;
int i,j,k,l;
TreeNode* z;
TreeNode* x;
queue<TreeNode* >a;
if(root==NULL)
return q;
a.push(root);
while(a.size())
{
vector<int >w;
k=a.size();
while(k--)
{
z=a.front();
if(z->left)
a.push(z->left);
if(z->right)
a.push(z->right);
w.push_back(z->val);
a.pop();
}
q.push_back(w);
}
for(i=1;i<q.size();i+=2)
{
reverse(q[i].begin(),q[i].end());
}
return q;
}
}; | 21.5 | 59 | 0.379845 | mittalnaman2706 |
a7ea2b322fecaa7b4a02e2d96db789062e02bf4c | 1,156 | hpp | C++ | include/RED4ext/Types/generated/anim/AnimNode_AimConstraint_ObjectUp.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/anim/AnimNode_AimConstraint_ObjectUp.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/anim/AnimNode_AimConstraint_ObjectUp.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/Vector3.hpp>
#include <RED4ext/Types/generated/anim/AnimNode_OnePoseInput.hpp>
#include <RED4ext/Types/generated/anim/ConstraintWeightMode.hpp>
#include <RED4ext/Types/generated/anim/NamedTrackIndex.hpp>
#include <RED4ext/Types/generated/anim/TransformIndex.hpp>
namespace RED4ext
{
namespace anim {
struct AnimNode_AimConstraint_ObjectUp : anim::AnimNode_OnePoseInput
{
static constexpr const char* NAME = "animAnimNode_AimConstraint_ObjectUp";
static constexpr const char* ALIAS = NAME;
anim::TransformIndex targetTransform; // 60
anim::TransformIndex upTransform; // 78
Vector3 forwardAxisLS; // 90
Vector3 upAxisLS; // 9C
anim::TransformIndex transformIndex; // A8
anim::ConstraintWeightMode weightMode; // C0
float weight; // C4
anim::NamedTrackIndex weightFloatTrack; // C8
uint8_t unkE0[0x108 - 0xE0]; // E0
};
RED4EXT_ASSERT_SIZE(AnimNode_AimConstraint_ObjectUp, 0x108);
} // namespace anim
} // namespace RED4ext
| 33.028571 | 78 | 0.763841 | Cyberpunk-Extended-Development-Team |
a7ec028f47d869af8d9e35e4cdcedf47560f0fe0 | 11,677 | cpp | C++ | tests/test_code/test_modbus.cpp | yisea123/modbus-tcp-server-1 | 0d9f697059b2034dfae2d45115c0f4897de87977 | [
"MIT"
] | 1 | 2019-12-11T05:24:14.000Z | 2019-12-11T05:24:14.000Z | tests/test_code/test_modbus.cpp | yisea123/modbus-tcp-server-1 | 0d9f697059b2034dfae2d45115c0f4897de87977 | [
"MIT"
] | null | null | null | tests/test_code/test_modbus.cpp | yisea123/modbus-tcp-server-1 | 0d9f697059b2034dfae2d45115c0f4897de87977 | [
"MIT"
] | null | null | null | #include "CppUTest/TestHarness.h"
#include <string.h>
#include <stdio.h>
#define NO_OF_INPUT_REGS 10
#define INPUT_REG_START_ADDRESS 0
extern "C"
{
#include "mbap_conf.h"
#include "mbap.h"
}
#define QUERY_SIZE_IN_BYTES (255u)
#define RESPONSE_SIZE_IN_BYTES (255u)
#define INPUT_REGISTER_START_ADDRESS (0u)
#define MAX_INPUT_REGISTERS (15u)
#define HOLDING_REGISTER_START_ADDRESS (0u)
#define MAX_HOLDING_REGISTERS (15u)
#define DISCRETE_INPUTS_START_ADDRESS (0u)
#define MAX_DISCRETE_INPUTS (3u)
#define COILS_START_ADDRESS (0u)
#define MAX_COILS (3u)
#define MBT_EXCEPTION_PACKET_LEN (9u)
#define QUERY_LEN (12u)
#define NO_OF_DATA_OFFSET (10u)
#define DATA_START_ADDRESS_OFFSET (8u)
#define REGISTER_VALUE_OFFSET (10u)
//PDU Offset in response
#define MBT_BYTE_COUNT_OFFSET (8u)
#define MBT_DATA_VALUES_OFFSET (9u)
#define MBAP_HEADER_LEN (7u)
#define DISCRETE_INPUT_BUF_SIZE (MAX_DISCRETE_INPUTS / 8u + 1u)
#define COILS_BUF_SIZE (MAX_COILS / 8u + 1u)
int16_t g_sInputRegsBuf[MAX_INPUT_REGISTERS] = {1, 2, 3};
int16_t g_sHoldingRegsBuf[MAX_HOLDING_REGISTERS] = {5, 6, 7};
uint8_t g_ucDiscreteInputsBuf[DISCRETE_INPUT_BUF_SIZE] = {0xef};
uint8_t g_ucCoilsBuf[COILS_BUF_SIZE] = {5};
int16_t g_sHoldingRegsLowerLimitBuf[MAX_HOLDING_REGISTERS] = {0, 0, 0};
int16_t g_sHoldingRegsHigherLimitBuf[MAX_HOLDING_REGISTERS] = {200, 200, 200};
TEST_GROUP(Module)
{
uint8_t *pucQuery = NULL;
uint8_t *pucResponse = NULL;
int16_t *psInputRegisters = NULL;
int16_t *psHoldingRegisters = NULL;
ModbusData_t *pModbusData = NULL;
void setup()
{
pucQuery = (uint8_t*)calloc(QUERY_SIZE_IN_BYTES, sizeof(uint8_t));
pucResponse = (uint8_t*)calloc(RESPONSE_SIZE_IN_BYTES, sizeof(uint8_t));
pModbusData = (ModbusData_t*)calloc(1, sizeof(ModbusData_t));
pModbusData->psInputRegisters = g_sInputRegsBuf;
pModbusData->usInputRegisterStartAddress = INPUT_REGISTER_START_ADDRESS;
pModbusData->usMaxInputRegisters = MAX_INPUT_REGISTERS;
pModbusData->psHoldingRegisters = g_sHoldingRegsBuf;
pModbusData->usHoldingRegisterStartAddress = HOLDING_REGISTER_START_ADDRESS;
pModbusData->usMaxHoldingRegisters = MAX_HOLDING_REGISTERS;
pModbusData->psHoldingRegisterLowerLimit = g_sHoldingRegsLowerLimitBuf;
pModbusData->psHoldingRegisterHigherLimit = g_sHoldingRegsHigherLimitBuf;
pModbusData->pucDiscreteInputs = g_ucDiscreteInputsBuf;
pModbusData->usDiscreteInputStartAddress = DISCRETE_INPUTS_START_ADDRESS;
pModbusData->usMaxDiscreteInputs = MAX_DISCRETE_INPUTS;
pModbusData->pucCoils = g_ucCoilsBuf;
pModbusData->usCoilsStartAddress = COILS_START_ADDRESS;
pModbusData->usMaxCoils = MAX_COILS;
mbap_DataInit(pModbusData);
}
void teardown()
{
free(pucQuery);
free(pucResponse);
free(pModbusData);
}
};
TEST(Module, read_input_registers)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 4, 0, 5, 0, 3};
uint8_t ucResponseLen = 0;
uint8_t ucByteCount = 0;
uint16_t usNumOfData = 0;
uint16_t usStartAddress = 0;
usStartAddress = (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET] << 8);
usStartAddress |= (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET + 1]);
usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8);
usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]);
ucResponseLen = MBAP_HEADER_LEN + (usNumOfData * 2) + 2;
ucByteCount = usNumOfData * 2;
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]);
for (uint8_t ucCount = 0; ucCount < usNumOfData; ucCount++)
{
int16_t sReceivedValue = 0;
sReceivedValue = (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2)] << 8);
sReceivedValue |= (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2) + 1]);
CHECK_EQUAL(g_sInputRegsBuf[ucCount + usStartAddress], sReceivedValue);
}
}
TEST(Module, illegal_input_registers_address)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 4, 0, 0, 0, 16};
uint8_t ucResponseLen = 0;
ucResponseLen = MBT_EXCEPTION_PACKET_LEN;
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ILLEGAL_DATA_ADDRESS, pucResponse[MBT_BYTE_COUNT_OFFSET] );
}
TEST(Module, read_holding_registers)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 3, 0, 5, 0, 3};
uint8_t ucResponseLen = 0;
uint8_t ucByteCount = 0;
uint16_t usNumOfData = 0;
uint16_t usStartAddress = 0;
usStartAddress = (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET] << 8);
usStartAddress |= (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET + 1]);
usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8);
usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]);
ucResponseLen = MBAP_HEADER_LEN + (usNumOfData * 2) + 2;
ucByteCount = usNumOfData * 2;
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]);
for (uint8_t ucCount = 0; ucCount < usNumOfData; ucCount++)
{
int16_t sReceivedValue = 0;
sReceivedValue = (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2)] << 8);
sReceivedValue |= (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2) + 1]);
CHECK_EQUAL(g_sHoldingRegsBuf[ucCount + usStartAddress], sReceivedValue);
}
}
TEST(Module, illegal_holding_registers_address)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 3, 0, 0, 0, 16};
uint8_t ucResponseLen = 0;
ucResponseLen = MBT_EXCEPTION_PACKET_LEN;
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ILLEGAL_DATA_ADDRESS, pucResponse[MBT_BYTE_COUNT_OFFSET] );
}
TEST(Module, illegal_function_code)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 10, 0, 0, 0, 11};
uint8_t ucResponseLen = 0;
ucResponseLen = MBT_EXCEPTION_PACKET_LEN;
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ILLEGAL_FUNCTION_CODE, pucResponse[MBT_BYTE_COUNT_OFFSET] );
}
TEST(Module, write_single_holding_register)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 6, 0, 1, 0, 200};
uint8_t ucResponseLen = 0;
int16_t sReceivedValue = 0;
int16_t sSentValue = 0;
ucResponseLen = MBAP_HEADER_LEN + 5;
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
sReceivedValue = (int16_t)(pucResponse[REGISTER_VALUE_OFFSET] << 8);
sReceivedValue |= (int16_t)(pucResponse[REGISTER_VALUE_OFFSET + 1]);
sSentValue = (int16_t)(ucQueryBuf[REGISTER_VALUE_OFFSET] << 8);
sSentValue |= (int16_t)(ucQueryBuf[REGISTER_VALUE_OFFSET + 1]);
CHECK_EQUAL(sSentValue, sReceivedValue);
}
TEST(Module, illega_data_value)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 6, 0, 1, 0, 201};
uint8_t ucResponseLen = 0;
ucResponseLen = MBT_EXCEPTION_PACKET_LEN;
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ILLEGAL_DATA_VALUE, pucResponse[MBT_BYTE_COUNT_OFFSET] );
}
TEST(Module, read_discrete_inputs)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 2, 0, 0, 0, 3};
uint8_t ucResponseLen = 0;
uint8_t ucByteCount = 0;
uint16_t usNumOfData = 0;
usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8);
usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]);
ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2;
ucByteCount = usNumOfData / 8;
if (0 != ucQueryBuf[11])
{
ucResponseLen = ucResponseLen + 1;
ucByteCount = ucByteCount + 1;
}
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]);
for (uint8_t ucCount = 0; ucCount < MAX_DISCRETE_INPUTS; ucCount++)
{
uint8_t ucReceivedValue = 0;
uint16_t usByteOffset = 0;
uint16_t usDiscreteBit = 0;
usByteOffset = ucCount / 8 ;
usDiscreteBit = ucCount - usByteOffset * 8;
ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]);
CHECK_EQUAL(g_ucDiscreteInputsBuf[usByteOffset] & (1 << usDiscreteBit) , ucReceivedValue & (1 << usDiscreteBit));
}
}
TEST(Module, read_coils)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 1, 0, 0, 0, 3};
uint8_t ucResponseLen = 0;
uint8_t ucByteCount = 0;
uint16_t usNumOfData = 0;
usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8);
usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]);
ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2;
ucByteCount = usNumOfData / 8;
if (0 != ucQueryBuf[11])
{
ucResponseLen = ucResponseLen + 1;
ucByteCount = ucByteCount + 1;
}
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]);
for (uint8_t ucCount = 0; ucCount < MAX_COILS; ucCount++)
{
uint8_t ucReceivedValue = 0;
uint16_t usByteOffset = 0;
uint16_t usCoilsBit = 0;
usByteOffset = ucCount / 8 ;
usCoilsBit = ucCount - usByteOffset * 8;
ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]);
CHECK_EQUAL(g_ucCoilsBuf[usByteOffset] & (1 << usCoilsBit) , ucReceivedValue & (1 << usCoilsBit));
}
}
TEST(Module, write_coil)
{
uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 1, 0, 0, 0, 3};
uint8_t ucResponseLen = 0;
uint8_t ucByteCount = 0;
uint16_t usNumOfData = 0;
usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8);
usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]);
ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2;
ucByteCount = usNumOfData / 8;
if (0 != ucQueryBuf[11])
{
ucResponseLen = ucResponseLen + 1;
ucByteCount = ucByteCount + 1;
}
memcpy(pucQuery, ucQueryBuf, QUERY_LEN);
CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse));
CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]);
for (uint8_t ucCount = 0; ucCount < MAX_COILS; ucCount++)
{
uint8_t ucReceivedValue = 0;
uint16_t usByteOffset = 0;
uint16_t usCoilsBit = 0;
usByteOffset = ucCount / 8 ;
usCoilsBit = ucCount - usByteOffset * 8;
ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]);
CHECK_EQUAL(g_ucCoilsBuf[usByteOffset] & (1 << usCoilsBit) , ucReceivedValue & (1 << usCoilsBit));
}
}
| 35.066066 | 119 | 0.684936 | yisea123 |
a7ed46564aa28c4496c89aac6c47e69f72c87805 | 2,034 | cpp | C++ | DataPackets/main.cpp | culaja/CppDsp | 70163cf51291692bb72a165fc0216ae087b75292 | [
"MIT"
] | null | null | null | DataPackets/main.cpp | culaja/CppDsp | 70163cf51291692bb72a165fc0216ae087b75292 | [
"MIT"
] | null | null | null | DataPackets/main.cpp | culaja/CppDsp | 70163cf51291692bb72a165fc0216ae087b75292 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cpptest.h>
#include "MainTestHarness.h"
#include "UnitTests/PacketQueueTests.h"
#define RUN_MAIN_TEST_HARNESS // Comment this line if you want to run unit tests, otherwise this will trigger MainTestHarness to execute
using namespace std;
enum OutputType
{
Compiler,
Html,
TextTerse,
TextVerbose
};
static void
usage()
{
cout << "usage: mytest [MODE]\n"
<< "where MODE may be one of:\n"
<< " --compiler\n"
<< " --html\n"
<< " --text-terse (default)\n"
<< " --text-verbose\n";
exit(0);
}
static auto_ptr<Test::Output>
cmdline(int argc, char* argv[])
{
if (argc > 2)
usage(); // will not return
Test::Output* output = 0;
if (argc == 1)
output = new Test::TextOutput(Test::TextOutput::Verbose);
else
{
const char* arg = argv[1];
if (strcmp(arg, "--compiler") == 0)
output = new Test::CompilerOutput;
else if (strcmp(arg, "--html") == 0)
output = new Test::HtmlOutput;
else if (strcmp(arg, "--text-terse") == 0)
output = new Test::TextOutput(Test::TextOutput::Terse);
else if (strcmp(arg, "--text-verbose") == 0)
output = new Test::TextOutput(Test::TextOutput::Verbose);
else
{
cout << "invalid commandline argument: " << arg << endl;
usage(); // will not return
}
}
return auto_ptr<Test::Output>(output);
}
int run_tests(int argc, char* argv[]) {
try
{
// Demonstrates the ability to use multiple test suites
//
Test::Suite ts;
ts.add(auto_ptr<Test::Suite>(new PacketQueueTests));
// Run the tests
//
auto_ptr<Test::Output> output(cmdline(argc, argv));
ts.run(*output, true);
Test::HtmlOutput* const html = dynamic_cast<Test::HtmlOutput*>(output.get());
if (html)
html->generate(cout, true, "MyTest");
}
catch (...)
{
cout << "unexpected exception encountered\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
// Main test program
//
int
main(int argc, char* argv[])
{
#ifdef RUN_MAIN_TEST_HARNESS
MainTestHarness test;
return test.Run(argc, argv);
#else
return run_tests(argc, argv);
#endif
} | 20.755102 | 136 | 0.656342 | culaja |
a7ee53eed9f898947d3f9cdf8453e33c43f2abf2 | 12,845 | cpp | C++ | tests/Widget.cpp | cyanskies/TGUI | 9d84916313aacdfc33dc9a8b9e60609449fddce7 | [
"Zlib"
] | null | null | null | tests/Widget.cpp | cyanskies/TGUI | 9d84916313aacdfc33dc9a8b9e60609449fddce7 | [
"Zlib"
] | null | null | null | tests/Widget.cpp | cyanskies/TGUI | 9d84916313aacdfc33dc9a8b9e60609449fddce7 | [
"Zlib"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus's Graphical User Interface
// Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Tests.hpp"
#include <TGUI/TGUI.hpp>
TEST_CASE("[Widget]") {
tgui::Widget::Ptr widget = std::make_shared<tgui::Button>();
SECTION("Visibile") {
REQUIRE(widget->isVisible());
widget->hide();
REQUIRE(!widget->isVisible());
widget->show();
REQUIRE(widget->isVisible());
}
SECTION("Enabled") {
REQUIRE(widget->isEnabled());
widget->disable();
REQUIRE(!widget->isEnabled());
widget->enable();
REQUIRE(widget->isEnabled());
}
SECTION("Parent") {
tgui::Panel::Ptr panel1 = std::make_shared<tgui::Panel>();
tgui::Panel::Ptr panel2 = std::make_shared<tgui::Panel>();
tgui::Panel::Ptr panel3 = std::make_shared<tgui::Panel>();
REQUIRE(widget->getParent() == nullptr);
panel1->add(widget);
REQUIRE(widget->getParent() == panel1.get());
panel1->remove(widget);
REQUIRE(widget->getParent() == nullptr);
panel2->add(widget);
REQUIRE(widget->getParent() == panel2.get());
widget->setParent(panel3.get());
REQUIRE(widget->getParent() == panel3.get());
widget->setParent(nullptr);
REQUIRE(widget->getParent() == nullptr);
}
SECTION("Opacity") {
REQUIRE(widget->getOpacity() == 1.f);
widget->setOpacity(0.5f);
REQUIRE(widget->getOpacity() == 0.5f);
widget->setOpacity(2.f);
REQUIRE(widget->getOpacity() == 1.f);
widget->setOpacity(-2.f);
REQUIRE(widget->getOpacity() == 0.f);
}
SECTION("Tooltip") {
auto tooltip1 = std::make_shared<tgui::Label>();
tooltip1->setText("some text");
widget->setToolTip(tooltip1);
REQUIRE(widget->getToolTip() == tooltip1);
// ToolTip does not has to be a label
auto tooltip2 = std::make_shared<tgui::Panel>();
widget->setToolTip(tooltip2);
REQUIRE(widget->getToolTip() == tooltip2);
// ToolTip can be removed
widget->setToolTip(nullptr);
REQUIRE(widget->getToolTip() == nullptr);
}
SECTION("Font") {
widget = std::make_shared<tgui::Button>();
REQUIRE(widget->getFont() == nullptr);
widget->setFont("resources/DroidSansArmenian.ttf");
REQUIRE(widget->getFont() != nullptr);
widget->setFont(nullptr);
REQUIRE(widget->getFont() == nullptr);
tgui::Gui gui;
gui.add(widget);
REQUIRE(widget->getFont() != nullptr);
}
SECTION("Move to front/back") {
auto container = std::make_shared<tgui::Panel>();
auto widget1 = std::make_shared<tgui::Button>();
auto widget2 = std::make_shared<tgui::Button>();
auto widget3 = std::make_shared<tgui::Button>();
container->add(widget1);
container->add(widget2);
container->add(widget3);
REQUIRE(container->getWidgets().size() == 3);
REQUIRE(container->getWidgets()[0] == widget1);
REQUIRE(container->getWidgets()[1] == widget2);
REQUIRE(container->getWidgets()[2] == widget3);
widget1->moveToFront();
REQUIRE(container->getWidgets().size() == 3);
REQUIRE(container->getWidgets()[0] == widget2);
REQUIRE(container->getWidgets()[1] == widget3);
REQUIRE(container->getWidgets()[2] == widget1);
widget3->moveToFront();
REQUIRE(container->getWidgets().size() == 3);
REQUIRE(container->getWidgets()[0] == widget2);
REQUIRE(container->getWidgets()[1] == widget1);
REQUIRE(container->getWidgets()[2] == widget3);
widget1->moveToBack();
REQUIRE(container->getWidgets().size() == 3);
REQUIRE(container->getWidgets()[0] == widget1);
REQUIRE(container->getWidgets()[1] == widget2);
REQUIRE(container->getWidgets()[2] == widget3);
widget2->moveToBack();
REQUIRE(container->getWidgets().size() == 3);
REQUIRE(container->getWidgets()[0] == widget2);
REQUIRE(container->getWidgets()[1] == widget1);
REQUIRE(container->getWidgets()[2] == widget3);
}
SECTION("Layouts") {
auto container = std::make_shared<tgui::Panel>();
auto widget2 = std::make_shared<tgui::Button>();
container->add(widget);
container->add(widget2, "w2");
widget2->setPosition(100, 50);
widget2->setSize(600, 150);
widget->setPosition(20, 10);
widget->setSize(100, 30);
SECTION("Position") {
REQUIRE(widget->getPosition() == sf::Vector2f(20, 10));
widget->setPosition(tgui::bindLeft(widget2), {"w2.y"});
REQUIRE(widget->getPosition() == sf::Vector2f(100, 50));
widget2->setPosition(50, 30);
REQUIRE(widget->getPosition() == sf::Vector2f(50, 30));
// String layout only works after adding widget to parent
auto widget3 = widget->clone();
REQUIRE(widget3->getPosition() == sf::Vector2f(50, 0));
container->add(widget3);
REQUIRE(widget3->getPosition() == sf::Vector2f(50, 30));
// Layout can only be copied when it is a string
widget2->setPosition(20, 40);
REQUIRE(widget3->getPosition() == sf::Vector2f(50, 40));
// String is re-evaluated and new widgets are bound after copying
widget->setPosition({"{width, height}"});
REQUIRE(widget->getPosition() == sf::Vector2f(100, 30));
auto widget4 = widget->clone();
widget->setSize(40, 50);
REQUIRE(widget4->getPosition() == sf::Vector2f(100, 30));
widget4->setSize(60, 70);
REQUIRE(widget4->getPosition() == sf::Vector2f(60, 70));
}
SECTION("Size") {
REQUIRE(widget->getSize() == sf::Vector2f(100, 30));
widget->setSize({"w2.width"}, tgui::bindHeight(widget2));
REQUIRE(widget->getSize() == sf::Vector2f(600, 150));
widget2->setSize(50, 30);
REQUIRE(widget->getSize() == sf::Vector2f(50, 30));
// String layout only works after adding widget to parent
auto widget3 = widget->clone();
REQUIRE(widget3->getSize() == sf::Vector2f(0, 30));
container->add(widget3);
REQUIRE(widget3->getSize() == sf::Vector2f(50, 30));
// Layout can only be copied when it is a string
widget2->setSize(20, 40);
REQUIRE(widget3->getSize() == sf::Vector2f(20, 30));
// String is re-evaluated and new widgets are bound after copying
widget->setSize({"position"});
REQUIRE(widget->getSize() == sf::Vector2f(20, 10));
auto widget4 = widget->clone();
widget->setPosition(40, 50);
REQUIRE(widget4->getSize() == sf::Vector2f(20, 10));
widget4->setPosition(60, 70);
REQUIRE(widget4->getSize() == sf::Vector2f(60, 70));
}
}
SECTION("Saving and loading widget with layouts from file") {
auto parent = std::make_shared<tgui::Panel>();
parent->add(widget, "Widget Name.With:Special{Chars}");
SECTION("Bind 2d non-string") {
widget->setPosition(tgui::bindPosition(parent));
widget->setSize(tgui::bindSize(parent));
parent->setSize(400, 300);
parent->setPosition(50, 50);
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt"));
parent->removeAllWidgets();
REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt"));
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt"));
REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt"));
widget = parent->get("Widget Name.With:Special{Chars}");
// Non-string layouts cannot be saved yet!
parent->setPosition(100, 100);
parent->setSize(800, 600);
REQUIRE(widget->getPosition() == sf::Vector2f(50, 50));
REQUIRE(widget->getSize() == sf::Vector2f(400, 300));
}
SECTION("Bind 1d non-strings and string combination") {
widget->setPosition(tgui::bindLeft(parent), {"parent.top"});
widget->setSize({"parent.width"}, tgui::bindHeight(parent));
parent->setSize(400, 300);
parent->setPosition(50, 50);
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt"));
parent->removeAllWidgets();
REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt"));
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt"));
REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt"));
widget = parent->get("Widget Name.With:Special{Chars}");
// Non-string layout cannot be saved yet, string layout will have been saved correctly!
parent->setPosition(100, 100);
parent->setSize(800, 600);
REQUIRE(widget->getPosition() == sf::Vector2f(50, 100));
REQUIRE(widget->getSize() == sf::Vector2f(800, 300));
}
SECTION("Bind 1d strings") {
widget->setPosition({"&.x"}, {"&.y"});
widget->setSize({"&.w"}, {"&.h"});
parent->setSize(400, 300);
parent->setPosition(50, 50);
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt"));
parent->removeAllWidgets();
REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt"));
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt"));
REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt"));
widget = parent->get("Widget Name.With:Special{Chars}");
parent->setPosition(100, 100);
parent->setSize(800, 600);
REQUIRE(widget->getPosition() == sf::Vector2f(100, 100));
REQUIRE(widget->getSize() == sf::Vector2f(800, 600));
}
SECTION("Bind 2d strings") {
widget->setPosition({"{&.x, &.y}"});
widget->setSize({"parent.size"});
parent->setSize(400, 300);
parent->setPosition(50, 50);
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt"));
parent->removeAllWidgets();
REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt"));
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt"));
REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt"));
widget = parent->get("Widget Name.With:Special{Chars}");
parent->setPosition(100, 100);
parent->setSize(800, 600);
REQUIRE(widget->getPosition() == sf::Vector2f(100, 100));
REQUIRE(widget->getSize() == sf::Vector2f(800, 600));
}
}
SECTION("Bug Fixes") {
SECTION("Disabled widgets should not be focusable (https://forum.tgui.eu/index.php?topic=384)") {
tgui::Panel::Ptr panel = std::make_shared<tgui::Panel>();
tgui::EditBox::Ptr editBox = std::make_shared<tgui::EditBox>();
editBox->setFont("resources/DroidSansArmenian.ttf");
panel->add(editBox);
editBox->focus();
REQUIRE(editBox->isFocused());
editBox->disable();
REQUIRE(!editBox->isFocused());
editBox->focus();
REQUIRE(!editBox->isFocused());
}
}
}
| 39.645062 | 129 | 0.576645 | cyanskies |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.