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 listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 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 listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c69a852a23024887d227bc695adfcee29828933e | 2,046 | hh | C++ | repos/ComponentUUVSimulator/smartsoft/src-gen/NavigationVelocityServiceInUpcallManager.hh | skarvtech/uwrosys | c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4 | [
"Apache-2.0"
] | null | null | null | repos/ComponentUUVSimulator/smartsoft/src-gen/NavigationVelocityServiceInUpcallManager.hh | skarvtech/uwrosys | c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4 | [
"Apache-2.0"
] | null | null | null | repos/ComponentUUVSimulator/smartsoft/src-gen/NavigationVelocityServiceInUpcallManager.hh | skarvtech/uwrosys | c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4 | [
"Apache-2.0"
] | null | null | null | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#ifndef _NAVIGATIONVELOCITYSERVICEIN_UPCALL_MANAGER_HH
#define _NAVIGATIONVELOCITYSERVICEIN_UPCALL_MANAGER_HH
#include <list>
#include "aceSmartSoft.hh"
#include "NavigationVelocityServiceInUpcallInterface.hh"
/** NavigationVelocityServiceInUpcallManager connects input-handling with Upcall propagation
*
* This class implements an InputHandler for the InputPort NavigationVelocityServiceIn and propagates the handling
* of incoming data to all associated (i.e. attached) Upcalls.
*/
class NavigationVelocityServiceInUpcallManager
: public Smart::IInputHandler<CommBasicObjects::CommNavigationVelocity>
{
private:
// list of associated updalls
std::list<NavigationVelocityServiceInUpcallInterface*> upcalls;
// call the on_NavigationVelocityServiceIn of all the attached NavigationVelocityServiceInUpcallInterfaces
void notify_upcalls(const CommBasicObjects::CommNavigationVelocity &input);
protected:
virtual void handle_input(const CommBasicObjects::CommNavigationVelocity &input) {
// relay input-handling to all attached NavigationVelocityServiceInUpcallInterfaces
this->notify_upcalls(input);
}
public:
NavigationVelocityServiceInUpcallManager(
Smart::InputSubject<CommBasicObjects::CommNavigationVelocity> *subject,
const int &prescaleFactor=1
);
virtual ~NavigationVelocityServiceInUpcallManager();
void attach(NavigationVelocityServiceInUpcallInterface *upcall);
void detach(NavigationVelocityServiceInUpcallInterface *upcall);
};
#endif
| 37.2 | 115 | 0.76002 | skarvtech |
c69abb2e5ccfcc20dbbffee17c89e8b114307d9c | 3,121 | cpp | C++ | src/c_update.cpp | DreamHacks/dd3d | 4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9 | [
"MIT"
] | null | null | null | src/c_update.cpp | DreamHacks/dd3d | 4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9 | [
"MIT"
] | null | null | null | src/c_update.cpp | DreamHacks/dd3d | 4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9 | [
"MIT"
] | 5 | 2017-07-09T12:03:19.000Z | 2022-02-09T09:37:36.000Z | #include "dd3d.h"
#include "m_user.h"
#include "m_service.h"
#include "connection.h"
#include "message.h"
#include "c_update.h"
const mysqlpp::sql_text* c_update_get_desc(const ReleaseInfo* info, uint32_t locale_id) {
const mysqlpp::sql_text* rv = NULL;
if (info->desc_map.size()) {
if (locale_id == 0 || !info->desc_map.count(locale_id))
locale_id = DEFAULT_LOCALE_ID;
release_desc_map_t::const_iterator it = info->desc_map.find(locale_id);
if (it != info->desc_map.end())
rv = &(it->second);
}
return rv;
}
bool c_update_handler_no_session(void* message, uint32_t message_size) {
bool rv = false;
const ReleaseInfo* info = m_service_get_lastest_release_info();
const mysqlpp::sql_text* desc = c_update_get_desc(info, 0);
if (NULL != desc) {
MessageFieldsData data;
message_fields_init(&data, 4);
message_field_add(&data, (uint8_t*)(&info->build), sizeof(mysqlpp::sql_int_unsigned));
message_field_add(&data, (uint8_t*)(info->link.c_str()), info->link.size());
message_field_add(&data, (uint8_t*)(desc->c_str()), desc->size());
message_field_add(&data, (uint8_t*)(&info->date), sizeof(mysqlpp::sql_int_unsigned));
uint32_t msg_size = message_size_calc(&data);
if (msg_size <= sizeof(MsgBuffer) && message_build(MESSAGE_TYPE_UPDATE, &data, MsgBuffer, sizeof(MsgBuffer))) {
connection_reply((uint8_t*)MsgBuffer, msg_size);
rv = true;
} else
syslog(LOG_ERR, "[ERROR]Build update message failed.\n");
message_clear_fields(&data);
} else
syslog(LOG_ERR, "[ERROR]Get lastest build information failed.\n");
return rv;
}
bool c_update_handler_localized(void* message, uint32_t message_size) {
bool rv = false;
char session_id[33];
memcpy(session_id, utils_poniter_calc<uint8_t*>(message, 2), 32);
session_id[32] = 0;
SessionInfo session_info;
if (m_user_get_session_by_id(&session_info, session_id)) {
const ReleaseInfo* info = m_service_get_lastest_release_info();
const mysqlpp::sql_text* desc = c_update_get_desc(info, session_info.locale_id);
if (NULL != desc) {
MessageFieldsData data;
message_fields_init(&data, 4);
message_field_add(&data, (uint8_t*)(&info->build), sizeof(mysqlpp::sql_int_unsigned));
message_field_add(&data, (uint8_t*)(info->link.c_str()), info->link.size());
message_field_add(&data, (uint8_t*)(desc->c_str()), desc->size());
message_field_add(&data, (uint8_t*)(&info->date), sizeof(mysqlpp::sql_int_unsigned));
uint32_t msg_size = message_size_calc(&data);
if (msg_size <= sizeof(MsgBuffer) && message_build(MESSAGE_TYPE_UPDATE, &data, MsgBuffer, sizeof(MsgBuffer))) {
connection_reply((uint8_t*)MsgBuffer, msg_size);
rv = true;
} else
syslog(LOG_ERR, "[ERROR]Build update message failed.\n");
message_clear_fields(&data);
} else
syslog(LOG_ERR, "[ERROR]Get lastest build information failed.\n");
}
return rv;
}
bool c_update_handler(void* message, uint32_t message_size) {
if (message_size == 2)
return c_update_handler_no_session(message, message_size);
else if (message_size == 32 + 2)
return c_update_handler_localized(message, message_size);
else
return false;
}
| 37.154762 | 114 | 0.725088 | DreamHacks |
c69c325fb02c8af2c27d6e2cd9df664962804d86 | 13,863 | cpp | C++ | Coin3D/src/Inventor/Win/widgets/SoWinBitmapButton.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/Inventor/Win/widgets/SoWinBitmapButton.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/Inventor/Win/widgets/SoWinBitmapButton.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | /**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/
#include <Inventor/lists/SbPList.h>
#include <Inventor/Win/widgets/SoWinBitmapButton.h>
#include <Inventor/Win/SoWin.h>
#include <sowindefs.h>
#include <Inventor/Win/Win32API.h>
#include <assert.h>
#include <stdio.h>
// *************************************************************************
class SoWinBitmapButtonP {
public:
SoWinBitmapButtonP(SoWinBitmapButton * master)
{
this->owner = master;
this->clickproc = NULL;
this->clickprocdata = NULL;
this->buttonwindow = NULL;
}
~SoWinBitmapButtonP()
{
// Note: since the buttonwindow is owned by it's parent,
// it will be destroyed (DestroyWindow()) when parent is destroyed.
// This could happen before or after this destructor is called,
// so we need to be robust. 2004-01-21 thammer.
// Note: We need to make sure the button_proc() is not called
// after the destructor has been called. 2004-01-21 thammer.
if ( (this->buttonwindow) && IsWindow(this->buttonwindow) ) {
Win32::SetWindowLongPtr(this->buttonwindow, GWLP_WNDPROC,
(LONG_PTR)this->prevwndfunc);
this->buttonwindow = NULL;
}
const int len = this->bitmaplist.getLength();
for (int i = 0; i < len; i++) { Win32::DeleteObject(this->bitmaplist[i]); }
}
HWND buildWidget(HWND parent, RECT rect);
HBITMAP createDIB(int width, int height, int bpp, void ** bits);
HBITMAP parseXpm(const char ** xpm, int dibdepth = 24);
static int axtoi(const char * str);
HWND buttonwindow;
SbPList bitmaplist;
SoWinBitmapButton::ClickedProc * clickproc;
void * clickprocdata;
WNDPROC prevwndfunc;
static LRESULT CALLBACK button_proc(HWND hwnd, UINT msg,
WPARAM wparam, LPARAM lparam);
private:
SoWinBitmapButton * owner;
};
#define PRIVATE(p) (p->pimpl)
#define PUBLIC(p) (p->owner)
// *************************************************************************
SoWinBitmapButton::SoWinBitmapButton(HWND parent,
int x,
int y,
int width,
int height,
int depth,
const char * name,
void * bits)
{
PRIVATE(this) = new SoWinBitmapButtonP(this);
RECT rect = { x, y, width, height };
PRIVATE(this)->buildWidget(parent, rect);
if (bits != NULL) {
this->addBitmap(width, height, depth, bits);
this->setBitmap(0);
}
}
SoWinBitmapButton::SoWinBitmapButton(HWND parent,
int depth,
const char * name,
void * bits)
{
PRIVATE(this) = new SoWinBitmapButtonP(this);
RECT rect = { 0, 0, 30, 30 };
PRIVATE(this)->buildWidget(parent, rect);
if (bits != NULL) {
this->addBitmap(rect.right - rect.left - 1,
rect.bottom - rect.top - 1,
depth, bits);
this->setBitmap(0);
}
}
SoWinBitmapButton::~SoWinBitmapButton(void)
{
delete PRIVATE(this);
}
HWND
SoWinBitmapButton::getWidget(void)
{
return PRIVATE(this)->buttonwindow;
}
int
SoWinBitmapButton::width(void) const
{
RECT rect;
Win32::GetWindowRect(PRIVATE(this)->buttonwindow, & rect);
return (rect.right - rect.left);
}
int
SoWinBitmapButton::height(void) const
{
RECT rect;
Win32::GetWindowRect(PRIVATE(this)->buttonwindow, & rect);
return (rect.bottom - rect.top);
}
void
SoWinBitmapButton::move(int x, int y)
{
assert(IsWindow(PRIVATE(this)->buttonwindow));
UINT flags = SWP_NOSIZE | SWP_NOZORDER;
Win32::SetWindowPos(PRIVATE(this)->buttonwindow, NULL, x, y, 0, 0, flags);
}
void
SoWinBitmapButton::move(int x, int y, int width, int height)
{
assert(IsWindow(PRIVATE(this)->buttonwindow));
Win32::MoveWindow(PRIVATE(this)->buttonwindow, x, y, width, height, TRUE);
}
void
SoWinBitmapButton::resize(int width, int height)
{
assert(IsWindow(PRIVATE(this)->buttonwindow));
UINT flags = SWP_NOMOVE | SWP_NOZORDER;
Win32::SetWindowPos(PRIVATE(this)->buttonwindow, NULL, 0, 0, width, height, flags);
}
void
SoWinBitmapButton::show(void)
{
(void)ShowWindow(PRIVATE(this)->buttonwindow, SW_SHOW);
}
void
SoWinBitmapButton::hide(void)
{
(void)ShowWindow(PRIVATE(this)->buttonwindow, SW_HIDE);
}
void
SoWinBitmapButton::registerClickedProc(ClickedProc * func, void * userdata)
{
PRIVATE(this)->clickproc = func;
PRIVATE(this)->clickprocdata = userdata;
}
LRESULT CALLBACK
SoWinBitmapButtonP::button_proc(HWND hwnd, UINT msg,
WPARAM wparam, LPARAM lparam)
{
LONG_PTR l = Win32::GetWindowLongPtr(hwnd, GWLP_USERDATA);
SoWinBitmapButtonP * that = (SoWinBitmapButtonP *)l;
if (that->clickproc) {
// Find out if the button was clicked.
SbBool clicked = (msg == WM_LBUTTONUP);
clicked = clicked && (GetCapture() == hwnd);
// FIXME: should also check that button is a) pressed and b)
// highlighted. (We would then at least match all tests done in
// Wine's BUTTON class before sending a WM_COMMAND message to it's
// parent.) 20030425 mortene.
if (clicked) {
POINT mousept = { LOWORD(lparam), HIWORD(lparam) };
RECT rect;
Win32::GetClientRect(hwnd, &rect);
clicked = PtInRect(&rect, mousept);
}
if (clicked) { that->clickproc(that->owner, that->clickprocdata); }
}
return CallWindowProc(that->prevwndfunc, hwnd, msg, wparam, lparam);
}
HWND
SoWinBitmapButtonP::buildWidget(HWND parent, RECT rect)
{
assert(IsWindow(parent));
this->buttonwindow =
Win32::CreateWindow_("BUTTON", // lpClassName
NULL, // lpWindowName
WS_VISIBLE | WS_CHILD | WS_CLIPSIBLINGS |
BS_PUSHBUTTON | BS_BITMAP | BS_CENTER, // dwStyle
rect.left, rect.top, // position
rect.right, rect.bottom, // window width & height
parent, // hWndParent (owner window)
NULL, // hMenu
NULL, // hInstance (application instance)
NULL); // lpParam (window-creation data)
this->prevwndfunc = (WNDPROC)
Win32::SetWindowLongPtr(this->buttonwindow, GWLP_WNDPROC,
(LONG_PTR)SoWinBitmapButtonP::button_proc);
(void)Win32::SetWindowLongPtr(this->buttonwindow, GWLP_USERDATA,
(LONG_PTR)this);
return this->buttonwindow;
}
void
SoWinBitmapButton::setEnabled(SbBool enable)
{
Win32::EnableWindow(PRIVATE(this)->buttonwindow, enable);
}
SbBool
SoWinBitmapButton::isEnabled(void) const
{
return (! (Win32::GetWindowLongPtr(PRIVATE(this)->buttonwindow, GWL_STYLE) & WS_DISABLED));
}
void
SoWinBitmapButton::setPressedState(SbBool enable)
{
(void)SendMessage(PRIVATE(this)->buttonwindow, BM_SETSTATE,
(WPARAM)enable, 0);
}
SbBool
SoWinBitmapButton::getPressedState(void) const
{
return (SendMessage(PRIVATE(this)->buttonwindow, BM_GETSTATE, 0, 0) &
BST_PUSHED);
}
void
SoWinBitmapButton::addBitmap(HBITMAP hbmp)
{
PRIVATE(this)->bitmaplist.append(hbmp);
}
void
SoWinBitmapButton::addBitmap(int width, int height, int bpp, void * src)
{
void * dest;
HBITMAP hbmp = PRIVATE(this)->createDIB(width, height, bpp, & dest);
(void)memcpy(dest, src, width * height * (bpp / 8));
this->addBitmap(hbmp);
}
void
SoWinBitmapButton::addBitmap(const char ** xpm, int bpp)
{
HBITMAP bm = PRIVATE(this)->parseXpm(xpm, bpp);
this->addBitmap(bm);
}
HBITMAP
SoWinBitmapButton::getBitmap(int index) const
{
return (HBITMAP) PRIVATE(this)->bitmaplist[index];
}
void
SoWinBitmapButton::setBitmap(int index)
{
assert(IsWindow(PRIVATE(this)->buttonwindow));
(void)SendMessage(PRIVATE(this)->buttonwindow,
BM_SETIMAGE,
(WPARAM) IMAGE_BITMAP,
(LPARAM) this->getBitmap(index));
Win32::InvalidateRect(PRIVATE(this)->buttonwindow, NULL, FALSE);
}
HBITMAP
SoWinBitmapButtonP::createDIB(int width, int height, int bpp, void ** bits) // 16||24||32 bpp
{
assert(bpp > 8);
HBITMAP bitmap = NULL;
HDC hdc = CreateCompatibleDC(NULL);
assert(hdc!=NULL && "CreateCompatibleDC() failed -- investigate");
int heapspace = sizeof(BITMAPINFOHEADER);
// FIXME: allocating the BITMAPINFO on the heap seems unnecessary..?
// Investigate. 20051020 mortene.
HANDLE heap = GetProcessHeap();
BITMAPINFO * format = (BITMAPINFO *) HeapAlloc(heap, 0, heapspace);
BITMAPINFOHEADER * header = (BITMAPINFOHEADER *) format;
header->biSize = sizeof(BITMAPINFOHEADER);
header->biWidth = width;
header->biHeight = -height;
header->biPlanes = 1;
header->biBitCount = bpp;
header->biCompression = BI_RGB;
header->biSizeImage = 0;
header->biXPelsPerMeter = 0;
header->biYPelsPerMeter = 0;
header->biClrUsed = 0;
header->biClrImportant = 0;
UINT flag = DIB_RGB_COLORS;
bitmap = CreateDIBSection(hdc, format, flag, (void **) bits, NULL, 0);
assert(* bits);
HeapFree(heap, 0, format);
Win32::DeleteDC(hdc);
return bitmap;
}
// Convert from xpm to DIB (demands hex colors).
HBITMAP
SoWinBitmapButtonP::parseXpm(const char ** xpm, int dibdepth)
{
unsigned char pixelsize = dibdepth / 8;
int width, height, numcol, numchars;
int nr = sscanf(xpm[0], "%d %d %d %d", &width, &height, &numcol, &numchars);
assert((nr == 4) && "corrupt xpm?");
// create color lookup table
char * charlookuptable = new char[numcol * numchars];
int * colorlookuptable = new int[numcol];
// get colors
int i;
for (i = 0; i < numcol; i++) {
int j;
for (j = 0; j < numchars; j ++) {
charlookuptable[(i * numchars) + j] = * (xpm[i + 1] + j);
}
// FIXME: make sure it is 'c '
const char * strstart = strchr((xpm[i + 1] + numchars), 'c');
const char * strend = strstart + 2;
if (*strend == '#')
colorlookuptable[i] = SoWinBitmapButtonP::axtoi(strend + 1);
else
colorlookuptable[i] = -1; // Parse string (color name)
}
// create bitmap
void * dest;
HBITMAP hbmp = this->createDIB(width, height, dibdepth, &dest);
// put pixels
for (i = 0; i < height; i++) {
const char * line = xpm[i + 1 + numcol];
int y = i * width * pixelsize;
int j;
for (j = 0; j < width; j++) {
int x = j * pixelsize;
// for every color
int k;
for (k = 0; k < numcol; k++) {
int l;
for (l = 0; l < numchars; l++)
if (charlookuptable[(k * numchars) + l] != line[(j * numchars) + l])
break;
// if we found the char in the lookup table
if (l >= numchars) {
unsigned int colorvalue;
if (colorlookuptable[k] == -1)
colorvalue = GetSysColor(COLOR_3DFACE) & 0x00FFFFFF; // FIXME: color make param
else
colorvalue = colorlookuptable[k] | 0xFF000000;
// FIXME: may not work with depth < 24
// for each color byte in the pixel
int m;
for (m = 0; m < pixelsize; m++) {
// put color byte (and only one byte)
((char *) dest)[y + x + m] =
(char) ((colorvalue & (0x000000FF << (m << 3))) >> (m << 3));
}
// next pixel
break;
}
}
}
}
// cleanup
delete [] charlookuptable;
delete [] colorlookuptable;
// return bitmap
return hbmp;
}
int
SoWinBitmapButtonP::axtoi(const char * str) // convert from ASCII hex to int
{
const char * c = str;
int n = int(strchr(c, '\0') - c);
int x = 0;
// convert n nibbles
for (int i = 0; i < n; i++) {
// numbers 0 - 9
if ((c[i] > 0x2F) && (c[i] < 0x3A))
x += ((c[i] - 0x30) << ((n - i - 1) * 4));
// capital letters A - F
if ((c[i] > 0x40) && (c[i] < 0x47))
x += ((c[i] - 0x41 + 0x0A) << ((n - i - 1) * 4));
// lower case letters a - f
if ((c[i] > 0x60) && (c[i] < 0x67))
x += ((c[i] - 0x61 + 0x0A) << ((n - i - 1) * 4));
}
return x;
}
| 28.119675 | 93 | 0.611844 | pniaz20 |
c69de44dd7fc42c74f379371de021d15d87f4686 | 807 | cpp | C++ | arith_instructions/slli.cpp | vinodganesan/shaktiISS | fb48e202596989004136b3d44e6fcfa191ba6ea8 | [
"BSD-3-Clause"
] | null | null | null | arith_instructions/slli.cpp | vinodganesan/shaktiISS | fb48e202596989004136b3d44e6fcfa191ba6ea8 | [
"BSD-3-Clause"
] | null | null | null | arith_instructions/slli.cpp | vinodganesan/shaktiISS | fb48e202596989004136b3d44e6fcfa191ba6ea8 | [
"BSD-3-Clause"
] | null | null | null | //Program for SLLI opcode
//SLLI is a logical left shift (zeros are shifted into the lower bits)
#include <stdio.h>
void slli(int rd,int rs1, int *shamt)
{
int shamt64[64], temp[64];
int shift;
int i = 0;
for (i= 0; i < 6; ++i)
{
shamt64[63-i] = shamt[5-i];
}
i = 0;
while(i < 58)
{
shamt64[i] = 0;
i++;
}
shift = (int)bin2dec(shamt64);
for (i = 0; i < shift; ++i)
{
temp[63-i] = 0;
}
i = 0;
while(i < 64-shift)
{
temp[i] = Rreg[rs1][i+shift];
i++;
}
if(rd!=0)
{
for( i = 0; i < 64; ++i)
Rreg[rd][i] = temp[i];
}
std::cout << "SLLI TAKEN\n";
/*printf("\nshift = %d\n", shift);
for (i = 0; i < 32; ++i)
{
printf("%d",Rreg[rs1][i]);
}
printf("\n");
for (i = 0; i < 32; ++i)
{
printf("%d",Rreg[rd][i]);
}*/
}
| 16.8125 | 71 | 0.473358 | vinodganesan |
c69f222fda95a9c7e5792be4e337d685d921ce8b | 780 | cpp | C++ | list-jkc.cpp | superblocks/superblocks | 920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc | [
"Unlicense"
] | 3 | 2018-09-09T10:05:38.000Z | 2020-11-06T02:11:46.000Z | list-jkc.cpp | superblocks/superblocks | 920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc | [
"Unlicense"
] | null | null | null | list-jkc.cpp | superblocks/superblocks | 920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc | [
"Unlicense"
] | null | null | null | // JKC superblocks list
// Superblocks - Version 0.4.3
//
// explorer: http://block.al.tcoin.info/chain/JKCCoin
// explorer: http://jkc.cryptocoinexplorer.com/
#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
using namespace std;
using namespace boost;
int list_length = 100000;
int main() {
cout << "[JKC] Junkcoin - Superblock list" << endl << endl;
cout << "BLOCK, REWARD" << endl;
for (int nHeight = 0; nHeight <= list_length; nHeight++) {
random::mt19937 gen(nHeight);
random::uniform_int_distribution<> dist(1, 100000);
int rand = dist(gen);
if(rand > 99990) {
cout << nHeight << ", 1000" << endl;
} else if (rand < 1001) {
cout << nHeight << ", 150" << endl;
}
}
return 0;
}
| 24.375 | 60 | 0.662821 | superblocks |
c6a040f0be24a921afeaf1bf5274a7e5ced30a62 | 4,351 | hpp | C++ | include/spotless_mini_explorer/pathPlanner.hpp | smahajan07/spotless_mini_explorer | 7e7eb1915cbc62f3e0db841eee9a87a99f8cf0e5 | [
"MIT"
] | 2 | 2021-01-29T07:39:39.000Z | 2021-01-30T02:10:04.000Z | include/spotless_mini_explorer/pathPlanner.hpp | smahajan07/spotless_mini_explorer | 7e7eb1915cbc62f3e0db841eee9a87a99f8cf0e5 | [
"MIT"
] | null | null | null | include/spotless_mini_explorer/pathPlanner.hpp | smahajan07/spotless_mini_explorer | 7e7eb1915cbc62f3e0db841eee9a87a99f8cf0e5 | [
"MIT"
] | null | null | null | /** MIT License
Copyright (c) 2018 Sarthak Mahajan
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.
*/
/**
*@copyright Copyright (c) 2018 Sarthak Mahajan
*@file pathPlanner.hpp
*@author Sarthak Mahajan
*@brief Here all the class variables and methods are declared. pathPlanner is
* the derived class (inherits from the frontierOps class). Primarily, this
* class is at the front end of the system. It subscribes to the map of the
* surrounding and sends it to methods of the frontierOps class to process it
* and send the computed goal. Now it takes control again and calls the method
* to move the bot to the desired location.
*/
#ifndef INCLUDE_SPOTLESS_MINI_EXPLORER_PATHPLANNER_HPP_
#define INCLUDE_SPOTLESS_MINI_EXPLORER_PATHPLANNER_HPP_
#include <iostream>
#include <vector>
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "nav_msgs/OccupancyGrid.h"
#include "sensor_msgs/PointCloud.h"
#include "spotless_mini_explorer/frontierOps.hpp"
/**
*@brief Path planner class
*/
class pathPlanner : public frontierOps {
private:
// create a object to publish velocities
geometry_msgs::Twist msg;
// create a node handle
ros::NodeHandle nh;
// create a subsciber for the laserscan topic
ros::Subscriber mapSub;
// create a publisher to publish velocities
ros::Publisher velPub;
// point cloud for frontiers
sensor_msgs::PointCloud frontierPtCloud;
// publisher for frontier point clouds
ros::Publisher publisherPtCloud;
public:
/**
*@brief Constructor for the pathPlanner class. It defines the publishers of
* the class.
*/
pathPlanner();
/**
*@brief This is the call back function of the map subscriber.
*
*@param map Occupancy grid of the surrounding. Unknown points correspond to
* -1, obstacles have a value greater than 0 and empty space will have the
* value 0. It is processed like a one dimensional array.
*
*@return None
*/
void mapCallback(const nav_msgs::OccupancyGrid& map);
/**
*@brief Method to make the bot rotate 360 degrees and get a sweep scan of the
* surrounding. This is called in the beginning to get the initial
* understanding of the environment.
*
*@param None
*
*@return None
*/
void fullScan();
/**
*@brief Sets the map subscriber to the correct topic.
*
*@param None
*
*@return None
*/
void updateMap();
/**
*@brief This is where the magic happens. At the end of every iteration of
* scanning and processing, the system generates a point cloud of frontiers.
* This method sets the goal as the nearest frontier for the bot using the
* move base package. In case the execution was not successful, which should be
* rare, it tries to go to the farthest frontier.
*
*@param frontierCloud It's the point cloud generated with the frontier median
* (centre) points
*
*@return None
*/
void moveBot(const sensor_msgs::PointCloud frontierCloud);
/**
*@brief Receives the array of frontier points and it sends back the centre
* point of the frontier.
*
*@param frontier Integer array of frontier points
*
*@return The center point from the frontier points
*/
int getMedian(std::vector<int> frontier);
/**
*@brief Destructor for class pathPlanner. Left empty for future development
*/
~pathPlanner();
};
#endif // INCLUDE_SPOTLESS_MINI_EXPLORER_PATHPLANNER_HPP_
| 32.470149 | 80 | 0.745116 | smahajan07 |
c6a1cf6a79f8750f792a1817b230be19b22a155d | 2,443 | cpp | C++ | JNI_Demo/rsademo/src/main/cpp/MyBASE64.cpp | 710224800/JNI_Demo | 13f629c6a2472d451191631bf1c9129cc9485fa1 | [
"Apache-2.0"
] | 4 | 2018-05-09T16:26:56.000Z | 2020-05-28T06:03:20.000Z | JNI_Demo/rsademo/src/main/cpp/MyBASE64.cpp | 710224800/JNI_Demo | 13f629c6a2472d451191631bf1c9129cc9485fa1 | [
"Apache-2.0"
] | null | null | null | JNI_Demo/rsademo/src/main/cpp/MyBASE64.cpp | 710224800/JNI_Demo | 13f629c6a2472d451191631bf1c9129cc9485fa1 | [
"Apache-2.0"
] | null | null | null | //
// Created by gzbd on 2016/12/7.
//
#include <evp.h>
#include "MyBASE64.h"
#include <bio.h>
#include <buffer.h>
#include "Log.h"
std::string MyBASE64::base64_encodestring(const std::string &text ){
EVP_ENCODE_CTX ectx;
int size = text.size()*2;
size = size > 64 ? size : 64;
unsigned char* out = (unsigned char*)malloc( size );
int outlen = 0;
int tlen = 0;
EVP_EncodeInit( &ectx );
EVP_EncodeUpdate( &ectx, out, &outlen, (const unsigned char*)text.c_str(), text.size() );
tlen += outlen;
EVP_EncodeFinal( &ectx, out+tlen, &outlen );
tlen += outlen;
std::string str( (char*)out, tlen );
free( out );
return str;
}
std::string MyBASE64::base64_decodestring(const std::string &text ){
EVP_ENCODE_CTX ectx;
unsigned char* out = (unsigned char*)malloc( text.size() );
int outlen = 0;
int tlen = 0;
EVP_DecodeInit( &ectx );
EVP_DecodeUpdate( &ectx, out, &outlen, (const unsigned char*)text.c_str(), text.size() );
tlen += outlen;
EVP_DecodeFinal( &ectx, out+tlen, &outlen );
tlen += outlen;
std::string data( (char*)out, tlen );
free( out );
return data;
}
std::string MyBASE64::base64_decode(const std::string& encoded_bytes, int *decoded_length) {
BIO *bioMem, *b64;
size_t buffer_length;
bioMem = BIO_new_mem_buf((void *) encoded_bytes.c_str(), -1);
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bioMem = BIO_push(b64, bioMem);
buffer_length = BIO_get_mem_data(bioMem, NULL);
static std::string decoded_bytes;
decoded_bytes.clear();
*decoded_length = BIO_read(bioMem, (void *)decoded_bytes.c_str(), (int)buffer_length);
BIO_free_all(bioMem);
return decoded_bytes;
}
/* Return NULL if failed, REMEMBER to free() */
std::string MyBASE64::base64_encode(const std::string& decoded_bytes,
size_t decoded_length) {
int x;
BIO *bioMem, *b64;
BUF_MEM *bufPtr;
static std::string buff ;
buff.clear();
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bioMem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bioMem);
BIO_write(b64,decoded_bytes.c_str(), (int)decoded_length);
x = BIO_flush(b64);
if (x < 1)
goto END;
BIO_get_mem_ptr(b64, &bufPtr);
buff.assign(bufPtr->data);
END: BIO_free_all(b64);
return buff;
}
| 23.718447 | 93 | 0.635284 | 710224800 |
c6a47bbd3d132f61dc02569358c338938e788e56 | 217 | cpp | C++ | concurrency/02_lambda_thread.cpp | anancds/modern-cpp | 4d656b56e33f437fd586f963ac49f760e6e23238 | [
"MIT"
] | null | null | null | concurrency/02_lambda_thread.cpp | anancds/modern-cpp | 4d656b56e33f437fd586f963ac49f760e6e23238 | [
"MIT"
] | null | null | null | concurrency/02_lambda_thread.cpp | anancds/modern-cpp | 4d656b56e33f437fd586f963ac49f760e6e23238 | [
"MIT"
] | null | null | null | //
// Created by cds on 2020/10/7.
//
#include <iostream>
#include <thread>
using namespace std;
int main() {
thread t([] {
cout << "Hello World from lambda thread." << endl;
});
t.join();
return 0;
} | 12.055556 | 54 | 0.580645 | anancds |
c6a6e62e35813b9c4c76fc6e998c0d57d7412b01 | 12,044 | hpp | C++ | src/LinAlg/hiopMatrixSparseCSR.hpp | fritzgoebel/hiop | 86e4e1b9899a0e21d74a3ad9a8aa973e0e289b98 | [
"BSD-3-Clause"
] | null | null | null | src/LinAlg/hiopMatrixSparseCSR.hpp | fritzgoebel/hiop | 86e4e1b9899a0e21d74a3ad9a8aa973e0e289b98 | [
"BSD-3-Clause"
] | null | null | null | src/LinAlg/hiopMatrixSparseCSR.hpp | fritzgoebel/hiop | 86e4e1b9899a0e21d74a3ad9a8aa973e0e289b98 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021-2022, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory (LLNL).
// LLNL-CODE-742473. All rights reserved.
//
// This file is part of HiOp. For details, see https://github.com/LLNL/hiop. HiOp
// is released under the BSD 3-clause license (https://opensource.org/licenses/BSD-3-Clause).
// Please also read "Additional BSD Notice" below.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// i. Redistributions of source code must retain the above copyright notice, this list
// of conditions and the disclaimer below.
// ii. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the disclaimer (as noted below) in the documentation and/or
// other materials provided with the distribution.
// iii. Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
//
// Additional BSD Notice
// 1. This notice is required to be provided under our contract with the U.S. Department
// of Energy (DOE). This work was produced at Lawrence Livermore National Laboratory under
// Contract No. DE-AC52-07NA27344 with the DOE.
// 2. Neither the United States Government nor Lawrence Livermore National Security, LLC
// nor any of their employees, makes any warranty, express or implied, or assumes any
// liability or responsibility for the accuracy, completeness, or usefulness of any
// information, apparatus, product, or process disclosed, or represents that its use would
// not infringe privately-owned rights.
// 3. Also, reference herein to any specific commercial products, process, or services by
// trade name, trademark, manufacturer or otherwise does not necessarily constitute or
// imply its endorsement, recommendation, or favoring by the United States Government or
// Lawrence Livermore National Security, LLC. The views and opinions of authors expressed
// herein do not necessarily state or reflect those of the United States Government or
// Lawrence Livermore National Security, LLC, and shall not be used for advertising or
// product endorsement purposes.
/**
* @file hiopMatrixSparseCSR.hpp
*
* @author Cosmin G. Petra <petra1@lnnl.gov>, LNNL
*
*/
#ifndef HIOP_SPARSE_MATRIX_CSR
#define HIOP_SPARSE_MATRIX_CSR
#include "hiopVector.hpp"
#include "hiopMatrixDense.hpp"
#include "hiopMatrixSparse.hpp"
#include "hiopMatrixSparseTriplet.hpp"
#include <cassert>
#include <unordered_map>
namespace hiop
{
/**
* @brief Abstract class for compressed sparse row storage for sparse matrices.
*/
class hiopMatrixSparseCSR : public hiopMatrixSparse
{
public:
hiopMatrixSparseCSR(int num_rows, int num_cols, int nnz)
: hiopMatrixSparse(num_rows, num_cols, nnz)
{
}
hiopMatrixSparseCSR()
: hiopMatrixSparseCSR(0, 0, 0)
{
}
virtual ~hiopMatrixSparseCSR()
{
}
/////////////////////////////////////////////////////////////////////
// Below are CSR-specific methods (addition to hiopMatrixSparse)
/////////////////////////////////////////////////////////////////////
/**
* @brief Extracts the diagonal entries of `this` matrix into the vector passed as argument
*
* @pre `this` matrix needs to be symmetric and of same size(s) as `diag_out`
*/
virtual void extract_diagonal(hiopVector& diag_out) const = 0;
/**
* Sets the diagonal of `this` to the constant `val`. If `val` is zero, the sparsity pattern
* of `this` is not altered.
*
* @pre `this` is expected to store the diagonal entries as nonzero elements.
*/
virtual void set_diagonal(const double& val) = 0;
/**
* Allocates a CSR matrix capable of storing the multiplication result of M = X*Y, where X
* is the calling matrix class (`this`) and Y is the `Y` argument of the method.
*
* @note Should be used in conjunction with `times_mat_symbolic` and `times_mat_numeric`
*
* @pre The dimensions of the matrices should be consistent with the multiplication.
*
*/
virtual hiopMatrixSparseCSR* times_mat_alloc(const hiopMatrixSparseCSR& Y) const = 0;
/**
* Computes sparsity pattern, meaning computes row pointers and column indexes of `M`,
* of M = X*Y, where X is the calling matrix class (`this`) and Y is the second argument.
*
* @note The output matrix `M` will have unique and ordered column indexes (with the same
* row)
*
* @note Specializations of this class may only be able to compute the sparsity pattern in
* tandem with the numerical multiplications (for example, because of API limitations).
* In this cases, the `times_mat_numeric` will take over sparsity computations and the
* arrays with row pointers and column indexes may be uninitialized after this call.
*
* @pre The dimensions of the matrices should be consistent with the multiplication.
*
* @pre The column indexes within the same row must be unique and ordered for `Y`.
*
* @pre The internal arrays of `M` should have enough storage to hold the sparsity
* pattern (row pointers and column indexes) and values of the multiplication result.
* This preallocation can be done by calling `times_mat_alloc` prior to this method.
*
*/
virtual void times_mat_symbolic(hiopMatrixSparseCSR& M, const hiopMatrixSparseCSR& Y) const = 0;
/**
* Computes (numerical values of) M = beta*M + alpha*X*D*Y, where X is the calling matrix
* class (`this`), beta and alpha are scalars passed as arguments, and M and Y are matrices
* of appropriate sizes passed as arguments.
*
* @note Generally, only the nonzero values of the input/output argument `M` are updated
* since the sparsity pattern (row pointers and column indexes) of `M` should have been
* already computed by `times_mat_symbolic`. Some specializations of this method may be
* restricted to performing both phases in inside this method.
*
* @pre The dimensions of the matrices should be consistent with the multiplication.
*
* @pre The column indexes within the same row must be unique and ordered both for input
* matrices and result matrix `M`.
*
* @pre The indexes arrays of `this`, `Y`, and `M` should not have changed since the
* last call to `times_diag_times_mat`.
*
* Example of usage:
* //initially allocate and compute M
* auto* M = X.times_mat_alloc(Y);
* X.times_mat_symbolic(M, Y);
* X.times_mat_numeric(0.0, M, 1.0, Y);
* ... calculations ....
* //if only nonzero entries of X and Y have changed, call the fast multiplication routine
* X.times_mat_numeric(0.0, M, 1.0, Y);
*
*/
virtual void times_mat_numeric(double beta,
hiopMatrixSparseCSR& M,
double alpha,
const hiopMatrixSparseCSR& Y) = 0;
/// @brief Column scaling or right multiplication by a diagonal: `this`=`this`*D
virtual void scale_cols(const hiopVector& D) = 0;
/// @brief Row scaling or left multiplication by a diagonal: `this`=D*`this`
virtual void scale_rows(const hiopVector& D) = 0;
/**
* Allocates and populates the sparsity pattern of `this` as the CSR representation
* of the triplet matrix `M`.
*
* @pre The input argument should have the nonzeros sorted by row and then by column
* indexes.
*/
virtual void form_from_symbolic(const hiopMatrixSparseTriplet& M) = 0;
/**
* Copies the numerical values of the triplet matrix M into the CSR matrix `this`
*
* @pre The sparsity pattern (row pointers and column indexes arrays) of `this` should be
* allocated and populated, possibly by a previous call to `form_from_symbolic`
*
* @pre The input argument should have the nonzeros sorted by row and then by column
* indexes.
*/
virtual void form_from_numeric(const hiopMatrixSparseTriplet& M) = 0;
/**
* Allocates and populates the sparsity pattern of `this` as the CSR representation
* of transpose of the triplet matrix `M`.
*
* @pre The input argument should have the nonzeros sorted by row and then by column
* indexes.
*/
virtual void form_transpose_from_symbolic(const hiopMatrixSparseTriplet& M) = 0;
/**
* Copies the numerical values of the transpose of the triplet matrix M into the
* CSR matrix `this`
*
* @pre The sparsity pattern (row pointers and column indexes arrays) of `this` should be
* allocated and populated, possibly by a previous call to `form_transpose_from_symbolic`
*
* @pre The input argument should have the nonzeros sorted by row and then by column
* indexes.
*/
virtual void form_transpose_from_numeric(const hiopMatrixSparseTriplet& M) = 0;
/**
* (Re)Initializes `this` to a diagonal matrix with diagonal entries given by D.
*/
virtual void form_diag_from_symbolic(const hiopVector& D) = 0;
/**
* Sets the diagonal entries of `this` equal to entries of D
*
* @pre Length of `D` should be equal to size(s) of `this`
*
* @pre `this` should be a diagonal matrix (in CSR format) with storage for
* all the diagonal entries, which can be ensured by calling the sister method
* `form_diag_from_symbolic`
*/
virtual void form_diag_from_numeric(const hiopVector& D) = 0;
/**
* Allocates and returns CSR matrix `M` capable of holding M = X+Y, where X is
* the calling matrix class (`this`) and Y is the argument passed to the method.
*/
virtual hiopMatrixSparseCSR* add_matrix_alloc(const hiopMatrixSparseCSR& Y) const = 0;
/**
* Computes sparsity pattern of M = X+Y (i.e., populates the row pointers and
* column indexes arrays) of `M`.
*
* @pre `this` and `Y` should hold matrices of identical dimensions.
*
*/
virtual void add_matrix_symbolic(hiopMatrixSparseCSR& M, const hiopMatrixSparseCSR& Y) const = 0;
/**
* Performs matrix addition M = gamma*M + alpha*X + beta*Y numerically, where
* X is `this` and gamma, alpha, and beta are scalars.
*
* @pre `M`, `this` and `Y` should hold matrices of identical dimensions.
*
* @pre `M` and `X+Y` should have identical sparsity pattern, namely the
* `add_matrix_symbolic` should have been called previously.
*
*/
virtual void add_matrix_numeric(double gamma,
hiopMatrixSparseCSR& M,
double alpha,
const hiopMatrixSparseCSR& Y,
double beta) const = 0;
/// @brief Performs a quick check and returns false if the CSR indexes are not ordered
virtual bool check_csr_is_ordered() = 0;
/////////////////////////////////////////////////////////////////////
// end of new CSR-specific methods
/////////////////////////////////////////////////////////////////////
protected:
//// inherits nrows_, ncols_, and nnz_ from parent hiopSparseMatrix
private:
hiopMatrixSparseCSR(const hiopMatrixSparseCSR&) = delete;
};
} //end of namespace
#endif
| 41.965157 | 100 | 0.692876 | fritzgoebel |
c6a82e2f63884345bb9166e4363862402b108fb3 | 286 | cpp | C++ | Source/SystemQOR/Linux/LinQSys/version.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/SystemQOR/Linux/LinQSys/version.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/SystemQOR/Linux/LinQSys/version.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | #ifdef SHARED
#include "LinQSys/version.h"
namespace nsLinux
{
static const char version[] = VERSION;
//------------------------------------------------------------------------------
const char *__libc_get_version()
{
return version;
}
}//nsLinux
#endif
| 16.823529 | 84 | 0.454545 | mfaithfull |
c6a9bf6bfb008d91a3aa4234d2c5692aa2b6c9b9 | 15,856 | hpp | C++ | PGC_openssl/depends/twisted_elgamal/twisted_elgamal.hpp | yuchen1024/libPGC | 9720b9e750991fee4fe7253b446ea7761665e424 | [
"MIT"
] | 9 | 2019-08-26T05:40:45.000Z | 2021-03-29T03:03:37.000Z | PGC_openssl/depends/twisted_elgamal/twisted_elgamal.hpp | yuchen1024/libPGC | 9720b9e750991fee4fe7253b446ea7761665e424 | [
"MIT"
] | null | null | null | PGC_openssl/depends/twisted_elgamal/twisted_elgamal.hpp | yuchen1024/libPGC | 9720b9e750991fee4fe7253b446ea7761665e424 | [
"MIT"
] | 2 | 2019-11-10T11:25:43.000Z | 2020-06-10T08:09:24.000Z | /****************************************************************************
this hpp implements twisted ElGamal encrypt scheme
*****************************************************************************
* @author This file is part of PGC, developed by Yu Chen
* @paper https://eprint.iacr.org/2019/319
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef __ENC__
#define __ENC__
#include "../common/global.hpp"
#include "../common/hash.hpp"
#include "../common/print.hpp"
#include "../common/routines.hpp"
#include "calculate_dlog.hpp"
const string hashmap_file = "point2index.table"; // name of hashmap file
// define the structure of PP
struct Twisted_ElGamal_PP
{
size_t MSG_LEN; // the length of message space, also the length of the DLOG interval
BIGNUM *BN_MSG_SIZE; // the size of message space
size_t TUNNING; //increase this parameter in [0, RANGE_LEN/2]: larger table leads to less running time
size_t IO_THREAD_NUM; // optimized number of threads for faster building hash map
size_t DEC_THREAD_NUM; // optimized number of threads for faster decryption: CPU dependent
EC_POINT *g;
EC_POINT *h; // two random generators
};
// define the structure of keypair
struct Twisted_ElGamal_KP
{
EC_POINT *pk; // define pk
BIGNUM *sk; // define sk
};
// define the structure of ciphertext
struct Twisted_ElGamal_CT
{
EC_POINT *X; // X = pk^r
EC_POINT *Y; // Y = g^m h^r
};
// define the structure of two-recipients one-message ciphertext (MR denotes multiple recipients)
struct MR_Twisted_ElGamal_CT
{
EC_POINT *X1; // X = pk1^r
EC_POINT *X2; // X = pk2^r
EC_POINT *Y; // Y = G^m H^r
};
/* allocate memory for PP */
void Twisted_ElGamal_PP_new(Twisted_ElGamal_PP &pp)
{
pp.g = EC_POINT_new(group);
pp.h = EC_POINT_new(group);
pp.BN_MSG_SIZE = BN_new();
}
/* free memory of PP */
void Twisted_ElGamal_PP_free(Twisted_ElGamal_PP &pp)
{
EC_POINT_free(pp.g);
EC_POINT_free(pp.h);
BN_free(pp.BN_MSG_SIZE);
}
void Twisted_ElGamal_KP_new(Twisted_ElGamal_KP &keypair)
{
keypair.pk = EC_POINT_new(group);
keypair.sk = BN_new();
}
void Twisted_ElGamal_KP_free(Twisted_ElGamal_KP &keypair)
{
EC_POINT_free(keypair.pk);
BN_free(keypair.sk);
}
void Twisted_ElGamal_CT_new(Twisted_ElGamal_CT &CT)
{
CT.X = EC_POINT_new(group);
CT.Y = EC_POINT_new(group);
}
void Twisted_ElGamal_CT_free(Twisted_ElGamal_CT &CT)
{
EC_POINT_free(CT.X);
EC_POINT_free(CT.Y);
}
void MR_Twisted_ElGamal_CT_new(MR_Twisted_ElGamal_CT &CT)
{
CT.X1 = EC_POINT_new(group);
CT.X2 = EC_POINT_new(group);
CT.Y = EC_POINT_new(group);
}
void MR_Twisted_ElGamal_CT_free(MR_Twisted_ElGamal_CT &CT)
{
EC_POINT_free(CT.X1);
EC_POINT_free(CT.X2);
EC_POINT_free(CT.Y);
}
void Twisted_ElGamal_PP_print(Twisted_ElGamal_PP &pp)
{
cout << "the length of message space = " << pp.MSG_LEN << endl;
cout << "the tunning parameter for fast decryption = " << pp.TUNNING << endl;
ECP_print(pp.g, "pp.g");
ECP_print(pp.h, "pp.h");
}
void Twisted_ElGamal_KP_print(Twisted_ElGamal_KP &keypair)
{
ECP_print(keypair.pk, "pk");
BN_print(keypair.sk, "sk");
}
void Twisted_ElGamal_CT_print(Twisted_ElGamal_CT &CT)
{
ECP_print(CT.X, "CT.X");
ECP_print(CT.Y, "CT.Y");
}
void MR_Twisted_ElGamal_CT_print(MR_Twisted_ElGamal_CT &CT)
{
ECP_print(CT.X1, "CT.X1");
ECP_print(CT.X2, "CT.X2");
ECP_print(CT.Y, "CT.Y");
}
void Twisted_ElGamal_CT_serialize(Twisted_ElGamal_CT &CT, ofstream &fout)
{
ECP_serialize(CT.X, fout);
ECP_serialize(CT.Y, fout);
}
void Twisted_ElGamal_CT_deserialize(Twisted_ElGamal_CT &CT, ifstream &fin)
{
ECP_deserialize(CT.X, fin);
ECP_deserialize(CT.Y, fin);
}
void MR_Twisted_ElGamal_CT_serialize(MR_Twisted_ElGamal_CT &CT, ofstream& fout)
{
ECP_serialize(CT.X1, fout);
ECP_serialize(CT.X2, fout);
ECP_serialize(CT.Y, fout);
}
void MR_Twisted_ElGamal_CT_deserialize(MR_Twisted_ElGamal_CT &CT, ifstream& fin)
{
ECP_deserialize(CT.X1, fin);
ECP_deserialize(CT.X2, fin);
ECP_deserialize(CT.Y, fin);
}
/* Setup algorithm */
void Twisted_ElGamal_Setup(Twisted_ElGamal_PP &pp, size_t MSG_LEN, size_t TUNNING,
size_t IO_THREAD_NUM, size_t DEC_THREAD_NUM)
{
pp.MSG_LEN = MSG_LEN;
pp.TUNNING = TUNNING;
pp.IO_THREAD_NUM = IO_THREAD_NUM;
pp.DEC_THREAD_NUM = DEC_THREAD_NUM;
/* set the message space to 2^{MSG_LEN} */
BN_set_word(pp.BN_MSG_SIZE, uint64_t(pow(2, pp.MSG_LEN)));
#ifdef DEBUG
cout << "message space = [0, ";
cout << BN_bn2hex(pp.BN_MSG_SIZE) << ')' << endl;
#endif
EC_POINT_copy(pp.g, generator);
/* generate pp.h via deterministic manner */
Hash_ECP_to_ECP(pp.g, pp.h);
#ifdef DEBUG
cout << "generate the public parameters for twisted ElGamal >>>" << endl;
Twisted_ElGamal_PP_print(pp);
#endif
}
void Twisted_ElGamal_Initialize(Twisted_ElGamal_PP &pp)
{
cout << "Initialize Twisted ElGamal >>>" << endl;
/* generate or load the point2index.table */
if(!FILE_exist(hashmap_file))
{
// generate and serialize the point_2_index table
Parallel_HASHMAP_serialize(pp.h, hashmap_file, pp.MSG_LEN, pp.TUNNING, pp.IO_THREAD_NUM);
}
// load the table from file
HASHMAP_deserialize(hashmap_file, pp.MSG_LEN, pp.TUNNING);
}
/* KeyGen algorithm */
void Twisted_ElGamal_KeyGen(Twisted_ElGamal_PP &pp, Twisted_ElGamal_KP &keypair)
{
BN_random(keypair.sk); // sk \sample Z_p
EC_POINT_mul(group, keypair.pk, keypair.sk, NULL, NULL, bn_ctx); // pk = g^sk
#ifdef DEBUG
cout << "key generation finished >>>" << endl;
Twisted_ElGamal_KP_print(keypair);
#endif
}
/* Encryption algorithm: compute CT = Enc(pk, m; r) */
void Twisted_ElGamal_Enc(Twisted_ElGamal_PP &pp,
EC_POINT* &pk,
BIGNUM* &m,
Twisted_ElGamal_CT &CT)
{
// generate the random coins
BIGNUM *r = BN_new();
BN_random(r);
// begin encryption
EC_POINT_mul(group, CT.X, NULL, pk, r, bn_ctx); // X = pk^r
EC_POINT_mul(group, CT.Y, r, pp.h, m, bn_ctx); // Y = g^r h^m
BN_free(r);
#ifdef DEBUG
cout << "twisted ElGamal encryption finishes >>>"<< endl;
Twisted_ElGamal_CT_print(CT);
#endif
}
/* Encryption algorithm: compute CT = Enc(pk, m; r): with explicit randomness */
void Twisted_ElGamal_Enc(Twisted_ElGamal_PP &pp,
EC_POINT* &pk,
BIGNUM* &m,
BIGNUM* &r,
Twisted_ElGamal_CT &CT)
{
// begin encryption
EC_POINT_mul(group, CT.X, NULL, pk, r, bn_ctx); // X = pk^r
EC_POINT_mul(group, CT.Y, r, pp.h, m, bn_ctx); // Y = g^r h^m
#ifdef DEBUG
cout << "twisted ElGamal encryption finishes >>>"<< endl;
Twisted_ElGamal_CT_print(CT);
#endif
}
/* Decryption algorithm: compute m = Dec(sk, CT) */
void Twisted_ElGamal_Dec(Twisted_ElGamal_PP &pp,
BIGNUM* &sk,
Twisted_ElGamal_CT &CT,
BIGNUM* &m)
{
//begin decryption
BIGNUM *sk_inverse = BN_new();
BN_mod_inverse(sk_inverse, sk, order, bn_ctx); // compute the inverse of sk in Z_q^*
EC_POINT *M = EC_POINT_new(group);
EC_POINT_mul(group, M, NULL, CT.X, sk_inverse, bn_ctx); // M = X^{sk^{-1}} = g^r
EC_POINT_invert(group, M, bn_ctx); // M = -g^r
EC_POINT_add(group, M, CT.Y, M, bn_ctx); // M = h^m
//Brute_Search(m, pp.h, M);
bool success = Shanks_DLOG(m, pp.h, M, pp.MSG_LEN, pp.TUNNING); // use Shanks's algorithm to decrypt
BN_free(sk_inverse);
EC_POINT_free(M);
if(success == false)
{
cout << "decyption fails in the specified range";
exit(EXIT_FAILURE);
}
}
/* rerandomize ciphertext CT with given randomness r */
void Twisted_ElGamal_ReRand(Twisted_ElGamal_PP &pp,
EC_POINT* &pk,
BIGNUM* &sk,
Twisted_ElGamal_CT &CT,
Twisted_ElGamal_CT &CT_new,
BIGNUM* &r)
{
// begin partial decryption
BIGNUM *sk_inverse = BN_new();
BN_mod_inverse(sk_inverse, sk, order, bn_ctx); // compute the inverse of sk in Z_q^*
EC_POINT *M = EC_POINT_new(group);
EC_POINT_mul(group, M, NULL, CT.X, sk_inverse, bn_ctx); // M = X^{sk^{-1}} = g^r
EC_POINT_invert(group, M, bn_ctx); // M = -g^r
EC_POINT_add(group, M, CT.Y, M, bn_ctx); // M = h^m
// begin re-encryption with the given randomness
EC_POINT_mul(group, CT_new.X, NULL, pk, r, bn_ctx); // CT_new.X = pk^r
EC_POINT_mul(group, CT_new.Y, r, NULL, NULL, bn_ctx); // CT_new.Y = g^r
EC_POINT_add(group, CT_new.Y, CT_new.Y, M, bn_ctx); // M = h^m
#ifdef DEBUG
cout << "refresh ciphertext succeeds >>>"<< endl;
Twisted_ElGamal_CT_print(CT_new);
#endif
BN_free(sk_inverse);
EC_POINT_free(M);
}
/* homomorphic add */
void Twisted_ElGamal_HomoAdd(Twisted_ElGamal_CT &CT_result, Twisted_ElGamal_CT &CT1, Twisted_ElGamal_CT &CT2)
{
EC_POINT_add(group, CT_result.X, CT1.X, CT2.X, bn_ctx);
EC_POINT_add(group, CT_result.Y, CT1.Y, CT2.Y, bn_ctx);
}
/* homomorphic sub */
void Twisted_ElGamal_HomoSub(Twisted_ElGamal_CT &CT_result, Twisted_ElGamal_CT &CT1, Twisted_ElGamal_CT &CT2)
{
EC_POINT_sub(CT_result.X, CT1.X, CT2.X);
EC_POINT_sub(CT_result.Y, CT1.Y, CT2.Y);
}
/* scalar operation */
void Twisted_ElGamal_ScalarMul(Twisted_ElGamal_CT &CT_result, Twisted_ElGamal_CT &CT, BIGNUM *&k)
{
EC_POINT_mul(group, CT_result.X, NULL, CT.X, k, bn_ctx);
EC_POINT_mul(group, CT_result.Y, NULL, CT.Y, k, bn_ctx);
}
/* Encryption algorithm (2-recipients 1-message) with given random coins
output X1 = pk1^r, X2 = pk2^r, Y = g^r h^m
Here we make the randomness explict for the ease of generating the ZKP */
void MR_Twisted_ElGamal_Enc(Twisted_ElGamal_PP &pp,
EC_POINT* &pk1,
EC_POINT* &pk2,
BIGNUM* &m,
BIGNUM* &r,
MR_Twisted_ElGamal_CT &CT)
{
EC_POINT_mul(group, CT.X1, NULL, pk1, r, bn_ctx); // CT_new.X1 = pk1^r
EC_POINT_mul(group, CT.X2, NULL, pk2, r, bn_ctx); // CT_new.X2 = pk2^r
EC_POINT_mul(group, CT.Y, r, pp.h, m, bn_ctx); // Y = g^r h^m
#ifdef DEBUG
cout << "2-recipient 1-message twisted ElGamal encryption finishes >>>"<< endl;
MR_Twisted_ElGamal_CT_print(CT);
#endif
}
/* parallel implementation */
/*
https://www.openssl.org/docs/manmaster/man3/BN_CTX_new.html
A given BN_CTX must only be used by a single thread of execution.
No locking is performed, and the internal pool allocator will not properly handle multiple threads of execution.
Thus, in multithread programming, a lazy and safe approach is setting bn_ctx = NULL
*/
// parallel encryption
inline void exp_operation(EC_POINT *&RESULT, EC_POINT *&A, BIGNUM *&r)
{
EC_POINT_mul(group, RESULT, NULL, A, r, NULL); // RESULT = A^r
}
inline void builtin_exp_operation(EC_POINT *&RESULT, BIGNUM *&r)
{
EC_POINT_mul(group, RESULT, r, NULL, NULL, NULL); // RESULT = g^r
}
inline void multiexp_operation(EC_POINT *&RESULT, EC_POINT *&h, BIGNUM *&r, BIGNUM *&m)
{
EC_POINT_mul(group, RESULT, r, h, m, bn_ctx); // Y = g^r h^m
}
/* Parallel Encryption algorithm: compute CT = Enc(pk, m; r) */
void Twisted_ElGamal_Parallel_Enc(Twisted_ElGamal_PP &pp, EC_POINT *&pk, BIGNUM *&m, Twisted_ElGamal_CT &CT)
{
/* generate fresh randomness */
BIGNUM *r = BN_new();
BN_random(r);
thread enc_thread1(exp_operation, std::ref(CT.X), std::ref(pk), std::ref(r)); // spawn new thread that calls foo()
thread enc_thread2(multiexp_operation, std::ref(CT.Y), std::ref(pp.h), std::ref(r), std::ref(m));
// synchronize threads
enc_thread1.join(); // pauses until first finishes
enc_thread2.join(); // pauses until second finishes
BN_free(r);
}
/* Decryption algorithm: compute m = Dec(sk, CT) */
void Twisted_ElGamal_Parallel_Dec(Twisted_ElGamal_PP &pp, BIGNUM *&sk, Twisted_ElGamal_CT &CT, BIGNUM *&m)
{
/* begin to decrypt */
BIGNUM *sk_inverse = BN_new();
BN_mod_inverse(sk_inverse, sk, order, bn_ctx); // compute the inverse of sk in Z_p^*
EC_POINT *M = EC_POINT_new(group);
EC_POINT_mul(group, M, NULL, CT.X, sk_inverse, bn_ctx); // M = X^{sk^{-1}} = g^r
EC_POINT_invert(group, M, bn_ctx); // M = -g^r
EC_POINT_add(group, M, CT.Y, M, bn_ctx); // M = h^m
bool success = Parallel_Shanks_DLOG(m, pp.h, M, pp.MSG_LEN, pp.TUNNING, pp.DEC_THREAD_NUM); // use Shanks's algorithm to decrypt
BN_free(sk_inverse);
EC_POINT_free(M);
if(success == false)
{
cout << "decyption fails: cannot find the message in the specified range";
exit(EXIT_FAILURE);
}
}
// parallel re-randomization
void Twisted_ElGamal_Parallel_ReRand(Twisted_ElGamal_PP &pp, EC_POINT *&pk, BIGNUM *&sk,
Twisted_ElGamal_CT &CT, Twisted_ElGamal_CT &CT_new, BIGNUM *&r)
{
/* partial decryption: only recover M = h^m */
BIGNUM *sk_inverse = BN_new();
BN_mod_inverse(sk_inverse, sk, order, bn_ctx); // compute the inverse of sk in Z_p^*
EC_POINT *M = EC_POINT_new(group);
EC_POINT_mul(group, M, NULL, CT.X, sk_inverse, bn_ctx); // M = X^{sk^{-1}} = g^r
EC_POINT_invert(group, M, bn_ctx); // M = -g^r
EC_POINT_add(group, M, CT.Y, M, bn_ctx); // M = h^m
/* re-encryption with the given randomness */
thread rerand_thread1(exp_operation, std::ref(CT.X), std::ref(pk), std::ref(r));
thread rerand_thread2(builtin_exp_operation, std::ref(CT.Y), std::ref(r));
rerand_thread1.join();
rerand_thread2.join();
EC_POINT_add(group, CT_new.Y, CT_new.Y, M, bn_ctx); // Y = g^r h^m
BN_free(sk_inverse);
EC_POINT_free(M);
}
/* parallel homomorphic add */
inline void add_operation(EC_POINT *&RESULT, EC_POINT *&X, EC_POINT *&Y)
{
EC_POINT_add(group, RESULT, X, Y, NULL);
}
void Twisted_ElGamal_Parallel_HomoAdd(Twisted_ElGamal_CT &CT_result, Twisted_ElGamal_CT &CT1, Twisted_ElGamal_CT &CT2)
{
thread add_thread1(add_operation, std::ref(CT_result.X), std::ref(CT1.X), std::ref(CT2.X));
thread add_thread2(add_operation, std::ref(CT_result.Y), std::ref(CT1.Y), std::ref(CT2.Y));
add_thread1.join();
add_thread2.join();
}
/* parallel homomorphic sub */
inline void sub_operation(EC_POINT *&RESULT, EC_POINT *&X, EC_POINT *&Y)
{
EC_POINT_sub_without_bnctx(RESULT, X, Y);
}
void Twisted_ElGamal_Parallel_HomoSub(Twisted_ElGamal_CT &CT_result, Twisted_ElGamal_CT &CT1, Twisted_ElGamal_CT &CT2)
{
thread sub_thread1(sub_operation, std::ref(CT_result.X), std::ref(CT1.X), std::ref(CT2.X));
thread sub_thread2(sub_operation, std::ref(CT_result.Y), std::ref(CT1.Y), std::ref(CT2.Y));
sub_thread1.join();
sub_thread2.join();
}
/* parallel scalar operation */
void Twisted_ElGamal_Parallel_ScalarMul(Twisted_ElGamal_CT &CT_result, Twisted_ElGamal_CT &CT, BIGNUM *&k)
{
thread scalar_thread1(exp_operation, std::ref(CT_result.X), std::ref(CT.X), std::ref(k));
thread scalar_thread2(exp_operation, std::ref(CT_result.Y), std::ref(CT.Y), std::ref(k));
// synchronize threads
scalar_thread1.join();
scalar_thread2.join();
}
#endif
| 31.585657 | 132 | 0.63528 | yuchen1024 |
c6b321375a31dce3fb29f1543b4fd49167282238 | 2,700 | cpp | C++ | XboxFramework/Texture.cpp | luca1337/D3D11XboxFramework | 92bafecb443d3fabbf4b302da2e55322657acc42 | [
"MIT"
] | null | null | null | XboxFramework/Texture.cpp | luca1337/D3D11XboxFramework | 92bafecb443d3fabbf4b302da2e55322657acc42 | [
"MIT"
] | null | null | null | XboxFramework/Texture.cpp | luca1337/D3D11XboxFramework | 92bafecb443d3fabbf4b302da2e55322657acc42 | [
"MIT"
] | null | null | null | #include "Texture.h"
#include "Engine.h"
#include "Window.h"
#include "ShaderObject.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
Texture::Texture(UINT width, UINT height, DXGI_FORMAT format) : width(width), height(height)
{
// create a new texture
D3D11_TEXTURE2D_DESC tex_desc = {};
tex_desc.ArraySize = 1;
if (format == DXGI_FORMAT_D24_UNORM_S8_UINT)
{
tex_desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
}
else
{
tex_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
}
tex_desc.Format = format;
tex_desc.Height = height;
tex_desc.Width = width;
tex_desc.MipLevels = 1;
tex_desc.Usage = D3D11_USAGE_DEFAULT;
tex_desc.SampleDesc.Count = 1;
tex_desc.SampleDesc.Quality = 0;
if (Engine::Singleton().GetDxDevice()->GetDXHandle()->CreateTexture2D(&tex_desc, nullptr, &texture) != S_OK)
{
throw std::exception("unable to create texture");
}
}
Texture::Texture(std::string file_path)
{
DXGI_FORMAT format;
// Load texture from file
int w, h, ch;
stbi_uc* pixels = stbi_load(file_path.c_str(), &w, &h, &ch, 4);
format = DXGI_FORMAT_R8G8B8A8_UNORM;
if (!pixels)
{
throw std::exception("unable to retrieve pixels data from texture resource.");
}
// Assign w and h
width = w;
height = h;
// create a new texture
D3D11_TEXTURE2D_DESC tex_desc = {};
tex_desc.ArraySize = 1;
if (format == DXGI_FORMAT_D24_UNORM_S8_UINT)
{
tex_desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
}
else
{
tex_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
}
tex_desc.Format = format;
tex_desc.Height = height;
tex_desc.Width = width;
tex_desc.MipLevels = 1;
tex_desc.Usage = D3D11_USAGE_DEFAULT;
tex_desc.SampleDesc.Count = 1;
tex_desc.SampleDesc.Quality = 0;
if (Engine::Singleton().GetDxDevice()->GetDXHandle()->CreateTexture2D(&tex_desc, nullptr, &texture) != S_OK)
{
throw std::exception("unable to create texture");
}
// UPLOAD IT ON GPU
Upload(pixels, width * 4, 0);
// Create our shader object in order to bind our texture
image = std::make_shared<ShaderObject>(*this);
//image->Bind(0);
}
Texture::Texture(std::shared_ptr<Window> window)
{
texture = window->GetDXTexture();
D3D11_TEXTURE2D_DESC tex_desc;
texture->GetDesc(&tex_desc);
width = tex_desc.Width;
height = tex_desc.Height;
}
void Texture::Upload(void* data, UINT pitch, UINT depth)
{
Engine::Singleton().GetDxDevice()->GetDXContext()->UpdateSubresource(texture, 0, nullptr, data, pitch, depth);
}
ID3D11Texture2D* Texture::GetDXHandle() { return texture; }
std::shared_ptr<ShaderObject> Texture::GetShaderObject()
{
return image;
}
UINT Texture::GetWidth() { return width; }
UINT Texture::GetHeight() { return height; } | 24.107143 | 111 | 0.728148 | luca1337 |
c6b36520f2174eec4ec06f688ce9f924539d63de | 1,035 | cpp | C++ | ares/md/interface/interface.cpp | moon-chilled/Ares | 909fb098c292f8336d0502dc677050312d8b5c81 | [
"0BSD"
] | 7 | 2020-07-25T11:44:39.000Z | 2021-01-29T13:21:31.000Z | ares/md/interface/interface.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | null | null | null | ares/md/interface/interface.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | 1 | 2021-03-22T16:15:30.000Z | 2021-03-22T16:15:30.000Z | #include <md/md.hpp>
namespace ares::MegaDrive {
Interface* interface = nullptr;
auto MegaDriveInterface::game() -> string {
if(expansion.node && (!cartridge.node || !cartridge.bootable())) {
if(mcd.disc) return mcd.name();
return expansion.name();
}
if(cartridge.node && cartridge.bootable()) {
return cartridge.name();
}
return "(no cartridge connected)";
}
auto MegaDriveInterface::root() -> Node::Object {
return system.node;
}
auto MegaDriveInterface::load(Node::Object& root) -> void {
interface = this;
system.load(root);
}
auto MegaDriveInterface::unload() -> void {
system.unload();
}
auto MegaDriveInterface::save() -> void {
system.save();
}
auto MegaDriveInterface::power() -> void {
system.power(false);
}
auto MegaDriveInterface::run() -> void {
system.run();
}
auto MegaDriveInterface::serialize(bool synchronize) -> serializer {
return system.serialize(synchronize);
}
auto MegaDriveInterface::unserialize(serializer& s) -> bool {
return system.unserialize(s);
}
}
| 19.166667 | 68 | 0.684058 | moon-chilled |
c6b3cdcd60b407ab0803392db583ed427bb063e4 | 1,161 | cpp | C++ | src/test/TankWarlockTestCase.cpp | MaNGOSBot/Uno | e5c95da966c367f1425d0d1d737bfdfc14362964 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | 1 | 2018-05-06T12:13:04.000Z | 2018-05-06T12:13:04.000Z | src/test/TankWarlockTestCase.cpp | Lidocian/ZeroBots | 297072e07f85fc661e1b0e9a34c09580e3bfef14 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | src/test/TankWarlockTestCase.cpp | Lidocian/ZeroBots | 297072e07f85fc661e1b0e9a34c09580e3bfef14 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | #include "pch.h"
#include "aitest.h"
#include "../../modules/Bots/playerbot/strategy/warlock/WarlockAiObjectContext.h"
using namespace ai;
class TankWarlockTestCase : public EngineTestBase
{
CPPUNIT_TEST_SUITE( TankWarlockTestCase );
CPPUNIT_TEST( summonPet );
CPPUNIT_TEST( cc );
CPPUNIT_TEST( incompatibles );
CPPUNIT_TEST( stress );
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
EngineTestBase::setUp();
setupEngine(new WarlockAiObjectContext(ai), "tank", NULL);
}
protected:
void summonPet()
{
itemAvailable("soul shard", 2);
tickWithNoPet();
tickWithNoPet();
assertActions(">S:summon felguard>S:summon voidwalker");
}
void cc()
{
tickWithCcTarget("banish");
tickWithCcTarget("fear");
assertActions(">Cc:banish on cc>Cc:fear on cc");
}
void incompatibles()
{
engine->addStrategies("tank", "dps", NULL);
CPPUNIT_ASSERT(engine->ListStrategies() == "Strategies: dps");
}
void stress()
{
runStressTest();
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( TankWarlockTestCase );
| 20.017241 | 81 | 0.631352 | MaNGOSBot |
c6b9e9fe0b6b125539f3ba144a354208275ce8c7 | 5,039 | cpp | C++ | alzette_box.cpp | 11320808551/rotational_cryptanalysis_dl | 1f36617d27d30d793f68a028ede842b0c2e83bff | [
"MIT"
] | 3 | 2021-02-17T10:21:07.000Z | 2021-03-23T02:28:00.000Z | alzette_box.cpp | 11320808551/rotational_cryptanalysis_dl | 1f36617d27d30d793f68a028ede842b0c2e83bff | [
"MIT"
] | null | null | null | alzette_box.cpp | 11320808551/rotational_cryptanalysis_dl | 1f36617d27d30d793f68a028ede842b0c2e83bff | [
"MIT"
] | 1 | 2021-12-25T07:42:58.000Z | 2021-12-25T07:42:58.000Z | //alzette_dl function == theoretical correlation
//alzette_dl_exper function == experimental correlation
#include<iostream>
#include<cstdlib>
#include<cstdint>
#include<cmath>
#include<random>
#define XOR(p1,p2) (p1+p2-2*p1*p2)
#define AND(p1,p2) ((p1+p2-p1*p2)*0.5)
#define mix(p1,p2,p3) (p1*p2*p3-0.5*(p1*p2+p1*p3+p2*p3)+0.5*(p1+p2+p3))
#define ROR(x,t) ((x>>t)|(x<<(32-t)))
#define ROL(x,t) ((x<<t)|(x>>(32-t)))
using namespace std;
//////////////////////////////////////////////// random number generator
uint32_t p = 0x7fffffff;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0,p-1);
////////////////////////////////////////////////
bool maskdot(int mask, int value){
bool tmp = 0;
for(int i=0; i<=31; i++){
if(((mask>>i)&0x1) == 1) tmp ^= ((value>>i)&0x1);
}
return tmp;
}
void modadd(double *a, double *b, double *z, int wordsize){
double c[32] = {0};
c[0] = 0;
z[0] = XOR(a[0],b[0]);
for(int i=1; i<wordsize; i++){
c[i] = mix(a[i-1],b[i-1],c[i-1]);
z[i] = XOR(XOR(a[i],b[i]),c[i]);
}
}
void print(double *v){ //print correlation
for(int j=0; j<=3; j++){
for(int i=0; i<=7; i++){
cout << log2(abs(2*v[8*j+i]-1)) << " ";
}cout << endl;}
cout << endl;
}
void Shift_modadd(double *a, double *b, double *z, int wordsize, int shift){ //tailored for alzette, one of the operand to modadd is right rotated by Shift
double b_shift[32] = {0};
for(int i=0; i<=31; i++){
b_shift[i] = b[(i+shift)%wordsize]; //right rotate b by shift bits
}
modadd(a,b_shift,z,32);
}
void alzette_dl(double *a, double *b){ //32-bit modadd
double z1[32] = {0};
double w1[32] = {0};
Shift_modadd(a,b,z1,32,31);
for(int i=0; i<=31; i++){
w1[i] = XOR(b[i],z1[(i+24)%32]);
}
double z2[32] = {0};
double w2[32] = {0};
Shift_modadd(z1,w1,z2,32,17);
for(int i=0; i<=31; i++){
w2[i] = XOR(w1[i],z2[(i+17)%32]);
}
double z3[32] = {0};
double w3[32] = {0};
modadd(z2,w2,z3,32);
for(int i=0; i<=31; i++){
w3[i] = XOR(w2[i],z3[(i+31)%32]);
}
Shift_modadd(z3,w3,a,32,24);
for(int i=0; i<=31; i++){
b[i] = XOR(w3[i],a[(i+16)%32]);
}
}
void alzette_dl_exper(uint32_t diff1, uint32_t diff2, uint32_t c){
int counter[64] = {0}; //initialise counter, a[0..31] = counter[0..31], b[0..31] = counter[32..63]
for(int i = 0; i<=0xfff; i++){
for(int j = 0; j<=0xfff; j++){ //PT space = 24-dim
uint32_t x = (ROL((dis(gen))&0xffffffff,2) ^ ((dis(gen))&0xffffffff)); uint32_t y = (ROL((dis(gen))&0xffffffff,2) ^ ((dis(gen))&0xffffffff)); //the random number generater only has 31 bits, so we use this method to get 32-bit random numbers
uint32_t xp = x ^ diff1; uint32_t yp = y ^ diff2;
//alzette PT
x +=ROR(y ,31);y ^=ROR(x ,24);x ^=c ;
x +=ROR(y ,17);y ^=ROR(x ,17);x ^=c ;
x +=y ;y ^=ROR(x ,31);x ^=c;
x +=ROR(y ,24);y ^=ROR(x ,16);x ^=c;
//alzette PT
xp +=ROR(yp ,31);yp ^=ROR(xp ,24);xp ^=c ;
xp +=ROR(yp ,17);yp ^=ROR(xp ,17);xp ^=c ;
xp +=yp ;yp ^=ROR(xp ,31);xp ^=c;
xp +=ROR(yp ,24);yp ^=ROR(xp ,16);xp ^=c;
uint32_t delta_x = x ^ xp;
uint32_t delta_y = y ^ yp;
for(int index = 0; index <= 63; index++){ //for all one bit output masks
if(index<=31){
if(maskdot((0x00000001<<index), delta_x) == 1) counter[index]++;
//else counter[index]--;
}
else{
if(maskdot((0x00000001<<(index-32)), delta_y) == 1) counter[index]++;
//else counter[index]--;
}
}
}}
cout << "DL-Probability by experiment : " <<endl;
for(int index=0; index<=63; index++){
cout << (abs(counter[index])/pow(2,24)) << " ";
if((index+1)%16==0)cout << endl;
}
}
int main(){
uint32_t c[8] = {0xB7E15162,0xBF715880,0x38B4DA56,0x324E7738,0xBB1185EB,0x4F7C7B57,0xCFBFA1C8,0xC2B3293D};
for(int diff_pos = 0; diff_pos<=31; diff_pos++){
uint32_t diff1 = 0x0;
uint32_t diff2 = 0x1 << diff_pos;
double a[32] = {0};
double b[32] = {0};
cout << "a = ";
for(int i=0; i<=31; i++){a[i] = (diff1>>i)&0x1;cout << a[i] << " ";}cout << endl;
cout << "b = ";
for(int i=0; i<=31; i++){b[i] = (diff2>>i)&0x1;cout << b[i] << " ";}cout << endl;
alzette_dl(a,b);
cout << "DL-probability by theoretical prediction: " <<endl;
cout << "a: " << endl;
for(int i=0; i<=31; i++){cout << a[i] << " ";if((i+1)%16==0){cout << endl;}}cout << endl;
cout << "b: " << endl;
for(int i=0; i<=31; i++){cout << b[i] << " ";if((i+1)%16==0){cout << endl;}}cout << endl;
cout << "Correlation (1-2*p) by theoretical prediction: 2^" <<endl;
cout << "a: " << endl;
for(int i=0; i<=31; i++){cout << log2(abs(1-2*a[i])) << " ";if((i+1)%16==0){cout << endl;}}cout << endl;
cout << "b: " << endl;
for(int i=0; i<=31; i++){cout << log2(abs(1-2*b[i])) << " ";if((i+1)%16==0){cout << endl;}}cout << endl;
alzette_dl_exper(diff1,diff2,c[0]);
}
return 0;
}
| 34.278912 | 246 | 0.520937 | 11320808551 |
c6bc90fe6b1e908499a620f11296d84357fbb81f | 1,561 | hpp | C++ | include/desola/tg/Exceptions.hpp | FrancisRussell/desola | a469428466e4849c7c0e2009a0c50b89184cae01 | [
"Apache-2.0"
] | 2 | 2021-12-17T10:46:20.000Z | 2021-12-18T11:53:50.000Z | include/desola/tg/Exceptions.hpp | FrancisRussell/desola | a469428466e4849c7c0e2009a0c50b89184cae01 | [
"Apache-2.0"
] | null | null | null | include/desola/tg/Exceptions.hpp | FrancisRussell/desola | a469428466e4849c7c0e2009a0c50b89184cae01 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************/
/* Copyright 2005-2006, Francis Russell */
/* */
/* 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 DESOLA_TG_EXCEPTIONS_HPP
#define DESOLA_TG_EXCEPTIONS_HPP
#include <desola/Exceptions.hpp>
#include <string>
namespace desola
{
namespace detail
{
class TGInvalidOperationError : public DesolaRuntimeError
{
public:
TGInvalidOperationError(const std::string& error);
};
}
}
#endif
| 40.025641 | 78 | 0.436259 | FrancisRussell |
c6bd90c2a305cb3747f67878100748c809cdafd7 | 3,440 | hpp | C++ | tools/src/map/map.hpp | dasisttao/scan_matching | f3021ca28f86606d183b2f2c5b0cad45f04f6e12 | [
"MIT"
] | null | null | null | tools/src/map/map.hpp | dasisttao/scan_matching | f3021ca28f86606d183b2f2c5b0cad45f04f6e12 | [
"MIT"
] | null | null | null | tools/src/map/map.hpp | dasisttao/scan_matching | f3021ca28f86606d183b2f2c5b0cad45f04f6e12 | [
"MIT"
] | null | null | null | #pragma once
#include <ros/ros.h>
#include <csv/csv.h>
#include <scan_match/var_defs.hpp>
#include <scan_match/transform.hpp>
#include <scan_match/utils.hpp>
class MyMap
{
public:
void readMapCrossroad(sensor_msgs::PointCloud2 &my_map, MyPointCloud2D &map_crossroad);
void rotatePoint(double &x, double &y, double alpha);
void readMapParkhaus(sensor_msgs::PointCloud2 &my_map, MyPointCloud2D &map_carpark);
void readRawData(sensor_msgs::PointCloud2 &map_pc, MyPointCloud2D &map_carpark,std::string map_path);
private:
CoordTransform coord_transform;
RVIZ rviz;
};
void MyMap::rotatePoint(double &x, double &y, double alpha)
{
Vector2d temp;
Vector2d result;
Matrix2d rot_M;
alpha = alpha * M_PI / 180;
rot_M << cos(alpha),
-sin(alpha),
sin(alpha), cos(alpha);
temp << x, y;
result = rot_M * temp;
x = result(0);
y = result(1);
}
void MyMap::readMapCrossroad(sensor_msgs::PointCloud2 &my_map, MyPointCloud2D &map_crossroad) //-1440, -4200
{
double x, y;
MyPoint map_pt;
io::CSVReader<2> in2("src/scan_matching/map/kreuzung_utm.csv");
//Lat x, Long y
in2.read_header(io::ignore_extra_column, "x", "y");
int i = 0;
while (in2.read_row(x, y))
{
map_crossroad.ids.push_back(i);
vector<double> utm_pt;
vector<double> utm_local_pt;
utm_pt.push_back(x); // Lat
utm_pt.push_back(y); // Long
utm_pt.push_back(0);
utm_local_pt = coord_transform.UTM2Local(utm_pt);
map_pt.x = utm_local_pt[0];
map_pt.y = utm_local_pt[1];
map_crossroad.pts.push_back(map_pt);
map_crossroad.weights.push_back(1);
map_crossroad.distances.push_back(0);
i++;
}
my_map = rviz.createPointCloud(map_crossroad, "ibeo_lux", 1);
}
void MyMap::readMapParkhaus(sensor_msgs::PointCloud2 &map_pc, MyPointCloud2D &map_carpark)
{
double x, y;
MyPoint map_pt;
io::CSVReader<2> in2("src/icp_lokalisierung/scan_matching/map/parkhaus.csv");
//Local X , Local Y
in2.read_header(io::ignore_extra_column, "x", "y");
int i = 0;
while (in2.read_row(x, y))
{
map_carpark.ids.push_back(i);
rotatePoint(x, y, -72.523); //+ gegen Uhrzeiger
map_pt.x = x;
map_pt.y = y;
map_carpark.pts.push_back(map_pt);
map_carpark.weights.push_back(1);
map_carpark.distances.push_back(0);
i++;
}
map_pc = rviz.createPointCloud(map_carpark, "ibeo_lux", 1.0);
}
void MyMap::readRawData(sensor_msgs::PointCloud2 &map_pc, MyPointCloud2D &map_carpark,std::string map_path)
{
if(map_carpark.ids.size()!=0){
std::cout<< "\n Clear the Old Map Data "<<std::endl;
map_carpark.ids.clear();
map_carpark.pts.clear();
map_carpark.weights.clear();
map_carpark.distances.clear();
}
double x, y;
MyPoint map_pt;
io::CSVReader<2> in2(map_path);
//Local X , Local Y
in2.read_header(io::ignore_extra_column, "x", "y");
int i = 0;
while (in2.read_row(x, y))
{
map_carpark.ids.push_back(i);
//rotatePoint(x, y, -72.523); //+ gegen Uhrzeiger
map_pt.x = x;
map_pt.y = y;
map_carpark.pts.push_back(map_pt);
map_carpark.weights.push_back(1);
map_carpark.distances.push_back(0);
i++;
}
map_pc = rviz.createPointCloud(map_carpark, "ibeo_lux", 1.0);
}
| 28.429752 | 108 | 0.6375 | dasisttao |
c6bdc1cf590616904ad2d6e3c056c09e1d791646 | 10,732 | cpp | C++ | src/ASAF8.cpp | CardinalModules/mscHack | cf6b1aa5ae47a9e56a0f2ddb0c1aa54927134fb5 | [
"MIT"
] | null | null | null | src/ASAF8.cpp | CardinalModules/mscHack | cf6b1aa5ae47a9e56a0f2ddb0c1aa54927134fb5 | [
"MIT"
] | 1 | 2022-02-03T20:22:41.000Z | 2022-02-03T20:52:04.000Z | src/ASAF8.cpp | CardinalModules/mscHack | cf6b1aa5ae47a9e56a0f2ddb0c1aa54927134fb5 | [
"MIT"
] | null | null | null | #include "mscHack.hpp"
#define nCHANNELS 8
#define nENVELOPE_SEGS 5
typedef struct
{
float m, b;
}ENV_SEG;
//-----------------------------------------------------
// Module Definition
//
//-----------------------------------------------------
struct ASAF8 : Module
{
enum ParamIds
{
PARAM_SPEED_IN,
PARAM_SPEED_OUT = PARAM_SPEED_IN + nCHANNELS,
nPARAMS = PARAM_SPEED_OUT + nCHANNELS
};
enum InputIds
{
IN_TRIGS,
IN_AUDIOL = IN_TRIGS + nCHANNELS,
IN_AUDIOR = IN_AUDIOL + nCHANNELS,
nINPUTS = IN_AUDIOR + nCHANNELS
};
enum OutputIds
{
OUT_AUDIOL,
OUT_AUDIOR = OUT_AUDIOL + nCHANNELS,
nOUTPUTS = OUT_AUDIOR + nCHANNELS,
};
enum LightIds
{
nLIGHTS
};
enum FadeStates
{
STATE_OFF,
STATE_FIN,
STATE_ON,
STATE_FOUT
};
bool m_bInitialized = false;
// triggers
MyLEDButton *m_pTrigButton[ nCHANNELS ] = {};
int m_State[ nCHANNELS ] = {STATE_OFF};
float m_fFade[ nCHANNELS ] = {};
float m_fPos[ nCHANNELS ] = {};
ENV_SEG m_EnvSeg[ nENVELOPE_SEGS ] = {};
Label *m_pTextLabel = NULL;
// Contructor
ASAF8()
{
config(nPARAMS, nINPUTS, nOUTPUTS, nLIGHTS);
for( int i = 0; i < nCHANNELS; i++ )
{
configParam( PARAM_SPEED_IN + i, 0.05f, 40.0f, 5.0f, "Fade In Speed" );
configParam( PARAM_SPEED_OUT + i, 0.05f, 40.0f, 5.0f, "Fade Out Speed" );
}
}
//-----------------------------------------------------
// spd_Knob
//-----------------------------------------------------
struct spd_Knob : Knob_Green1_15
{
ASAF8 *mymodule;
int param;
char strVal[ 10 ] = {};
void onChange( const event::Change &e ) override
{
auto paramQuantity = getParamQuantity();
mymodule = (ASAF8*)paramQuantity->module;
sprintf( strVal, "[%.2fs]", paramQuantity->getValue() );
mymodule->m_pTextLabel->text = strVal;
RoundKnob::onChange( e );
}
};
void envSeg_from_points( float x1, float y1, float x2, float y2, ENV_SEG *L );
bool processFade( int ch, bool bfin );
// Overrides
void JsonParams( bool bTo, json_t *root);
void process(const ProcessArgs &args) override;
json_t* dataToJson() override;
void dataFromJson(json_t *rootJ) override;
void onRandomize() override;
void onReset() override;
};
// dumb
ASAF8 g_ASAF8_Browser;
//-----------------------------------------------------
// ASAF8_TrigButton
//-----------------------------------------------------
void ASAF8_TrigButton( void *pClass, int id, bool bOn )
{
ASAF8 *mymodule;
mymodule = (ASAF8*)pClass;
if( bOn )
mymodule->m_pTrigButton[ id ]->Set( true );
//mymodule->m_State[ id ] = ASAF8::STATE_FIN;
else
mymodule->m_pTrigButton[ id ]->Set( false );
//mymodule->m_State[ id ] = ASAF8::STATE_FOUT;
}
//-----------------------------------------------------
// Procedure: Widget
//
//-----------------------------------------------------
struct ASAF8_Widget : ModuleWidget
{
ASAF8_Widget( ASAF8 *module )
{
int x, y;
ASAF8 *pmod;
//box.size = Vec( 15*12, 380);
setModule(module);
if( !module )
pmod = &g_ASAF8_Browser;
else
pmod = module;
setPanel(APP->window->loadSvg(asset::plugin( thePlugin, "res/ASAF8.svg")));
pmod->m_pTextLabel = new Label();
pmod->m_pTextLabel->box.pos = Vec( 90, 28 );
pmod->m_pTextLabel->text = "----";
addChild( pmod->m_pTextLabel );
x = 3;
y = 77;
for( int ch = 0; ch < nCHANNELS; ch++ )
{
// inputs
addInput(createInput<MyPortInSmall>( Vec( x + 1, y ), module, ASAF8::IN_AUDIOL + ch ) );
addInput(createInput<MyPortInSmall>( Vec( x + 22, y ), module, ASAF8::IN_AUDIOR + ch ) );
// trigger input
addInput(createInput<MyPortInSmall>( Vec( x + 47, y ), module, ASAF8::IN_TRIGS + ch ) );
// trigger button
pmod->m_pTrigButton[ ch ] = new MyLEDButton( x + 68, y - 1, 19, 19, 15.0, DWRGB( 180, 180, 180 ), DWRGB( 0, 255, 0 ), MyLEDButton::TYPE_SWITCH, ch, module, ASAF8_TrigButton );
addChild( pmod->m_pTrigButton[ ch ] );
// speed knobs
addParam(createParam<ASAF8::spd_Knob>( Vec( x + 94, y ), module, ASAF8::PARAM_SPEED_IN + ch ) );
addParam(createParam<ASAF8::spd_Knob>( Vec( x + 115, y ), module, ASAF8::PARAM_SPEED_OUT + ch ) );
// outputs
addOutput(createOutput<MyPortOutSmall>( Vec( x + 137, y ), module, ASAF8::OUT_AUDIOL + ch ) );
addOutput(createOutput<MyPortOutSmall>( Vec( x + 158, y ), module, ASAF8::OUT_AUDIOR + ch ) );
y += 33;
}
addChild(createWidget<ScrewSilver>(Vec(15, 0)));
addChild(createWidget<ScrewSilver>(Vec(box.size.x-30, 0)));
addChild(createWidget<ScrewSilver>(Vec(15, 365)));
addChild(createWidget<ScrewSilver>(Vec(box.size.x-30, 365)));
if( module )
{
module->envSeg_from_points( 0.0f, 1.0f, 0.2f, 0.975f, &module->m_EnvSeg[ 0 ] );
module->envSeg_from_points( 0.2f, 0.975f, 0.3f, 0.9f, &module->m_EnvSeg[ 1 ] );
module->envSeg_from_points( 0.3f, 0.9f, 0.7f, 0.1f, &module->m_EnvSeg[ 2 ] );
module->envSeg_from_points( 0.7f, 0.1f, 0.8f, 0.075f, &module->m_EnvSeg[ 3 ] );
module->envSeg_from_points( 0.8f, 0.075f, 1.0f, 0.0f, &module->m_EnvSeg[ 4 ] );
module->m_bInitialized = true;
}
}
};
//-----------------------------------------------------
// Procedure: JsonParams
//
//-----------------------------------------------------
void ASAF8::JsonParams( bool bTo, json_t *root)
{
JsonDataInt( bTo, "m_State", root, m_State, nCHANNELS );
}
//-----------------------------------------------------
// Procedure: toJson
//
//-----------------------------------------------------
json_t *ASAF8::dataToJson()
{
json_t *root = json_object();
if( !root )
return NULL;
JsonParams( TOJSON, root );
return root;
}
//-----------------------------------------------------
// Procedure: fromJson
//
//-----------------------------------------------------
void ASAF8::dataFromJson( json_t *root )
{
JsonParams( FROMJSON, root );
if( !m_bInitialized )
return;
for( int ch = 0; ch < nCHANNELS; ch++ )
{
if( m_State[ ch ] == STATE_OFF || m_State[ ch ] == STATE_FOUT )
{
m_pTrigButton[ ch ]->Set( false );
m_State[ ch ] = STATE_OFF;
m_fFade[ ch ] = 0.0f;
}
else
{
m_pTrigButton[ ch ]->Set( true );
m_State[ ch ] = STATE_ON;
m_fFade[ ch ] = 1.0f;
}
}
}
//-----------------------------------------------------
// Procedure: onReset
//
//-----------------------------------------------------
void ASAF8::onReset()
{
}
//-----------------------------------------------------
// Procedure: onRandomize
//
//-----------------------------------------------------
void ASAF8::onRandomize()
{
}
//-----------------------------------------------------
// Function: envSeg_from_points
//
//-----------------------------------------------------
void ASAF8::envSeg_from_points( float x1, float y1, float x2, float y2, ENV_SEG *L )
{
L->m = (y2 - y1) / (x2 - x1);
L->b = y1 - (L->m * x1);
}
//-----------------------------------------------------
// Procedure: processFade
//
//-----------------------------------------------------
bool ASAF8::processFade( int ch, bool bfin )
{
int i = 0;
float inc;
if( bfin )
inc = 1.0f / ( APP->engine->getSampleRate() * params[ PARAM_SPEED_IN + ch ].getValue() );
else
inc = 1.0f / ( APP->engine->getSampleRate() * params[ PARAM_SPEED_OUT + ch ].getValue() );
if( m_fPos[ ch ] < 0.2f )
i = 0;
else if( m_fPos[ ch ] < 0.3f )
i = 1;
else if( m_fPos[ ch ] < 0.7f )
i = 2;
else if( m_fPos[ ch ] < 0.8f )
i = 3;
else
i = 4;
if( bfin )
m_fFade[ ch ] = 1.0f - ( ( m_fPos[ ch ] * m_EnvSeg[ i ].m ) + m_EnvSeg[ i ].b );
else
m_fFade[ ch ] = ( m_fPos[ ch ] * m_EnvSeg[ i ].m ) + m_EnvSeg[ i ].b;
m_fPos[ ch ] += inc;
// return true means we are finished fade
if( m_fPos[ ch ] >= 1.0f )
return true;
return false;
}
//-----------------------------------------------------
// Procedure: step
//
//-----------------------------------------------------
#define FADE_GATE_LVL (0.01f)
void ASAF8::process(const ProcessArgs &args)
{
if( !m_bInitialized )
return;
for( int ch = 0; ch < nCHANNELS; ch++ )
{
switch( m_State[ ch ] )
{
case STATE_FOUT:
if( inputs[ IN_TRIGS + ch ].getNormalVoltage( 0.0f ) >= FADE_GATE_LVL || m_pTrigButton[ ch ]->m_bOn )
{
m_pTrigButton[ ch ]->Set( true );
m_fPos[ ch ] = 1.0f - m_fPos[ ch ];
m_State[ ch ] = STATE_FIN;
break;
}
if( processFade( ch, false ) )
{
m_fFade[ ch ] = 0.0f;
m_State[ ch ] = STATE_OFF;
}
break;
case STATE_OFF:
if( inputs[ IN_TRIGS + ch ].getNormalVoltage( 0.0f ) >= FADE_GATE_LVL || m_pTrigButton[ ch ]->m_bOn )
{
m_pTrigButton[ ch ]->Set( true );
m_State[ ch ] = STATE_FIN;
m_fPos[ ch ] = 0.0f;
break;
}
m_fFade[ ch ] = 0.0f;
break;
case STATE_FIN:
if( inputs[ IN_TRIGS + ch ].getNormalVoltage( 1.0f ) < FADE_GATE_LVL || !m_pTrigButton[ ch ]->m_bOn )
{
m_pTrigButton[ ch ]->Set( false );
m_fPos[ ch ] = 1.0f - m_fPos[ ch ];
m_State[ ch ] = STATE_FOUT;
break;
}
if( processFade( ch, true ) )
{
m_fFade[ ch ] = 1.0f;
m_State[ ch ] = STATE_ON;
}
break;
case STATE_ON:
if( inputs[ IN_TRIGS + ch ].getNormalVoltage( 1.0f ) < FADE_GATE_LVL || !m_pTrigButton[ ch ]->m_bOn )
{
m_pTrigButton[ ch ]->Set( false );
m_State[ ch ] = STATE_FOUT;
m_fPos[ ch ] = 0.0f;
break;
}
m_fFade[ ch ] = 1.0f;
break;
}
if( inputs[ IN_AUDIOL + ch ].isConnected() )
outputs[ OUT_AUDIOL + ch ].setVoltage( inputs[ IN_AUDIOL + ch ].getVoltageSum() * m_fFade[ ch ] );
else
outputs[ OUT_AUDIOL + ch ].value = CV_MAX10 * m_fFade[ ch ];
if( inputs[ IN_AUDIOR + ch ].isConnected() )
outputs[ OUT_AUDIOR + ch ].setVoltage( inputs[ IN_AUDIOR + ch ].getVoltageSum() * m_fFade[ ch ] );
else
outputs[ OUT_AUDIOR + ch ].value = CV_MAX10 * m_fFade[ ch ];
}
}
Model *modelASAF8 = createModel<ASAF8, ASAF8_Widget>( "ASAF8" );
| 26.048544 | 184 | 0.490868 | CardinalModules |
c6beffdea51a98f3b6b0068ef381173a020c6f2e | 2,111 | hxx | C++ | include/nifty/graph/opt/common/solver_base.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | 38 | 2016-06-29T07:42:50.000Z | 2021-12-09T09:25:25.000Z | include/nifty/graph/opt/common/solver_base.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | 62 | 2016-07-27T16:07:53.000Z | 2022-03-30T17:24:36.000Z | include/nifty/graph/opt/common/solver_base.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | 20 | 2016-01-25T21:21:52.000Z | 2021-12-09T09:25:16.000Z | #pragma once
#include <string>
#include <initializer_list>
#include <sstream>
#include <stdexcept>
#include "nifty/exceptions/exceptions.hxx"
#include "nifty/graph/opt/common/solver_base.hxx"
#include "nifty/graph/opt/common/visitor_base.hxx"
namespace nifty {
namespace graph {
namespace opt{
namespace common{
template<class OBJECTIVE, class CHILD>
class SolverBase{
public:
typedef OBJECTIVE ObjectiveType;
typedef SolverBase<ObjectiveType,CHILD> SelfType;
typedef VisitorBase<CHILD> VisitorBaseType;
typedef VisitorProxy<CHILD> VisitorProxyType;
typedef typename ObjectiveType::GraphType GraphType;
typedef typename ObjectiveType::NodeLabelsType NodeLabelsType;
virtual ~SolverBase(){};
virtual void optimize(NodeLabelsType & nodeLabels, VisitorBaseType * visitor) = 0;
virtual const ObjectiveType & objective() const = 0;
virtual const NodeLabelsType & currentBestNodeLabels() = 0;
virtual std::string name() const = 0 ;
/**
* @brief Inform solver about a change of weights.
* @details Inform solver that all weights could have changed.
* If a particular solver does not overload this function, an
* WeightsChangedNotSupported exception is thrown.
* After a call of this function it is save to run optimize
* again, therefore it resets the solver
*/
virtual void weightsChanged(){
std::stringstream ss;
ss<<this->name()<<" does not support changing weights";
throw exceptions::WeightsChangedNotSupported(ss.str());
}
// with default implementation
virtual double currentBestEnergy() {
const auto & nl = this->currentBestNodeLabels();
const auto & obj = this->objective();
return obj.evalNodeLabels(nl);
}
};
} // namespace nifty::graph::opt::common
} // namespace nifty::graph::opt
} // namespace nifty::graph
} // namespace nifty
| 30.157143 | 90 | 0.641402 | konopczynski |
c6c1a1437413e08ac6b3f1ab7e02a899a6ee1cf2 | 2,787 | cpp | C++ | Lab7/F.cpp | satans404/CS203-2020fal-SUSTech | 356e616081962e04477912d2d81d31fd1b85fa23 | [
"MIT"
] | 2 | 2020-11-25T11:10:39.000Z | 2020-11-26T12:22:23.000Z | Lab7/F.cpp | satans404/CS203-2020fall-SUSTech | 356e616081962e04477912d2d81d31fd1b85fa23 | [
"MIT"
] | null | null | null | Lab7/F.cpp | satans404/CS203-2020fall-SUSTech | 356e616081962e04477912d2d81d31fd1b85fa23 | [
"MIT"
] | null | null | null | #pragma GCC optimize(3, "Ofast", "inline")
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#define int long long
using namespace std;
int T, n, q, m, l, x, y, ans, pos;
vector<int> v;
struct Edge
{
int to, Next, val;
void push(int a, int b)
{
to = a;
Next = b;
val = 1;
}
} edge[210000];
int w[110000], head[110000], cnt, lg[210000], dfn[110000], dep[110000], tot, f[210000][20];
void get_lcainit()
{
cnt = 0;
tot = 0;
memset(head, 0, sizeof(head));
memset(dep,0,sizeof(dep));
memset(w, 0, sizeof(w));
}
void add(int u, int v)
{
edge[++cnt].push(v, head[u]);
head[u] = cnt;
}
void dfs(int u, int fa)
{
f[++tot][0] = u;
dfn[u] = tot;
dep[u] = dep[fa] + 1;
for (signed i = head[u]; i; i = edge[i].Next)
{
int v = edge[i].to;
if (v == fa)
continue;
w[v] = w[u] + edge[i].val;
dfs(v, u);
f[++tot][0] = u;
}
}
void getf()
{
lg[1] = 0;
for (signed i = 2; i <= tot; i++)
lg[i] = lg[i >> 1] + 1;
for (signed j = 1; j <= 19; j++)
{
for (signed i = 1; i + (1 << j) - 1 <= tot; i++)
{
dep[f[i][j - 1]] < dep[f[i + (1 << j - 1)][j - 1]] ? f[i][j] = f[i][j - 1] : f[i][j] = f[i + (1 << j - 1)][j - 1];
}
}
}
int get_lca(int u, int v)
{
u = dfn[u];
v = dfn[v];
if (u > v)
swap(u, v);
int len = lg[v - u + 1];
if (dep[f[u][len]] < dep[f[v - (1 << len) + 1][len]])
{
return f[u][len];
}
else
{
return f[v - (1 << len) + 1][len];
}
}
int get_dis(int u, int v)
{
int tmp = get_lca(u, v);
return w[u] + w[v] - w[tmp] - w[tmp];
}
inline void init()
{
scanf("%lld%lld", &n, &m);
get_lcainit();
for (int i = 1; i < n; i++)
{
scanf("%lld%lld", &x, &y);
add(x, y);
add(y, x);
}
dfs(1, 0);
getf();
pos = 0;
ans = 0;
v.clear();
}
void work()
{
init();
for (int i = 1; i <= m; i++)
{
scanf("%lld", &x);
v.push_back(x);
if (pos==0||dep[pos] < dep[x])
{
pos = x;
}
}
l = v.size();
for (int i = 0; i < l; i++)
{
x = v[i];
ans = max(ans, (get_dis(x, pos) + (long long)1) / (long long)2);
}
printf("%lld\n", ans);
}
signed main()
{
scanf("%lld", &T);
while (T--)
{
work();
}
}
/*
2
4 2
1 2
2 4
2 3
1 3
4 2
1 2
2 4
2 3
1 1
*/
/**************************************************************
Problem: 1240
User: 11912823
Language: C++
Result: 正确
Time:260 ms
Memory:45688 kb
****************************************************************/
| 18.335526 | 126 | 0.407607 | satans404 |
c6c1a314543ba51404f774d80af28349fbff579d | 742 | hpp | C++ | include/theconf/configuration.hpp | PeterHajdu/theconf | 1c4609634b76d98b9d02ef490385a098ba28433d | [
"MIT"
] | null | null | null | include/theconf/configuration.hpp | PeterHajdu/theconf | 1c4609634b76d98b9d02ef490385a098ba28433d | [
"MIT"
] | null | null | null | include/theconf/configuration.hpp | PeterHajdu/theconf | 1c4609634b76d98b9d02ef490385a098ba28433d | [
"MIT"
] | null | null | null | #pragma once
#include <istream>
#include <string>
#include <sstream>
#include <vector>
namespace the
{
namespace conf
{
void parse( std::istream& );
void clear();
bool has( const std::string& key );
const std::string& get_value( const std::string& key );
void set_value( const std::string& key, const std::string& value );
typedef std::vector< std::string > ParameterVector;
void parse( const ParameterVector& );
template < typename T >
T get( const std::string& key )
{
std::stringstream ss( get_value( key ) );
T return_value;
ss >> return_value;
return return_value;
}
template < typename T >
void set( const std::string& key, const T& value )
{
std::stringstream ss;
ss << value;
set_value( key, ss.str() );
}
}
}
| 16.863636 | 67 | 0.679245 | PeterHajdu |
c6cca4f7e7411f6214b12723bf83e54c6a31846f | 20,093 | cpp | C++ | FireRender.Max.Plugin/plugin/FireRenderPortalLight.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 6 | 2020-05-24T12:00:43.000Z | 2021-07-13T06:22:49.000Z | FireRender.Max.Plugin/plugin/FireRenderPortalLight.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 4 | 2020-09-17T17:05:38.000Z | 2021-06-23T14:29:14.000Z | FireRender.Max.Plugin/plugin/FireRenderPortalLight.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 8 | 2020-05-15T08:29:17.000Z | 2021-07-14T08:38:07.000Z | /**********************************************************************
Copyright 2020 Advanced Micro Devices, 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 "frWrap.h"
#include "Common.h"
#include "Resource.h"
#include "plugin/FireRenderPortalLight.h"
#include "utils/Utils.h"
#include <math.h>
#include "ParamBlock.h"
#include <iparamb2.h>
#include <LINSHAPE.H>
#include <3dsmaxport.h> //for DLGetWindowLongPtr
#include <hsv.h>
#include <decomp.h>
#include <iparamm2.h>
#include <memory>
FIRERENDER_NAMESPACE_BEGIN
TCHAR* FIRERENDER_PORTALLIGHT_CATEGORY = _T("Radeon ProRender");
TCHAR* FIRERENDER_PORTALLIGHT_OBJECT_NAME = _T("RPRPortalLight");
TCHAR* FIRERENDER_PORTALLIGHT_INTERNAL_NAME = _T("Portal Light");
TCHAR* FIRERENDER_PORTALLIGHT_CLASS_NAME = _T("Portal Light");
class FireRenderPortalLightClassDesc : public ClassDesc2
{
public:
int IsPublic() override { return 1; } // DEACTIVATED! SET TO 1 TO REACTIVATE.
HINSTANCE HInstance() override
{
FASSERT(fireRenderHInstance != NULL);
return fireRenderHInstance;
}
//used in MaxScript to create objects of this class
const TCHAR* InternalName() override { return FIRERENDER_PORTALLIGHT_INTERNAL_NAME; }
//used as lable in creation UI and in MaxScript to create objects of this class
const TCHAR* ClassName() override {
return FIRERENDER_PORTALLIGHT_CLASS_NAME;
}
Class_ID ClassID() override { return FIRERENDER_PORTALLIGHT_CLASS_ID; }
SClass_ID SuperClassID() override { return LIGHT_CLASS_ID; }
const TCHAR* Category() override { return FIRERENDER_PORTALLIGHT_CATEGORY; }
void* Create(BOOL loading) override ;
};
static FireRenderPortalLightClassDesc desc;
static const int VERSION = 1;
static ParamBlockDesc2 paramBlock(0, _T("PortalLightPbDesc"), 0, &desc, P_AUTO_CONSTRUCT + P_VERSION + P_AUTO_UI,
VERSION, // for P_VERSION
0, //for P_AUTO_CONSTRUCT
//P_AUTO_UI
IDD_FIRERENDER_PORTALLIGHT, IDS_FR_ENV, 0, 0, NULL,
PORTAL_PARAM_P0, _T("p0"), TYPE_POINT3, 0, 0,
p_default, Point3(0.f, 0.f, 0.f), PB_END,
PORTAL_PARAM_P1, _T("p1"), TYPE_POINT3, 0, 0,
p_default, Point3(0.f, 0.f, 0.f), PB_END,
p_end
);
ClassDesc2* GetFireRenderPortalLightDesc()
{
return &desc;
}
class FireRenderPortalLight : public GenLight, public IFireRenderPortalLight
{
Point3 Vertices[4] = { {0.f, 0.f, 0.f},{ 0.f, 0.f, 0.f },{ 0.f, 0.f, 0.f },{ 0.f, 0.f, 0.f } };
bool VerticesBuilt = false;
class CreateCallBack : public CreateMouseCallBack
{
private:
FireRenderPortalLight *ob = 0;
IParamBlock2 *pblock = 0;
Point3 p0, p1;
public:
int proc(ViewExp *vpt, int msg, int point, int flags, IPoint2 m, Matrix3& mat)
{
if (msg == MOUSE_POINT)
{
if (point == 0)
{
p0 = p1 = vpt->SnapPoint(m, m, NULL, SNAP_IN_PLANE);
pblock->SetValue(PORTAL_PARAM_P0, 0, p0);
pblock->SetValue(PORTAL_PARAM_P1, 0, p0);
mat.SetTrans(p0);
}
else
{
return 0;
}
}
else if (msg == MOUSE_MOVE)
{
p1 = vpt->SnapPoint(m, m, NULL, SNAP_IN_PLANE);
Point3 center = (p0 + p1) * 0.5f;
mat.SetTrans(center);
Point3 _p0, _p1;
pblock->GetValue(PORTAL_PARAM_P0, 0, _p0, FOREVER);
pblock->GetValue(PORTAL_PARAM_P1, 0, _p1, FOREVER);
_p0 = center - p0;
_p1 = center - p1;
pblock->SetValue(PORTAL_PARAM_P0, 0, _p0);
pblock->SetValue(PORTAL_PARAM_P1, 0, _p1);
}
else if (msg == MOUSE_ABORT)
{
return CREATE_ABORT;
}
else if (msg == MOUSE_FREEMOVE)
{
vpt->SnapPreview(m, m, NULL, SNAP_IN_PLANE);
}
return CREATE_CONTINUE;
}
void SetObj(FireRenderPortalLight* obj)
{
ob = obj;
pblock = ob->GetParamBlock(0);
}
};
public:
FireRenderPortalLight()
{
GetFireRenderPortalLightDesc()->MakeAutoParamBlocks(this);
}
~FireRenderPortalLight() {
DebugPrint(_T("FireRenderPortalLight::~FireRenderPortalLight\n"));
DeleteAllRefs();
}
void GetCorners(Point3& p1, Point3& p2, Point3& p3, Point3& p4) override
{
BuildVertices();
p1 = Vertices[0];
p2 = Vertices[1];
p3 = Vertices[2];
p4 = Vertices[3];
}
CreateMouseCallBack *BaseObject::GetCreateMouseCallBack(void)
{
static CreateCallBack createCallback;
createCallback.SetObj(this);
return &createCallback;
}
GenLight *NewLight(int type)
{
return new FireRenderPortalLight();
}
// From Object
ObjectState Eval(TimeValue time)
{
return ObjectState(this);
}
//makes part of the node name e.g. TheName001, if method returns L"TheName"
void InitNodeName(TSTR& s) { s = FIRERENDER_PORTALLIGHT_OBJECT_NAME; }
//displayed in Modifier list
const MCHAR *GetObjectName() override { return FIRERENDER_PORTALLIGHT_OBJECT_NAME; }
Interval ObjectValidity(TimeValue t) override
{
Interval valid;
valid.SetInfinite();
return valid;
}
BOOL UsesWireColor() { return 1; } // 6/18/01 2:51pm --MQM-- now we can set object color
int DoOwnSelectHilite() { return 1; }
void NotifyChanged() { NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); }
// inherited virtual methods for Reference-management
void BuildVertices(bool force = false)
{
if (VerticesBuilt && (!force))
return;
Point3 _p0, _p1, p0, p1;
pblock2->GetValue(PORTAL_PARAM_P0, 0, p0, FOREVER);
pblock2->GetValue(PORTAL_PARAM_P1, 0, p1, FOREVER);
_p0.x = std::min(p0.x, p1.x);
_p0.y = std::min(p0.y, p1.y);
_p0.z = std::min(p0.z, p1.z);
_p1.x = std::max(p0.x, p1.x);
_p1.y = std::max(p0.y, p1.y);
_p1.z = std::max(p0.z, p1.z);
Vertices[0] = p0;
Vertices[1] = Point3(p1.x, p0.y, p0.z);
Vertices[2] = p1;
Vertices[3] = Point3(p0.x, p1.y, p0.z);
VerticesBuilt = true;
}
RefResult NotifyRefChanged(NOTIFY_REF_CHANGED_PARAMETERS) override
{
if ((REFMSG_CHANGE==msg) && (hTarget == pblock2))
{
auto p = pblock2->LastNotifyParamID();
if (p == PORTAL_PARAM_P0 || p == PORTAL_PARAM_P1)
BuildVertices(true);
//some params have changed - should redraw all
if(GetCOREInterface()){
GetCOREInterface()->RedrawViews(GetCOREInterface()->GetTime());
}
}
return REF_SUCCEED;
}
IParamBlock2* pblock2 = NULL;
void DeleteThis() override
{
delete this;
}
Class_ID ClassID() override {
return FIRERENDER_PORTALLIGHT_CLASS_ID;
}
//
void GetClassName(TSTR& s) override {
FIRERENDER_PORTALLIGHT_CLASS_NAME;
}
RefTargetHandle Clone(RemapDir& remap) override
{
FireRenderPortalLight* newob = new FireRenderPortalLight();
newob->VerticesBuilt = VerticesBuilt;
newob->Vertices[0] = Vertices[0];
newob->Vertices[1] = Vertices[1];
newob->Vertices[2] = Vertices[2];
newob->Vertices[3] = Vertices[3];
newob->ReplaceReference(0, remap.CloneRef(pblock2));
BaseClone(this, newob, remap);
return(newob);
}
IParamBlock2* GetParamBlock(int i) override {
FASSERT(i == 0);
return pblock2;
}
IParamBlock2* GetParamBlockByID(BlockID id) override {
FASSERT(pblock2->ID() == id);
return pblock2;
}
int NumRefs() override {
return 1;
}
void SetReference(int i, RefTargetHandle rtarg) override {
FASSERT(0 == i);
pblock2 = (IParamBlock2*)rtarg;
}
RefTargetHandle GetReference(int i) override {
FASSERT(0 == i);
return (RefTargetHandle)pblock2;
}
void DrawGeometry(ViewExp *vpt, IParamBlock2 *pblock, BOOL sel = FALSE, BOOL frozen = FALSE)
{
BuildVertices();
if (sel)
{
vpt->getGW()->setColor(LINE_COLOR, Color(1.0f, 1.0f, 1.0f));
}
else
{
if (!frozen)
vpt->getGW()->setColor(LINE_COLOR, Color(1.0f, 1.0f, 0.0f));
else
if (!frozen)
vpt->getGW()->setColor(LINE_COLOR, Color(.5f, .5f, .5f));
}
Point3 v[3];
GraphicsWindow *gw = vpt->getGW();
v[0] = Vertices[0];
v[1] = Vertices[1];
gw->polyline(2, v, NULL, NULL, FALSE, NULL);
v[0] = Vertices[1];
v[1] = Vertices[2];
gw->polyline(2, v, NULL, NULL, FALSE, NULL);
v[0] = Vertices[2];
v[1] = Vertices[3];
gw->polyline(2, v, NULL, NULL, FALSE, NULL);
v[0] = Vertices[3];
v[1] = Vertices[0];
gw->polyline(2, v, NULL, NULL, FALSE, NULL);
vpt->getGW()->marker(const_cast<Point3 *>(&Point3::Origin), X_MRKR);
}
Matrix3 GetTransformMatrix(TimeValue t, INode* inode, ViewExp* vpt)
{
Matrix3 tm = inode->GetObjectTM(t);
return tm;
}
Color GetViewportMainColor(INode* pNode)
{
if (pNode->Dependent())
{
return Color(ColorMan()->GetColor(kViewportShowDependencies));
}
else if (pNode->Selected())
{
return Color(GetSelColor());
}
else if (pNode->IsFrozen())
{
return Color(GetFreezeColor());
}
return Color(1,1,0);
}
Color GetViewportColor(INode* pNode, Color selectedColor)
{
if (pNode->Dependent())
{
return Color(ColorMan()->GetColor(kViewportShowDependencies));
}
else if (pNode->Selected())
{
return selectedColor;
}
else if (pNode->IsFrozen())
{
return Color(GetFreezeColor());
}
return selectedColor * 0.5f;
}
int Display(TimeValue t, INode* inode, ViewExp *vpt, int flags) override
{
if (!vpt || !vpt->IsAlive())
{
// why are we here
DbgAssert(!_T("Invalid viewport!"));
return FALSE;
}
Matrix3 prevtm = vpt->getGW()->getTransform();
Matrix3 tm = inode->GetObjectTM(t);
vpt->getGW()->setTransform(tm);
DrawGeometry(vpt, GetParamBlock(0), inode->Selected(), inode->IsFrozen());
vpt->getGW()->setTransform(prevtm);
return(0);
}
void GetWorldBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box)
{
if (!vpt || !vpt->IsAlive())
{
box.Init();
return;
}
Matrix3 worldTM = inode->GetNodeTM(t);
Point3 _Vertices[4];
for (int i = 0; i < 4; i++)
_Vertices[i] = Vertices[i] * worldTM;
box.Init();
for (int i = 0; i < 4; i++)
{
box.pmin.x = std::min(box.pmin.x, _Vertices[i].x);
box.pmin.y = std::min(box.pmin.y, _Vertices[i].y);
box.pmin.z = std::min(box.pmin.z, _Vertices[i].z);
box.pmax.x = std::max(box.pmin.x, _Vertices[i].x);
box.pmax.y = std::max(box.pmin.y, _Vertices[i].y);
box.pmax.z = std::max(box.pmin.z, _Vertices[i].z);
}
}
int HitTest(TimeValue t, INode* inode, int type, int crossing, int flags, IPoint2 *p, ViewExp *vpt) override
{
if (!vpt || !vpt->IsAlive())
{
// why are we here
DbgAssert(!_T("Invalid viewport!"));
return FALSE;
}
HitRegion hitRegion;
DWORD savedLimits;
GraphicsWindow *gw = vpt->getGW();
Matrix3 prevtm = gw->getTransform();
gw->setTransform(idTM);
MakeHitRegion(hitRegion, type, crossing, 8, p);
savedLimits = gw->getRndLimits();
gw->setRndLimits((savedLimits | GW_PICK) & ~GW_ILLUM & ~GW_Z_BUFFER);
gw->setHitRegion(&hitRegion);
gw->clearHitCode();
Matrix3 tm = inode->GetObjectTM(t);
gw->setTransform(tm);
DrawGeometry(vpt, GetParamBlock(0));
int res = gw->checkHitCode();
gw->setRndLimits(savedLimits);
gw->setTransform(prevtm);
return res;
};
void GetLocalBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box) override
{
Matrix3 nodeTM = inode->GetNodeTM(t);
Matrix3 parentTM = inode->GetParentNode()->GetNodeTM(t);
Matrix3 localTM = nodeTM*Inverse(parentTM);
Point3 _Vertices[4];
for (int i = 0; i < 4; i++)
_Vertices[i] = Vertices[i] * localTM;
box.Init();
for (int i = 0; i < 4; i++)
{
box.pmin.x = std::min(box.pmin.x, _Vertices[i].x);
box.pmin.y = std::min(box.pmin.y, _Vertices[i].y);
box.pmin.z = std::min(box.pmin.z, _Vertices[i].z);
box.pmax.x = std::max(box.pmin.x, _Vertices[i].x);
box.pmax.y = std::max(box.pmin.y, _Vertices[i].y);
box.pmax.z = std::max(box.pmin.z, _Vertices[i].z);
}
}
// LightObject methods
Point3 GetRGBColor(TimeValue t, Interval &valid) override { return Point3(1.0f, 1.0f, 1.0f); }
void SetRGBColor(TimeValue t, Point3 &color) override { /* empty */ }
void SetUseLight(int onOff) override { /* empty */ }
BOOL GetUseLight() override { return TRUE; }
void SetHotspot(TimeValue time, float f) override { /* empty */ }
float GetHotspot(TimeValue t, Interval& valid) override { return -1.0f; }
void SetFallsize(TimeValue time, float f) override { /* empty */ }
float GetFallsize(TimeValue t, Interval& valid) override { return -1.0f; }
void SetAtten(TimeValue time, int which, float f) override { /* empty */ }
float GetAtten(TimeValue t, int which, Interval& valid) override { return 0.0f; }
void SetTDist(TimeValue time, float f) override { /* empty */ }
float GetTDist(TimeValue t, Interval& valid) override { return 0.0f; }
void SetConeDisplay(int s, int notify) override { /* empty */ }
BOOL GetConeDisplay() override { return FALSE; }
void SetIntensity(TimeValue time, float f) override { /* empty */ }
float GetIntensity(TimeValue t, Interval& valid) override { return 1.0f; }
void SetUseAtten(int s) override { /* empty */ }
BOOL GetUseAtten() override { return FALSE; }
void SetAspect(TimeValue t, float f) override { /* empty */ }
float GetAspect(TimeValue t, Interval& valid) override { return -1.0f; }
void SetOvershoot(int a) override { /* empty */ }
int GetOvershoot() override { return 0; }
void SetShadow(int a) override { /* empty */ }
int GetShadow() override { return 0; }
// From Light
RefResult EvalLightState(TimeValue t, Interval& valid, LightState* cs)
{
cs->color = GetRGBColor(t, valid);
cs->on = GetUseLight();
cs->intens = GetIntensity(t, valid);
cs->hotsize = GetHotspot(t, valid);
cs->fallsize = GetFallsize(t, valid);
cs->useNearAtten = FALSE;
cs->useAtten = GetUseAtten();
cs->nearAttenStart = GetAtten(t, ATTEN1_START, valid);
cs->nearAttenEnd = GetAtten(t, ATTEN1_END, valid);
cs->attenStart = GetAtten(t, ATTEN_START, valid);
cs->attenEnd = GetAtten(t, ATTEN_END, valid);
cs->aspect = GetAspect(t, valid);
cs->overshoot = GetOvershoot();
cs->shadow = GetShadow();
cs->shape = CIRCLE_LIGHT;
cs->ambientOnly = GetAmbientOnly();
cs->affectDiffuse = GetAffectDiffuse();
cs->affectSpecular = GetAffectSpecular();
cs->type = OMNI_LGT;
return REF_SUCCEED;
}
ObjLightDesc* CreateLightDesc(INode *inode, BOOL forceShadowBuf) override { return NULL; }
int Type() override { return OMNI_LIGHT; }
virtual void SetHSVColor(TimeValue, Point3 &)
{
}
virtual Point3 GetHSVColor(TimeValue t, Interval &valid)
{
int h, s, v;
Point3 rgbf = GetRGBColor(t, valid);
DWORD rgb = RGB((int)(rgbf[0] * 255.0f), (int)(rgbf[1] * 255.0f), (int)(rgbf[2] * 255.0f));
RGBtoHSV(rgb, &h, &s, &v);
return Point3(h / 255.0f, s / 255.0f, v / 255.0f);
}
void SetAttenDisplay(int) override { /* empty */ }
BOOL GetAttenDisplay() override { return FALSE; }
void Enable(int) override {}
void SetMapBias(TimeValue, float) override { /* empty */ }
float GetMapBias(TimeValue, Interval &) override { return 0; }
void SetMapRange(TimeValue, float) override { /* empty */ }
float GetMapRange(TimeValue, Interval &) override { return 0; }
void SetMapSize(TimeValue, int) override { /* empty */ }
int GetMapSize(TimeValue, Interval &) override { return 0; }
void SetRayBias(TimeValue, float) override { /* empty */ }
float GetRayBias(TimeValue, Interval &) override { return 0; }
int GetUseGlobal() override { return FALSE; }
void SetUseGlobal(int) override { /* empty */ }
int GetShadowType() override { return -1; }
void SetShadowType(int) override { /* empty */ }
int GetAbsMapBias() override { return FALSE; }
void SetAbsMapBias(int) override { /* empty */ }
BOOL IsSpot() override { return FALSE; }
BOOL IsDir() override { return FALSE; }
void SetSpotShape(int) override { /* empty */ }
int GetSpotShape() override { return CIRCLE_LIGHT; }
void SetContrast(TimeValue, float) override { /* empty */ }
float GetContrast(TimeValue, Interval &) override { return 0; }
void SetUseAttenNear(int) override { /* empty */ }
BOOL GetUseAttenNear() override { return FALSE; }
void SetAttenNearDisplay(int) override { /* empty */ }
BOOL GetAttenNearDisplay() override { return FALSE; }
ExclList &GetExclusionList() override { return m_exclList; }
void SetExclusionList(ExclList &) override { /* empty */ }
BOOL SetHotSpotControl(Control *) override { return FALSE; }
BOOL SetFalloffControl(Control *) override { return FALSE; }
BOOL SetColorControl(Control *) override { return FALSE; }
Control *GetHotSpotControl() override { return NULL; }
Control *GetFalloffControl() override { return NULL; }
Control *GetColorControl() override { return NULL; }
void SetAffectDiffuse(BOOL onOff) override { /* empty */ }
BOOL GetAffectDiffuse() override { return TRUE; }
void SetAffectSpecular(BOOL onOff) override { /* empty */ }
BOOL GetAffectSpecular() override { return TRUE; }
void SetAmbientOnly(BOOL onOff) override { /* empty */ }
BOOL GetAmbientOnly() override { return FALSE; }
void SetDecayType(BOOL onOff) override {}
BOOL GetDecayType() override { return 1; }
void SetDecayRadius(TimeValue time, float f) override {}
float GetDecayRadius(TimeValue t, Interval& valid) override { return 40.0f; } //! check different values
protected:
ExclList m_exclList;
};
void* FireRenderPortalLightClassDesc::Create(BOOL loading) {
return new FireRenderPortalLight();
}
FIRERENDER_NAMESPACE_END
| 33.156766 | 113 | 0.591549 | Vsevolod1983 |
c6d01399067b48f9dcdd717a8194abcde058edc8 | 246 | cpp | C++ | vim/example_cpp/main.cpp | kemnitzs/hpc | 2d77cf77008408006e1ba62d6466611e2d91b504 | [
"MIT"
] | 2 | 2019-03-11T14:19:40.000Z | 2019-03-12T14:48:47.000Z | vim/example_cpp/main.cpp | kemnitzs/hpc | 2d77cf77008408006e1ba62d6466611e2d91b504 | [
"MIT"
] | null | null | null | vim/example_cpp/main.cpp | kemnitzs/hpc | 2d77cf77008408006e1ba62d6466611e2d91b504 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
struct MyStructure {
int a;
int b;
};
int main(int argc, char** argv){
MyStructure ms;
ms.a;
std::vector<double> v;
for( auto& e : v ){
e = 10;
}
return 0;
}
| 11.181818 | 32 | 0.512195 | kemnitzs |
c6d23f163cd11e873fc159d3575dd192addd6057 | 14,521 | cpp | C++ | src/qt/qtbase/src/gui/kernel/qsessionmanager.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/src/gui/kernel/qsessionmanager.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/gui/kernel/qsessionmanager.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qsessionmanager.h>
#include <qguiapplication.h>
#include <qpa/qplatformsessionmanager.h>
#include <qpa/qplatformintegration.h>
#include <private/qobject_p.h>
#include <private/qguiapplication_p.h>
#include <private/qsessionmanager_p.h>
#ifndef QT_NO_SESSIONMANAGER
QT_BEGIN_NAMESPACE
/*!
\class QSessionManager
\brief The QSessionManager class provides access to the session manager.
\inmodule QtGui
A session manager in a desktop environment (in which Qt GUI applications
live) keeps track of a session, which is a group of running applications,
each of which has a particular state. The state of an application contains
(most notably) the documents the application has open and the position and
size of its windows.
The session manager is used to save the session, e.g., when the machine is
shut down, and to restore a session, e.g., when the machine is started up.
We recommend that you use QSettings to save an application's settings,
for example, window positions, recently used files, etc. When the
application is restarted by the session manager, you can restore the
settings.
QSessionManager provides an interface between the application and the
platform's session manager. In Qt, session management requests for action
are handled by the two signals QGuiApplication::commitDataRequest() and
QGuiApplication::saveStateRequest(). Both provide a reference to a
QSessionManager object as argument. The session manager can only be
accessed in slots invoked by these signals.
\warning If you use QSessionManager, you should disable fallback session
management: QGuiApplication::setFallbackSessionManagementEnabled().
No user interaction is possible \e unless the application gets explicit
permission from the session manager. You ask for permission by calling
allowsInteraction() or, if it is really urgent, allowsErrorInteraction().
Qt does not enforce this, but the session manager may.
You can try to abort the shutdown process by calling cancel().
For sophisticated session managers provided on Unix/X11, QSessionManager
offers further possibilities to fine-tune an application's session
management behavior: setRestartCommand(), setDiscardCommand(),
setRestartHint(), setProperty(), requestPhase2(). See the respective
function descriptions for further details.
\sa QGuiApplication, {Session Management}
*/
/*! \enum QSessionManager::RestartHint
This enum type defines the circumstances under which this application wants
to be restarted by the session manager. The current values are:
\value RestartIfRunning If the application is still running when the
session is shut down, it wants to be restarted
at the start of the next session.
\value RestartAnyway The application wants to be started at the
start of the next session, no matter what.
(This is useful for utilities that run just
after startup and then quit.)
\value RestartImmediately The application wants to be started immediately
whenever it is not running.
\value RestartNever The application does not want to be restarted
automatically.
The default hint is \c RestartIfRunning.
*/
QSessionManagerPrivate::QSessionManagerPrivate(const QString &id,
const QString &key)
: QObjectPrivate()
{
platformSessionManager = QGuiApplicationPrivate::platformIntegration()->createPlatformSessionManager(id, key);
Q_ASSERT_X(platformSessionManager, "Platform session management",
"No platform session management, should use the default implementation");
}
QSessionManagerPrivate::~QSessionManagerPrivate()
{
delete platformSessionManager;
platformSessionManager = 0;
}
QSessionManager::QSessionManager(QGuiApplication *app, QString &id, QString &key)
: QObject(*(new QSessionManagerPrivate(id, key)), app)
{
}
QSessionManager::~QSessionManager()
{
}
/*!
Returns the identifier of the current session.
If the application has been restored from an earlier session, this
identifier is the same as it was in the earlier session.
\sa sessionKey(), QGuiApplication::sessionId()
*/
QString QSessionManager::sessionId() const
{
Q_D(const QSessionManager);
return d->platformSessionManager->sessionId();
}
/*!
\fn QString QSessionManager::sessionKey() const
Returns the session key in the current session.
If the application has been restored from an earlier session, this key is
the same as it was when the previous session ended.
The session key changes with every call of commitData() or saveState().
\sa sessionId(), QGuiApplication::sessionKey()
*/
QString QSessionManager::sessionKey() const
{
Q_D(const QSessionManager);
return d->platformSessionManager->sessionKey();
}
/*!
Asks the session manager for permission to interact with the user. Returns
true if interaction is permitted; otherwise returns \c false.
The rationale behind this mechanism is to make it possible to synchronize
user interaction during a shutdown. Advanced session managers may ask all
applications simultaneously to commit their data, resulting in a much
faster shutdown.
When the interaction is completed we strongly recommend releasing the user
interaction semaphore with a call to release(). This way, other
applications may get the chance to interact with the user while your
application is still busy saving data. (The semaphore is implicitly
released when the application exits.)
If the user decides to cancel the shutdown process during the interaction
phase, you must tell the session manager that this has happened by calling
cancel().
Here's an example of how an application's QGuiApplication::commitDataRequest()
might be implemented:
\snippet code/src_gui_kernel_qguiapplication.cpp 1
If an error occurred within the application while saving its data, you may
want to try allowsErrorInteraction() instead.
\sa QGuiApplication::commitDataRequest(), release(), cancel()
*/
bool QSessionManager::allowsInteraction()
{
Q_D(QSessionManager);
return d->platformSessionManager->allowsInteraction();
}
/*!
Returns \c true if error interaction is permitted; otherwise returns \c false.
This is similar to allowsInteraction(), but also enables the application to
tell the user about any errors that occur. Session managers may give error
interaction requests higher priority, which means that it is more likely
that an error interaction is permitted. However, you are still not
guaranteed that the session manager will allow interaction.
\sa allowsInteraction(), release(), cancel()
*/
bool QSessionManager::allowsErrorInteraction()
{
Q_D(QSessionManager);
return d->platformSessionManager->allowsErrorInteraction();
}
/*!
Releases the session manager's interaction semaphore after an interaction
phase.
\sa allowsInteraction(), allowsErrorInteraction()
*/
void QSessionManager::release()
{
Q_D(QSessionManager);
d->platformSessionManager->release();
}
/*!
Tells the session manager to cancel the shutdown process. Applications
should not call this function without asking the user first.
\sa allowsInteraction(), allowsErrorInteraction()
*/
void QSessionManager::cancel()
{
Q_D(QSessionManager);
d->platformSessionManager->cancel();
}
/*!
Sets the application's restart hint to \a hint. On application startup, the
hint is set to \c RestartIfRunning.
\note These flags are only hints, a session manager may or may not respect
them.
We recommend setting the restart hint in QGuiApplication::saveStateRequest()
because most session managers perform a checkpoint shortly after an
application's
startup.
\sa restartHint()
*/
void QSessionManager::setRestartHint(QSessionManager::RestartHint hint)
{
Q_D(QSessionManager);
d->platformSessionManager->setRestartHint(hint);
}
/*!
\fn QSessionManager::RestartHint QSessionManager::restartHint() const
Returns the application's current restart hint. The default is
\c RestartIfRunning.
\sa setRestartHint()
*/
QSessionManager::RestartHint QSessionManager::restartHint() const
{
Q_D(const QSessionManager);
return d->platformSessionManager->restartHint();
}
/*!
If the session manager is capable of restoring sessions it will execute
\a command in order to restore the application. The command defaults to
\snippet code/src_gui_kernel_qguiapplication.cpp 2
The \c -session option is mandatory; otherwise QGuiApplication cannot
tell whether it has been restored or what the current session identifier
is.
See QGuiApplication::isSessionRestored() and
QGuiApplication::sessionId() for details.
If your application is very simple, it may be possible to store the entire
application state in additional command line options. This is usually a
very bad idea because command lines are often limited to a few hundred
bytes. Instead, use QSettings, temporary files, or a database for this
purpose. By marking the data with the unique sessionId(), you will be able
to restore the application in a future session.
\sa restartCommand(), setDiscardCommand(), setRestartHint()
*/
void QSessionManager::setRestartCommand(const QStringList &command)
{
Q_D(QSessionManager);
d->platformSessionManager->setRestartCommand(command);
}
/*!
Returns the currently set restart command.
To iterate over the list, you can use the \l foreach pseudo-keyword:
\snippet code/src_gui_kernel_qguiapplication.cpp 3
\sa setRestartCommand(), restartHint()
*/
QStringList QSessionManager::restartCommand() const
{
Q_D(const QSessionManager);
return d->platformSessionManager->restartCommand();
}
/*!
Sets the discard command to the given \a command.
\sa discardCommand(), setRestartCommand()
*/
void QSessionManager::setDiscardCommand(const QStringList &command)
{
Q_D(QSessionManager);
d->platformSessionManager->setDiscardCommand(command);
}
/*!
Returns the currently set discard command.
To iterate over the list, you can use the \l foreach pseudo-keyword:
\snippet code/src_gui_kernel_qguiapplication.cpp 4
\sa setDiscardCommand(), restartCommand(), setRestartCommand()
*/
QStringList QSessionManager::discardCommand() const
{
Q_D(const QSessionManager);
return d->platformSessionManager->discardCommand();
}
/*!
\overload
Low-level write access to the application's identification and state
records are kept in the session manager.
The property called \a name has its value set to the string \a value.
*/
void QSessionManager::setManagerProperty(const QString &name,
const QString &value)
{
Q_D(QSessionManager);
d->platformSessionManager->setManagerProperty(name, value);
}
/*!
Low-level write access to the application's identification and state record
are kept in the session manager.
The property called \a name has its value set to the string list \a value.
*/
void QSessionManager::setManagerProperty(const QString &name,
const QStringList &value)
{
Q_D(QSessionManager);
d->platformSessionManager->setManagerProperty(name, value);
}
/*!
Returns \c true if the session manager is currently performing a second
session management phase; otherwise returns \c false.
\sa requestPhase2()
*/
bool QSessionManager::isPhase2() const
{
Q_D(const QSessionManager);
return d->platformSessionManager->isPhase2();
}
/*!
Requests a second session management phase for the application. The
application may then return immediately from the
QGuiApplication::commitDataRequest() or QApplication::saveStateRequest()
function, and they will be called again once most or all other
applications have finished their session management.
The two phases are useful for applications such as the X11 window manager
that need to store information about another application's windows and
therefore have to wait until these applications have completed their
respective session management tasks.
\note If another application has requested a second phase it may get called
before, simultaneously with, or after your application's second phase.
\sa isPhase2()
*/
void QSessionManager::requestPhase2()
{
Q_D(QSessionManager);
d->platformSessionManager->requestPhase2();
}
QT_END_NAMESPACE
#endif // QT_NO_SESSIONMANAGER
| 34.822542 | 114 | 0.726809 | power-electro |
c6d36e1127817c4b2304a6ab971594141ec87e89 | 63,783 | cpp | C++ | src/OpenLoco/Windows/CompanyList.cpp | Margen67/OpenLoco | 29b405007e0e2a1691d1f11ee0899bf586cc6217 | [
"MIT"
] | null | null | null | src/OpenLoco/Windows/CompanyList.cpp | Margen67/OpenLoco | 29b405007e0e2a1691d1f11ee0899bf586cc6217 | [
"MIT"
] | null | null | null | src/OpenLoco/Windows/CompanyList.cpp | Margen67/OpenLoco | 29b405007e0e2a1691d1f11ee0899bf586cc6217 | [
"MIT"
] | null | null | null | #include "../Company.h"
#include "../CompanyManager.h"
#include "../Date.h"
#include "../Graphics/Colour.h"
#include "../Graphics/ImageIds.h"
#include "../Input.h"
#include "../Interop/Interop.hpp"
#include "../Localisation/FormatArguments.hpp"
#include "../Localisation/StringIds.h"
#include "../Objects/CargoObject.h"
#include "../Objects/CompetitorObject.h"
#include "../Objects/InterfaceSkinObject.h"
#include "../Objects/ObjectManager.h"
#include "../OpenLoco.h"
#include "../Ui/WindowManager.h"
#include "../Utility/Numeric.hpp"
#include "../Widget.h"
using namespace OpenLoco::Interop;
namespace OpenLoco::Ui::Windows::CompanyList
{
static loco_global<uint8_t[32], 0x004F9442> _cargoLineColour;
static loco_global<Ui::WindowNumber_t, 0x00523390> _toolWindowNumber;
static loco_global<Ui::WindowType, 0x00523392> _toolWindowType;
static loco_global<uint16_t[3], 0x0052624E> _word_52624E;
static loco_global<CompanyId_t[3], 0x00526254> _byte_526254;
static loco_global<uint32_t[3], 0x00526258> _dword_526258;
static loco_global<currency32_t[32][60], 0x009C68F8> _deliveredCargoPayment;
static loco_global<uint16_t, 0x009C68C7> _word_9C68C7;
static loco_global<uint16_t, 0x0113DC7A> _graphLeft;
static loco_global<uint16_t, 0x0113DC7C> _graphTop;
static loco_global<uint16_t, 0x0113DC7E> _graphRight;
static loco_global<uint16_t, 0x0113DC80> _graphBottom;
static loco_global<uint16_t, 0x0113DC82> _graphYOffset;
static loco_global<uint16_t, 0x0113DC84> _graphXOffset;
static loco_global<uint32_t, 0x0113DC86> _graphYAxisLabelIncrement;
static loco_global<uint16_t, 0x0113DC8A> _graphLineCount;
static loco_global<uint32_t[32], 0x0113DC8C> _graphYData;
static loco_global<uint32_t, 0x0113DD0C> _graphDataTypeSize;
static loco_global<uint16_t[32], 0x0113DD10> _graphDataStart;
static loco_global<uint32_t, 0x0113DD50> _dword_113DD50;
static loco_global<uint8_t[32], 0x0113DD54> _graphLineColour;
static loco_global<uint16_t, 0x0113DD74> _graphDataEnd;
static loco_global<uint16_t, 0x0113DD76> _graphXLabel;
static loco_global<uint32_t, 0x0113DD78> _graphXAxisRange;
static loco_global<uint32_t, 0x0113DD7C> _dword_113DD7C;
static loco_global<uint16_t, 0x0113DD80> _word_113DD80; //graphXAxisIncrement?
static loco_global<uint16_t, 0x0113DD82> _graphXAxisLabelIncrement;
static loco_global<uint16_t, 0x0113DD84> _graphYLabel;
static loco_global<uint32_t, 0x0113DD86> _dword_113DD86;
static loco_global<uint32_t, 0x0113DD8A> _dword_113DD8A;
static loco_global<uint32_t, 0x0113DD8E> _dword_113DD8E;
static loco_global<uint8_t, 0x0113DD99> _byte_113DD99;
static loco_global<uint16_t[32], 0x0113DD9A> _graphItemId;
namespace Common
{
enum widx
{
frame,
caption,
close_button,
panel,
tab_company_list,
tab_performance,
tab_cargo_units,
tab_cargo_distance,
tab_values,
tab_payment_rates,
tab_speed_records,
};
const uint64_t enabledWidgets = (1 << widx::close_button) | (1 << widx::tab_company_list) | (1 << widx::tab_performance) | (1 << widx::tab_cargo_units) | (1 << widx::tab_cargo_distance) | (1 << widx::tab_values) | (1 << widx::tab_payment_rates) | (1 << widx::tab_speed_records);
#define commonWidgets(frameWidth, frameHeight, windowCaptionId) \
makeWidget({ 0, 0 }, { frameWidth, frameHeight }, WidgetType::frame, WindowColour::primary), \
makeWidget({ 1, 1 }, { frameWidth - 2, 13 }, WidgetType::caption_25, WindowColour::primary, windowCaptionId), \
makeWidget({ frameWidth - 15, 2 }, { 13, 13 }, WidgetType::wt_9, WindowColour::primary, ImageIds::close_button, StringIds::tooltip_close_window), \
makeWidget({ 0, 41 }, { frameWidth, 231 }, WidgetType::panel, WindowColour::secondary), \
makeRemapWidget({ 3, 15 }, { 31, 27 }, WidgetType::wt_8, WindowColour::secondary, ImageIds::tab, StringIds::tab_compare_companies), \
makeRemapWidget({ 34, 15 }, { 31, 27 }, WidgetType::wt_8, WindowColour::secondary, ImageIds::tab, StringIds::tab_company_performance), \
makeRemapWidget({ 65, 15 }, { 31, 27 }, WidgetType::wt_8, WindowColour::secondary, ImageIds::tab, StringIds::tab_cargo_graphs), \
makeRemapWidget({ 96, 15 }, { 31, 27 }, WidgetType::wt_8, WindowColour::secondary, ImageIds::tab, StringIds::tab_cargo_distance_graphs), \
makeRemapWidget({ 127, 15 }, { 31, 27 }, WidgetType::wt_8, WindowColour::secondary, ImageIds::tab, StringIds::tab_company_values), \
makeRemapWidget({ 158, 15 }, { 31, 27 }, WidgetType::wt_8, WindowColour::secondary, ImageIds::tab, StringIds::tab_cargo_payment_rates), \
makeRemapWidget({ 189, 15 }, { 31, 27 }, WidgetType::wt_8, WindowColour::secondary, ImageIds::tab, StringIds::tab_speed_records)
static void onMouseUp(Window* self, WidgetIndex_t widgetIndex);
static void onUpdate(Window* self);
static void prepareDraw(Window* self);
static void switchTab(Window* self, WidgetIndex_t widgetIndex);
static void refreshCompanyList(Window* self);
static void drawTabs(Window* self, Gfx::Context* context);
static void drawGraph(Window* self, Gfx::Context* context);
static void drawGraphAndLegend(Window* self, Gfx::Context* context);
static void initEvents();
}
namespace CompanyList
{
static const Ui::Size maxWindowSize = { 640, 470 };
static const Ui::Size minWindowSize = { 300, 272 };
static const Ui::Size windowSize = { 640, 272 };
static const uint8_t rowHeight = 25;
enum widx
{
sort_name = 11,
sort_status,
sort_performance,
sort_value,
scrollview,
};
const uint64_t enabledWidgets = Common::enabledWidgets | (1 << sort_name) | (1 << sort_status) | (1 << sort_performance) | (1 << sort_value) | (1 << scrollview);
Widget widgets[] = {
commonWidgets(640, 272, StringIds::title_company_list),
makeWidget({ 4, 43 }, { 175, 12 }, WidgetType::wt_14, WindowColour::secondary, ImageIds::null, StringIds::tooltip_sort_company_name),
makeWidget({ 179, 43 }, { 210, 12 }, WidgetType::wt_14, WindowColour::secondary, ImageIds::null, StringIds::tooltip_sort_company_status),
makeWidget({ 389, 43 }, { 145, 12 }, WidgetType::wt_14, WindowColour::secondary, ImageIds::null, StringIds::tooltip_sort_company_performance),
makeWidget({ 534, 43 }, { 100, 12 }, WidgetType::wt_14, WindowColour::secondary, ImageIds::null, StringIds::tooltip_sort_company_value),
makeWidget({ 3, 56 }, { 634, 201 }, WidgetType::scrollview, WindowColour::secondary, Scrollbars::vertical),
widgetEnd(),
};
static WindowEventList events;
enum SortMode : uint16_t
{
Name,
Status,
Performance,
Value,
};
// 0x004360A2
static void onMouseUp(Window* self, WidgetIndex_t widgetIndex)
{
switch (widgetIndex)
{
case Common::widx::close_button:
WindowManager::close(self);
break;
case Common::widx::tab_company_list:
case Common::widx::tab_performance:
case Common::widx::tab_cargo_units:
case Common::widx::tab_cargo_distance:
case Common::widx::tab_values:
case Common::widx::tab_payment_rates:
case Common::widx::tab_speed_records:
Common::switchTab(self, widgetIndex);
break;
case sort_name:
case sort_status:
case sort_performance:
case sort_value:
{
auto sortMode = widgetIndex - widx::sort_name;
if (self->sort_mode == sortMode)
return;
self->sort_mode = sortMode;
self->invalidate();
self->var_83C = 0;
self->row_hover = -1;
Common::refreshCompanyList(self);
break;
}
}
}
// 0x004363CB
static void onResize(Window* self)
{
self->setSize(minWindowSize, maxWindowSize);
}
// 0x00437BA0
static bool orderByName(const OpenLoco::Company& lhs, const OpenLoco::Company& rhs)
{
char lhsString[256] = { 0 };
StringManager::formatString(lhsString, lhs.name);
char rhsString[256] = { 0 };
StringManager::formatString(rhsString, rhs.name);
return strcmp(lhsString, rhsString) < 0;
}
// 0x00437BE1
static bool orderByStatus(const OpenLoco::Company& lhs, const OpenLoco::Company& rhs)
{
char lhsString[256] = { 0 };
{
auto args = FormatArguments();
auto statusString = CompanyManager::getOwnerStatus(lhs.id(), args);
StringManager::formatString(lhsString, statusString, &args);
}
char rhsString[256] = { 0 };
{
auto args = FormatArguments();
auto statusString = CompanyManager::getOwnerStatus(lhs.id(), args);
StringManager::formatString(rhsString, statusString, &args);
}
return strcmp(lhsString, rhsString) < 0;
}
// 0x00437C53
static bool orderByPerformance(const OpenLoco::Company& lhs, const OpenLoco::Company& rhs)
{
auto lhsPerformance = lhs.performance_index;
auto rhsPerformance = rhs.performance_index;
return rhsPerformance < lhsPerformance;
}
// 0x00437C67
static bool orderByValue(const OpenLoco::Company& lhs, const OpenLoco::Company& rhs)
{
return rhs.companyValueHistory[0] < lhs.companyValueHistory[0];
}
// 0x00437BA0, 0x00437BE1, 0x00437C53, 0x00437C67
static bool getOrder(const SortMode mode, OpenLoco::Company& lhs, OpenLoco::Company& rhs)
{
switch (mode)
{
case SortMode::Name:
return orderByName(lhs, rhs);
case SortMode::Status:
return orderByStatus(lhs, rhs);
case SortMode::Performance:
return orderByPerformance(lhs, rhs);
case SortMode::Value:
return orderByValue(lhs, rhs);
}
return false;
}
// 0x00437AE2
static void updateCompanyList(Window* self)
{
auto chosenCompany = -1;
for (auto& company : CompanyManager::companies())
{
if ((company.challenge_flags & CompanyFlags::sorted) != 0)
continue;
if (chosenCompany == -1)
{
chosenCompany = company.id();
continue;
}
if (getOrder(SortMode(self->sort_mode), company, *CompanyManager::get(chosenCompany)))
{
chosenCompany = company.id();
}
}
if (chosenCompany != -1)
{
bool shouldInvalidate = false;
CompanyManager::get(chosenCompany)->challenge_flags |= CompanyFlags::sorted;
if (chosenCompany != self->row_info[self->row_count])
{
self->row_info[self->row_count] = chosenCompany;
shouldInvalidate = true;
}
self->row_count++;
if (self->row_count > self->var_83C)
{
self->var_83C = self->row_count;
shouldInvalidate = true;
}
if (shouldInvalidate)
{
self->invalidate();
}
}
else
{
if (self->var_83C != self->row_count)
{
self->var_83C = self->row_count;
self->invalidate();
}
Common::refreshCompanyList(self);
}
}
// 0x004362C0
static void onUpdate(Window* self)
{
self->frame_no++;
self->callPrepareDraw();
WindowManager::invalidateWidget(WindowType::companyList, self->number, self->current_tab + Common::widx::tab_company_list);
_word_9C68C7++;
// Add three companies every tick.
updateCompanyList(self);
updateCompanyList(self);
updateCompanyList(self);
}
// 0x004362F7
static void event_08(Window* self)
{
self->flags |= WindowFlags::not_scroll_view;
}
// 0x004362FF
static void event_09(Window* self)
{
if (!(self->flags & WindowFlags::not_scroll_view))
return;
if (self->row_hover == -1)
return;
self->row_hover = -1;
self->invalidate();
}
// 0x00436321
static void getScrollSize(Window* self, uint32_t scrollIndex, uint16_t* scrollWidth, uint16_t* scrollHeight)
{
*scrollHeight = self->var_83C * rowHeight;
}
// 0x004363A0
static void onScrollMouseDown(Window* self, int16_t x, int16_t y, uint8_t scroll_index)
{
uint16_t currentRow = y / rowHeight;
if (currentRow > self->var_83C)
return;
int16_t currentCompany = self->row_info[currentRow];
if (currentCompany == -1)
return;
CompanyWindow::open(currentCompany);
}
// 0x00436361
static void onScrollMouseOver(Window* self, int16_t x, int16_t y, uint8_t scroll_index)
{
self->flags &= ~(WindowFlags::not_scroll_view);
uint16_t currentRow = y / rowHeight;
int16_t currentCompany = -1;
if (currentRow < self->var_83C)
currentCompany = self->row_info[currentRow];
if (self->row_hover == currentCompany)
return;
self->row_hover = currentCompany;
self->invalidate();
}
// 0x004362B6
static std::optional<FormatArguments> tooltip(Window* self, WidgetIndex_t widgetIndex)
{
FormatArguments args{};
args.push(StringIds::tooltip_scroll_company_list);
return args;
}
// 0x0043632C
static Ui::CursorId cursor(Window* self, int16_t widgetIdx, int16_t xPos, int16_t yPos, Ui::CursorId fallback)
{
if (widgetIdx != widx::scrollview)
return fallback;
uint16_t currentIndex = yPos / rowHeight;
if (currentIndex < self->var_83C && self->row_info[currentIndex] != -1)
return CursorId::handPointer;
return fallback;
}
// 0x00435D07
static void prepareDraw(Window* self)
{
Common::prepareDraw(self);
self->widgets[widx::scrollview].right = self->width - 4;
self->widgets[widx::scrollview].bottom = self->height - 14;
// Reposition header buttons
self->widgets[widx::sort_name].right = std::min(178, self->width - 8);
self->widgets[widx::sort_status].left = std::min(179, self->width - 8);
self->widgets[widx::sort_status].right = std::min(388, self->width - 8);
self->widgets[widx::sort_performance].left = std::min(389, self->width - 8);
self->widgets[widx::sort_performance].right = std::min(533, self->width - 8);
self->widgets[widx::sort_value].left = std::min(534, self->width - 8);
self->widgets[widx::sort_value].right = std::min(633, self->width - 8);
// Set header button captions
self->widgets[widx::sort_name].text = self->sort_mode == SortMode::Name ? StringIds::table_header_company_name_desc : StringIds::table_header_company_name;
self->widgets[widx::sort_status].text = self->sort_mode == SortMode::Status ? StringIds::table_header_company_status_desc : StringIds::table_header_company_status;
self->widgets[widx::sort_performance].text = self->sort_mode == SortMode::Performance ? StringIds::table_header_company_performance_desc : StringIds::table_header_company_performance;
self->widgets[widx::sort_value].text = self->sort_mode == SortMode::Value ? StringIds::table_header_company_value_desc : StringIds::table_header_company_value;
}
// 0x00435E56
static void draw(Window* self, Gfx::Context* context)
{
self->draw(context);
Common::drawTabs(self, context);
auto args = FormatArguments();
if (self->var_83C == 1)
args.push(StringIds::company_singular);
else
args.push(StringIds::companies_plural);
args.push(self->var_83C);
auto xPos = self->x + 3;
auto yPos = self->y + self->height - 13;
Gfx::drawString_494B3F(*context, xPos, yPos, Colour::black, StringIds::black_stringid, &args);
}
// 0x00435EA7
static void drawScroll(Window& self, Gfx::Context& context, const uint32_t scrollIndex)
{
auto colour = Colour::getShade(self.getColour(WindowColour::secondary), 3);
Gfx::clearSingle(context, colour);
auto yBottom = 0;
for (auto i = 0; i < self.var_83C; i++, yBottom += 25)
{
auto yTop = yBottom + 25;
if (yTop <= context.y)
continue;
yTop = context.y + context.height;
if (yBottom >= yTop)
continue;
auto rowItem = self.row_info[i];
if (rowItem == -1)
continue;
auto stringId = StringIds::black_stringid;
if (rowItem == self.row_hover)
{
Gfx::drawRect(context, 0, yBottom, self.width, 24, (1 << 25) | PaletteIndex::index_30);
stringId = StringIds::wcolour2_stringid;
}
auto company = CompanyManager::get(rowItem);
auto competitorObj = ObjectManager::get<CompetitorObject>(company->competitor_id);
auto imageId = Gfx::recolour(competitorObj->images[company->owner_emotion], company->mainColours.primary);
{
auto args = FormatArguments();
args.push(StringIds::table_item_company);
args.push(imageId);
args.push(company->name);
Gfx::drawString_494BBF(context, 0, yBottom - 1, 173, Colour::black, stringId, &args);
}
{
auto args = FormatArguments();
args.skip(sizeof(string_id));
string_id ownerStatus = CompanyManager::getOwnerStatus(company->id(), args);
args.rewind();
args.push(ownerStatus);
Gfx::drawString_494BBF(context, 175, yBottom + 7, 208, Colour::black, stringId, &args);
}
auto performanceStringId = StringIds::performance_index;
if ((company->challenge_flags & CompanyFlags::increasedPerformance) && (company->challenge_flags & CompanyFlags::decreasedPerformance))
{
performanceStringId = StringIds::performance_index_decrease;
if (company->challenge_flags & CompanyFlags::increasedPerformance)
{
performanceStringId = StringIds::performance_index_increase;
}
}
{
auto args = FormatArguments();
args.push(performanceStringId);
formatPerformanceIndex(company->performance_index, args);
Gfx::drawString_494BBF(context, 385, yBottom - 1, 143, Colour::black, stringId, &args);
}
{
auto args = FormatArguments();
args.push(StringIds::company_value_currency);
args.push(company->companyValueHistory[0]);
Gfx::drawString_494BBF(context, 530, yBottom - 1, 98, Colour::black, stringId, &args);
}
}
}
// 0x00436198
static void tabReset(Window* self)
{
self->min_width = minWindowSize.width;
self->min_height = minWindowSize.height;
self->max_width = maxWindowSize.width;
self->max_height = maxWindowSize.height;
self->width = windowSize.width;
self->height = windowSize.height;
self->var_83C = 0;
self->row_hover = -1;
Common::refreshCompanyList(self);
}
static void initEvents()
{
events.on_mouse_up = onMouseUp;
events.on_resize = onResize;
events.on_update = onUpdate;
events.event_08 = event_08;
events.event_09 = event_09;
events.get_scroll_size = getScrollSize;
events.scroll_mouse_down = onScrollMouseDown;
events.scroll_mouse_over = onScrollMouseOver;
events.tooltip = tooltip;
events.cursor = cursor;
events.prepare_draw = prepareDraw;
events.draw = draw;
events.draw_scroll = drawScroll;
}
}
// 0x00435BC8
Window* open()
{
auto window = WindowManager::bringToFront(WindowType::companyList);
if (window != nullptr)
{
if (Input::isToolActive(_toolWindowType, _toolWindowNumber))
{
Input::toolCancel();
window = WindowManager::bringToFront(WindowType::companyList);
}
}
if (window == nullptr)
{
Ui::Size windowSize = { 640, 272 };
window = WindowManager::createWindow(WindowType::companyList, windowSize, 0, &CompanyList::events);
window->frame_no = 0;
window->saved_view.clear();
window->flags |= WindowFlags::resizable;
window->sort_mode = 2;
window->var_83C = 0;
window->row_hover = -1;
Common::refreshCompanyList(window);
auto skin = ObjectManager::get<InterfaceSkinObject>();
window->setColour(WindowColour::primary, skin->colour_0B);
window->setColour(WindowColour::secondary, skin->colour_0C);
window->var_854 = 0;
}
window->current_tab = 0;
window->min_width = CompanyList::minWindowSize.width;
window->min_height = CompanyList::minWindowSize.height;
window->max_width = CompanyList::maxWindowSize.width;
window->max_height = CompanyList::maxWindowSize.height;
window->invalidate();
Common::initEvents();
window->widgets = CompanyList::widgets;
window->enabled_widgets = CompanyList::enabledWidgets;
window->holdable_widgets = 0;
window->event_handlers = &CompanyList::events;
window->activated_widgets = 0;
window->initScrollWidgets();
return window;
}
// 0x00435C69
void openPerformanceIndexes()
{
auto window = open();
window->callOnMouseUp(Common::widx::tab_performance);
}
namespace CompanyPerformance
{
static const Ui::Size windowSize = { 635, 322 };
const uint64_t enabledWidgets = Common::enabledWidgets;
Widget widgets[] = {
commonWidgets(635, 322, StringIds::title_company_performance),
widgetEnd(),
};
static WindowEventList events;
// 0x004366D7
static void onResize(Window* self)
{
self->setSize(windowSize, windowSize);
}
// 0x00436490
static void draw(Window* self, Gfx::Context* context)
{
self->draw(context);
Common::drawTabs(self, context);
_graphLeft = self->x + 4;
_graphTop = self->y + self->widgets[Common::widx::panel].top + 4;
_graphRight = 520;
_graphBottom = self->height - self->widgets[Common::widx::panel].top - 8;
_graphYOffset = 17;
_graphXOffset = 40;
_graphYAxisLabelIncrement = 20;
_dword_113DD50 = 0;
uint16_t maxHistorySize = 1;
for (auto& company : CompanyManager::companies())
{
if (maxHistorySize < company.history_size)
maxHistorySize = company.history_size;
}
uint8_t count = 0;
for (auto& company : CompanyManager::companies())
{
auto companyId = company.id();
auto companyColour = CompanyManager::getCompanyColour(companyId);
_graphYData[count] = reinterpret_cast<uint32_t>(&company.performance_index_history[0]);
_graphDataStart[count] = maxHistorySize - company.history_size;
_graphLineColour[count] = Colour::getShade(companyColour, 6);
_graphItemId[count] = companyId;
count++;
}
_graphLineCount = count;
_graphDataEnd = maxHistorySize;
_graphDataTypeSize = 2;
_graphXLabel = StringIds::rawdate_short;
_graphYLabel = StringIds::percentage_one_decimal_place;
_word_113DD80 = 4;
_graphXAxisLabelIncrement = 12;
_dword_113DD86 = 0;
_dword_113DD8A = 100;
_dword_113DD8E = 2;
Common::drawGraphAndLegend(self, context);
}
// 0x004361D8
static void tabReset(Window* self)
{
self->min_width = windowSize.width;
self->min_height = windowSize.height;
self->max_width = windowSize.width;
self->max_height = windowSize.height;
self->width = windowSize.width;
self->height = windowSize.height;
}
static void initEvents()
{
events.on_mouse_up = Common::onMouseUp;
events.on_resize = onResize;
events.on_update = Common::onUpdate;
events.prepare_draw = Common::prepareDraw;
events.draw = draw;
}
}
namespace CargoUnits
{
static const Ui::Size windowSize = { 640, 272 };
const uint64_t enabledWidgets = Common::enabledWidgets;
Widget widgets[] = {
commonWidgets(635, 322, StringIds::title_company_cargo_units),
widgetEnd(),
};
static WindowEventList events;
// 0x004369FB
static void onResize(Window* self)
{
self->setSize(windowSize, windowSize);
}
// 0x004367B4
static void draw(Window* self, Gfx::Context* context)
{
self->draw(context);
Common::drawTabs(self, context);
_graphLeft = self->x + 4;
_graphTop = self->y + self->widgets[Common::widx::panel].top + 4;
_graphRight = 525;
_graphBottom = self->height - self->widgets[Common::widx::panel].top - 8;
_graphYOffset = 17;
_graphXOffset = 45;
_graphYAxisLabelIncrement = 25;
_dword_113DD50 = 0;
uint16_t maxHistorySize = 1;
for (auto& company : CompanyManager::companies())
{
if (maxHistorySize < company.history_size)
maxHistorySize = company.history_size;
}
uint8_t count = 0;
for (auto& company : CompanyManager::companies())
{
auto companyId = company.id();
auto companyColour = CompanyManager::getCompanyColour(companyId);
_graphYData[count] = reinterpret_cast<uint32_t>(&company.cargo_units_delivered_history[0]);
_graphDataStart[count] = maxHistorySize - company.history_size;
_graphLineColour[count] = Colour::getShade(companyColour, 6);
_graphItemId[count] = companyId;
count++;
}
_graphLineCount = count;
_graphDataEnd = maxHistorySize;
_graphDataTypeSize = 4;
_graphXLabel = StringIds::rawdate_short;
_graphYLabel = StringIds::cargo_units_delivered;
_word_113DD80 = 4;
_graphXAxisLabelIncrement = 12;
_dword_113DD86 = 0;
_dword_113DD8A = 1000;
_dword_113DD8E = 2;
Common::drawGraphAndLegend(self, context);
}
// 0x00436201
static void tabReset(Window* self)
{
self->min_width = windowSize.width;
self->min_height = windowSize.height;
self->max_width = windowSize.width;
self->max_height = windowSize.height;
self->width = windowSize.width;
self->height = windowSize.height;
}
static void initEvents()
{
events.on_mouse_up = Common::onMouseUp;
events.on_resize = onResize;
events.on_update = Common::onUpdate;
events.prepare_draw = Common::prepareDraw;
events.draw = draw;
}
}
namespace CargoDistance
{
static const Ui::Size windowSize = { 660, 272 };
const uint64_t enabledWidgets = Common::enabledWidgets;
Widget widgets[] = {
commonWidgets(635, 322, StringIds::title_cargo_distance_graphs),
widgetEnd(),
};
static WindowEventList events;
// 0x00436D1F
static void onResize(Window* self)
{
self->setSize(windowSize, windowSize);
}
// 0x00436AD8
static void draw(Window* self, Gfx::Context* context)
{
self->draw(context);
Common::drawTabs(self, context);
_graphLeft = self->x + 4;
_graphTop = self->y + self->widgets[Common::widx::panel].top + 4;
_graphRight = 545;
_graphBottom = self->height - self->widgets[Common::widx::panel].top - 8;
_graphYOffset = 17;
_graphXOffset = 65;
_graphYAxisLabelIncrement = 25;
_dword_113DD50 = 0;
uint16_t maxHistorySize = 1;
for (auto& company : CompanyManager::companies())
{
if (maxHistorySize < company.history_size)
maxHistorySize = company.history_size;
}
uint8_t count = 0;
for (auto& company : CompanyManager::companies())
{
auto companyId = company.id();
auto companyColour = CompanyManager::getCompanyColour(companyId);
_graphYData[count] = reinterpret_cast<uint32_t>(&company.cargo_units_distance_history[0]);
_graphDataStart[count] = maxHistorySize - company.history_size;
_graphLineColour[count] = Colour::getShade(companyColour, 6);
_graphItemId[count] = companyId;
count++;
}
_graphLineCount = count;
_graphDataEnd = maxHistorySize;
_graphDataTypeSize = 4;
_graphXLabel = StringIds::rawdate_short;
_graphYLabel = StringIds::cargo_units_delivered;
_word_113DD80 = 4;
_graphXAxisLabelIncrement = 12;
_dword_113DD86 = 0;
_dword_113DD8A = 1000;
_dword_113DD8E = 2;
Common::drawGraphAndLegend(self, context);
}
// 0x00436227
static void tabReset(Window* self)
{
self->min_width = windowSize.width;
self->min_height = windowSize.height;
self->max_width = windowSize.width;
self->max_height = windowSize.height;
self->width = windowSize.width;
self->height = windowSize.height;
}
static void initEvents()
{
events.on_mouse_up = Common::onMouseUp;
events.on_resize = onResize;
events.on_update = Common::onUpdate;
events.prepare_draw = Common::prepareDraw;
events.draw = draw;
}
}
namespace CompanyValues
{
static const Ui::Size windowSize = { 685, 322 };
const uint64_t enabledWidgets = Common::enabledWidgets;
Widget widgets[] = {
commonWidgets(685, 322, StringIds::title_company_values),
widgetEnd(),
};
static WindowEventList events;
// 0x00437043
static void onResize(Window* self)
{
self->setSize(windowSize, windowSize);
}
// 0x00436DFC
static void draw(Window* self, Gfx::Context* context)
{
self->draw(context);
Common::drawTabs(self, context);
_graphLeft = self->x + 4;
_graphTop = self->y + self->widgets[Common::widx::panel].top + 4;
_graphRight = 570;
_graphBottom = self->height - self->widgets[Common::widx::panel].top - 8;
_graphYOffset = 17;
_graphXOffset = 90;
_graphYAxisLabelIncrement = 25;
_dword_113DD50 = 0;
uint16_t maxHistorySize = 1;
for (auto& company : CompanyManager::companies())
{
if (maxHistorySize < company.history_size)
maxHistorySize = company.history_size;
}
uint8_t count = 0;
for (auto& company : CompanyManager::companies())
{
auto companyId = company.id();
auto companyColour = CompanyManager::getCompanyColour(companyId);
_graphYData[count] = reinterpret_cast<uint32_t>(&company.companyValueHistory[0]);
_graphDataStart[count] = maxHistorySize - company.history_size;
_graphLineColour[count] = Colour::getShade(companyColour, 6);
_graphItemId[count] = companyId;
count++;
}
_graphLineCount = count;
_graphDataEnd = maxHistorySize;
_graphDataTypeSize = 6;
_graphXLabel = StringIds::rawdate_short;
_graphYLabel = StringIds::small_company_value_currency;
_word_113DD80 = 4;
_graphXAxisLabelIncrement = 12;
_dword_113DD86 = 0;
_dword_113DD8A = 10000;
_dword_113DD8E = 2;
Common::drawGraphAndLegend(self, context);
}
// 0x0043624D
static void tabReset(Window* self)
{
self->min_width = windowSize.width;
self->min_height = windowSize.height;
self->max_width = windowSize.width;
self->max_height = windowSize.height;
self->width = windowSize.width;
self->height = windowSize.height;
}
static void initEvents()
{
events.on_mouse_up = Common::onMouseUp;
events.on_resize = onResize;
events.on_update = Common::onUpdate;
events.prepare_draw = Common::prepareDraw;
events.draw = draw;
}
}
namespace CargoPaymentRates
{
static const Ui::Size windowSize = { 495, 342 };
const uint64_t enabledWidgets = Common::enabledWidgets;
Widget widgets[] = {
commonWidgets(495, 342, StringIds::title_cargo_payment_rates),
widgetEnd(),
};
static WindowEventList events;
// 0x0043737D
static void onResize(Window* self)
{
self->setSize(windowSize, windowSize);
}
// 0x00437949
static void drawGraphLegend(Window* self, Gfx::Context* context, int16_t x, int16_t y)
{
auto cargoCount = 0;
for (uint8_t i = 0; i < ObjectManager::getMaxObjects(ObjectType::cargo); i++)
{
auto cargo = ObjectManager::get<CargoObject>(i);
if (cargo == nullptr)
continue;
auto colour = _cargoLineColour[i];
colour = Colour::getShade(colour, 6);
auto stringId = StringIds::small_black_string;
if (self->var_854 & (1 << cargoCount))
{
stringId = StringIds::small_white_string;
}
if (!(self->var_854 & (1 << cargoCount)) || !(_word_9C68C7 & (1 << 2)))
{
Gfx::fillRect(*context, x, y + 3, x + 4, y + 7, colour);
}
auto args = FormatArguments();
args.push(cargo->name);
Gfx::drawString_494BBF(*context, x + 6, y, 94, Colour::black, stringId, &args);
y += 10;
cargoCount++;
}
}
// 0x00437120
static void draw(Window* self, Gfx::Context* context)
{
self->draw(context);
Common::drawTabs(self, context);
_graphLeft = self->x + 4;
_graphTop = self->y + self->widgets[Common::widx::panel].top + 14;
_graphRight = 380;
_graphBottom = self->height - self->widgets[Common::widx::panel].top - 28;
_graphYOffset = 17;
_graphXOffset = 80;
_graphYAxisLabelIncrement = 25;
_dword_113DD50 = 0;
auto count = 0;
for (uint8_t i = 0; i < ObjectManager::getMaxObjects(ObjectType::cargo); i++)
{
auto cargo = ObjectManager::get<CargoObject>(i);
if (cargo == nullptr)
continue;
auto colour = _cargoLineColour[i];
_graphYData[count] = reinterpret_cast<uint32_t>(&_deliveredCargoPayment[i][0]);
_graphDataStart[count] = 0;
_graphLineColour[count] = Colour::getShade(colour, 6);
_graphItemId[count] = i;
count++;
}
_graphLineCount = count;
_graphDataEnd = 60;
_graphDataTypeSize = 4;
_graphXLabel = StringIds::cargo_delivered_days;
_graphYLabel = StringIds::cargo_delivered_currency;
_word_113DD80 = 5;
_graphXAxisLabelIncrement = 20;
_dword_113DD86 = 0;
_dword_113DD8A = 0;
_dword_113DD8E = 0;
_graphXAxisRange = 2;
_dword_113DD7C = 2;
_byte_113DD99 = 1;
Common::drawGraph(self, context);
if (self->var_854 != 0)
{
auto i = 0;
while (Utility::bitScanForward(self->var_854) != _graphItemId[i])
{
i++;
}
_dword_113DD50 = 0xFFFFFFFF & ~(1 << i);
if (_word_9C68C7 & (1 << 2))
_graphLineColour[i] = 10;
_dword_113DD8E = _dword_113DD8E | (1 << 2);
Common::drawGraph(self, context);
}
auto x = self->width + self->x - 104;
auto y = self->y + 52;
drawGraphLegend(self, context, x, y);
x = self->x + 8;
y = self->widgets[Common::widx::panel].top + self->y + 1;
auto args = FormatArguments();
args.push<uint16_t>(100);
args.push<uint16_t>(10);
Gfx::drawString_494B3F(*context, x, y, Colour::black, StringIds::cargo_deliver_graph_title, &args);
x = self->x + 160;
y = self->height + self->y - 13;
Gfx::drawString_494B3F(*context, x, y, Colour::black, StringIds::cargo_transit_time);
}
// 0x004375F7
static void buildDeliveredCargoPaymentsTable()
{
for (uint8_t cargoItem = 0; cargoItem < ObjectManager::getMaxObjects(ObjectType::cargo); ++cargoItem)
{
auto* cargoObj = ObjectManager::get<CargoObject>(cargoItem);
if (cargoObj == nullptr)
{
continue;
}
for (uint16_t numDays = 2; numDays <= 122; ++numDays)
{
_deliveredCargoPayment[cargoItem][(numDays / 2) - 1] = CompanyManager::calculateDeliveredCargoPayment(cargoItem, 100, 10, numDays);
}
}
}
// 0x004379F2
static void setLegendHover(Window* self, int16_t x, int16_t y)
{
uint32_t selectedCargo = 0;
if (!Input::hasFlag(Input::Flags::flag5))
{
const auto location = Input::getMouseLocation2();
auto* frontWindow = WindowManager::findAt(location);
const auto xDiff = location.x - x;
const auto yDiff = location.y - y;
if (frontWindow != nullptr && frontWindow == self && xDiff <= 100 && xDiff >= 0 && yDiff < 320 && yDiff >= 0)
{
auto listY = yDiff;
uint8_t cargoItem = 0;
for (; cargoItem < ObjectManager::getMaxObjects(ObjectType::cargo); ++cargoItem)
{
auto* cargoObj = ObjectManager::get<CargoObject>(cargoItem);
if (cargoObj == nullptr)
{
continue;
}
listY -= 10;
if (listY <= 0)
{
selectedCargo = 1ULL << cargoItem;
break;
}
}
}
}
if (self->var_854 != selectedCargo)
{
// TODO: var_854 is 16 bits but selectedCargo is 32 bits. Only the first 15 cargo types can be selected.
self->var_854 = selectedCargo;
self->invalidate();
}
if (self->var_854 != 0)
{
self->invalidate();
}
}
// 0x00436273
static void tabReset(Window* self)
{
self->min_width = windowSize.width;
self->min_height = windowSize.height;
self->max_width = windowSize.width;
self->max_height = windowSize.height;
self->width = windowSize.width;
self->height = windowSize.height;
buildDeliveredCargoPaymentsTable();
}
static void initEvents()
{
events.on_mouse_up = Common::onMouseUp;
events.on_resize = onResize;
events.on_update = Common::onUpdate;
events.prepare_draw = Common::prepareDraw;
events.draw = draw;
}
}
namespace CompanySpeedRecords
{
static const Ui::Size windowSize = { 495, 169 };
const uint64_t enabledWidgets = Common::enabledWidgets;
Widget widgets[] = {
commonWidgets(495, 169, StringIds::title_speed_records),
widgetEnd(),
};
static WindowEventList events;
// 0x0043737D
static void onResize(Window* self)
{
self->setSize(windowSize, windowSize);
}
// 0x0043745A
static void draw(Window* self, Gfx::Context* context)
{
self->draw(context);
Common::drawTabs(self, context);
auto y = self->y + 47;
for (auto i = 0; i < 3; i++)
{
auto recordType = _word_52624E[i];
if (recordType == 0)
continue;
{
auto args = FormatArguments();
args.push(recordType);
const string_id string[] = {
StringIds::land_speed_record,
StringIds::air_speed_record,
StringIds::water_speed_record,
};
auto x = self->x + 4;
Gfx::drawString_494B3F(*context, x, y, Colour::black, string[i], &args);
}
y += 11;
auto companyId = _byte_526254[i];
if (companyId != CompanyId::null)
{
auto company = CompanyManager::get(companyId);
auto competitorObj = ObjectManager::get<CompetitorObject>(company->competitor_id);
auto imageId = competitorObj->images[company->owner_emotion];
imageId = Gfx::recolour(imageId, company->mainColours.primary);
auto x = self->x + 4;
Gfx::drawImage(context, x, y, imageId);
x = self->x + 33;
y += 7;
auto args = FormatArguments();
args.push(company->name);
args.push<uint16_t>(0);
args.push(_dword_526258[i]);
Gfx::drawString_494B3F(*context, x, y, Colour::black, StringIds::record_date_achieved, &args);
y += 17;
}
y += 5;
}
}
static void initEvents()
{
events.on_mouse_up = Common::onMouseUp;
events.on_resize = onResize;
events.on_update = Common::onUpdate;
events.prepare_draw = Common::prepareDraw;
events.draw = draw;
}
}
namespace Common
{
struct TabInformation
{
Widget* widgets;
const widx widgetIndex;
WindowEventList* events;
const uint64_t enabledWidgets;
};
static TabInformation tabInformationByTabOffset[] = {
{ CompanyList::widgets, widx::tab_company_list, &CompanyList::events, CompanyList::enabledWidgets },
{ CompanyPerformance::widgets, widx::tab_performance, &CompanyPerformance::events, CompanyPerformance::enabledWidgets },
{ CargoUnits::widgets, widx::tab_cargo_units, &CargoUnits::events, CargoUnits::enabledWidgets },
{ CargoDistance::widgets, widx::tab_cargo_distance, &CargoDistance::events, CargoDistance::enabledWidgets },
{ CompanyValues::widgets, widx::tab_values, &CompanyValues::events, CompanyValues::enabledWidgets },
{ CargoPaymentRates::widgets, widx::tab_payment_rates, &CargoPaymentRates::events, CargoPaymentRates::enabledWidgets },
{ CompanySpeedRecords::widgets, widx::tab_speed_records, &CompanySpeedRecords::events, CompanySpeedRecords::enabledWidgets },
};
// 0x0043667B
static void onMouseUp(Window* self, WidgetIndex_t widgetIndex)
{
switch (widgetIndex)
{
case Common::widx::close_button:
WindowManager::close(self);
break;
case Common::widx::tab_company_list:
case Common::widx::tab_performance:
case Common::widx::tab_cargo_units:
case Common::widx::tab_cargo_distance:
case Common::widx::tab_values:
case Common::widx::tab_payment_rates:
case Common::widx::tab_speed_records:
Common::switchTab(self, widgetIndex);
break;
}
}
// 0x004378BA
static void setLegendHover(Window* self, int16_t x, int16_t y)
{
uint32_t selectedCompany = 0;
if (!Input::hasFlag(Input::Flags::flag5))
{
const auto location = Input::getMouseLocation2();
auto* frontWindow = WindowManager::findAt(location);
const auto xDiff = location.x - x;
const auto yDiff = location.y - y;
if (frontWindow != nullptr && frontWindow == self && xDiff <= 100 && xDiff >= 0 && yDiff < 150 && yDiff >= 0)
{
auto listY = yDiff;
for (auto& company : CompanyManager::companies())
{
listY -= 10;
if (listY <= 0)
{
selectedCompany = 1ULL << company.id();
break;
}
}
}
}
if (self->var_854 != selectedCompany)
{
self->var_854 = selectedCompany;
self->invalidate();
}
if (self->var_854 != 0)
{
self->invalidate();
}
}
// 0x00437570
static void onUpdate(Window* self)
{
self->frame_no++;
self->callPrepareDraw();
WindowManager::invalidateWidget(WindowType::townList, self->number, self->current_tab + Common::widx::tab_company_list);
auto x = self->width - 104 + self->x;
auto y = self->y + 52;
switch (self->current_tab + widx::tab_company_list)
{
case widx::tab_cargo_distance:
case widx::tab_cargo_units:
case widx::tab_performance:
case widx::tab_values:
{
_word_9C68C7++;
setLegendHover(self, x, y);
break;
}
case widx::tab_payment_rates:
{
_word_9C68C7++;
CargoPaymentRates::setLegendHover(self, x, y);
break;
}
case widx::tab_speed_records:
break;
}
}
// 0x00436419
static void prepareDraw(Window* self)
{
// Reset tab widgets if needed
const auto& tabWidgets = tabInformationByTabOffset[self->current_tab].widgets;
if (self->widgets != tabWidgets)
{
self->widgets = tabWidgets;
self->initScrollWidgets();
}
// Activate the current tab
self->activated_widgets &= ~((1ULL << tab_cargo_distance) | (1ULL << tab_cargo_units) | (1ULL << tab_company_list) | (1ULL << tab_payment_rates) | (1ULL << tab_performance) | (1ULL << tab_speed_records) | (1ULL << tab_values));
self->activated_widgets |= (1ULL << Common::tabInformationByTabOffset[self->current_tab].widgetIndex);
self->widgets[Common::widx::frame].right = self->width - 1;
self->widgets[Common::widx::frame].bottom = self->height - 1;
self->widgets[Common::widx::panel].right = self->width - 1;
self->widgets[Common::widx::panel].bottom = self->height - 1;
self->widgets[Common::widx::caption].right = self->width - 2;
self->widgets[Common::widx::close_button].left = self->width - 15;
self->widgets[Common::widx::close_button].right = self->width - 3;
}
//0x004360FA
static void switchTab(Window* self, WidgetIndex_t widgetIndex)
{
if (Input::isToolActive(self->type, self->number))
Input::toolCancel();
self->current_tab = widgetIndex - widx::tab_company_list;
self->frame_no = 0;
self->flags &= ~(WindowFlags::flag_16);
self->viewportRemove(0);
const auto& tabInfo = tabInformationByTabOffset[widgetIndex - widx::tab_company_list];
self->enabled_widgets = tabInfo.enabledWidgets;
self->holdable_widgets = 0;
self->event_handlers = tabInfo.events;
self->activated_widgets = 0;
self->widgets = tabInfo.widgets;
self->invalidate();
switch (widgetIndex)
{
case widx::tab_company_list:
CompanyList::tabReset(self);
break;
case widx::tab_performance:
CompanyPerformance::tabReset(self);
break;
case widx::tab_cargo_units:
CargoUnits::tabReset(self);
break;
case widx::tab_cargo_distance:
CargoDistance::tabReset(self);
break;
case widx::tab_values:
CompanyValues::tabReset(self);
break;
case widx::tab_payment_rates:
CargoPaymentRates::tabReset(self);
break;
}
self->callOnResize();
self->callPrepareDraw();
self->initScrollWidgets();
self->invalidate();
self->moveInsideScreenEdges();
}
// 0x00437637
static void drawTabs(Window* self, Gfx::Context* context)
{
auto skin = ObjectManager::get<InterfaceSkinObject>();
// Company List Tab
{
uint32_t imageId = skin->img;
imageId += InterfaceSkin::ImageIds::tab_companies;
Widget::drawTab(self, context, imageId, widx::tab_company_list);
}
// Performance Index Tab
{
static const uint32_t performanceImageIds[] = {
InterfaceSkin::ImageIds::tab_performance_index_frame0,
InterfaceSkin::ImageIds::tab_performance_index_frame1,
InterfaceSkin::ImageIds::tab_performance_index_frame2,
InterfaceSkin::ImageIds::tab_performance_index_frame3,
InterfaceSkin::ImageIds::tab_performance_index_frame4,
InterfaceSkin::ImageIds::tab_performance_index_frame5,
InterfaceSkin::ImageIds::tab_performance_index_frame6,
InterfaceSkin::ImageIds::tab_performance_index_frame7,
};
uint32_t imageId = skin->img;
if (self->current_tab == widx::tab_performance - widx::tab_company_list)
imageId += performanceImageIds[(self->frame_no / 4) % std::size(performanceImageIds)];
else
imageId += performanceImageIds[0];
imageId = Gfx::recolour(imageId, self->getColour(WindowColour::secondary));
Widget::drawTab(self, context, imageId, widx::tab_performance);
}
// Cargo Unit Tab
{
static const uint32_t cargoUnitsImageIds[] = {
InterfaceSkin::ImageIds::tab_cargo_units_frame0,
InterfaceSkin::ImageIds::tab_cargo_units_frame1,
InterfaceSkin::ImageIds::tab_cargo_units_frame2,
InterfaceSkin::ImageIds::tab_cargo_units_frame3,
InterfaceSkin::ImageIds::tab_cargo_units_frame4,
InterfaceSkin::ImageIds::tab_cargo_units_frame5,
InterfaceSkin::ImageIds::tab_cargo_units_frame6,
InterfaceSkin::ImageIds::tab_cargo_units_frame7,
};
uint32_t imageId = skin->img;
if (self->current_tab == widx::tab_cargo_units - widx::tab_company_list)
imageId += cargoUnitsImageIds[(self->frame_no / 4) % std::size(cargoUnitsImageIds)];
else
imageId += cargoUnitsImageIds[0];
imageId = Gfx::recolour(imageId, self->getColour(WindowColour::secondary));
Widget::drawTab(self, context, imageId, widx::tab_cargo_units);
}
// Cargo Distance Tab
{
static const uint32_t cargoDistanceImageIds[] = {
InterfaceSkin::ImageIds::tab_cargo_distance_frame0,
InterfaceSkin::ImageIds::tab_cargo_distance_frame1,
InterfaceSkin::ImageIds::tab_cargo_distance_frame2,
InterfaceSkin::ImageIds::tab_cargo_distance_frame3,
InterfaceSkin::ImageIds::tab_cargo_distance_frame4,
InterfaceSkin::ImageIds::tab_cargo_distance_frame5,
InterfaceSkin::ImageIds::tab_cargo_distance_frame6,
InterfaceSkin::ImageIds::tab_cargo_distance_frame7,
};
uint32_t imageId = skin->img;
if (self->current_tab == widx::tab_cargo_distance - widx::tab_company_list)
imageId += cargoDistanceImageIds[(self->frame_no / 4) % std::size(cargoDistanceImageIds)];
else
imageId += cargoDistanceImageIds[0];
imageId = Gfx::recolour(imageId, self->getColour(WindowColour::secondary));
Widget::drawTab(self, context, imageId, widx::tab_cargo_distance);
}
// Company Values Tab
{
static const uint32_t companyValuesImageIds[] = {
InterfaceSkin::ImageIds::tab_production_frame0,
InterfaceSkin::ImageIds::tab_production_frame1,
InterfaceSkin::ImageIds::tab_production_frame2,
InterfaceSkin::ImageIds::tab_production_frame3,
InterfaceSkin::ImageIds::tab_production_frame4,
InterfaceSkin::ImageIds::tab_production_frame5,
InterfaceSkin::ImageIds::tab_production_frame6,
InterfaceSkin::ImageIds::tab_production_frame7,
};
uint32_t imageId = skin->img;
if (self->current_tab == widx::tab_values - widx::tab_company_list)
imageId += companyValuesImageIds[(self->frame_no / 4) % std::size(companyValuesImageIds)];
else
imageId += companyValuesImageIds[0];
imageId = Gfx::recolour(imageId, self->getColour(WindowColour::secondary));
Widget::drawTab(self, context, imageId, widx::tab_values);
if (!(self->isDisabled(widx::tab_values)))
{
auto x = self->widgets[widx::tab_values].left + self->x + 28;
auto y = self->widgets[widx::tab_values].top + self->y + 14 + 1;
Gfx::drawString_494C78(*context, x, y, Colour::black, StringIds::currency_symbol);
}
}
// Payment Rates Tab
{
uint32_t imageId = skin->img;
imageId += InterfaceSkin::ImageIds::tab_cargo_payment_rates;
Widget::drawTab(self, context, imageId, widx::tab_payment_rates);
if (!(self->isDisabled(widx::tab_payment_rates)))
{
auto x = self->widgets[widx::tab_payment_rates].left + self->x + 28;
auto y = self->widgets[widx::tab_payment_rates].top + self->y + 14 + 1;
Gfx::drawString_494C78(*context, x, y, Colour::black, StringIds::currency_symbol);
}
}
// Speed Records Tab
{
uint32_t imageId = skin->img;
imageId += InterfaceSkin::ImageIds::tab_awards;
imageId = Gfx::recolour(imageId, self->getColour(WindowColour::secondary));
Widget::drawTab(self, context, imageId, widx::tab_speed_records);
}
}
// 0x00437AB6
static void refreshCompanyList(Window* self)
{
self->row_count = 0;
for (auto& company : CompanyManager::companies())
{
company.challenge_flags &= ~CompanyFlags::sorted;
}
}
// 0x004CF824
static void drawGraph(Window* self, Gfx::Context* context)
{
registers regs;
regs.esi = X86Pointer(self);
regs.edi = X86Pointer(context);
call(0x004CF824, regs);
}
// 0x00437810
static void drawGraphLegend(Window* self, Gfx::Context* context, int16_t x, int16_t y)
{
auto companyCount = 0;
for (auto& company : CompanyManager::companies())
{
auto companyColour = CompanyManager::getCompanyColour(company.id());
auto colour = Colour::getShade(companyColour, 6);
auto stringId = StringIds::small_black_string;
if (self->var_854 & (1 << companyCount))
{
stringId = StringIds::small_white_string;
}
if (!(self->var_854 & (1 << companyCount)) || !(_word_9C68C7 & (1 << 2)))
{
Gfx::fillRect(*context, x, y + 3, x + 4, y + 7, colour);
}
auto args = FormatArguments();
args.push(company.name);
Gfx::drawString_494BBF(*context, x + 6, y, 94, Colour::black, stringId, &args);
y += 10;
companyCount++;
}
}
// 0x004365E4
static void drawGraphAndLegend(Window* self, Gfx::Context* context)
{
auto totalMonths = (getCurrentYear() * 12) + static_cast<uint16_t>(getCurrentMonth());
_graphXAxisRange = totalMonths;
_dword_113DD7C = 1;
_byte_113DD99 = 1;
Common::drawGraph(self, context);
if (self->var_854 != 0)
{
auto i = 0;
auto bitScan = Utility::bitScanForward(self->var_854);
while (bitScan != _graphItemId[i] && bitScan != -1)
{
i++;
}
_dword_113DD50 = 0xFFFFFFFF & ~(1 << i);
if (_word_9C68C7 & (1 << 2))
_graphLineColour[i] = 10;
_dword_113DD8E = _dword_113DD8E | (1 << 2);
Common::drawGraph(self, context);
}
auto x = self->width + self->x - 104;
auto y = self->y + 52;
Common::drawGraphLegend(self, context, x, y);
}
static void initEvents()
{
CompanyList::initEvents();
CompanyValues::initEvents();
CompanyPerformance::initEvents();
CargoDistance::initEvents();
CargoUnits::initEvents();
CargoPaymentRates::initEvents();
CompanySpeedRecords::initEvents();
}
}
}
| 36.847487 | 286 | 0.53947 | Margen67 |
c6d996c9382b5c2b3f71eb62c53b2307e25964a0 | 929 | cpp | C++ | Example/thread_09/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | Example/thread_09/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | Example/thread_09/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | #include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
void wait(int seconds)
{
boost::this_thread::sleep_for(boost::chrono::seconds{seconds});
}
boost::timed_mutex mutex;
void thread1()
{
using boost::this_thread::get_id;
for (int i = 0; i < 5; ++i)
{
wait(1);
boost::unique_lock<boost::timed_mutex> lock{mutex};
std::cout << "Thread " << get_id() << ": " << i << std::endl;
boost::timed_mutex *m = lock.release();
m->unlock();
}
}
void thread2()
{
using boost::this_thread::get_id;
for (int i = 0; i < 5; ++i)
{
wait(1);
boost::unique_lock<boost::timed_mutex> lock{mutex,
boost::try_to_lock};
if (lock.owns_lock() || lock.try_lock_for(boost::chrono::seconds{1}))
{
std::cout << "Thread " << get_id() << ": " << i << std::endl;
}
}
}
int main()
{
boost::thread t1{thread1};
boost::thread t2{thread2};
t1.join();
t2.join();
} | 20.195652 | 73 | 0.592034 | KwangjoJeong |
c6dac2b62a04fddcfd3398b92abf86f10a94c974 | 2,930 | hh | C++ | service/capability_manager.hh | jinsukoh/nugu-linux | 4120811126031439b02d50723e17683cbced67a0 | [
"Apache-2.0"
] | 1 | 2019-10-24T03:58:10.000Z | 2019-10-24T03:58:10.000Z | service/capability_manager.hh | jinsukoh/nugu-linux | 4120811126031439b02d50723e17683cbced67a0 | [
"Apache-2.0"
] | null | null | null | service/capability_manager.hh | jinsukoh/nugu-linux | 4120811126031439b02d50723e17683cbced67a0 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __NUGU_CAPABILITY_AGENT_H__
#define __NUGU_CAPABILITY_AGENT_H__
#include <map>
#include <memory>
#include <core/nugu_directive_sequencer.h>
#include <core/nugu_focus.h>
#include <interface/capability/capability_interface.hh>
#include "playsync_manager.hh"
namespace NuguCore {
class IFocusListener {
public:
virtual ~IFocusListener() = default;
virtual NuguFocusResult onFocus(NuguFocusResource rsrc, void* event) = 0;
virtual NuguFocusResult onUnfocus(NuguFocusResource rsrc, void* event) = 0;
virtual NuguFocusStealResult onStealRequest(NuguFocusResource rsrc, void* event, NuguFocusType target_type) = 0;
};
class CapabilityManager {
private:
CapabilityManager();
virtual ~CapabilityManager();
public:
static CapabilityManager* getInstance();
static void destroyInstance();
PlaySyncManager* getPlaySyncManager();
static DirseqReturn dirseqCallback(NuguDirective* ndir, void* userdata);
void addCapability(std::string cname, ICapabilityInterface* cap);
void removeCapability(std::string cname);
void setWakeupWord(std::string word);
std::string makeContextInfo(Json::Value& ctx);
std::string makeAllContextInfo();
std::string makeAllContextInfoStack();
void preprocessDirective(NuguDirective* ndir);
void sendCommand(CapabilityType from, CapabilityType to, std::string command, std::string param);
void sendCommandAll(std::string command, std::string param);
void getCapabilityProperty(CapabilityType cap, std::string property, std::string& value);
void getCapabilityProperties(CapabilityType cap, std::string property, std::list<std::string>& values);
bool isFocusOn(NuguFocusResource rsrc);
int addFocus(std::string fname, NuguFocusType type, IFocusListener* listener);
int removeFocus(std::string fname);
int requestFocus(std::string fname, NuguFocusResource rsrc, void* event);
int releaseFocus(std::string fname, NuguFocusResource rsrc);
private:
ICapabilityInterface* findCapability(std::string cname);
static CapabilityManager* instance;
std::map<std::string, ICapabilityInterface*> caps;
std::map<std::string, NuguFocus*> focusmap;
std::string wword;
std::unique_ptr<PlaySyncManager> playsync_manager = nullptr;
};
} // NuguCore
#endif
| 34.069767 | 116 | 0.752218 | jinsukoh |
c6dfbaaa9c463afd39d85ff9a09f0cd201eabb8b | 271 | hpp | C++ | FootCommander.hpp | sapirp/task4-warGame-A | f2ba937017c3967f2d4a483b0bdcc604bb75f654 | [
"MIT"
] | null | null | null | FootCommander.hpp | sapirp/task4-warGame-A | f2ba937017c3967f2d4a483b0bdcc604bb75f654 | [
"MIT"
] | null | null | null | FootCommander.hpp | sapirp/task4-warGame-A | f2ba937017c3967f2d4a483b0bdcc604bb75f654 | [
"MIT"
] | null | null | null |
#ifndef _footCommender_H
#define _footCommender_H
#include "FootSoldier.hpp"
class FootCommander : public FootSoldier
{
public:
//constructor
FootCommander(int p) : FootSoldier(p)
{
std::cout << "FootCommander const" << std::endl;
}
};
#endif | 15.055556 | 56 | 0.675277 | sapirp |
c6e06d98089e292162481e230ce2fc0cb0637abb | 4,309 | hpp | C++ | Public/Src/Sandbox/MacOs/Interop/Sandbox/Handlers/AccessHandler.hpp | RobJellinghaus/BuildXL | 78f64d827a105a26b11a7cae1bcb57037c396dde | [
"MIT"
] | null | null | null | Public/Src/Sandbox/MacOs/Interop/Sandbox/Handlers/AccessHandler.hpp | RobJellinghaus/BuildXL | 78f64d827a105a26b11a7cae1bcb57037c396dde | [
"MIT"
] | 3 | 2019-12-05T04:47:42.000Z | 2020-02-07T17:15:35.000Z | Public/Src/Sandbox/MacOs/Interop/Sandbox/Handlers/AccessHandler.hpp | RobJellinghaus/BuildXL | 78f64d827a105a26b11a7cae1bcb57037c396dde | [
"MIT"
] | 1 | 2019-12-05T00:02:03.000Z | 2019-12-05T00:02:03.000Z | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#ifndef AccessHandler_hpp
#define AccessHandler_hpp
#include "Sandbox.hpp"
#include "Checkers.hpp"
#include "IOEvent.hpp"
enum ReportResult
{
kReported,
kSkipped,
kFailed
};
typedef bool (Handler)(void *data);
struct AccessHandler
{
private:
const char *IgnoreDataPartitionPrefix(const char* path);
const char *kDataPartitionPrefix = "/System/Volumes/Data/";
const size_t kAdjustedPrefixLength = strlen("/System/Volumes/Data");
Sandbox *sandbox_;
std::shared_ptr<SandboxedProcess> process_;
ReportResult ReportFileOpAccess(FileOperation operation,
PolicyResult policy,
AccessCheckResult accessCheckResult,
pid_t processID);
protected:
inline Sandbox* GetSandbox() const { return sandbox_; }
inline const std::shared_ptr<SandboxedProcess> GetProcess() const { return process_; }
inline const std::shared_ptr<SandboxedPip> GetPip() const { return process_->GetPip(); }
PolicySearchCursor FindManifestRecord(const char *absolutePath, size_t pathLength = -1);
/*!
* Copies 'process_->getPath()' into 'report->path'.
*/
void SetProcessPath(AccessReport *report);
/*!
* Template for checking and reporting file accesses.
*
* The key used for looking up if the operation was already reported is "<operation>,<path>".
*
* @param operation Operation to be executed
* @param path Absolute path against which the operation is to be executed
* @param checker Checker function to apply to policy
* @param pid The id of the process belonging to this I/O obsevation
* @param isDir Indicates if the report is being generated for a directory or file
*/
AccessCheckResult CheckAndReportInternal(FileOperation operation,
const char *path,
CheckFunc checker,
const pid_t pid,
bool isDir);
inline AccessCheckResult CheckAndReport(FileOperation operation, const char *path, CheckFunc checker, const pid_t pid)
{
return CheckAndReportInternal(operation, path, checker, pid, false);
}
inline AccessCheckResult CheckAndReport(FileOperation operation, const char *path, CheckFunc checker, const pid_t pid, bool isDir)
{
return CheckAndReportInternal(operation, path, checker, pid, isDir);
}
public:
AccessHandler() = delete;
AccessHandler(Sandbox *sandbox)
{
sandbox_ = sandbox;
process_ = nullptr;
}
~AccessHandler()
{
sandbox_ = nullptr;
process_ = nullptr;
}
/*!
* Attempts to find a tracked ProcessObject instance that corresponds to a given 'pid'.
* If successful, initializes this object with the found ProcessObject.
*
* IMPORTANT: This should be the first method to call after upon constructor this object.
* Whenever the initialization fails, this object should not be used futher.
*
* @param pid Process ID to try to find.
* @result Indicates whether the initialization was successful.
*/
bool TryInitializeWithTrackedProcess(pid_t pid);
inline void SetProcess(std::shared_ptr<SandboxedProcess> process) { process_ = process; }
inline bool HasTrackedProcess() const { return process_ != nullptr; }
inline pid_t GetProcessId() const { return GetPip()->GetProcessId(); }
inline pipid_t GetPipId() const { return GetPip()->GetPipId(); }
inline int GetProcessTreeSize() const { return GetPip()->GetTreeSize(); }
inline FileAccessManifestFlag GetFamFlags() const { return GetPip()->GetFamFlags(); }
PolicyResult PolicyForPath(const char *absolutePath);
bool ReportProcessTreeCompleted(pid_t processId);
bool ReportProcessExited(pid_t childPid);
bool ReportChildProcessSpawned(pid_t childPid);
};
#endif /* AccessHandler_hpp */
| 35.319672 | 134 | 0.649339 | RobJellinghaus |
c6e10baa45898695fbaf4f77dcfebfa2806d72f0 | 552 | hpp | C++ | lib/tests/mock_server.hpp | mihaibuzgau/facter | 451ee4288c61c6185295b454339801b84b8242ef | [
"Apache-2.0"
] | null | null | null | lib/tests/mock_server.hpp | mihaibuzgau/facter | 451ee4288c61c6185295b454339801b84b8242ef | [
"Apache-2.0"
] | null | null | null | lib/tests/mock_server.hpp | mihaibuzgau/facter | 451ee4288c61c6185295b454339801b84b8242ef | [
"Apache-2.0"
] | null | null | null | #pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#pragma GCC diagnostic pop
namespace facter {
using boost::asio::ip::tcp;
class mock_server {
public:
mock_server(int port);
~mock_server();
private:
boost::asio::io_service io_service_;
tcp::acceptor acceptor_;
tcp::socket socket_;
boost::thread thread_;
};
} // namespace facter
| 21.230769 | 50 | 0.666667 | mihaibuzgau |
c6e455880230ad5a9d5eb18f989eb2912491b0d4 | 675 | cpp | C++ | allMatuCommit/3.8 计算e的x次方_2021010915007_20210920110953.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | allMatuCommit/3.8 计算e的x次方_2021010915007_20210920110953.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | allMatuCommit/3.8 计算e的x次方_2021010915007_20210920110953.cpp | BachWV/matu | d4e3a89385f0a205431dd34c2c7214af40bb8ddb | [
"MIT"
] | null | null | null | #include<stdio.h>
double Factorial(double n);
double Pow(double n,int exp);
int main(void)
{
double dN, dX, dF, dEx = 1;
scanf("%lf %lf", &dX, &dN);
int iN = (int)dN;
if (dX > 0 && dN >= 0)
{
for (;iN>=1;iN--)
{
dEx = dEx + Pow(dX,iN) / Factorial(iN);
}
printf("%lf", dEx);
}
else
{
printf("error");
}
return 0;
}
double Factorial(double n)
{
int iNf=1,iNt=n;
for (int iCon_1 = 1; iCon_1 <= n; iCon_1++)
{
iNf = iNf * (iNt--);
}
return (double)iNf;
}
double Pow(double n,int exp)
{
double dResult = 1;
for (int iCon_3=1; iCon_3 <= exp; iCon_3++)
{
dResult = dResult * n;
}
return dResult;
} | 15.697674 | 45 | 0.525926 | BachWV |
c6e8455d88b66b5bffb05e3d65c871b9f87eee44 | 9,790 | cpp | C++ | test/BaumWelchAlgorithmTests.cpp | Jamagas/HMM | 7a9fc3446c28be79da36e7b567ad3b18cdf5c185 | [
"MIT"
] | 1 | 2021-03-07T15:51:12.000Z | 2021-03-07T15:51:12.000Z | test/BaumWelchAlgorithmTests.cpp | Jamagas/HMM | 7a9fc3446c28be79da36e7b567ad3b18cdf5c185 | [
"MIT"
] | null | null | null | test/BaumWelchAlgorithmTests.cpp | Jamagas/HMM | 7a9fc3446c28be79da36e7b567ad3b18cdf5c185 | [
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <HMM/BaumWelchAlgorithm.h>
/* http://www.cs.rochester.edu/u/james/CSC248/Lec11.pdf */
TEST (BaumWelchAlgorithmTests, ForwardAlgorithm_1) {
std::array<double, 2> ispDistribution = {{ 0.8, 0.2 }};
InitialStateProbabilityDistribution<2> initialDistribution = InitialStateProbabilityDistribution<2>(ispDistribution);
std::array<std::array<double, 2>, 2> stpDistribution = {{
{{ 0.6, 0.4 }},
{{ 0.3, 0.7 }}
}};
StateTransitionProbabilityDistributionMatrix<2> transitionDistribution = StateTransitionProbabilityDistributionMatrix<2>(stpDistribution);
std::array<std::array<double, 3>, 2> sepDistribution = {{
{{ 0.3, 0.4, 0.3 }},
{{ 0.4, 0.3, 0.3 }}
}};
StateEmissionProbabilityDistributionMatrix<2, 3> emissionDistribution = StateEmissionProbabilityDistributionMatrix<2, 3>(sepDistribution);
std::array<std::string, 3> observations = {{ "R", "W", "B" }};
Model<2, 3> model = Model<2, 3>(transitionDistribution, emissionDistribution, initialDistribution, observations);
std::array<std::string, 4> observationSequance = {{ "R", "W", "B", "B" }};
std::array<std::array<double, 4>, 2> alpha = forwardAlgorithmMatrix(model, observationSequance);
EXPECT_DOUBLE_EQ(0.24, alpha[0][0]);
EXPECT_DOUBLE_EQ(0.08, alpha[1][0]);
EXPECT_DOUBLE_EQ(0.0672, alpha[0][1]);
EXPECT_DOUBLE_EQ(0.0456, alpha[1][1]);
EXPECT_DOUBLE_EQ(0.0162, alpha[0][2]);
EXPECT_DOUBLE_EQ(0.01764, alpha[1][2]);
EXPECT_DOUBLE_EQ(0.0045036, alpha[0][3]);
EXPECT_DOUBLE_EQ(0.0056484, alpha[1][3]);
}
/* http://www2.nkfust.edu.tw/~wenh/2008/multimedia/HMMPack/HMMIntro.ppt */
TEST (BaumWelchAlgorithmTests, ForwardAlgorithm_2) {
std::array<double, 3> ispDistribution = {{ 0.5, 0.25, 0.25 }};
InitialStateProbabilityDistribution<3> initialDistribution = InitialStateProbabilityDistribution<3>(ispDistribution);
std::array<std::array<double, 3>, 3> stpDistribution = {{
{{ 0.2, 0.6, 0.2 }},
{{ 0.25, 0.5, 0.25 }},
{{ 0.35, 0.15, 0.5 }}
}};
StateTransitionProbabilityDistributionMatrix<3> transitionDistribution = StateTransitionProbabilityDistributionMatrix<3>(stpDistribution);
std::array<std::array<double, 3>, 3> sepDistribution = {{
{{ 0.25, 0.25, 0.5 }},
{{ 0.2, 0.3, 0.5 }},
{{ 0.45, 0.05, 0.5 }}
}};
StateEmissionProbabilityDistributionMatrix<3, 3> emissionDistribution = StateEmissionProbabilityDistributionMatrix<3, 3>(sepDistribution);
std::array<std::string, 3> observations = {{ "R", "G", "B" }};
Model<3, 3> model = Model<3, 3>(transitionDistribution, emissionDistribution, initialDistribution, observations);
std::array<std::string, 3> observationSequance = {{ "R", "G", "B" }};
std::array<std::array<double, 3>, 3> alpha = forwardAlgorithmMatrix(model, observationSequance);
EXPECT_NEAR(0.125, alpha[0][0], 0.00005);
EXPECT_NEAR(0.05, alpha[1][0], 0.00005);
EXPECT_NEAR(0.1125, alpha[2][0], 0.00005);
EXPECT_NEAR(0.0192, alpha[0][1], 0.00005);
EXPECT_NEAR(0.0351, alpha[1][1], 0.00005);
EXPECT_NEAR(0.0047, alpha[2][1], 0.00005);
EXPECT_NEAR(0.0071, alpha[0][2], 0.00005);
EXPECT_NEAR(0.0149, alpha[1][2], 0.00005);
EXPECT_NEAR(0.0075, alpha[2][2], 0.00005);
}
/* http://www.cs.rochester.edu/u/james/CSC248/Lec11.pdf */
TEST (BaumWelchAlgorithmTests, BackwardAlgorithm_1) {
std::array<double, 2> ispDistribution = {{ 0.8, 0.2 }};
InitialStateProbabilityDistribution<2> initialDistribution = InitialStateProbabilityDistribution<2>(ispDistribution);
std::array<std::array<double, 2>, 2> stpDistribution = {{
{{ 0.6, 0.4 }},
{{ 0.3, 0.7 }}
}};
StateTransitionProbabilityDistributionMatrix<2> transitionDistribution = StateTransitionProbabilityDistributionMatrix<2>(stpDistribution);
std::array<std::array<double, 3>, 2> sepDistribution = {{
{{ 0.3, 0.4, 0.3 }},
{{ 0.4, 0.3, 0.3 }}
}};
StateEmissionProbabilityDistributionMatrix<2, 3> emissionDistribution = StateEmissionProbabilityDistributionMatrix<2, 3>(sepDistribution);
std::array<std::string, 3> observations = {{ "R", "W", "B" }};
Model<2, 3> model = Model<2, 3>(transitionDistribution, emissionDistribution, initialDistribution, observations);
std::array<std::string, 4> observationSequance = {{ "R", "W", "B", "B" }};
std::array<std::array<double, 4>, 2> beta = backwardAlgorithmMatrix(model, observationSequance);
EXPECT_DOUBLE_EQ(0.0324, beta[0][0]);
EXPECT_DOUBLE_EQ(0.0297, beta[1][0]);
EXPECT_DOUBLE_EQ(0.09, beta[0][1]);
EXPECT_DOUBLE_EQ(0.09, beta[1][1]);
EXPECT_DOUBLE_EQ(0.3, beta[0][2]);
EXPECT_DOUBLE_EQ(0.3, beta[1][2]);
EXPECT_DOUBLE_EQ(1.0, beta[0][3]);
EXPECT_DOUBLE_EQ(1.0, beta[1][3]);
}
/* http://www2.nkfust.edu.tw/~wenh/2008/multimedia/HMMPack/HMMIntro.ppt */
TEST (BaumWelchAlgorithmTests, BackwardAlgorithm_2) {
std::array<double, 3> ispDistribution = {{ 0.5, 0.25, 0.25 }};
InitialStateProbabilityDistribution<3> initialDistribution = InitialStateProbabilityDistribution<3>(ispDistribution);
std::array<std::array<double, 3>, 3> stpDistribution = {{
{{ 0.2, 0.6, 0.2 }},
{{ 0.25, 0.5, 0.25 }},
{{ 0.35, 0.15, 0.5 }}
}};
StateTransitionProbabilityDistributionMatrix<3> transitionDistribution = StateTransitionProbabilityDistributionMatrix<3>(stpDistribution);
std::array<std::array<double, 3>, 3> sepDistribution = {{
{{ 0.25, 0.25, 0.5 }},
{{ 0.2, 0.3, 0.5 }},
{{ 0.45, 0.05, 0.5 }}
}};
StateEmissionProbabilityDistributionMatrix<3, 3> emissionDistribution = StateEmissionProbabilityDistributionMatrix<3, 3>(sepDistribution);
std::array<std::string, 3> observations = {{ "R", "G", "B" }};
Model<3, 3> model = Model<3, 3>(transitionDistribution, emissionDistribution, initialDistribution, observations);
std::array<std::string, 3> observationSequance = {{ "R", "G", "B" }};
std::array<std::array<double, 3>, 3> beta = backwardAlgorithmMatrix(model, observationSequance);
EXPECT_NEAR(0.12, beta[0][0], 0.00005);
EXPECT_NEAR(0.1125, beta[1][0], 0.00005);
EXPECT_NEAR(0.0788, beta[2][0], 0.00005);
EXPECT_NEAR(0.5, beta[0][1], 0.00005);
EXPECT_NEAR(0.5, beta[1][1], 0.00005);
EXPECT_NEAR(0.5, beta[2][1], 0.00005);
EXPECT_NEAR(1.0, beta[0][2], 0.00005);
EXPECT_NEAR(1.0, beta[1][2], 0.00005);
EXPECT_NEAR(1.0, beta[2][2], 0.00005);
}
TEST(BaumWelchAlgorithmTests, ForwardBackwardArriveAtSameValue_1) {
std::array<double, 2> ispDistribution = {{ 0.8, 0.2 }};
InitialStateProbabilityDistribution<2> initialDistribution = InitialStateProbabilityDistribution<2>(ispDistribution);
std::array<std::array<double, 2>, 2> stpDistribution = {{
{{ 0.6, 0.4 }},
{{ 0.3, 0.7 }}
}};
StateTransitionProbabilityDistributionMatrix<2> transitionDistribution = StateTransitionProbabilityDistributionMatrix<2>(stpDistribution);
std::array<std::array<double, 3>, 2> sepDistribution = {{
{{ 0.3, 0.4, 0.3 }},
{{ 0.4, 0.3, 0.3 }}
}};
StateEmissionProbabilityDistributionMatrix<2, 3> emissionDistribution = StateEmissionProbabilityDistributionMatrix<2, 3>(sepDistribution);
std::array<std::string, 3> observations = {{ "R", "W", "B" }};
Model<2, 3> model = Model<2, 3>(transitionDistribution, emissionDistribution, initialDistribution, observations);
std::array<std::string, 4> observationSequance = {{ "R", "W", "B", "B" }};
std::array<std::array<double, 4>, 2> alpha = forwardAlgorithmMatrix(model, observationSequance);
std::array<std::array<double, 4>, 2> beta = backwardAlgorithmMatrix(model, observationSequance);
EXPECT_TRUE(forwardAlgorithmTermination(model, alpha) > 0);
EXPECT_TRUE(backwardAlgorithmTermination(model, beta) > 0);
EXPECT_DOUBLE_EQ(forwardAlgorithmTermination(model, alpha), backwardAlgorithmTermination(model, beta));
}
TEST(BaumWelchAlgorithmTests, ForwardBackwardArriveAtSameValue_2) {
std::array<double, 3> ispDistribution = {{ 0.5, 0.25, 0.25 }};
InitialStateProbabilityDistribution<3> initialDistribution = InitialStateProbabilityDistribution<3>(ispDistribution);
std::array<std::array<double, 3>, 3> stpDistribution = {{
{{ 0.2, 0.6, 0.2 }},
{{ 0.25, 0.5, 0.25 }},
{{ 0.35, 0.15, 0.5 }}
}};
StateTransitionProbabilityDistributionMatrix<3> transitionDistribution = StateTransitionProbabilityDistributionMatrix<3>(stpDistribution);
std::array<std::array<double, 3>, 3> sepDistribution = {{
{{ 0.25, 0.25, 0.5 }},
{{ 0.2, 0.3, 0.5 }},
{{ 0.45, 0.05, 0.5 }}
}};
StateEmissionProbabilityDistributionMatrix<3, 3> emissionDistribution = StateEmissionProbabilityDistributionMatrix<3, 3>(sepDistribution);
std::array<std::string, 3> observations = {{ "R", "G", "B" }};
Model<3, 3> model = Model<3, 3>(transitionDistribution, emissionDistribution, initialDistribution, observations);
std::array<std::string, 3> observationSequance = {{ "R", "G", "B" }};
std::array<std::array<double, 3>, 3> alpha = forwardAlgorithmMatrix(model, observationSequance);
std::array<std::array<double, 3>, 3> beta = backwardAlgorithmMatrix(model, observationSequance);
EXPECT_TRUE(forwardAlgorithmTermination(model, alpha) > 0);
EXPECT_TRUE(backwardAlgorithmTermination(model, beta) > 0);
EXPECT_DOUBLE_EQ(forwardAlgorithmTermination(model, alpha), backwardAlgorithmTermination(model, beta));
}
| 45.962441 | 142 | 0.657916 | Jamagas |
c6f325412373c57eac4f2ebc3a5b535291ab971d | 6,222 | hpp | C++ | include/pressiodemoapps/impl/euler_3d_ghost_filler.hpp | fnrizzi/pressio-demoapps | 6ff10bbcf4d526610580940753c9620725bff1ba | [
"BSD-3-Clause"
] | 2 | 2021-11-17T18:20:21.000Z | 2022-03-05T09:23:02.000Z | include/pressiodemoapps/impl/euler_3d_ghost_filler.hpp | fnrizzi/pressio-demoapps | 6ff10bbcf4d526610580940753c9620725bff1ba | [
"BSD-3-Clause"
] | 70 | 2021-05-13T08:27:05.000Z | 2022-03-30T15:39:29.000Z | include/pressiodemoapps/impl/euler_3d_ghost_filler.hpp | fnrizzi/pressio-demoapps | 6ff10bbcf4d526610580940753c9620725bff1ba | [
"BSD-3-Clause"
] | 1 | 2021-12-27T13:39:03.000Z | 2021-12-27T13:39:03.000Z |
#ifndef PRESSIODEMOAPPS_GHOST_FILLER_EE3D_HPP_
#define PRESSIODEMOAPPS_GHOST_FILLER_EE3D_HPP_
namespace pressiodemoapps{ namespace ee{ namespace impl{
template<class state_t, class mesh_t, class ghost_t>
class Ghost3dSedov
{
public:
Ghost3dSedov() = delete;
Ghost3dSedov(const int stencilSize,
const state_t & stateIn,
const mesh_t & meshIn,
ghost_t & ghostLeft,
ghost_t & ghostRight,
ghost_t & ghostBack,
ghost_t & ghostFront,
ghost_t & ghostBottom,
ghost_t & ghostTop)
: m_stencilSize(stencilSize),
m_state(stateIn),
m_meshObj(meshIn),
m_ghostLeft(ghostLeft),
m_ghostRight(ghostRight),
m_ghostBack(ghostBack),
m_ghostFront(ghostFront),
m_ghostBottom(ghostBottom),
m_ghostTop(ghostTop)
{}
template<int stencilSize, class index_t>
typename std::enable_if<stencilSize == 3>::type
operator()(index_t smPt, int gRow)
{
constexpr int numDofPerCell = 5;
const auto & graph = m_meshObj.graph();
const auto cellGID = graph(smPt, 0);
const auto uIndex = cellGID*numDofPerCell;
const auto left0 = graph(smPt, 1);
const auto front0 = graph(smPt, 2);
const auto right0 = graph(smPt, 3);
const auto back0 = graph(smPt, 4);
const auto bot0 = graph(smPt, 5);
const auto top0 = graph(smPt, 6);
if (left0 == -1)
{
m_ghostLeft(gRow, 0) = m_state(uIndex);
m_ghostLeft(gRow, 1) = -m_state(uIndex+1);
m_ghostLeft(gRow, 2) = m_state(uIndex+2);
m_ghostLeft(gRow, 3) = m_state(uIndex+3);
m_ghostLeft(gRow, 4) = m_state(uIndex+4);
}
if (front0 == -1)
{
m_ghostFront(gRow, 0) = m_state(uIndex);
m_ghostFront(gRow, 1) = m_state(uIndex+1);
m_ghostFront(gRow, 2) = m_state(uIndex+2);
m_ghostFront(gRow, 3) = m_state(uIndex+3);
m_ghostFront(gRow, 4) = m_state(uIndex+4);
}
if (right0 == -1)
{
m_ghostRight(gRow, 0) = m_state(uIndex);
m_ghostRight(gRow, 1) = m_state(uIndex+1);
m_ghostRight(gRow, 2) = m_state(uIndex+2);
m_ghostRight(gRow, 3) = m_state(uIndex+3);
m_ghostRight(gRow, 4) = m_state(uIndex+4);
}
if (back0 == -1)
{
m_ghostBack(gRow, 0) = m_state(uIndex);
m_ghostBack(gRow, 1) = m_state(uIndex+1);
m_ghostBack(gRow, 2) = -m_state(uIndex+2);
m_ghostBack(gRow, 3) = m_state(uIndex+3);
m_ghostBack(gRow, 4) = m_state(uIndex+4);
}
if (top0 == -1)
{
m_ghostTop(gRow, 0) = m_state(uIndex);
m_ghostTop(gRow, 1) = m_state(uIndex+1);
m_ghostTop(gRow, 2) = m_state(uIndex+2);
m_ghostTop(gRow, 3) = m_state(uIndex+3);
m_ghostTop(gRow, 4) = m_state(uIndex+4);
}
if (bot0 == -1)
{
m_ghostBottom(gRow, 0) = m_state(uIndex);
m_ghostBottom(gRow, 1) = m_state(uIndex+1);
m_ghostBottom(gRow, 2) = m_state(uIndex+2);
m_ghostBottom(gRow, 3) = -m_state(uIndex+3);
m_ghostBottom(gRow, 4) = m_state(uIndex+4);
}
}
template<int stencilSize, class index_t>
typename std::enable_if<stencilSize == 5>::type
operator()(index_t smPt, int gRow)
{
constexpr int numDofPerCell = 5;
const auto & graph = m_meshObj.graph();
const auto left0 = graph(smPt, 1);
const auto front0 = graph(smPt, 2);
const auto right0 = graph(smPt, 3);
const auto back0 = graph(smPt, 4);
const auto bot0 = graph(smPt, 5);
const auto top0 = graph(smPt, 6);
const auto left1 = graph(smPt, 7);
const auto front1 = graph(smPt, 8);
const auto right1 = graph(smPt, 9);
const auto back1 = graph(smPt, 10);
const auto bot1 = graph(smPt, 11);
const auto top1 = graph(smPt, 12);
const auto left0i = left0*numDofPerCell;
const auto front0i = front0*numDofPerCell;
const auto right0i = right0*numDofPerCell;
const auto back0i = back0*numDofPerCell;
const auto bot0i = bot0*numDofPerCell;
const auto top0i = top0*numDofPerCell;
this->template operator()<3, index_t>(smPt, gRow);
// degree 1
if (left1 == -1)
{
m_ghostLeft(gRow, 5) = m_state(right0i);
m_ghostLeft(gRow, 6) = -m_state(right0i+1);
m_ghostLeft(gRow, 7) = m_state(right0i+2);
m_ghostLeft(gRow, 8) = m_state(right0i+3);
m_ghostLeft(gRow, 9) = m_state(right0i+4);
}
if (front1 == -1)
{
m_ghostFront(gRow, 5) = m_state(back0i);
m_ghostFront(gRow, 6) = m_state(back0i+1);
m_ghostFront(gRow, 7) = m_state(back0i+2);
m_ghostFront(gRow, 8) = m_state(back0i+3);
m_ghostFront(gRow, 9) = m_state(back0i+4);
}
if (right1 == -1)
{
m_ghostRight(gRow, 5) = m_state(left0i);
m_ghostRight(gRow, 6) = m_state(left0i+1);
m_ghostRight(gRow, 7) = m_state(left0i+2);
m_ghostRight(gRow, 8) = m_state(left0i+3);
m_ghostRight(gRow, 9) = m_state(left0i+4);
}
if (back1 == -1)
{
m_ghostBack(gRow, 5) = m_state(front0i);
m_ghostBack(gRow, 6) = m_state(front0i+1);
m_ghostBack(gRow, 7) = -m_state(front0i+2);
m_ghostBack(gRow, 8) = m_state(front0i+3);
m_ghostBack(gRow, 9) = m_state(front0i+4);
}
if (top1 == -1)
{
m_ghostTop(gRow, 5) = m_state(bot0i);
m_ghostTop(gRow, 6) = m_state(bot0i+1);
m_ghostTop(gRow, 7) = m_state(bot0i+2);
m_ghostTop(gRow, 8) = m_state(bot0i+3);
m_ghostTop(gRow, 9) = m_state(bot0i+4);
}
if (bot1 == -1)
{
m_ghostBottom(gRow, 5) = m_state(top0i);
m_ghostBottom(gRow, 6) = m_state(top0i+1);
m_ghostBottom(gRow, 7) = m_state(top0i+2);
m_ghostBottom(gRow, 8) = -m_state(top0i+3);
m_ghostBottom(gRow, 9) = m_state(top0i+4);
}
}
template<int stencilSize, class index_t>
typename std::enable_if<stencilSize==7>::type
operator()(index_t smPt, int gRow)
{
throw std::runtime_error("For 3d, only 1st order is currently working");
}
private:
const int m_stencilSize;
const state_t & m_state;
const mesh_t & m_meshObj;
ghost_t & m_ghostLeft;
ghost_t & m_ghostRight;
ghost_t & m_ghostBack;
ghost_t & m_ghostFront;
ghost_t & m_ghostBottom;
ghost_t & m_ghostTop;
};
}}}
#endif
| 29.349057 | 76 | 0.618933 | fnrizzi |
c6f8ef8dda6b16dfe1f9e6d9e673130721eda64c | 2,030 | cpp | C++ | chap7/chap7-1.10.cpp | liangzai90/Amazing-Algorithm-With-C | d1e992517eafd9197075d85591ed5270d945b5e3 | [
"Apache-2.0"
] | null | null | null | chap7/chap7-1.10.cpp | liangzai90/Amazing-Algorithm-With-C | d1e992517eafd9197075d85591ed5270d945b5e3 | [
"Apache-2.0"
] | null | null | null | chap7/chap7-1.10.cpp | liangzai90/Amazing-Algorithm-With-C | d1e992517eafd9197075d85591ed5270d945b5e3 | [
"Apache-2.0"
] | null | null | null | /*
数据结构趣题
判断完全二叉树
完全二叉树的定义是这样的:
深度为k的,有n个结点的二叉树,
当且仅当其每一个结点都与深度为k的满二叉树中的编号为1~n的结点相对应,
则它被称为完全二叉树。
所谓满二叉树就是:深度为k且有(2^k -1)个结点的二叉树。
其中,结点的编号约定为:编号从根结点其从上至下,自左向右地顺序编号。
*/
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <vector>
#include <malloc.h>
using namespace std;
typedef struct BiTNode
{
char data;//结点的数据域
struct BiTNode *LChild, *RChild;//指向左孩子和右孩子
}BiTNode, *BiTreePtr;
//创建一棵二叉树...传入指针的指针
void CreateBiTree(BiTreePtr* T, int* level1, int level2)
{
char c;
scanf("%c", &c);
if (c == '#') *T = NULL;
else
{
*T = (BiTNode*)malloc(sizeof(BiTNode));//创建根结点
(*T)->data = c;//向根结点输入数据
if (*level1 < level2)
{
*level1 = level2;
}
//递归创建左子树
CreateBiTree(&((*T)->LChild), &(*level1), level2 + 1);
//递归创建右子树
CreateBiTree(&((*T)->RChild), &(*level1), level2 + 1);
}
}
//判断是否是完全二叉树.1:yes; 0:no
int JusticCompleteBiTree(BiTreePtr T, int level, int n, int *flag)
{
if (!T)
{
return 1;
}
if (n == level)
{
if (T->LChild == NULL && T->RChild != NULL) return 0;
//同层的前面的结点无空指针,出现空指针
if (*flag == 0)
{
if (T->RChild == NULL)
{
*flag = 1;
}
}
else if (*flag == 1)
{
if (T->LChild != NULL || T->RChild!=NULL )
{
return 0;
}
}
}
if (level != n && level != n + 1)
{
if (T->LChild == NULL || T->RChild==NULL)
{
return 0;
}
}
if (!JusticCompleteBiTree(T->LChild, level + 1, n, flag)) return 0;
if (!JusticCompleteBiTree(T->RChild, level + 1, n, flag)) return 0;
return 1;
}
int main()
{
BiTreePtr T;
int level1 = 0;
int flag = 0;
printf("Please input some character to create a binary tree \r\n");
//创建一棵二叉树T,level1返回它的深度
CreateBiTree(&T, &level1, 0);
if (JusticCompleteBiTree(T, 0, level1 - 1, &flag))
{
printf("It is a complete binary tree .\r\n");
}
else
{
printf("It is NOT a complete binary tree .\r\n");
}
cout << endl;
cout << "Hello World C Algorithm." << endl;
system("pause");
return 0;
}
/*
//先根遍历
abc##d##ef###
*/
| 14.710145 | 68 | 0.600985 | liangzai90 |
c6fc72f4091abb28056059ac086597f5fa0875a6 | 40 | hpp | C++ | List_4/L4_Z2/inc/libraries.hpp | Rexluu/PAMSI | 5ac5fa6746e6f572892cfe5c02be321ce33d52fa | [
"Apache-2.0"
] | null | null | null | List_4/L4_Z2/inc/libraries.hpp | Rexluu/PAMSI | 5ac5fa6746e6f572892cfe5c02be321ce33d52fa | [
"Apache-2.0"
] | null | null | null | List_4/L4_Z2/inc/libraries.hpp | Rexluu/PAMSI | 5ac5fa6746e6f572892cfe5c02be321ce33d52fa | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <stdlib.h>
| 13.333333 | 19 | 0.725 | Rexluu |
c6fd0888eca07aac06fcb39ba5df67910fe017e7 | 476 | hpp | C++ | source/toy/canvas/detail/ModelBuffer.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 4 | 2017-07-06T22:18:41.000Z | 2021-05-24T21:28:37.000Z | source/toy/canvas/detail/ModelBuffer.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | null | null | null | source/toy/canvas/detail/ModelBuffer.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 1 | 2020-08-02T13:00:38.000Z | 2020-08-02T13:00:38.000Z |
#pragma once
#include "toy/Standard.hpp"
#include "toy/canvas/VertexBuffer.hpp"
namespace toy{
namespace canvas{
namespace _detail{
class ModelBuffer
{
public:
ModelBuffer(){}
virtual ~ModelBuffer(){}
virtual void setShape(const std::vector<toy::canvas::VertexBuffer> &data)=0;
virtual void setIndices(const std::vector<uint8_t> &data)=0;
virtual void setIndices(const std::initializer_list<uint8_t> &data)=0;
virtual const void* data() const=0;
};
}}}
| 17 | 78 | 0.72479 | ToyAuthor |
c6fecba892c967c970cc9884a7837c37f13c108c | 962 | cpp | C++ | socketclient/src/main.cpp | BooRar/Blackbird | 7c8a1c9de16a5b6bb5b7142aad21026dbb9646c2 | [
"MIT"
] | null | null | null | socketclient/src/main.cpp | BooRar/Blackbird | 7c8a1c9de16a5b6bb5b7142aad21026dbb9646c2 | [
"MIT"
] | null | null | null | socketclient/src/main.cpp | BooRar/Blackbird | 7c8a1c9de16a5b6bb5b7142aad21026dbb9646c2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main()
{
std::cout << "Welcome to the socket client " <<std::endl;
//create socket
int network_socket;
network_socket = socket(AF_INET , SOCK_STREAM , 0 );
//specify an address forthe network_socket
//
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY ; //ip adress of the server
int connection_status = connect(network_socket , (struct sockaddr *) &server_address , sizeof(server_address));
if (connection_status == -1)
{
printf("Connection Failed \n");
}
char server_response[256];
recv(network_socket , &server_response, sizeof(server_response),0);
//print out the data from server
printf("the is data %s\n",server_response);
//
//close
close(network_socket);
return 0;
}
| 20.913043 | 111 | 0.72973 | BooRar |
050303e573a10c80b7ac3336ec47a75c1d896af4 | 19,362 | cpp | C++ | src/IO/mpcdiReaderIntern.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 3 | 2021-03-09T01:57:37.000Z | 2021-05-07T08:40:41.000Z | src/IO/mpcdiReaderIntern.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 1 | 2021-06-01T07:52:36.000Z | 2021-06-03T00:54:49.000Z | src/IO/mpcdiReaderIntern.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 4 | 2020-06-22T14:14:15.000Z | 2021-11-11T14:34:42.000Z | /* =========================================================================
Program: MPCDI Library
Language: C++
Date: $Date: 2012-02-08 11:39:41 -0500 (Wed, 08 Feb 2012) $
Version: $Revision: 18341 $
Copyright (c) 2013 Scalable Display Technologies, Inc.
All Rights Reserved.
The MPCDI Library is distributed under the BSD license.
Please see License.txt distributed with this package.
===================================================================auto== */
#include <time.h>
#include <algorithm>
#include "mpcdiReaderIntern.h"
#include "mpcdiFileUtils.h"
#include "mpcdiUtils.h"
#include "mpcdiPNGReadWrite.h"
#include "mpcdiPfmIO.h"
#include "mpcdiErrorHelper.h"
#include "mpcdiMacros.h"
using namespace mpcdi;
const int ReaderIntern::s_MaxSupportedMajorVersion = 1;
const int ReaderIntern::s_MaxSupportedMinorVersions[] = {0};
/* ====================================================================== */
Reader * Reader::CreateReader()
{
return (Reader*)(new ReaderIntern());
}
/* ====================================================================== */
ReaderIntern::ReaderIntern()
{
m_DoProfileValidation = false;
m_CheckVersionSupported = true;
}
/* ====================================================================== */
std::string ReaderIntern::GetSupportedVersions()
{
std::stringstream ss;
ss << "Supported versions: " << std::endl;
for (int i=1;i<=s_MaxSupportedMajorVersion;i++)
{
ss << " MajorVersion: " << i << " Minor Versions";
int supportedMinorVersions = s_MaxSupportedMinorVersions[i-1];
for (int j=0;j<=supportedMinorVersions;j++)
ss << " ." << j;
ss << std::endl;
}
return ss.str();
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::Read(std::istream &is, Profile * profile)
{
return MPCDI_FAILURE;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::Read(std::string FileName, Profile * profile)
{
if (!exist_file(FileName.c_str()))
return MPCDI_FILE_ALREADY_EXISTS;
m_Zipper = new ZipReader(FileName);
m_Zipper->OpenArchive();
void* buf=NULL;
int size_buf;
MPCDI_Error err;
/* the standard specifies mpcdi.xml however mpacs.xml has been observed by other other implementations */
if MPCDI_FAILED(err = m_Zipper->GetFile("mpcdi.xml", buf, size_buf))
if MPCDI_FAILED(err = m_Zipper->GetFile("mpacs.xml", buf, size_buf))
return err;
// gzip layer needs to be included
m_XmlIO = new XmlIO();
m_XmlIO->GetDoc().Parse((const char*)buf,size_buf);
mpcdi::ProfileVersion version;
GetVersion(m_XmlIO->GetDoc(), version);
err = ReadMPCD(*profile, version);
//clean up
free(buf);
delete m_Zipper;
m_Zipper = NULL;
delete m_XmlIO;
m_XmlIO = NULL;
if (err != MPCDI_SUCCESS)
return err;
if (m_DoProfileValidation)
{
err = profile->ValidateProfile();
if MPCDI_FAILED(err)
return err;
}
return MPCDI_SUCCESS;
}
/*=======================================================================*/
MPCDI_Error ReaderIntern::GetVersion(tinyxml2::XMLDocument &doc, ProfileVersion & version)
{
version = ProfileVersion();
tinyxml2::XMLElement *root = m_XmlIO->GetDoc().RootElement();
if ( std::string(root->Name()).compare(XML_NODES::MPCDI) != 0)
return MPCDI_FAILURE;
std::string versionstring;
MPCDI_FAIL_RET(XmlIO::QueryStringAttribute(XML_ATTR::version, root, versionstring));
return mpcdi::Utils::StringToProfileVersion(versionstring,version);
}
/*=======================================================================*/
MPCDI_Error ReaderIntern::ReadMPCD(Profile & profile, mpcdi::ProfileVersion version)
{
if(m_CheckVersionSupported)
{
if((version.MajorVersion > s_MaxSupportedMajorVersion)) // fail on major version mismatch
{
CREATE_ERROR_MSG(msg, "MPACS Version: " << mpcdi::Utils::ProfileVersionToString(version) << " is not supported by the reader, you can turn CheckVersionSupported off at Reader will attempt to read it, some information might be skipped.")
ReturnCustomErrorMacro(MPCDI_UNSPORTED_PROFILE_VERSION,msg);
}
if (version.MinorVersion > s_MaxSupportedMinorVersions[version.MajorVersion-1]) // drop down to highest minor version suppported
version.MinorVersion = s_MaxSupportedMinorVersions[version.MajorVersion-1];
}
else
{
// drop down to highest supported version
version.MajorVersion = std::min(version.MajorVersion,s_MaxSupportedMajorVersion);
version.MinorVersion = s_MaxSupportedMinorVersions[version.MajorVersion-1];
}
assert(version.MajorVersion > 0);
assert(version.MinorVersion >= 0);
if (version.MajorVersion == 1 && version.MinorVersion == 0)
return ReadMPCDVersion1_0(profile);
// we should never actually make it here
CREATE_ERROR_MSG(msg, "Failed to read profile");
ReturnCustomErrorMacro(MPCDI_FAILURE, msg);
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadMPCDVersion1_0(Profile & profile)
{
tinyxml2::XMLElement *root = m_XmlIO->GetDoc().RootElement();
// Requirement: XML 1.0 and UTF-8. Not bothering to check for it.
MPCDI_FAIL_RET(ReadProfile1_0(root, profile));
MPCDI_FAIL_RET(ReadDisplay1_0(root, *profile.GetDisplay()));
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadProfile1_0(tinyxml2::XMLElement *element, Profile & profile)
{
std::string profileType;
MPCDI_FAIL_RET(XmlIO::QueryStringAttribute(XML_ATTR::profile, element, profileType));
ProfileType currentType = GetProfileType(profileType.c_str());
profile.SetProfileType(currentType);
std::string dateValue;
MPCDI_FAIL_RET(XmlIO::QueryStringAttribute(XML_ATTR::date, element, dateValue));
profile.SetDate(dateValue); // FIXME: do a ISO8601 format check
int levelValue;
MPCDI_FAIL_RET(XmlIO::QueryIntAttribute(XML_ATTR::level, element, levelValue));
profile.SetLevel(levelValue);
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadDisplay1_0(tinyxml2::XMLElement *parent, Display & display)
{
tinyxml2::XMLElement *displayElement = parent->FirstChildElement(XML_NODES::display.c_str());
if (displayElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR,"Failed to find display node");
tinyxml2::XMLElement *bufferElement = displayElement->FirstChildElement();
for(bufferElement; bufferElement; bufferElement = bufferElement->NextSiblingElement())
{
MPCDI_FAIL_RET(ReadBuffer1_0(bufferElement, display));
}
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadBuffer1_0(tinyxml2::XMLElement *bufferElement, Display &display)
{
assert(bufferElement != NULL);
MPCDI_Error err;
// check if indeed is buffer element
if(std::string(bufferElement->Name()) != XML_NODES::buffer)
{
std::string errMsg = std::string("Expected a buffer found: ") + std::string(bufferElement->Name());
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, errMsg);
}
const char *atrValue = bufferElement->Attribute(XML_ATTR::id.c_str());
if (atrValue == NULL)
return MPCDI_FAILED_TO_FIND_XML_ATTRIBUTE;
std::string bufferId = std::string(atrValue);
if MPCDI_FAILED(err = display.NewBuffer(bufferId))
return err;
Buffer *buffer = display.GetBuffer(bufferId);
int value;
buffer->SetXresolution(-1);
if MPCDI_SUCCEEDED(XmlIO::QueryIntAttribute(XML_ATTR::Xresolution, bufferElement, value))
buffer->SetXresolution(value);
buffer->SetYresolution(-1);
if MPCDI_SUCCEEDED(XmlIO::QueryIntAttribute(XML_ATTR::Yresolution, bufferElement, value))
buffer->SetYresolution(value);
tinyxml2::XMLElement *regionElement = bufferElement->FirstChildElement();
for(regionElement; regionElement; regionElement = regionElement->NextSiblingElement())
{
MPCDI_FAIL_RET(ReadRegion(regionElement, *buffer)); // should we delete buffer on fail?
}
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadRegion(tinyxml2::XMLElement *regionElement, Buffer &buffer)
{
assert(regionElement != NULL);
MPCDI_Error err;
// check if indeed is buffer element
if(std::string(regionElement->Name()) != XML_NODES::region)
return MPCDI_XML_FORMAT_ERROR;
const char *atrValue = regionElement->Attribute(XML_ATTR::id.c_str());
if (atrValue == NULL)
ReturnCustomErrorMacro(MPCDI_FAILED_TO_FIND_XML_ATTRIBUTE, "Failed to find buffer id attribute");
std::string regionId = std::string(atrValue);
if(MPCDI_FAILED(err=buffer.NewRegion(regionId)))
return err;
Region *region = buffer.GetRegion(regionId);
MPCDI_FAIL_RET(XmlIO::QueryIntAttribute(XML_ATTR::Xresolution,regionElement,region->GetRefXresolution()));
MPCDI_FAIL_RET(XmlIO::QueryIntAttribute(XML_ATTR::Yresolution,regionElement,region->GetRefYresolution()));
MPCDI_FAIL_RET(XmlIO::QueryFloatAttribute(XML_ATTR::x,regionElement,region->GetRefX()));
MPCDI_FAIL_RET(XmlIO::QueryFloatAttribute(XML_ATTR::y,regionElement,region->GetRefY()));
MPCDI_FAIL_RET(XmlIO::QueryFloatAttribute(XML_ATTR::xsize,regionElement,region->GetRefXsize()));
MPCDI_FAIL_RET(XmlIO::QueryFloatAttribute(XML_ATTR::ysize,regionElement,region->GetRefYsize()));
tinyxml2::XMLElement *element = regionElement->FirstChildElement(XML_NODES::frustum.c_str());
if (element != NULL)
{
region->SetFrustum();
MPCDI_FAIL_RET(ReadFrustum1_0(element, *region->GetFrustum()));
}
element = regionElement->FirstChildElement(XML_NODES::coordinateFrame.c_str());
if (element != NULL)
{
region->SetCoordinateFrame();
MPCDI_FAIL_RET(ReadCoordinateFrame1_0(element, *region->GetCoordinateFrame()));
}
MPCDI_FAIL_RET(ReadFileSet1_0(region->GetId(), *region->GetFileSet()));
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadFrustum1_0(tinyxml2::XMLElement *frustumElement, Frustum & frustum)
{
if (frustumElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, "Frustum node not found");
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::yaw,frustumElement,frustum.GetRefYaw()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::pitch,frustumElement,frustum.GetRefPitch()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::roll,frustumElement,frustum.GetRefRoll()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::rightAngle,frustumElement,frustum.GetRefRightAngle()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::leftAngle,frustumElement,frustum.GetRefLeftAngle()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::upAngle,frustumElement,frustum.GetRefUpAngle()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::downAngle,frustumElement,frustum.GetRefDownAngle()));
//if(LeftAngle > RightAngle)
// return ERROR_SOME_ERROR;
//if(DownAngle < UpAngle)
// return ERROR_SOME_ERROR;
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadCoordinateFrame1_0(tinyxml2::XMLElement *coordinateFrameElement, CoordinateFrame &coordinateFrame)
{
if (coordinateFrameElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, "CoordinateFrame node not found");
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::posx, coordinateFrameElement, coordinateFrame.GetRefPosx()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::posy, coordinateFrameElement, coordinateFrame.GetRefPosy()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::posz, coordinateFrameElement, coordinateFrame.GetRefPosz()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::yawx, coordinateFrameElement, coordinateFrame.GetRefYawx()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::yawy, coordinateFrameElement, coordinateFrame.GetRefYawy()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::yawz, coordinateFrameElement, coordinateFrame.GetRefYawz()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::pitchx, coordinateFrameElement, coordinateFrame.GetRefPitchx()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::pitchy, coordinateFrameElement, coordinateFrame.GetRefPitchy()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::pitchz, coordinateFrameElement, coordinateFrame.GetRefPitchz()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::rollx, coordinateFrameElement, coordinateFrame.GetRefRollx()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::rolly, coordinateFrameElement, coordinateFrame.GetRefRolly()));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::rollz, coordinateFrameElement, coordinateFrame.GetRefRollz()));
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadFileSet1_0(std::string regionid, FileSet & fileSet)
{
tinyxml2::XMLElement *filesElement;
filesElement = m_XmlIO->GetDoc().RootElement()->FirstChildElement(XML_NODES::files.c_str());
if (filesElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, "FilesElement node not found");
tinyxml2::XMLElement *fileSetElement = filesElement->FirstChildElement();
for(fileSetElement; fileSetElement; fileSetElement = fileSetElement->NextSiblingElement())
{
std::string nodeRegionId;
MPCDI_FAIL_RET(XmlIO::QueryStringAttribute(XML_ATTR::region, fileSetElement, nodeRegionId));
if (nodeRegionId==regionid)
{
MPCDI_FAIL_RET(ReadGeometryWarpFile1_0(fileSetElement->FirstChildElement(XML_NODES::geometryWarpFile.c_str()), fileSet));
MPCDI_FAIL_RET(ReadAlphaMap1_0(fileSetElement->FirstChildElement(XML_NODES::alphaMap.c_str()), fileSet));
//// Only fail on this guys if there is an error Reading in the structure.
//// if the tags are not there, don't worry about it.
//// CAREFUL! Only allowed to miss the high level tag, nothing more.
tinyxml2::XMLElement *element = fileSetElement->FirstChildElement(XML_NODES::betaMap.c_str());
if (element!=NULL)
MPCDI_FAIL_RET(ReadBetaMap1_0(element, fileSet));
element = fileSetElement->FirstChildElement(XML_NODES::distortionMap.c_str());
if (element != NULL)
MPCDI_FAIL_RET(ReadDistortionMapFile1_0(element, fileSet));
}
}
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadAlphaMap1_0(tinyxml2::XMLElement *alphaMapElement, FileSet & fileSet)
{
if (alphaMapElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, "AlphaMapElement node not found");
std::string alphaMapPath;
int componentDepth,bitDepth;
double gammaEmbedded;
MPCDI_FAIL_RET(XmlIO::QueryStringText(XML_NODES::path, alphaMapElement, alphaMapPath));
MPCDI_FAIL_RET(XmlIO::QueryIntText(XML_NODES::componentDepth, alphaMapElement, componentDepth));
MPCDI_FAIL_RET(XmlIO::QueryIntText(XML_NODES::bitDepth, alphaMapElement, bitDepth));
MPCDI_FAIL_RET(XmlIO::QueryDoubleText(XML_NODES::gammaEmbedded, alphaMapElement, gammaEmbedded));
DataMap *dataMap = NULL;
MPCDI_FAIL_RET(ReadDataMap(alphaMapPath, dataMap));
fileSet.SetAlphaMap(dataMap->GetSizeX(),dataMap->GetSizeY(),dataMap->GetComponentDepth());
fileSet.GetAlphaMap()->CopyData(*dataMap);
//todo copy data!!
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadBetaMap1_0(tinyxml2::XMLElement *betaMapElement, FileSet & fileSet)
{
if (betaMapElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, "BetaMapElement node not found");
std::string betaMapPath;
int bitDepth,componentDepth;
MPCDI_FAIL_RET(XmlIO::QueryIntText(XML_NODES::bitDepth, betaMapElement, bitDepth));
MPCDI_FAIL_RET(XmlIO::QueryIntText(XML_NODES::componentDepth, betaMapElement, componentDepth));
MPCDI_FAIL_RET(XmlIO::QueryStringText(XML_NODES::path, betaMapElement, betaMapPath));
DataMap *dataMap = NULL;
MPCDI_FAIL_RET(ReadDataMap(betaMapPath, dataMap));
fileSet.SetBetaMap(dataMap->GetSizeX(),dataMap->GetSizeY(),dataMap->GetComponentDepth());
fileSet.GetBetaMap()->CopyData(*dataMap);
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadGeometryWarpFile1_0(tinyxml2::XMLElement *dmfElement, FileSet & fileSet)
{
if (dmfElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, "ReadGeometryWarpFile node not found");
std::string path;
MPCDI_FAIL_RET(XmlIO::QueryStringText(XML_NODES::path, dmfElement, path));
PFM *pfm = NULL;
MPCDI_FAIL_RET(ReadPFM(path, pfm));
MPCDI_Error err;
if (MPCDI_FAILED(err = fileSet.SetGeometryWarpFile(pfm->GetSizeX(),pfm->GetSizeY())))
return err;
GeometryWarpFile * warpFile = fileSet.GetGeometryWarpFile();
warpFile->SetPath(path);
warpFile->CopyData(*pfm);
std::string value;
MPCDI_FAIL_RET(XmlIO::QueryStringText(XML_NODES::geometricUnit, dmfElement, value));
warpFile->SetGeometricUnit(GetGeometricUnit(value));
MPCDI_FAIL_RET(XmlIO::QueryStringText(XML_NODES::interpolation, dmfElement, value));
warpFile->SetInterpolation(GetInterpolation(value));
MPCDI_FAIL_RET(XmlIO::QueryStringText(XML_NODES::originof3DData, dmfElement, value));
warpFile->SetOriginOf3DData(GetOriginOf3DData(value));
//if (sl && origin == IdealeyePoint) return ERROR_OF_SOME_SORT;
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadDistortionMapFile1_0(tinyxml2::XMLElement *dmfElement, FileSet & fileSet)
{
if (dmfElement == NULL)
ReturnCustomErrorMacro(MPCDI_XML_FORMAT_ERROR, "DistortionMap node not found");
std::string path;
MPCDI_FAIL_RET(XmlIO::QueryStringText(XML_NODES::path, dmfElement, path));
PFM *pfm = NULL;
MPCDI_FAIL_RET(ReadPFM(path, pfm));
MPCDI_Error err;
if (MPCDI_FAILED(err = fileSet.SetDistortionMap(pfm->GetSizeX(),pfm->GetSizeY())))
return err;
DistortionMap * distortionMap = fileSet.GetDistortionMap();
distortionMap->SetPath(path);
distortionMap->CopyData(*pfm);
return MPCDI_SUCCESS;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadDataMap(std::string FileName, DataMap *&dataMap)
{
void* buf=NULL;
int size_buf;
MPCDI_Error err = m_Zipper->GetFile(FileName.c_str(), buf, size_buf);
if MPCDI_FAILED(err)
return err;
std::string buffer;
std::stringstream membuf;
membuf.write((const char*)buf,size_buf);
free(buf);
err = PNGReadWrite::Read(membuf,dataMap);
return err;
}
/* ====================================================================== */
MPCDI_Error ReaderIntern::ReadPFM(std::string FileName, PFM *&pfm)
{
void* buf=NULL;
int size_buf;
MPCDI_Error err = m_Zipper->GetFile(FileName.c_str(), buf, size_buf);
if MPCDI_FAILED(err)
return err;
std::string buffer;
std::stringstream membuf;
membuf.write((const char*)buf,size_buf);
free(buf);
err = PfmIO::Read(membuf,pfm);
return err;
}
| 36.532075 | 242 | 0.6881 | scaredyfish |
050871d6fbf45194d269bbe517c088e47961f703 | 66 | hpp | C++ | Framework/Interface/Interface.hpp | kiorisyshen/GameEngineFromScratch | c2760084c8f1dd853f489a681ab3280647a8ece2 | [
"MIT"
] | 1 | 2020-05-25T11:34:54.000Z | 2020-05-25T11:34:54.000Z | Framework/Interface/Interface.hpp | freudshow/GameEngineFromScratch | 8a5ddaff58ff26123c06a5c502f5d78891a6f05e | [
"MIT"
] | null | null | null | Framework/Interface/Interface.hpp | freudshow/GameEngineFromScratch | 8a5ddaff58ff26123c06a5c502f5d78891a6f05e | [
"MIT"
] | 1 | 2020-03-06T15:27:24.000Z | 2020-03-06T15:27:24.000Z | #pragma once
#define Interface class
#define implements public
| 9.428571 | 25 | 0.787879 | kiorisyshen |
050c85ae05825c586a9d020ccd7cd7b7d7591156 | 1,917 | cpp | C++ | Applications/DataExplorer/Base/TreeModelIterator.cpp | HaibingShao/ogs6_ufz | d4acfe7132eaa2010157122da67c7a4579b2ebae | [
"BSD-4-Clause"
] | null | null | null | Applications/DataExplorer/Base/TreeModelIterator.cpp | HaibingShao/ogs6_ufz | d4acfe7132eaa2010157122da67c7a4579b2ebae | [
"BSD-4-Clause"
] | null | null | null | Applications/DataExplorer/Base/TreeModelIterator.cpp | HaibingShao/ogs6_ufz | d4acfe7132eaa2010157122da67c7a4579b2ebae | [
"BSD-4-Clause"
] | null | null | null | /**
* \file
* \author Lars Bilke
* \date 2010-06-23
* \brief Implementation of the TreeModelIterator class.
*
* \copyright
* Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*/
// ** INCLUDES **
#include "TreeModelIterator.h"
#include "TreeItem.h"
#include "TreeModel.h"
TreeModelIterator::TreeModelIterator( TreeModel* model )
: _current(NULL), _model(model)
{
if (_model->rootItem()->childCount() > 0)
{
_current = _model->rootItem();
next(_current);
//_parentIndex.push(0);
//_currentIndex = 0;
}
}
TreeItem* TreeModelIterator::operator*() const
{
return _current;
}
TreeModelIterator& TreeModelIterator::operator++()
{
if (_current)
_current = next(_current);
return *this;
}
TreeItem* TreeModelIterator::next( const TreeItem* current )
{
if (!current)
return NULL;
TreeItem* next = NULL;
if (current->childCount())
{
// walk the child
_parentIndex.push(_currentIndex);
_currentIndex = 0;
next = current->child(0);
}
else
{
// walk the sibling
TreeItem* parent = current->parentItem();
next = parent ? parent->child(_currentIndex + 1)
: _model->rootItem()->child(_currentIndex + 1);
while (!next && parent)
{
// if we had no sibling walk up the parent
// and try the sibling of that
parent = parent->parentItem();
_currentIndex = _parentIndex.pop();
next = parent ? parent->child(_currentIndex + 1)
: _model->rootItem()->child(_currentIndex + 1);
}
if (next)
++(_currentIndex);
}
return next;
}
| 24.265823 | 76 | 0.580595 | HaibingShao |
050cd418e1d84bcd60ac736baa2ea940e96670cb | 906 | cpp | C++ | Blue-Flame-Engine/Editor/EditorScene.cpp | 21423236/Blue-Flame-Engine | cf26fbdb94d1338f04e57ba88f0bbfc8b77c969b | [
"MIT"
] | 1 | 2021-07-02T12:40:44.000Z | 2021-07-02T12:40:44.000Z | Blue-Flame-Engine/Editor/EditorScene.cpp | 21423236/Blue-Flame-Engine | cf26fbdb94d1338f04e57ba88f0bbfc8b77c969b | [
"MIT"
] | null | null | null | Blue-Flame-Engine/Editor/EditorScene.cpp | 21423236/Blue-Flame-Engine | cf26fbdb94d1338f04e57ba88f0bbfc8b77c969b | [
"MIT"
] | null | null | null | #include "EditorScene.h"
namespace Editor
{
using namespace BF;
using namespace BF::Math;
using namespace BF::Graphics;
using namespace BF::Graphics::API;
using namespace BF::Graphics::Renderers;
EditorScene::EditorScene() :
tilesheet(*this, scenePanel.GetPaintTile()), scenePanel(*this, tilesheet)
{
}
EditorScene::~EditorScene()
{
}
void EditorScene::Initialize()
{
Scene::Initialize();
camera.Initialize(Matrix4::Orthographic(0.0f, Engine::GetWindow().GetClientWidth(), 0.0f, Engine::GetWindow().GetClientHeight(), -1.0f, 1.0f));
}
void EditorScene::Load()
{
Scene::Load();
}
void EditorScene::FixedUpdate()
{
}
void EditorScene::Update()
{
Scene::Update();
camera.Update();
}
void EditorScene::Render()
{
Engine::GetContext().Clear(Color(0.5f, 0.0f, 0.1f, 1.0f));
Scene::Render();
scenePanel.RenderTileMap();
Engine::GetContext().SwapBuffers();
}
} | 18.875 | 145 | 0.684327 | 21423236 |
050d8d1705636ae66e565f1d0ebe743197fce798 | 5,160 | cpp | C++ | Plugins/FileDownloader/Source/FileDownloader/Private/FileDownloadManager.cpp | VirtualLilies/FileDownloader | f5fbbb53c04061e2b62c6350cd383716a79ed8cf | [
"CC0-1.0"
] | null | null | null | Plugins/FileDownloader/Source/FileDownloader/Private/FileDownloadManager.cpp | VirtualLilies/FileDownloader | f5fbbb53c04061e2b62c6350cd383716a79ed8cf | [
"CC0-1.0"
] | null | null | null | Plugins/FileDownloader/Source/FileDownloader/Private/FileDownloadManager.cpp | VirtualLilies/FileDownloader | f5fbbb53c04061e2b62c6350cd383716a79ed8cf | [
"CC0-1.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "FileDownloadManager.h"
#include "DownloadTask.h"
#include "Misc/Paths.h"
void UFileDownloadManager::Tick(float DeltaTime)
{
if (bStopAll)
{
return;
}
static float TimeCount = 0.f;
TimeCount += DeltaTime;
if (TimeCount >= TickInterval)
{
TimeCount = 0.f;
//broadcast event
//find task to do
if (CurrentDoingWorks < MaxParallelTask && TaskList.Num())
{
int32 Idx = FindTaskToDo();
if (Idx > INDEX_NONE)
{
TaskList[Idx]->Start();
++CurrentDoingWorks;
}
}
}
}
TStatId UFileDownloadManager::GetStatId() const
{
return TStatId();
}
void UFileDownloadManager::BeginDestroy()
{
StopAll();
Super::BeginDestroy();
}
void UFileDownloadManager::StartAll()
{
bStopAll = false;
for (int32 i =0; i < TaskList.Num(); ++i)
{
TaskList[i]->SetNeedStop(false);
}
}
void UFileDownloadManager::StartTask(const FGuid& InGuid)
{
int32 ret = FindTaskByGuid(InGuid);
if (ret > INDEX_NONE)
{
TaskList[ret]->SetNeedStop(false);
bStopAll = false;
}
}
void UFileDownloadManager::StopAll()
{
for (int32 i = 0; i < TaskList.Num(); ++i)
{
TaskList[i]->Stop();
}
bStopAll = true;
CurrentDoingWorks = 0;
}
void UFileDownloadManager::StopTask(const FGuid& InGuid)
{
int32 ret = FindTaskByGuid(InGuid);
if (ret >= 0)
{
if (TaskList[ret]->GetState() == ETaskState::DOWNLOADING)
{
TaskList[ret]->Stop();
--CurrentDoingWorks;
}
}
}
int32 UFileDownloadManager::GetTotalPercent() const
{
int64 CurrentSize = 0;
int64 TotalSize = 0;
for (int32 i = 0; i < TaskList.Num(); ++i)
{
CurrentSize += TaskList[i]->GetCurrentSize();
TotalSize += TaskList[i]->GetTotalSize();
}
if (TotalSize < 1)
{
return 0;
}
return (float)(CurrentSize) / TotalSize * 100.f;
}
void UFileDownloadManager::GetByteSize(int64& OutCurrentSize, int64& OutTotalSize) const
{
OutCurrentSize = 0;
OutTotalSize = 0;
for (int32 i = 0; i < TaskList.Num(); ++i)
{
OutCurrentSize += TaskList[i]->GetCurrentSize();
OutTotalSize += TaskList[i]->GetTotalSize();
}
}
void UFileDownloadManager::Clear()
{
StopAll();
TaskList.Reset();
ErrorCount = 0;
}
bool UFileDownloadManager::SaveTaskToJsonFile(const FGuid& InGuid, const FString& InFileName /*= TEXT("")*/)
{
int32 ret = FindTaskByGuid(InGuid);
if (ret < 0)
{
return false;
}
return TaskList[ret]->SaveTaskToJsonFile(InFileName);
}
TArray<FTaskInformation> UFileDownloadManager::GetAllTaskInformation() const
{
TArray<FTaskInformation> Ret;
for (int32 i = 0; i < TaskList.Num(); ++i)
{
Ret.Add(TaskList[i]->GetTaskInformation());
}
return Ret;
}
FGuid UFileDownloadManager::AddTaskByUrl(const FString& InUrl, const FString& InDirectory, const FString& InFileName)
{
FString TmpDir = InDirectory;
if (TmpDir.IsEmpty())
{
//https://www.google.com/
static int32 URLTag = 8;
int32 StartSlash = InUrl.Find(FString("/"), ESearchCase::IgnoreCase, ESearchDir::FromStart, URLTag);
int32 LastSlash = InUrl.Find(FString("/"), ESearchCase::IgnoreCase, ESearchDir::FromEnd);
FString UrlDirectory = InUrl.Mid(StartSlash, LastSlash - StartSlash);
TmpDir = FPaths::ProjectDir() + UrlDirectory;
}
TSharedPtr<DownloadTask>Task = MakeShareable(new DownloadTask(InUrl, TmpDir, InFileName));
if (Task.IsValid() == false)
{
FGuid ret;
ret.Invalidate();
return ret;
}
for (int32 i = 0; i < TaskList.Num(); ++i)
{
if (TaskList[i]->GetSourceUrl() == Task->GetSourceUrl())
{
//任务存在于任务列表
return TaskList[i]->GetGuid();
}
}
Task->ProcessTaskEvent = [this](ETaskEvent InEvent, const FTaskInformation& InInfo, int32 InHpptCode)
{
if (this != nullptr)
{
this->OnTaskEvent(InEvent, InInfo, InHpptCode);
}
};
TaskList.Add(Task);
return Task->GetGuid();
}
bool UFileDownloadManager::SetTotalSizeByIndex(int32 InIndex, int32 InTotalSize)
{
if (InIndex < TaskList.Num() && InTotalSize > 1 && TaskList[InIndex]->GetTotalSize() < 1)
{
TaskList[InIndex]->SetTotalSize(InTotalSize);
return true;
}
return false;
}
bool UFileDownloadManager::SetTotalSizeByGuid(FGuid InGid, int32 InTotalSize)
{
int32 Idx = FindTaskByGuid(InGid);
return SetTotalSizeByIndex(Idx, InTotalSize);
}
void UFileDownloadManager::OnTaskEvent(ETaskEvent InEvent, const FTaskInformation& InInfo, int32 InHttpCode)
{
OnDlManagerEvent.Broadcast(InEvent, InInfo, InHttpCode);
if (InEvent >= ETaskEvent::DOWNLOAD_COMPLETED)
{
if (CurrentDoingWorks > 0)
{
--CurrentDoingWorks;
}
if (InEvent == ETaskEvent::ERROR_OCCUR)
{
++ErrorCount;
}
if (CurrentDoingWorks < 1)
{
OnAllTaskCompleted.Broadcast(ErrorCount);
ErrorCount = 0;
}
}
return ;
}
int32 UFileDownloadManager::FindTaskToDo() const
{
int32 ret = INDEX_NONE;
for (int32 i = 0; i < TaskList.Num(); ++i)
{
if (TaskList[i]->GetState() == ETaskState::WAIT && TaskList[i]->GetNeedStop() == false)
{
ret = i;
}
}
return ret;
}
int32 UFileDownloadManager::FindTaskByGuid(const FGuid& InGuid) const
{
int32 ret = INDEX_NONE;
for (int32 i = 0; i < TaskList.Num(); ++i)
{
if (TaskList[i]->GetGuid() == InGuid)
{
ret = i;
}
}
return ret;
}
| 19.694656 | 117 | 0.68469 | VirtualLilies |
050fe9e408e3d04ffed05fbfd05435743540fce8 | 14,342 | cc | C++ | src/main.cc | conclusiveeng/devclient | 98e3ab39acaab156ab52705be8b4d9213efe9633 | [
"BSD-2-Clause"
] | null | null | null | src/main.cc | conclusiveeng/devclient | 98e3ab39acaab156ab52705be8b4d9213efe9633 | [
"BSD-2-Clause"
] | null | null | null | src/main.cc | conclusiveeng/devclient | 98e3ab39acaab156ab52705be8b4d9213efe9633 | [
"BSD-2-Clause"
] | 1 | 2020-11-25T11:24:42.000Z | 2020-11-25T11:24:42.000Z | /*-
* SPDX-License-Identifier: BSD-2-Clause-FreeBSD
*
* Copyright (c) 2019 Conclusive Engineering
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include "profile.hh"
#include <iostream>
#include <memory>
#include <string>
#include <sysexits.h>
#include <getopt.h>
#include <fmt/format.h>
#include <gtkmm/application.h>
#include <fstream>
#include <stdlib.h>
#include <log.hh>
#include <device.hh>
#include <uart.hh>
#include <i2c.hh>
#include <eeprom/24c.hh>
#include <gpio.hh>
#include <utils.hh>
#include <mainwindow.hh>
#include <application.hh>
#include <nogui.hh>
#include <onie_tlv.hh>
using namespace std;
static const struct option long_options[] = {
{ "baudrate", required_argument, nullptr, 'b' },
{ "compile-dts", required_argument, nullptr, 'c' },
{ "device", optional_argument, nullptr, 'd' },
{ "gpio", optional_argument, nullptr, 'g' },
{ "help", no_argument, nullptr, 'h' },
{ "jtag", required_argument, nullptr, 'j' },
{ "list", no_argument, nullptr, 'l' },
{ "passthrough", no_argument, nullptr, 'p' },
{ "read-eeprom", no_argument, nullptr, 'r' },
{ "script", required_argument, nullptr, 's' },
{ "decompile-dts", required_argument, nullptr, 't' },
{ "uart", required_argument, nullptr, 'u' },
{ "write-eeprom", no_argument, nullptr, 'w' },
{ "config", required_argument, nullptr, 'x' },
{ nullptr, 0, nullptr, 0}
};
static void
usage(const std::string &argv0)
{
fmt::print("usage: {:s}\n", argv0);
fmt::print("-b: baud rate for UART port, allowed values: 9600, 19200, 38400, 57600, 115200\n");
fmt::print(" example: -b 115200\n");
fmt::print("-c: compile dts from file and write it to eeprom\n");
fmt::print(" example: -c board.dts\n");
fmt::print("-d: serial string of the selected device\n");
fmt::print(" example: -d 006/2019\n");
fmt::print("-g: set value for gpio pins\n");
fmt::print("-h: this help message\n");
fmt::print("-j: IP address and two TCP port numbers for listening for JTAG communication\n");
fmt::print(" cannot be used together with -p option\n");
fmt::print(" parameter format: <IP_address>:<gdb_port>:<telnet_port>\n");
fmt::print(" example: -j 0.0.0.0:3333:4444\n");
fmt::print("-l: list connected devices\n");
fmt::print("-m: read .yaml file with ONIE TLV config and write to eeprom\n");
fmt::print("-n: read eeprom by address and print ONIE TLV values to stdout\n");
fmt::print(" example: -n 0x50 \n");
fmt::print("-p: enable JTAG pass-through mode, cannot be used together with -j option\n");
fmt::print("-r: read raw eeprom contents (binary data) and save it to file\n");
fmt::print(" example: -r eeprom.img\n");
fmt::print("-s: absolute path to script\n");
fmt::print("-t: download contents of eeprom, decompile it and write it to dts file\n");
fmt::print(" example: -t board.dts\n");
fmt::print("-u: IP address and TCP port number for listening for serial/uart communication\n");
fmt::print(" example: -u 0.0.0.0:2222\n");
fmt::print("-w: write raw contents of file (binary data) to eeprom\n");
fmt::print(" example: -w eeprom.img\n");
fmt::print("-x: configuration with serial port and JTAG settings\n");
fmt::print(" example: -x profile/profile-kstr-sama5d27.yml\n");
fmt::print("\nInvocation examples:\n");
fmt::print("{:s} -d 006/2019 -u 0.0.0.0:2222 -b 115200 -j 0.0.0.0:3333:4444 -s /tmp/script\n", argv0);
fmt::print("{:s} -d 006/2019 -u 0.0.0.0:2222 -b 115200 -p\n", argv0);
fmt::print("{:s} -d 006/2019 -w eeprom.img\n", argv0);
fmt::print("{:s} -x profile/profile-kstr-sama5d27.yml\n", argv0);
}
int
uart_maintenance(std::string serial, std::string uart_listen_addr, uint32_t baudrate_value, std::shared_ptr<SerialCmdLine> &serial_cmd)
{
Device dev;
if (!uart_listen_addr.empty()) {
uint16_t port;
std::string addr;
if ((baudrate_value != 9600) &&
(baudrate_value != 19200) &&
(baudrate_value != 38400) &&
(baudrate_value != 57600) &&
(baudrate_value != 115200)) {
fmt::print("Improper baud rate value: {:d}\n", baudrate_value);
exit(0);
}
addr = uart_listen_addr.substr(0, uart_listen_addr.find(':'));
port = std::stoi(uart_listen_addr.substr(
uart_listen_addr.find(':') + 1,
uart_listen_addr.size()), 0, 10);
auto saddr = Gio::InetSocketAddress::create(
Gio::InetAddress::create(addr),
port);
fmt::print("To use serial port connect using telnet to host {}\n", uart_listen_addr);
dev = *DeviceEnumerator::find_by_serial(serial);
serial_cmd = std::shared_ptr<SerialCmdLine>(new SerialCmdLine(
dev,
saddr,
baudrate_value));
serial_cmd->start();
}
return 0;
}
int jtag_maintenance(std::string serial, std::string jtag, std::string script, std::shared_ptr<JtagCmdLine> &jtag_cmd)
{
Device dev;
if (!jtag.empty()) {
uint16_t port_gdb, port_ocd;
std::string addr;
Glib::RefPtr<Gio::InetAddress> saddr;
addr = jtag.substr(0, jtag.find(':'));
port_gdb = std::stoi(jtag.substr(
jtag.find(':') + 1,
jtag.size()), 0, 10);
port_ocd = std::stoi(jtag.substr(
jtag.rfind(':') + 1,
jtag.size()), 0, 10);
dev = *DeviceEnumerator::find_by_serial(serial);
saddr = Gio::InetAddress::create(addr);
fmt::print("To use JTAG connect to GDB at port {} and OpenOCD at port {}\n", port_gdb, port_ocd);
jtag_cmd = std::unique_ptr<JtagCmdLine>(new JtagCmdLine(
dev,
saddr,
port_gdb,
port_ocd,
script));
jtag_cmd->m_server->start();
}
return 0;
}
int
parse_config_file(std::string file_read, std::shared_ptr<SerialCmdLine> &serial_cmd, std::shared_ptr<JtagCmdLine> &jtag_cmd)
{
ProfileConfig pc = ProfileConfig(file_read);
try {
std::string listen_addr = fmt::format("{}:{}", pc.get_uart_listen_address(), pc.get_uart_port());
uart_maintenance(pc.get_devcable_serial(), listen_addr, pc.get_uart_baudrate(), serial_cmd);
} catch (const ProfileConfigException& error) {
Logger::error("Serial port configuration is invalid. {}", error.get_info());
exit(-1);
}
try {
if (pc.get_jtag_passtrough() == true) {
fmt::print("Passtrough mode is enabled in config file. Please use external JTAG.\n");
Device dev = *DeviceEnumerator::find_by_serial(pc.get_devcable_serial());
jtag_cmd->bypass(dev);
} else {
std::string jtag_connector = fmt::format("{}:{}:{}", pc.get_jtag_listen_address(),
pc.get_jtag_gdb_port(), pc.get_jtag_telnet_port());
jtag_maintenance(pc.get_devcable_serial(), jtag_connector, pc.get_jtag_script_file(), jtag_cmd);
}
} catch (const ProfileConfigException& error) {
Logger::error("Serial port configuration is invalid. {}", error.get_info());
exit(-1);
}
return 0;
}
int
parse_cmdline(int argc, char *const argv[], std::shared_ptr<SerialCmdLine> &serial_cmd, std::shared_ptr<JtagCmdLine> &jtag_cmd)
{
Glib::RefPtr<Gtk::Application> app;
Device dev;
std::unique_ptr<Uart> uart;
std::string uart_listen_addr;
std::string serial;
std::string jtag;
std::string script;
std::string file_read;
std::string file_write;
std::string eeprom_addr;
uint8_t gpio_value;
uint32_t baudrate_value;
std::ofstream f_out;
std::ifstream f_in;
bool cmdline = false;
bool list = false;
bool eeprom_read = false;
bool eeprom_write = false;
bool eeprom_compile = false;
bool eeprom_decompile = false;
bool gpio = false;
bool pass_through = false;
bool config = false;
bool tlv_write = false;
bool tlv_read = false;
int ch;
for (;;) {
ch = getopt_long(argc, argv, "b:c:d:g:hj:lm:n:pr:s:t:u:w:x:", long_options, nullptr);
if (ch == -1)
break;
switch (ch) {
case 'b':
baudrate_value = std::stoi(optarg, 0, 10);
cmdline = true;
break;
case 'c':
eeprom_compile = true;
file_read = optarg;
break;
case 'd':
serial = optarg;
cmdline = true;
break;
case 'g':
gpio = true;
gpio_value = std::stoi(optarg, 0, 16);
break;
case 'h':
usage(argv[0]);
exit(0);
case 'j':
jtag = optarg;
cmdline = true;
break;
case 'l':
list = true;
break;
case 'm':
tlv_write = true;
file_read = optarg;
break;
case 'n':
tlv_read = true;
eeprom_addr = optarg;
break;
case 'p':
pass_through = true;
cmdline = true;
break;
case 'r':
eeprom_read = true;
file_write = optarg;
break;
case 's':
script = optarg;
cmdline = true;
break;
case 't':
eeprom_decompile = true;
file_write = optarg;
break;
case 'u':
uart_listen_addr = optarg;
cmdline = true;
break;
case 'w':
eeprom_write = true;
file_read = optarg;
break;
case 'x':
config = true;
file_read = optarg;
cmdline = true;
break;
default:
usage(argv[0]);
exit(EX_USAGE);
}
}
Gio::init();
if (config) {
parse_config_file(file_read, serial_cmd, jtag_cmd);
}
if (!jtag.empty() && pass_through) {
Logger::error("JTAG options -j and -p cannot be used together");
exit(0);
}
if (list) {
fmt::print("Available devices:\n");
for (const auto &i: DeviceEnumerator::enumerate()) {
fmt::print("{:#04x}:{:#04x} - {} ({})\n", i.vid, i.pid,
i.description, i.serial);
}
exit(0);
}
if (gpio) {
dev = *DeviceEnumerator::find_by_serial(serial);
Gpio gpio(dev);
gpio.set(gpio_value);
exit(0);
}
if (eeprom_read) {
dev = *DeviceEnumerator::find_by_serial(serial);
I2C i2c(dev, 300000);
Eeprom24c eeprom(i2c);
std::vector<uint8_t> data;
char rdata[4096];
eeprom.read(0, 4096, data);
f_out.open(file_write, ios::out | ios::binary | ios::trunc);
std::copy(data.begin(), data.end(), rdata);
f_out.write(rdata, 4096);
f_out.close();
exit(0);
}
if (eeprom_write) {
dev = *DeviceEnumerator::find_by_serial(serial);
I2C i2c(dev, 300000);
Eeprom24c eeprom(i2c);
std::vector<uint8_t> data;
char rdata[4096];
f_in.open(file_read, ios::in | ios::binary);
f_in.read(rdata, 4096);
f_in.close();
for (unsigned int x = 0; x < sizeof(rdata); x++)
data.push_back(rdata[x]);
eeprom.write(0, data);
exit(0);
}
if (eeprom_decompile) {
dev = *DeviceEnumerator::find_by_serial(serial);
I2C i2c(dev, 300000);
Eeprom24c eeprom(i2c);
std::vector<uint8_t> data;
char rdata[4096], fname[256], cmd[256 + 128 + 32];
eeprom.read(0, 4096, data);
// save contents of eeprom to temporary file
std::sprintf(fname, "%s_tmp", file_write.c_str());
f_out.open(fname, ios::out | ios::binary | ios::trunc);
std::copy(data.begin(), data.end(), rdata);
f_out.write(rdata, 4096);
f_out.close();
// dtb decompilation
std::sprintf(cmd, "dtc -I dtb -O dts %s -o %s", fname, file_write.c_str());
std::system(cmd);
std::remove(fname);
exit(0);
}
if (eeprom_compile) {
dev = *DeviceEnumerator::find_by_serial(serial);
I2C i2c(dev, 300000);
Eeprom24c eeprom(i2c);
std::vector<uint8_t> data;
char rdata[4096], fname[256], cmd[256 + 128 + 32];
std::sprintf(fname, "%s_tmp", file_read.c_str());
// dts compilation
std::sprintf(cmd, "dtc -I dts -O dtb %s -o %s", file_read.c_str(), fname);
std::system(cmd);
f_in.open(fname, ios::in | ios::binary);
f_in.read(rdata, 4096);
f_in.close();
for (unsigned int x = 0; x < sizeof(rdata); x++)
data.push_back(rdata[x]);
std::remove(fname);
eeprom.write(0, data);
exit(0);
}
if (tlv_write) {
dev = *DeviceEnumerator::find_by_serial(serial);
I2C i2c(dev, 300000);
Eeprom24c eeprom(i2c);
std::vector<uint8_t> data;
OnieTLV otlv;
uint8_t eeprom_file[TLV_EEPROM_MAX_SIZE];
try {
otlv.load_from_yaml(file_read);
} catch (OnieTLVException& onieTLVException) {
Logger::error("There was a problem with loading EEPROM config file.\n{}", onieTLVException.get_info());
exit(-1);
}
otlv.generate_eeprom_file(eeprom_file);
data = std::vector<uint8_t>(eeprom_file, eeprom_file+otlv.get_usage());
eeprom.set_address(otlv.get_eeprom_address_from_yaml());
eeprom.write(0, data);
exit(0);
}
if (tlv_read) {
dev = *DeviceEnumerator::find_by_serial(serial);
I2C i2c(dev, 300000);
Eeprom24c eeprom(i2c);
std::vector<uint8_t> data;
OnieTLV otlv;
eeprom.set_address(eeprom_addr);
try {
eeprom.read(0, TLV_EEPROM_MAX_SIZE, data);
otlv.load_from_eeprom(data.data());
} catch (const std::runtime_error &err) {
Logger::error("There was an error while reading EEPROM.");
exit(-1);
}
for (const auto tlv_id: otlv.ALL_TLV_ID) {
std::cout << fmt::format("Field id: [0x{:x}] Value: [{}]\n", tlv_id, otlv.get_tlv_record(tlv_id).value_or(""));
}
exit(0);
}
if (!uart_listen_addr.empty())
uart_maintenance(serial, uart_listen_addr, baudrate_value, serial_cmd);
if (!jtag.empty())
jtag_maintenance(serial, jtag, script, jtag_cmd);
if (pass_through) {
jtag_cmd = std::unique_ptr<JtagCmdLine>(new JtagCmdLine(dev));
jtag_cmd->bypass(dev);
}
return cmdline;
}
int
main(int argc, char *const argv[])
{
Glib::RefPtr<Gtk::Application> app;
std::shared_ptr<SerialCmdLine> serial_cmd;
bool cmdline = false;
std::shared_ptr<JtagCmdLine> jtag_cmd;
Gio::init();
Glib::init();
cmdline = parse_cmdline(argc, argv, serial_cmd, jtag_cmd);
if (cmdline == true) {
serial_cmd->main_loop->run();
} else {
return Devclient::Application::instance()->run();
}
}
| 28.569721 | 135 | 0.672919 | conclusiveeng |
05193de83469452121fd7c0ce37025c35ad6f5da | 422 | hpp | C++ | contracts/includes/vapaee/token/tables/earnings.hpp | vapaee/vapaee.io-source | b2b0c07850a817629055a848b9239a59dc10b545 | [
"MIT"
] | 7 | 2019-06-09T03:52:14.000Z | 2020-03-01T13:27:24.000Z | contracts/includes/vapaee/token/tables/earnings.hpp | vapaee/vapaee.io-source | b2b0c07850a817629055a848b9239a59dc10b545 | [
"MIT"
] | 27 | 2019-12-28T12:29:12.000Z | 2022-03-02T04:08:55.000Z | contracts/includes/vapaee/token/tables/earnings.hpp | vapaee/vapaee.io-source | b2b0c07850a817629055a848b9239a59dc10b545 | [
"MIT"
] | 2 | 2019-11-29T22:32:47.000Z | 2021-02-18T23:47:47.000Z | #include <vapaee/token/tables/_aux.hpp>
// TABLE earnings (singleton table) -----------
// scope: owner (only contract)
TABLE earnings_table {
asset quantity;
uint64_t primary_key() const { return quantity.symbol.code().raw(); }
};
typedef eosio::multi_index< "earnings"_n, earnings_table > earnings;
// ------------------------------------
| 38.363636 | 81 | 0.516588 | vapaee |
051f9288241a34c636181de3998435c4e51f50d3 | 4,200 | cc | C++ | src/events/AdhocCliCommParser.cc | D15C0DE/openMSX | 5119a9657de4b82115c745f670cdc55dc7363133 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 320 | 2015-06-16T20:32:33.000Z | 2022-03-26T17:03:27.000Z | src/events/AdhocCliCommParser.cc | D15C0DE/openMSX | 5119a9657de4b82115c745f670cdc55dc7363133 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2,592 | 2015-05-30T12:12:21.000Z | 2022-03-31T17:16:15.000Z | src/events/AdhocCliCommParser.cc | D15C0DE/openMSX | 5119a9657de4b82115c745f670cdc55dc7363133 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 74 | 2015-06-18T19:51:15.000Z | 2022-03-24T15:09:33.000Z | #include "AdhocCliCommParser.hh"
#include "utf8_unchecked.hh"
#include "xrange.hh"
AdhocCliCommParser::AdhocCliCommParser(std::function<void(const std::string&)> callback_)
: callback(std::move(callback_))
, state(O0)
{
}
void AdhocCliCommParser::parse(const char* buf, size_t n)
{
for (auto i : xrange(n)) {
parse(buf[i]);
}
}
void AdhocCliCommParser::parse(char c)
{
// Whenever there is a parse error we return to the initial state
switch (state) {
case O0: // looking for opening tag
state = (c == '<') ? O1 : O0; break;
case O1: // matched <
state = (c == 'c') ? O2 : O0; break;
case O2: // matched <c
state = (c == 'o') ? O3 : O0; break;
case O3: // matched <co
state = (c == 'm') ? O4 : O0; break;
case O4: // matched <com
state = (c == 'm') ? O5 : O0; break;
case O5: // matched <comm
state = (c == 'a') ? O6 : O0; break;
case O6: // matched <comma
state = (c == 'n') ? O7 : O0; break;
case O7: // matched <comman
state = (c == 'd') ? O8 : O0; break;
case O8: // matched <command
if (c == '>') {
state = C0;
command.clear();
} else {
state = O0;
}
break;
case C0: // matched <command>, now parsing xml entities and </command>
if (c == '<') state = C1;
else if (c == '&') state = A1;
else command += c;
break;
case C1: // matched <
state = (c == '/') ? C2 : O0; break;
case C2: // matched </
state = (c == 'c') ? C3 : O0; break;
case C3: // matched </c
state = (c == 'o') ? C4 : O0; break;
case C4: // matched </co
state = (c == 'm') ? C5 : O0; break;
case C5: // matched </com
state = (c == 'm') ? C6 : O0; break;
case C6: // matched </comm
state = (c == 'a') ? C7 : O0; break;
case C7: // matched </comma
state = (c == 'n') ? C8 : O0; break;
case C8: // matched </comman
state = (c == 'd') ? C9 : O0; break;
case C9: // matched </command
if (c == '>') callback(command);
state = O0;
break;
case A1: // matched &
if (c == 'l') state = L2;
else if (c == 'a') state = A2;
else if (c == 'g') state = G2;
else if (c == 'q') state = Q2;
else if (c == '#') { state = H2; unicode = 0; }
else state = O0; // error
break;
case A2: // matched &a
if (c == 'm') state = A3;
else if (c == 'p') state = P3;
else state = O0; // error
break;
case A3: // matched &am
state = (c == 'p') ? A4 : O0; break;
case A4: // matched &
if (c == ';') {
command += '&';
state = C0;
} else {
state = O0; // error
}
break;
case P3: // matched &ap
state = (c == 'o') ? P4 : O0; break;
case P4: // matched &apo
state = (c == 's') ? P5 : O0; break;
case P5: // matched &apos
if (c == ';') {
command += '\'';
state = C0;
} else {
state = O0; // error
}
break;
case Q2: // matched &q
state = (c == 'u') ? Q3 : O0; break;
case Q3: // matched &qu
state = (c == 'o') ? Q4 : O0; break;
case Q4: // matched &quo
state = (c == 't') ? Q5 : O0; break;
case Q5: // matched "
if (c == ';') {
command += '"';
state = C0;
} else {
state = O0; // error
}
break;
case G2: // matched &g
state = (c == 't') ? G3 : O0; break;
case G3: // matched >
if (c == ';') {
command += '>';
state = C0;
} else {
state = O0; // error
}
break;
case L2: // matched &l
state = (c == 't') ? L3 : O0; break;
case L3: // matched <
if (c == ';') {
command += '<';
state = C0;
} else {
state = O0; // error
}
break;
case H2: // matched &#
// This also parses invalid input like 'xab;' but let's
// ignore that. It also doesn't check for overflow etc.
if (c == ';') {
utf8::unchecked::append(unicode, back_inserter(command));
state = C0;
} else if (c == 'x') {
state = H3;
} else {
unicode *= 10;
if (('0' <= c) && (c <= '9')) unicode += c - '0';
else state = O0;
}
break;
case H3: // matched &#x
if (c == ';') {
utf8::unchecked::append(unicode, back_inserter(command));
state = C0;
} else {
unicode *= 16;
if (('0' <= c) && (c <= '9')) unicode += c - '0';
else if (('a' <= c) && (c <= 'f')) unicode += c - 'a' + 10;
else if (('A' <= c) && (c <= 'F')) unicode += c - 'A' + 10;
else state = O0;
}
break;
}
}
| 24.852071 | 89 | 0.501905 | D15C0DE |
052a9edb2304fb1e11af576cc11898f45684d63e | 15,110 | hpp | C++ | Scheduler/CoinOR/include/coin/CbcCutGenerator.hpp | enyquist/Concordia_Scheduling | 5eb96ed585e7f2002983159b8ee0837b791753fa | [
"MIT"
] | null | null | null | Scheduler/CoinOR/include/coin/CbcCutGenerator.hpp | enyquist/Concordia_Scheduling | 5eb96ed585e7f2002983159b8ee0837b791753fa | [
"MIT"
] | null | null | null | Scheduler/CoinOR/include/coin/CbcCutGenerator.hpp | enyquist/Concordia_Scheduling | 5eb96ed585e7f2002983159b8ee0837b791753fa | [
"MIT"
] | null | null | null | /* $Id: CbcCutGenerator.hpp 1675 2011-06-19 17:23:14Z stefan $ */
// Copyright (C) 2003, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef CbcCutGenerator_H
#define CbcCutGenerator_H
#include "OsiSolverInterface.hpp"
#include "OsiCuts.hpp"
#include "CglCutGenerator.hpp"
#include "CbcCutModifier.hpp"
class CbcModel;
class OsiRowCut;
class OsiRowCutDebugger;
//#############################################################################
/** Interface between Cbc and Cut Generation Library.
\c CbcCutGenerator is intended to provide an intelligent interface between
Cbc and the cutting plane algorithms in the CGL. A \c CbcCutGenerator is
bound to a \c CglCutGenerator and to an \c CbcModel. It contains parameters
which control when and how the \c generateCuts method of the
\c CglCutGenerator will be called.
The builtin decision criteria available to use when deciding whether to
generate cuts are limited: every <i>X</i> nodes, when a solution is found,
and when a subproblem is found to be infeasible. The idea is that the class
will grow more intelligent with time.
\todo Add a pointer to function member which will allow a client to install
their own decision algorithm to decide whether or not to call the CGL
\p generateCuts method. Create a default decision method that looks
at the builtin criteria.
\todo It strikes me as not good that generateCuts contains code specific to
individual CGL algorithms. Another set of pointer to function members,
so that the client can specify the cut generation method as well as
pre- and post-generation methods? Taken a bit further, should this
class contain a bunch of pointer to function members, one for each
of the places where the cut generator might be referenced?
Initialization, root node, search tree node, discovery of solution,
and termination all come to mind. Initialization and termination would
also be useful for instrumenting cbc.
*/
class CbcCutGenerator {
public:
/** \name Generate Cuts */
//@{
/** Generate cuts for the client model.
Evaluate the state of the client model and decide whether to generate cuts.
The generated cuts are inserted into and returned in the collection of cuts
\p cs.
If \p fullScan is !=0, the generator is obliged to call the CGL
\c generateCuts routine. Otherwise, it is free to make a local decision.
Negative fullScan says things like at integer solution
The current implementation uses \c whenCutGenerator_ to decide.
The routine returns true if reoptimisation is needed (because the state of
the solver interface has been modified).
If node then can find out depth
*/
bool generateCuts( OsiCuts &cs, int fullScan, OsiSolverInterface * solver,
CbcNode * node);
//@}
/**@name Constructors and destructors */
//@{
/// Default constructor
CbcCutGenerator ();
/// Normal constructor
CbcCutGenerator(CbcModel * model, CglCutGenerator * generator,
int howOften = 1, const char * name = NULL,
bool normal = true, bool atSolution = false,
bool infeasible = false, int howOftenInsub = -100,
int whatDepth = -1, int whatDepthInSub = -1, int switchOffIfLessThan = 0);
/// Copy constructor
CbcCutGenerator (const CbcCutGenerator &);
/// Assignment operator
CbcCutGenerator & operator=(const CbcCutGenerator& rhs);
/// Destructor
~CbcCutGenerator ();
//@}
/**@name Gets and sets */
//@{
/** Set the client model.
In addition to setting the client model, refreshModel also calls
the \c refreshSolver method of the CglCutGenerator object.
*/
void refreshModel(CbcModel * model);
/// return name of generator
inline const char * cutGeneratorName() const {
return generatorName_;
}
/// Create C++ lines to show how to tune
void generateTuning( FILE * fp);
/** Set the cut generation interval
Set the number of nodes evaluated between calls to the Cgl object's
\p generateCuts routine.
If \p value is positive, cuts will always be generated at the specified
interval.
If \p value is negative, cuts will initially be generated at the specified
interval, but Cbc may adjust the value depending on the success of cuts
produced by this generator.
A value of -100 disables the generator, while a value of -99 means
just at root.
*/
void setHowOften(int value) ;
/// Get the cut generation interval.
inline int howOften() const {
return whenCutGenerator_;
}
/// Get the cut generation interval.in sub tree
inline int howOftenInSub() const {
return whenCutGeneratorInSub_;
}
/// Get level of cut inaccuracy (0 means exact e.g. cliques)
inline int inaccuracy() const {
return inaccuracy_;
}
/// Set level of cut inaccuracy (0 means exact e.g. cliques)
inline void setInaccuracy(int level) {
inaccuracy_ = level;
}
/** Set the cut generation depth
Set the depth criterion for calls to the Cgl object's
\p generateCuts routine. Only active if > 0.
If whenCutGenerator is positive and this is positive then this overrides.
If whenCutGenerator is -1 then this is used as criterion if any cuts
were generated at root node.
If whenCutGenerator is anything else this is ignored.
*/
void setWhatDepth(int value) ;
/// Set the cut generation depth in sub tree
void setWhatDepthInSub(int value) ;
/// Get the cut generation depth criterion.
inline int whatDepth() const {
return depthCutGenerator_;
}
/// Get the cut generation depth criterion.in sub tree
inline int whatDepthInSub() const {
return depthCutGeneratorInSub_;
}
/// Get switches (for debug)
inline int switches() const {
return switches_;
}
/// Get whether the cut generator should be called in the normal place
inline bool normal() const {
return (switches_&1) != 0;
}
/// Set whether the cut generator should be called in the normal place
inline void setNormal(bool value) {
switches_ &= ~1;
switches_ |= value ? 1 : 0;
}
/// Get whether the cut generator should be called when a solution is found
inline bool atSolution() const {
return (switches_&2) != 0;
}
/// Set whether the cut generator should be called when a solution is found
inline void setAtSolution(bool value) {
switches_ &= ~2;
switches_ |= value ? 2 : 0;
}
/** Get whether the cut generator should be called when the subproblem is
found to be infeasible.
*/
inline bool whenInfeasible() const {
return (switches_&4) != 0;
}
/** Set whether the cut generator should be called when the subproblem is
found to be infeasible.
*/
inline void setWhenInfeasible(bool value) {
switches_ &= ~4;
switches_ |= value ? 4 : 0;
}
/// Get whether the cut generator is being timed
inline bool timing() const {
return (switches_&64) != 0;
}
/// Set whether the cut generator is being timed
inline void setTiming(bool value) {
switches_ &= ~64;
switches_ |= value ? 64 : 0;
timeInCutGenerator_ = 0.0;
}
/// Return time taken in cut generator
inline double timeInCutGenerator() const {
return timeInCutGenerator_;
}
inline void incrementTimeInCutGenerator(double value) {
timeInCutGenerator_ += value;
}
/// Get the \c CglCutGenerator corresponding to this \c CbcCutGenerator.
inline CglCutGenerator * generator() const {
return generator_;
}
/// Number times cut generator entered
inline int numberTimesEntered() const {
return numberTimes_;
}
inline void setNumberTimesEntered(int value) {
numberTimes_ = value;
}
inline void incrementNumberTimesEntered(int value = 1) {
numberTimes_ += value;
}
/// Total number of cuts added
inline int numberCutsInTotal() const {
return numberCuts_;
}
inline void setNumberCutsInTotal(int value) {
numberCuts_ = value;
}
inline void incrementNumberCutsInTotal(int value = 1) {
numberCuts_ += value;
}
/// Total number of elements added
inline int numberElementsInTotal() const {
return numberElements_;
}
inline void setNumberElementsInTotal(int value) {
numberElements_ = value;
}
inline void incrementNumberElementsInTotal(int value = 1) {
numberElements_ += value;
}
/// Total number of column cuts
inline int numberColumnCuts() const {
return numberColumnCuts_;
}
inline void setNumberColumnCuts(int value) {
numberColumnCuts_ = value;
}
inline void incrementNumberColumnCuts(int value = 1) {
numberColumnCuts_ += value;
}
/// Total number of cuts active after (at end of n cut passes at each node)
inline int numberCutsActive() const {
return numberCutsActive_;
}
inline void setNumberCutsActive(int value) {
numberCutsActive_ = value;
}
inline void incrementNumberCutsActive(int value = 1) {
numberCutsActive_ += value;
}
inline void setSwitchOffIfLessThan(int value) {
switchOffIfLessThan_ = value;
}
inline int switchOffIfLessThan() const {
return switchOffIfLessThan_;
}
/// Say if optimal basis needed
inline bool needsOptimalBasis() const {
return (switches_&128) != 0;
}
/// Set if optimal basis needed
inline void setNeedsOptimalBasis(bool yesNo) {
switches_ &= ~128;
switches_ |= yesNo ? 128 : 0;
}
/// Whether generator MUST be called again if any cuts (i.e. ignore break from loop)
inline bool mustCallAgain() const {
return (switches_&8) != 0;
}
/// Set whether generator MUST be called again if any cuts (i.e. ignore break from loop)
inline void setMustCallAgain(bool yesNo) {
switches_ &= ~8;
switches_ |= yesNo ? 8 : 0;
}
/// Whether generator switched off for moment
inline bool switchedOff() const {
return (switches_&16) != 0;
}
/// Set whether generator switched off for moment
inline void setSwitchedOff(bool yesNo) {
switches_ &= ~16;
switches_ |= yesNo ? 16 : 0;
}
/// Whether last round of cuts did little
inline bool ineffectualCuts() const {
return (switches_&512) != 0;
}
/// Set whether last round of cuts did little
inline void setIneffectualCuts(bool yesNo) {
switches_ &= ~512;
switches_ |= yesNo ? 512 : 0;
}
/// Whether to use if any cuts generated
inline bool whetherToUse() const {
return (switches_&1024) != 0;
}
/// Set whether to use if any cuts generated
inline void setWhetherToUse(bool yesNo) {
switches_ &= ~1024;
switches_ |= yesNo ? 1024 : 0;
}
/// Whether in must call again mode (or after others)
inline bool whetherInMustCallAgainMode() const {
return (switches_&2048) != 0;
}
/// Set whether in must call again mode (or after others)
inline void setWhetherInMustCallAgainMode(bool yesNo) {
switches_ &= ~2048;
switches_ |= yesNo ? 2048 : 0;
}
/// Whether to call at end
inline bool whetherCallAtEnd() const {
return (switches_&4096) != 0;
}
/// Set whether to call at end
inline void setWhetherCallAtEnd(bool yesNo) {
switches_ &= ~4096;
switches_ |= yesNo ? 4096 : 0;
}
/// Number of cuts generated at root
inline int numberCutsAtRoot() const {
return numberCutsAtRoot_;
}
inline void setNumberCutsAtRoot(int value) {
numberCutsAtRoot_ = value;
}
/// Number of cuts active at root
inline int numberActiveCutsAtRoot() const {
return numberActiveCutsAtRoot_;
}
inline void setNumberActiveCutsAtRoot(int value) {
numberActiveCutsAtRoot_ = value;
}
/// Number of short cuts at root
inline int numberShortCutsAtRoot() const {
return numberShortCutsAtRoot_;
}
/// Set model
inline void setModel(CbcModel * model) {
model_ = model;
}
/// Whether global cuts at root
inline bool globalCutsAtRoot() const {
return (switches_&32) != 0;
}
/// Set whether global cuts at root
inline void setGlobalCutsAtRoot(bool yesNo) {
switches_ &= ~32;
switches_ |= yesNo ? 32 : 0;
}
/// Whether global cuts
inline bool globalCuts() const {
return (switches_&256) != 0;
}
/// Set whether global cuts
inline void setGlobalCuts(bool yesNo) {
switches_ &= ~256;
switches_ |= yesNo ? 256 : 0;
}
//@}
private:
/**@name Private gets and sets */
//@{
//@}
/// Saved cuts
OsiCuts savedCuts_;
/// Time in cut generator
double timeInCutGenerator_;
/// The client model
CbcModel *model_;
// The CglCutGenerator object
CglCutGenerator * generator_;
/// Name of generator
char * generatorName_;
/** Number of nodes between calls to the CglCutGenerator::generateCuts
routine.
*/
int whenCutGenerator_;
/** Number of nodes between calls to the CglCutGenerator::generateCuts
routine in sub tree.
*/
int whenCutGeneratorInSub_;
/** If first pass at root produces fewer than this cuts then switch off
*/
int switchOffIfLessThan_;
/** Depth at which to call the CglCutGenerator::generateCuts
routine (If >0 then overrides when and is called if depth%depthCutGenerator==0).
*/
int depthCutGenerator_;
/** Depth at which to call the CglCutGenerator::generateCuts
routine (If >0 then overrides when and is called if depth%depthCutGenerator==0).
In sub tree.
*/
int depthCutGeneratorInSub_;
/// Level of cut inaccuracy (0 means exact e.g. cliques)
int inaccuracy_;
/// Number times cut generator entered
int numberTimes_;
/// Total number of cuts added
int numberCuts_;
/// Total number of elements added
int numberElements_;
/// Total number of column cuts added
int numberColumnCuts_;
/// Total number of cuts active after (at end of n cut passes at each node)
int numberCutsActive_;
/// Number of cuts generated at root
int numberCutsAtRoot_;
/// Number of cuts active at root
int numberActiveCutsAtRoot_;
/// Number of short cuts at root
int numberShortCutsAtRoot_;
/// Switches - see gets and sets
int switches_;
};
// How often to do if mostly switched off (A)
# define SCANCUTS 1000
// How often to do if mostly switched off (probing B)
# define SCANCUTS_PROBING 1000
#endif
| 33.208791 | 94 | 0.65546 | enyquist |
052ce5ae03d50a8209618afb53dca0fa2758ade1 | 72 | cpp | C++ | main.cpp | Daniel-Ros/cpp-ex1 | 1c634af36a182d17f8e5292f5203aa28bebfe312 | [
"MIT"
] | null | null | null | main.cpp | Daniel-Ros/cpp-ex1 | 1c634af36a182d17f8e5292f5203aa28bebfe312 | [
"MIT"
] | null | null | null | main.cpp | Daniel-Ros/cpp-ex1 | 1c634af36a182d17f8e5292f5203aa28bebfe312 | [
"MIT"
] | null | null | null | #include "app.hpp"
int main(){
App app;
app.showScreen();
} | 12 | 25 | 0.541667 | Daniel-Ros |
0534f9a52141f8a4e38ef6ad92e9df11f3c366ca | 20,715 | hpp | C++ | include/seqan3/argument_parser/detail/format_help.hpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | 1 | 2021-03-01T11:12:56.000Z | 2021-03-01T11:12:56.000Z | include/seqan3/argument_parser/detail/format_help.hpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | 2 | 2017-05-17T07:16:19.000Z | 2020-02-13T16:10:10.000Z | include/seqan3/argument_parser/detail/format_help.hpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Svenja Mehringer <svenja.mehringer AT fu-berlin.de>
* \brief Provides the format_help struct that print the help page to the command line
* and the two child formats (format_version, format_short_help) that print
* short help messages to the command line.
*/
#pragma once
#include <cassert>
#include <iostream>
#include <seqan3/argument_parser/detail/format_base.hpp>
#include <seqan3/core/detail/debug_stream_type.hpp>
#include <seqan3/core/detail/terminal.hpp>
#include <seqan3/range/views/repeat_n.hpp>
#include <seqan3/version.hpp>
namespace seqan3::detail
{
/*!\brief The format that prints the help page to std::cout.
* \ingroup argument_parser
*
* \details
* The help page printing is not done immediately, because the user might not
* provide meta information, positional options, etc. in the correct order.
* In addition the needed order would be different from the parse format.
* Thus the calls are stored (parser_set_up_calls and positional_option_calls)
* and only evaluated when calling format_help::parse().
*/
class format_help : public format_help_base<format_help>
{
//!\brief The CRTP base class type.
using base_type = format_help_base<format_help>;
//!\brief Befriend the base class to give access to the private member functions.
friend base_type;
public:
/*!\name Constructors, destructor and assignment
* \{
*/
format_help() = default; //!< Defaulted.
format_help(format_help const & pf) = default; //!< Defaulted.
format_help & operator=(format_help const &) = default; //!< Defaulted.
format_help(format_help &&) = default; //!< Defaulted.
format_help & operator=(format_help &&) = default; //!< Defaulted.
~format_help() = default; //!< Defaulted.
//!\copydoc format_help_base(std::vector<std::string> const &, bool const)
format_help(std::vector<std::string> const & names, bool const advanced = false) : base_type{names, advanced}
{};
//!\}
protected:
//!\privatesection
//!\brief Stores the relevant parameters of the documentation on the screen.
struct console_layout_struct
{
//!\brief The screen width.
unsigned screenWidth;
//!\brief The default screen width.
unsigned defaultScreenWidth;
//!\brief The maximal screen width.
unsigned maximalScreenWidth;
//!\brief The minimal screen width.
unsigned minimalScreenWidth;
//!\brief The left Padding.
unsigned leftPadding;
//!\brief The center Padding.
unsigned centerPadding;
//!\brief The right Padding.
unsigned rightPadding;
//!\brief The left Column Width.
unsigned leftColumnWidth;
//!\brief The right Column Width.
unsigned rightColumnWidth;
//!\brief The right Column Tab.
unsigned rightColumnTab;
//!\brief The constructor.
console_layout_struct() :
screenWidth{0}, defaultScreenWidth{80}, maximalScreenWidth{120}, minimalScreenWidth{40},
leftPadding{4}, centerPadding{2}, rightPadding{2}, leftColumnWidth{4}, rightColumnWidth{0}
{
// Guess terminal screen width and set into layout.
unsigned cols = get_terminal_width();
screenWidth = (cols > 0) ? cols : defaultScreenWidth;
screenWidth = std::max(screenWidth, minimalScreenWidth);
screenWidth = std::min(screenWidth, maximalScreenWidth);
screenWidth -= rightPadding;
rightColumnWidth = screenWidth - leftPadding - leftColumnWidth - centerPadding - rightPadding;
rightColumnTab = leftPadding + leftColumnWidth + centerPadding;
}
};
//!\brief Prints a help page header to std::cout.
void print_header()
{
std::ostream_iterator<char> out(std::cout);
std::cout << meta.app_name;
if (!empty(meta.short_description))
std::cout << " - " << meta.short_description;
std::cout << "\n";
unsigned len = text_width(meta.app_name) + (empty(meta.short_description) ? 0 : 3) +
text_width(meta.short_description);
std::fill_n(out, len, '=');
std::cout << '\n';
}
/*!\brief Prints a help page section to std::cout.
* \param[in] title The title of the subsection of the help page.
*/
void print_section(std::string const & title)
{
std::ostream_iterator<char> out(std::cout);
std::cout << '\n' << to_text("\\fB");
std::transform(title.begin(), title.end(), out, [] (unsigned char c) { return std::toupper(c); });
std::cout << to_text("\\fP") << '\n';
prev_was_paragraph = false;
}
/*!\brief Prints a help page subsection to std::cout.
* \param[in] title The title of the subsection of the help page.
*/
void print_subsection(std::string const & title)
{
std::ostream_iterator<char> out(std::cout);
std::cout << '\n' << to_text("\\fB");
std::fill_n(out, layout.leftPadding / 2, ' ');
std::cout << title << to_text("\\fP") << '\n';
prev_was_paragraph = false;
}
/*!\brief Prints a text to std::cout.
* \param[in] text The text to print.
* \param[in] line_is_paragraph Whether to insert as paragraph
* or just a line (only one line break if not a paragraph).
*/
void print_line(std::string const & text, bool const line_is_paragraph)
{
if (prev_was_paragraph)
std::cout << '\n';
std::ostream_iterator<char> out(std::cout);
std::fill_n(out, layout.leftPadding, ' ');
print_text(text, layout.leftPadding);
prev_was_paragraph = line_is_paragraph;
}
/*!\brief Prints a help page list_item to std::cout.
* \param[in] term The key of the key-value pair of the list item.
* \param[in] desc The value of the key-value pair of the list item.
*
* \details
*
* A list item is composed of a key (term) and value (desc)
* and usually used for option identifier-description-pairs.
* E.g.:
*```console
* -a, --age LONG
* Super important integer for age.
*```
*/
void print_list_item(std::string const & term, std::string const & desc)
{
if (prev_was_paragraph)
std::cout << '\n';
std::ostream_iterator<char> out(std::cout);
// Print term.
std::fill_n(out, layout.leftPadding, ' ');
std::cout << to_text(term);
unsigned pos = layout.leftPadding + term.size();
if (pos + layout.centerPadding > layout.rightColumnTab)
{
std::cout << '\n';
pos = 0;
}
std::fill_n(out, layout.rightColumnTab - pos, ' ');
print_text(desc, layout.rightColumnTab);
prev_was_paragraph = false;
}
//!\brief Prints the version information to std::cout.
void print_version()
{
std::ostream_iterator<char> out(std::cout);
// Print version, date and url.
std::cout << "\n" << to_text("\\fB") << "VERSION" << to_text("\\fP") << "\n";
std::fill_n(out, layout.leftPadding, ' ');
std::cout << to_text("\\fB") << "Last update: " << to_text("\\fP") << meta.date << "\n";
std::fill_n(out, layout.leftPadding, ' ');
std::cout << to_text("\\fB") << meta.app_name << " version: " << to_text("\\fP") << meta.version << "\n";
std::fill_n(out, layout.leftPadding, ' ');
std::cout << to_text("\\fB") << "SeqAn version: " << to_text("\\fP") << SEQAN3_VERSION_MAJOR << '.'
<< SEQAN3_VERSION_MINOR << '.' << SEQAN3_VERSION_PATCH;
if (!empty(meta.url))
{
std::cout << "\n" << to_text("\\fB") << "URL" << to_text("\\fP") << "\n";
std::fill_n(out, layout.leftPadding, ' ');
std::cout << meta.url << "\n";
}
std::cout << "\n";
}
//!\brief Prints a help page footer to std::cout.
void print_footer()
{
print_version();
std::ostream_iterator<char> out(std::cout);
// Print legal stuff
if ((!empty(meta.short_copyright)) || (!empty(meta.long_copyright)) || (!empty(meta.citation)))
{
std::cout << "\n" << to_text("\\fB") << "LEGAL" << to_text("\\fP") << "\n";
if (!empty(meta.short_copyright))
{
std::fill_n(out, layout.leftPadding, ' ');
std::cout << to_text("\\fB") << meta.app_name << " Copyright: "
<< to_text("\\fP") << meta.short_copyright << "\n";
}
std::fill_n(out, layout.leftPadding, ' ');
std::cout << to_text("\\fB") << "SeqAn Copyright: " << to_text("\\fP")
<< "2006-2015 Knut Reinert, FU-Berlin; released under the 3-clause BSDL.\n";
if (!empty(meta.citation))
{
std::fill_n(out, layout.leftPadding, ' ');
std::cout << to_text("\\fB") << "In your academic works please cite: " << to_text("\\fP")
<< meta.citation << "\n";
}
if (!empty(meta.long_copyright))
{
std::fill_n(out, layout.leftPadding, ' ');
std::cout << "For full copyright and/or warranty information see " << to_text("\\fB")
<< "--copyright" << to_text("\\fP") << ".\n";
}
}
}
/*!\brief Formats text for pretty command line printing.
* \param[in] str The input string to format for correct command line printing.
*/
std::string to_text(std::string const & str)
{
std::string result;
for (auto it = str.begin(); it != str.end(); ++it)
{
if (*it == '\\')
{
// Handle escape sequence, we interpret only "\-", "\fI", and "\fB".
++it;
assert(it != str.end());
if (*it == '-')
{
result.push_back(*it);
}
else if (*it == 'f')
{
++it;
assert(it != str.end());
if (*it == 'I')
{
if (is_terminal())
result.append("\033[4m");
}
else if (*it == 'B')
{
if (is_terminal())
result.append("\033[1m");
}
else if (*it == 'P')
{
if (is_terminal())
result.append("\033[0m");
}
else
{
result.append("\\f");
result.push_back(*it);
}
}
else
{
result.push_back('\\');
result.push_back(*it);
}
}
else
{
result.push_back(*it);
}
}
return result;
}
/*!\brief Returns width of text if printed.
* \param[in] text The string to compute the width for on the command line.
* /detail Note: "\-" has length 1, "\fI", "\fB", "\fP" have length 0.
*/
unsigned text_width(std::string const & text)
{
unsigned result = 0;
for (unsigned i = 0; i < text.size(); ++i)
{
if (text[i] != '\\')
{
result += 1;
continue;
}
if (i + 1 == text.size())
{
result += 1; // Will print "\\".
continue;
}
if (text[i + 1] == '\\' || text[i + 1] == '-')
{
i += 1;
result += 1;
continue; // Will print '\\' or '-'.
}
if (i + 2 == text.size())
{
i += 1;
result += 2; // Will print two chars.
continue;
}
if (text[i + 1] == 'f')
{
if (text[i + 2] == 'B' || text[i + 2] == 'I' || text[i + 2] == 'P')
i += 2; // Skip f and {B, I, P}.
else
result += 1;
}
}
return result;
}
/*!\brief Prints text with correct line wrapping to the command line (std::cout).
* \param[in] text The string to print on the command line.
* \param[in] tab The position offset (indentation) to start printing at.
*/
void print_text(std::string const & text, unsigned const tab)
{
unsigned pos = tab;
std::ostream_iterator<char> out(std::cout);
// Tokenize the text.
std::istringstream iss(text.c_str());
std::vector<std::string> tokens;
std::ranges::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(),
std::ranges::back_inserter(tokens));
// Print the text.
assert(pos <= tab);
std::fill_n(out, tab - pos, ' '); // go to tab
pos = tab;
typedef std::vector<std::string>::const_iterator TConstIter;
for (TConstIter it = tokens.begin(); it != tokens.end(); ++it)
{
if (it == tokens.begin())
{
std::cout << to_text(*it);
pos += text_width(*it);
if (pos > layout.screenWidth)
{
std::cout << '\n';
std::fill_n(out, tab, ' ');
pos = tab;
}
}
else
{
if (pos + 1 + text_width(*it) > layout.screenWidth)
{
// Would go over screen with next, print current word on next line.
std::cout << '\n';
fill_n(out, tab, ' ');
std::cout << to_text(*it);
pos = tab + text_width(*it);
}
else
{
std::cout << ' ';
std::cout << to_text(*it);
pos += text_width(*it) + 1;
}
}
}
if (!empty(tokens))
std::cout << '\n';
}
//!\brief Needed for correct formatting while calling different print functions.
bool prev_was_paragraph{false};
//!\brief Stores the relevant parameters of the documentation on the screen.
console_layout_struct layout{};
};
/*!\brief The format that prints a short help message to std::cout.
* \ingroup argument_parser
*
* \details
*
* The short help message printing is not done immediately, because the user cannot provide
* meta information (e.g. app_name) on construction of the parser. Thus the meta information is collected
* and only evaluated when calling seqan3::detail::format_version::parse.
*/
class format_short_help : public format_help
{
public:
/*!\brief Initiates the printing of a short help message to std::cout.
* \param[in] parser_meta The meta information that are needed for a detailed version information.
*/
void parse(argument_parser_meta_data const & parser_meta)
{
meta = parser_meta;
print_header();
if (!parser_meta.synopsis.empty())
print_synopsis();
print_line("Try -h or --help for more information.\n", true);
std::exit(EXIT_SUCCESS);
}
};
/*!\brief The format that prints the version to std::cout.
* \ingroup argument_parser
*
* \details
*
* The version printing is not done immediately, because the user cannot provide
* meta information on construction of the parser. Thus the meta information is collected
* and only evaluated when calling format_version::parse().
*/
class format_version : public format_help
{
public:
/*!\brief Initiates the printing of the version information to std::cout.
* \param[in] parser_meta The meta information that are needed for a detailed version information.
*/
void parse(argument_parser_meta_data & parser_meta)
{
meta = parser_meta;
print_header();
print_version();
std::exit(EXIT_SUCCESS); // program should not continue from here
}
};
/*!\brief The format that prints the copyright information to std::cout.
* \ingroup argument_parser
*
* \details
*
* The copyright message printing is not done immediately, because the user cannot provide
* meta information (e.g. long_copyright) on construction of the parser. Thus the meta information is collected
* and only evaluated when calling seqan3::detail::format_version::parse.
*/
class format_copyright : public format_help
{
public:
/*!\brief Initiates the printing of the copyright message to std::cout.
* \param[in] parser_meta The meta information that are needed for a detailed version information.
*/
void parse(argument_parser_meta_data const & parser_meta)
{
meta = parser_meta;
debug_stream_type stream{std::cout};
std::string seqan_license{
R"(Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.)"};
stream << views::repeat_n('=', 80) << to_text("\n\\fB") << "Copyright information for "
<< meta.app_name << ":\n" << to_text("\\fP") << views::repeat_n('-', 80) << '\n';
if (!empty(meta.long_copyright))
{
stream << to_text("\\fP") << meta.long_copyright << "\n";
}
else if (!empty(meta.short_copyright))
{
stream << to_text("\\fP") << meta.app_name << " full copyright information not available. Displaying"
<< " short copyright information instead:\n" << to_text("\\fP") << meta.short_copyright << "\n";
}
else
{
stream << to_text("\\fP") << meta.app_name << " copyright information not available.\n";
}
stream << views::repeat_n('=', 80) << to_text("\n\\fB")
<< "This program contains SeqAn code licensed under the following terms:\n" << to_text("\\fP")
<< views::repeat_n('-', 80) << '\n' << seqan_license << '\n';
std::exit(EXIT_SUCCESS);
}
};
} // namespace seqan3::detail
| 37.257194 | 114 | 0.552064 | marehr |
053dc45f6a8d650f2e873eb6270140f0f51789c0 | 2,418 | hh | C++ | 1-Simulation/source/include/GasHit.hh | surfound/CXPD | 788a125048cc3d79244a0562d94263e48ca22a6a | [
"Apache-2.0"
] | 1 | 2019-08-01T03:48:26.000Z | 2019-08-01T03:48:26.000Z | 1-Simulation/source/include/GasHit.hh | surfound/CXPD | 788a125048cc3d79244a0562d94263e48ca22a6a | [
"Apache-2.0"
] | null | null | null | 1-Simulation/source/include/GasHit.hh | surfound/CXPD | 788a125048cc3d79244a0562d94263e48ca22a6a | [
"Apache-2.0"
] | null | null | null | //*********************************************
// This is auto generated by G4gen 0.6
// author:Qian
#ifndef GasHit_h
#define GasHit_h
#include "G4THitsCollection.hh"
#include "G4Allocator.hh"
#include "G4Step.hh"
#include "G4VHit.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
class GasHit : public G4VHit
{
public:
GasHit();
~GasHit();
GasHit(const GasHit &);
GasHit(const G4Step *);
const GasHit &operator=(const GasHit &);
int operator==(const GasHit &) const;
inline void *operator new(size_t);
inline void operator delete(void *);
void Init();
inline G4int GetPDGID() { return pdgID; }
inline G4int GetProducerID() { return prodID; }
inline G4int GetTrackID() { return trackID; }
inline G4double GetEdep() { return Edep; }
inline G4double GetStepLength() { return stepL; }
inline G4ThreeVector GetPostPosition() { return postPos; }
inline G4ThreeVector GetPrePosition() { return prePos; }
inline G4bool IsFirstDeposit() { return isFirstDeposit; }
inline void SetPDGID(G4int id) { pdgID = id; }
inline void SetProducerID(G4int id) { prodID = id; }
inline void SetTrackID(G4int id) { trackID = id; }
inline void SetEdep(G4double edep) { Edep = edep; }
inline void SetStepLength(G4double length) { stepL = length; }
inline void SetPostPosition(G4ThreeVector pos) { postPos = pos; }
inline void SetPrePosition(G4ThreeVector pos) { prePos = pos; }
inline void SetFirstDepositFlag() { isFirstDeposit = true; }
private:
G4int pdgID;
G4int prodID;
G4int trackID;
G4double Edep;
G4double stepL;
G4ThreeVector prePos;
G4ThreeVector postPos;
G4bool isFirstDeposit;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
typedef G4THitsCollection<GasHit> GasHitCollection;
extern G4ThreadLocal G4Allocator<GasHit> *GasHitAllocator;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
inline void *GasHit::operator new(size_t)
{
if (!GasHitAllocator)
GasHitAllocator = new G4Allocator<GasHit>;
return (void *)GasHitAllocator->MallocSingle();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
inline void GasHit::operator delete(void *aHit)
{
GasHitAllocator->FreeSingle((GasHit *)aHit);
}
#endif
| 29.487805 | 78 | 0.653019 | surfound |
053e22dec86b814335205978eefce1aef01e9dfb | 517 | cpp | C++ | test/vector.cpp | priseborough/Matrix | 6009709986fc681c712ffe7206e68eaa5224db8b | [
"BSD-3-Clause-Clear"
] | 2 | 2021-01-17T04:31:37.000Z | 2021-07-09T17:58:27.000Z | test/vector.cpp | priseborough/Matrix | 6009709986fc681c712ffe7206e68eaa5224db8b | [
"BSD-3-Clause-Clear"
] | null | null | null | test/vector.cpp | priseborough/Matrix | 6009709986fc681c712ffe7206e68eaa5224db8b | [
"BSD-3-Clause-Clear"
] | 2 | 2016-10-24T10:05:08.000Z | 2017-06-04T19:18:35.000Z | #include <assert.h>
#include <stdio.h>
#include <matrix/math.hpp>
using namespace matrix;
template class Vector<float, 5>;
int main()
{
float data1[] = {1,2,3,4,5};
float data2[] = {6,7,8,9,10};
Vector<float, 5> v1(data1);
assert(fabs(v1.norm() - 7.416198487095663f) < 1e-5);
Vector<float, 5> v2(data2);
assert(fabs(v1.dot(v2) - 130.0f) < 1e-5);
v2.normalize();
Vector<float, 5> v3(v2);
assert(v2 == v3);
return 0;
}
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
| 20.68 | 56 | 0.589942 | priseborough |
053f3a1d9c9c2e377f8d2602baa66eba062db528 | 8,631 | cpp | C++ | src/main.cpp | matey-99/MistEngine | 1a60f98da6b9331b3249f995e2b2566449ce0187 | [
"MIT"
] | 2 | 2022-02-08T13:16:01.000Z | 2022-02-28T18:21:35.000Z | src/main.cpp | matey-99/MistEngine | 1a60f98da6b9331b3249f995e2b2566449ce0187 | [
"MIT"
] | null | null | null | src/main.cpp | matey-99/MistEngine | 1a60f98da6b9331b3249f995e2b2566449ce0187 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include "imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <stb_image.h>
#include "Editor/ImGuiRenderer.h"
#include <glad/glad.h> // Initialize with gladLoadGL()
#include <GLFW/glfw3.h> // Include glfw3.h after our OpenGL definitions
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "typedefs.h"
#include "Scene/Scene.h"
#include "Scene/SceneSerializer.h"
#include "Editor/Editor.h"
#include "Material/Material.h"
#include "Scene/Component/StaticMeshComponent.h"
#include "Scene/Component/Light/Light.h"
#include "Renderer/Framebuffer.h"
#include "Input/Input.h"
#define FPS 60.0f
#define MS_PER_UPDATE 1 / FPS
Ref<Scene> scene = Ref<Scene>();
float deltaTime = 0.0f;
float lastFrame = 0.0f;
float lag = 0.0f;
bool rotateCamera = false;
bool moveCamera = false;
bool isPlayMode = false;
bool isViewportHovered = false;
const float mouseSensitivity = 0.1f;
const float scrollSensitivity = 0.1f;
float lastMouseX = 400, lastMouseY = 300;
bool leftCtrlClicked = false;
bool keyDClicked = false;
void ProcessKeyboardInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)// || glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
scene->GetCamera()->Move(CameraMovement::Forward, deltaTime);
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)// || glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
scene->GetCamera()->Move(CameraMovement::Backward, deltaTime);
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)// || glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
scene->GetCamera()->Move(CameraMovement::Left, deltaTime);
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)// || glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
scene->GetCamera()->Move(CameraMovement::Right, deltaTime);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
Editor::GetInstance()->SetGizmoOperation(ImGuizmo::OPERATION::TRANSLATE);
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
Editor::GetInstance()->SetGizmoOperation(ImGuizmo::OPERATION::ROTATE);
if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS)
Editor::GetInstance()->SetGizmoOperation(ImGuizmo::OPERATION::SCALE);
}
void ProcessMouseInput(GLFWwindow* window)
{
if (isViewportHovered)
{
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_3) == GLFW_PRESS)
{
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPos(window, xpos, ypos);
moveCamera = true;
}
else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_2) == GLFW_PRESS)
{
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPos(window, xpos, ypos);
rotateCamera = true;
moveCamera = false;
}
}
if (moveCamera && glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_3) == GLFW_RELEASE)
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
moveCamera = false;
}
else if (rotateCamera && glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_2) == GLFW_RELEASE)
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
rotateCamera = false;
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_LEFT_CONTROL)
{
if (action == GLFW_PRESS)
leftCtrlClicked = true;
else if (action == GLFW_RELEASE)
leftCtrlClicked = false;
}
if (key == GLFW_KEY_D)
{
if (action == GLFW_PRESS)
keyDClicked = true;
else if (action == GLFW_RELEASE)
keyDClicked = false;
}
if (leftCtrlClicked && keyDClicked)
Editor::GetInstance()->GetSceneHierarchyPanel()->DuplicateSelectedEntity();
ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mods);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
float xoffset = xpos - lastMouseX;
float yoffset = lastMouseY - ypos;
lastMouseX = xpos;
lastMouseY = ypos;
xoffset *= mouseSensitivity;
yoffset *= mouseSensitivity;
if (rotateCamera)
{
scene->GetCamera()->Rotate(xoffset, yoffset, deltaTime);
}
if (moveCamera)
{
scene->GetCamera()->Move(xoffset, yoffset, deltaTime);
}
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
if (isViewportHovered && !isPlayMode)
scene->GetCamera()->Move(yoffset, deltaTime);
ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset);
}
static void glfw_error_callback(int error, const char* description)
{
fprintf(stderr, "Glfw Error %d: %s\n", error, description);
}
int main(int, char**)
{
// Setup window
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
return 1;
// GL 4.3 + GLSL 430
const char* glsl_version = "#version 450";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // 3.0+ only
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
// Create window with graphics context
GLFWwindow* window = glfwCreateWindow(1440, 900, "Mist Engine", NULL, NULL);
if (window == NULL)
return 1;
//glfwMaximizeWindow(window);
glfwMakeContextCurrent(window);
glfwSwapInterval(1); // Enable vsync
if (glfwRawMouseMotionSupported())
glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
// Initialize OpenGL loader
bool err = !gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
if (err)
{
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return 1;
}
Renderer::GetInstance()->Initialize();
Renderer::GetInstance()->InitializeMainSceneFramebuffer();
Renderer::GetInstance()->InitializePostProcessingFramebuffer();
Renderer::GetInstance()->InitializeShadowMapFramebuffers();
Renderer::GetInstance()->InitializePostProcessing();
if (!(scene = SceneSerializer::Deserialize("../../res/scenes/Showcase.scene")))
scene = CreateRef<Scene>();
ImGuiRenderer imGuiRenderer = ImGuiRenderer();
imGuiRenderer.Setup(window, glsl_version, scene);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetKeyCallback(window, key_callback);
auto input = Input::GetInstance();
bool shouldRender = false;
lastFrame = glfwGetTime();
// Main loop
while (!glfwWindowShouldClose(window))
{
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
lag += deltaTime;
if (imGuiRenderer.GetEditor()->IsPlayMode() && !isPlayMode)
{
isPlayMode = true;
scene->BeginPlay();
}
else if (!imGuiRenderer.GetEditor()->IsPlayMode() && isPlayMode)
{
isPlayMode = false;
scene->EndPlay();
}
isViewportHovered = imGuiRenderer.GetEditor()->GetViewport()->IsHovered();
if (isViewportHovered && !isPlayMode)
ProcessKeyboardInput(window);
if (!isPlayMode)
ProcessMouseInput(window);
else
input->ProcessKeyboardInput(window);
glfwPollEvents();
while (lag >= MS_PER_UPDATE)
{
scene->Update();
if (isPlayMode)
scene->Tick(deltaTime);
shouldRender = true;
lag -= MS_PER_UPDATE;
}
if (shouldRender)
{
Renderer::GetInstance()->RenderScene(scene);
if (Renderer::GetInstance()->IsPostProcessing())
Renderer::GetInstance()->AddPostProcessingEffects();
imGuiRenderer.Render();
imGuiRenderer.EndFrame();
glfwSwapBuffers(window);
shouldRender = false;
}
}
imGuiRenderer.CleanUp();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
} | 29.558219 | 108 | 0.65705 | matey-99 |
0541f71341bb27b48c2e998b8086ea4ed332a840 | 802 | cpp | C++ | Numba and C++/cppfuncs/test_numba.cpp | ThomasHJorgensen/ConsumptionSavingNotebooks | badbdfb1da226d5494026de2adcfec171c7f40ea | [
"MIT"
] | 1 | 2021-11-07T23:37:25.000Z | 2021-11-07T23:37:25.000Z | Numba and C++/cppfuncs/test_numba.cpp | ThomasHJorgensen/ConsumptionSavingNotebooks | badbdfb1da226d5494026de2adcfec171c7f40ea | [
"MIT"
] | null | null | null | Numba and C++/cppfuncs/test_numba.cpp | ThomasHJorgensen/ConsumptionSavingNotebooks | badbdfb1da226d5494026de2adcfec171c7f40ea | [
"MIT"
] | null | null | null | //////////////////////////
// 1. external includes //
//////////////////////////
// standard C++ libraries
#include <windows.h>
#include <stdio.h>
#include <cmath>
#include <omp.h>
///////////////
// 2. macros //
///////////////
#define EXPORT extern "C" __declspec(dllexport)
/////////////
// 3. main //
/////////////
EXPORT void setup_omp(){ // required when using vs
SetEnvironmentVariable("OMP_WAIT_POLICY", "passive");
}
EXPORT void fun(double *X, double *Y, double *Z, int NX, int NY, int threads){
#pragma omp parallel num_threads(threads)
{
#pragma omp for
for(int i = 0; i < NX; i++){
Z[i] = 0;
for(int j = 0; j < NY; j++){
Z[i] += exp(log(X[i]*Y[j]+0.001))/(X[i]*Y[j])-1;
}
}
} // omp parallel
}
| 18.651163 | 78 | 0.471322 | ThomasHJorgensen |
0547a18c2c91c46a462e339f3065befbbc7c75a6 | 20,922 | cpp | C++ | SOURCES/sim/displays/wpnmfd.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/sim/displays/wpnmfd.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/sim/displays/wpnmfd.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #include "stdhdr.h"
#include "mfd.h"
#include "hud.h"
#include "stdhdr.h"
#include "mfd.h"
#include "hud.h"
#include "sms.h"
#include "simdrive.h"
#include "camp2sim.h"
#include "Graphics\Include\render2d.h"
#include "Graphics\Include\canvas3d.h"
#include "Graphics\Include\tviewpnt.h"
#include "Graphics\Include\renderir.h"
#include "otwdrive.h"
#include "cpmanager.h"
#include "icp.h"
#include "aircrft.h"
#include "fcc.h"
#include "radardoppler.h"
#include "mavdisp.h"
#include "misldisp.h"
#include "airframe.h"
#include "simweapn.h"
#include "missile.h"
#include "harmpod.h"
#include "commands.h"
extern bool g_bGreyMFD;
extern bool g_bGreyScaleMFD;
extern bool bNVGmode;
//MI
void DrawBullseyeCircle(VirtualDisplay* display, float cursorX, float cursorY);
WpnMfdDrawable::WpnMfdDrawable()
{
self = NULL;
pFCC = NULL;
mavDisplay = NULL;
Sms = NULL;
theRadar = NULL;
}
void WpnMfdDrawable::DisplayInit (ImageBuffer* image)
{
DisplayExit();
if (!g_bGreyScaleMFD)
g_bGreyMFD = false;
privateDisplay = new RenderIR;
((RenderIR*)privateDisplay)->Setup(image, OTWDriver.GetViewpoint());
if ((g_bGreyMFD) && (!bNVGmode))
privateDisplay->SetColor(GetMfdColor(MFD_WHITE));
else
privateDisplay->SetColor (0xff00ff00);
((Render3D*)privateDisplay)->SetFOV(6.0f*DTR);
}
VirtualDisplay* WpnMfdDrawable::GetDisplay(void)
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
if(!playerAC || !playerAC->Sms ||
!playerAC->Sms->curWeapon)
return privateDisplay;
Sms = playerAC->Sms;
VirtualDisplay* retval= privateDisplay;
MissileClass* theMissile = (MissileClass*)(Sms->GetCurrentWeapon());
float rx, ry, rz;
Tpoint pos;
if(Sms->CurHardpoint() < 0)
{
return retval;
}
if(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponClass() == wcAgmWpn &&
Sms->curWeaponType == wtAgm65)
{
if (theMissile && theMissile->IsMissile())
{
mavDisplay = (MaverickDisplayClass*)theMissile->display;
if (mavDisplay)
{
if (!mavDisplay->GetDisplay())
{
if (privateDisplay)
{
mavDisplay->DisplayInit(((Render2D*)(privateDisplay))->GetImageBuffer());
}
mavDisplay->viewPoint = viewPoint;
// Set missile initial position
Sms->hardPoint[Sms->CurHardpoint()]->GetSubPosition(Sms->curWpnNum, &rx, &ry, &rz);
rx += 5.0F;
pos.x = Sms->Ownship()->XPos() + Sms->Ownship()->dmx[0][0]*rx + Sms->Ownship()->dmx[1][0]*ry +
Sms->Ownship()->dmx[2][0]*rz;
pos.y = Sms->Ownship()->YPos() + Sms->Ownship()->dmx[0][1]*rx + Sms->Ownship()->dmx[1][1]*ry +
Sms->Ownship()->dmx[2][1]*rz;
pos.z = Sms->Ownship()->ZPos() + Sms->Ownship()->dmx[0][2]*rx + Sms->Ownship()->dmx[1][2]*ry +
Sms->Ownship()->dmx[2][2]*rz;
mavDisplay->SetXYZ (pos.x, pos.y, pos.z);
}
retval = mavDisplay->GetDisplay();
}
}
}
return (retval);
}
void WpnMfdDrawable::Display (VirtualDisplay* newDisplay)
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
float cX, cY;
display = newDisplay;
self = ((AircraftClass*)playerAC);
theRadar = (RadarDopplerClass*)FindSensor(playerAC, SensorClass::Radar);
pFCC = playerAC->Sms->Ownship()->GetFCC();
Sms = playerAC->Sms;
mavDisplay = NULL;
display = newDisplay;
HarmTargetingPod* harmPod = (HarmTargetingPod*)FindSensor(Sms->Ownship(), SensorClass::HTS);
if(!theRadar || !pFCC || !self || !Sms)
{
ShiWarning("Oh Oh shouldn't be here without a radar or FCC or player or SMS!");
return;
}
if( !g_bRealisticAvionics || !Sms->curWeapon || (Sms->curWeaponType != wtAgm65 && Sms->curWeaponType != wtAgm88) )
{
OffMode(display);
return;
}
if ( harmPod && Sms->curWeaponType == wtAgm88 )
{
// This makes sure we are in the correct FCC submode
if ( pFCC->GetSubMode() != FireControlComputer::HARM )
{
pFCC->SetSubMode( FireControlComputer::HARM );
harmPod->SetSubMode( HarmTargetingPod::HarmModeChooser );
}
HARMWpnMode();
}
if(Sms->curWeapon && Sms->curWeaponType == wtAgm65) // RV-I-Hawk - No do for HARM WPN
{
ShiAssert(Sms->curWeapon->IsMissile());
mavDisplay = (MaverickDisplayClass*)((MissileClass*)Sms->GetCurrentWeapon())->display;
// FRB - B&W display
if ((g_bGreyMFD) && (!bNVGmode))
display->SetColor(GetMfdColor(MFD_WHITE));
else
display->SetColor (0xff00ff00);
if(mavDisplay && (!((MissileClass*)Sms->GetCurrentWeapon())->Covered || playerAC->AutopilotType() == AircraftClass::CombatAP) && Sms->MavCoolTimer <= 0.0F)
{
mavDisplay->SetIntensity(GetIntensity());
mavDisplay->viewPoint = viewPoint;
mavDisplay->Display(display);
//DLZ
DrawDLZ(display);
}
else if(Sms->MavCoolTimer > 0.0F && Sms->Powered)
{
display->TextCenter(0.0F, 0.7F, "NOT TIMED OUT");
}
DrawRALT(display);
}
// RV-I-Hawk - No do for HARM WPN in HTSSubmode
if ( Sms->curWeaponType == wtAgm65 ||( Sms->curWeaponType == wtAgm88 && harmPod->GetSubMode() != HarmTargetingPod::HarmModeChooser) )
{
// FRB - B&W display
if ((g_bGreyMFD) && (!bNVGmode))
display->SetColor(GetMfdColor(MFD_WHITE));
else
display->SetColor (0xff00ff00);
//SMSMissiles
DrawHDPT(display, Sms);
}
// RV-I-Hawk - No do for HARM WPN
if ( Sms->curWeaponType == wtAgm65 )
{
// FRB - B&W display
if ((g_bGreyMFD) && (!bNVGmode))
display->SetColor(GetMfdColor(MFD_WHITE));
else
display->SetColor (0xff00ff00);
//OSB's
OSBLabels(display);
}
//Reference symbol
theRadar->GetCursorPosition (&cX, &cY);
if(OTWDriver.pCockpitManager && OTWDriver.pCockpitManager->mpIcp &&
OTWDriver.pCockpitManager->mpIcp->ShowBullseyeInfo)
{
// FRB - B&W display
if ((g_bGreyMFD) && (!bNVGmode))
display->SetColor(GetMfdColor(MFD_WHITE));
else
display->SetColor (0xff00ff00);
DrawBullseyeCircle(display, cX, cY);
}
else
{
DrawReference(MfdDisplay[OnMFD()]->GetOwnShip());
}
//Booster 18/09/2004 - Draw Pull Up cross on MFD-SMS if ground Collision
if (playerAC->mFaults->GetFault(alt_low))
{
DrawRedBreak(display);
}
// RV - I-Hawk
// Check, if 1 of the MFDs is showing TGP and the attitude warning is set, show it...
// (works on all MFDs and not only here)
for ( int i = 0; i < 4; i++ )
{
if ( (MfdDisplay[i])->GetTGPWarning() && (MfdDisplay[i])->CurMode() == MFDClass::TGPMode )
{
TGPAttitudeWarning(display);
break;
}
}
}
void WpnMfdDrawable::DrawDLZ(VirtualDisplay* display)
{
if(!pFCC){ return; }
float yOffset;
float percentRange;
float rMax, rMin;
float range;
float dx, dy, dz;
if (pFCC->missileTarget)
{
// Range Carat / Closure
rMax = pFCC->missileRMax;
rMin = pFCC->missileRMin;
// get range to ground designaate point
dx = Sms->Ownship()->XPos() - pFCC->groundDesignateX;
dy = Sms->Ownship()->YPos() - pFCC->groundDesignateY;
dz = Sms->Ownship()->ZPos() - pFCC->groundDesignateZ;
range = (float)sqrt( dx*dx + dy*dy + dz*dz );
// Normailze the ranges for DLZ display
percentRange = range / pFCC->missileWEZDisplayRange;
rMin /= pFCC->missileWEZDisplayRange;
rMax /= pFCC->missileWEZDisplayRange;
// Clamp in place
rMin = min (rMin, 1.0F);
rMax = min (rMax, 1.0F);
// Draw the symbol
// Rmin/Rmax
display->Line (0.9F, -0.8F + rMin * 1.6F, 0.95F, -0.8F + rMin * 1.6F);
display->Line (0.9F, -0.8F + rMin * 1.6F, 0.9F, -0.8F + rMax * 1.6F);
display->Line (0.9F, -0.8F + rMax * 1.6F, 0.95F, -0.8F + rMax * 1.6F);
// Range Caret
yOffset = min (-0.8F + percentRange * 1.6F, 1.0F);
display->Line (0.9F, yOffset, 0.9F - 0.03F, yOffset + 0.03F);
display->Line (0.9F, yOffset, 0.9F - 0.03F, yOffset - 0.03F);
}
}
void WpnMfdDrawable::PushButton(int whichButton, int whichMFD)
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
FireControlComputer* pFCC = playerAC->Sms->Ownship()->GetFCC();
HarmTargetingPod* harmPod = (HarmTargetingPod*)FindSensor(Sms->Ownship(), SensorClass::HTS);
// RV - I-Hawk - First check if FCC isn't in HARM mode
if ( pFCC->GetMasterMode() != FireControlComputer::AirGroundHARM )
{
switch (whichButton)
{
case 0:
if(!Sms->Powered)
{
Sms->Powered = TRUE;
}
break;
case 1:
Sms->StepMavSubMode();
break;
case 2:
if(mavDisplay)
{
mavDisplay->ToggleFOV();
}
break;
case 4:
((MissileClass*)Sms->GetCurrentWeapon())->HOC = !((MissileClass*)Sms->GetCurrentWeapon())->HOC;
break;
case 19:
if ((g_bGreyMFD) || (!g_bGreyScaleMFD))
g_bGreyMFD = false;
else
g_bGreyMFD = true;
break;
case 10:
case 11:
case 12:
case 13:
case 14:
MfdDrawable::PushButton(whichButton, whichMFD);
break;
default:
break;
}
}
else // Now handle the HARM mode
{
switch ( harmPod->GetSubMode() )
{
case HarmTargetingPod::HarmModeChooser:
default:
switch ( whichButton )
{
case 10:
case 11:
case 12:
case 13:
case 14:
MfdDrawable::PushButton(whichButton, whichMFD);
break;
case 19:
harmPod->SetSubMode( HarmTargetingPod::POS );
harmPod->SetRange( 60 );
break;
case 18:
harmPod->SetSubMode( HarmTargetingPod::HAS );
harmPod->SetRange( 60 );
harmPod->ResetHASTimer();
harmPod->SetFilterMode( HarmTargetingPod::ALL );
break;
}
break;
case HarmTargetingPod::HAS:
switch ( whichButton )
{
case 0:
harmPod->SetSubMode( HarmTargetingPod::HarmModeChooser );
pFCC->dropTrackCmd = TRUE; // drop target if switching HTS mode
break;
case 2:
harmPod->ToggleZoomMode();
break;
case 3:
// Go to the threats filtering screen
harmPod->SetSubMode( HarmTargetingPod::FilterMode );
harmPod->SetLastSubMode( HarmTargetingPod::HAS );
break;
case 6:
// Reset HAS timer
harmPod->ResetHASTimer();
break;
case 10:
case 11:
case 12:
case 13:
case 14:
MfdDrawable::PushButton(whichButton, whichMFD);
}
break;
case HarmTargetingPod::POS:
switch ( whichButton )
{
case 0:
harmPod->SetSubMode( HarmTargetingPod::HarmModeChooser );
pFCC->dropTrackCmd = TRUE; // drop target if switching HTS mode
break;
case 10:
case 11:
case 12:
case 13:
case 14:
MfdDrawable::PushButton(whichButton, whichMFD);
break;
case 16:
harmPod->SetPOSTargetIndex ( 0 );
harmPod->LockPOSTarget();
break;
case 17:
harmPod->SetPOSTargetIndex ( 1 );
harmPod->LockPOSTarget();
break;
case 18:
harmPod->SetPOSTargetIndex ( 2 );
harmPod->LockPOSTarget();
break;
case 19:
harmPod->SetPOSTargetIndex ( 3 );
harmPod->LockPOSTarget();
break;
}
break;
case HarmTargetingPod::Handoff:
switch ( whichButton )
{
case 0:
harmPod->SetSubMode( HarmTargetingPod::HarmModeChooser );
pFCC->dropTrackCmd = TRUE; // drop target if switching HARM mode
break;
case 10:
case 11:
case 12:
case 13:
case 14:
MfdDrawable::PushButton(whichButton, whichMFD);
break;
}
break;
case HarmTargetingPod::FilterMode:
switch ( whichButton )
{
case 0:
harmPod->SetSubMode( HarmTargetingPod::HAS ); // Return right back to HAS
playerAC->SOIManager ( SimVehicleClass::SOI_WEAPON );
break;
case 10:
case 11:
case 12:
case 13:
case 14:
MfdDrawable::PushButton(whichButton, whichMFD);
break;
// Eache of this buttons sets a different filtering mode and getting back to HAS
case 19:
harmPod->SetFilterMode ( HarmTargetingPod::ALL );
harmPod->ResetHASTimer();
harmPod->SetSubMode( HarmTargetingPod::HAS );
playerAC->SOIManager ( SimVehicleClass::SOI_WEAPON );
break;
case 18:
harmPod->SetFilterMode ( HarmTargetingPod::HP );
harmPod->ResetHASTimer();
harmPod->SetSubMode( HarmTargetingPod::HAS );
playerAC->SOIManager ( SimVehicleClass::SOI_WEAPON );
break;
case 17:
harmPod->SetFilterMode ( HarmTargetingPod::HA );
harmPod->ResetHASTimer();
harmPod->SetSubMode( HarmTargetingPod::HAS );
playerAC->SOIManager ( SimVehicleClass::SOI_WEAPON );
break;
case 16:
harmPod->SetFilterMode ( HarmTargetingPod::LA );
harmPod->ResetHASTimer();
harmPod->SetSubMode( HarmTargetingPod::HAS );
playerAC->SOIManager ( SimVehicleClass::SOI_WEAPON );
break;
}
break;
}
}
}
void WpnMfdDrawable::OSBLabels(VirtualDisplay* display)
{
char tempstr[10] = "";
if(!Sms->Powered)
LabelButton (0, "STBY");
else
LabelButton (0, "OPER");
if(Sms->MavSubMode == SMSBaseClass::PRE)
sprintf(tempstr,"PRE");
else if(Sms->MavSubMode == SMSBaseClass::VIS)
sprintf(tempstr, "VIS");
else
sprintf(tempstr,"BORE");
LabelButton(1, tempstr);
if (g_bGreyMFD)
LabelButton(19, "GRAY", "OFF");
else
LabelButton(19, "GRAY", "ON");
// RV - Biker - Make FOV switching this dynamic
//if (mavDisplay && mavDisplay->CurFOV() > (3.5F * DTR))
float ZoomMin;
float ZoomMax;
if((MissileClass*)Sms->GetCurrentWeapon() && ((MissileClass*)Sms->GetCurrentWeapon())->GetEXPLevel() > 0 && ((MissileClass*)Sms->GetCurrentWeapon())->GetFOVLevel() > 0) {
ZoomMin = ((MissileClass*)Sms->GetCurrentWeapon())->GetFOVLevel();
ZoomMax = ((MissileClass*)Sms->GetCurrentWeapon())->GetEXPLevel();
}
else {
// This should work for old values
ZoomMin = 3.0f;
ZoomMax = 6.0f;
}
if (mavDisplay && mavDisplay->CurFOV() > 12.0f/(ZoomMax-(ZoomMax-ZoomMin)/2.0f) * DTR)
LabelButton (2, "FOV");
else
LabelButton (2, "EXP", NULL, 1);
if(Sms->curWeapon)
{
if(((MissileClass*)Sms->GetCurrentWeapon())->HOC)
LabelButton (4, "HOC");
else
LabelButton (4, "COH");
}
//Doc says this isn't there anymore in the real deal
//LabelButton (19, pFCC->subModeString);
char tmpStr[12];
float width = display->TextWidth("M ");
if (Sms->CurHardpoint() < 0)
return;
sprintf (tmpStr, "%d%s", Sms->NumCurrentWpn(), Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponData()->mnemonic);
ShiAssert(strlen(tmpStr) < sizeof (tmpStr));
LabelButton(5, tmpStr);
char *mode = "";
if(Sms->Powered && Sms->MavCoolTimer <= 0.0F)
{
switch (Sms->MasterArm())
{
case SMSBaseClass::Safe:
mode = "";
break;
case SMSBaseClass::Sim:
mode = "SIM";
break;
case SMSBaseClass::Arm:
mode = "RDY";
break;
}
}
float x, y;
GetButtonPos (12, &x, &y);
display->TextCenter(x, y + display->TextHeight(), mode);
BottomRow();
}
void WpnMfdDrawable::DrawRALT(VirtualDisplay* display)
{
if( TheHud && !(self->mFaults && self->mFaults->GetFault(FaultClass::ralt_fault))
&& self->af->platform->RaltReady() &&
TheHud->FindRollAngle(-TheHud->hat) && TheHud->FindPitchAngle(-TheHud->hat) )
{
float x,y = 0;
GetButtonPos(5, &x, &y);
y += display->TextHeight();
x -= 0.05F;
int RALT = (int)-TheHud->hat;
char tempstr[10] = "";
if(RALT > 9990)
RALT = 9990;
sprintf(tempstr, "%d", RALT);
display->TextRight(x, y, tempstr);
}
}
void WpnMfdDrawable::DrawHDPT(VirtualDisplay* display, SMSClass* Sms)
{
float leftEdge;
float width = display->TextWidth("M ");
float x = 0, y = 0;
GetButtonPos(8, &x, &y); // use button 8 as a reference (lower rhs)
y -= display->TextHeight()*2;
for(int i=0; i<Sms->NumHardpoints(); i++)
{
char c = HdptStationSym(i, Sms);
if (c == ' ') continue; // Don't bother drawing blanks.
Str[0] = c;
Str[1] = '\0';
if(i < 6)
{
leftEdge = -x + width * (i-1);
display->TextLeft(leftEdge, y, Str, (Sms->CurHardpoint() == i ? 2 : 0));
}
else
{
leftEdge = x - width * (Sms->NumHardpoints() - i - 1);
// Box the current station
display->TextRight(leftEdge, y, Str, (Sms->CurHardpoint() == i ? 2 : 0));
}
}
}
char WpnMfdDrawable::HdptStationSym(int n, SMSClass* Sms) // JPO new routine
{
if (Sms->hardPoint[n] == NULL) return ' '; // empty hp
if(Sms->hardPoint[n]->weaponCount <= 0) return ' '; //MI don't bother drawing empty hardpoints
if (Sms->StationOK(n) == FALSE) return 'F'; // malfunction on HP
if (Sms->hardPoint[n]->GetWeaponType() == Sms->curWeaponType)
return '0' + n; // exact match for weapon
if (Sms->hardPoint[n]->GetWeaponClass() == Sms->curWeaponClass)
return 'M'; // weapon of similar class
return ' ';
}
// RV - I-Hawk - Manage HARM modes display
void WpnMfdDrawable::HARMWpnMode()
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
pFCC = playerAC->Sms->Ownship()->GetFCC();
Sms = playerAC->Sms;
HarmTargetingPod* harmPod = (HarmTargetingPod*)FindSensor(Sms->Ownship(), SensorClass::HTS);
if ( pFCC->GetMasterMode() == FireControlComputer::AirGroundHARM ) // Varify we are in HARM FCC Master mode
{
switch ( harmPod->GetSubMode() ) // Check which Submode
{
case HarmTargetingPod::HarmModeChooser:
default:
LabelButton (17, "DL");
LabelButton (18, "HAS");
LabelButton (19, "POS");
BottomRow();
if ( !(playerAC->GetSOI() == SimVehicleClass::SOI_WEAPON) )
{
DWORD tempColor = display->Color();
display->SetColor(GetMfdColor(MFD_WHITY_GRAY));
display->TextCenter(0.0F, 0.6F, "NOT SOI");
display->SetColor(tempColor);
}
break;
case HarmTargetingPod::POS:
LabelButton (0, "POS");
LabelButton (1, "TBL1");
LabelButton (2, "PB");
LabelButton (4, "UFC");
LabelButton (8, "GS", "OF");
LabelButton (9, "T", "I");
harmPod->SetIntensity(GetIntensity());
harmPod->POSDisplay(display);
BottomRow();
if ( !(playerAC->GetSOI() == SimVehicleClass::SOI_WEAPON) )
{
DWORD tempColor = display->Color();
display->SetColor(GetMfdColor(MFD_WHITY_GRAY));
display->TextCenter(0.0F, 0.6F, "NOT SOI");
display->SetColor(tempColor);
}
break;
case HarmTargetingPod::HAS:
LabelButton (0, "HAS");
LabelButton (1, "TBL1");
switch ( harmPod->GetZoomMode() )
{
case HarmTargetingPod::Center:
LabelButton (2, "CTR");
break;
case HarmTargetingPod::Right:
LabelButton (2, "RT");
break;
case HarmTargetingPod::Left:
LabelButton (2, "LT");
break;
case HarmTargetingPod::Wide:
default:
LabelButton (2, "WIDE");
break;
}
LabelButton (3, "SRCH");
LabelButton (4, "UFC");
LabelButton (6, "R", "S");
LabelButton (9, "T", "I");
harmPod->SetIntensity(GetIntensity());
harmPod->HASDisplay(display);
BottomRow();
if ( !(playerAC->GetSOI() == SimVehicleClass::SOI_WEAPON) )
{
DWORD tempColor = display->Color();
display->SetColor(GetMfdColor(MFD_WHITY_GRAY));
display->TextCenter(0.0F, 0.52F, "NOT SOI");
display->SetColor(tempColor);
}
break;
case HarmTargetingPod::Handoff:
LabelButton (0, "HAS");
LabelButton (1, "TBL1");
switch ( harmPod->GetZoomMode() )
{
case HarmTargetingPod::Center:
LabelButton (2, "CTR");
break;
case HarmTargetingPod::Right:
LabelButton (2, "RT");
break;
case HarmTargetingPod::Left:
LabelButton (2, "LT");
break;
case HarmTargetingPod::Wide:
if ( harmPod->GetPreHandoffMode() == HarmTargetingPod::HAS )
{
LabelButton (2, "WIDE");
}
break;
}
LabelButton (4, "UFC");
LabelButton (9, "T", "I");
harmPod->SetIntensity(GetIntensity());
harmPod->HandoffDisplay(display);
BottomRow();
if ( !(playerAC->GetSOI() == SimVehicleClass::SOI_WEAPON) )
{
DWORD tempColor = display->Color();
display->SetColor(GetMfdColor(MFD_WHITY_GRAY));
display->TextCenter(0.0F, 0.6F, "NOT SOI");
display->SetColor(tempColor);
}
break;
case HarmTargetingPod::FilterMode:
LabelButton (0, "HAS");
float x,y;
int boxed = harmPod->GetFilterMode();
GetButtonPos(19, &x, &y);
display->TextLeft ( x, y, "ALL", boxed == HarmTargetingPod::ALL ? 2 : 0 );
GetButtonPos(18, &x, &y);
display->TextLeft ( x, y, "HP", boxed == HarmTargetingPod::HP ? 2 : 0 );
GetButtonPos(17, &x, &y);
display->TextLeft ( x, y, "HA", boxed == HarmTargetingPod::HA ? 2 : 0 );
GetButtonPos(16, &x, &y);
display->TextLeft ( x, y, "LA", boxed == HarmTargetingPod::LA ? 2 : 0 );
BottomRow();
if ( !(playerAC->GetSOI() == SimVehicleClass::SOI_WEAPON) )
{
DWORD tempColor = display->Color();
display->SetColor(GetMfdColor(MFD_WHITY_GRAY));
display->TextCenter(0.0F, 0.6F, "NOT SOI");
display->SetColor(tempColor);
}
break;
}
}
}
void WpnMfdDrawable::OffMode(VirtualDisplay* display)
{
float cX, cY = 0;
display->TextCenterVertical (0.0f, 0.2f, "WPN");
int ofont = display->CurFont();
display->SetFont(2);
display->TextCenterVertical (0.0f, 0.0f, "OFF");
display->SetFont(ofont);
theRadar->GetCursorPosition (&cX, &cY);
if( OTWDriver.pCockpitManager && OTWDriver.pCockpitManager->mpIcp && // JPG 14 Dec 03 - Added BE/ownship info
OTWDriver.pCockpitManager->mpIcp->ShowBullseyeInfo )
{
DrawBullseyeCircle(display, cX, cY);
}
else
{
DrawReference(MfdDisplay[OnMFD()]->GetOwnShip());
}
BottomRow();
} | 25.086331 | 171 | 0.642529 | IsraelyFlightSimulator |
054a8c0a1544705e8618a969a1adabfa5f7db3e9 | 1,709 | cpp | C++ | cpp/src/syscall/stat.cpp | pblaberge/TOT | d2cd110731d8f40fd8ed7652e6a4f1e065538edc | [
"MIT"
] | null | null | null | cpp/src/syscall/stat.cpp | pblaberge/TOT | d2cd110731d8f40fd8ed7652e6a4f1e065538edc | [
"MIT"
] | null | null | null | cpp/src/syscall/stat.cpp | pblaberge/TOT | d2cd110731d8f40fd8ed7652e6a4f1e065538edc | [
"MIT"
] | null | null | null | #include "cpp/syscall.hpp"
#include "cpp/src/syscall/errno_internal.hpp"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
namespace sys_call {
namespace {
void kernelStruct2StatT(Stat_t* to, struct stat const * from) {
to->Dev = from->st_dev;
to->Ino = from->st_ino;
to->Nlink = from->st_nlink;
to->Mode = from->st_mode;
to->Uid = from->st_uid;
to->Gid = from->st_gid;
to->Rdev = from->st_rdev;
to->Size = from->st_size;
to->Blksize = from->st_blksize;
to->Blocks = from->st_blocks;
to->Atim = Timespec{
.Sec = from->st_atim.tv_sec,
.NSec = from->st_atim.tv_nsec,
};
to->Mtim = Timespec{
.Sec = from->st_mtim.tv_sec,
.NSec = from->st_mtim.tv_nsec,
};
to->Ctim = Timespec{
.Sec = from->st_ctim.tv_sec,
.NSec = from->st_ctim.tv_nsec,
};
}
error::ptr fstatat(int dirfd, std::string const& path, Stat_t* s, int flags)
{
struct stat stat_kernel_struct;
if (int e = ::fstatat(dirfd, path.c_str(), &stat_kernel_struct, flags); e != 0) {
return internal::err_from_errno();
}
kernelStruct2StatT(s, &stat_kernel_struct);
return nullptr;
}
}
error::ptr fstat(int fd, Stat_t* s)
{
struct stat stat_kernel_struct;
if (int e = ::fstat(fd, &stat_kernel_struct); e != 0) {
return internal::err_from_errno();
}
kernelStruct2StatT(s, &stat_kernel_struct);
return nullptr;
}
error::ptr stat(std::string const& path, Stat_t* stat)
{
return fstatat(AT_FDCWD, path, stat, 0);
}
error::ptr lstat(std::string const& path, Stat_t* stat)
{
return fstatat(AT_FDCWD, path, stat, AT_SYMLINK_NOFOLLOW);
}
}
| 21.3625 | 85 | 0.625512 | pblaberge |
d72bdc0ab03429cc0f2e0505ab04b6dc375783b4 | 1,177 | hpp | C++ | src/entity_manager.hpp | Harrand/Asteroids-Topaz | ce549802b0360f2554f4f6189d6ca0a486c4c928 | [
"Apache-2.0"
] | null | null | null | src/entity_manager.hpp | Harrand/Asteroids-Topaz | ce549802b0360f2554f4f6189d6ca0a486c4c928 | [
"Apache-2.0"
] | null | null | null | src/entity_manager.hpp | Harrand/Asteroids-Topaz | ce549802b0360f2554f4f6189d6ca0a486c4c928 | [
"Apache-2.0"
] | null | null | null | #ifndef TOPAZASTEROIDS_ENTITY_MANAGER_HPP
#define TOPAZASTEROIDS_ENTITY_MANAGER_HPP
#include "core/listener.hpp"
#include "core/scene.hpp"
#include "sprite_collection.hpp"
#include "player.hpp"
#include "asteroid.hpp"
#include "bullet.hpp"
class EntityManager : public Scene
{
public:
EntityManager(Window& event_window);
bool has_player() const;
Player& spawn_player(Vector2F position, float rotation, Vector2F scale);
Asteroid& spawn_asteroid(Vector2F position, float rotation, Vector2F scale, Asteroid::Type type);
virtual void update(float delta) override;
bool screen_wrapping_enabled() const;
std::optional<Vector2I> get_screen_wapping_bounds() const;
void enable_screen_wrapping(Vector2I bounds);
void disable_screen_wrapping();
const SpriteCollection& get_sprite_collection() const;
protected:
void handle_screen_wrapping();
std::vector<Player*> get_players();
std::vector<Bullet*> get_bullets();
KeyListener key_listener;
MouseListener mouse_listener;
SpriteCollection sprite_collection;
Mesh quad;
std::optional<Vector2I> screen_wrapping_bounds;
};
#endif //TOPAZASTEROIDS_ENTITY_MANAGER_HPP
| 32.694444 | 101 | 0.771453 | Harrand |
d73a1c381cd67192014d0bcb120024a49df84fa1 | 6,712 | cp | C++ | Linux/Sources/Application/Preferences_Dialog/CLoggingOptionsDialog.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 | Linux/Sources/Application/Preferences_Dialog/CLoggingOptionsDialog.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 | Linux/Sources/Application/Preferences_Dialog/CLoggingOptionsDialog.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.
*/
// CLoggingOptionsDialog.cpp : implementation file
//
#include "CLoggingOptionsDialog.h"
#include <JXWindow.h>
#include <JXStaticText.h>
#include <JXTextButton.h>
#include <JXTextCheckbox.h>
#include <JXUpRect.h>
#include <jXGlobals.h>
#include <cassert>
/////////////////////////////////////////////////////////////////////////////
// CLoggingOptionsDialog dialog
CLoggingOptionsDialog::CLoggingOptionsDialog(JXDirector* supervisor)
: CDialogDirector(supervisor)
{
}
void CLoggingOptionsDialog::OnCreate()
{
// begin JXLayout
JXWindow* window = new JXWindow(this, 455,350, "");
assert( window != NULL );
SetWindow(window);
JXUpRect* obj1 =
new JXUpRect(window,
JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 455,350);
assert( obj1 != NULL );
mActivate =
new JXTextCheckbox("Logging is Enabled", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,15, 180,20);
assert( mActivate != NULL );
mIMAP =
new JXTextCheckbox("Log IMAP Connections", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,40, 180,20);
assert( mIMAP != NULL );
mPOP3 =
new JXTextCheckbox("Log POP3 Connections", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,60, 180,20);
assert( mPOP3 != NULL );
mSMTP =
new JXTextCheckbox("Log SMTP Connections", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,80, 180,20);
assert( mSMTP != NULL );
mIMSP =
new JXTextCheckbox("Log IMSP Connections", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,100, 180,20);
assert( mIMSP != NULL );
mACAP =
new JXTextCheckbox("Log ACAP Connections", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,120, 180,20);
assert( mACAP != NULL );
mHTTP =
new JXTextCheckbox("Log HTTP Connections", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,140, 180,20);
assert( mHTTP != NULL );
mOKBtn =
new JXTextButton("OK", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 365,315, 70,25);
assert( mOKBtn != NULL );
mOKBtn->SetShortcuts("^M");
mCancelBtn =
new JXTextButton("Cancel", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 275,315, 70,25);
assert( mCancelBtn != NULL );
mCancelBtn->SetShortcuts("^[");
mAuthentication =
new JXTextCheckbox("Show Authentication Details", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,165, 190,20);
assert( mAuthentication != NULL );
mPlayback =
new JXTextCheckbox("Log Disconnected Playback", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,190, 190,20);
assert( mPlayback != NULL );
mPlugins =
new JXTextCheckbox("Log Plugins", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,210, 180,20);
assert( mPlugins != NULL );
mFiltering =
new JXTextCheckbox("Log Filtering", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,230, 180,20);
assert( mFiltering != NULL );
mErrors =
new JXTextCheckbox("Log Errors", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,255, 180,20);
assert( mErrors != NULL );
mOverwrite =
new JXTextCheckbox("Overwrite Logs on Startup", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 20,280, 180,20);
assert( mOverwrite != NULL );
mClearBtn =
new JXTextButton("Clear Logs", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 140,315, 100,25);
assert( mClearBtn != NULL );
mFlushBtn =
new JXTextButton("Flush Logs", obj1,
JXWidget::kHElastic, JXWidget::kVElastic, 25,315, 100,25);
assert( mFlushBtn != NULL );
// end JXLayout
mLogs[CLog::eLogIMAP] = mIMAP;
mLogs[CLog::eLogPOP3] = mPOP3;
mLogs[CLog::eLogIMSP] = mIMSP;
mLogs[CLog::eLogACAP] = mACAP;
mLogs[CLog::eLogSMTP] = mSMTP;
mLogs[CLog::eLogHTTP] = mHTTP;
mLogs[CLog::eLogPlugin] = mPlugins;
mLogs[CLog::eLogFilters] = mFiltering;
mLogs[CLog::eLogExceptions] = mErrors;
window->SetTitle("Logging Options");
SetButtons(mOKBtn, mCancelBtn);
ListenTo(mFlushBtn);
ListenTo(mClearBtn);
}
/////////////////////////////////////////////////////////////////////////////
// CLoggingOptionsDialog message handlers
void CLoggingOptionsDialog::Receive(JBroadcaster* sender, const Message& message)
{
if (message.Is(JXButton::kPushed))
{
if (sender == mFlushBtn)
{
CLog::FlushLogs();
return;
}
else if (sender == mClearBtn)
{
CLog::ClearLogs();
return;
}
}
CDialogDirector::Receive(sender, message);
}
// Set options in dialog
void CLoggingOptionsDialog::SetOptions(const CLog::SLogOptions& options)
{
mActivate->SetState(JConvertToBoolean(options.mActivate));
for(unsigned long i = CLog::eLogTypeFirst; i < CLog::eLogTypeLast; i++)
mLogs[i]->SetState(JConvertToBoolean(options.mEnable[i]));
mAuthentication->SetState(JConvertToBoolean(options.mAuthentication));
mPlayback->SetState(JConvertToBoolean(options.mPlayback));
mOverwrite->SetState(JConvertToBoolean(options.mOverwrite));
}
// Get options from dialog
void CLoggingOptionsDialog::GetOptions(CLog::SLogOptions& options)
{
options.mActivate = mActivate->IsChecked();
for(unsigned long i = CLog::eLogTypeFirst; i < CLog::eLogTypeLast; i++)
options.mEnable[i] = mLogs[i]->IsChecked();
options.mAuthentication = mAuthentication->IsChecked();
options.mPlayback = mPlayback->IsChecked();
options.mOverwrite = mOverwrite->IsChecked();
}
bool CLoggingOptionsDialog::PoseDialog(CLog::SLogOptions& options)
{
bool result = false;
CLoggingOptionsDialog* dlog = new CLoggingOptionsDialog(JXGetApplication());
dlog->OnCreate();
dlog->SetOptions(options);
// Test for OK
if (dlog->DoModal(false) == kDialogClosed_OK)
{
dlog->GetOptions(options);
result = true;
dlog->Close();
}
return result;
}
| 29.699115 | 81 | 0.641836 | mulberry-mail |
d73e12dfed16c7028b3d00e8fdb7150e8b3d99ae | 19,042 | cc | C++ | src/devices/pci/testing/pci_protocol_fake_tests.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | src/devices/pci/testing/pci_protocol_fake_tests.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | src/devices/pci/testing/pci_protocol_fake_tests.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fuchsia/hardware/pci/cpp/banjo.h>
#include <lib/device-protocol/pci.h>
#include <lib/mmio/mmio.h>
#include <lib/zx/bti.h>
#include <lib/zx/object.h>
#include <lib/zx/vmo.h>
#include <zircon/errors.h>
#include <zxtest/zxtest.h>
#include "fuchsia/hardware/pci/c/banjo.h"
#include "src/devices/pci/testing/pci_protocol_fake.h"
class FakePciProtocolTests : public zxtest::Test {
protected:
void SetUp() final {
fake_pci_.reset();
pci_ = ddk::PciProtocolClient(&fake_pci_.get_protocol());
}
pci::FakePciProtocol& fake_pci() { return fake_pci_; }
ddk::PciProtocolClient& pci() { return pci_; }
private:
pci::FakePciProtocol fake_pci_;
ddk::PciProtocolClient pci_;
};
TEST_F(FakePciProtocolTests, SetCreateBar) {
zx::vmo vmo;
size_t size = 8193;
ASSERT_OK(zx::vmo::create(size, 0, &vmo));
fake_pci().SetBar(0, size, std::move(vmo));
fake_pci().CreateBar(1, size);
pci_bar_t bar;
pci().GetBar(0, &bar);
EXPECT_EQ(size, bar.size);
pci().GetBar(1, &bar);
EXPECT_EQ(size, bar.size);
}
TEST_F(FakePciProtocolTests, ResetDevice) {
uint32_t reset_cnt = 0;
ASSERT_EQ(reset_cnt++, fake_pci().GetResetCount());
ASSERT_OK(pci().ResetDevice());
ASSERT_EQ(reset_cnt++, fake_pci().GetResetCount());
ASSERT_OK(pci().ResetDevice());
ASSERT_EQ(reset_cnt++, fake_pci().GetResetCount());
}
TEST_F(FakePciProtocolTests, GetBti) {
zx::bti bti{};
ASSERT_OK(pci().GetBti(0, &bti));
zx_info_bti_t info;
// Verify it's a BTI at least.
ASSERT_OK(bti.get_info(ZX_INFO_BTI, &info, sizeof(info), /*actual_count=*/nullptr,
/*avail_count=*/nullptr));
}
TEST_F(FakePciProtocolTests, EnableBusMaster) {
// If enable has never been called there should be no value.
ASSERT_FALSE(fake_pci().GetBusMasterEnabled().has_value());
ASSERT_OK(pci().EnableBusMaster(true));
ASSERT_TRUE(fake_pci().GetBusMasterEnabled().value());
ASSERT_OK(pci().EnableBusMaster(false));
ASSERT_FALSE(fake_pci().GetBusMasterEnabled().value());
}
TEST_F(FakePciProtocolTests, GetDeviceInfo) {
pcie_device_info_t actual{};
pcie_device_info_t zeroed{};
ASSERT_OK(pci().GetDeviceInfo(&actual));
ASSERT_EQ(0, memcmp(&zeroed, &actual, sizeof(zeroed)));
pcie_device_info_t expected = {
.vendor_id = 0x1,
.device_id = 0x2,
.base_class = 0x3,
.sub_class = 0x4,
.program_interface = 0x5,
.revision_id = 0x6,
.bus_id = 0x7,
.dev_id = 0x8,
.func_id = 0x9,
};
fake_pci().SetDeviceInfo(expected);
ASSERT_OK(pci().GetDeviceInfo(&actual));
ASSERT_EQ(0, memcmp(&expected, &actual, sizeof(expected)));
// Did we update the config header to match the device structure?
uint8_t val8;
uint16_t val16;
ASSERT_OK(pci().ConfigRead16(PCI_CFG_VENDOR_ID, &val16));
ASSERT_EQ(expected.vendor_id, val16);
ASSERT_OK(pci().ConfigRead16(PCI_CFG_DEVICE_ID, &val16));
ASSERT_EQ(expected.device_id, val16);
ASSERT_OK(pci().ConfigRead8(PCI_CFG_REVISION_ID, &val8));
ASSERT_EQ(expected.revision_id, val8);
ASSERT_OK(pci().ConfigRead8(PCI_CFG_CLASS_CODE_BASE, &val8));
ASSERT_EQ(expected.base_class, val8);
ASSERT_OK(pci().ConfigRead8(PCI_CFG_CLASS_CODE_SUB, &val8));
ASSERT_EQ(expected.sub_class, val8);
ASSERT_OK(pci().ConfigRead8(PCI_CFG_CLASS_CODE_INTR, &val8));
ASSERT_EQ(expected.program_interface, val8);
}
TEST_F(FakePciProtocolTests, QueryIrqMode) {
uint32_t irq_cnt = 0;
ASSERT_EQ(ZX_ERR_NOT_SUPPORTED, pci().QueryIrqMode(PCI_IRQ_MODE_LEGACY, &irq_cnt));
ASSERT_EQ(ZX_ERR_NOT_SUPPORTED, pci().QueryIrqMode(PCI_IRQ_MODE_MSI, &irq_cnt));
ASSERT_EQ(ZX_ERR_NOT_SUPPORTED, pci().QueryIrqMode(PCI_IRQ_MODE_MSI_X, &irq_cnt));
fake_pci().AddLegacyInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_LEGACY, &irq_cnt));
ASSERT_EQ(1, irq_cnt);
// MSI supports interrupt configuration via powers of two, so ensure that we
// round down if not enough have been added.
fake_pci().AddMsiInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_MSI, &irq_cnt));
ASSERT_EQ(1, irq_cnt);
fake_pci().AddMsiInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_MSI, &irq_cnt));
ASSERT_EQ(2, irq_cnt);
fake_pci().AddMsiInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_MSI, &irq_cnt));
ASSERT_EQ(2, irq_cnt);
fake_pci().AddMsiInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_MSI, &irq_cnt));
ASSERT_EQ(4, irq_cnt);
// MSI-X doesn't care about alignment, so any value should work.
fake_pci().AddMsixInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_MSI_X, &irq_cnt));
ASSERT_EQ(1, irq_cnt);
fake_pci().AddMsixInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_MSI_X, &irq_cnt));
ASSERT_EQ(2, irq_cnt);
fake_pci().AddMsixInterrupt();
ASSERT_EQ(ZX_OK, pci().QueryIrqMode(PCI_IRQ_MODE_MSI_X, &irq_cnt));
ASSERT_EQ(3, irq_cnt);
}
TEST_F(FakePciProtocolTests, SetIrqMode) {
fake_pci().AddLegacyInterrupt();
fake_pci().AddMsiInterrupt();
fake_pci().AddMsiInterrupt();
fake_pci().AddMsiInterrupt();
fake_pci().AddMsiInterrupt();
fake_pci().AddMsixInterrupt();
fake_pci().AddMsixInterrupt();
pci_irq_mode_t mode = PCI_IRQ_MODE_LEGACY;
ASSERT_OK(pci().SetIrqMode(mode, 1));
ASSERT_EQ(1, fake_pci().GetIrqCount());
ASSERT_EQ(mode, fake_pci().GetIrqMode());
ASSERT_EQ(ZX_ERR_INVALID_ARGS, pci().SetIrqMode(mode, 2));
mode = PCI_IRQ_MODE_MSI;
ASSERT_OK(pci().SetIrqMode(mode, 1));
ASSERT_EQ(1, fake_pci().GetIrqCount());
ASSERT_EQ(mode, fake_pci().GetIrqMode());
ASSERT_OK(pci().SetIrqMode(mode, 2));
ASSERT_EQ(2, fake_pci().GetIrqCount());
ASSERT_EQ(mode, fake_pci().GetIrqMode());
ASSERT_EQ(ZX_ERR_INVALID_ARGS, pci().SetIrqMode(mode, 3));
ASSERT_EQ(2, fake_pci().GetIrqCount());
ASSERT_EQ(mode, fake_pci().GetIrqMode());
ASSERT_OK(pci().SetIrqMode(mode, 4));
ASSERT_EQ(4, fake_pci().GetIrqCount());
ASSERT_EQ(mode, fake_pci().GetIrqMode());
}
TEST_F(FakePciProtocolTests, ConfigureIrqMode) {
// The intent is to check that the IRQ modes are always favored in order of
// MSI-X > MSI > Legacy, but also choosing based on how many interrupts each
// mode is configured to provide.
pci_irq_mode_t mode;
fake_pci().AddLegacyInterrupt();
ASSERT_OK(pci().ConfigureIrqMode(1, &mode));
ASSERT_EQ(1, fake_pci().GetIrqCount());
ASSERT_EQ(PCI_IRQ_MODE_LEGACY, mode);
ASSERT_EQ(PCI_IRQ_MODE_LEGACY, fake_pci().GetIrqMode());
ASSERT_OK(pci().AckInterrupt());
mode = PCI_IRQ_MODE_LEGACY_NOACK;
ASSERT_OK(pci().SetIrqMode(mode, 1));
ASSERT_EQ(1, fake_pci().GetIrqCount());
ASSERT_EQ(PCI_IRQ_MODE_LEGACY_NOACK, mode);
ASSERT_EQ(PCI_IRQ_MODE_LEGACY_NOACK, fake_pci().GetIrqMode());
ASSERT_STATUS(ZX_ERR_BAD_STATE, pci().AckInterrupt());
fake_pci().AddMsiInterrupt();
ASSERT_OK(pci().ConfigureIrqMode(1, &mode));
ASSERT_EQ(1, fake_pci().GetIrqCount());
ASSERT_EQ(PCI_IRQ_MODE_MSI, mode);
ASSERT_EQ(PCI_IRQ_MODE_MSI, fake_pci().GetIrqMode());
ASSERT_STATUS(ZX_ERR_BAD_STATE, pci().AckInterrupt());
fake_pci().AddMsixInterrupt();
ASSERT_OK(pci().ConfigureIrqMode(1, &mode));
ASSERT_EQ(1, fake_pci().GetIrqCount());
ASSERT_EQ(PCI_IRQ_MODE_MSI_X, mode);
ASSERT_EQ(PCI_IRQ_MODE_MSI_X, fake_pci().GetIrqMode());
ASSERT_STATUS(ZX_ERR_BAD_STATE, pci().AckInterrupt());
// Ensure it will find the mode that supports the number necessary.
fake_pci().AddMsiInterrupt();
ASSERT_OK(pci().ConfigureIrqMode(2, &mode));
ASSERT_EQ(2, fake_pci().GetIrqCount());
ASSERT_EQ(PCI_IRQ_MODE_MSI, mode);
ASSERT_EQ(PCI_IRQ_MODE_MSI, fake_pci().GetIrqMode());
ASSERT_STATUS(ZX_ERR_BAD_STATE, pci().AckInterrupt());
fake_pci().AddMsixInterrupt();
ASSERT_OK(pci().ConfigureIrqMode(2, &mode));
ASSERT_EQ(2, fake_pci().GetIrqCount());
ASSERT_EQ(PCI_IRQ_MODE_MSI_X, mode);
ASSERT_EQ(PCI_IRQ_MODE_MSI_X, fake_pci().GetIrqMode());
ASSERT_STATUS(ZX_ERR_BAD_STATE, pci().AckInterrupt());
}
namespace {
// When interrupts are added to the fake a borrowed copy of the interrupt is
// returned for comparison by tests later. Its koid should match the koid of the
// duplicated handle returned by MapInterrupt.
template <typename T>
bool MatchKoids(const zx::unowned<T>& first, const zx::object<T>& second) {
zx_info_handle_basic finfo{}, sinfo{};
ZX_ASSERT(first->get_info(ZX_INFO_HANDLE_BASIC, &finfo, sizeof(finfo), nullptr, nullptr) ==
ZX_OK);
ZX_ASSERT(second.get_info(ZX_INFO_HANDLE_BASIC, &sinfo, sizeof(sinfo), nullptr, nullptr) ==
ZX_OK);
return finfo.koid == sinfo.koid;
}
} // namespace
TEST_F(FakePciProtocolTests, MapInterrupt) {
// One notable difference between this fake and the real PCI protocol is that
// it is an error to call SetIrqMode and switch modes if an existing MSI is
// mapped still. In the fake though, it's fine to do so. Switching IRQ modes
// is not something drivers do in practice, so it's fine if they encounter
// ZX_ERR_BAD_STATE at runtime if documentation details it.
zx::unowned_interrupt legacy = fake_pci().AddLegacyInterrupt();
zx::unowned_interrupt msi0 = fake_pci().AddMsiInterrupt();
zx::unowned_interrupt msi1 = fake_pci().AddMsiInterrupt();
zx::unowned_interrupt msix0 = fake_pci().AddMsixInterrupt();
zx::unowned_interrupt msix1 = fake_pci().AddMsixInterrupt();
zx::unowned_interrupt msix2 = fake_pci().AddMsixInterrupt();
zx::interrupt interrupt{};
uint32_t irq_cnt = 1;
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_LEGACY, irq_cnt));
ASSERT_OK(pci().MapInterrupt(0, &interrupt));
ASSERT_TRUE(MatchKoids(legacy, interrupt));
ASSERT_FALSE(MatchKoids(msi0, interrupt));
ASSERT_FALSE(MatchKoids(msi1, interrupt));
ASSERT_FALSE(MatchKoids(msix0, interrupt));
ASSERT_FALSE(MatchKoids(msix1, interrupt));
ASSERT_FALSE(MatchKoids(msix2, interrupt));
ASSERT_EQ(ZX_ERR_INVALID_ARGS, pci().MapInterrupt(irq_cnt, &interrupt));
interrupt.reset();
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_LEGACY_NOACK, irq_cnt));
ASSERT_OK(pci().MapInterrupt(0, &interrupt));
ASSERT_TRUE(MatchKoids(legacy, interrupt));
ASSERT_FALSE(MatchKoids(msi0, interrupt));
ASSERT_FALSE(MatchKoids(msi1, interrupt));
ASSERT_FALSE(MatchKoids(msix0, interrupt));
ASSERT_FALSE(MatchKoids(msix1, interrupt));
ASSERT_FALSE(MatchKoids(msix2, interrupt));
ASSERT_EQ(ZX_ERR_INVALID_ARGS, pci().MapInterrupt(irq_cnt, &interrupt));
interrupt.reset();
irq_cnt = 2;
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_MSI, irq_cnt));
ASSERT_OK(pci().MapInterrupt(0, &interrupt));
ASSERT_FALSE(MatchKoids(legacy, interrupt));
ASSERT_TRUE(MatchKoids(msi0, interrupt));
ASSERT_FALSE(MatchKoids(msi1, interrupt));
ASSERT_FALSE(MatchKoids(msix0, interrupt));
ASSERT_FALSE(MatchKoids(msix1, interrupt));
ASSERT_FALSE(MatchKoids(msix2, interrupt));
ASSERT_EQ(ZX_ERR_INVALID_ARGS, pci().MapInterrupt(irq_cnt, &interrupt));
interrupt.reset();
ASSERT_OK(pci().MapInterrupt(1, &interrupt));
ASSERT_FALSE(MatchKoids(legacy, interrupt));
ASSERT_FALSE(MatchKoids(msi0, interrupt));
ASSERT_TRUE(MatchKoids(msi1, interrupt));
ASSERT_FALSE(MatchKoids(msix0, interrupt));
ASSERT_FALSE(MatchKoids(msix1, interrupt));
ASSERT_FALSE(MatchKoids(msix2, interrupt));
interrupt.reset();
irq_cnt = 3;
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_MSI_X, irq_cnt));
ASSERT_OK(pci().MapInterrupt(0, &interrupt));
ASSERT_FALSE(MatchKoids(legacy, interrupt));
ASSERT_FALSE(MatchKoids(msi0, interrupt));
ASSERT_FALSE(MatchKoids(msi1, interrupt));
ASSERT_TRUE(MatchKoids(msix0, interrupt));
ASSERT_FALSE(MatchKoids(msix1, interrupt));
ASSERT_FALSE(MatchKoids(msix2, interrupt));
interrupt.reset();
ASSERT_OK(pci().MapInterrupt(1, &interrupt));
ASSERT_FALSE(MatchKoids(legacy, interrupt));
ASSERT_FALSE(MatchKoids(msi0, interrupt));
ASSERT_FALSE(MatchKoids(msi1, interrupt));
ASSERT_FALSE(MatchKoids(msix0, interrupt));
ASSERT_TRUE(MatchKoids(msix1, interrupt));
ASSERT_FALSE(MatchKoids(msix2, interrupt));
interrupt.reset();
ASSERT_OK(pci().MapInterrupt(2, &interrupt));
ASSERT_FALSE(MatchKoids(legacy, interrupt));
ASSERT_FALSE(MatchKoids(msi0, interrupt));
ASSERT_FALSE(MatchKoids(msi1, interrupt));
ASSERT_FALSE(MatchKoids(msix0, interrupt));
ASSERT_FALSE(MatchKoids(msix1, interrupt));
ASSERT_TRUE(MatchKoids(msix2, interrupt));
ASSERT_EQ(ZX_ERR_INVALID_ARGS, pci().MapInterrupt(irq_cnt, &interrupt));
}
TEST_F(FakePciProtocolTests, VerifyAllocatedMsis) {
fake_pci().AddLegacyInterrupt();
fake_pci().AddMsiInterrupt();
fake_pci().AddMsiInterrupt();
fake_pci().AddMsixInterrupt();
zx::interrupt zero, one;
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_MSI, 2));
ASSERT_OK(pci().MapInterrupt(0, &zero));
ASSERT_OK(pci().MapInterrupt(1, &one));
// Changing to other IRQ modes should be blocked because IRQ handles are outstanding.
ASSERT_EQ(ZX_ERR_BAD_STATE, pci().SetIrqMode(PCI_IRQ_MODE_LEGACY, 1));
ASSERT_EQ(ZX_ERR_BAD_STATE, pci().SetIrqMode(PCI_IRQ_MODE_LEGACY_NOACK, 1));
ASSERT_EQ(ZX_ERR_BAD_STATE, pci().SetIrqMode(PCI_IRQ_MODE_MSI_X, 1));
zero.reset();
one.reset();
// Now transitioning should work.
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_LEGACY, 1));
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_MSI_X, 1));
// Verify MSI-X works the same.
ASSERT_OK(pci().MapInterrupt(0, &zero));
ASSERT_EQ(ZX_ERR_BAD_STATE, pci().SetIrqMode(PCI_IRQ_MODE_LEGACY, 1));
zero.reset();
ASSERT_OK(pci().SetIrqMode(PCI_IRQ_MODE_LEGACY, 1));
}
TEST_F(FakePciProtocolTests, ConfigRW) {
auto config = fake_pci().GetConfigVmo();
// Verify the header space range. Reads can read the header [0, 63], but
// writes cannot. All IO must fit within the config space [0, 255].
uint8_t val8;
ASSERT_DEATH([&]() { pci().ConfigWrite8(0, 0xFF); });
ASSERT_NO_DEATH([&]() { pci().ConfigRead8(0, &val8); });
ASSERT_DEATH([&]() { pci().ConfigWrite8(PCI_CFG_HEADER_SIZE - 1, 0xFF); });
ASSERT_NO_DEATH([&]() { pci().ConfigRead8(PCI_CFG_HEADER_SIZE - 1, &val8); });
// The ensures we also verify that offset + read/write size is within bounds.
uint32_t val32;
ASSERT_DEATH([&]() { pci().ConfigWrite32(PCI_BASE_CONFIG_SIZE - 2, 0xFF); });
ASSERT_DEATH([&]() { pci().ConfigRead32(PCI_BASE_CONFIG_SIZE - 2, &val32); });
for (uint16_t off = PCI_CFG_HEADER_SIZE; off < PCI_BASE_CONFIG_SIZE; off++) {
uint8_t val8;
pci().ConfigWrite8(off, off);
pci().ConfigRead8(off, &val8);
ASSERT_EQ(off, val8);
ASSERT_OK(config->read(&val8, off, sizeof(val8)));
ASSERT_EQ(off, val8);
}
for (uint16_t off = PCI_CFG_HEADER_SIZE; off < PCI_BASE_CONFIG_SIZE - 1; off++) {
uint16_t val16;
pci().ConfigWrite16(off, off);
pci().ConfigRead16(off, &val16);
ASSERT_EQ(off, val16);
ASSERT_OK(config->read(&val16, off, sizeof(val16)));
ASSERT_EQ(off, val16);
}
for (uint16_t off = PCI_CFG_HEADER_SIZE; off < PCI_BASE_CONFIG_SIZE - 3; off++) {
uint32_t val32;
pci().ConfigWrite32(off, off);
pci().ConfigRead32(off, &val32);
ASSERT_EQ(off, val32);
ASSERT_OK(config->read(&val32, off, sizeof(val32)));
ASSERT_EQ(off, val32);
}
}
TEST_F(FakePciProtocolTests, GetBar) {
uint32_t page_size = zx_system_get_page_size();
zx::vmo vmo{};
// Verify the bar_id and bounds asserts.
ASSERT_OK(zx::vmo::create(page_size, 0, &vmo));
ASSERT_DEATH([&]() { fake_pci().SetBar(6, page_size, std::move(vmo)); });
ASSERT_OK(zx::vmo::create(page_size, 0, &vmo));
ASSERT_DEATH([&]() { fake_pci().SetBar(0, page_size + 1, std::move(vmo)); });
pci_bar_t bar{};
ASSERT_EQ(ZX_ERR_NOT_FOUND, pci().GetBar(0, &bar));
ASSERT_EQ(ZX_ERR_INVALID_ARGS, pci().GetBar(6, &bar));
uint32_t valid_bar = 3;
uint64_t bar_size = 256;
ASSERT_OK(zx::vmo::create(page_size, 0, &vmo));
ASSERT_NO_DEATH([&]() { fake_pci().SetBar(valid_bar, bar_size, std::move(vmo)); });
zx::unowned_vmo borrowed = fake_pci().GetBar(valid_bar);
ASSERT_OK(pci().GetBar(valid_bar, &bar));
// Verify that the VMO we got back wit hthe protocol method matches the setup
// and that the other fields are correct.
ASSERT_TRUE(MatchKoids(borrowed, *zx::unowned_vmo(bar.u.handle)));
ASSERT_EQ(valid_bar, bar.id);
ASSERT_EQ(bar_size, bar.size);
}
TEST_F(FakePciProtocolTests, MapMmio) {
const uint32_t bar_id = 0;
const uint64_t bar_size = 256;
zx::vmo vmo{};
ASSERT_OK(zx::vmo::create(bar_size, 0, &vmo));
fake_pci().SetBar(bar_id, bar_size, std::move(vmo));
zx::unowned_vmo borrow = fake_pci().GetBar(bar_id);
// Ensure that our fake implementation / backend for the BAR methods still works with
// the MapMmio helper method added to device-protocol.
ddk::Pci dp_pci(fake_pci().get_protocol());
std::optional<ddk::MmioBuffer> mmio = std::nullopt;
ASSERT_OK(dp_pci.MapMmio(bar_id, ZX_CACHE_POLICY_UNCACHED_DEVICE, &mmio));
ASSERT_TRUE(MatchKoids(borrow, *mmio->get_vmo()));
}
TEST_F(FakePciProtocolTests, Capabilities) {
// Try invalid capabilities.
ASSERT_DEATH([&]() { fake_pci().AddCapability(0, PCI_CFG_HEADER_SIZE, 16); });
ASSERT_DEATH([&]() {
fake_pci().AddCapability(PCI_CAP_ID_FLATTENING_PORTAL_BRIDGE + 1, PCI_CFG_HEADER_SIZE, 16);
});
// Try invalid locations.
ASSERT_DEATH([&]() { fake_pci().AddVendorCapability(PCI_CFG_HEADER_SIZE - 16, 32); });
ASSERT_DEATH([&]() { fake_pci().AddVendorCapability(PCI_BASE_CONFIG_SIZE - 16, 32); });
// Overlap tests.
ASSERT_NO_DEATH([&]() { fake_pci().AddVendorCapability(0xB0, 16); });
ASSERT_DEATH([&]() { fake_pci().AddVendorCapability(0xB0 + 8, 16); });
ASSERT_DEATH([&]() { fake_pci().AddVendorCapability(0xB0 - 8, 16); });
ASSERT_DEATH([&]() { fake_pci().AddVendorCapability(0xB0, 32); });
}
TEST_F(FakePciProtocolTests, PciGetFirstAndNextCapability) {
auto config = fake_pci().GetConfigVmo();
// The first capability should set up the capabilities pointer.
fake_pci().AddVendorCapability(0x50, 6);
uint8_t offset1 = 0;
ASSERT_OK(pci().GetFirstCapability(PCI_CAP_ID_VENDOR, &offset1));
uint8_t val;
config->read(&val, PCI_CFG_CAPABILITIES_PTR, sizeof(val));
ASSERT_EQ(0x50, val);
config->read(&val, offset1, sizeof(val));
ASSERT_EQ(PCI_CAP_ID_VENDOR, val);
config->read(&val, offset1 + 2, sizeof(val));
ASSERT_EQ(6, val);
// After adding the new capability we need to check that the previous next pointer was set up.
fake_pci().AddVendorCapability(0x60, 8);
config->read(&val, 0x51, sizeof(val));
ASSERT_EQ(val, 0x60);
// Can we find sequential capabilites, or different IDs?
uint8_t offset2 = 0;
ASSERT_OK(pci().GetNextCapability(PCI_CAP_ID_VENDOR, offset1, &offset2));
ASSERT_EQ(0x60, offset2);
fake_pci().AddPciExpressCapability(0x70);
fake_pci().AddVendorCapability(0xB0, 16);
ASSERT_OK(pci().GetFirstCapability(PCI_CAP_ID_PCI_EXPRESS, &offset1));
ASSERT_EQ(0x70, offset1);
ASSERT_OK(pci().GetNextCapability(PCI_CAP_ID_VENDOR, offset2, &offset1));
ASSERT_EQ(0xB0, offset1);
}
| 37.856859 | 96 | 0.725081 | csrpi |
d73e1e75239fd2e0b3ff57026a2c8c679c1b202d | 53,930 | cpp | C++ | vp/src/nvdla_cmod/csb_master/gen/NV_NVDLA_csb_master.cpp | amedoc/riscv-vp | 28caea322a6553caa1bbda99658982bedd29db4c | [
"MIT"
] | null | null | null | vp/src/nvdla_cmod/csb_master/gen/NV_NVDLA_csb_master.cpp | amedoc/riscv-vp | 28caea322a6553caa1bbda99658982bedd29db4c | [
"MIT"
] | null | null | null | vp/src/nvdla_cmod/csb_master/gen/NV_NVDLA_csb_master.cpp | amedoc/riscv-vp | 28caea322a6553caa1bbda99658982bedd29db4c | [
"MIT"
] | null | null | null | // ================================================================
// NVDLA Open Source Project
//
// Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the
// NVDLA Open Hardware License; Check "LICENSE" which comes with
// this distribution for more information.
// ================================================================
// File Name: NV_NVDLA_csb_master.cpp
#include "../../../nvdla_cmod/csb_master/gen/NV_NVDLA_csb_master.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include "../../../nvdla_cmod/include/log.h"
#define NVDLA_AMAP_BASE_MASK 0xFFFFF000
#define NVDLA_CSB_ADDR_COMPENSATION 0x00001000
USING_SCSIM_NAMESPACE(cmod)
USING_SCSIM_NAMESPACE(clib)
// Constructor
NV_NVDLA_csb_master::NV_NVDLA_csb_master( sc_module_name module_name )
:NV_NVDLA_csb_master_base(module_name),
csb2nvdla_wr_hack_bp(),
csb2nvdla_wr_hack("csb2nvdla_wr"),
serving_client_id(0xFFFFFFFF)
{
}
// Deconstructor
NV_NVDLA_csb_master::~NV_NVDLA_csb_master() {
}
inline void
NV_NVDLA_csb_master::nvdla2csb_b_transport(int ID, NV_MSDEC_csb2xx_16m_secure_be_lvl_t* payload, sc_time& delay) {
payload->pd.csb2xx_16m_secure_be_lvl.addr = payload->pd.csb2xx_16m_secure_be_lvl.addr << 2;
if (0xFFFFFFFF!=serving_client_id) {
// There is ongoing resquest, wait
}
// Both read request and none-posted write shall wait for response
if ( (0==payload->pd.csb2xx_16m_secure_be_lvl.write) || (0!=payload->pd.csb2xx_16m_secure_be_lvl.write && 0!=payload->pd.csb2xx_16m_secure_be_lvl.nposted) ) {
serving_client_id = payload->pd.csb2xx_16m_secure_be_lvl.addr & NVDLA_AMAP_BASE_MASK;
}
if (0!=payload->pd.csb2xx_16m_secure_be_lvl.write) {
// Write request
serving_client_id |= 0x1;
}
// Invoke client initiator
uint32_t base_addr = payload->pd.csb2xx_16m_secure_be_lvl.addr & NVDLA_AMAP_BASE_MASK;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, base_addr: 0x%x\x0A", base_addr));
switch (base_addr) {
case GLB_BASE:
csb2glb_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to GLB_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2glb_req_b_transport(&csb2glb_req_payload, delay);
break;
case GEC_BASE:
csb2gec_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to GEC_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2gec_req_b_transport(&csb2gec_req_payload, delay);
break;
case MCIF_BASE:
csb2mcif_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to MCIF_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2mcif_req_b_transport(&csb2mcif_req_payload, delay);
break;
case CVIF_BASE:
csb2cvif_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CVIF_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2cvif_req_b_transport(&csb2cvif_req_payload, delay);
break;
case BDMA_BASE:
csb2bdma_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to BDMA_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2bdma_req_b_transport(&csb2bdma_req_payload, delay);
break;
case CDMA_BASE:
csb2cdma_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CDMA_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2cdma_req_b_transport(&csb2cdma_req_payload, delay);
break;
case CSC_BASE:
csb2csc_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CSC_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2csc_req_b_transport(&csb2csc_req_payload, delay);
break;
case CMAC_A_BASE:
csb2cmac_a_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CMAC_A_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2cmac_a_req_b_transport(&csb2cmac_a_req_payload, delay);
break;
case CMAC_B_BASE:
csb2cmac_b_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CMAC_B_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2cmac_b_req_b_transport(&csb2cmac_b_req_payload, delay);
break;
case CACC_BASE:
csb2cacc_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CACC_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2cacc_req_b_transport(&csb2cacc_req_payload, delay);
break;
case SDP_RDMA_BASE:
csb2sdp_rdma_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to SDP_RDMA_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2sdp_rdma_req_b_transport(&csb2sdp_rdma_req_payload, delay);
break;
case SDP_BASE:
csb2sdp_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to SDP_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2sdp_req_b_transport(&csb2sdp_req_payload, delay);
break;
case PDP_RDMA_BASE:
csb2pdp_rdma_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to PDP_RDMA_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2pdp_rdma_req_b_transport(&csb2pdp_rdma_req_payload, delay);
break;
case PDP_BASE:
csb2pdp_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to PDP_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2pdp_req_b_transport(&csb2pdp_req_payload, delay);
break;
case CDP_RDMA_BASE:
csb2cdp_rdma_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CDP_RDMA_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2cdp_rdma_req_b_transport(&csb2cdp_rdma_req_payload, delay);
break;
case CDP_BASE:
csb2cdp_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to CDP_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2cdp_req_b_transport(&csb2cdp_req_payload, delay);
break;
case RBK_BASE:
csb2rbk_req_payload = *payload;
cslDebug((30, "NV_NVDLA_csb_master::nvdla2csb_b_transport, csb req to RBK_BASE, \x0A"));
cslDebug((30, "Addr: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.addr));
cslDebug((30, "Data: 0x%x\x0A", payload->pd.csb2xx_16m_secure_be_lvl.wdat));
cslDebug((30, "Is write: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.write)));
cslDebug((30, "nposted: 0x%x\x0A", uint32_t(payload->pd.csb2xx_16m_secure_be_lvl.nposted)));
csb2rbk_req_b_transport(&csb2rbk_req_payload, delay);
break;
default:
FAIL(("NV_NVDLA_csb_master::nvdla2csb_b_transport: Receiving an invalid csb address to nvdla sub-units. payload->pd.csb2xx_16m_secure_be_lvl.addr = 0x%x, base_addr=0x%x", payload->pd.csb2xx_16m_secure_be_lvl.addr, base_addr));
}
}
inline void
NV_NVDLA_csb_master::csb2nvdla_wr_hack_b_transport(NV_MSDEC_xx2csb_wr_erpt_t* payload, sc_time& delay) {
uint8_t *csb2nvdla_wr_hack_bp_byte_enable_ptr;
uint32_t payload_byte_size;
payload_byte_size = sizeof(NV_MSDEC_xx2csb_wr_erpt_t);
csb2nvdla_wr_hack_bp_byte_enable_ptr = new uint8_t[payload_byte_size];
memset(csb2nvdla_wr_hack_bp_byte_enable_ptr, 0xFF, payload_byte_size);
csb2nvdla_wr_hack_bp.set_data_ptr((unsigned char*) payload);
csb2nvdla_wr_hack_bp.set_data_length(payload_byte_size);
csb2nvdla_wr_hack_bp.set_byte_enable_ptr((unsigned char*)csb2nvdla_wr_hack_bp_byte_enable_ptr);
csb2nvdla_wr_hack_bp.set_byte_enable_length(payload_byte_size);
csb2nvdla_wr_hack_bp.set_command(tlm::TLM_WRITE_COMMAND);
csb2nvdla_wr_hack->b_transport(csb2nvdla_wr_hack_bp, delay);
delete[] csb2nvdla_wr_hack_bp_byte_enable_ptr;
// csb2nvdla_wr_hack_bp.set_data_ptr((unsigned char*) payload);
// csb2nvdla_wr_hack->b_transport(csb2nvdla_wr_hack_bp, delay);
}
inline void
NV_NVDLA_csb_master::glb2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::glb: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (GLB_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::glb: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::glb2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::glb2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::gec2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::gec: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (GEC_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::gec: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::gec2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::gec2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::mcif2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::mcif: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (MCIF_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::mcif: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::mcif2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::mcif2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::cvif2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::cvif: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CVIF_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::cvif: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cvif2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cvif2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::bdma2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::bdma: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (BDMA_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::bdma: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::bdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::bdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::cdma2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::cdma: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CDMA_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::cdma: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::csc2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::csc: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CSC_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::csc: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::csc2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::csc2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::cmac_a2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::cmac_a: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CMAC_A_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::cmac_a: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cmac_a2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cmac_a2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::cmac_b2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::cmac_b: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CMAC_B_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::cmac_b: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cmac_b2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cmac_b2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::cacc2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::cacc: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CACC_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::cacc: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cacc2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cacc2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::sdp_rdma2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::sdp_rdma: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (SDP_RDMA_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::sdp_rdma: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::sdp_rdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::sdp_rdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::sdp2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::sdp: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (SDP_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::sdp: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::sdp2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::sdp2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::pdp_rdma2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::pdp_rdma: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (PDP_RDMA_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::pdp_rdma: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::pdp_rdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::pdp_rdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::pdp2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::pdp: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (PDP_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::pdp: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::pdp2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::pdp2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::cdp_rdma2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::cdp_rdma: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CDP_RDMA_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::cdp_rdma: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cdp_rdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cdp_rdma2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::cdp2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::cdp: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (CDP_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::cdp: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cdp2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::cdp2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
inline void
NV_NVDLA_csb_master::rbk2csb_resp_b_transport(int ID, nvdla_xx2csb_resp_t* payload, sc_time& delay)
{
// uint8_t bit_iter;
// Check is nvdla waiting for a request
if (0xFFFFFFFF == serving_client_id) {
FAIL(("NV_NVDLA_csb_master::rbk: Client sends out a CSB response without receiving a CSB request."));
}
// Check base matches with serving_client_id
if (RBK_BASE != (serving_client_id & NVDLA_AMAP_BASE_MASK)) {
FAIL(("NV_NVDLA_csb_master::rbk: Client sends out a CSB response without receiving a CSB request."));
}
// if ((serving_client_id & 0x1)!=0) {}
if (XX2CSB_RESP_TAG_WRITE==payload->tag) {
// Write response, invoke csb2nvdla read response initiator socket
// Not use csb2nvdla_wr_hack_payload which is connected to dummy
// In TB, only csb2nvdla_payload is checked.
csb2nvdla_payload.error = payload->pd.xx2csb_wr_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_wr_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::rbk2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
// for (bit_iter = 0; bit_iter < 32; bit_iter++) {
// if ( (payload->pd.xx2csb_wr_erpt.error & (0x1<<bit_iter)) != 0x0 ) {
// csb2nvdla_wr[bit_iter] = true;
// } else {
// csb2nvdla_wr[bit_iter] = false;
// }
// }
// if (payload->pd.xx2csb_wr_erpt.error != 0x0) {
// csb2nvdla_wr[32] = true;
// } else {
// csb2nvdla_wr[32] = false;
// }
// csb2nvdla_wr[33] = true;
} else {
// Read response, invoke csb2nvdla read response initiator socket
csb2nvdla_payload.error = payload->pd.xx2csb_rd_erpt.error;
csb2nvdla_payload.pd.xx2csb.rdat = payload->pd.xx2csb_rd_erpt.rdat;
cslDebug((30, "NV_NVDLA_csb_master::rbk2csb_resp_b_transport. Err bit: 0x\x25x Data: 0x\x25x\x0A", uint32_t(csb2nvdla_payload.error), csb2nvdla_payload.pd.xx2csb.rdat));
csb2nvdla_b_transport(&csb2nvdla_payload, delay);
}
serving_client_id = 0xFFFFFFFF;
}
| 54.751269 | 238 | 0.649676 | amedoc |
d7505a6855f1f40480c143580281c2538eb1416f | 745 | cpp | C++ | Codeforces/1374D.cpp | hyturing/Competitve-Programming | 571da19ae5d17fdcf2b9a9956eaf5a6c5f7d27e8 | [
"MIT"
] | 5 | 2021-01-25T17:08:45.000Z | 2021-09-11T17:33:39.000Z | Codeforces/1374D.cpp | hyturing/Competitve-Programming | 571da19ae5d17fdcf2b9a9956eaf5a6c5f7d27e8 | [
"MIT"
] | null | null | null | Codeforces/1374D.cpp | hyturing/Competitve-Programming | 571da19ae5d17fdcf2b9a9956eaf5a6c5f7d27e8 | [
"MIT"
] | 1 | 2021-03-22T16:53:30.000Z | 2021-03-22T16:53:30.000Z | /* Author: hyturing - Hemant Kumar Yadav */
#include "bits/stdc++.h"
using namespace std;
#define endl "\n"
#define ll long long
const ll MOD = 1e9+7;
void solve(){
// code here
ll n, k;
cin >> n >> k;
vector<ll> a(n);
for(auto &x: a) cin >> x;
map<ll,ll> m;
for(auto x: a){
if(x%k > 0) m[x%k]++;
}
ll mx = -1, cnt=0;
for(auto x: m){
if(x.first > mx){mx = x.first; cnt = x.second;}
}
mx = 0;
ll num=1;
for(auto x: m){
if(x.second > mx){mx = x.second; num = x.first;}
}
cout << k*(mx-1)+k-num+1 << endl;
return;
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int tc = 1;
cin >> tc;
for(int i = 1; i <= tc; i++){
// cout << "Case #" << i << ": ";
solve();
}
return 0;
}
| 14.056604 | 50 | 0.520805 | hyturing |
d7518cd83fad2897bd1a309175f77bba2f3df5e0 | 4,255 | cpp | C++ | src/mplsh.cpp | girke-lab/eiR-release | 84754b4573b1c1aabc65cbdabcfe7867c6b415a2 | [
"BSL-1.0"
] | null | null | null | src/mplsh.cpp | girke-lab/eiR-release | 84754b4573b1c1aabc65cbdabcfe7867c6b415a2 | [
"BSL-1.0"
] | null | null | null | src/mplsh.cpp | girke-lab/eiR-release | 84754b4573b1c1aabc65cbdabcfe7867c6b415a2 | [
"BSL-1.0"
] | null | null | null | /*
Copyright (C) 2008 Wei Dong <wdong@princeton.edu>. All Rights Reserved.
This file is part of LSHKIT.
LSHKIT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LSHKIT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LSHKIT. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <queue>
#include <lshkit/mplsh.h>
#include <stdlib.h>
namespace lshkit
{
ProbeSequenceTemplates __probeSequenceTemplates(Probe::MAX_M, Probe::MAX_T);
void GenExpectScores (ProbeSequence &seq, unsigned M)
{
assert(M <= sizeof(seq[0].mask)* 8);
seq.resize(2 * M);
for (unsigned l = 0; l < M; ++l)
{
unsigned r = 2 * M - l - 1;
seq[l].mask = seq[r].mask = seq[r].shift = leftshift(l);
seq[l].shift = 0;
seq[l].reserve = seq[r].reserve = 0;
float delta = (l + 1.0) / (M + 1.0) * 0.5;
seq[l].score = (l + 1.0) * (l + 2.0) / (M + 1.0) / (M + 2.0) * 0.25;
seq[r].score = 1.0 - 2.0 * delta + seq[l].score;
}
}
class ProbeGT
{
public:
bool operator () (const Probe &p1, const Probe &p2) const
{
return p2 < p1;
}
};
void GenProbeSequenceTemplate (ProbeSequence &seq, unsigned M, unsigned T)
{
ProbeSequence scores;
GenExpectScores(scores, M);
assert(T > 0);
std::priority_queue<Probe, std::vector<Probe>, ProbeGT> heap;
Probe init;
init.mask = init.shift = 0;
init.score = 0;
init.reserve = 0;
heap.push(init);
seq.clear();
for (;;)
{
if (heap.empty()) break;
seq.push_back(heap.top());
if (seq.size() == T) break;
Probe shift = heap.top();
heap.pop();
for (unsigned next = shift.reserve; next < 2 * M; ++next)
{
if (!shift.conflict(scores[next]))
{
Probe tmp = shift + scores[next];
tmp.reserve = next + 1;
heap.push(tmp);
}
}
}
}
void MultiProbeLsh::genProbeSequence (Domain obj, std::vector<unsigned>
&seq, unsigned T) const
{
ProbeSequence scores;
std::vector<unsigned> base;
scores.resize(2 * lsh_.size());
base.resize(lsh_.size());
for (unsigned i = 0; i < lsh_.size(); ++i)
{
float delta;
base[i] = Super::lsh_[i](obj, &delta);
scores[2*i].mask = i;
scores[2*i].reserve = 1; // direction
scores[2*i].score = delta;
scores[2*i+1].mask = i;
scores[2*i+1].reserve = unsigned(-1);
scores[2*i+1].score = 1.0 - delta;
}
std::sort(scores.begin(), scores.end());
ProbeSequence &tmpl = __probeSequenceTemplates[lsh_.size()];
seq.clear();
for (ProbeSequence::const_iterator it = tmpl.begin();
it != tmpl.end(); ++it)
{
if (seq.size() == T) break;
const Probe &probe = *it;
unsigned hash = 0;
for (unsigned i = 0; i < lsh_.size(); ++i)
{
unsigned h = base[scores[i].mask];
if (probe.mask & leftshift(i))
{
if (probe.shift & leftshift(i))
{
h += scores[i].reserve;
}
else
{
h += unsigned(-1) * scores[i].reserve;
}
}
hash += h * a_[scores[i].mask];
}
seq.push_back(hash % H_);
}
}
}
| 30.177305 | 80 | 0.491657 | girke-lab |
d751eddeff02ae9cf2ed4389358f02a352047270 | 11,597 | cpp | C++ | code/source/util/str8.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | 12 | 2015-01-12T00:19:20.000Z | 2021-08-05T10:47:20.000Z | code/source/util/str8.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | code/source/util/str8.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | #include "str8.hpp"
#include "ensure.hpp"
#include "debug/print.hpp"
#include "util/dyn_array.hpp"
#include <cstring>
#include <cstdio>
#include <cstdarg>
#include <cstdlib>
#include <algorithm>
#include <utf8.h>
namespace clover {
namespace util {
namespace {
/// @see http://en.wikipedia.org/wiki/UTF-8#Description
/// This uses RFC 3629, max 4-byte sequences
/// @param unsafeStr Null-terminated string, hopefully in UTF-8 encoding
std::size_t toUtf8(const char* unsafeStr, std::string& output){
const unsigned char* it = reinterpret_cast<const unsigned char*>(unsafeStr);
std::size_t charCount = 0;
while (*it) {
if (*it < 0x80) {
output += *it;
++it;
} else if (((it[0] & 0xe0) == 0xc0) && ((it[1] & 0xc0) == 0x80)) {
output.append(it, it+2);
it += 2;
} else if (((it[0] & 0xf0) == 0xe0) && ((it[1] & 0xc0) == 0x80) && ((it[2] & 0xc0) == 0x80)) {
output.append(it, it+3);
it += 3;
} else if (((it[0] & 0xf8) == 0xf0) && ((it[1] & 0xc0) == 0x80) &&
((it[2] & 0xc0) == 0x80) && ((it[3] & 0xc0) == 0x80)) {
output.append(it, it+4);
it += 4;
} else {
// This isn't valid UTF-8 character, treat it as Windows-1252 or ~Latin1/ISO-8859-15
// These rules were built with ruby, running something similar to:
// puts ((128..255).to_a-[129,141,143,144,157]).map{|c| "#{c.to_s(16)}: "+c.chr.encode("UTF-8", "windows-1252").bytes.to_a.inspect}.join("\n")
if (*it < 0xa0) {
static const char * table[] = {
"\xe2\x82\xac",
"",
"\xe2\x80\x9a",
"\xc6\x92",
"\xe2\x80\x9e",
"\xe2\x80\xa6",
"\xe2\x80\xa0",
"\xe2\x80\xa1",
"\xcb\x86",
"\xe2\x80\xb0",
"\xc5\xa0",
"\xe2\x80\xb9",
"\xc5\x92",
"",
"\xc5\xbd",
"",
"",
"\xe2\x80\x98",
"\xe2\x80\x99",
"\xe2\x80\x9c",
"\xe2\x80\x9d",
"\xe2\x80\xa2",
"\xe2\x80\x93",
"\xe2\x80\x94",
"\xcb\x9c",
"\xe2\x84\xa2",
"\xc5\xa1",
"\xe2\x80\xba",
"\xc5\x93",
""
"\xc5\xbe",
"\xc5\xb8"
};
debug_ensure(*it-0x80 >= 0);
const char* conv = table[*it-0x80];
int len = strlen(conv);
/// According to http://en.wikipedia.org/wiki/Windows-1252#Codepage_layout
/// empty string in the table are illegal chars. We will just remove these from input
if (len == 0)
continue;
output.append(conv);
it += len;
} else if (*it < 0xc0) {
output += 0xc2;
output += *it;
} else {
output += 0xc3;
output += *it - 0x40;
}
++it;
}
++charCount;
}
return charCount;
}
std::size_t encodeCodePoint(uint32 maybeUnicode, char u[4]){
/// @todo remove utf8.h dependency and code this faster, also use Windows-1252 conversion like toUtf8
try {
char* end = utf8::append(maybeUnicode, u);
return end - u;
} catch (utf8::invalid_code_point&) {
return 0;
}
}
} // anonymous
Str8::Str8() : ascii(true), strLength(0){
}
Str8::Str8(const std::string& str){
strLength = toUtf8(str.c_str(), data);
ascii = strLength == data.size();
}
Str8::Str8(const char8 *buf){
strLength = toUtf8(buf, data);
ascii = strLength == data.size();
}
Str8& Str8::operator()(const char8* buf, ...){
va_list arg_list;
va_start(arg_list, buf);
setFormattedArgList(buf, arg_list);
va_end(arg_list);
return *this;
}
Str8& Str8::operator<<(int32 c){
char8 buf[11];
sprintf(buf, "%d", c);
data += buf;
strLength += strlen(buf);
return *this;
}
Str8& Str8::operator=(const char8* buf){
data.clear();
strLength = toUtf8(buf, data);
ascii = strLength == data.size();
return *this;
}
Str8& Str8::operator+=(const char8* buf){
strLength += toUtf8(buf, data);
ascii = strLength == data.size();
return *this;
}
Str8& Str8::operator+=(const Str8& str){
data += str.data;
strLength += str.strLength;
ascii = ascii && str.ascii;
return *this;
}
Str8 Str8::operator+(const char8* buf) const{
Str8 str= *this;
str += buf;
return str;
}
Str8 Str8::operator+(const Str8& str) const{
Str8 cpy(*this);
cpy += str;
return cpy;
}
Str8& Str8::operator+=(uint32 unicode){
char u[4];
const std::size_t charSize = encodeCodePoint(unicode, u);
++strLength;
data.append(u, u + charSize);
ascii = strLength == data.size();
return *this;
}
void Str8::setFormattedArgList(const char8* buf, va_list arg_list){
ensure(buf);
if (*buf == '\0'){
clear();
return;
}
const uint32 format_buf_size= 10000;
// Can't be static because accessed from threads
char8 format_buf[format_buf_size];
vsnprintf(format_buf, format_buf_size, buf, arg_list);
*this = format_buf;
}
const char* Str8::cStr() const{
return data.c_str();
}
uint32 Str8::operator[](uint32 i) const {
ensure(i < strLength && i >= 0);
if (ascii)
return data[i];
auto it = data.begin();
utf8::unchecked::advance(it, i);
return utf8::unchecked::peek_next(it);
}
void Str8::resize(uint32 s, uint32 unicode){
if (strLength > s) {
if (ascii) {
data.resize(s);
strLength = s;
} else {
auto it = data.begin();
utf8::unchecked::advance(it, s);
data.resize(it - data.begin());
strLength = s;
ascii = strLength == data.size();
}
} else if (strLength < s) {
char u[4];
const std::size_t charSize = encodeCodePoint(unicode, u);
if (charSize == 0) return;
const int newChars = s - strLength;
const std::size_t b = data.size();
data.resize(data.size() + newChars * charSize);
for (std::size_t i = 0, e = newChars * charSize; i < e; ++i)
data[b+i] = u[i % charSize];
strLength = s;
ascii = strLength == data.size();
}
}
int32 Str8::find(uint32 unicode, int32 pos) const{
if (unicode < 0x80 && ascii)
return data.find(unicode, pos);
auto it = data.begin(), end = data.end();
if (pos >= int32(strLength))
return -1;
utf8::unchecked::advance(it, pos);
for (; it < end; ++pos) {
if (utf8::unchecked::next(it) == unicode)
return pos;
}
return -1;
}
int32 Str8::findLast(uint32 unicode) const {
if (unicode < 0x80 && ascii)
return data.find_last_of(unicode);
auto it = data.begin(), end = data.end();
int32 match = -1;
for (int pos = 0; it < end; ++pos) {
if (utf8::unchecked::next(it) == unicode)
match = pos;
}
return match;
}
void Str8::erase(uint32 pos, uint32 count){
ensure(pos < strLength);
ensure_msg(pos + count <= strLength, "Pos: %i, count: %i, strLength: %i", pos, count, strLength);
ensure(count > 0);
if (ascii) {
data.erase(pos, count);
strLength = data.size();
return;
}
auto it = data.begin();
utf8::unchecked::advance(it, pos);
auto end = it;
utf8::unchecked::advance(end, count);
data.erase(it, end);
strLength -= count;
ascii = strLength == data.size();
}
Str8 Str8::endNewlineErased() const {
Str8 ret= *this;
if (!ret.empty() && ret[ret.length() - 1] == '\n'){
ret.erase(ret.length() - 1, 1); // Erase newline at the end
}
return (ret);
}
void Str8::insert(uint32 pos, uint32 unicode, uint32 count){
ensure(pos < strLength);
ensure(count > 0);
auto it = data.begin();
if (ascii)
it += count;
else
utf8::unchecked::advance(it, pos);
char u[4];
const std::size_t charSize = encodeCodePoint(unicode, u);
if (charSize == 0) return;
auto offset = it - data.begin();
data.insert(it, count*charSize, u[0]);
if (charSize > 1)
for (uint32 i = offset, j = 0; i < offset + count*charSize; ++i, ++j)
data[i] = u[j % charSize];
strLength += count;
ascii = strLength == data.size();
}
bool Str8::contains(const Str8& other, bool notice_capitals){
if (other.length() > length()) return false;
if (!notice_capitals){
return lowerCased().contains(other.lowerCased());
}
uint32 match= 0;
for(uint32 i=0; length() - i >= other.length() - match &&
i < length() &&
match < other.length(); ++i){
if ((*this)[i] == other[match]){
++match;
}
else {
uint32 prev= match;
match= 0;
if (prev > 0){
ensure(i >= match);
// Go backwards
i -= prev;
continue;
}
}
}
return match == other.length();
}
Str8 Str8::upperCased() const {
Str8 ret= *this;
std::transform(ret.data.begin(), ret.data.end(), ret.data.begin(), ::toupper);
return (ret);
}
Str8 Str8::lowerCased() const {
Str8 ret= *this;
std::transform(ret.data.begin(), ret.data.end(), ret.data.begin(), ::tolower);
return (ret);
}
util::DynArray<Str8> Str8::splitted(uint32 unicode_separator, SizeType count) const {
/// @todo Change to work really with unicodes
util::DynArray<Str8> ret;
bool last_was_separator= false;
Str8 accum, comp_accum;
for (auto it= data.begin(); it != data.end(); ++it){
last_was_separator= false;
if ((uint32)*it == unicode_separator){
comp_accum += *it;
}
else {
accum += comp_accum;
accum += *it;
comp_accum.clear();
}
if (comp_accum.length() == count){
comp_accum.clear();
ret.pushBack(accum);
accum.clear();
last_was_separator= true;
}
}
if (!accum.empty())
ret.pushBack(accum);
if (last_was_separator)
ret.pushBack(Str8());
return (ret);
}
SizeType Str8::count(uint32 unicode) const {
if (ascii) {
if (unicode >= 0x80)
return 0;
char asciiChar = (char)unicode;
return std::count(data.begin(), data.end(), asciiChar);
}
SizeType count= 0;
for (auto it = data.begin(), end = data.end(); it != end;)
if (utf8::unchecked::next(it) == unicode)
++count;
return count;
}
int Str8::replace(uint32 from, uint32 to) {
int replaces = 0;
// ascii replace is easy to do without reallocating
if (from < 0x80 && to < 0x80) {
if (ascii) {
// std::replace doesn't return the number of replaces
for (auto it = data.begin(), end = data.end(); it != end; ++it) {
if (*it == char(from)) {
*it = to;
++replaces;
}
}
} else {
for (auto it = data.begin(), end = data.end(); it != end;) {
if (*it == char(from)) {
*it++ = to;
++replaces;
} else {
utf8::unchecked::next(it);
}
}
}
} else {
Str8 tmp;
for (auto it = data.begin(), end = data.end(); it != end; ) {
uint32 c = utf8::unchecked::next(it);
if (c == from) {
tmp += to;
++replaces;
} else {
tmp += c;
}
}
*this = tmp;
}
return replaces;
}
Str8 Str8::toUnixNewlines() const {
Str8 out;
out.data.reserve(data.size());
char prev = '\0';
for (auto it = data.begin(), end = data.end(); it != end;) {
uint32 c = utf8::unchecked::next(it);
if (c == '\r') {
if (prev == '\n') {
prev = '\0';
continue;
}
out += '\n';
prev = c;
} else if (c == '\n') {
if (prev == '\r') {
prev = '\0';
continue;
}
out += '\n';
prev = c;
} else {
out += c;
prev = '\0';
}
}
return out;
}
Str8 Str8::substr(std::size_t pos, std::size_t count) const {
if (ascii) {
Str8 tmp;
tmp.ascii = true;
tmp.data = data.substr(pos, count);
tmp.strLength = tmp.data.length();
return tmp;
}
if (pos > strLength)
throw std::out_of_range("Str8 substr pos > strLength");
if (pos == strLength)
return Str8();
// if count is npos, it will overflow with pos + count
if (count >= strLength || pos + count >= strLength)
count = strLength - pos;
auto it = data.begin();
utf8::unchecked::advance(it, pos);
auto end = it;
utf8::unchecked::advance(end, count);
Str8 tmp;
tmp.data = std::string(it, end);
tmp.strLength = count;
tmp.ascii = count == tmp.data.length();
return tmp;
}
Str8 Str8::format(const char8* buf, ...){
Str8 tmp;
va_list arg_list;
va_start(arg_list, buf);
tmp.setFormattedArgList(buf, arg_list);
va_end(arg_list);
return tmp;
}
} // util
} // clover
| 21.009058 | 146 | 0.59386 | crafn |
d752799e57a44afeea2320034791d6f3bf904469 | 9,927 | hpp | C++ | windows/include/boost/gil/bit_aligned_pixel_iterator.hpp | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | 6 | 2015-12-29T07:21:01.000Z | 2020-05-29T10:47:38.000Z | external/windows/boost/include/boost/gil/bit_aligned_pixel_iterator.hpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | null | null | null | external/windows/boost/include/boost/gil/bit_aligned_pixel_iterator.hpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | null | null | null | /*
Copyright 2005-2007 Adobe Systems Incorporated
Use, modification and distribution are 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).
See http://opensource.adobe.com/gil for most recent version including documentation.
*/
/*************************************************************************************************/
#ifndef GIL_BIT_ALIGNED_PIXEL_ITERATOR_HPP
#define GIL_BIT_ALIGNED_PIXEL_ITERATOR_HPP
////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief A model of a heterogeneous pixel that is not byte aligned. Examples are bitmap (1-bit pixels) or 6-bit RGB (222)
/// \author Lubomir Bourdev and Hailin Jin \n
/// Adobe Systems Incorporated
/// \date 2005-2007 \n Last updated on September 28, 2006
///
////////////////////////////////////////////////////////////////////////////////////////
#include <functional>
#include <boost/iterator/iterator_facade.hpp>
#include "gil_config.hpp"
#include "bit_aligned_pixel_reference.hpp"
#include "pixel_iterator.hpp"
namespace boost { namespace gil {
/// \defgroup PixelIteratorNonAlignedPixelIterator bit_aligned_pixel_iterator
/// \ingroup PixelIteratorModel
/// \brief An iterator over non-byte-aligned pixels. Models PixelIteratorConcept, PixelBasedConcept, MemoryBasedIteratorConcept, HasDynamicXStepTypeConcept
////////////////////////////////////////////////////////////////////////////////////////
/// \brief An iterator over non-byte-aligned pixels. Models PixelIteratorConcept, PixelBasedConcept, MemoryBasedIteratorConcept, HasDynamicXStepTypeConcept
///
/// An iterator over pixels that correspond to non-byte-aligned bit ranges. Examples of such pixels are single bit grayscale pixel, or a 6-bit RGB 222 pixel.
///
/// \ingroup PixelIteratorNonAlignedPixelIterator PixelBasedModel
template <typename NonAlignedPixelReference>
struct bit_aligned_pixel_iterator : public iterator_facade<bit_aligned_pixel_iterator<NonAlignedPixelReference>,
typename NonAlignedPixelReference::value_type,
random_access_traversal_tag,
const NonAlignedPixelReference,
typename NonAlignedPixelReference::bit_range_t::difference_type> {
private:
typedef iterator_facade<bit_aligned_pixel_iterator<NonAlignedPixelReference>,
typename NonAlignedPixelReference::value_type,
random_access_traversal_tag,
const NonAlignedPixelReference,
typename NonAlignedPixelReference::bit_range_t::difference_type> parent_t;
template <typename Ref> friend struct bit_aligned_pixel_iterator;
typedef typename NonAlignedPixelReference::bit_range_t bit_range_t;
public:
typedef typename parent_t::difference_type difference_type;
typedef typename parent_t::reference reference;
bit_aligned_pixel_iterator() {}
bit_aligned_pixel_iterator(const bit_aligned_pixel_iterator& p) : _bit_range(p._bit_range) {}
bit_aligned_pixel_iterator& operator=(const bit_aligned_pixel_iterator& p) { _bit_range=p._bit_range; return *this; }
template <typename Ref> bit_aligned_pixel_iterator(const bit_aligned_pixel_iterator<Ref>& p) : _bit_range(p._bit_range) {}
bit_aligned_pixel_iterator(reference* ref) : _bit_range(ref->bit_range()) {}
explicit bit_aligned_pixel_iterator(typename bit_range_t::byte_t* data, int bit_offset=0) : _bit_range(data,bit_offset) {}
/// For some reason operator[] provided by iterator_adaptor returns a custom class that is convertible to reference
/// We require our own reference because it is registered in iterator_traits
reference operator[](difference_type d) const { bit_aligned_pixel_iterator it=*this; it.advance(d); return *it; }
reference operator->() const { return **this; }
const bit_range_t& bit_range() const { return _bit_range; }
bit_range_t& bit_range() { return _bit_range; }
private:
bit_range_t _bit_range;
BOOST_STATIC_CONSTANT(int, bit_size = NonAlignedPixelReference::bit_size);
friend class boost::iterator_core_access;
reference dereference() const { return NonAlignedPixelReference(_bit_range); }
void increment() { ++_bit_range; }
void decrement() { --_bit_range; }
void advance(difference_type d) { _bit_range.bit_advance(d*bit_size); }
difference_type distance_to(const bit_aligned_pixel_iterator& it) const { return _bit_range.bit_distance_to(it._bit_range) / bit_size; }
bool equal(const bit_aligned_pixel_iterator& it) const { return _bit_range==it._bit_range; }
};
template <typename NonAlignedPixelReference>
struct const_iterator_type<bit_aligned_pixel_iterator<NonAlignedPixelReference> > {
typedef bit_aligned_pixel_iterator<typename NonAlignedPixelReference::const_reference> type;
};
template <typename NonAlignedPixelReference>
struct iterator_is_mutable<bit_aligned_pixel_iterator<NonAlignedPixelReference> > : public mpl::bool_<NonAlignedPixelReference::is_mutable> {};
template <typename NonAlignedPixelReference>
struct is_iterator_adaptor<bit_aligned_pixel_iterator<NonAlignedPixelReference> > : public mpl::false_ {};
/////////////////////////////
// PixelBasedConcept
/////////////////////////////
template <typename NonAlignedPixelReference>
struct color_space_type<bit_aligned_pixel_iterator<NonAlignedPixelReference> > : public color_space_type<NonAlignedPixelReference> {};
template <typename NonAlignedPixelReference>
struct channel_mapping_type<bit_aligned_pixel_iterator<NonAlignedPixelReference> > : public channel_mapping_type<NonAlignedPixelReference> {};
template <typename NonAlignedPixelReference>
struct is_planar<bit_aligned_pixel_iterator<NonAlignedPixelReference> > : public is_planar<NonAlignedPixelReference> {}; // == false
/////////////////////////////
// MemoryBasedIteratorConcept
/////////////////////////////
template <typename NonAlignedPixelReference>
struct byte_to_memunit<bit_aligned_pixel_iterator<NonAlignedPixelReference> > : public mpl::int_<8> {};
template <typename NonAlignedPixelReference>
inline std::ptrdiff_t memunit_step(const bit_aligned_pixel_iterator<NonAlignedPixelReference>&) {
return NonAlignedPixelReference::bit_size;
}
template <typename NonAlignedPixelReference>
inline std::ptrdiff_t memunit_distance(const bit_aligned_pixel_iterator<NonAlignedPixelReference>& p1, const bit_aligned_pixel_iterator<NonAlignedPixelReference>& p2) {
return (p2.bit_range().current_byte() - p1.bit_range().current_byte())*8 + p2.bit_range().bit_offset() - p1.bit_range().bit_offset();
}
template <typename NonAlignedPixelReference>
inline void memunit_advance(bit_aligned_pixel_iterator<NonAlignedPixelReference>& p, std::ptrdiff_t diff) {
p.bit_range().bit_advance(diff);
}
template <typename NonAlignedPixelReference>
inline bit_aligned_pixel_iterator<NonAlignedPixelReference> memunit_advanced(const bit_aligned_pixel_iterator<NonAlignedPixelReference>& p, std::ptrdiff_t diff) {
bit_aligned_pixel_iterator<NonAlignedPixelReference> ret=p;
memunit_advance(ret, diff);
return ret;
}
template <typename NonAlignedPixelReference> inline
NonAlignedPixelReference memunit_advanced_ref(bit_aligned_pixel_iterator<NonAlignedPixelReference> it, std::ptrdiff_t diff) {
return *memunit_advanced(it,diff);
}
/////////////////////////////
// HasDynamicXStepTypeConcept
/////////////////////////////
template <typename NonAlignedPixelReference>
struct dynamic_x_step_type<bit_aligned_pixel_iterator<NonAlignedPixelReference> > {
typedef memory_based_step_iterator<bit_aligned_pixel_iterator<NonAlignedPixelReference> > type;
};
/////////////////////////////
// iterator_type_from_pixel
/////////////////////////////
template <typename B, typename C, typename L, bool M>
struct iterator_type_from_pixel<const bit_aligned_pixel_reference<B,C,L,M>,false,false,false> {
typedef bit_aligned_pixel_iterator<bit_aligned_pixel_reference<B,C,L,false> > type;
};
template <typename B, typename C, typename L, bool M>
struct iterator_type_from_pixel<const bit_aligned_pixel_reference<B,C,L,M>,false,false,true> {
typedef bit_aligned_pixel_iterator<bit_aligned_pixel_reference<B,C,L,true> > type;
};
template <typename B, typename C, typename L, bool M, bool IsPlanar, bool IsStep, bool IsMutable>
struct iterator_type_from_pixel<bit_aligned_pixel_reference<B,C,L,M>,IsPlanar,IsStep,IsMutable>
: public iterator_type_from_pixel<const bit_aligned_pixel_reference<B,C,L,M>,IsPlanar,IsStep,IsMutable> {};
} } // namespace boost::gil
namespace std {
// It is important to provide an overload of uninitialized_copy for bit_aligned_pixel_iterator. The default STL implementation calls placement new,
// which is not defined for bit_aligned_pixel_iterator.
template <typename NonAlignedPixelReference>
boost::gil::bit_aligned_pixel_iterator<NonAlignedPixelReference> uninitialized_copy(boost::gil::bit_aligned_pixel_iterator<NonAlignedPixelReference> first,
boost::gil::bit_aligned_pixel_iterator<NonAlignedPixelReference> last,
boost::gil::bit_aligned_pixel_iterator<NonAlignedPixelReference> dst) {
return std::copy(first,last,dst);
}
} // namespace std
#endif
| 51.703125 | 170 | 0.697189 | jaredhoberock |
d7573462aae89df4631b6eb27dea3e346afb689e | 2,013 | cpp | C++ | src/core/stream/outputstream.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/core/stream/outputstream.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/core/stream/outputstream.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | /*
Copyright 2009-2021 Nicolas Colombe
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 <core/stream/outputstream.hpp>
namespace eXl
{
OutputStream::OutputStream() = default;
OutputStream_ostream::OutputStream_streambuf::OutputStream_streambuf(OutputStream* iStream, size_t iBuffSize)
:m_Stream(iStream)
, m_Buffer(iBuffSize + 1)
, m_WriteOffset(0)
{
char *base = &m_Buffer.front();
setp(base, base + m_Buffer.size() - 1);
}
std::streambuf::int_type OutputStream_ostream::OutputStream_streambuf::overflow(int ch)
{
if (ch != traits_type::eof())
{
eXl_ASSERT(std::less_equal<char *>()(pptr(), epptr()));
*pptr() = ch;
pbump(1);
if (sync() == 0)
return ch;
}
return traits_type::eof();
}
int OutputStream_ostream::OutputStream_streambuf::sync()
{
std::ptrdiff_t n = pptr() - pbase();
pbump(-n);
size_t writtenSize = m_Stream->Write(n, pbase());
m_WriteOffset += writtenSize;
return writtenSize == n ? 0 : -1;
}
} | 40.26 | 460 | 0.723299 | eXl-Nic |
d757fadf39f7ea0369cb005e1670ea1001b83215 | 14,173 | cpp | C++ | src/InstrumentationEngine/AssemblyInfo.cpp | csdahlberg/CLRInstrumentationEngine | 8a56752fcdaaafcb0a466c1df9e4f411de59c84c | [
"MIT"
] | null | null | null | src/InstrumentationEngine/AssemblyInfo.cpp | csdahlberg/CLRInstrumentationEngine | 8a56752fcdaaafcb0a466c1df9e4f411de59c84c | [
"MIT"
] | null | null | null | src/InstrumentationEngine/AssemblyInfo.cpp | csdahlberg/CLRInstrumentationEngine | 8a56752fcdaaafcb0a466c1df9e4f411de59c84c | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "stdafx.h"
#include "AssemblyInfo.h"
// These have to go after AssemblyInfo.h because of cyclical dependencies...
#include "ProfilerManager.h"
#include "EnumeratorImpl.h"
#ifndef PLATFORM_UNIX
#include "StrongName.h"
#endif
MicrosoftInstrumentationEngine::CAssemblyInfo::CAssemblyInfo(CProfilerManager* pProfilerManager) :
m_pProfilerManager(pProfilerManager),
m_assemblyId(0),
m_tkAssembly(mdTokenNil),
m_manifestModuleID(0),
m_pPublicKey(NULL),
m_cbPublicKey(0),
m_publicKeyTokenInitialized(false)
{
DEFINE_REFCOUNT_NAME(CAssemblyInfo);
InitializeCriticalSection(&m_cs);
}
MicrosoftInstrumentationEngine::CAssemblyInfo::~CAssemblyInfo()
{
DeleteCriticalSection(&m_cs);
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::Initialize(
_In_ AssemblyID assemblyId,
_In_ WCHAR* wszAssemblyName,
_In_ IAppDomainInfo* pAppDomainInfo,
_In_ ModuleID manifestModuleID
)
{
m_assemblyId = assemblyId;
m_bstrAssemblyName = wszAssemblyName;
m_pAppDomainInfo = pAppDomainInfo;
m_manifestModuleID = manifestModuleID;
return S_OK;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetAppDomainInfo(_Out_ IAppDomainInfo** ppAppDomainInfo)
{
HRESULT hr = S_OK;
IfNullRetPointer(ppAppDomainInfo);
hr = m_pAppDomainInfo.CopyTo(ppAppDomainInfo);
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::AddModuleInfo(_In_ CModuleInfo* pModuleInfo)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Begin CAssemblyInfo::AddModuleInfo"));
CCriticalSectionHolder lock(&m_cs);
ModuleID moduleId;
IfFailRet(pModuleInfo->GetModuleID(&moduleId));
m_moduleInfos[moduleId] = pModuleInfo;
// If this is the manifest module, there is more work to be done
if (moduleId == m_manifestModuleID)
{
m_pManifestModule = (IModuleInfo*)pModuleInfo;
IfFailRet(HandleManifestModuleLoad());
}
CLogging::LogMessage(_T("end CAssemblyInfo::AddModuleInfo"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::HandleManifestModuleLoad()
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Begin CAssemblyInfo::HandleManifestModuleLoad"));
if (m_pManifestModule == NULL)
{
CLogging::LogError(_T("Starting CAssemblyInfo::HandleManifestModuleLoad - No manifest module"));
return E_FAIL;
}
CComPtr<IMetaDataAssemblyImport> pMetaDataAssemblyImport;
IfFailRet(m_pManifestModule->GetMetaDataAssemblyImport((IUnknown**)&pMetaDataAssemblyImport));
IfFailRet(pMetaDataAssemblyImport->GetAssemblyFromScope(&m_tkAssembly));
IfFailRet(pMetaDataAssemblyImport->GetAssemblyProps(m_tkAssembly, &m_pPublicKey, &m_cbPublicKey, nullptr, nullptr, 0, nullptr, nullptr, nullptr));
COR_PRF_RUNTIME_TYPE runtimeType;
if (FAILED(m_pProfilerManager->GetRuntimeType(&runtimeType)) ||
runtimeType != COR_PRF_CORE_CLR) // Don't attempt to calculate public key token in coreclr case.
{
IfFailRet(InitializePublicKeyToken());
}
CLogging::LogMessage(_T("End CAssemblyInfo::HandleManifestModuleLoad"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::ModuleInfoUnloaded(_In_ CModuleInfo* pModuleInfo)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Begin CAssemblyInfo::ModuleInfoUnloaded"));
CCriticalSectionHolder lock(&m_cs);
ModuleID moduleId;
IfFailRet(pModuleInfo->GetModuleID(&moduleId));
m_moduleInfos.erase(moduleId);
CLogging::LogMessage(_T("End CAssemblyInfo::ModuleInfoUnloaded"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetModuleCount(_Out_ ULONG* pcModuleInfos)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Begin CAssemblyInfo::GetModuleCount"));
IfNullRetPointer(pcModuleInfos);
CCriticalSectionHolder lock(&m_cs);
*pcModuleInfos = ((ULONG)m_moduleInfos.size());
CLogging::LogMessage(_T("End CAssemblyInfo::GetModuleCount"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetModules(_In_ ULONG cModuleInfos, _Out_ IEnumModuleInfo** ppModuleInfos)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetModules"));
IfNullRetPointer(ppModuleInfos);
*ppModuleInfos = NULL;
CCriticalSectionHolder lock(&m_cs);
vector<CComPtr<IModuleInfo>> vecModules;
for (std::pair<ModuleID, CComPtr<CModuleInfo>> p : m_moduleInfos)
{
vecModules.push_back((IModuleInfo*)(p.second));
}
CComPtr<CEnumerator<IEnumModuleInfo, IModuleInfo>> pEnumerator;
pEnumerator.Attach(new CEnumerator<IEnumModuleInfo, IModuleInfo>);
if (pEnumerator == NULL)
{
return E_OUTOFMEMORY;
}
IfFailRet(pEnumerator->Initialize(vecModules));
*ppModuleInfos = (IEnumModuleInfo*)pEnumerator;
(*ppModuleInfos)->AddRef();
CLogging::LogMessage(_T("End CAssemblyInfo::GetModules"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetModuleById(_In_ ModuleID moduleId, _Out_ IModuleInfo** ppModuleInfo)
{
HRESULT hr = S_OK;
IfNullRetPointer(ppModuleInfo);
*ppModuleInfo = NULL;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetModuleById"));
CCriticalSectionHolder lock(&m_cs);
std::unordered_map<ModuleID, CComPtr<CModuleInfo>>::iterator iter = m_moduleInfos.find(moduleId);
if (iter == m_moduleInfos.end())
{
CLogging::LogError(_T("CAssemblyInfo::GetModuleById - Failed to find specified assembly %04x"), moduleId);
return E_FAIL;
}
*ppModuleInfo = iter->second;
(*ppModuleInfo)->AddRef();
CLogging::LogMessage(_T("End CAssemblyInfo::GetModuleById"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetModuleByMvid(_In_ GUID* pMvid, _Out_ IModuleInfo** ppModuleInfo)
{
HRESULT hr = S_OK;
IfNullRetPointer(ppModuleInfo);
*ppModuleInfo = NULL;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetModuleByMvid"));
CCriticalSectionHolder lock(&m_cs);
vector<CComPtr<IModuleInfo>> vecModules;
for (std::pair<AssemblyID, CComPtr<CModuleInfo>> p : m_moduleInfos)
{
CComPtr<IModuleInfo> pModuleInfo = (IModuleInfo*)(p.second);
GUID currMvid;
IfFailRet(pModuleInfo->GetMVID(&currMvid));
if (currMvid == *pMvid)
{
vecModules.push_back(pModuleInfo);
}
}
CComPtr<CEnumerator<IEnumModuleInfo, IModuleInfo>> pEnumerator;
pEnumerator.Attach(new CEnumerator<IEnumModuleInfo, IModuleInfo>);
if (pEnumerator == NULL)
{
return E_OUTOFMEMORY;
}
IfFailRet(pEnumerator->Initialize(vecModules));
CLogging::LogMessage(_T("End CAssemblyInfo::GetModuleByMvid"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetModulesByName(_In_ BSTR pszModuleName, _Out_ IEnumModuleInfo** ppEnumModuleInfo)
{
HRESULT hr = S_OK;
IfNullRetPointer(ppEnumModuleInfo);
*ppEnumModuleInfo = NULL;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetModulesByName"));
CCriticalSectionHolder lock(&m_cs);
vector<CComPtr<IModuleInfo>> vecModules;
for (std::pair<AssemblyID, CComPtr<CModuleInfo>> p : m_moduleInfos)
{
CComPtr<IModuleInfo> pModuleInfo = (IModuleInfo*)(p.second);
CComBSTR bstrCurrName;
IfFailRet(pModuleInfo->GetModuleName(&bstrCurrName));
#ifndef PLATFORM_UNIX
if (wcscmp(pszModuleName, bstrCurrName) == 0)
#else
if (PAL_wcscmp(pszModuleName, bstrCurrName) == 0)
#endif
{
vecModules.push_back(pModuleInfo);
}
}
CComPtr<CEnumerator<IEnumModuleInfo, IModuleInfo>> pEnumerator;
pEnumerator.Attach(new CEnumerator<IEnumModuleInfo, IModuleInfo>);
if (pEnumerator == NULL)
{
return E_OUTOFMEMORY;
}
IfFailRet(pEnumerator->Initialize(vecModules));
CLogging::LogMessage(_T("End CAssemblyInfo::GetModulesByName"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetModuleForMethod(_In_ mdToken token, _Out_ IModuleInfo** ppModuleInfo)
{
HRESULT hr = S_OK;
*ppModuleInfo = nullptr;
//VSFAIL(L"NYI");
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetModuleForType(_In_ BSTR pszTypeName, _In_ mdToken tkResolutionScope, _Out_ mdToken* pTkTypeDef)
{
HRESULT hr = S_OK;
*pTkTypeDef = mdTokenNil;
//VSFAIL(L"NYI");
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetManifestModule(_Out_ IModuleInfo** ppModuleInfo)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetManifestModule"));
IfNullRetPointer(ppModuleInfo);
*ppModuleInfo = NULL;
if (m_pManifestModule == NULL)
{
CLogging::LogMessage(_T("CAssemblyInfo::GetManifestModule - Why no manifest module?"));
return E_FAIL;
}
IfFailRet(m_pManifestModule.CopyTo(ppModuleInfo));
CLogging::LogMessage(_T("end CAssemblyInfo::GetManifestModule"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetPublicKey(_In_ ULONG cbBytes, _Out_writes_(cbBytes) BYTE* pbBytes)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetPublicKey"));
IfNullRetPointer(pbBytes);
if (cbBytes != m_cbPublicKey)
{
CLogging::LogError(_T("CAssemblyInfo::GetPublicKey - Incorrect public key buffer size"));
}
memcpy_s(pbBytes, cbBytes, m_pPublicKey, m_cbPublicKey);
CLogging::LogMessage(_T("end CAssemblyInfo::GetPublicKey"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetPublicKeySize(_Out_ ULONG* pcbBytes)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetPublicKeySize"));
IfNullRetPointer(pcbBytes);
*pcbBytes = m_cbPublicKey;
CLogging::LogMessage(_T("end CAssemblyInfo::GetPublicKeySize"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetPublicKeyToken(_Out_ BSTR* pbstrPublicKeyToken)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetPublicKeyToken"));
IfNullRetPointer(pbstrPublicKeyToken);
if (!m_publicKeyTokenInitialized)
{
CLogging::LogError(_T("Starting CAssemblyInfo::GetPublicKeyToken - public key token not initiliazed"));
return E_FAIL;
}
IfFailRet(m_bstrPublicKeyToken.CopyTo(pbstrPublicKeyToken));
CLogging::LogMessage(_T("end CAssemblyInfo::GetPublicKeyToken"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetID(_Out_ AssemblyID* pAssemblyId)
{
HRESULT hr = S_OK;
IfNullRetPointer(pAssemblyId);
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetID"));
*pAssemblyId = m_assemblyId;
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetID"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetName(_Out_ BSTR* pbstrName)
{
HRESULT hr = S_OK;
IfNullRetPointer(pbstrName);
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetName"));
IfFailRet(m_bstrAssemblyName.CopyTo(pbstrName));
CLogging::LogMessage(_T("End CAssemblyInfo::GetName"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::GetMetaDataToken(_Out_ DWORD* pdwToken)
{
HRESULT hr = S_OK;
IfNullRetPointer(pdwToken);
CLogging::LogMessage(_T("Starting CAssemblyInfo::GetMetaDataToken"));
if (m_tkAssembly == mdTokenNil)
{
CLogging::LogMessage(_T("CAssemblyInfo::GetMetaDataToken - token is mdTokenNil."));
return E_FAIL;
}
*pdwToken = m_tkAssembly;
CLogging::LogMessage(_T("End CAssemblyInfo::GetMetaDataToken"));
return hr;
}
HRESULT MicrosoftInstrumentationEngine::CAssemblyInfo::InitializePublicKeyToken()
{
HRESULT hr = S_OK;
// Strong name not supported on linux
#ifndef PLATFORM_UNIX
if (m_publicKeyTokenInitialized)
{
return S_OK;
}
CLogging::LogMessage(_T("Begin CAssemblyInfo::InitializePublicKeyToken"));
m_publicKeyTokenInitialized = true;
// Check if there is a public key for this assembly
if (!m_pPublicKey || !m_cbPublicKey)
{
CLogging::LogMessage(_T("CAssemblyInfo::InitializePublicKeyToken - No public key for assembly"));
return S_FALSE;
}
// Regulators..... mount up
BOOLEAN (__stdcall *StrongNameTokenFromPublicKeyPtr)(BYTE*, ULONG, BYTE**, ULONG*) = GetStrongNameTokenFromPublicKeyPtr();
VOID (__stdcall *StrongNameFreeBufferPtr)(BYTE*) = GetStrongNameFreeBufferPtr();
if (!StrongNameTokenFromPublicKeyPtr || !StrongNameFreeBufferPtr)
{
CLogging::LogError(_T("CAssemblyInfo::InitializePublicKeyToken - CLR exports not found"));
return E_FAIL;
}
// Get the public key token from the public key
BYTE* pPublicKeyToken = 0;
ULONG publicKeyTokenSize = 0;
if (!StrongNameTokenFromPublicKeyPtr(reinterpret_cast<BYTE*>(const_cast<void*>(m_pPublicKey)), m_cbPublicKey, &pPublicKeyToken, &publicKeyTokenSize))
{
CLogging::LogError(_T("CAssemblyInfo::InitializePublicKeyToken - Failed to get public key token"));
return E_FAIL;
}
// Build up a string representation in uppercase hex for the public key token
const DWORD dwPublicKeyTokenBufferLen = 16 + 1;
WCHAR wszPublicKeyToken[dwPublicKeyTokenBufferLen] = { 0 };
WCHAR *currTokenPos = wszPublicKeyToken;
WCHAR *endTokenBuffer = wszPublicKeyToken + 16; // Ignore last element since it is for null not content.
for (ULONG i = 0; i < publicKeyTokenSize && (currTokenPos != endTokenBuffer); ++i)
{
// 2 for each printed character in a byte and 1 for the implicit null
swprintf_s(currTokenPos, (2 + 1), L"%02X", pPublicKeyToken[i]);
currTokenPos += 2;
}
// Free the buffer that was allocated by StrongNameTokenFromPublicKey
StrongNameFreeBufferPtr(pPublicKeyToken);
m_bstrPublicKeyToken = wszPublicKeyToken;
CLogging::LogMessage(_T("End CAssemblyInfo::InitializePublicKeyToken"));
#endif
return S_OK;
} | 29.343685 | 153 | 0.724899 | csdahlberg |
d7599b3c7e33c164e21793c676b80491dbf9be7a | 890 | hh | C++ | dron/dron/Prostopadloscian.hh | placekziemniaczany/dron2 | 4b3fa3d684feb6becb22e25f2119103d1f8cf923 | [
"MIT"
] | null | null | null | dron/dron/Prostopadloscian.hh | placekziemniaczany/dron2 | 4b3fa3d684feb6becb22e25f2119103d1f8cf923 | [
"MIT"
] | null | null | null | dron/dron/Prostopadloscian.hh | placekziemniaczany/dron2 | 4b3fa3d684feb6becb22e25f2119103d1f8cf923 | [
"MIT"
] | null | null | null | #ifndef PROSTOPADLOSCIAN_HH
#define PROSTOPADLOSCIAN_HH
/*!
* \file
* \brief Definicja klasy Prostopadloscian
*
* Plik zawiera definicjê klasy Prostopadloscian
*/
#include "Bryla.hh"
#include "InterfejsRysowania.hh"
#include "ZbiorWierzcholkow.hh"
/*!
* \brief Modeluje Prostopadloscian, korpus Drona
*
* Modeluje prostoadloscian dziedzczacy z klas bryla i interfejsrysowania
* Posiada metody rysowania, wczytywania i przesuwania
*
*/
class Prostopadloscian : public Bryla, public InterfejsRysowania {
public:
/*!
* \brief funkcja rysujaca prostopadloscian
*/
void rysuj(std::shared_ptr<drawNS::Draw3DAPI> kpi);
/*!
* \brief funkcja wczytujaca z pliku wierzcholki
*/
void loadfromfile(string plik);
/*!
* \brief Przesuwajaca prostopadloscian o wektor
*/
void PrzesunOWektor(Wektor3D W);
void Obrot(double, obroc_wokol);
};
#endif
| 22.820513 | 74 | 0.725843 | placekziemniaczany |
d75a5ee7d04b367711557b7a8abc762315c527ad | 38,318 | cpp | C++ | core/globals.cpp | efornara/fantocci | 74981d9632736f120d53b2193da027f7fa671d43 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | core/globals.cpp | efornara/fantocci | 74981d9632736f120d53b2193da027f7fa671d43 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | core/globals.cpp | efornara/fantocci | 74981d9632736f120d53b2193da027f7fa671d43 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | /*************************************************************************/
/* globals.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "globals.h"
#include "os/dir_access.h"
#include "os/file_access.h"
#include "bind/core_bind.h"
#include "io/file_access_network.h"
#include "io/file_access_pack.h"
#include "io/marshalls.h"
#include "os/keyboard.h"
#include "os/os.h"
Globals *Globals::singleton = NULL;
Globals *Globals::get_singleton() {
return singleton;
}
String Globals::get_resource_path() const {
return resource_path;
};
String Globals::localize_path(const String &p_path) const {
if (resource_path == "")
return p_path; //not initialied yet
if (p_path.begins_with("res://") || p_path.begins_with("user://") ||
(p_path.is_abs_path() && !p_path.begins_with(resource_path)))
return p_path.simplify_path();
DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
String path = p_path.replace("\\", "/").simplify_path();
if (dir->change_dir(path) == OK) {
String cwd = dir->get_current_dir();
cwd = cwd.replace("\\", "/");
memdelete(dir);
if (!cwd.begins_with(resource_path)) {
return p_path;
};
return cwd.replace_first(resource_path, "res:/");
} else {
memdelete(dir);
int sep = path.find_last("/");
if (sep == -1) {
return "res://" + path;
};
String parent = path.substr(0, sep);
String plocal = localize_path(parent);
if (plocal == "") {
return "";
};
return plocal + path.substr(sep, path.size() - sep);
};
}
void Globals::set_persisting(const String &p_name, bool p_persist) {
ERR_FAIL_COND(!props.has(p_name));
props[p_name].persist = p_persist;
}
bool Globals::is_persisting(const String &p_name) const {
ERR_FAIL_COND_V(!props.has(p_name), false);
return props[p_name].persist;
}
String Globals::globalize_path(const String &p_path) const {
if (p_path.begins_with("res://")) {
if (resource_path != "") {
return p_path.replace("res:/", resource_path);
};
return p_path.replace("res://", "");
};
return p_path;
}
bool Globals::_set(const StringName &p_name, const Variant &p_value) {
_THREAD_SAFE_METHOD_
if (p_value.get_type() == Variant::NIL)
props.erase(p_name);
else {
if (props.has(p_name)) {
if (!props[p_name].overrided)
props[p_name].variant = p_value;
if (props[p_name].order >= NO_ORDER_BASE && registering_order) {
props[p_name].order = last_order++;
}
} else {
props[p_name] = VariantContainer(p_value, last_order++ + (registering_order ? 0 : NO_ORDER_BASE));
}
}
if (!disable_platform_override) {
String s = String(p_name);
int sl = s.find("/");
int p = s.find(".");
if (p != -1 && sl != -1 && p < sl) {
Vector<String> ps = s.substr(0, sl).split(".");
String prop = s.substr(sl, s.length() - sl);
for (int i = 1; i < ps.size(); i++) {
if (ps[i] == OS::get_singleton()->get_name()) {
String fullprop = ps[0] + prop;
set(fullprop, p_value);
props[fullprop].overrided = true;
}
}
}
}
return true;
}
bool Globals::_get(const StringName &p_name, Variant &r_ret) const {
_THREAD_SAFE_METHOD_
if (!props.has(p_name))
return false;
r_ret = props[p_name].variant;
return true;
}
struct _VCSort {
String name;
Variant::Type type;
int order;
int flags;
bool operator<(const _VCSort &p_vcs) const { return order == p_vcs.order ? name < p_vcs.name : order < p_vcs.order; }
};
void Globals::_get_property_list(List<PropertyInfo> *p_list) const {
_THREAD_SAFE_METHOD_
Set<_VCSort> vclist;
for (Map<StringName, VariantContainer>::Element *E = props.front(); E; E = E->next()) {
const VariantContainer *v = &E->get();
if (v->hide_from_editor)
continue;
_VCSort vc;
vc.name = E->key();
vc.order = v->order;
vc.type = v->variant.get_type();
if (vc.name.begins_with("input/") || vc.name.begins_with("import/") || vc.name.begins_with("export/") || vc.name.begins_with("/remap") || vc.name.begins_with("/locale") || vc.name.begins_with("/autoload"))
vc.flags = PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_STORAGE;
else
vc.flags = PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE;
if (v->persist) {
vc.flags |= PROPERTY_USAGE_CHECKED;
}
vclist.insert(vc);
}
for (Set<_VCSort>::Element *E = vclist.front(); E; E = E->next()) {
if (custom_prop_info.has(E->get().name)) {
PropertyInfo pi = custom_prop_info[E->get().name];
pi.name = E->get().name;
pi.usage = E->get().flags;
p_list->push_back(pi);
} else
p_list->push_back(PropertyInfo(E->get().type, E->get().name, PROPERTY_HINT_NONE, "", E->get().flags));
}
}
bool Globals::_load_resource_pack(const String &p_pack) {
if (PackedData::get_singleton()->is_disabled())
return false;
bool ok = PackedData::get_singleton()->add_pack(p_pack) == OK;
if (!ok)
return false;
//if data.pck is found, all directory access will be from here
DirAccess::make_default<DirAccessPack>(DirAccess::ACCESS_RESOURCES);
using_datapack = true;
return true;
}
Error Globals::setup(const String &p_path, const String &p_main_pack) {
//an absolute mess of a function, must be cleaned up and reorganized somehow at some point
//_load_settings(p_path+"/override.cfg");
if (p_main_pack != "") {
bool ok = _load_resource_pack(p_main_pack);
ERR_FAIL_COND_V(!ok, ERR_CANT_OPEN);
if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) {
_load_settings("res://override.cfg");
}
return OK;
}
if (OS::get_singleton()->get_executable_path() != "") {
if (_load_resource_pack(OS::get_singleton()->get_executable_path())) {
if (p_path != "") {
resource_path = p_path;
} else {
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
resource_path = d->get_current_dir();
memdelete(d);
}
if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) {
_load_settings("res://override.cfg");
}
return OK;
}
}
if (FileAccessNetworkClient::get_singleton()) {
if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) {
_load_settings("res://override.cfg");
}
return OK;
}
if (OS::get_singleton()->get_resource_dir() != "") {
//OS will call Globals->get_resource_path which will be empty if not overriden!
//if the OS would rather use somewhere else, then it will not be empty.
resource_path = OS::get_singleton()->get_resource_dir().replace("\\", "/");
if (resource_path.length() && resource_path[resource_path.length() - 1] == '/')
resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end
print_line("has res dir: " + resource_path);
if (!_load_resource_pack("res://data.pck"))
_load_resource_pack("res://data.zip");
// make sure this is load from the resource path
print_line("exists engine cfg? " + itos(FileAccess::exists("/engine.cfg")));
if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) {
print_line("loaded engine.cfg");
_load_settings("res://override.cfg");
}
return OK;
}
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
if (!d) {
resource_path = p_path;
} else {
d->change_dir(p_path);
String candidate = d->get_current_dir();
String current_dir = d->get_current_dir();
String exec_name = OS::get_singleton()->get_executable_path().get_file().basename();
bool found = false;
bool first_time = true;
while (true) {
//try to load settings in ascending through dirs shape!
//tries to open pack, but only first time
if (first_time && (_load_resource_pack(current_dir + "/" + exec_name + ".pck") || _load_resource_pack(current_dir + "/" + exec_name + ".zip"))) {
if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) {
_load_settings("res://override.cfg");
found = true;
}
break;
} else if (first_time && (_load_resource_pack(current_dir + "/data.pck") || _load_resource_pack(current_dir + "/data.zip"))) {
if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) {
_load_settings("res://override.cfg");
found = true;
}
break;
} else if (_load_settings(current_dir + "/engine.cfg") == OK || _load_settings_binary(current_dir + "/engine.cfb") == OK) {
_load_settings(current_dir + "/override.cfg");
candidate = current_dir;
found = true;
break;
}
d->change_dir("..");
if (d->get_current_dir() == current_dir)
break; //not doing anything useful
current_dir = d->get_current_dir();
first_time = false;
}
resource_path = candidate;
resource_path = resource_path.replace("\\", "/"); // windows path to unix path just in case
memdelete(d);
if (!found)
return ERR_FILE_NOT_FOUND;
};
if (resource_path.length() && resource_path[resource_path.length() - 1] == '/')
resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end
return OK;
}
bool Globals::has(String p_var) const {
_THREAD_SAFE_METHOD_
return props.has(p_var);
}
static Vector<String> _decode_params(const String &p_string) {
int begin = p_string.find("(");
ERR_FAIL_COND_V(begin == -1, Vector<String>());
begin++;
int end = p_string.find(")");
ERR_FAIL_COND_V(end < begin, Vector<String>());
return p_string.substr(begin, end - begin).split(",");
}
static String _get_chunk(const String &str, int &pos, int close_pos) {
enum {
MIN_COMMA,
MIN_COLON,
MIN_CLOSE,
MIN_QUOTE,
MIN_PARENTHESIS,
MIN_CURLY_OPEN,
MIN_OPEN
};
int min_pos = close_pos;
int min_what = MIN_CLOSE;
#define TEST_MIN(m_how, m_what) \
{ \
int res = str.find(m_how, pos); \
if (res != -1 && res < min_pos) { \
min_pos = res; \
min_what = m_what; \
} \
}
TEST_MIN(",", MIN_COMMA);
TEST_MIN("[", MIN_OPEN);
TEST_MIN("{", MIN_CURLY_OPEN);
TEST_MIN("(", MIN_PARENTHESIS);
TEST_MIN("\"", MIN_QUOTE);
int end = min_pos;
switch (min_what) {
case MIN_COMMA: {
} break;
case MIN_CLOSE: {
//end because it's done
} break;
case MIN_QUOTE: {
end = str.find("\"", min_pos + 1) + 1;
ERR_FAIL_COND_V(end == -1, Variant());
} break;
case MIN_PARENTHESIS: {
end = str.find(")", min_pos + 1) + 1;
ERR_FAIL_COND_V(end == -1, Variant());
} break;
case MIN_OPEN: {
int level = 1;
end++;
while (end < close_pos) {
if (str[end] == '[')
level++;
if (str[end] == ']') {
level--;
if (level == 0)
break;
}
end++;
}
ERR_FAIL_COND_V(level != 0, Variant());
end++;
} break;
case MIN_CURLY_OPEN: {
int level = 1;
end++;
while (end < close_pos) {
if (str[end] == '{')
level++;
if (str[end] == '}') {
level--;
if (level == 0)
break;
}
end++;
}
ERR_FAIL_COND_V(level != 0, Variant());
end++;
} break;
}
String ret = str.substr(pos, end - pos);
pos = end;
while (pos < close_pos) {
if (str[pos] != ',' && str[pos] != ' ' && str[pos] != ':')
break;
pos++;
}
return ret;
}
static Variant _decode_variant(const String &p_string) {
String str = p_string.strip_edges();
if (str.nocasecmp_to("true") == 0)
return Variant(true);
if (str.nocasecmp_to("false") == 0)
return Variant(false);
if (str.nocasecmp_to("nil") == 0)
return Variant();
if (str.is_valid_float()) {
if (str.find(".") == -1)
return str.to_int();
else
return str.to_double();
}
if (str.begins_with("#")) { //string
return Color::html(str);
}
if (str.begins_with("\"")) { //string
int end = str.find_last("\"");
ERR_FAIL_COND_V(end == 0, Variant());
return str.substr(1, end - 1).xml_unescape();
}
if (str.begins_with("[")) { //array
int close_pos = str.find_last("]");
ERR_FAIL_COND_V(close_pos == -1, Variant());
Array array;
int pos = 1;
while (pos < close_pos) {
String s = _get_chunk(str, pos, close_pos);
array.push_back(_decode_variant(s));
}
return array;
}
if (str.begins_with("{")) { //array
int close_pos = str.find_last("}");
ERR_FAIL_COND_V(close_pos == -1, Variant());
Dictionary d;
int pos = 1;
while (pos < close_pos) {
String key = _get_chunk(str, pos, close_pos);
String data = _get_chunk(str, pos, close_pos);
d[_decode_variant(key)] = _decode_variant(data);
}
return d;
}
if (str.begins_with("key")) {
Vector<String> params = _decode_params(p_string);
ERR_FAIL_COND_V(params.size() != 1 && params.size() != 2, Variant());
int scode = 0;
if (params[0].is_numeric()) {
scode = params[0].to_int();
if (scode < 10)
scode += KEY_0;
} else
scode = find_keycode(params[0]);
InputEvent ie;
ie.type = InputEvent::KEY;
ie.key.scancode = scode;
if (params.size() == 2) {
String mods = params[1];
if (mods.findn("C") != -1)
ie.key.mod.control = true;
if (mods.findn("A") != -1)
ie.key.mod.alt = true;
if (mods.findn("S") != -1)
ie.key.mod.shift = true;
if (mods.findn("M") != -1)
ie.key.mod.meta = true;
}
return ie;
}
if (str.begins_with("mbutton")) {
Vector<String> params = _decode_params(p_string);
ERR_FAIL_COND_V(params.size() != 2, Variant());
InputEvent ie;
ie.type = InputEvent::MOUSE_BUTTON;
ie.device = params[0].to_int();
ie.mouse_button.button_index = params[1].to_int();
return ie;
}
if (str.begins_with("jbutton")) {
Vector<String> params = _decode_params(p_string);
ERR_FAIL_COND_V(params.size() != 2, Variant());
InputEvent ie;
ie.type = InputEvent::JOYSTICK_BUTTON;
ie.device = params[0].to_int();
ie.joy_button.button_index = params[1].to_int();
return ie;
}
if (str.begins_with("jaxis")) {
Vector<String> params = _decode_params(p_string);
ERR_FAIL_COND_V(params.size() != 2, Variant());
InputEvent ie;
ie.type = InputEvent::JOYSTICK_MOTION;
ie.device = params[0].to_int();
int axis = params[1].to_int();
;
ie.joy_motion.axis = axis >> 1;
ie.joy_motion.axis_value = axis & 1 ? 1 : -1;
return ie;
}
if (str.begins_with("img")) {
Vector<String> params = _decode_params(p_string);
if (params.size() == 0) {
return Image();
}
ERR_FAIL_COND_V(params.size() != 5, Image());
String format = params[0].strip_edges();
Image::Format imgformat;
if (format == "grayscale") {
imgformat = Image::FORMAT_GRAYSCALE;
} else if (format == "intensity") {
imgformat = Image::FORMAT_INTENSITY;
} else if (format == "grayscale_alpha") {
imgformat = Image::FORMAT_GRAYSCALE_ALPHA;
} else if (format == "rgb") {
imgformat = Image::FORMAT_RGB;
} else if (format == "rgba") {
imgformat = Image::FORMAT_RGBA;
} else if (format == "indexed") {
imgformat = Image::FORMAT_INDEXED;
} else if (format == "indexed_alpha") {
imgformat = Image::FORMAT_INDEXED_ALPHA;
} else if (format == "bc1") {
imgformat = Image::FORMAT_BC1;
} else if (format == "bc2") {
imgformat = Image::FORMAT_BC2;
} else if (format == "bc3") {
imgformat = Image::FORMAT_BC3;
} else if (format == "bc4") {
imgformat = Image::FORMAT_BC4;
} else if (format == "bc5") {
imgformat = Image::FORMAT_BC5;
} else if (format == "custom") {
imgformat = Image::FORMAT_CUSTOM;
} else {
ERR_FAIL_V(Image());
}
int mipmaps = params[1].to_int();
int w = params[2].to_int();
int h = params[3].to_int();
if (w == 0 && h == 0) {
//r_v = Image(w, h, imgformat);
return Image();
};
String data = params[4];
int datasize = data.length() / 2;
DVector<uint8_t> pixels;
pixels.resize(datasize);
DVector<uint8_t>::Write wb = pixels.write();
const CharType *cptr = data.c_str();
int idx = 0;
uint8_t byte;
while (idx < datasize * 2) {
CharType c = *(cptr++);
ERR_FAIL_COND_V(c == '<', ERR_FILE_CORRUPT);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) {
if (idx & 1) {
byte |= HEX2CHR(c);
wb[idx >> 1] = byte;
} else {
byte = HEX2CHR(c) << 4;
}
idx++;
}
}
wb = DVector<uint8_t>::Write();
return Image(w, h, mipmaps, imgformat, pixels);
}
if (str.find(",") != -1) { //vector2 or vector3
// Since the data could be stored as Vector2(0, 0)
// We need to first remove any string from the data.
// To do that, we split the data using '(' as delimiter
// and keep the last element only.
// Then using the "split_floats" function should work like a charm
Vector<String> sarr = str.split("(", true);
Vector<float> farr = sarr[sarr.size() - 1].split_floats(",", true);
if (farr.size() == 2) {
return Vector2(farr[0], farr[1]);
}
if (farr.size() == 3) {
return Vector3(farr[0], farr[1], farr[2]);
}
ERR_FAIL_V(Variant());
}
return Variant();
}
void Globals::set_registering_order(bool p_enable) {
registering_order = p_enable;
}
Error Globals::_load_settings_binary(const String p_path) {
Error err;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err != OK) {
return err;
}
uint8_t hdr[4];
f->get_buffer(hdr, 4);
if (hdr[0] != 'E' || hdr[1] != 'C' || hdr[2] != 'F' || hdr[3] != 'G') {
memdelete(f);
ERR_EXPLAIN("Corrupted header in binary engine.cfb (not ECFG)");
ERR_FAIL_V(ERR_FILE_CORRUPT;)
}
set_registering_order(false);
uint32_t count = f->get_32();
for (int i = 0; i < count; i++) {
uint32_t slen = f->get_32();
CharString cs;
cs.resize(slen + 1);
cs[slen] = 0;
f->get_buffer((uint8_t *)cs.ptr(), slen);
String key;
key.parse_utf8(cs.ptr());
uint32_t vlen = f->get_32();
Vector<uint8_t> d;
d.resize(vlen);
f->get_buffer(d.ptr(), vlen);
Variant value;
Error err = decode_variant(value, d.ptr(), d.size());
ERR_EXPLAIN("Error decoding property: " + key);
ERR_CONTINUE(err != OK);
set(key, value);
set_persisting(key, true);
}
set_registering_order(true);
return OK;
}
Error Globals::_load_settings(const String p_path) {
Error err;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err != OK) {
return err;
}
String line;
String section;
String subpath;
set_registering_order(false);
int line_count = 0;
while (!f->eof_reached()) {
String line = f->get_line().strip_edges();
line_count++;
if (line == "")
continue;
// find comments
{
int pos = 0;
while (true) {
int ret = line.find(";", pos);
if (ret == -1)
break;
int qc = 0;
for (int i = 0; i < ret; i++) {
if (line[i] == '"')
qc++;
}
if (!(qc & 1)) {
//not inside string, real comment
line = line.substr(0, ret);
break;
}
pos = ret + 1;
}
}
if (line.begins_with("[")) {
int end = line.find_last("]");
ERR_CONTINUE(end != line.length() - 1);
String section = line.substr(1, line.length() - 2);
if (section == "global" || section == "")
subpath = "";
else
subpath = section + "/";
} else if (line.find("=") != -1) {
int eqpos = line.find("=");
String var = line.substr(0, eqpos).strip_edges();
String value = line.substr(eqpos + 1, line.length()).strip_edges();
Variant val = _decode_variant(value);
set(subpath + var, val);
set_persisting(subpath + var, true);
//props[subpath+var]=VariantContainer(val,last_order++,true);
} else {
if (line.length() > 0) {
ERR_PRINT(String("Syntax error on line " + itos(line_count) + " of file " + p_path).ascii().get_data());
};
};
}
memdelete(f);
set_registering_order(true);
return OK;
}
static String _encode_variant(const Variant &p_variant) {
switch (p_variant.get_type()) {
case Variant::BOOL: {
bool val = p_variant;
return (val ? "true" : "false");
} break;
case Variant::INT: {
int val = p_variant;
return itos(val);
} break;
case Variant::REAL: {
float val = p_variant;
return rtos(val) + (val == int(val) ? ".0" : "");
} break;
case Variant::VECTOR2: {
Vector2 val = p_variant;
return String("Vector2(") + rtos(val.x) + String(", ") + rtos(val.y) + String(")");
} break;
case Variant::VECTOR3: {
Vector3 val = p_variant;
return String("Vector3(") + rtos(val.x) + String(", ") + rtos(val.y) + String(", ") + rtos(val.z) + String(")");
} break;
case Variant::STRING: {
String val = p_variant;
return "\"" + val.xml_escape() + "\"";
} break;
case Variant::COLOR: {
Color val = p_variant;
return "#" + val.to_html();
} break;
case Variant::STRING_ARRAY:
case Variant::INT_ARRAY:
case Variant::REAL_ARRAY:
case Variant::ARRAY: {
Array arr = p_variant;
String str = "[";
for (int i = 0; i < arr.size(); i++) {
if (i > 0)
str += ", ";
str += _encode_variant(arr[i]);
}
str += "]";
return str;
} break;
case Variant::DICTIONARY: {
Dictionary d = p_variant;
String str = "{";
List<Variant> keys;
d.get_key_list(&keys);
for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
if (E != keys.front())
str += ", ";
str += _encode_variant(E->get());
str += ":";
str += _encode_variant(d[E->get()]);
}
str += "}";
return str;
} break;
case Variant::IMAGE: {
String str = "img(";
Image img = p_variant;
if (!img.empty()) {
String format;
switch (img.get_format()) {
case Image::FORMAT_GRAYSCALE: format = "grayscale"; break;
case Image::FORMAT_INTENSITY: format = "intensity"; break;
case Image::FORMAT_GRAYSCALE_ALPHA: format = "grayscale_alpha"; break;
case Image::FORMAT_RGB: format = "rgb"; break;
case Image::FORMAT_RGBA: format = "rgba"; break;
case Image::FORMAT_INDEXED: format = "indexed"; break;
case Image::FORMAT_INDEXED_ALPHA: format = "indexed_alpha"; break;
case Image::FORMAT_BC1: format = "bc1"; break;
case Image::FORMAT_BC2: format = "bc2"; break;
case Image::FORMAT_BC3: format = "bc3"; break;
case Image::FORMAT_BC4: format = "bc4"; break;
case Image::FORMAT_BC5: format = "bc5"; break;
case Image::FORMAT_CUSTOM: format = "custom custom_size=" + itos(img.get_data().size()) + ""; break;
default: {}
}
str += format + ", ";
str += itos(img.get_mipmaps()) + ", ";
str += itos(img.get_width()) + ", ";
str += itos(img.get_height()) + ", ";
DVector<uint8_t> data = img.get_data();
int ds = data.size();
DVector<uint8_t>::Read r = data.read();
for (int i = 0; i < ds; i++) {
uint8_t byte = r[i];
const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char bstr[3] = { hex[byte >> 4], hex[byte & 0xF], 0 };
str += bstr;
}
}
str += ")";
return str;
} break;
case Variant::INPUT_EVENT: {
InputEvent ev = p_variant;
switch (ev.type) {
case InputEvent::KEY: {
String mods;
if (ev.key.mod.control)
mods += "C";
if (ev.key.mod.shift)
mods += "S";
if (ev.key.mod.alt)
mods += "A";
if (ev.key.mod.meta)
mods += "M";
if (mods != "")
mods = ", " + mods;
return "key(" + keycode_get_string(ev.key.scancode) + mods + ")";
} break;
case InputEvent::MOUSE_BUTTON: {
return "mbutton(" + itos(ev.device) + ", " + itos(ev.mouse_button.button_index) + ")";
} break;
case InputEvent::JOYSTICK_BUTTON: {
return "jbutton(" + itos(ev.device) + ", " + itos(ev.joy_button.button_index) + ")";
} break;
case InputEvent::JOYSTICK_MOTION: {
return "jaxis(" + itos(ev.device) + ", " + itos(ev.joy_motion.axis * 2 + (ev.joy_motion.axis_value < 0 ? 0 : 1)) + ")";
} break;
default: {
return "nil";
} break;
}
} break;
default: {}
}
return "nil"; //don't know wha to do with this
}
int Globals::get_order(const String &p_name) const {
ERR_FAIL_COND_V(!props.has(p_name), -1);
return props[p_name].order;
}
void Globals::set_order(const String &p_name, int p_order) {
ERR_FAIL_COND(!props.has(p_name));
props[p_name].order = p_order;
}
void Globals::clear(const String &p_name) {
ERR_FAIL_COND(!props.has(p_name));
props.erase(p_name);
}
Error Globals::save() {
return save_custom(get_resource_path() + "/engine.cfg");
}
Error Globals::_save_settings_binary(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom) {
Error err;
FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err);
if (err != OK) {
ERR_EXPLAIN("Coudln't save engine.cfb at " + p_file);
ERR_FAIL_COND_V(err, err)
}
uint8_t hdr[4] = { 'E', 'C', 'F', 'G' };
file->store_buffer(hdr, 4);
int count = 0;
for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) {
for (List<String>::Element *F = E->get().front(); F; F = F->next()) {
count++;
}
}
file->store_32(count); //store how many properties are saved
for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) {
for (List<String>::Element *F = E->get().front(); F; F = F->next()) {
String key = F->get();
if (E->key() != "")
key = E->key() + "/" + key;
Variant value;
if (p_custom.has(key))
value = p_custom[key];
else
value = get(key);
file->store_32(key.length());
file->store_string(key);
int len;
Error err = encode_variant(value, NULL, len);
if (err != OK)
memdelete(file);
ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA);
Vector<uint8_t> buff;
buff.resize(len);
err = encode_variant(value, &buff[0], len);
if (err != OK)
memdelete(file);
ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA);
file->store_32(len);
file->store_buffer(buff.ptr(), buff.size());
}
}
file->close();
memdelete(file);
return OK;
}
Error Globals::_save_settings_text(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom) {
Error err;
FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err);
if (err) {
ERR_EXPLAIN("Coudln't save engine.cfg - " + p_file);
ERR_FAIL_COND_V(err, err)
}
for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) {
if (E != props.front())
file->store_string("\n");
if (E->key() != "")
file->store_string("[" + E->key() + "]\n\n");
for (List<String>::Element *F = E->get().front(); F; F = F->next()) {
String key = F->get();
if (E->key() != "")
key = E->key() + "/" + key;
Variant value;
if (p_custom.has(key))
value = p_custom[key];
else
value = get(key);
file->store_string(F->get() + "=" + _encode_variant(value) + "\n");
}
}
file->close();
memdelete(file);
return OK;
}
Error Globals::_save_custom_bnd(const String &p_file) { // add other params as dictionary and array?
return save_custom(p_file);
};
Error Globals::save_custom(const String &p_path, const CustomMap &p_custom, const Set<String> &p_ignore_masks) {
ERR_FAIL_COND_V(p_path == "", ERR_INVALID_PARAMETER);
Set<_VCSort> vclist;
for (Map<StringName, VariantContainer>::Element *G = props.front(); G; G = G->next()) {
const VariantContainer *v = &G->get();
if (v->hide_from_editor)
continue;
if (p_custom.has(G->key()))
continue;
bool discard = false;
for (const Set<String>::Element *E = p_ignore_masks.front(); E; E = E->next()) {
if (String(G->key()).match(E->get())) {
discard = true;
break;
}
}
if (discard)
continue;
_VCSort vc;
vc.name = G->key(); //*k;
vc.order = v->order;
vc.type = v->variant.get_type();
vc.flags = PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE;
if (!v->persist)
continue;
vclist.insert(vc);
}
for (const Map<String, Variant>::Element *E = p_custom.front(); E; E = E->next()) {
_VCSort vc;
vc.name = E->key();
vc.order = 0xFFFFFFF;
vc.type = E->get().get_type();
vc.flags = PROPERTY_USAGE_STORAGE;
vclist.insert(vc);
}
Map<String, List<String> > props;
for (Set<_VCSort>::Element *E = vclist.front(); E; E = E->next()) {
String category = E->get().name;
String name = E->get().name;
int div = category.find("/");
if (div < 0)
category = "";
else {
category = category.substr(0, div);
name = name.substr(div + 1, name.size());
}
props[category].push_back(name);
}
if (p_path.ends_with(".cfg"))
return _save_settings_text(p_path, props, p_custom);
else if (p_path.ends_with(".cfb"))
return _save_settings_binary(p_path, props, p_custom);
else {
ERR_EXPLAIN("Unknown config file format: " + p_path);
ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
}
return OK;
#if 0
Error err = file->open(dst_file,FileAccess::WRITE);
if (err) {
memdelete(file);
ERR_EXPLAIN("Coudln't save engine.cfg");
ERR_FAIL_COND_V(err,err)
}
for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) {
if (E!=props.front())
file->store_string("\n");
if (E->key()!="")
file->store_string("["+E->key()+"]\n\n");
for(List<String>::Element *F=E->get().front();F;F=F->next()) {
String key = F->get();
if (E->key()!="")
key=E->key()+"/"+key;
Variant value;
if (p_custom.has(key))
value=p_custom[key];
else
value = get(key);
file->store_string(F->get()+"="+_encode_variant(value)+"\n");
}
}
file->close();
memdelete(file);
return OK;
#endif
}
Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default) {
if (Globals::get_singleton()->has(p_var))
return Globals::get_singleton()->get(p_var);
Globals::get_singleton()->set(p_var, p_default);
return p_default;
}
void Globals::add_singleton(const Singleton &p_singleton) {
singletons.push_back(p_singleton);
}
Object *Globals::get_singleton_object(const String &p_name) const {
for (const List<Singleton>::Element *E = singletons.front(); E; E = E->next()) {
if (E->get().name == p_name) {
return E->get().ptr;
};
};
return NULL;
};
bool Globals::has_singleton(const String &p_name) const {
return get_singleton_object(p_name) != NULL;
};
void Globals::get_singletons(List<Singleton> *p_singletons) {
for (List<Singleton>::Element *E = singletons.front(); E; E = E->next())
p_singletons->push_back(E->get());
}
Vector<String> Globals::get_optimizer_presets() const {
List<PropertyInfo> pi;
Globals::get_singleton()->get_property_list(&pi);
Vector<String> names;
for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
if (!E->get().name.begins_with("optimizer_presets/"))
continue;
names.push_back(E->get().name.get_slicec('/', 1));
}
names.sort();
return names;
}
void Globals::_add_property_info_bind(const Dictionary &p_info) {
ERR_FAIL_COND(!p_info.has("name"));
ERR_FAIL_COND(!p_info.has("type"));
PropertyInfo pinfo;
pinfo.name = p_info["name"];
ERR_FAIL_COND(!props.has(pinfo.name));
pinfo.type = Variant::Type(p_info["type"].operator int());
ERR_FAIL_INDEX(pinfo.type, Variant::VARIANT_MAX);
if (p_info.has("hint"))
pinfo.hint = PropertyHint(p_info["hint"].operator int());
if (p_info.has("hint_string"))
pinfo.hint_string = p_info["hint_string"];
set_custom_property_info(pinfo.name, pinfo);
}
void Globals::set_custom_property_info(const String &p_prop, const PropertyInfo &p_info) {
ERR_FAIL_COND(!props.has(p_prop));
custom_prop_info[p_prop] = p_info;
}
void Globals::set_disable_platform_override(bool p_disable) {
disable_platform_override = p_disable;
}
bool Globals::is_using_datapack() const {
return using_datapack;
}
void Globals::_bind_methods() {
ObjectTypeDB::bind_method(_MD("has", "name"), &Globals::has);
ObjectTypeDB::bind_method(_MD("set_order", "name", "pos"), &Globals::set_order);
ObjectTypeDB::bind_method(_MD("get_order", "name"), &Globals::get_order);
ObjectTypeDB::bind_method(_MD("set_persisting", "name", "enable"), &Globals::set_persisting);
ObjectTypeDB::bind_method(_MD("is_persisting", "name"), &Globals::is_persisting);
ObjectTypeDB::bind_method(_MD("add_property_info", "hint"), &Globals::_add_property_info_bind);
ObjectTypeDB::bind_method(_MD("clear", "name"), &Globals::clear);
ObjectTypeDB::bind_method(_MD("localize_path", "path"), &Globals::localize_path);
ObjectTypeDB::bind_method(_MD("globalize_path", "path"), &Globals::globalize_path);
ObjectTypeDB::bind_method(_MD("save"), &Globals::save);
ObjectTypeDB::bind_method(_MD("has_singleton", "name"), &Globals::has_singleton);
ObjectTypeDB::bind_method(_MD("get_singleton", "name"), &Globals::get_singleton_object);
ObjectTypeDB::bind_method(_MD("load_resource_pack", "pack"), &Globals::_load_resource_pack);
ObjectTypeDB::bind_method(_MD("save_custom", "file"), &Globals::_save_custom_bnd);
}
Globals::Globals() {
singleton = this;
last_order = 0;
disable_platform_override = false;
registering_order = true;
Array va;
InputEvent key;
key.type = InputEvent::KEY;
InputEvent joyb;
joyb.type = InputEvent::JOYSTICK_BUTTON;
set("application/name", "");
set("application/main_scene", "");
custom_prop_info["application/main_scene"] = PropertyInfo(Variant::STRING, "application/main_scene", PROPERTY_HINT_FILE, "tscn,scn,xscn,xml,res");
set("application/disable_stdout", false);
set("application/use_shared_user_dir", true);
key.key.scancode = KEY_RETURN;
va.push_back(key);
key.key.scancode = KEY_ENTER;
va.push_back(key);
key.key.scancode = KEY_SPACE;
va.push_back(key);
joyb.joy_button.button_index = JOY_BUTTON_0;
va.push_back(joyb);
set("input/ui_accept", va);
input_presets.push_back("input/ui_accept");
va = Array();
key.key.scancode = KEY_SPACE;
va.push_back(key);
joyb.joy_button.button_index = JOY_BUTTON_3;
va.push_back(joyb);
set("input/ui_select", va);
input_presets.push_back("input/ui_select");
va = Array();
key.key.scancode = KEY_ESCAPE;
va.push_back(key);
joyb.joy_button.button_index = JOY_BUTTON_1;
va.push_back(joyb);
set("input/ui_cancel", va);
input_presets.push_back("input/ui_cancel");
va = Array();
key.key.scancode = KEY_TAB;
va.push_back(key);
set("input/ui_focus_next", va);
input_presets.push_back("input/ui_focus_next");
va = Array();
key.key.scancode = KEY_TAB;
key.key.mod.shift = true;
va.push_back(key);
set("input/ui_focus_prev", va);
input_presets.push_back("input/ui_focus_prev");
key.key.mod.shift = false;
va = Array();
key.key.scancode = KEY_LEFT;
va.push_back(key);
joyb.joy_button.button_index = JOY_DPAD_LEFT;
va.push_back(joyb);
set("input/ui_left", va);
input_presets.push_back("input/ui_left");
va = Array();
key.key.scancode = KEY_RIGHT;
va.push_back(key);
joyb.joy_button.button_index = JOY_DPAD_RIGHT;
va.push_back(joyb);
set("input/ui_right", va);
input_presets.push_back("input/ui_right");
va = Array();
key.key.scancode = KEY_UP;
va.push_back(key);
joyb.joy_button.button_index = JOY_DPAD_UP;
va.push_back(joyb);
set("input/ui_up", va);
input_presets.push_back("input/ui_up");
va = Array();
key.key.scancode = KEY_DOWN;
va.push_back(key);
joyb.joy_button.button_index = JOY_DPAD_DOWN;
va.push_back(joyb);
set("input/ui_down", va);
input_presets.push_back("input/ui_down");
va = Array();
key.key.scancode = KEY_PAGEUP;
va.push_back(key);
set("input/ui_page_up", va);
input_presets.push_back("input/ui_page_up");
va = Array();
key.key.scancode = KEY_PAGEDOWN;
va.push_back(key);
set("input/ui_page_down", va);
input_presets.push_back("input/ui_page_down");
// set("display/orientation", "landscape");
custom_prop_info["display/orientation"] = PropertyInfo(Variant::STRING, "display/orientation", PROPERTY_HINT_ENUM, "landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor");
custom_prop_info["render/mipmap_policy"] = PropertyInfo(Variant::INT, "render/mipmap_policy", PROPERTY_HINT_ENUM, "Allow,Allow For Po2,Disallow");
custom_prop_info["render/thread_model"] = PropertyInfo(Variant::INT, "render/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded");
custom_prop_info["physics_2d/thread_model"] = PropertyInfo(Variant::INT, "physics_2d/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded");
set("debug/profiler_max_functions", 16384);
using_datapack = false;
}
Globals::~Globals() {
singleton = NULL;
}
| 25.579439 | 213 | 0.625111 | efornara |
d76252cbd49e296c5e5b764fc133dfb902f17032 | 82,785 | cpp | C++ | gui/qml_ValueSource_qml.cpp | kdeoliveira/coen320 | 4c788b3c2544e57e27bac8a59232f06c7a04d67a | [
"MIT"
] | null | null | null | gui/qml_ValueSource_qml.cpp | kdeoliveira/coen320 | 4c788b3c2544e57e27bac8a59232f06c7a04d67a | [
"MIT"
] | null | null | null | gui/qml_ValueSource_qml.cpp | kdeoliveira/coen320 | 4c788b3c2544e57e27bac8a59232f06c7a04d67a | [
"MIT"
] | null | null | null | // /qml/ValueSource.qml
namespace QmlCacheGeneratedCode {
namespace _qml_ValueSource_qml {
extern const unsigned char qmlData alignas(16) [] = {
0x71,0x76,0x34,0x63,0x64,0x61,0x74,0x61,
0x29,0x0,0x0,0x0,0x2,0xf,0x5,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x1c,0x4a,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x18,0x9c,0x6e,0x30,
0x6a,0x26,0x12,0xf0,0xa9,0x94,0x13,0xf2,
0x6,0xe9,0x8e,0xf7,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x23,0x0,0x0,0x0,
0x30,0x0,0x0,0x0,0x98,0x14,0x0,0x0,
0x37,0x0,0x0,0x0,0xf8,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0xd4,0x1,0x0,0x0,
0x0,0x0,0x0,0x0,0xd4,0x1,0x0,0x0,
0x0,0x0,0x0,0x0,0xd4,0x1,0x0,0x0,
0x5d,0x0,0x0,0x0,0xd4,0x1,0x0,0x0,
0x0,0x0,0x0,0x0,0x48,0x3,0x0,0x0,
0x1e,0x0,0x0,0x0,0x50,0x3,0x0,0x0,
0x0,0x0,0x0,0x0,0x40,0x4,0x0,0x0,
0x0,0x0,0x0,0x0,0x40,0x4,0x0,0x0,
0x0,0x0,0x0,0x0,0x40,0x4,0x0,0x0,
0x0,0x0,0x0,0x0,0x40,0x4,0x0,0x0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0x0,0x0,0x0,0x0,
0x54,0x0,0x0,0x0,0x54,0x0,0x0,0x0,
0x54,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x54,0x0,0x0,0x0,0x54,0x0,0x0,0x0,
0x0,0x0,0x1,0x0,0x54,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x6c,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x6c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x6c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x1c,0x0,0x0,0x0,0x0,0x0,0x7,0x0,
0x36,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x41,0x1,0xc0,0x1,0x41,0x1,0x20,0x2,
0x0,0x0,0x0,0x0,0x11,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x0,0x0,0xff,0xff,
0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0,
0x54,0x0,0x0,0x0,0x54,0x0,0x0,0x0,
0x54,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x54,0x0,0x0,0x0,0x54,0x0,0x0,0x0,
0x0,0x0,0x1,0x0,0x54,0x0,0x0,0x0,
0x0,0x0,0x0,0x0,0x6c,0x0,0x0,0x0,
0x47,0x1,0xd0,0x0,0x0,0x0,0x0,0x0,
0x6c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x6c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x12,0x0,0x0,0x0,0x0,0x0,0x2,0x0,
0x16,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
0x48,0x1,0x10,0x1,0x48,0x1,0xb0,0x1,
0x0,0x0,0x0,0x0
};
}
}
| 34.769005 | 53 | 0.741729 | kdeoliveira |
d76c5e1056032cf26b5dd543c0d220d56e78439e | 450 | cpp | C++ | Plugins/RadiantUI/Source/RadiantUI/Private/RadiantWebViewInputMaskedActionList.cpp | joeriedel/RadiantUI | 64c7d7719dc3c519bacaed8912c6937a549b4f8a | [
"MIT"
] | 104 | 2015-01-01T17:48:03.000Z | 2021-09-23T12:45:21.000Z | Plugins/RadiantUI/Source/RadiantUI/Private/RadiantWebViewInputMaskedActionList.cpp | ChairGraveyard/RadiantUI | 2d395ae509e40fed96afa7dc73d86c7a3d99fa51 | [
"MIT"
] | 7 | 2015-03-22T22:30:00.000Z | 2017-09-22T10:42:04.000Z | Plugins/RadiantUI/Source/RadiantUI/Private/RadiantWebViewInputMaskedActionList.cpp | ChairGraveyard/RadiantUI | 2d395ae509e40fed96afa7dc73d86c7a3d99fa51 | [
"MIT"
] | 60 | 2015-01-05T21:05:16.000Z | 2022-01-14T09:12:09.000Z | // Copyright 2014 Joseph Riedel, All Rights Reserved.
// See LICENSE for licensing terms.
#pragma once
#include "RadiantUIPrivatePCH.h"
URadiantWebViewInputMaskedActionList::URadiantWebViewInputMaskedActionList(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
ActionMappings.Add("Jump");
ActionMappings.Add("RunModifier");
ActionMappings.Add("Fire");
AxisMappings.Add("MoveForward");
AxisMappings.Add("MoveRight");
} | 26.470588 | 119 | 0.8 | joeriedel |
d7716b73035465bd41692317626bad6c81f8b22d | 15,348 | cpp | C++ | tests/unit/basis/lagrange_basis2d.cpp | Andlon/crest | f79bf5a68f3eb86f5e3422881678bc6f9011730a | [
"MIT"
] | null | null | null | tests/unit/basis/lagrange_basis2d.cpp | Andlon/crest | f79bf5a68f3eb86f5e3422881678bc6f9011730a | [
"MIT"
] | 5 | 2017-01-24T10:45:27.000Z | 2017-01-27T16:21:37.000Z | tests/unit/basis/lagrange_basis2d.cpp | Andlon/crest | f79bf5a68f3eb86f5e3422881678bc6f9011730a | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <crest/geometry/indexed_mesh.hpp>
#include <crest/basis/lagrange_basis2d.hpp>
#include <util/eigen_matchers.hpp>
using ::testing::ElementsAreArray;
using ::testing::Pointwise;
using ::testing::Eq;
using ::testing::DoubleEq;
using crest::IndexedMesh;
using crest::LagrangeBasis2d;
typedef IndexedMesh<double, int>::Vertex Vertex;
typedef IndexedMesh<double, int>::Element Element;
class linear_lagrangian_basis_test : public ::testing::Test
{
protected:
virtual void SetUp()
{
vertices_unit_square_basic = {
Vertex(0.0, 0.0),
Vertex(0.0, 1.0),
Vertex(1.0, 1.0),
Vertex(1.0, 0.0)
};
elements_unit_square_basic = {
Element({3, 0, 1}),
Element({1, 2, 3})
};
vertices_unit_square_1_interior_node = {
Vertex(0.0, 0.0),
Vertex(1.0, 0.0),
Vertex(1.0, 1.0),
Vertex(0.0, 1.0),
Vertex(0.5, 0.5)
};
elements_unit_square_1_interior_node = {
Element({0, 1, 4}),
Element({1, 2, 4}),
Element({2, 3, 4}),
Element({3, 0, 4})
};
vertices_unit_square_5_interior_nodes = {
Vertex(0.0, 0.0),
Vertex(0.5, 0.0),
Vertex(1.0, 0.0),
Vertex(0.75, 0.25),
Vertex(0.25, 0.25),
Vertex(0.0, 0.5),
Vertex(0.5, 0.5),
Vertex(1.0, 0.5),
Vertex(0.75, 0.75),
Vertex(0.25, 0.75),
Vertex(0.0, 1.0),
Vertex(0.5, 1.0),
Vertex(1.0, 1.0)
};
elements_unit_square_5_interior_nodes = {
Element({0, 4, 5}),
Element({0, 1, 4}),
Element({1, 3, 4}),
Element({1, 2, 3}),
Element({2, 7, 3}),
Element({7, 8, 3}),
Element({3, 8, 6}),
Element({6, 4, 3}),
Element({4, 6, 9}),
Element({4, 9, 5}),
Element({5, 9, 10}),
Element({10, 9, 11}),
Element({9, 8, 11}),
Element({8, 12, 11}),
Element({7, 12, 8}),
Element({6, 8, 9})
};
}
// The simplest possible triangulation of the unit square
std::vector<Vertex> vertices_unit_square_basic;
std::vector<Element> elements_unit_square_basic;
std::vector<Vertex> vertices_unit_square_1_interior_node;
std::vector<Element> elements_unit_square_1_interior_node;
// A triangulation of the unit square with a regular pattern consisting of 13 vertices and 15 triangles,
// showcasing vertices both on the boundary and in the interior.
std::vector<Vertex> vertices_unit_square_5_interior_nodes;
std::vector<Element> elements_unit_square_5_interior_nodes;
};
TEST_F(linear_lagrangian_basis_test, assemble_mass_matrix_1_interior_node)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_1_interior_node, elements_unit_square_1_interior_node);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto assembly = basis.assemble();
// For historical reasons, there's only the values for entries of the
// "interior" and "boundary" parts of the matrix available
const auto interior = mesh.compute_interior_vertices();
const auto interior_mass = sparse_submatrix(assembly.mass, interior, interior);
EXPECT_THAT(interior_mass.rows(), Eq(1));
EXPECT_THAT(interior_mass.cols(), Eq(1));
EXPECT_THAT(interior_mass.coeff(0, 0), DoubleEq(1.0 / 6.0));
const auto boundary = mesh.boundary_vertices();
const Eigen::MatrixXd boundary_mass = sparse_submatrix(assembly.mass, interior, boundary);
Eigen::Matrix<double, 1, 4> expected_boundary_mass;
expected_boundary_mass << (1.0 / 24.0), (1.0 / 24.0), (1.0 / 24.0), (1.0 / 24.0);
EXPECT_THAT(boundary_mass.rows(), Eq(1));
EXPECT_THAT(boundary_mass.cols(), Eq(4));
EXPECT_TRUE(boundary_mass.isApprox(expected_boundary_mass));
}
TEST_F(linear_lagrangian_basis_test, assemble_stiffness_matrix_1_interior_node)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_1_interior_node, elements_unit_square_1_interior_node);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto assembly = basis.assemble();
// For historical reasons, there's only the values for entries of the
// "interior" and "boundary" parts of the matrix available
const auto interior = mesh.compute_interior_vertices();
const auto interior_stiffness = sparse_submatrix(assembly.stiffness, interior, interior);
EXPECT_THAT(interior_stiffness.rows(), Eq(1));
EXPECT_THAT(interior_stiffness.cols(), Eq(1));
EXPECT_THAT(interior_stiffness.coeff(0, 0), DoubleEq(4.0));
const auto boundary = mesh.boundary_vertices();
const Eigen::MatrixXd boundary_stiffness = sparse_submatrix(assembly.stiffness, interior, boundary);
Eigen::Matrix<double, 1, 4> expected_boundary_stiffness;
expected_boundary_stiffness << -1.0, -1.0, -1.0, -1.0;
EXPECT_THAT(boundary_stiffness.rows(), Eq(1));
EXPECT_THAT(boundary_stiffness.cols(), Eq(4));
EXPECT_TRUE(boundary_stiffness.isApprox(expected_boundary_stiffness));
}
TEST_F(linear_lagrangian_basis_test, assemble_mass_matrix_5_interior_nodes)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_5_interior_nodes, elements_unit_square_5_interior_nodes);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto assembly = basis.assemble();
const auto interior = mesh.compute_interior_vertices();
const auto boundary = mesh.boundary_vertices();
// For historical reasons, there's only the values for entries of the
// "interior" and "boundary" parts of the matrix available
{
const auto interior_mass = sparse_submatrix(assembly.mass, interior, interior);
// The expected data is obtained through laborious semi-manual calculations,
// exploiting symmetry of the mesh to reduce work. I set up the integrals,
// and solved them with Mathematica.
const auto a = 1.0 / 16.0;
const auto b = 1.0 / 96.0;
const auto c = 1.0 / 96.0;
const auto d = 1.0 / 24.0;
Eigen::Matrix<double, 5, 5> expected_interior;
expected_interior <<
a, b, c, b, 0.0,
b, a, c, 0.0, b,
c, c, d, c, c,
b, 0.0, c, a, b,
0.0, b, c, b, a;
EXPECT_THAT(interior_mass.rows(), Eq(5));
EXPECT_THAT(interior_mass.cols(), Eq(5));
EXPECT_TRUE(interior_mass.isApprox(expected_interior));
}
{
const auto boundary_mass = sparse_submatrix(assembly.mass, interior, boundary);
const auto a = 1.0 / 96.0;
const auto b = 1.0 / 96.0;
Eigen::Matrix<double, 5, 8> expected_boundary;
expected_boundary.setZero();
expected_boundary(0, 1) = b;
expected_boundary(0, 2) = a;
expected_boundary(0, 4) = b;
expected_boundary(1, 0) = a;
expected_boundary(1, 1) = b;
expected_boundary(1, 3) = b;
expected_boundary(3, 4) = b;
expected_boundary(3, 6) = b;
expected_boundary(3, 7) = a;
expected_boundary(4, 3) = b;
expected_boundary(4, 5) = a;
expected_boundary(4, 6) = b;
EXPECT_THAT(boundary_mass.rows(), Eq(5));
EXPECT_THAT(boundary_mass.cols(), Eq(8));
EXPECT_TRUE(boundary_mass.isApprox(expected_boundary));
}
}
TEST_F(linear_lagrangian_basis_test, assemble_stiffness_matrix_5_interior_nodes)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_5_interior_nodes, elements_unit_square_5_interior_nodes);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto assembly = basis.assemble();
const auto interior = mesh.compute_interior_vertices();
const auto boundary = mesh.boundary_vertices();
// For historical reasons, there's only the values for entries of the
// "interior" and "boundary" parts of the matrix available
// The expected data is obtained through laborious semi-manual calculations,
// exploiting symmetry of the mesh to reduce work. I set up the integrals,
// and solved them with Mathematica.
{
const auto interior_stiffness = sparse_submatrix(assembly.stiffness, interior, interior);
const auto a = 4.0;
const auto b = 0.0;
const auto c = -1.0;
const auto d = 4.0;
Eigen::Matrix<double, 5, 5> expected_interior;
expected_interior <<
a, b, c, b, 0.0,
b, a, c, 0.0, b,
c, c, d, c, c,
b, 0.0, c, a, b,
0.0, b, c, b, a;
EXPECT_THAT(interior_stiffness.rows(), Eq(5));
EXPECT_THAT(interior_stiffness.cols(), Eq(5));
EXPECT_TRUE(interior_stiffness.isApprox(expected_interior));
}
{
const auto boundary_stiffness = sparse_submatrix(assembly.stiffness, interior, boundary);
const auto a = -1.0;
const auto b = -1.0;
Eigen::Matrix<double, 5, 8> expected_boundary;
expected_boundary.setZero();
expected_boundary(0, 1) = b;
expected_boundary(0, 2) = a;
expected_boundary(0, 4) = b;
expected_boundary(1, 0) = a;
expected_boundary(1, 1) = b;
expected_boundary(1, 3) = b;
expected_boundary(3, 4) = b;
expected_boundary(3, 6) = b;
expected_boundary(3, 7) = a;
expected_boundary(4, 3) = b;
expected_boundary(4, 5) = a;
expected_boundary(4, 6) = b;
EXPECT_THAT(boundary_stiffness.rows(), Eq(5));
EXPECT_THAT(boundary_stiffness.cols(), Eq(8));
EXPECT_TRUE(boundary_stiffness.isApprox(expected_boundary));
}
}
TEST_F(linear_lagrangian_basis_test, compute_load_zero_1_interior_node)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_1_interior_node, elements_unit_square_1_interior_node);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto f = [] (auto, auto) { return 0.0; };
Eigen::VectorXd expected(5);
expected.setZero();
EXPECT_TRUE(basis.load<1>(f).isApprox(expected));
}
TEST_F(linear_lagrangian_basis_test, compute_load_zero_5_interior_nodes)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_5_interior_nodes, elements_unit_square_5_interior_nodes);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto f = [] (auto, auto) { return 0.0; };
Eigen::VectorXd expected(13);
expected.setZero();
EXPECT_TRUE(basis.load<1>(f).isApprox(expected));
}
TEST_F(linear_lagrangian_basis_test, compute_load_one_1_interior_node)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_1_interior_node, elements_unit_square_1_interior_node);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto interior = mesh.compute_interior_vertices();
const auto f = [] (auto, auto) { return 1.0; };
// For historical reasons, we only have expected values for the interior nodes
const auto load = basis.load<1>(f);
const auto load_interior = submatrix(load, interior, { 0 });
Eigen::VectorXd expected(1);
expected << (1.0 / 3.0);
EXPECT_TRUE(load_interior.isApprox(expected));
}
TEST_F(linear_lagrangian_basis_test, compute_quadratic_function_5_interior_node)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_5_interior_nodes, elements_unit_square_5_interior_nodes);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto interior = mesh.compute_interior_vertices();
const auto f = [] (auto x, auto y) { return (x - 0.5) * (x - 0.5) + (y - 0.5) * (y - 0.5) - 2; };
const auto load = basis.load<10>(f);
const auto load_interior = submatrix(load, interior, { 0 });
const auto a = -15.0 / 64.0;
const auto b = -79.0 / 480.0;
Eigen::VectorXd expected(5);
expected << a, a, b, a, a;
EXPECT_TRUE(load_interior.isApprox(expected));
}
TEST_F(linear_lagrangian_basis_test, interpolate_1_interior_node)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_1_interior_node, elements_unit_square_1_interior_node);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto f = [] (auto x, auto y) { return x * x + y * y + 1.0; };
const auto weights = basis.interpolate(f);
EXPECT_THAT(weights(0), DoubleEq(1.0));
EXPECT_THAT(weights(1), DoubleEq(2.0));
EXPECT_THAT(weights(2), DoubleEq(3.0));
EXPECT_THAT(weights(3), DoubleEq(2.0));
EXPECT_THAT(weights(4), DoubleEq(1.5));
}
TEST_F(linear_lagrangian_basis_test, interpolate_boundary_1_interior_node)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_1_interior_node, elements_unit_square_1_interior_node);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto f = [] (auto x, auto y) { return x * x + y * y + 1.0; };
const auto weights = basis.interpolate_boundary(f);
EXPECT_THAT(weights.rows(), Eq(4));
EXPECT_THAT(weights(0), DoubleEq(1.0));
EXPECT_THAT(weights(1), DoubleEq(2.0));
EXPECT_THAT(weights(2), DoubleEq(3.0));
EXPECT_THAT(weights(3), DoubleEq(2.0));
}
TEST_F(linear_lagrangian_basis_test, error_l2_basic_unit_square)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_basic, elements_unit_square_basic);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto u = [] (auto x, auto y) { return x * x + y * y; };
VectorX<double> weights(4);
weights << 0.0, 1.0, 2.0, 1.0;
const auto expected_error = std::sqrt(11.0 / 90.0);
EXPECT_THAT(basis.error_l2<10>(u, weights), DoubleEq(expected_error));
}
TEST_F(linear_lagrangian_basis_test, error_h1_semi_basic_unit_square)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_basic, elements_unit_square_basic);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto u_x = [] (auto x, auto ) { return 2.0 * x; };
const auto u_y = [] (auto , auto y) { return 2.0 * y; };
VectorX<double> weights(4);
weights << 0.0, 1.0, 2.0, 1.0;
const auto expected_error = std::sqrt(2.0 / 3.0);
EXPECT_THAT(basis.error_h1_semi<10>(u_x, u_y, weights), DoubleEq(expected_error));
}
TEST_F(linear_lagrangian_basis_test, error_h1_basic_unit_square)
{
const auto mesh = IndexedMesh<double, int>(vertices_unit_square_basic, elements_unit_square_basic);
const auto basis = LagrangeBasis2d<double>(mesh);
const auto u = [] (auto x, auto y) { return x * x + y * y; };
const auto u_x = [] (auto x, auto ) { return 2.0 * x; };
const auto u_y = [] (auto , auto y) { return 2.0 * y; };
VectorX<double> weights(4);
weights << 0.0, 1.0, 2.0, 1.0;
const auto expected_error = std::sqrt(11.0 / 90.0 + 2.0 / 3.0);
EXPECT_THAT(basis.error_h1<10>(u, u_x, u_y, weights), DoubleEq(expected_error));
}
| 35.859813 | 125 | 0.636435 | Andlon |
d772561827fe4727116b31daee35cd4d38694a71 | 32,127 | cpp | C++ | export/release/windows/obj/src/flixel/input/mouse/FlxMouse.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | export/release/windows/obj/src/flixel/input/mouse/FlxMouse.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | export/release/windows/obj/src/flixel/input/mouse/FlxMouse.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_Type
#include <Type.h>
#endif
#ifndef INCLUDED_flixel_FlxG
#include <flixel/FlxG.h>
#endif
#ifndef INCLUDED_flixel_FlxGame
#include <flixel/FlxGame.h>
#endif
#ifndef INCLUDED_flixel_input_FlxInput
#include <flixel/input/FlxInput.h>
#endif
#ifndef INCLUDED_flixel_input_FlxPointer
#include <flixel/input/FlxPointer.h>
#endif
#ifndef INCLUDED_flixel_input_IFlxInput
#include <flixel/input/IFlxInput.h>
#endif
#ifndef INCLUDED_flixel_input_IFlxInputManager
#include <flixel/input/IFlxInputManager.h>
#endif
#ifndef INCLUDED_flixel_input_mouse_FlxMouse
#include <flixel/input/mouse/FlxMouse.h>
#endif
#ifndef INCLUDED_flixel_input_mouse_FlxMouseButton
#include <flixel/input/mouse/FlxMouseButton.h>
#endif
#ifndef INCLUDED_flixel_input_mouse__FlxMouse_GraphicCursor
#include <flixel/input/mouse/_FlxMouse/GraphicCursor.h>
#endif
#ifndef INCLUDED_flixel_math_FlxPoint
#include <flixel/math/FlxPoint.h>
#endif
#ifndef INCLUDED_flixel_system_frontEnds_SignalFrontEnd
#include <flixel/system/frontEnds/SignalFrontEnd.h>
#endif
#ifndef INCLUDED_flixel_system_scaleModes_BaseScaleMode
#include <flixel/system/scaleModes/BaseScaleMode.h>
#endif
#ifndef INCLUDED_flixel_util_FlxDestroyUtil
#include <flixel/util/FlxDestroyUtil.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxPooled
#include <flixel/util/IFlxPooled.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxSignal
#include <flixel/util/IFlxSignal.h>
#endif
#ifndef INCLUDED_flixel_util__FlxSignal_FlxBaseSignal
#include <flixel/util/_FlxSignal/FlxBaseSignal.h>
#endif
#ifndef INCLUDED_flixel_util__FlxSignal_FlxSignal0
#include <flixel/util/_FlxSignal/FlxSignal0.h>
#endif
#ifndef INCLUDED_lime_app_IModule
#include <lime/app/IModule.h>
#endif
#ifndef INCLUDED_openfl_Lib
#include <openfl/Lib.h>
#endif
#ifndef INCLUDED_openfl_display_Bitmap
#include <openfl/display/Bitmap.h>
#endif
#ifndef INCLUDED_openfl_display_BitmapData
#include <openfl/display/BitmapData.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObject
#include <openfl/display/DisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectContainer
#include <openfl/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display_InteractiveObject
#include <openfl/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_openfl_display_MovieClip
#include <openfl/display/MovieClip.h>
#endif
#ifndef INCLUDED_openfl_display_Sprite
#include <openfl/display/Sprite.h>
#endif
#ifndef INCLUDED_openfl_display_Stage
#include <openfl/display/Stage.h>
#endif
#ifndef INCLUDED_openfl_events_Event
#include <openfl/events/Event.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_MouseEvent
#include <openfl/events/MouseEvent.h>
#endif
#ifndef INCLUDED_openfl_ui_Mouse
#include <openfl/ui/Mouse.h>
#endif
#ifndef INCLUDED_openfl_utils_Assets
#include <openfl/utils/Assets.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_34_new,"flixel.input.mouse.FlxMouse","new",0x1251bd04,"flixel.input.mouse.FlxMouse.new","flixel/input/mouse/FlxMouse.hx",34,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_205_load,"flixel.input.mouse.FlxMouse","load",0xf3e8bd02,"flixel.input.mouse.FlxMouse.load","flixel/input/mouse/FlxMouse.hx",205,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_363_destroy,"flixel.input.mouse.FlxMouse","destroy",0x77a13b9e,"flixel.input.mouse.FlxMouse.destroy","flixel/input/mouse/FlxMouse.hx",363,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_402_reset,"flixel.input.mouse.FlxMouse","reset",0xe595a773,"flixel.input.mouse.FlxMouse.reset","flixel/input/mouse/FlxMouse.hx",402,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_451_update,"flixel.input.mouse.FlxMouse","update",0x7bea17e5,"flixel.input.mouse.FlxMouse.update","flixel/input/mouse/FlxMouse.hx",451,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_485_onFocus,"flixel.input.mouse.FlxMouse","onFocus",0xede20cdd,"flixel.input.mouse.FlxMouse.onFocus","flixel/input/mouse/FlxMouse.hx",485,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_499_onFocusLost,"flixel.input.mouse.FlxMouse","onFocusLost",0xc7f71561,"flixel.input.mouse.FlxMouse.onFocusLost","flixel/input/mouse/FlxMouse.hx",499,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_516_onGameStart,"flixel.input.mouse.FlxMouse","onGameStart",0x61da7695,"flixel.input.mouse.FlxMouse.onGameStart","flixel/input/mouse/FlxMouse.hx",516,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_524_onMouseWheel,"flixel.input.mouse.FlxMouse","onMouseWheel",0xdc642911,"flixel.input.mouse.FlxMouse.onMouseWheel","flixel/input/mouse/FlxMouse.hx",524,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_537_onMouseLeave,"flixel.input.mouse.FlxMouse","onMouseLeave",0x84fd296d,"flixel.input.mouse.FlxMouse.onMouseLeave","flixel/input/mouse/FlxMouse.hx",537,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_585_showSystemCursor,"flixel.input.mouse.FlxMouse","showSystemCursor",0xf4551c9e,"flixel.input.mouse.FlxMouse.showSystemCursor","flixel/input/mouse/FlxMouse.hx",585,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_596_hideSystemCursor,"flixel.input.mouse.FlxMouse","hideSystemCursor",0xb5438fe3,"flixel.input.mouse.FlxMouse.hideSystemCursor","flixel/input/mouse/FlxMouse.hx",596,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_613_set_useSystemCursor,"flixel.input.mouse.FlxMouse","set_useSystemCursor",0x074e74d3,"flixel.input.mouse.FlxMouse.set_useSystemCursor","flixel/input/mouse/FlxMouse.hx",613,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_627_showCursor,"flixel.input.mouse.FlxMouse","showCursor",0xa585e38f,"flixel.input.mouse.FlxMouse.showCursor","flixel/input/mouse/FlxMouse.hx",627,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_646_hideCursor,"flixel.input.mouse.FlxMouse","hideCursor",0xd396e514,"flixel.input.mouse.FlxMouse.hideCursor","flixel/input/mouse/FlxMouse.hx",646,0xe4e80b89)
HX_LOCAL_STACK_FRAME(_hx_pos_dcc29ee8d0f87524_652_set_visible,"flixel.input.mouse.FlxMouse","set_visible",0xb9fd1039,"flixel.input.mouse.FlxMouse.set_visible","flixel/input/mouse/FlxMouse.hx",652,0xe4e80b89)
namespace flixel{
namespace input{
namespace mouse{
void FlxMouse_obj::__construct( ::openfl::display::Sprite cursorContainer){
HX_GC_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_34_new)
HXLINE( 179) this->_prevY = 0;
HXLINE( 177) this->_prevX = 0;
HXLINE( 163) this->_visibleWhenFocusLost = true;
HXLINE( 162) this->_wheelUsed = false;
HXLINE( 159) this->_cursor = null();
HXLINE( 63) this->useSystemCursor = false;
HXLINE( 58) this->visible = true;
HXLINE( 46) this->wheel = 0;
HXLINE( 40) this->enabled = true;
HXLINE( 417) super::__construct();
HXLINE( 418) this->cursorContainer = cursorContainer;
HXLINE( 419) this->cursorContainer->mouseChildren = false;
HXLINE( 420) this->cursorContainer->mouseEnabled = false;
HXLINE( 422) this->_leftButton = ::flixel::input::mouse::FlxMouseButton_obj::__alloc( HX_CTX ,-1);
HXLINE( 424) this->_stage = ::openfl::Lib_obj::get_current()->stage;
HXLINE( 425) this->_stage->addEventListener(HX_("mouseDown",27,b1,c2,ee),this->_leftButton->onDown_dyn(),null(),null(),null());
HXLINE( 426) this->_stage->addEventListener(HX_("mouseUp",e0,f3,72,c0),this->_leftButton->onUp_dyn(),null(),null(),null());
HXLINE( 429) this->_middleButton = ::flixel::input::mouse::FlxMouseButton_obj::__alloc( HX_CTX ,-2);
HXLINE( 430) this->_rightButton = ::flixel::input::mouse::FlxMouseButton_obj::__alloc( HX_CTX ,-3);
HXLINE( 432) this->_stage->addEventListener(HX_("middleMouseDown",12,2b,fe,01),this->_middleButton->onDown_dyn(),null(),null(),null());
HXLINE( 433) this->_stage->addEventListener(HX_("middleMouseUp",0b,8d,f5,3a),this->_middleButton->onUp_dyn(),null(),null(),null());
HXLINE( 434) this->_stage->addEventListener(HX_("rightMouseDown",ab,29,d7,cd),this->_rightButton->onDown_dyn(),null(),null(),null());
HXLINE( 435) this->_stage->addEventListener(HX_("rightMouseUp",64,83,21,ab),this->_rightButton->onUp_dyn(),null(),null(),null());
HXLINE( 437) this->_stage->addEventListener(HX_("mouseLeave",92,28,20,90),this->onMouseLeave_dyn(),null(),null(),null());
HXLINE( 440) this->_stage->addEventListener(HX_("mouseWheel",36,28,87,e7),this->onMouseWheel_dyn(),null(),null(),null());
HXLINE( 442) ::flixel::FlxG_obj::signals->postGameStart->add(this->onGameStart_dyn());
HXLINE( 443) ::openfl::ui::Mouse_obj::hide();
}
Dynamic FlxMouse_obj::__CreateEmpty() { return new FlxMouse_obj; }
void *FlxMouse_obj::_hx_vtable = 0;
Dynamic FlxMouse_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< FlxMouse_obj > _hx_result = new FlxMouse_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool FlxMouse_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x5316fc32) {
return inClassId==(int)0x00000001 || inClassId==(int)0x5316fc32;
} else {
return inClassId==(int)0x62adae31;
}
}
static ::flixel::input::IFlxInputManager_obj _hx_flixel_input_mouse_FlxMouse__hx_flixel_input_IFlxInputManager= {
( void (::hx::Object::*)())&::flixel::input::mouse::FlxMouse_obj::destroy,
( void (::hx::Object::*)())&::flixel::input::mouse::FlxMouse_obj::reset,
( void (::hx::Object::*)())&::flixel::input::mouse::FlxMouse_obj::update,
( void (::hx::Object::*)())&::flixel::input::mouse::FlxMouse_obj::onFocus,
( void (::hx::Object::*)())&::flixel::input::mouse::FlxMouse_obj::onFocusLost,
};
static ::flixel::util::IFlxDestroyable_obj _hx_flixel_input_mouse_FlxMouse__hx_flixel_util_IFlxDestroyable= {
( void (::hx::Object::*)())&::flixel::input::mouse::FlxMouse_obj::destroy,
};
void *FlxMouse_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0x65dd217a: return &_hx_flixel_input_mouse_FlxMouse__hx_flixel_input_IFlxInputManager;
case (int)0xd4fe2fcd: return &_hx_flixel_input_mouse_FlxMouse__hx_flixel_util_IFlxDestroyable;
}
return super::_hx_getInterface(inHash);
}
void FlxMouse_obj::load( ::Dynamic Graphic,::hx::Null< Float > __o_Scale,::hx::Null< int > __o_XOffset,::hx::Null< int > __o_YOffset){
Float Scale = __o_Scale.Default(1);
int XOffset = __o_XOffset.Default(0);
int YOffset = __o_YOffset.Default(0);
HX_GC_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_205_load)
HXLINE( 207) if (::hx::IsNotNull( this->_cursor )) {
HXLINE( 209) ::flixel::util::FlxDestroyUtil_obj::removeChild(this->cursorContainer,this->_cursor);
}
HXLINE( 213) if (::hx::IsNull( Graphic )) {
HXLINE( 215) Graphic = ::flixel::input::mouse::_FlxMouse::GraphicCursor_obj::__alloc( HX_CTX ,0,0,null(),null());
}
HXLINE( 218) if (::Std_obj::isOfType(Graphic,::hx::ClassOf< ::hx::Class >())) {
HXLINE( 220) this->_cursor = ( ( ::openfl::display::Bitmap)(::Type_obj::createInstance(Graphic,::cpp::VirtualArray_obj::__new(0))) );
}
else {
HXLINE( 222) if (::Std_obj::isOfType(Graphic,::hx::ClassOf< ::openfl::display::BitmapData >())) {
HXLINE( 224) this->_cursor = ::openfl::display::Bitmap_obj::__alloc( HX_CTX ,( ( ::openfl::display::BitmapData)(Graphic) ),null(),null());
}
else {
HXLINE( 226) if (::Std_obj::isOfType(Graphic,::hx::ClassOf< ::String >())) {
HXLINE( 228) ::String id = ( (::String)(Graphic) );
HXDLIN( 228) ::openfl::display::BitmapData _hx_tmp;
HXDLIN( 228) if (::openfl::utils::Assets_obj::exists(id,null())) {
HXLINE( 228) _hx_tmp = ::openfl::utils::Assets_obj::getBitmapData(id,false);
}
else {
HXLINE( 228) _hx_tmp = null();
}
HXDLIN( 228) this->_cursor = ::openfl::display::Bitmap_obj::__alloc( HX_CTX ,_hx_tmp,null(),null());
}
else {
HXLINE( 232) this->_cursor = ::openfl::display::Bitmap_obj::__alloc( HX_CTX , ::flixel::input::mouse::_FlxMouse::GraphicCursor_obj::__alloc( HX_CTX ,0,0,null(),null()),null(),null());
}
}
}
HXLINE( 235) this->_cursor->set_x(( (Float)(XOffset) ));
HXLINE( 236) this->_cursor->set_y(( (Float)(YOffset) ));
HXLINE( 237) this->_cursor->set_scaleX(Scale);
HXLINE( 238) this->_cursor->set_scaleY(Scale);
HXLINE( 267) this->cursorContainer->addChild(this->_cursor);
}
HX_DEFINE_DYNAMIC_FUNC4(FlxMouse_obj,load,(void))
void FlxMouse_obj::destroy(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_363_destroy)
HXLINE( 364) if (::hx::IsNotNull( this->_stage )) {
HXLINE( 366) this->_stage->removeEventListener(HX_("mouseDown",27,b1,c2,ee),this->_leftButton->onDown_dyn(),null());
HXLINE( 367) this->_stage->removeEventListener(HX_("mouseUp",e0,f3,72,c0),this->_leftButton->onUp_dyn(),null());
HXLINE( 370) this->_stage->removeEventListener(HX_("middleMouseDown",12,2b,fe,01),this->_middleButton->onDown_dyn(),null());
HXLINE( 371) this->_stage->removeEventListener(HX_("middleMouseUp",0b,8d,f5,3a),this->_middleButton->onUp_dyn(),null());
HXLINE( 372) this->_stage->removeEventListener(HX_("rightMouseDown",ab,29,d7,cd),this->_rightButton->onDown_dyn(),null());
HXLINE( 373) this->_stage->removeEventListener(HX_("rightMouseUp",64,83,21,ab),this->_rightButton->onUp_dyn(),null());
HXLINE( 375) this->_stage->removeEventListener(HX_("mouseLeave",92,28,20,90),this->onMouseLeave_dyn(),null());
HXLINE( 378) this->_stage->removeEventListener(HX_("mouseWheel",36,28,87,e7),this->onMouseWheel_dyn(),null());
}
HXLINE( 381) this->cursorContainer = null();
HXLINE( 382) this->_cursor = null();
HXLINE( 388) this->_leftButton = ( ( ::flixel::input::mouse::FlxMouseButton)(::flixel::util::FlxDestroyUtil_obj::destroy(this->_leftButton)) );
HXLINE( 390) this->_middleButton = ( ( ::flixel::input::mouse::FlxMouseButton)(::flixel::util::FlxDestroyUtil_obj::destroy(this->_middleButton)) );
HXLINE( 391) this->_rightButton = ( ( ::flixel::input::mouse::FlxMouseButton)(::flixel::util::FlxDestroyUtil_obj::destroy(this->_rightButton)) );
HXLINE( 394) this->_cursorBitmapData = ::flixel::util::FlxDestroyUtil_obj::dispose(this->_cursorBitmapData);
HXLINE( 395) ::flixel::FlxG_obj::signals->postGameStart->remove(this->onGameStart_dyn());
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,destroy,(void))
void FlxMouse_obj::reset(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_402_reset)
HXLINE( 403) this->_leftButton->reset();
HXLINE( 406) this->_middleButton->reset();
HXLINE( 407) this->_rightButton->reset();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,reset,(void))
void FlxMouse_obj::update(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_451_update)
HXLINE( 452) this->_prevX = this->x;
HXLINE( 453) this->_prevY = this->y;
HXLINE( 456) {
HXLINE( 456) Float newX = ::flixel::FlxG_obj::game->get_mouseX();
HXDLIN( 456) Float newY = ::flixel::FlxG_obj::game->get_mouseY();
HXDLIN( 456) this->_globalScreenX = ::Std_obj::_hx_int((newX / ::flixel::FlxG_obj::scaleMode->scale->x));
HXDLIN( 456) this->_globalScreenY = ::Std_obj::_hx_int((newY / ::flixel::FlxG_obj::scaleMode->scale->y));
HXDLIN( 456) this->updatePositions();
}
HXLINE( 459) if (this->visible) {
HXLINE( 461) ::openfl::display::Sprite _hx_tmp = this->cursorContainer;
HXDLIN( 461) _hx_tmp->set_x(::flixel::FlxG_obj::game->get_mouseX());
HXLINE( 462) ::openfl::display::Sprite _hx_tmp1 = this->cursorContainer;
HXDLIN( 462) _hx_tmp1->set_y(::flixel::FlxG_obj::game->get_mouseY());
}
HXLINE( 467) this->_leftButton->update();
HXLINE( 469) this->_middleButton->update();
HXLINE( 470) this->_rightButton->update();
HXLINE( 474) if (!(this->_wheelUsed)) {
HXLINE( 476) this->wheel = 0;
}
HXLINE( 478) this->_wheelUsed = false;
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,update,(void))
void FlxMouse_obj::onFocus(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_485_onFocus)
HXLINE( 486) this->reset();
HXLINE( 489) this->set_useSystemCursor(this->useSystemCursor);
HXLINE( 491) this->set_visible(this->_visibleWhenFocusLost);
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,onFocus,(void))
void FlxMouse_obj::onFocusLost(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_499_onFocusLost)
HXLINE( 501) this->_visibleWhenFocusLost = this->visible;
HXLINE( 503) if (this->visible) {
HXLINE( 505) this->set_visible(false);
}
HXLINE( 508) ::openfl::ui::Mouse_obj::show();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,onFocusLost,(void))
void FlxMouse_obj::onGameStart(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_516_onGameStart)
HXDLIN( 516) this->set_visible(this->visible);
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,onGameStart,(void))
void FlxMouse_obj::onMouseWheel( ::openfl::events::MouseEvent flashEvent){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_524_onMouseWheel)
HXDLIN( 524) if (this->enabled) {
HXLINE( 526) this->_wheelUsed = true;
HXLINE( 527) this->wheel = flashEvent->delta;
}
}
HX_DEFINE_DYNAMIC_FUNC1(FlxMouse_obj,onMouseWheel,(void))
void FlxMouse_obj::onMouseLeave( ::openfl::events::Event _){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_537_onMouseLeave)
HXLINE( 538) this->_rightButton->onUp(null());
HXLINE( 539) this->_middleButton->onUp(null());
}
HX_DEFINE_DYNAMIC_FUNC1(FlxMouse_obj,onMouseLeave,(void))
void FlxMouse_obj::showSystemCursor(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_585_showSystemCursor)
HXLINE( 589) this->cursorContainer->set_visible(false);
HXLINE( 592) ::openfl::ui::Mouse_obj::show();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,showSystemCursor,(void))
void FlxMouse_obj::hideSystemCursor(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_596_hideSystemCursor)
HXLINE( 603) ::openfl::ui::Mouse_obj::hide();
HXLINE( 605) if (this->visible) {
HXLINE( 607) this->cursorContainer->set_visible(true);
}
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,hideSystemCursor,(void))
bool FlxMouse_obj::set_useSystemCursor(bool value){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_613_set_useSystemCursor)
HXLINE( 614) if (value) {
HXLINE( 616) this->showSystemCursor();
}
else {
HXLINE( 620) this->hideSystemCursor();
}
HXLINE( 622) return (this->useSystemCursor = value);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxMouse_obj,set_useSystemCursor,return )
void FlxMouse_obj::showCursor(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_627_showCursor)
HXDLIN( 627) if (this->useSystemCursor) {
HXLINE( 629) ::openfl::ui::Mouse_obj::show();
}
else {
HXLINE( 633) if (::hx::IsNull( this->_cursor )) {
HXLINE( 634) this->load(null(),null(),null(),null());
}
HXLINE( 639) this->cursorContainer->set_visible(true);
HXLINE( 640) ::openfl::ui::Mouse_obj::hide();
}
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,showCursor,(void))
void FlxMouse_obj::hideCursor(){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_646_hideCursor)
HXLINE( 647) this->cursorContainer->set_visible(false);
HXLINE( 648) ::openfl::ui::Mouse_obj::hide();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxMouse_obj,hideCursor,(void))
bool FlxMouse_obj::set_visible(bool value){
HX_STACKFRAME(&_hx_pos_dcc29ee8d0f87524_652_set_visible)
HXLINE( 653) if (value) {
HXLINE( 654) this->showCursor();
}
else {
HXLINE( 656) this->hideCursor();
}
HXLINE( 658) return (this->visible = value);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxMouse_obj,set_visible,return )
::hx::ObjectPtr< FlxMouse_obj > FlxMouse_obj::__new( ::openfl::display::Sprite cursorContainer) {
::hx::ObjectPtr< FlxMouse_obj > __this = new FlxMouse_obj();
__this->__construct(cursorContainer);
return __this;
}
::hx::ObjectPtr< FlxMouse_obj > FlxMouse_obj::__alloc(::hx::Ctx *_hx_ctx, ::openfl::display::Sprite cursorContainer) {
FlxMouse_obj *__this = (FlxMouse_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(FlxMouse_obj), true, "flixel.input.mouse.FlxMouse"));
*(void **)__this = FlxMouse_obj::_hx_vtable;
__this->__construct(cursorContainer);
return __this;
}
FlxMouse_obj::FlxMouse_obj()
{
}
void FlxMouse_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(FlxMouse);
HX_MARK_MEMBER_NAME(enabled,"enabled");
HX_MARK_MEMBER_NAME(wheel,"wheel");
HX_MARK_MEMBER_NAME(cursorContainer,"cursorContainer");
HX_MARK_MEMBER_NAME(visible,"visible");
HX_MARK_MEMBER_NAME(useSystemCursor,"useSystemCursor");
HX_MARK_MEMBER_NAME(_leftButton,"_leftButton");
HX_MARK_MEMBER_NAME(_middleButton,"_middleButton");
HX_MARK_MEMBER_NAME(_rightButton,"_rightButton");
HX_MARK_MEMBER_NAME(_cursor,"_cursor");
HX_MARK_MEMBER_NAME(_cursorBitmapData,"_cursorBitmapData");
HX_MARK_MEMBER_NAME(_wheelUsed,"_wheelUsed");
HX_MARK_MEMBER_NAME(_visibleWhenFocusLost,"_visibleWhenFocusLost");
HX_MARK_MEMBER_NAME(_prevX,"_prevX");
HX_MARK_MEMBER_NAME(_prevY,"_prevY");
HX_MARK_MEMBER_NAME(_stage,"_stage");
HX_MARK_END_CLASS();
}
void FlxMouse_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(enabled,"enabled");
HX_VISIT_MEMBER_NAME(wheel,"wheel");
HX_VISIT_MEMBER_NAME(cursorContainer,"cursorContainer");
HX_VISIT_MEMBER_NAME(visible,"visible");
HX_VISIT_MEMBER_NAME(useSystemCursor,"useSystemCursor");
HX_VISIT_MEMBER_NAME(_leftButton,"_leftButton");
HX_VISIT_MEMBER_NAME(_middleButton,"_middleButton");
HX_VISIT_MEMBER_NAME(_rightButton,"_rightButton");
HX_VISIT_MEMBER_NAME(_cursor,"_cursor");
HX_VISIT_MEMBER_NAME(_cursorBitmapData,"_cursorBitmapData");
HX_VISIT_MEMBER_NAME(_wheelUsed,"_wheelUsed");
HX_VISIT_MEMBER_NAME(_visibleWhenFocusLost,"_visibleWhenFocusLost");
HX_VISIT_MEMBER_NAME(_prevX,"_prevX");
HX_VISIT_MEMBER_NAME(_prevY,"_prevY");
HX_VISIT_MEMBER_NAME(_stage,"_stage");
}
::hx::Val FlxMouse_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"load") ) { return ::hx::Val( load_dyn() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"wheel") ) { return ::hx::Val( wheel ); }
if (HX_FIELD_EQ(inName,"reset") ) { return ::hx::Val( reset_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"_prevX") ) { return ::hx::Val( _prevX ); }
if (HX_FIELD_EQ(inName,"_prevY") ) { return ::hx::Val( _prevY ); }
if (HX_FIELD_EQ(inName,"_stage") ) { return ::hx::Val( _stage ); }
if (HX_FIELD_EQ(inName,"update") ) { return ::hx::Val( update_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"enabled") ) { return ::hx::Val( enabled ); }
if (HX_FIELD_EQ(inName,"visible") ) { return ::hx::Val( visible ); }
if (HX_FIELD_EQ(inName,"_cursor") ) { return ::hx::Val( _cursor ); }
if (HX_FIELD_EQ(inName,"destroy") ) { return ::hx::Val( destroy_dyn() ); }
if (HX_FIELD_EQ(inName,"onFocus") ) { return ::hx::Val( onFocus_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"_wheelUsed") ) { return ::hx::Val( _wheelUsed ); }
if (HX_FIELD_EQ(inName,"showCursor") ) { return ::hx::Val( showCursor_dyn() ); }
if (HX_FIELD_EQ(inName,"hideCursor") ) { return ::hx::Val( hideCursor_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"_leftButton") ) { return ::hx::Val( _leftButton ); }
if (HX_FIELD_EQ(inName,"onFocusLost") ) { return ::hx::Val( onFocusLost_dyn() ); }
if (HX_FIELD_EQ(inName,"onGameStart") ) { return ::hx::Val( onGameStart_dyn() ); }
if (HX_FIELD_EQ(inName,"set_visible") ) { return ::hx::Val( set_visible_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"_rightButton") ) { return ::hx::Val( _rightButton ); }
if (HX_FIELD_EQ(inName,"onMouseWheel") ) { return ::hx::Val( onMouseWheel_dyn() ); }
if (HX_FIELD_EQ(inName,"onMouseLeave") ) { return ::hx::Val( onMouseLeave_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"_middleButton") ) { return ::hx::Val( _middleButton ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"cursorContainer") ) { return ::hx::Val( cursorContainer ); }
if (HX_FIELD_EQ(inName,"useSystemCursor") ) { return ::hx::Val( useSystemCursor ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"showSystemCursor") ) { return ::hx::Val( showSystemCursor_dyn() ); }
if (HX_FIELD_EQ(inName,"hideSystemCursor") ) { return ::hx::Val( hideSystemCursor_dyn() ); }
break;
case 17:
if (HX_FIELD_EQ(inName,"_cursorBitmapData") ) { return ::hx::Val( _cursorBitmapData ); }
break;
case 19:
if (HX_FIELD_EQ(inName,"set_useSystemCursor") ) { return ::hx::Val( set_useSystemCursor_dyn() ); }
break;
case 21:
if (HX_FIELD_EQ(inName,"_visibleWhenFocusLost") ) { return ::hx::Val( _visibleWhenFocusLost ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val FlxMouse_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"wheel") ) { wheel=inValue.Cast< int >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"_prevX") ) { _prevX=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"_prevY") ) { _prevY=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"_stage") ) { _stage=inValue.Cast< ::openfl::display::Stage >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"enabled") ) { enabled=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"visible") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_visible(inValue.Cast< bool >()) );visible=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"_cursor") ) { _cursor=inValue.Cast< ::openfl::display::Bitmap >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"_wheelUsed") ) { _wheelUsed=inValue.Cast< bool >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"_leftButton") ) { _leftButton=inValue.Cast< ::flixel::input::mouse::FlxMouseButton >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"_rightButton") ) { _rightButton=inValue.Cast< ::flixel::input::mouse::FlxMouseButton >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"_middleButton") ) { _middleButton=inValue.Cast< ::flixel::input::mouse::FlxMouseButton >(); return inValue; }
break;
case 15:
if (HX_FIELD_EQ(inName,"cursorContainer") ) { cursorContainer=inValue.Cast< ::openfl::display::Sprite >(); return inValue; }
if (HX_FIELD_EQ(inName,"useSystemCursor") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_useSystemCursor(inValue.Cast< bool >()) );useSystemCursor=inValue.Cast< bool >(); return inValue; }
break;
case 17:
if (HX_FIELD_EQ(inName,"_cursorBitmapData") ) { _cursorBitmapData=inValue.Cast< ::openfl::display::BitmapData >(); return inValue; }
break;
case 21:
if (HX_FIELD_EQ(inName,"_visibleWhenFocusLost") ) { _visibleWhenFocusLost=inValue.Cast< bool >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void FlxMouse_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("enabled",81,04,31,7e));
outFields->push(HX_("wheel",9b,34,ba,c9));
outFields->push(HX_("cursorContainer",8b,3b,1c,12));
outFields->push(HX_("visible",72,78,24,a3));
outFields->push(HX_("useSystemCursor",0c,3e,de,f9));
outFields->push(HX_("_leftButton",78,ea,7a,db));
outFields->push(HX_("_middleButton",06,ea,42,d7));
outFields->push(HX_("_rightButton",ef,dc,6e,a9));
outFields->push(HX_("_cursor",75,a0,5f,ad));
outFields->push(HX_("_cursorBitmapData",8e,5e,40,cd));
outFields->push(HX_("_wheelUsed",39,58,29,d8));
outFields->push(HX_("_visibleWhenFocusLost",cf,95,3f,38));
outFields->push(HX_("_prevX",46,9d,6f,c4));
outFields->push(HX_("_prevY",47,9d,6f,c4));
outFields->push(HX_("_stage",ff,b1,f2,7f));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo FlxMouse_obj_sMemberStorageInfo[] = {
{::hx::fsBool,(int)offsetof(FlxMouse_obj,enabled),HX_("enabled",81,04,31,7e)},
{::hx::fsInt,(int)offsetof(FlxMouse_obj,wheel),HX_("wheel",9b,34,ba,c9)},
{::hx::fsObject /* ::openfl::display::Sprite */ ,(int)offsetof(FlxMouse_obj,cursorContainer),HX_("cursorContainer",8b,3b,1c,12)},
{::hx::fsBool,(int)offsetof(FlxMouse_obj,visible),HX_("visible",72,78,24,a3)},
{::hx::fsBool,(int)offsetof(FlxMouse_obj,useSystemCursor),HX_("useSystemCursor",0c,3e,de,f9)},
{::hx::fsObject /* ::flixel::input::mouse::FlxMouseButton */ ,(int)offsetof(FlxMouse_obj,_leftButton),HX_("_leftButton",78,ea,7a,db)},
{::hx::fsObject /* ::flixel::input::mouse::FlxMouseButton */ ,(int)offsetof(FlxMouse_obj,_middleButton),HX_("_middleButton",06,ea,42,d7)},
{::hx::fsObject /* ::flixel::input::mouse::FlxMouseButton */ ,(int)offsetof(FlxMouse_obj,_rightButton),HX_("_rightButton",ef,dc,6e,a9)},
{::hx::fsObject /* ::openfl::display::Bitmap */ ,(int)offsetof(FlxMouse_obj,_cursor),HX_("_cursor",75,a0,5f,ad)},
{::hx::fsObject /* ::openfl::display::BitmapData */ ,(int)offsetof(FlxMouse_obj,_cursorBitmapData),HX_("_cursorBitmapData",8e,5e,40,cd)},
{::hx::fsBool,(int)offsetof(FlxMouse_obj,_wheelUsed),HX_("_wheelUsed",39,58,29,d8)},
{::hx::fsBool,(int)offsetof(FlxMouse_obj,_visibleWhenFocusLost),HX_("_visibleWhenFocusLost",cf,95,3f,38)},
{::hx::fsInt,(int)offsetof(FlxMouse_obj,_prevX),HX_("_prevX",46,9d,6f,c4)},
{::hx::fsInt,(int)offsetof(FlxMouse_obj,_prevY),HX_("_prevY",47,9d,6f,c4)},
{::hx::fsObject /* ::openfl::display::Stage */ ,(int)offsetof(FlxMouse_obj,_stage),HX_("_stage",ff,b1,f2,7f)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *FlxMouse_obj_sStaticStorageInfo = 0;
#endif
static ::String FlxMouse_obj_sMemberFields[] = {
HX_("enabled",81,04,31,7e),
HX_("wheel",9b,34,ba,c9),
HX_("cursorContainer",8b,3b,1c,12),
HX_("visible",72,78,24,a3),
HX_("useSystemCursor",0c,3e,de,f9),
HX_("_leftButton",78,ea,7a,db),
HX_("_middleButton",06,ea,42,d7),
HX_("_rightButton",ef,dc,6e,a9),
HX_("_cursor",75,a0,5f,ad),
HX_("_cursorBitmapData",8e,5e,40,cd),
HX_("_wheelUsed",39,58,29,d8),
HX_("_visibleWhenFocusLost",cf,95,3f,38),
HX_("_prevX",46,9d,6f,c4),
HX_("_prevY",47,9d,6f,c4),
HX_("_stage",ff,b1,f2,7f),
HX_("load",26,9a,b7,47),
HX_("destroy",fa,2c,86,24),
HX_("reset",cf,49,c8,e6),
HX_("update",09,86,05,87),
HX_("onFocus",39,fe,c6,9a),
HX_("onFocusLost",bd,e4,85,41),
HX_("onGameStart",f1,45,69,db),
HX_("onMouseWheel",35,ca,ca,bf),
HX_("onMouseLeave",91,ca,63,68),
HX_("showSystemCursor",c2,1f,8d,c0),
HX_("hideSystemCursor",07,93,7b,81),
HX_("set_useSystemCursor",2f,00,86,c1),
HX_("showCursor",b3,33,5d,a8),
HX_("hideCursor",38,35,6e,d6),
HX_("set_visible",95,df,8b,33),
::String(null()) };
::hx::Class FlxMouse_obj::__mClass;
void FlxMouse_obj::__register()
{
FlxMouse_obj _hx_dummy;
FlxMouse_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("flixel.input.mouse.FlxMouse",12,2b,6e,8c);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(FlxMouse_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< FlxMouse_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = FlxMouse_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = FlxMouse_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace flixel
} // end namespace input
} // end namespace mouse
| 45.764957 | 231 | 0.726336 | bobisdabbing |
d772dd2e1f45ebc3bc48dd3ff8a74ab0920a80ff | 4,384 | hpp | C++ | include/calc/Pid.hpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 2 | 2016-05-21T03:09:19.000Z | 2016-08-27T03:40:51.000Z | include/calc/Pid.hpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 75 | 2017-10-08T22:21:19.000Z | 2020-03-30T21:13:20.000Z | include/calc/Pid.hpp | StratifyLabs/StratifyLib | 975a5c25a84296fd0dec64fe4dc579cf7027abe6 | [
"MIT"
] | 5 | 2018-03-27T16:44:09.000Z | 2020-07-08T16:45:55.000Z | /*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#ifndef SAPI_CALC_PID_HPP_
#define SAPI_CALC_PID_HPP_
#include "../api/CalcObject.hpp"
namespace calc {
/*! \brief PID Control Loop Class (float)
* \details This class implements a PID control loop using floating point
* values.
*
* A PID control loop uses three constant values in order to calculate a control
* variable such that the input converges on the target variable.
*
* The following terminology is used in this documentation.
*
* - kp: Proportional constant
* - ki: Integral constant
* - kd: Differential constant
* - present value: the current value of the system output
* - target variable: desired output value of the system
* - control variable: calculated value to apply such that the input tends to the target variable
* - error variable: the error variable is the difference between the target variable and the present value
*
* An example for using a PID control loop is temperature control. Consider a system
* that uses a PWM value to heat an element and a temperature sensor to read the output.
* The above terminology is applied as follows:
*
* - kp: Value selected by the developer to tune the control loop
* - ki: Value selected by the developer to tune the control loop
* - kd: Value selected by the developer to tune the control loop
* - present value: the value of the temperature sensor output
* - target variable: the desired temperature sensor output
* - control variable: the PWM duty cycle that should be applied to the heater
* - error variable: the different between the desired temperature output and the present temperature output
*
* \code
* //md2code:include
* #include <sapi/calc.hpp>
* #include <sapi/hal.hpp>
* \endcode
*
*
* \code
* //md2code:main
* PidF32 pid_loop;
* Pwm control(0);
* Adc present_value(0);
* u16 adc_value;
*
* volatile bool is_active = true;
*
* pid_loop
* .set_kp(1.0f)
* .set_ki(0.1f)
* .set_kd(0.001f)
* .set_maximum(1000.0f) //max duty cycle
* .set_minimum(0.0f); //min duty cycle
*
* //Init the PWM output and ADC input
*
* while( is_active ){
* present_value.read(
* arg::Location(0),
* arg::DestinationBuffer(&adc_value),
* arg::Size(2)
* );
* control.set_channel(
* 0,
* pid_loop.calculate_control_variable(
* 3.3f * adc_value / 4096.0f
* )
* );
* }
* \endcode
*
*
*/
class PidF32 : public api::WorkObject {
public:
/*! \details Constructs a new PID (float) object.
*
*/
PidF32();
/*! \details Resets the state of the PID control loop. */
void reset();
/*! \details Sets the proportional constant value. */
PidF32 & set_kp(float v){ m_kp = v; return *this; }
/*! \details Sets the integral constant value. */
PidF32 & set_ki(float v){ m_ki = v; return *this; }
/*! \details Sets the differential constant value. */
PidF32 & set_kd(float v){ m_kd = v; return *this; }
/*! \details Sets the maximum allowed value of the target variable. */
PidF32 & set_maximum(float v){ m_max = v; return *this; }
/*! \details Sets the minimum allowed value of the target variable. */
PidF32 & set_minimum(float v){ m_min = v; return *this; }
/*! \details Sets the value for the target variable. */
PidF32 & set_target(float v){ m_target = v; return *this; }
/*! \details Returns the proportional constant. */
float kp() const { return m_kp; }
/*! \details Returns the integral constant. */
float ki() const { return m_ki; }
/*! \details Returns the differential constant. */
float kd() const { return m_kd; }
/*! \details Returns the maximum value for the control variable. */
float max() const { return m_max; }
/*! \details Returns the minimum value for the control variable. */
float min() const { return m_min; }
/*! \details Returns the target variable. */
float target() const { return m_target; }
/*! \details Calculates the control variable based on
* the current state of the system.
*
* @param present_value The present value of the system
* @return The updated control variable to be applied to the system
*/
float calculate_control_variable(float present_value);
private:
float m_target;
float m_error;
float m_kp;
float m_ki;
float m_kd;
float m_integral;
float m_max;
float m_min;
};
typedef PidF32 Pid_f;
}
#endif /* SAPI_CALC_PID_HPP_ */
| 30.873239 | 108 | 0.69594 | bander9289 |
d776a3f6f3b0b0d752cd1fe0f8742ed5ad62539a | 450 | cpp | C++ | engine/labs/sol-plugins/firstPlugin/firstplugin.cpp | sfaure-witekio/qt-training-material | d166e4ed9cc5f5faab85b0337c5844c4cdcb206e | [
"BSD-3-Clause"
] | 16 | 2017-01-11T17:28:03.000Z | 2021-09-27T16:12:01.000Z | engine/labs/sol-plugins/firstPlugin/firstplugin.cpp | sfaure-witekio/qt-training-material | d166e4ed9cc5f5faab85b0337c5844c4cdcb206e | [
"BSD-3-Clause"
] | null | null | null | engine/labs/sol-plugins/firstPlugin/firstplugin.cpp | sfaure-witekio/qt-training-material | d166e4ed9cc5f5faab85b0337c5844c4cdcb206e | [
"BSD-3-Clause"
] | 4 | 2017-03-17T02:44:32.000Z | 2021-01-22T07:57:34.000Z | /*************************************************************************
*
* Copyright (c) 2016 The Qt Company
* All rights reserved.
*
* See the LICENSE.txt file shipped along with this file for the license.
*
*************************************************************************/
#include "firstplugin.h"
FirstPlugin::FirstPlugin()
{
}
QString FirstPlugin::getTheString(void) const
{
return QString("The first Plug-in");
}
| 18 | 75 | 0.46 | sfaure-witekio |
d7786a94b7b1091c8c5e5883a20541d592b7ffbc | 5,606 | cpp | C++ | logger.cpp | rlefevre1/Logger | 03c1e59f651ed4da39fb2f9281c0c51627f4b19f | [
"BSD-3-Clause"
] | null | null | null | logger.cpp | rlefevre1/Logger | 03c1e59f651ed4da39fb2f9281c0c51627f4b19f | [
"BSD-3-Clause"
] | null | null | null | logger.cpp | rlefevre1/Logger | 03c1e59f651ed4da39fb2f9281c0c51627f4b19f | [
"BSD-3-Clause"
] | null | null | null | #include "logger.h"
#include <fstream>
namespace logs
{
// Constructors
Logger::Logger() : flags_logs_enabled_ {{INFO, true}, {WARNING, true}, {ERROR, true}, {FATAL, true}},
logs_headers_ {{INFO, "[INFO]"}, {WARNING, "[WARNING]"}, {ERROR, "[ERROR]"}, {FATAL, "[FATAL]"}},
separator_(" - "), newline_("\n")
{}
Logger::Logger(std::size_t buffer_min_capacity) : Logger()
{
buffer_.reserve(buffer_min_capacity);
}
// Flags
void Logger::setEnabled(LOG_TYPE log_type, bool enabled)
{
flags_logs_enabled_[log_type] = enabled;
}
void Logger::setEnabledAll(bool enabled)
{
for(auto it = flags_logs_enabled_.begin(); it != flags_logs_enabled_.end(); ++it)
it->second = enabled;
}
bool Logger::isEnabled(LOG_TYPE log_type) const
{
return flags_logs_enabled_.at(log_type);
}
// Format
void Logger::setHeader(LOG_TYPE log_type, const std::string & header)
{
logs_headers_[log_type] = header;
}
std::string Logger::header(LOG_TYPE log_type) const
{
return logs_headers_.at(log_type);
}
void Logger::setSeparator(const std::string & sep)
{
separator_ = sep;
}
std::string Logger::separator() const
{
return separator_;
}
void Logger::setNewline(const std::string & nl)
{
newline_ = nl;
}
std::string Logger::newline() const
{
return newline_;
}
// Log & dump
void Logger::log(LOG_TYPE log_type, const std::string & message)
{
if(flags_logs_enabled_[log_type])
buffer_.push_back(logs_headers_[log_type] + separator_ + message);
}
void Logger::log(LOG_TYPE log_type, const std::string & message, std::ostream & os) const
{
if(flags_logs_enabled_.at(log_type))
os << logs_headers_.at(log_type) << separator_ << message << newline_;
}
bool Logger::log(LOG_TYPE log_type, const std::string & message, const std::string & file_name, std::ios_base::openmode mode) const
{
if(flags_logs_enabled_.at(log_type))
{
std::ofstream ofs(file_name, mode);
if(!ofs)
return false;
ofs << logs_headers_.at(log_type) << separator_ << message << newline_;
ofs.close();
}
return true;
}
void Logger::dump(std::ostream & os)
{
for(const auto & line : buffer_)
os << line << newline_;
buffer_.clear();
}
bool Logger::dump(const std::string & file_name, std::ios_base::openmode mode)
{
std::ofstream ofs(file_name, mode);
if(!ofs)
return false;
for(const auto & line : buffer_)
ofs << line << newline_;
ofs.close();
buffer_.clear();
return true;
}
bool SLogger::INFO_ENABLED_FLAG = true;
bool SLogger::WARNING_ENABLED_FLAG = true;
bool SLogger::ERROR_ENABLED_FLAG = true;
bool SLogger::FATAL_ENABLED_FLAG = true;
std::string SLogger::NEWLINE = "\n";
void SLogger::log(LOG_TYPE log_type, const std::string & message, std::ostream & os)
{
switch (log_type)
{
case INFO: if(INFO_ENABLED_FLAG) os << "[INFO] - " << message << NEWLINE;
break;
case WARNING: if(WARNING_ENABLED_FLAG) os << "[WARNING] - " << message << NEWLINE;
break;
case ERROR: if(ERROR_ENABLED_FLAG) os << "[ERROR] - " << message << NEWLINE;
break;
case FATAL: if(FATAL_ENABLED_FLAG) os << "[WARNING] - " << message << NEWLINE;
}
}
bool SLogger::log(LOG_TYPE log_type, const std::string & message, const std::string & file_name, std::ios_base::openmode mode)
{
switch (log_type)
{
case INFO: if(INFO_ENABLED_FLAG)
{
std::ofstream ofs(file_name, mode);
if(!ofs)
return false;
ofs << "[INFO] - " << message << NEWLINE;
ofs.close();
}
break;
case WARNING: if(WARNING_ENABLED_FLAG)
{
std::ofstream ofs(file_name, mode);
if(!ofs)
return false;
ofs << "[WARNING] - " << message << NEWLINE;
ofs.close();
}
break;
case ERROR: if(ERROR_ENABLED_FLAG)
{
std::ofstream ofs(file_name, mode);
if(!ofs)
return false;
ofs << "[ERROR] - " << message << NEWLINE;
ofs.close();
}
break;
case FATAL: if(FATAL_ENABLED_FLAG)
{
std::ofstream ofs(file_name, mode);
if(!ofs)
return false;
ofs << "[FATAL] - " << message << NEWLINE;
ofs.close();
}
}
return true;
}
}
| 34.392638 | 136 | 0.475384 | rlefevre1 |
d779abf5321faf67b25e129fe8d98a1a0ab5970f | 1,768 | cpp | C++ | 00148_sort-list/200213-1.cpp | yanlinlin82/leetcode | ddcc0b9606d951cff9c08d1f7dfbc202067c8d65 | [
"MIT"
] | 6 | 2019-10-23T01:07:29.000Z | 2021-12-05T01:51:16.000Z | 00148_sort-list/200213-1.cpp | yanlinlin82/leetcode | ddcc0b9606d951cff9c08d1f7dfbc202067c8d65 | [
"MIT"
] | null | null | null | 00148_sort-list/200213-1.cpp | yanlinlin82/leetcode | ddcc0b9606d951cff9c08d1f7dfbc202067c8d65 | [
"MIT"
] | 1 | 2021-12-03T06:54:57.000Z | 2021-12-03T06:54:57.000Z | // https://leetcode-cn.com/problems/sort-list/
#include <cstdio>
#include <initializer_list>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* init(initializer_list<int> a) {
ListNode node(0);
ListNode* p = &node;
for (auto e : a) {
p->next = new ListNode(e);
p = p->next;
}
return node.next;
}
void release(ListNode* p) {
if (p) release(p->next);
delete p;
}
void print(ListNode* p) {
printf("[ "); for (; p; p = p->next) printf("%d ", p->val); printf("]\n");
}
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
int n = 0;
for (ListNode* p = head; p; p = p->next) ++n;
ListNode* p = head;
for (int i = 0; i + 1 < n / 2; ++i) p = p->next;
ListNode* q = p->next;
p->next = NULL;
p = head;
p = sortList(p);
q = sortList(q);
ListNode node(0);
ListNode* curr = &node;
for (;;) {
if (p && q) {
if (p->val <= q->val) {
curr->next = p;
p = p->next;
curr = curr->next;
} else {
curr->next = q;
q = q->next;
curr = curr->next;
}
} else if (p) {
curr->next = p;
p = p->next;
curr = curr->next;
} else if (q) {
curr->next = q;
q = q->next;
curr = curr->next;
} else {
break;
}
}
return node.next;
}
};
int main()
{
Solution s;
{
ListNode* p = init({4,2,1,3});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
{
ListNode* p = init({-1,5,3,4,0});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
{
ListNode* p = init({});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
{
ListNode* p = init({1});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
return 0;
}
| 16.679245 | 75 | 0.52319 | yanlinlin82 |
d77da50adea5844a68a9a956670440a3d138f31e | 20,158 | cpp | C++ | Core-src/Filters.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 6 | 2015-03-04T19:41:12.000Z | 2022-03-27T09:44:25.000Z | Core-src/Filters.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 20 | 2015-03-03T21:02:20.000Z | 2021-08-02T13:26:59.000Z | Core-src/Filters.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 8 | 2015-02-23T19:10:32.000Z | 2020-10-26T08:03:00.000Z | /*
Copyright (c) 2003, Xentronix
Author: Frans van Nispen (frans@xentronix.com)
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 Xentronix nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <LayoutBuilder.h>
#include <stdio.h>
#include <File.h>
#include "Globals.h"
#include "Filters.h"
#include "FilterDialogs.h"
#include "PeakFile.h"
#include "VMSystem.h"
// the filters with GUI
#include "RoomFilter.h"
#include "ReverbFilter.h"
#include "DelayFilter.h"
#include "BassBoostFilter.h"
#include "AmplifierFilter.h"
#include "CompressorFilter.h"
#include "NormalizeFilter.h"
#define FILTER_BLOCK 2048
float filmod[11][260]; // stores for 9 band EQ
float filstor[11]; // more stores for 9 band EQ
int32 __Last_Filter = 0;
int32 __Last_FilterTmp = 0;
int32 __FilterCount = 0; // nr of open filters
filter_info __FilterList[] = {
{"---", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"SILENCE", FILTER_BOTH, 1},
{"---", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"FADE_IN", FILTER_BOTH, 1},
{"FADE_OUT", FILTER_BOTH, 1},
{"NORMALIZE", FILTER_BOTH | FILTER_GUI, 2},
{"---", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"BASSBOOST", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"COMPRESSOR", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"AMPLIFIER", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"---", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"DELAY", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"REVERB", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"ROOM", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"---", FILTER_BOTH | FILTER_REALTIME | FILTER_GUI, 1},
{"INVERT", FILTER_BOTH, 1},
{"SWAP", FILTER_STEREO, 1},
{NULL,0, 0} };
// reinstate the last filter using the tag from the prefs
void FiltersInit()
{
int32 filter = 0;
while(__FilterList[filter].name != NULL)
{
if (strcmp(__FilterList[filter].name, Prefs.repeat_tag.String()) == 0){
__Last_Filter = filter;
__Last_FilterTmp = filter;
return;
}
filter++;
}
}
// Create the filter object and return it's pointer
RealtimeFilter *CreateFilter(int32 filter)
{
RealtimeFilter *pFilter = NULL;
bool bRealtime = __FilterList[filter].type & FILTER_REALTIME;
if (strcmp(__FilterList[filter].name, "ROOM") == 0)
pFilter = new RoomWindow(bRealtime);
else if (strcmp(__FilterList[filter].name, "DELAY") == 0)
pFilter = new DelayWindow(bRealtime);
else if (strcmp(__FilterList[filter].name, "REVERB") == 0)
pFilter = new ReverbWindow(bRealtime);
else if (strcmp(__FilterList[filter].name, "BASSBOOST") == 0)
pFilter = new BassBoostFilter(bRealtime);
else if (strcmp(__FilterList[filter].name, "INVERT") == 0)
pFilter = new InvertFilter();
else if (strcmp(__FilterList[filter].name, "SWAP") == 0)
pFilter = new SwapFilter();
else if (strcmp(__FilterList[filter].name, "AMPLIFIER") == 0)
pFilter = new AmplifierFilter(bRealtime);
else if (strcmp(__FilterList[filter].name, "COMPRESSOR") == 0)
pFilter = new CompressorFilter(bRealtime);
else if (strcmp(__FilterList[filter].name, "SILENCE") == 0)
pFilter = new SilenceFilter();
else if (strcmp(__FilterList[filter].name, "FADE_IN") == 0)
pFilter = new FadeInFilter();
else if (strcmp(__FilterList[filter].name, "FADE_OUT") == 0)
pFilter = new FadeOutFilter();
else if (strcmp(__FilterList[filter].name, "NORMALIZE") == 0)
pFilter = new NormalizeFilter();
// set the passes the filter needs
if (pFilter)
pFilter->SetPasses( __FilterList[filter].passes );
return pFilter;
}
// here we need to run the filters. For the lite version it will just use
// the build in ones, while the other will use plug-ins
void RunFilter(const char *tag)
{
int32 filter = 0;
while(__FilterList[filter].name != NULL)
{
if (strcmp(__FilterList[filter].name, tag) == 0){
RunFilter(filter);
return;
}
filter++;
}
}
void RunFilter(int32 filter)
{
if (__FilterCount == PLAY_HOOKS/2) return;
__Last_FilterTmp = filter;
RealtimeFilter *pFilter = CreateFilter(filter);
if (pFilter)
{
__FilterCount++; // another filter open
// add the GUI
BView *view = pFilter->ConfigView();
if (view){
// run with GUI
pFilter->GetLayout()->AddView(0, view);
pFilter->MoveTo( Pool.mainWindow->Frame().left +__FilterCount * 40 +40, Pool.mainWindow->Frame().top + 80 + __FilterCount * 20);
pFilter->Run(); // start looper
pFilter->InitFilter(Pool.system_frequency, 2); // initiase
pFilter->Start(); // start media buffers
pFilter->Show(); // show to user
}else{
// run without GUI
ExecuteFilter(pFilter);
}
}
}
void WriteBack(float *src, float *dest, int32 size)
{
if (Pool.selection == BOTH || Pool.sample_type == MONO)
memcpy( dest, src, size*4 );
else
if (Pool.selection == LEFT) /* allways stereo */
{
for (int32 x = 0; x < size; x+=2)
dest[x] = src[x];
}
else
{
src++;
dest++;
for (int32 x = 0; x < size; x+=2)
dest[x] = src[x];
}
}
void ExecuteFilter(RealtimeFilter *pFilter)
{
if (!pFilter) return;
__FilterCount--; // another filter closed
pFilter->Lock();
if (pFilter->IsHidden()){
// run without GUI
}
else{
pFilter->Hide();
pFilter->Stop();
pFilter->DeAllocate(); // remove buffers used for realtime effect
}
if (Pool.PrepareFilter()){
// init with track data
float *filter_buffer = new float[FILTER_BLOCK];
int32 size = (Pool.r_sel_pointer - Pool.pointer +1)*Pool.sample_type;
Pool.StartProgress(Language.get("WORKING"), size * pFilter->Passes());
#ifndef __VM_SYSTEM // RAM
for (int32 filter_pass = 0; filter_pass < pFilter->Passes(); filter_pass++)
{
int32 size = (Pool.r_sel_pointer - Pool.pointer +1)*Pool.sample_type;
float *p = Pool.sample_memory + Pool.pointer*Pool.sample_type;
pFilter->InitFilter(Pool.system_frequency, Pool.sample_type, filter_pass, size);
while(size >= FILTER_BLOCK){
memcpy( filter_buffer, p, FILTER_BLOCK*4 ); // get the data
pFilter->FilterBuffer( filter_buffer, FILTER_BLOCK);
WriteBack( filter_buffer, p, FILTER_BLOCK);
p+=FILTER_BLOCK;
size-=FILTER_BLOCK;
Pool.ProgressUpdate( FILTER_BLOCK );
}
if (size)
{
memcpy( filter_buffer, p, size*4 ); // get the data
pFilter->FilterBuffer( filter_buffer, size);
WriteBack( filter_buffer, p, size);
}
}
#else // VM
// TODO:
#endif
Pool.HideProgress();
Pool.changed = true;
delete filter_buffer;
}
// enable repeat action
__Last_Filter = __Last_FilterTmp;
Prefs.repeat_tag.SetTo(__FilterList[__Last_Filter].name);
pFilter->DeAllocate();
pFilter->Quit();
Pool.ResetIndexView();
Pool.UpdateToolBar();
Pool.RedrawWindow();
}
void CancelFilter(RealtimeFilter *pFilter)
{
if (!pFilter) return;
__FilterCount--; // another filter closed
pFilter->Stop();
pFilter->DeAllocate();
pFilter->Lock();
pFilter->Quit();
}
void RunLastFilter()
{
RealtimeFilter *pFilter = CreateFilter(__Last_Filter);
if (pFilter)
{
ExecuteFilter(pFilter);
}
}
// ============================================================ Swap
SwapFilter::SwapFilter() : RealtimeFilter(NULL, false)
{}
void SwapFilter::FilterBuffer(float *buffer, size_t size)
{
for (size_t i=0; i<size; i+=2){
float tmp = buffer[i+0];
buffer[i+0] = buffer[i+1];
buffer[i+1] = tmp;
}
}
// ============================================================ Invert
InvertFilter::InvertFilter() : RealtimeFilter(NULL, false)
{}
void InvertFilter::FilterBuffer(float *buffer, size_t size)
{
for (size_t i=0; i<size; i++){
buffer++;
*buffer = -*buffer;
}
}
// ============================================================ Silence
SilenceFilter::SilenceFilter() : RealtimeFilter(NULL, false)
{}
void SilenceFilter::FilterBuffer(float *buffer, size_t size)
{
for (size_t i=0; i<size; i++){
*buffer++ = 0.0f;
}
}
// ============================================================ FadeIn
FadeInFilter::FadeInFilter() : RealtimeFilter(NULL, false)
{}
void FadeInFilter::FilterBuffer(float *buffer, size_t size)
{
for (size_t i=0; i<size; i++){
buffer++;
*buffer = (*buffer)*count / m_total;
count++;
}
}
bool FadeInFilter::InitFilter(float f, int32 c, int32 pass, int32 size)
{
RealtimeFilter::InitFilter(f, c, pass, size);
count = 0;
return true;
}
// ============================================================ FadeOut
FadeOutFilter::FadeOutFilter() : RealtimeFilter(NULL, false)
{}
void FadeOutFilter::FilterBuffer(float *buffer, size_t size)
{
for (size_t i=0; i<size; i++){
buffer++;
*buffer = (*buffer)*count / m_total;
count--;
}
}
bool FadeOutFilter::InitFilter(float f, int32 c, int32 pass, int32 size)
{
RealtimeFilter::InitFilter(f, c, pass, size);
count = size;
return true;
}
// ============================================================ Trim
void DoTrim()
{
if (Pool.sample_type == NONE || Pool.selection == NONE) return;
Pool.mainWindow->PostMessage(TRANSPORT_STOP); // stop playing
if (Prefs.save_undo) Hist.Save(H_FULL, 0, Pool.size); // full undo
if (Pool.pointer != 0){ // copy to begin of memory
float *src = Pool.sample_memory + Pool.pointer*Pool.sample_type;
float *dst = Pool.sample_memory;
float *end = Pool.sample_memory + Pool.r_sel_pointer*Pool.sample_type;
while(src<=end){
*dst++ = *src++;
}
}
// resize memory
Pool.size = (Pool.r_sel_pointer - Pool.pointer);
Pool.r_sel_pointer = Pool.size;
Pool.r_pointer = Pool.size;
Pool.pointer = 0;
Pool.l_pointer = 0;
Pool.sample_memory = (float*)realloc(Pool.sample_memory, Pool.size*Pool.sample_type*4 +1024);
// wipe last piece
float *p = Pool.sample_memory + (Pool.size+1)*Pool.sample_type;
for (int i=0; i<256; i++) // now delete 1Kb additional memory as reserved to prevent crashes
*p++=0;
Pool.changed = true;
Pool.ResetIndexView();
Pool.UpdateToolBar();
Pool.RedrawWindow();
}
#define BUFFER_SIZE 128*1024
#define BLOCK_SIZE BUFFER_SIZE*4
/*******************************************************
*
*******************************************************/
void DoResample()
{
if (Pool.sample_type == NONE) return;
int32 preResample_type = Pool.sample_type;
float *buffer = (float*)malloc(BUFFER_SIZE*4+4);
if (!buffer) return; // error
Pool.player->Stop();
Pool.mainWindow->PostMessage(TRANSPORT_STOP); // stop playing
if (Prefs.save_undo) Hist.Save(H_FULL, 0, Pool.size); // full undo
app_info info;
be_app->GetAppInfo(&info);
BString str("/tmp/BeAETmp");
str << info.thread; // make the file unique
BPath path;
path.SetTo(str.String());
BFile *file = new BFile(path.Path(), B_READ_WRITE|B_CREATE_FILE|B_ERASE_FILE);//|B_FAIL_IF_EXISTS
if(file->InitCheck() != B_OK){
// errror
return;
}
BEntry e(path.Path());
float left = 0.0, right = 0.0, add = 0.0;
float fraq = Pool.frequency/Prefs.filter_resample_freq; // the convert frequency
float *mem = Pool.sample_memory;
float *end = Pool.sample_memory + Pool.size*Pool.sample_type;
int32 count = 1000;
int32 bit_convert = (1 << Prefs.filter_resample_bits)-1;
Pool.size = (int64)ceil(Pool.size * Prefs.filter_resample_freq / Pool.frequency);
int32 buffer_pointer = 0;
Pool.StartProgress(Language.get("RESAMPLING"), Pool.size);
if (Pool.sample_type == MONO && Prefs.filter_resample_mono){ // mono to mono
while(mem<= end){
left = *mem;
// sample conversion
left = floor(left * bit_convert)/bit_convert;
buffer[buffer_pointer++] = left;
if (buffer_pointer == BUFFER_SIZE){
file->Write((void*)buffer, BUFFER_SIZE*4);
buffer_pointer = 0;
}
add += fraq;
while (add >= 1.0){
++mem;
--add;
}
if (count-- <0){count = 1000; Pool.ProgressUpdate( 500 ); }
}
if (buffer_pointer){
file->Write((void*)buffer, buffer_pointer*4);
}
}else if (Pool.sample_type == MONO && !Prefs.filter_resample_mono){ // mono to stereo
float l_mul = bit_convert*Prefs.filter_resample_sl/100;
float r_mul = bit_convert*Prefs.filter_resample_sr/100;
while(mem<= end){
left = *mem;
right = *mem;
// sample conversion
left = floor(left * l_mul)/bit_convert;
right = floor(right * r_mul)/bit_convert;
buffer[buffer_pointer++] = MIN(left,1);
buffer[buffer_pointer++] = MIN(right,1);
if (buffer_pointer == BUFFER_SIZE){
file->Write((void*)buffer, BUFFER_SIZE*4);
buffer_pointer = 0;
}
add += fraq;
while (add >= 1.0){
++mem;
--add;
}
if (count-- <0){count = 1000; Pool.ProgressUpdate( 500 ); }
}
if (buffer_pointer){
file->Write((void*)buffer, buffer_pointer*4);
}
}else if (Pool.sample_type == STEREO && !Prefs.filter_resample_mono){ // stereo to stereo
while(mem<= end){
// sample conversion
left = floor(mem[0] * bit_convert)/bit_convert;
right = floor(mem[1] * bit_convert)/bit_convert;
buffer[buffer_pointer++] = left;
buffer[buffer_pointer++] = right;
if (buffer_pointer == BUFFER_SIZE){
file->Write((void*)buffer, BUFFER_SIZE*4);
buffer_pointer = 0;
}
add += fraq;
while (add >= 1.0){
mem+=2;
--add;
}
if (count-- <0){count = 1000; Pool.ProgressUpdate( 500 ); }
}
if (buffer_pointer){
file->Write((void*)buffer, buffer_pointer*4);
}
}else if (Pool.sample_type == STEREO && Prefs.filter_resample_mono){ // stereo to mono
float l_mul = bit_convert*Prefs.filter_resample_ml/100;
float r_mul = bit_convert*Prefs.filter_resample_mr/100;
while(mem<= end){
// sample conversion
left = floor(mem[0] * l_mul)/bit_convert + floor(mem[1] * r_mul)/bit_convert;
buffer[buffer_pointer++] = MIN(left,1);
if (buffer_pointer == BUFFER_SIZE){
file->Write((void*)buffer, BUFFER_SIZE*4);
buffer_pointer = 0;
}
add += fraq;
while (add >= 1.0){
mem+=2;
--add;
}
if (count-- <0){count = 1000; Pool.ProgressUpdate( 500 ); }
}
if (buffer_pointer){
file->Write((void*)buffer, buffer_pointer*4);
}
}
// now reset memory and load the file
Pool.frequency = Prefs.filter_resample_freq;
if (Prefs.filter_resample_mono)
Pool.sample_type = MONO;
else
Pool.sample_type = STEREO;
Pool.sample_bits = Prefs.filter_resample_bits;
Pool.m_format.u.raw_audio.frame_rate = Prefs.filter_resample_freq;
Pool.m_format.u.raw_audio.channel_count = Pool.sample_type;
if (Pool.sample_bits <= 8) Pool.m_format.u.raw_audio.format = 0x11; // 8bits
if (Pool.sample_bits <= 16 && Pool.sample_bits >8) Pool.m_format.u.raw_audio.format = 0x2; // 16bits
if (Pool.sample_bits <= 32 && Pool.sample_bits >16) Pool.m_format.u.raw_audio.format = 0x24; // 32bits (float)
// resize mem to frequncy
Pool.pointer = 0;
Pool.l_pointer = 0;
Pool.r_pointer = Pool.size;
Pool.r_sel_pointer = Pool.size;
Pool.selection = BOTH;
free(Pool.sample_memory);
Pool.sample_memory = (float*)malloc(Pool.size*Pool.sample_type*4 +1024);
file->Seek(0, SEEK_SET); // reset file
end = Pool.sample_memory + Pool.size*Pool.sample_type;
uint32 size = (Pool.size+1)*4*Pool.sample_type;
char *p = (char*)(Pool.sample_memory);
while(size>=BLOCK_SIZE){
file->Read((void*)p, BLOCK_SIZE);
p+=BLOCK_SIZE;
size-=BLOCK_SIZE;
Pool.ProgressUpdate( BLOCK_SIZE/(4*Pool.sample_type) );
}
if (size)
file->Read((void*)p, size);
Pool.HideProgress();
if(file) delete file;
e.Remove(); // remove file
free(buffer);
// init the BSoundPlayer to the new frequency
Pool.InitBufferPlayer( Pool.frequency );
Pool.changed = true;
Peak.Init( Pool.size+1, (Pool.sample_type == MONO) ); // Init peakfile
Pool.ResetIndexView();
Pool.UpdateToolBar();
if (Pool.sample_type != preResample_type)
{
Pool.update_draw_cache = true;
Pool.sample_view_dirty = true;
}
Pool.RedrawWindow();
}
// ========================= Zero crossings
void ZeroLL()
{
float left = 0, right = 0, tmpL = 0, tmpR = 0;
switch(Pool.sample_type){
case MONO:
left = Pool.sample_memory[Pool.pointer];
while (Pool.pointer>0){
tmpL = Pool.sample_memory[Pool.pointer];
if (left>0 && tmpL<0) break;
if (left<0 && tmpL>0) break;
Pool.pointer--;
}
break;
case STEREO:
left = Pool.sample_memory[Pool.pointer*2];
right = Pool.sample_memory[Pool.pointer*2+1];
while (Pool.pointer>0){
tmpL = Pool.sample_memory[Pool.pointer*2];
tmpR = Pool.sample_memory[Pool.pointer*2+1];
if ((left>0 && tmpL<0) && (right>0 && tmpR<0)) break;
if ((left<0 && tmpL>0) && (right<0 && tmpR>0)) break;
Pool.pointer--;
}
break;
}
}
void ZeroLR()
{
float left = 0, right = 0, tmpL = 0, tmpR = 0;
switch(Pool.sample_type){
case MONO:
left = Pool.sample_memory[Pool.pointer];
while (Pool.pointer<Pool.size){
tmpL = Pool.sample_memory[Pool.pointer];
if (left>0 && tmpL<0) break;
if (left<0 && tmpL>0) break;
Pool.pointer++;
}
break;
case STEREO:
left = Pool.sample_memory[Pool.pointer*2];
right = Pool.sample_memory[Pool.pointer*2+1];
while (Pool.pointer<Pool.size){
tmpL = Pool.sample_memory[Pool.pointer*2];
tmpR = Pool.sample_memory[Pool.pointer*2+1];
if ((left>0 && tmpL<0) && (right>0 && tmpR<0)) break;
if ((left<0 && tmpL>0) && (right<0 && tmpR>0)) break;
Pool.pointer++;
}
break;
}
if (Pool.pointer > Pool.r_sel_pointer) Pool.selection = NONE;
}
void ZeroRL()
{
if (Pool.selection==NONE)
return;
float left = 0, right = 0, tmpL = 0, tmpR = 0;
switch(Pool.sample_type){
case MONO:
left = Pool.sample_memory[Pool.r_sel_pointer];
while (Pool.r_sel_pointer>Pool.pointer){
tmpL = Pool.sample_memory[Pool.r_sel_pointer];
if (left>0 && tmpL<0) break;
if (left<0 && tmpL>0) break;
Pool.r_sel_pointer--;
}
break;
case STEREO:
left = Pool.sample_memory[Pool.r_sel_pointer*2];
right = Pool.sample_memory[Pool.r_sel_pointer*2+1];
while (Pool.r_sel_pointer>Pool.pointer){
tmpL = Pool.sample_memory[Pool.r_sel_pointer*2];
tmpR = Pool.sample_memory[Pool.r_sel_pointer*2+1];
if ((left>0 && tmpL<0) && (right>0 && tmpR<0)) break;
if ((left<0 && tmpL>0) && (right<0 && tmpR>0)) break;
Pool.r_sel_pointer--;
}
break;
}
}
void ZeroRR()
{
if (Pool.selection==NONE){
Pool.selection = BOTH;
Pool.r_sel_pointer = Pool.pointer;
}
float left = 0, right = 0, tmpL = 0, tmpR = 0;
switch(Pool.sample_type){
case MONO:
left = Pool.sample_memory[Pool.r_sel_pointer];
while (Pool.r_sel_pointer<Pool.size){
tmpL = Pool.sample_memory[Pool.r_sel_pointer];
if (left>0 && tmpL<0) break;
if (left<0 && tmpL>0) break;
Pool.r_sel_pointer++;
}
break;
case STEREO:
left = Pool.sample_memory[Pool.r_sel_pointer*2];
right = Pool.sample_memory[Pool.r_sel_pointer*2+1];
while (Pool.r_sel_pointer<Pool.size){
tmpL = Pool.sample_memory[Pool.r_sel_pointer*2];
tmpR = Pool.sample_memory[Pool.r_sel_pointer*2+1];
if ((left>0 && tmpL<0) && (right>0 && tmpR<0)) break;
if ((left<0 && tmpL>0) && (right<0 && tmpR>0)) break;
Pool.r_sel_pointer++;
}
break;
}
}
| 27.42585 | 131 | 0.665145 | HaikuArchives |
d78847103bb9a1f4678b7a384b16167c1fc1bb4f | 3,258 | cpp | C++ | testsuites/unittest/drivers/hid/smoke/hid_test_001.cpp | qdsxinyee4/PatentsViewh | c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9 | [
"BSD-3-Clause"
] | 175 | 2020-10-21T15:15:18.000Z | 2022-03-31T04:59:30.000Z | testsuites/unittest/drivers/hid/smoke/hid_test_001.cpp | qdsxinyee4/PatentsViewh | c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9 | [
"BSD-3-Clause"
] | 1 | 2020-12-20T11:41:53.000Z | 2020-12-21T04:49:33.000Z | testsuites/unittest/drivers/hid/smoke/hid_test_001.cpp | qdsxinyee4/PatentsViewh | c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9 | [
"BSD-3-Clause"
] | 39 | 2020-10-26T03:23:18.000Z | 2022-03-28T16:23:03.000Z | /*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "it_test_hid.h"
#include "fcntl.h"
#include "sys/ioctl.h"
#define MOUSE_DEV_PATH "/dev/usb/uhid0"
#define MOUSE_DATA_LEN 5
#define MOUSE_TEST_COUNT 20
#define MOUSE_WAIT_TIME 1000
#define USB_GET_REPORT_ID _IOR('U', 25, int)
static int Testcase(VOID)
{
int ret;
int fd = -1;
int i;
struct pollfd pfds[1];
char *buf = NULL;
int id = -1;
ret = access(MOUSE_DEV_PATH, 0);
if (!ret) {
fd = open(MOUSE_DEV_PATH, O_RDWR, 0666);
ICUNIT_ASSERT_NOT_EQUAL(fd, -1, fd);
buf = (char *)malloc(MOUSE_DATA_LEN);
ICUNIT_ASSERT_NOT_EQUAL(buf, NULL, buf);
(void)memset_s(buf, MOUSE_DATA_LEN, 0, MOUSE_DATA_LEN);
ret = ioctl(fd, USB_GET_REPORT_ID, &id);
ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);
ICUNIT_ASSERT_EQUAL(id, 0, id);
printf("Reading mouse data ... \n");
for (i = 0; i < MOUSE_TEST_COUNT; i++) {
pfds[0].fd = fd;
pfds[0].events = POLLIN;
ret = poll(pfds, 1, MOUSE_WAIT_TIME);
ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);
if (ret == 0) {
continue;
} else {
printf("read ...\n");
read(fd, buf, MOUSE_DATA_LEN);
printf("mouse data [%#x %#x %#x %#x]\n", buf[0], buf[1], buf[2], buf[3]);
}
}
ret = close(fd);
ICUNIT_ASSERT_EQUAL(ret, 0, ret);
free(buf);
}
return 0;
}
void ItTestHid001(void)
{
TEST_ADD_CASE("IT_DRIVERS_HID_001", Testcase, TEST_LOS, TEST_DRIVERBASE, TEST_LEVEL0, TEST_FUNCTION);
}
| 35.413043 | 105 | 0.669122 | qdsxinyee4 |
d789ac373409dd4a1364e17a18d361f10f185841 | 64,589 | hpp | C++ | src/tip/db/pg/detail/connection_fsm.hpp | zmij/pg_async | 08e4078588827c87297168102d7ed6b9807ab818 | [
"Artistic-2.0"
] | 25 | 2016-02-12T14:06:23.000Z | 2021-12-20T02:45:35.000Z | src/tip/db/pg/detail/connection_fsm.hpp | zmij/pg_async | 08e4078588827c87297168102d7ed6b9807ab818 | [
"Artistic-2.0"
] | 9 | 2016-11-21T08:49:19.000Z | 2019-07-02T10:52:35.000Z | src/tip/db/pg/detail/connection_fsm.hpp | zmij/pg_async | 08e4078588827c87297168102d7ed6b9807ab818 | [
"Artistic-2.0"
] | 5 | 2018-03-16T11:46:23.000Z | 2022-03-06T06:58:57.000Z | /*
* connection_fsm.hpp
*
* Created on: Jul 30, 2015
* Author: zmij
*/
#ifndef LIB_PG_ASYNC_SRC_TIP_DB_PG_DETAIL_BASIC_CONNECTION_NEW_HPP_
#define LIB_PG_ASYNC_SRC_TIP_DB_PG_DETAIL_BASIC_CONNECTION_NEW_HPP_
#include <boost/noncopyable.hpp>
#include <map>
#include <stack>
#include <set>
#include <memory>
#include <afsm/fsm.hpp>
#include <tip/db/pg/asio_config.hpp>
#include <tip/db/pg/common.hpp>
#include <tip/db/pg/error.hpp>
#include <tip/db/pg/transaction.hpp>
#include <tip/db/pg/resultset.hpp>
#include <tip/db/pg/detail/basic_connection.hpp>
#include <tip/db/pg/detail/protocol.hpp>
#include <tip/db/pg/detail/md5.hpp>
#include <tip/db/pg/detail/result_impl.hpp>
#include <tip/db/pg/detail/connection_observer.hpp>
#include <tip/db/pg/log.hpp>
namespace tip {
namespace db {
namespace pg {
class resultset;
namespace events {
struct transport_connected {};
struct authn_event {
detail::auth_states state;
detail::message_ptr message;
};
struct complete {};
struct ready_for_query {
char status;
};
struct row_description {
mutable std::vector<field_description> fields;
};
struct row_event {
std::shared_ptr< detail::row_data > data;
row_event() : data(std::make_shared< detail::row_data >()) {}
detail::row_data&
row() { return *data; }
detail::row_data
move_row() const
{
detail::row_data rd;
rd.swap(*data);
return rd;
}
// TODO Move accessor
};
struct parse_complete {};
struct bind_complete {};
struct no_data {}; // Prepared query doesn't return data
struct terminate {};
} /* namespace events */
namespace detail {
LOCAL_LOGGING_FACILITY_CFG_FUNC(PGFSM, config::INTERNALS_LOG, fsm_log);
template < typename Mutex, typename TransportType, typename SharedType >
struct connection_fsm_def : ::afsm::def::state_machine<
connection_fsm_def< Mutex, TransportType, SharedType > >,
public std::enable_shared_from_this< SharedType > {
//@{
/** @name Misc typedefs */
using transport_type = TransportType;
using shared_type = SharedType;
using this_type = connection_fsm_def<Mutex, transport_type, shared_type>;
using message_ptr = std::shared_ptr< message >;
using prepared_statements_map = std::map< std::string, events::row_description >;
using result_ptr = std::shared_ptr< result_impl >;
using connection_fsm_type = ::afsm::state_machine<this_type, Mutex, connection_observer>;
using none = ::afsm::none;
template < typename StateDef, typename ... Tags >
using state = ::afsm::def::state<StateDef, Tags...>;
template < typename MachineDef, typename ... Tags >
using state_machine = ::afsm::def::state_machine<MachineDef, Tags...>;
template < typename ... T >
using transition_table = ::afsm::def::transition_table<T...>;
template < typename Event, typename Action = none, typename Guard = none >
using in = ::afsm::def::internal_transition< Event, Action, Guard>;
template <typename SourceState, typename Event, typename TargetState,
typename Action = none, typename Guard = none>
using tr = ::afsm::def::transition<SourceState, Event, TargetState, Action, Guard>;
template < typename Predicate >
using not_ = ::psst::meta::not_<Predicate>;
//@}
//@{
/** @name Actions */
struct on_connection_error {
template < typename SourceState, typename TargetState >
void
operator() (error::connection_error const& err, connection_fsm_type& fsm,
SourceState&, TargetState&)
{
fsm.log(logger::ERROR) << "connection::on_connection_error Error: "
<< err.what();
fsm.notify_error(err);
}
};
struct disconnect {
template < typename SourceState, typename TargetState >
void
operator() (events::terminate const&, connection_fsm_type& fsm, SourceState&, TargetState&)
{
fsm.log() << "connection: disconnect";
fsm.send(message(terminate_tag));
fsm.close_transport();
}
};
//@}
//@{
/** @name States */
struct unplugged : state< unplugged > {
using deferred_events = ::psst::meta::type_tuple<
events::terminate,
events::begin,
events::commit,
events::rollback,
events::execute,
events::execute_prepared
>;
};
struct terminated : ::afsm::def::terminal_state< terminated > {
template < typename Event >
void
on_enter(Event const&, connection_fsm_type& fsm)
{
fsm.log() << "entering: terminated";
fsm.send(message(terminate_tag));
fsm.notify_terminated();
}
};
struct t_conn : state< t_conn > {
using deferred_events = ::psst::meta::type_tuple<
events::terminate,
events::begin,
events::commit,
events::rollback,
events::execute,
events::execute_prepared
>;
void
on_enter(connection_options const& opts, connection_fsm_type& fsm)
{
fsm.connect_transport(opts);
}
template < typename Event >
void
on_exit(Event const&, connection_fsm_type& fsm)
{
fsm.start_read();
}
};
struct authn : state< authn > {
using deferred_events = ::psst::meta::type_tuple<
events::terminate,
events::begin,
events::commit,
events::rollback,
events::execute,
events::execute_prepared
>;
template < typename Event >
void
on_enter(Event const&, connection_fsm_type& fsm)
{
fsm.send_startup_message();
}
struct handle_authn_event {
template < typename SourceState, typename TargetState >
void
operator() (events::authn_event const& evt, connection_fsm_type& fsm,
SourceState&, TargetState&)
{
fsm.log() << "authn: handle auth_event";
switch (evt.state) {
case OK: {
fsm.log() << "Authenticated with postgre server";
break;
}
case Cleartext : {
fsm.log() << "Cleartext password requested";
message pm(password_message_tag);
pm.write(fsm.options().password);
fsm.send(::std::move(pm));
break;
}
case MD5Password: {
fsm.log() << "MD5 password requested";
// Read salt
std::string salt;
evt.message->read(salt, 4);
connection_options const& co = fsm.options();
// Calculate hash
std::string pwdhash = boost::md5((co.password + co.user).c_str()).digest().hex_str_value();
std::string md5digest = std::string("md5") + boost::md5( (pwdhash + salt).c_str() ).digest().hex_str_value();
// Construct and send message
message pm(password_message_tag);
pm.write(md5digest);
fsm.send(::std::move(pm));
break;
}
default : {
std::stringstream err;
err << "Unsupported authentication scheme "
<< evt.state << " requested by server";
fsm.process_event(error::connection_error(err.str()));
}
}
}
};
using internal_transitions = transition_table<
in< events::authn_event, handle_authn_event, none >
>;
};
struct idle : state< idle > {
template < typename Event >
void
on_enter(Event const&, connection_fsm_type& fsm)
{
fsm.notify_idle();
}
using internal_transitions = transition_table<
/* Event Action Guard */
/* +-----------------+-----------+---------+*/
in< events::ready_for_query, none, none >
>;
};
struct transaction : state_machine<transaction> {
using deferred_events = ::psst::meta::type_tuple< events::terminate >;
using transaction_fsm_type = ::afsm::inner_state_machine< transaction,
connection_fsm_type >;
using transaction_ptr = std::shared_ptr< pg::transaction >;
using transaction_weak_ptr = std::weak_ptr< pg::transaction >;
//@{
/** State forwards */
struct tran_error;
//@}
//@{
/** @name Actions */
struct transaction_started {
template < typename Event, typename SourceState, typename TargetState >
void
operator() (Event const&, transaction_fsm_type& fsm, SourceState&, TargetState&)
{
fsm.log() << "transaction::transaction_started";
fsm.notify_started();
}
};
struct commit_transaction {
template < typename SourceState, typename TargetState >
void
operator() (events::commit const&, transaction_fsm_type& fsm, SourceState&, TargetState&)
{
fsm.log() << "transaction::commit_transaction";
fsm.connection().send_commit();
}
};
struct rollback_transaction {
template < typename SourceState, typename TargetState >
void
operator() (events::rollback const&, transaction_fsm_type& fsm, SourceState&, TargetState&)
{
fsm.log() << "transaction::rollback_transaction";
fsm.connection().send_rollback();
fsm.notify_error(error::query_error("Transaction rolled back"));
}
template < typename Event, typename SourceState, typename TargetState >
void
operator() (Event const&, transaction_fsm_type& fsm, SourceState&, TargetState&)
{
fsm.log() << "transaction::rollback_transaction (on error)";
fsm.connection().send_rollback();
fsm.notify_error(error::query_error("Transaction rolled back"));
}
};
struct tran_finished {
template < typename SourceState, typename TargetState >
void
operator() (events::execute const& evt, transaction_fsm_type& fsm,
SourceState&, TargetState&)
{
fsm.log(logger::WARNING)
<< "Execute event queued after transaction close";
if (evt.error) {
try {
evt.error( error::transaction_closed{} );
} catch (::std::exception const& e) {
fsm.log(logger::WARNING) << "Exception in execute error handler " << e.what();
} catch (...) {
// Ignore handler error
fsm.log(logger::WARNING) << "Exception in execute error handler";
}
}
}
template < typename SourceState, typename TargetState >
void
operator() (events::execute_prepared const& evt, transaction_fsm_type& fsm,
SourceState&, TargetState&)
{
fsm.log(logger::WARNING)
<< "Execute prepared event queued after transaction close";
if (evt.error) {
try {
evt.error( error::transaction_closed{} );
} catch (::std::exception const& e) {
fsm.log(logger::WARNING) << "Exception in execute prepared error handler " << e.what();
} catch (...) {
// Ignore handler error
fsm.log(logger::WARNING) << "Exception in execute prepared error handler";
}
}
}
};
//@}
//@{
/** @name Transaction sub-states */
struct starting : state< starting > {
using deferred_events = ::psst::meta::type_tuple<
events::execute,
events::execute_prepared,
events::commit,
events::rollback
>;
void
on_enter(events::begin const& evt, transaction_fsm_type& fsm)
{
fsm.connection().send_begin(evt);
}
using internal_transitions = transition_table<
/* Event Action Guard */
/* +-------------------------+-----------+----------+*/
in< command_complete , none , none >
>;
};
struct idle : state< idle > {
using idle_fsm = ::afsm::state<idle, transaction_fsm_type>;
idle_fsm&
fsm()
{ return static_cast<idle_fsm&>(*this); }
idle_fsm const&
fsm() const
{ return static_cast<idle_fsm const&>(*this); }
transaction_fsm_type&
tran()
{ return fsm().enclosing_fsm(); }
transaction_fsm_type const&
tran() const
{ return fsm().enclosing_fsm(); }
::psst::log::local
log(logger::event_severity s = PGFSM_DEFAULT_SEVERITY) const
{
return tran().log();
}
void
on_exit(error::query_error const& err, transaction_fsm_type& fsm)
{
fsm.notify_error(err);
}
void
on_exit(error::client_error const& err, transaction_fsm_type& fsm)
{
fsm.notify_error(err);
}
using internal_transitions = transition_table<
/* Event Action Guard */
/* +-------------------------+-------+---------+*/
in< command_complete , none , none >,
in< events::ready_for_query , none , none >
>;
};
struct tran_error : state< tran_error > {
using internal_transitions = transition_table<
/* Event Action Guard */
/* +---------------------+-----------------------+---------+*/
in< events::commit, none, none >,
in< events::rollback, none, none >
>;
};
struct exiting : state< exiting > {
template < typename Event >
void
on_enter(Event const&, transaction_fsm_type& fsm)
{
callback_ = notification_callback{};
}
void
on_enter(events::commit const& evt, transaction_fsm_type& fsm)
{
callback_ = evt.callback;
}
void
on_enter(events::rollback const& evt, transaction_fsm_type& fsm)
{
callback_ = evt.callback;
}
template < typename Event >
void
on_exit(Event const&, transaction_fsm_type& fsm)
{
if (callback_) {
auto cb = callback_;
fsm.connection().async_notify(
[cb](){
try {
cb();
} catch (::std::exception const& e) {
fsm_log(logger::WARNING) << "Exception in notify handler on exit transaction " << e.what();
} catch(...) {
// Ignore handler error
fsm_log(logger::WARNING) << "Exception in notify handler on exit transaction";
}
}
);
callback_ = notification_callback{};
}
}
using internal_transitions = transition_table<
/* Event Action Guard */
/* +-----------------------------+---------------+---------+*/
in< command_complete , none , none >,
in< events::commit , none , none >,
in< events::rollback , none , none >,
in< events::execute , tran_finished , none >,
in< events::execute_prepared , tran_finished , none >
>;
notification_callback callback_;
};
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Simple query sub state machine
//--------------------------------------------------------------------
struct simple_query : state_machine< simple_query > {
using simple_query_fsm_type =
::afsm::inner_state_machine<simple_query, transaction_fsm_type>;
simple_query_fsm_type&
fsm()
{ return static_cast<simple_query_fsm_type&>(*this); }
simple_query_fsm_type const&
fsm() const
{ return static_cast<simple_query_fsm_type const&>(*this); }
transaction_fsm_type&
tran()
{ return fsm().enclosing_fsm(); }
transaction_fsm_type const&
tran() const
{ return fsm().enclosing_fsm(); }
connection_fsm_type&
connection()
{ return tran().connection(); }
connection_fsm_type const&
connection() const
{ return tran().connection(); }
::psst::log::local
log(logger::event_severity s = PGFSM_DEFAULT_SEVERITY) const
{
return tran().log(s);
}
void
on_enter(events::execute const& q, transaction_fsm_type&)
{
log() << "Execute query: " << q.expression;
query_ = q;
message m(query_tag);
m.write(q.expression);
connection().send(::std::move(m));
}
template < typename Event, typename FSM >
void
on_exit(Event const&, FSM&)
{
query_ = events::execute{};
}
template < typename FSM >
void
on_exit(error::query_error const& err, FSM&)
{
tran().notify_error(*this, err);
query_ = events::execute{};
}
template < typename FSM >
void
on_exit(error::client_error const& err, FSM&)
{
tran().notify_error(err);
query_ = events::execute();
}
using deferred_events = ::psst::meta::type_tuple<
events::execute,
events::execute_prepared,
events::commit,
events::rollback
>;
//@{
/** @name Simple query sub-states */
struct waiting : state< waiting > {
struct non_select_result {
void
operator()(command_complete const& evt, simple_query_fsm_type& fsm,
waiting&, waiting&)
{
fsm.tran().log() << "Non-select query complete "
<< evt.command_tag;
// FIXME Non-select query result
fsm.tran().notify_result(fsm, result_ptr(new result_impl), true);
}
};
using internal_transitions = transition_table<
in< command_complete, non_select_result, none >
>;
};
struct fetch_data : state< fetch_data> {
using deferred_events = ::psst::meta::type_tuple< events::ready_for_query >;
fetch_data() : result_( new result_impl ) {}
void
on_enter(events::row_description const& rd,
simple_query_fsm_type& fsm)
{
// TODO Don't reset the resultset
result_.reset(new result_impl); // TODO Number of resultset
result_->row_description().swap(rd.fields);
}
template < typename Event >
void
on_exit(Event const&, simple_query_fsm_type& fsm)
{
fsm.tran().notify_result(fsm, resultset(result_), true);
}
struct parse_data_row {
template < typename FSM, typename TargetState >
void
operator() (events::row_event const& row, FSM&,
fetch_data& fetch, TargetState&)
{
// TODO Move the data from event
fetch.result_->rows().push_back(row.move_row());
}
};
using internal_transitions = transition_table<
in< events::row_event, parse_data_row, none >
>;
result_ptr result_;
};
using initial_state = waiting;
//@}
//@{
/** @name Transitions for simple query */
using transitions = transition_table<
/* Start Event Next Action Guard */
/* +----------------+---------------------------+---------------+-----------+-------+ */
tr< waiting , events::row_description , fetch_data , none , none >,
tr< fetch_data , command_complete , waiting , none , none >
>;
events::execute query_;
};
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Extended query sub state machine
//--------------------------------------------------------------------
struct extended_query : state_machine<extended_query> {
using extended_query_fsm_type =
::afsm::inner_state_machine<extended_query, transaction_fsm_type>;
extended_query() : row_limit_(0),
result_(new result_impl) {}
extended_query_fsm_type&
fsm()
{ return static_cast<extended_query_fsm_type&>(*this); }
extended_query_fsm_type const&
fsm() const
{ return static_cast<extended_query_fsm_type const&>(*this); }
transaction_fsm_type&
tran()
{ return fsm().enclosing_fsm(); }
transaction_fsm_type const&
tran() const
{ return fsm().enclosing_fsm(); }
connection_fsm_type&
connection()
{ return tran().connection(); }
connection_fsm_type const&
connection() const
{ return tran().connection(); }
::psst::log::local
log(logger::event_severity s = PGFSM_DEFAULT_SEVERITY) const
{
return tran().log(s);
}
void
on_enter(events::execute_prepared const& q, transaction_fsm_type&)
{
query_ = q;
std::ostringstream os;
os << query_.expression;
if (!query_.param_types.empty()) {
os << "{";
std::ostream_iterator< oids::type::oid_type > out(os, ",");
std::copy( query_.param_types.begin(), query_.param_types.end() - 1, out );
os << query_.param_types.back() << "}";
}
query_name_ = "q_" +
std::string( boost::md5( os.str().c_str() ).digest().hex_str_value() );
}
template < typename Event, typename FSM >
void
on_exit(Event const&, FSM&)
{
query_ = events::execute_prepared();
}
template < typename FSM >
void
on_exit(error::query_error const& err, FSM&)
{
tran().notify_error(*this, err);
query_ = events::execute_prepared();
}
template < typename FSM >
void
on_exit(error::client_error const& err, FSM&)
{
tran().notify_error(err);
query_ = events::execute_prepared();
}
bool
is_query_prepared() const
{
return connection().is_prepared(query_name_);
}
void
send_parse()
{
tran().log() << "Parse query " << query_.expression;
message cmd(parse_tag);
cmd.write(query_name_);
cmd.write(query_.expression);
cmd.write( (smallint)query_.param_types.size() );
for (oids::type::oid_type oid : query_.param_types) {
cmd.write( (integer)oid );
}
message describe(describe_tag);
describe.write('S');
describe.write(query_name_);
cmd.pack(describe);
cmd.pack(message(sync_tag));
connection().send(::std::move(cmd));
}
void
send_bind_exec()
{
message cmd(bind_tag);
cmd.write(portal_name_);
cmd.write(query_name_);
if (!query_.params.empty()) {
auto out = cmd.output();
std::copy(query_.params.begin(), query_.params.end(), out);
} else {
cmd.write((smallint)0); // parameter format codes
cmd.write((smallint)0); // number of parameters
}
if (is_query_prepared()) {
events::row_description const& row =
connection().get_prepared(query_name_);
cmd.write((smallint)row.fields.size());
tran().log() << "Write " << row.fields.size() << " field formats";
for (auto const& fd : row.fields) {
cmd.write((smallint)fd.format_code);
}
} else {
cmd.write((smallint)0); // no row description
}
tran().log() << "Execute prepared query: " << query_.expression;
message execute(execute_tag);
execute.write(portal_name_);
execute.write(row_limit_);
cmd.pack(execute);
cmd.pack(message(sync_tag));
connection().send(::std::move(cmd));
}
using deferred_events = ::psst::meta::type_tuple<
events::execute,
events::execute_prepared,
events::commit,
events::rollback
>;
//@{
struct store_prepared_desc {
template < typename SourceState, typename TargetState >
void
operator() (events::row_description const& row, extended_query_fsm_type& fsm,
SourceState&, TargetState&)
{
for (auto& fd : row.fields) {
if (io::traits::has_binary_parser(fd.type_oid))
fd.format_code = BINARY_DATA_FORMAT;
}
fsm.result_.reset(new result_impl);
fsm.result_->row_description() = row.fields; // copy!
fsm.connection().set_prepared(fsm.query_name_, row);
}
template < typename SourceState, typename TargetState >
void
operator() (events::no_data const&, extended_query& fsm,
SourceState&, TargetState&)
{
fsm.result_.reset(new result_impl);
events::row_description row;
fsm.connection().set_prepared(fsm.query_name_, row);
}
};
struct skip_parsing {
template < typename Event, typename SourceState,
typename TargetState>
void
operator()(Event const&, extended_query& fsm,
SourceState&, TargetState&)
{
fsm.result_.reset(new result_impl);
fsm.result_->row_description() =
fsm.connection().get_prepared(fsm.query_name_).fields;
}
};
struct parse_data_row {
template < typename SourceState, typename TargetState >
void
operator() (events::row_event const& row, extended_query& fsm,
SourceState&, TargetState&)
{
fsm.result_->rows().push_back(row.move_row());
}
};
struct complete_execution {
template < typename SourceState, typename TargetState >
void
operator() (command_complete const& complete, extended_query& fsm,
SourceState&, TargetState&)
{
// TODO Process non-select query result
}
};
//@}
//@{
/** @name Extended query sub-states */
struct prepare : state< prepare > {};
struct parse : state< parse > {
template < typename Event >
void
on_enter(Event const&, extended_query& fsm)
{
fsm.send_parse();
}
using internal_transitions = transition_table<
in< events::parse_complete, none, none >,
in< events::row_description, store_prepared_desc, none >,
in< events::no_data, store_prepared_desc, none >
>;
};
struct bind : state< bind > {
using deferred_events = ::psst::meta::type_tuple<
events::row_event,
command_complete
>;
template < typename Event >
void
on_enter( Event const&, extended_query_fsm_type& fsm )
{
fsm.send_bind_exec();
}
};
struct exec : state< exec > {
template < typename Event >
void
on_exit(Event const&, extended_query_fsm_type& fsm)
{
fsm.tran().log() << "Exit exec state resultset columns "
<< fsm.result_->row_description().size()
<< " rows " << fsm.result_->size();
fsm.tran().notify_result(fsm, resultset(fsm.result_), true);
}
void
on_exit(error::query_error const& err, extended_query_fsm_type& fsm)
{
fsm.tran().notify_error(fsm, err);
}
void
on_exit(error::db_error const& err, extended_query_fsm_type& fsm)
{
fsm.tran().notify_error(err);
}
using internal_transitions = transition_table<
in< events::row_event, parse_data_row, none >,
in< command_complete, none, none >
>;
};
using initial_state = prepare;
//@}
struct is_prepared
{
template < typename FSM, typename State >
bool
operator()(FSM& fsm, State&) const
{
return fsm.connection().is_prepared(fsm.query_name_);
}
template < class EVT, class SourceState, class TargetState>
bool
operator()(EVT const&, extended_query_fsm_type& fsm, SourceState&,TargetState&)
{
return fsm.connection().is_prepared(fsm.query_name_);
}
};
//@{
/** Transitions for extended query
* https://www.postgresql.org/docs/9.4/static/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
*/
/** @todo Row limits and portal suspended state */
/** @todo Exit on error handling */
using transitions = transition_table<
/* Start Event Next Action Guard */
/* +------------+---------------------------+-------+---------------+-------------------+ */
tr< prepare , none , parse , none , not_<is_prepared> >,
tr< prepare , none , bind , skip_parsing , is_prepared >,
tr< parse , events::ready_for_query , bind , none , none >,
tr< bind , events::bind_complete , exec , none , none >
>;
//@}
events::execute_prepared query_;
std::string query_name_;
std::string portal_name_;
integer row_limit_;
result_ptr result_;
}; // extended_query
using initial_state = starting;
//@}
//@{
/** @name Transition table for transaction */
using transitions = transition_table<
/* Start Event Next Action */
/*+----------------+---------------------------+-------------------+-----------------------+ */
tr< starting , events::ready_for_query , idle , transaction_started >,
/*+----------------+---------------------------+-------------------+-----------------------+ */
tr< idle , events::commit , exiting , commit_transaction >,
tr< idle , events::rollback , exiting , rollback_transaction >,
tr< idle , error::query_error , exiting , rollback_transaction >,
tr< idle , error::client_error , exiting , rollback_transaction >,
/*+----------------+---------------------------+-------------------+-----------------------+ */
tr< idle , events::execute , simple_query , none >,
tr< simple_query , events::ready_for_query , idle , none >,
tr< simple_query , error::query_error , tran_error , none >,
tr< simple_query , error::client_error , tran_error , none >,
tr< simple_query , error::db_error , tran_error , none >,
/*+----------------+---------------------------+-------------------+-----------------------+ */
tr< idle , events::execute_prepared , extended_query , none >,
tr< extended_query , events::ready_for_query , idle , none >,
tr< extended_query , error::query_error , tran_error , none >,
tr< extended_query , error::client_error , tran_error , none >,
tr< extended_query , error::db_error , tran_error , none >,
/*+----------------+---------------------------+-------------------+-----------------------+ */
tr< tran_error , events::ready_for_query , exiting , rollback_transaction >
>;
//@}
void
notify_started()
{
if (callbacks_.started) {
transaction_ptr t(new pg::transaction( connection().shared_from_this() ));
tran_object_ = t;
try {
callbacks_.started(t);
callbacks_.started = nullptr;
} catch (error::query_error const& e) {
log(logger::ERROR)
<< "Transaction started handler throwed a query_error:"
<< e.what();
connection().process_event(e);
} catch (error::db_error const& e) {
log(logger::ERROR)
<< "Transaction started handler throwed a db_error: "
<< e.what();
connection().process_event(e);
} catch (std::exception const& e) {
log(logger::ERROR)
<< "Transaction started handler throwed an exception: "
<< e.what();
connection().process_event(error::client_error(e));
} catch (...) {
log(logger::ERROR)
<< "Transaction started handler throwed an unknown exception";
connection().process_event(error::client_error("Unknown exception"));
}
}
}
template < typename Source >
void
notify_result(Source& state, resultset res, bool complete)
{
if (state.query_.result) {
auto result_cb = state.query_.result;
auto conn = connection().shared_from_this();
connection().async_notify(
[conn, result_cb, res, complete](){
conn->log() << "In async notify";
try {
result_cb(res, complete);
} catch (error::query_error const& e) {
conn->log(logger::ERROR)
<< "Query result handler throwed a query_error: "
<< e.what();
conn->process_event(e);
} catch (error::db_error const& e) {
conn->log(logger::ERROR)
<< "Query result handler throwed a db_error: "
<< e.what();
conn->process_event(e);
} catch (std::exception const& e) {
conn->log(logger::ERROR)
<< "Query result handler throwed an exception: "
<< e.what();
conn->process_event(error::client_error(e));
} catch (...) {
conn->log(logger::ERROR)
<< "Query result handler throwed an unknown exception";
conn->process_event(error::client_error("Unknown exception"));
}
});
}
}
void
notify_error(error::db_error const& qe)
{
if (callbacks_.error) {
// If the async error handler throws an exception
// all we can do - log the error.
auto error_cb = callbacks_.error;
auto conn = connection().shared_from_this();
connection().async_notify(
[error_cb, conn, qe](){
try {
error_cb(qe);
} catch (std::exception const& e) {
conn->log(logger::ERROR)
<< "Transaction error handler throwed an exception: "
<< e.what();
} catch (...) {
conn->log(logger::ERROR)
<< "Transaction error handler throwed an unknown exception.";
}
});
}
}
template < typename State >
void
notify_error(State& state, error::query_error const& qe)
{
if (state.query_.error) {
try {
state.query_.error(qe);
} catch (std::exception const& e) {
log(logger::ERROR) << "Query error handler throwed an exception: "
<< e.what();
notify_error(qe);
notify_error(error::client_error(e));
} catch (...) {
log(logger::ERROR) << "Query error handler throwed an unexpected exception";
notify_error(qe);
notify_error(error::client_error("Unknown exception"));
}
} else {
log(logger::WARNING) << "No query error handler";
notify_error(qe);
}
}
transaction_fsm_type&
fsm()
{ return static_cast<transaction_fsm_type&>(*this); }
transaction_fsm_type const&
fsm() const
{ return static_cast<transaction_fsm_type const&>(*this); }
connection_fsm_type&
connection()
{ return fsm().enclosing_fsm(); }
connection_fsm_type const&
connection() const
{ return fsm().enclosing_fsm(); }
//@{
/** @name Transaction entry-exit */
void
on_enter(events::begin const& evt, connection_fsm_type& fsm)
{
connection().in_transaction_ = true;
callbacks_ = evt;
}
template < typename Event, typename FSM >
void
on_exit(Event const&, FSM&)
{
connection().in_transaction_ = false;
auto tran = tran_object_.lock();
if (tran) {
tran->mark_done();
}
tran_object_.reset();
callbacks_ = events::begin{};
}
//@}
::psst::log::local
log(logger::event_severity s = PGFSM_DEFAULT_SEVERITY) const
{
return connection().log(s);
}
events::begin callbacks_;
transaction_weak_ptr tran_object_;
}; // transaction state machine
//------------------------------------------------------------------------
using initial_state = unplugged;
//@}
//@{
/** @name Connection state transition table */
using transitions = transition_table<
/* Start Event Next Action */
/*+-------------+---------------------------+---------------+-----------------------+*/
tr< unplugged , connection_options , t_conn , none >,
tr< unplugged , events::terminate , terminated , none >,
tr< t_conn , events::complete , authn , none >,
tr< t_conn , error::connection_error , terminated , on_connection_error >,
tr< authn , events::ready_for_query , idle , none >,
tr< authn , error::connection_error , terminated , on_connection_error >,
/* Transitions from idle */
/*+-------------+---------------------------+---------------+-----------------------+*/
tr< idle , events::begin , transaction , none >,
tr< idle , events::terminate , terminated , disconnect >,
tr< idle , error::connection_error , terminated , on_connection_error >,
/*+-------------+---------------------------+---------------+-----------------------+*/
tr< transaction , events::ready_for_query , idle , none >,
tr< transaction , error::connection_error , terminated , on_connection_error >
>;
//@}
template< typename Event, typename FSM >
void
exception_caught(Event const&, FSM&, ::std::exception& e)
{
log(logger::WARNING) << "Exception escaped all catch handlers "
<< e.what();
}
//@{
using io_service_ptr = asio_config::io_service_ptr;
using client_options_type = std::map< std::string, std::string >;
using shared_base = std::enable_shared_from_this< shared_type >;
using asio_io_handler = std::function< void (asio_config::error_code const& error,
size_t bytes_transferred) >;
//@}
//@{
connection_fsm_def(io_service_ptr svc, client_options_type const& co)
: shared_base(), io_service_{svc}, strand_{*svc}, transport_{svc},
client_opts_{co},
serverPid_{0}, serverSecret_{0}, in_transaction_{false},
connection_number_{ next_connection_number() }
{
incoming_.prepare(8192); // FIXME Magic number, move to configuration
}
virtual ~connection_fsm_def() {}
//@}
size_t
number() const
{
return connection_number_;
}
void
connect_transport(connection_options const& opts)
{
if (opts.uri.empty()) {
throw error::connection_error("No connection uri!");
}
if (opts.database.empty()) {
throw error::connection_error("No database!");
}
if (opts.user.empty()) {
throw error::connection_error("User not specified!");
}
conn_opts_ = opts;
auto _this = shared_base::shared_from_this();
transport_.connect_async(conn_opts_,
[_this](asio_config::error_code const& ec)
{
_this->handle_connect(ec);
});
}
void
close_transport()
{
transport_.close();
}
void
start_read()
{
auto _this = shared_base::shared_from_this();
transport_.async_read(incoming_,
[_this](asio_config::error_code const& ec, size_t bytes_transferred)
{
_this->handle_read(ec, bytes_transferred);
});
}
void
send_startup_message()
{
message m(empty_tag);
create_startup_message(m);
send(::std::move(m));
}
void
send_begin(events::begin const& evt)
{
log() << "Send begin";
message m(query_tag);
::std::ostringstream cmd{"begin"};
cmd << evt.mode;
m.write(cmd.str());
send(::std::move(m));
}
void
send_commit()
{
log() << "Send commit";
message m(query_tag);
m.write("commit");
send(::std::move(m));
}
void
send_rollback()
{
log() << "Send rollback";
message m(query_tag);
m.write("rollback");
send(::std::move(m));
}
void
send(message&& m, asio_io_handler handler = asio_io_handler())
{
if (transport_.connected()) {
auto msg = ::std::make_shared<message>(::std::move(m));
auto data_range = msg->buffer();
auto _this = shared_base::shared_from_this();
auto write_handler =
[_this, handler, msg](asio_config::error_code const& ec, size_t sz)
{
if (handler)
handler(ec, sz);
else
_this->handle_write(ec, sz);
};
transport_.async_write(
ASIO_NAMESPACE::buffer(&*data_range.first,
data_range.second - data_range.first),
write_handler
);
}
}
connection_options const&
options() const
{ return conn_opts_; }
//@{
/** @name Prepared queries */
bool
is_prepared ( std::string const& query ) const
{
return prepared_.count(query);
}
void
set_prepared( std::string const& query, events::row_description const& row_desc )
{
prepared_.insert(std::make_pair(query, row_desc));
}
events::row_description const&
get_prepared( std::string const& query_name ) const
{
auto f = prepared_.find(query_name);
if (f != prepared_.end()) {
return f->second;
}
throw error::db_error("Query is not prepared");
}
//@}
//@{
bool
in_transaction() const
{
return in_transaction_;
}
//@}
//@{
/** @connection events notifications */
void
notify_idle()
{
try {
do_notify_idle();
} catch (::std::exception const& e) {
log(logger::WARNING) << "Exception in on idle handler " << e.what();
} catch (...) {
// Ignore handler error
log(logger::WARNING) << "Exception in on idle handler";
}
}
void
notify_terminated()
{
try {
do_notify_terminated();
} catch (::std::exception const& e) {
log(logger::WARNING) << "Exception in terminated handler " << e.what();
} catch (...) {
// Ignore handler error
log(logger::WARNING) << "Exception in terminated handler";
}
}
void
notify_error(error::connection_error const& e) { do_notify_error(e); }
template < typename Handler >
void
async_notify(Handler&& h)
{
strand_.post( ::std::forward<Handler>(h) );
}
//@}
::psst::log::local
log(logger::event_severity s = PGFSM_DEFAULT_SEVERITY) const
{
return fsm_log(s) << "Conn# " << connection_number_ << ": ";
}
private:
virtual void do_notify_idle() {};
virtual void do_notify_terminated() {};
virtual void do_notify_error(error::connection_error const&) {};
private:
connection_fsm_type&
fsm()
{
return static_cast< connection_fsm_type& >(*this);
}
connection_fsm_type const&
fsm() const
{
return static_cast< connection_fsm_type const& >(*this);
}
void
handle_connect(asio_config::error_code const& ec)
{
if (!ec) {
fsm().process_event(events::complete{});
} else {
fsm().process_event( error::connection_error{ec.message()} );
}
}
void
handle_read(asio_config::error_code const& ec, size_t bytes_transferred)
{
if (!ec) {
// read message
std::istreambuf_iterator<char> in(&incoming_);
read_message(in, bytes_transferred);
// start async operation again
start_read();
} else {
// Socket error - force termination
fsm().process_event(error::connection_error(ec.message()));
}
}
void
handle_write(asio_config::error_code const& ec, size_t)
{
if (ec) {
// Socket error - force termination
fsm().process_event(error::connection_error(ec.message()));
}
}
template < typename InputIter, typename OutputIter >
InputIter
copy(InputIter in, InputIter end, size_t max, OutputIter out)
{
for (size_t i = 0; i < max && in != end; ++i) {
*out++ = *in++;
}
return in;
}
void
read_message( std::istreambuf_iterator< char > in, size_t max_bytes )
{
const size_t header_size = sizeof(integer) + sizeof(byte);
while (max_bytes > 0) {
if (!message_) {
message_.reset(new detail::message);
}
auto out = message_->output();
std::istreambuf_iterator<char> eos;
if (message_->buffer_size() < header_size) {
// Read the header
size_t to_read = std::min((header_size - message_->buffer_size()), max_bytes);
in = copy(in, eos, to_read, out);
max_bytes -= to_read;
}
if (message_->length() > message_->size()) {
// Read the message body
size_t to_read = std::min(message_->length() - message_->size(), max_bytes);
in = copy(in, eos, to_read, out);
max_bytes -= to_read;
assert(message_->size() <= message_->length()
&& "Read too much from the buffer" );
}
if (message_->size() >= 4 && message_->length() == message_->size()) {
message_ptr m = message_;
m->reset_read();
handle_message(m);
message_.reset();
}
}
}
void
create_startup_message(message& m)
{
m.write(PROTOCOL_VERSION);
// Create startup packet
m.write(options::USER);
m.write(conn_opts_.user);
m.write(options::DATABASE);
m.write(conn_opts_.database);
for (auto opt : client_opts_) {
m.write(opt.first);
m.write(opt.second);
}
// trailing terminator
m.write('\0');
}
void
handle_message(message_ptr m)
{
namespace util = ::psst::util;
message_tag tag = m->tag();
if (message::backend_tags().count(tag)) {
switch (tag) {
case authentication_tag: {
integer auth_state(-1);
m->read(auth_state);
fsm().process_event(
events::authn_event{ (auth_states)auth_state, m });
break;
}
case command_complete_tag: {
command_complete cmpl;
m->read(cmpl.command_tag);
log() << "Command complete ("
<< cmpl.command_tag << ")";
fsm().process_event(cmpl);
break;
}
case backend_key_data_tag: {
m->read(serverPid_);
m->read(serverSecret_);
break;
}
case error_response_tag: {
notice_message msg;
m->read(msg);
log(logger::ERROR) << "Error " << msg ;
error::query_error err(msg.message, msg.severity,
msg.sqlstate, msg.detail);
fsm().process_event(err);
break;
}
case parameter_status_tag: {
std::string key;
std::string value;
m->read(key);
m->read(value);
log() << "Parameter " << key << " = " << value;
client_opts_[key] = value;
break;
}
case notice_response_tag : {
notice_message msg;
m->read(msg);
log(logger::INFO) << "Notice " << msg;
break;
}
case ready_for_query_tag: {
char stat(0);
m->read(stat);
log() << "Database "
<< (util::CLEAR) << (util::RED | util::BRIGHT)
<< conn_opts_.uri
<< "[" << conn_opts_.database << "]"
<< logger::severity_color()
<< " is ready for query (" << stat << ")";
fsm().process_event(events::ready_for_query{ stat });
break;
}
case row_description_tag: {
events::row_description rd;
smallint col_cnt;
m->read(col_cnt);
rd.fields.reserve(col_cnt);
for (int i =0; i < col_cnt; ++i) {
field_description fd;
if (m->read(fd)) {
rd.fields.push_back(fd);
} else {
log(logger::ERROR)
<< "Failed to read field description " << i;
// FIXME Process error
}
}
fsm().process_event(rd);
break;
}
case data_row_tag: {
events::row_event r;
if (m->read(r.row())) {
fsm().process_event(r);
} else {
// FIXME Process error
log(logger::ERROR) << "Failed to read data row";
}
break;
}
case parse_complete_tag: {
log() << "Parse complete";
fsm().process_event(events::parse_complete{});
break;
}
case parameter_desription_tag: {
log() << "Parameter descriptions";
break;
}
case bind_complete_tag: {
log() << "Bind complete";
fsm().process_event(events::bind_complete{});
break;
}
case no_data_tag: {
fsm().process_event(events::no_data{});
break;
}
case portal_suspended_tag : {
log() << "Portal suspended";
break;
}
default: {
{
log(logger::DEBUG)
<< "Unhandled message "
<< (util::MAGENTA | util::BRIGHT)
<< (char)tag
<< logger::severity_color();
}
break;
}
}
}
}
static size_t
next_connection_number()
{
static std::atomic<size_t> _number{0};
return _number++;
}
private:
friend class transaction;
asio_config::io_service_ptr io_service_;
asio_config::io_service::strand strand_;
transport_type transport_;
client_options_type client_opts_;
ASIO_NAMESPACE::streambuf incoming_;
message_ptr message_;
integer serverPid_;
integer serverSecret_;
prepared_statements_map prepared_;
::std::atomic<bool> in_transaction_;
size_t connection_number_;
protected:
connection_options conn_opts_;
};
//----------------------------------------------------------------------------
// Concrete connection
//----------------------------------------------------------------------------
template < typename TransportType >
class concrete_connection : public basic_connection,
public ::afsm::state_machine< connection_fsm_def< ::std::mutex, TransportType,
concrete_connection< TransportType > >, ::std::mutex, connection_observer > {
public:
using transport_type = TransportType;
using this_type = concrete_connection< transport_type >;
using fsm_type =
::afsm::state_machine<
connection_fsm_def< ::std::mutex, transport_type, this_type >,
::std::mutex, connection_observer >;
public:
concrete_connection(io_service_ptr svc,
client_options_type const& co,
connection_callbacks const& callbacks)
: basic_connection(), fsm_type(svc, co),
callbacks_(callbacks)
{
if (PGFSM_DEFAULT_SEVERITY > logger::OFF)
fsm_type::make_observer();
}
virtual ~concrete_connection() {}
using fsm_type::log;
private:
//@{
/** @name State machine abstract interface implementation */
virtual void
do_notify_idle() override
{
if (callbacks_.idle) {
callbacks_.idle(fsm_type::shared_from_this());
} else {
log(logger::WARNING) << "No connection idle callback";
}
}
virtual void
do_notify_terminated() override
{
if (callbacks_.terminated) {
callbacks_.terminated(fsm_type::shared_from_this());
} else {
log() << "No connection terminated callback";
}
callbacks_ = connection_callbacks(); // clean up callbacks, no work further.
}
virtual void
do_notify_error(error::connection_error const& e) override
{
log(logger::ERROR) << "Connection error " << e.what();
if (callbacks_.error) {
callbacks_.error(connection_ptr(), e);
} else {
log(logger::ERROR) << "No connection_error callback";
}
}
//@}
virtual void
do_connect(connection_options const& co) override
{
fsm_type::process_event(co);
}
virtual dbalias const&
get_alias() const override
{
return fsm_type::conn_opts_.alias;
}
virtual bool
is_in_transaction() const override
{
return fsm_type::in_transaction();
}
virtual void
do_begin(events::begin&& evt) override
{
if (fsm_type::in_transaction()) {
log(logger::ERROR) << "Cannot begin transaction: already in transaction";
throw error::db_error("Already in transaction");
}
fsm_type::process_event(::std::move(evt));
}
virtual void
do_commit(notification_callback cb, error_callback ecb) override
{
if (!fsm_type::in_transaction()) {
log(logger::ERROR) << "Cannot commit transaction: not in transaction";
if (ecb) {
ecb(error::db_error("Not in transaction"));
}
}
fsm_type::process_event(events::commit{cb, ecb});
}
virtual void
do_rollback(notification_callback cb, error_callback ecb) override
{
if (!fsm_type::in_transaction()) {
log(logger::ERROR) << "Cannot rollback transaction: not in transaction";
if (ecb) {
ecb(error::db_error("Not in transaction"));
}
}
fsm_type::process_event(events::rollback{cb, ecb});
}
virtual void
do_execute(events::execute&& query) override
{
fsm_type::process_event(::std::move(query));
}
virtual void
do_execute(events::execute_prepared&& query) override
{
fsm_type::process_event(::std::move(query));
}
virtual void
do_terminate() override
{
fsm_type::process_event(events::terminate{});
}
private:
connection_callbacks callbacks_;
};
} // namespace detail
} // namespace pg
} // namespace db
} // namespace tip
#endif /* LIB_PG_ASYNC_SRC_TIP_DB_PG_DETAIL_BASIC_CONNECTION_NEW_HPP_ */
| 36.470356 | 133 | 0.46429 | zmij |
d78a332c7792ab3bdcc967f7da56adb0dec68d08 | 1,655 | hpp | C++ | driver/block/ramdisk.hpp | Edgaru089/helos1 | 8dd27c421bdf1d55e3a62b61927d2f0db6f94d01 | [
"Apache-2.0"
] | null | null | null | driver/block/ramdisk.hpp | Edgaru089/helos1 | 8dd27c421bdf1d55e3a62b61927d2f0db6f94d01 | [
"Apache-2.0"
] | null | null | null | driver/block/ramdisk.hpp | Edgaru089/helos1 | 8dd27c421bdf1d55e3a62b61927d2f0db6f94d01 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "blockdevice.hpp"
namespace helos {
namespace block {
// Ramdisk is a block device residing in runtime RAM.
class BlockDeviceRamdisk: public BlockDevice {
public:
BlockDeviceRamdisk(const BlockDeviceRamdisk &) = delete; // Don't copy by value
BlockDeviceRamdisk(BlockDeviceRamdisk &&) = delete;
const BlockDeviceRamdisk &operator=(const BlockDeviceRamdisk &) = delete;
public:
// Creates new, empty (all zero) ramdisk, allocating from kernel memory
BlockDeviceRamdisk(uint64_t blockSize, uint64_t blockCount, ::helos::Permission perm);
// Creates a Ramdisk wrapper from an existing buffer
// Size of the buffer must be a multiple of BlockSize
BlockDeviceRamdisk(void *buffer, uint64_t blockSize, uint64_t blockCount, ::helos ::Permission perm);
~BlockDeviceRamdisk();
public:
uint64_t BlockSize() const override { return blocksize; }
uint64_t Size() const override { return blockcount; }
uint64_t SizeBytes() const override { return blocksize * blockcount; }
::helos::Permission DevicePermission() const override { return perm; }
uint64_t ReadBlock(uint64_t blockOffset, void *data, uint64_t blockCount) const override;
uint64_t WriteBlock(uint64_t blockOffset, const void *data, uint64_t blockCount) override;
public:
// Buffer returns the underlying buffer.
void *Buffer() { return buffer; }
private:
uint64_t blocksize, blockcount;
void * buffer;
int pages; // Number of pages allocated in 4K or 2M paging allocation
::helos::Permission perm;
uint16_t alloctype; // Type of the buffer allocated
};
} // namespace block
} // namespace helos
| 33.77551 | 102 | 0.739577 | Edgaru089 |
d78bde05575515f03516ef6c9949115f3baca6bd | 514 | cpp | C++ | while2.cpp | Ahtesham1234/whiles.cpp | d4071b986090c1561acf72823e7e70b2a2fae8ce | [
"Apache-2.0"
] | null | null | null | while2.cpp | Ahtesham1234/whiles.cpp | d4071b986090c1561acf72823e7e70b2a2fae8ce | [
"Apache-2.0"
] | null | null | null | while2.cpp | Ahtesham1234/whiles.cpp | d4071b986090c1561acf72823e7e70b2a2fae8ce | [
"Apache-2.0"
] | null | null | null | //while2.cpp
//this program print number to the fourth power
#include <iostream>
#incllude <iomanip> //for stew
using namespace std;
int main()
{
int pow=1; //power initially 1
int numb=1 //numb goes from 1 to ???
while (pow<10000) //loop while power <= 4 digits
{
cout << stew(2) << numb; // display number
cout<< setw(5) <<pow <<endl; //display fourth power
++numb ;
pow= numb*numb*numb*numb ; //calculate fourth power
}
cout << endl;
return 0;
}
| 20.56 | 59 | 0.593385 | Ahtesham1234 |
d79245f98f668f3728536eb0415c3bbe29f98c11 | 1,072 | cpp | C++ | SRC/sql/samples/Oracle_returning.cpp | crashangelbr/ChatScript_SQLServer | 4a8b53b2a368863d3aae887186ec911a17711fe5 | [
"MIT"
] | null | null | null | SRC/sql/samples/Oracle_returning.cpp | crashangelbr/ChatScript_SQLServer | 4a8b53b2a368863d3aae887186ec911a17711fe5 | [
"MIT"
] | null | null | null | SRC/sql/samples/Oracle_returning.cpp | crashangelbr/ChatScript_SQLServer | 4a8b53b2a368863d3aae887186ec911a17711fe5 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <SQLAPI.h>
#include <samisc.h>
int main(int argc, char* argv[])
{
SAConnection con; // create connection object
try
{
con.Connect(
"ora111", // database name
"sys", // user name
"java", // password
SA_Oracle_Client);
SACommand cmd(&con, _TSA("delete from t1"));
cmd.Execute();
cmd.setCommandText(_TSA("insert into t1(id,description) values(t1_seq.nextval, 'test') returning id into :idval"));
SAParam& p = cmd.Param(_TSA("idval"));
p.setParamDirType(SA_ParamOutput);
// !important!
p.setAsLong();
p.setParamType(SA_dtLong);
cmd.Execute();
long nID = p.asLong();
sa_tprintf(_TSA("NEW ID %d\n"), nID);
cmd.setCommandText(_TSA("select id,description from t1"));
cmd.Execute();
while (cmd.FetchNext())
{
sa_tprintf(_TSA("%d "), cmd[1].asLong());
sa_tprintf((const SAChar*)cmd[2].asString());
sa_tprintf(_TSA("\n"));
}
}
catch (SAException &x)
{
sa_tprintf(_TSA("ERR: "));
sa_tprintf((const SAChar*)x.ErrText());
sa_tprintf(_TSA("\n"));
}
return 0;
}
| 23.304348 | 117 | 0.642724 | crashangelbr |
d792a6651b1b55575ec0ca8a96a4f36bc8aebbff | 1,501 | hpp | C++ | src/img/PolygonHierarchy.hpp | dholzmueller/sfcpp | b929419b13c35fff199c6c65e87ecffae9963cfc | [
"Apache-2.0"
] | 15 | 2017-10-20T07:53:03.000Z | 2021-09-23T15:54:54.000Z | src/img/PolygonHierarchy.hpp | dholzmueller/sfcpp | b929419b13c35fff199c6c65e87ecffae9963cfc | [
"Apache-2.0"
] | null | null | null | src/img/PolygonHierarchy.hpp | dholzmueller/sfcpp | b929419b13c35fff199c6c65e87ecffae9963cfc | [
"Apache-2.0"
] | 3 | 2017-10-20T20:02:29.000Z | 2020-12-02T12:47:53.000Z | /* Copyright 2017 The sfcpp Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef POLYGONHIERARCHY_HPP
#define POLYGONHIERARCHY_HPP
//#include "Image.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
namespace sfcpp {
namespace img {
class PolygonHierarchy{
public:
/*
Constructors
*/
PolygonHierarchy();
PolygonHierarchy(cv::Mat& img);
//void addChild(PolygonHierarchy child);
std::vector<cv::Point> getData();
std::vector<PolygonHierarchy> getSubTree();
private:
bool id;
std::vector<cv::Point> data;
std::vector<PolygonHierarchy> subTree;
PolygonHierarchy(std::vector<cv::Point> contour, std::vector<PolygonHierarchy> subTreeParam);
std::vector<PolygonHierarchy> createSubTree(std::vector<std::vector<cv::Point>> contours, std::vector<cv::Vec4i> hierarchy, int startIndex);
};
}
}
#endif /* POLYGONHIERARCHY_HPP */
| 26.803571 | 143 | 0.706862 | dholzmueller |
d793e408fde2ffa5449e04c891e9970776a143e4 | 32,442 | cpp | C++ | logdevice/server/rebuilding/RebuildingReadStorageTaskV2.cpp | mateuszp4925/LogDevice | 6e79f0e61fff11b0caf15eb0bfd4d16ab5481a83 | [
"BSD-3-Clause"
] | 1 | 2019-12-18T09:07:45.000Z | 2019-12-18T09:07:45.000Z | logdevice/server/rebuilding/RebuildingReadStorageTaskV2.cpp | mateuszp4925/LogDevice | 6e79f0e61fff11b0caf15eb0bfd4d16ab5481a83 | [
"BSD-3-Clause"
] | null | null | null | logdevice/server/rebuilding/RebuildingReadStorageTaskV2.cpp | mateuszp4925/LogDevice | 6e79f0e61fff11b0caf15eb0bfd4d16ab5481a83 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/server/rebuilding/RebuildingReadStorageTaskV2.h"
#include "logdevice/common/AdminCommandTable.h"
#include "logdevice/server/ServerProcessor.h"
#include "logdevice/server/storage_tasks/StorageThreadPool.h"
namespace facebook { namespace logdevice {
RebuildingReadStorageTaskV2::RebuildingReadStorageTaskV2(
std::weak_ptr<Context> context)
: StorageTask(StorageTask::Type::REBUILDING_READ_V2), context_(context) {}
void RebuildingReadStorageTaskV2::execute() {
std::shared_ptr<Context> context = context_.lock();
if (context == nullptr) {
// The ShardRebuilding was aborted. Nothing to do.
return;
}
auto start_time = SteadyTimestamp::now();
// Let's just lock the mutex for the whole duration of the storage task.
// We could make it more fine-grained and lock it only for accesses to
// context's fields, avoiding blocking IO with locked mutex, but it doesn't
// really matter because ShardRebuilding never accesses Context when a storage
// task is in flight.
std::lock_guard<std::mutex> context_lock(context->logsMutex);
ld_check(!context->reachedEnd);
ld_check(!context->persistentError);
ld_check(result_.empty());
StatsHolder* stats = getStats();
STAT_INCR(stats, read_streams_num_ops_rebuilding);
if (context->iterator == nullptr) {
if (!fetchTrimPoints(context.get())) {
context->persistentError = true;
return;
}
LocalLogStore::ReadOptions opts(
"RebuildingReadStorageTaskV2", /* rebuilding */ true);
opts.fill_cache = context->rebuildingSettings->use_rocksdb_cache;
opts.allow_copyset_index = true;
std::unordered_map<logid_t, std::pair<lsn_t, lsn_t>> logs;
for (const auto& p : context->logs) {
logs[p.first] =
std::make_pair(p.second.trimPoint + 1, p.second.plan.untilLSN);
}
context->iterator = createIterator(opts, logs);
context->nextLocation =
std::shared_ptr<LocalLogStore::AllLogsIterator::Location>(
context->iterator->minLocation());
context->filter = std::make_unique<Filter>(context.get());
}
LocalLogStore::AllLogsIterator* iterator = context->iterator.get();
context->filter->task = this;
context->filter->clearStats();
LocalLogStore::ReadStats read_stats;
read_stats.max_bytes_to_read = context->rebuildingSettings->max_batch_bytes;
read_stats.max_execution_time = context->rebuildingSettings->max_batch_time;
// Count iterator initialization and trim point fetching towards the
// execution time limit.
read_stats.read_start_time = start_time;
size_t prev_block_bytes_read = iterator->getIOBytesUnnormalized();
size_t records_in_result = 0;
size_t bytes_in_result = 0;
SCOPE_EXIT {
context->bytesRead =
read_stats.read_record_bytes + read_stats.read_csi_bytes;
size_t block_bytes_read =
iterator->getIOBytesUnnormalized() - prev_block_bytes_read;
if (context->persistentError || context->reachedEnd) {
context->iterator.reset();
}
if (context->persistentError) {
// No point delivering records if rebuilding is going to stall now.
result_.clear();
} else {
auto shard = context->myShardID.shard();
PER_SHARD_STAT_ADD(stats,
read_streams_num_records_read_rebuilding,
shard,
read_stats.read_records);
PER_SHARD_STAT_ADD(
stats,
read_streams_num_bytes_read_rebuilding,
shard,
read_stats.read_record_bytes + read_stats.read_csi_bytes);
PER_SHARD_STAT_ADD(stats,
read_streams_num_record_bytes_read_rebuilding,
shard,
read_stats.read_record_bytes);
PER_SHARD_STAT_ADD(stats,
read_streams_num_csi_entries_read_rebuilding,
shard,
read_stats.read_csi_entries);
PER_SHARD_STAT_ADD(stats,
read_streams_num_csi_bytes_read_rebuilding,
shard,
read_stats.read_csi_bytes);
PER_SHARD_STAT_ADD(stats,
read_streams_block_bytes_read_rebuilding,
shard,
block_bytes_read);
STAT_ADD(stats,
read_streams_num_records_filtered_rebuilding,
read_stats.filtered_records);
STAT_ADD(stats,
read_streams_num_bytes_filtered_rebuilding,
read_stats.filtered_record_bytes);
STAT_ADD(stats,
read_streams_num_records_late_filtered_rebuilding,
context->filter->nRecordsLateFiltered);
size_t tot_skipped = context->filter->nRecordsSCDFiltered +
context->filter->nRecordsNotDirtyFiltered +
context->filter->nRecordsTimestampFiltered +
context->filter->nRecordsDrainedFiltered +
context->filter->nRecordsEpochRangeFiltered;
auto end_time = SteadyTimestamp::now();
RATELIMIT_INFO(
std::chrono::seconds(10),
1,
"Rebuilding has read a batch of records in %.3fs. Got %lu records "
"(%lu bytes) in %lu chunks, read %lu bytes of rocksdb blocks. "
"Skipped %lu records (SCD: %lu, ND: %lu, "
"DRAINED: %lu, TS: %lu, EPOCH: %lu; LATE: %lu).",
std::chrono::duration_cast<std::chrono::duration<double>>(end_time -
start_time)
.count(),
records_in_result,
bytes_in_result,
result_.size(),
block_bytes_read,
tot_skipped,
context->filter->nRecordsSCDFiltered,
context->filter->nRecordsNotDirtyFiltered,
context->filter->nRecordsDrainedFiltered,
context->filter->nRecordsTimestampFiltered,
context->filter->nRecordsEpochRangeFiltered,
context->filter->nRecordsLateFiltered);
}
};
std::vector<ShardID> temp_copyset;
switch (iterator->state()) {
case IteratorState::AT_RECORD:
// Previous storage task stopped at a record.
break;
case IteratorState::LIMIT_REACHED:
// Previous storage task reached a limit. Tell it to resume where it
// left off, but with the refreshed limit.
iterator->next(context->filter.get(), &read_stats);
break;
case IteratorState::AT_END:
// Newly created or invalidated iterator.
iterator->seek(
*context->nextLocation, context->filter.get(), &read_stats);
break;
case IteratorState::ERROR:
// If previous storage task got the iterator into ERROR state, it would
// have reported it, and ShardRebuilding wouldn't have scheduled another
// storage task.
case IteratorState::WOULDBLOCK:
case IteratorState::MAX:
ld_critical(
"Unexpected iterator state: %s", toString(iterator->state()).c_str());
ld_check(false);
context->persistentError = true;
return;
}
ld_check(result_.empty());
ChunkData* chunk = nullptr;
Context::LogState* log_state = nullptr;
for (; iterator->state() == IteratorState::AT_RECORD;
iterator->next(context->filter.get(), &read_stats)) {
if (!result_.empty() && read_stats.readLimitReached()) {
// Current record took us over the limit. If it's not the first record,
// stop here without delivering it.
break;
}
logid_t log = iterator->getLogID();
lsn_t lsn = iterator->getLSN();
Slice record = iterator->getRecord();
bool start_new_chunk = false;
// Make sure log_state points to current log.
if (chunk == nullptr || log != chunk->address.log) {
auto it = context->logs.find(log);
ld_check(it != context->logs.end()); // Filter should reject such records
log_state = &it->second;
start_new_chunk = true;
}
if (lsn <= log_state->lastSeenLSN) {
RATELIMIT_WARNING(
std::chrono::seconds(10),
10,
"AllLogsIterator's LSN went backwards. This should be rare. Log: "
"%lu, last seen lsn: %s, current lsn: %s, location: %s",
log.val(),
lsn_to_string(log_state->lastSeenLSN).c_str(),
lsn_to_string(lsn).c_str(),
iterator->getLocation()->toString().c_str());
continue;
}
// Bump currentBlockID if needed.
RecordTimestamp timestamp;
int rv = checkRecordForBlockChange(
log, lsn, record, context.get(), log_state, &temp_copyset, ×tamp);
if (rv != 0) {
ld_check_eq(err, E::MALFORMED_RECORD);
RATELIMIT_ERROR(std::chrono::seconds(10),
10,
"Malformed record at %s",
iterator->getLocation()->toString().c_str());
STAT_INCR(stats, rebuilding_malformed_records);
++context->numMalformedRecordsSeen;
if (context->numMalformedRecordsSeen >=
context->rebuildingSettings->max_malformed_records_to_tolerate) {
// Suspiciously many records are malformed. Escalate and stall.
ld_critical("Rebuilding saw too many (%lu) malformed records. "
"Stopping rebuilding just in case. Please investigate.",
context->numMalformedRecordsSeen);
context->persistentError = true;
return;
}
continue;
}
if (!start_new_chunk) {
// Chunk needs to contain records for the same log with consecutive LSNs,
// same copyset and same block ID.
// The consecutive LSN requirement is not necessary currently,
// but may be useful in future for donor-driven rebuilding without WAL.
start_new_chunk |= lsn > log_state->lastSeenLSN + 1 ||
log_state->currentBlockID != chunk->blockID;
}
log_state->lastSeenLSN = lsn;
// Create new chunk if needed.
if (start_new_chunk) {
result_.push_back(std::make_unique<ChunkData>());
chunk = result_.back().get();
chunk->address.log = log;
chunk->address.min_lsn = lsn;
chunk->blockID = log_state->currentBlockID;
chunk->oldestTimestamp = timestamp;
++log_state->chunksDelivered;
bool found = lookUpEpochMetadata(log,
lsn,
context.get(),
log_state,
/* create_replication_scheme */ true);
// If the record is not covered by RebuildingPlan, ReadFilter would have
// discarded it.
ld_check(found);
ld_check_le(log_state->currentEpochRange.first, lsn_to_epoch(lsn));
ld_check_gt(log_state->currentEpochRange.second, lsn_to_epoch(lsn));
ld_check(log_state->currentReplication != nullptr);
chunk->replication = log_state->currentReplication;
} else {
// All records of a chunk must share the same EpochMetadata.
// To ensure that let's ensure that they share the same epoch.
ld_check_eq(lsn_to_epoch(lsn), lsn_to_epoch(chunk->address.min_lsn));
}
chunk->address.max_lsn = lsn;
chunk->addRecord(lsn, record);
++log_state->recordsDelivered;
log_state->bytesDelivered += record.size;
++records_in_result;
bytes_in_result += record.size;
}
switch (iterator->state()) {
case IteratorState::AT_RECORD:
case IteratorState::LIMIT_REACHED:
context->nextLocation =
std::shared_ptr<LocalLogStore::AllLogsIterator::Location>(
iterator->getLocation());
context->progress = iterator->getProgress();
break;
case IteratorState::AT_END:
context->reachedEnd = true;
context->nextLocation.reset();
context->progress = 1;
// context->iterator will be destroyed in the SCOPE_EXIT above, after
// pulling stats out of it one last time.
break;
case IteratorState::WOULDBLOCK:
case IteratorState::MAX:
ld_critical(
"Unexpected iterator state: %s", toString(iterator->state()).c_str());
ld_check(false);
FOLLY_FALLTHROUGH;
case IteratorState::ERROR:
ld_info("Stopping rebuilding after encountering an iterator error.");
context->persistentError = true;
break;
}
}
int RebuildingReadStorageTaskV2::checkRecordForBlockChange(
logid_t log,
lsn_t lsn,
Slice record,
Context* context,
Context::LogState* log_state,
std::vector<ShardID>* temp_copyset,
RecordTimestamp* out_timestamp) {
copyset_size_t new_copyset_size;
Payload payload;
temp_copyset->resize(COPYSET_SIZE_MAX);
std::chrono::milliseconds timestamp;
int rv = LocalLogStoreRecordFormat::parse(record,
×tamp,
nullptr,
nullptr,
nullptr,
&new_copyset_size,
temp_copyset->data(),
COPYSET_SIZE_MAX,
nullptr,
nullptr,
&payload,
context->myShardID.shard());
if (rv != 0) {
RATELIMIT_ERROR(std::chrono::seconds(1),
1,
"Cannot parse record at lsn %s of log %lu.",
lsn_to_string(lsn).c_str(),
log.val());
ld_check(err == E::MALFORMED_RECORD);
return -1;
}
*out_timestamp = RecordTimestamp(timestamp);
temp_copyset->resize(new_copyset_size);
bool copyset_changed = (log_state->lastSeenCopyset != *temp_copyset);
bool epoch_changed =
lsn_to_epoch(log_state->lastSeenLSN) != lsn_to_epoch(lsn);
// Factor 2 is arbitrary.
size_t max_block_size = getSettings().get()->sticky_copysets_block_size * 2;
bool byte_limit_exceeded = log_state->bytesInCurrentBlock > max_block_size;
if (copyset_changed || epoch_changed || byte_limit_exceeded) {
// end of the block reached, bump block counter and save the new copyset
++log_state->currentBlockID;
log_state->bytesInCurrentBlock = 0;
std::swap(log_state->lastSeenCopyset, *temp_copyset);
}
log_state->bytesInCurrentBlock += payload.size();
return 0;
}
bool RebuildingReadStorageTaskV2::lookUpEpochMetadata(
logid_t log,
lsn_t lsn,
Context* context,
Context::LogState* log_state,
bool create_replication_scheme) {
epoch_t epoch = lsn_to_epoch(lsn);
if (epoch < log_state->currentEpochRange.first ||
epoch >= log_state->currentEpochRange.second) {
// This record is not in the same epoch range as the last one.
// Look up the new epoch range.
log_state->currentEpochMetadata =
log_state->plan.lookUpEpoch(epoch, &log_state->currentEpochRange);
log_state->currentReplication = nullptr;
}
if (log_state->currentEpochMetadata == nullptr) {
// Rebuilding is not interested in this epoch.
return false;
}
if (create_replication_scheme && log_state->currentReplication == nullptr) {
auto ucfg = getConfig();
auto cfg = ucfg->get();
auto log_group = cfg->getLogGroupByIDShared(log);
auto& rebuilding_shards = context->rebuildingSet->shards;
auto it = rebuilding_shards.find(context->myShardID);
bool relocate_local_records = it != rebuilding_shards.end() &&
it->second.mode == RebuildingMode::RELOCATE;
log_state->currentReplication = std::make_shared<ReplicationScheme>(
log,
*log_state->currentEpochMetadata,
ucfg->getNodesConfiguration(),
getMyNodeID(),
log_group ? &log_group->attrs() : nullptr,
*getSettings().get(),
relocate_local_records,
log_state->plan.sequencerNodeID);
markNodesInRebuildingSetNotAvailable(
log_state->currentReplication->nodeset_state.get(), context);
}
return true;
}
void RebuildingReadStorageTaskV2::markNodesInRebuildingSetNotAvailable(
NodeSetState* nodeset_state,
Context* context) {
for (auto it : context->rebuildingSet->shards) {
if (!nodeset_state->containsShard(it.first)) {
// This node is no longer in the config.
continue;
}
if (!it.second.dc_dirty_ranges.empty()) {
// Shard is only missing some time-ranged records. It should be
// up and able to take stores.
continue;
}
nodeset_state->setNotAvailableUntil(
it.first,
std::chrono::steady_clock::time_point::max(),
NodeSetState::NodeSetState::NotAvailableReason::STORE_DISABLED);
}
}
void RebuildingReadStorageTaskV2::onDone() {
std::shared_ptr<Context> context = context_.lock();
if (context == nullptr) {
// The ShardRebuilding was aborted. Nothing to do.
return;
}
context->onDone(std::move(result_));
}
void RebuildingReadStorageTaskV2::onDropped() {
ld_check(false);
}
void RebuildingReadStorageTaskV2::getDebugInfoDetailed(
StorageTaskDebugInfo& info) const {
std::shared_ptr<Context> context = context_.lock();
if (context == nullptr) {
info.extra_info = "ShardRebuilding went away";
return;
}
info.extra_info =
folly::sformat("{} logs, location: {}",
context->logs.size(),
context->nextLocation ? context->nextLocation->toString()
: std::string("none"));
}
UpdateableSettings<Settings> RebuildingReadStorageTaskV2::getSettings() {
return storageThreadPool_->getSettings();
}
std::shared_ptr<UpdateableConfig> RebuildingReadStorageTaskV2::getConfig() {
return storageThreadPool_->getProcessor().config_;
}
folly::Optional<NodeID> RebuildingReadStorageTaskV2::getMyNodeID() {
return storageThreadPool_->getProcessor().getOptionalMyNodeID();
}
StatsHolder* RebuildingReadStorageTaskV2::getStats() {
return storageThreadPool_->stats();
}
std::unique_ptr<LocalLogStore::AllLogsIterator>
RebuildingReadStorageTaskV2::createIterator(
const LocalLogStore::ReadOptions& opts,
const std::unordered_map<logid_t, std::pair<lsn_t, lsn_t>>& logs) {
return storageThreadPool_->getLocalLogStore().readAllLogs(opts, logs);
}
bool RebuildingReadStorageTaskV2::fetchTrimPoints(Context* context) {
LogStorageStateMap& log_state_map =
storageThreadPool_->getProcessor().getLogStorageStateMap();
for (auto& p : context->logs) {
LogStorageState* s =
log_state_map.insertOrGet(p.first, context->myShardID.shard());
ld_check(s != nullptr);
folly::Optional<lsn_t> t = s->getTrimPoint();
if (t.hasValue()) {
// Got trim point in memory.
p.second.trimPoint = t.value();
continue;
}
// Need to load trim point from rocksdb.
TrimMetadata meta{LSN_INVALID};
int rv =
storageThreadPool_->getLocalLogStore().readLogMetadata(p.first, &meta);
if (rv == 0 || err == E::NOTFOUND) {
s->updateTrimPoint(meta.trim_point_);
p.second.trimPoint = meta.trim_point_;
} else {
storageThreadPool_->getLocalLogStore().enterFailSafeMode(
"RebuildingReadStorageTaskV2::fetchTrimPoints()",
"Failed to read TrimMetadata");
s->notePermanentError(
"Reading trim point (in RebuildingReadStorageTaskV2)");
return false;
}
}
return true;
}
void RebuildingReadStorageTaskV2::updateTrimPoint(
logid_t log,
Context* context,
Context::LogState* log_state) {
LogStorageStateMap& log_state_map =
storageThreadPool_->getProcessor().getLogStorageStateMap();
LogStorageState* s = log_state_map.find(log, context->myShardID.shard());
ld_check(s != nullptr); // fetchTrimPoints() should have created it
folly::Optional<lsn_t> t = s->getTrimPoint();
ld_check(t.hasValue()); // fetchTrimPoints() should have set it
log_state->trimPoint = t.value();
}
RebuildingReadStorageTaskV2::Filter::Filter(Context* context)
: context(context) {
scd_my_shard_id_ = context->myShardID;
}
void RebuildingReadStorageTaskV2::Filter::clearStats() {
nRecordsLateFiltered = 0;
nRecordsSCDFiltered = 0;
nRecordsNotDirtyFiltered = 0;
nRecordsDrainedFiltered = 0;
nRecordsTimestampFiltered = 0;
nRecordsEpochRangeFiltered = 0;
}
bool RebuildingReadStorageTaskV2::Filter::shouldProcessTimeRange(
RecordTimestamp min,
RecordTimestamp max) {
auto& cache = timeRangeCache;
cache.clear();
if (min > max) {
// [+inf, -inf] is expected for empty partitions. Any other inverted
// ranges are not expected.
if (min != RecordTimestamp::max() || max != RecordTimestamp::min()) {
RATELIMIT_INFO(std::chrono::seconds(10),
2,
"shouldProcessTimeRange() called with min > max: %s > %s",
min.toString().c_str(),
max.toString().c_str());
}
// Be conservative.
return true;
}
if (min != RecordTimestamp::min()) {
context->progressTimestamp = min;
}
cache.minTs = min;
cache.maxTs = max;
bool have_shards_intersecting_range = false;
for (const auto& node_kv : context->rebuildingSet->shards) {
ShardID shard = node_kv.first;
auto& node_info = node_kv.second;
if (node_info.dc_dirty_ranges.empty()) {
// Empty dc_dirty_ranges means that the node is dirty for all time points.
have_shards_intersecting_range = true;
continue;
}
// Node is only partially dirty (time range data is provided).
ld_check(node_info.mode == RebuildingMode::RESTORE);
for (const auto& dc_tr_kv : node_info.dc_dirty_ranges) {
if (dc_tr_kv.second.empty()) {
ld_check(false);
continue;
}
auto& time_ranges = dc_tr_kv.second;
if (boost::icl::intersects(time_ranges, RecordTimeInterval(min, max))) {
// The shard is dirty for some of the timestamps in [min, max].
have_shards_intersecting_range = true;
} else {
// The shard is clean for all timestamps in [min, max].
cache.shardsOutsideTimeRange.emplace(shard, dc_tr_kv.first);
}
}
}
return have_shards_intersecting_range;
}
bool RebuildingReadStorageTaskV2::Filter::shouldProcessRecordRange(
logid_t log,
lsn_t min_lsn,
lsn_t max_lsn,
RecordTimestamp /* min_ts */,
RecordTimestamp /* max_ts */) {
// Note: we're not taking time ranges into account. I.e. if in some partition
// the effective rebuilding set (rebuilding set minus shardsOutsideTimeRange)
// doesn't intersect some log's nodeset, we could detect it here and skip
// this log in this partition. For simplicity we're not doing it currently.
// We're just skipping epoch ranges not covered by rebuilding plan.
if (!lookUpLogState(log)) {
return false;
}
task->updateTrimPoint(log, context, currentLogState);
if (max_lsn <= currentLogState->trimPoint ||
min_lsn > currentLogState->plan.untilLSN) {
return false;
}
// Find the epoch range covering min_lsn.
bool first_epoch_good =
task->lookUpEpochMetadata(log,
min_lsn,
context,
currentLogState,
/* create_replication_scheme */ false);
// If min_lsn is covered by rebuilding plan, process the range.
if (first_epoch_good) {
return true;
}
// If max_lsn is in the same, non-covered, epoch range as min_lsn, reject the
// lsn range.
if (lsn_to_epoch(max_lsn) < currentLogState->currentEpochRange.second) {
return false;
}
// The epoch currentEpochRange.second is covered by plan and
// intersects [min_lsn, max_lsn]. Process the lsn range.
return true;
}
bool RebuildingReadStorageTaskV2::Filter::
operator()(logid_t log,
lsn_t lsn,
const ShardID* copyset,
copyset_size_t copyset_size,
LocalLogStoreRecordFormat::csi_flags_t flags,
RecordTimestamp min_ts,
RecordTimestamp max_ts) {
required_in_copyset_.clear();
scd_known_down_.clear();
// Assume that iterator passes an exact timestamp iff it had to read the
// full record. If we end up filtering out such records a lot, that means
// there's room for improvement: we'd rather filter them out at CSI stage
// without reading the full records. So count such situations separately in
// stats.
bool late = min_ts == max_ts;
if (flags & LocalLogStoreRecordFormat::CSI_FLAG_DRAINED) {
noteRecordFiltered(FilteredReason::DRAINED, late);
return false;
}
if (!lookUpLogState(log)) {
noteRecordFiltered(FilteredReason::EPOCH_RANGE, late);
return false;
}
if (lsn <= currentLogState->trimPoint ||
lsn > currentLogState->plan.untilLSN) {
return false;
}
// Look up the EpochMetaData to find replication factor.
if (!task->lookUpEpochMetadata(log,
lsn,
context,
currentLogState,
/* create_replication_scheme */ false)) {
noteRecordFiltered(FilteredReason::EPOCH_RANGE, late);
return false;
}
// Tell base LocalLogStoreReadFilter what the "normal" replication factor is.
scd_replication_ =
currentLogState->currentEpochMetadata->replication.getReplicationFactor();
auto filtered_reason = FilteredReason::NOT_DIRTY;
// TODO(T43708398): in order to work around T43708398, we always look for
// append dirty ranges.
auto dc = DataClass::APPEND;
for (copyset_off_t i = 0; i < copyset_size; ++i) {
ShardID shard = copyset[i];
auto node_kv = context->rebuildingSet->shards.find(shard);
if (node_kv != context->rebuildingSet->shards.end()) {
auto& node_info = node_kv->second;
if (!node_info.dc_dirty_ranges.empty()) {
// Node is only partially dirty (time range data is provided).
ld_check(node_info.mode == RebuildingMode::RESTORE);
// Exclude if DataClass/Timestamp do not match.
auto dc_tr_kv = node_info.dc_dirty_ranges.find(dc);
if (dc_tr_kv == node_info.dc_dirty_ranges.end() ||
dc_tr_kv->second.empty()) {
// DataClass isn't dirty.
// We should never serialize an empty DataClass since it is
// not dirty, but we tolerate it in production builds.
ld_check(dc_tr_kv == node_info.dc_dirty_ranges.end());
continue;
}
// Check if the record's timestamp intersects some of the
// time ranges of this shard in the rebuilding set.
const auto& time_ranges = dc_tr_kv->second;
bool intersects;
if (timeRangeCache.valid(min_ts, max_ts)) {
// (a) Just like (d), but we already have a cached result for this
// time range.
intersects = !timeRangeCache.shardsOutsideTimeRange.count(
std::make_pair(shard, dc));
} else if (min_ts == max_ts) {
// (b) We know the exact timestamp of the record.
intersects = time_ranges.find(min_ts) != time_ranges.end();
} else if (min_ts > max_ts) {
// (c) Invalid range. Be paranoid and assume that it intersects the
// rebuilding range.
RATELIMIT_INFO(std::chrono::seconds(10),
2,
"operator() called with min_ts > max_ts: %s > %s",
min_ts.toString().c_str(),
max_ts.toString().c_str());
intersects = true;
} else {
// (d) We don't know the exact timestamp, but we know that it's
// somewhere in [min_ts, max_ts] range. Check if this range
// intersects any of the rebuilding time ranges for this shard.
intersects = boost::icl::intersects(
time_ranges, RecordTimeInterval(min_ts, max_ts));
// At the time of writing, this should be unreachable with all
// existing LocalLogStore::ReadIterator implementations.
// If you see this message, it's likely that there's a bug.
RATELIMIT_INFO(
std::chrono::seconds(10),
1,
"Time range in operator() (log %lu lsn %s ts [%s, %s]) doesn't "
"match time range in shouldProcessTimeRange() ([%s, %s]). "
"Suspicious. Please check the code.",
log.val(),
lsn_to_string(lsn).c_str(),
min_ts.toString().c_str(),
max_ts.toString().c_str(),
timeRangeCache.minTs.toString().c_str(),
timeRangeCache.maxTs.toString().c_str());
}
if (!intersects) {
// Record falls outside a dirty time range.
filtered_reason = FilteredReason::TIMESTAMP;
continue;
}
}
// Records inside a dirty region may be lost, but some/all may
// have been durably stored before we crashed. We only serve as a
// donor for records we happen to find in a dirty region if some
// other node's failure also impacts the record (i.e. if we get past
// this point during a different iteration of this loop).
ld_check(scd_my_shard_id_.isValid());
if (shard == scd_my_shard_id_ &&
node_kv->second.mode == RebuildingMode::RESTORE) {
continue;
}
// Node's shard either needs to be fully rebuilt or is dirty in this
// region and we can serve as a donor.
required_in_copyset_.push_back(shard);
// If the rebuilding node is rebuilding in RESTORE mode, it should not
// participate as a donor. Add it to the known down list so that other
// nodes will send the records for which it was the leader.
//
// Note: If this node is in the rebuilding set for a time-ranged
// rebuild, and that range overlaps with under-replication
// on another node, it is possible for our node id to be added
// here. However, the SCD filtering logic ignores known_down
// for the local node id and we will be considered a donor for
// the record. This can lead to overreplication, but also
// ensures that data that can be rebuilt isn't skipped.
if (node_kv->second.mode == RebuildingMode::RESTORE) {
scd_known_down_.push_back(shard);
}
}
}
// Perform SCD copyset filtering.
bool result = !required_in_copyset_.empty();
if (result) {
filtered_reason = FilteredReason::SCD;
result = LocalLogStoreReadFilter::operator()(
log, lsn, copyset, copyset_size, flags, min_ts, max_ts);
}
if (!result) {
noteRecordFiltered(filtered_reason, late);
}
return result;
}
bool RebuildingReadStorageTaskV2::Filter::lookUpLogState(logid_t log) {
if (log == currentLog) {
return currentLogState != nullptr;
}
currentLog = log;
auto it = context->logs.find(log);
if (it == context->logs.end()) {
currentLogState = nullptr;
return false;
}
currentLogState = &it->second;
return true;
}
/**
* Update stats regarding skipped records.
*/
void RebuildingReadStorageTaskV2::Filter::noteRecordFiltered(
FilteredReason reason,
bool late) {
switch (reason) {
case FilteredReason::SCD:
++nRecordsSCDFiltered;
break;
case FilteredReason::NOT_DIRTY:
++nRecordsNotDirtyFiltered;
break;
case FilteredReason::DRAINED:
++nRecordsDrainedFiltered;
break;
case FilteredReason::TIMESTAMP:
++nRecordsTimestampFiltered;
break;
case FilteredReason::EPOCH_RANGE:
++nRecordsEpochRangeFiltered;
break;
}
if (late) {
++nRecordsLateFiltered;
}
}
void RebuildingReadStorageTaskV2::Context::getLogsDebugInfo(
InfoRebuildingLogsTable& table) const {
std::lock_guard<std::mutex> lock(logsMutex);
for (const auto& p : logs) {
const LogState& s = p.second;
table.next()
.set<0>(p.first)
.set<1>(myShardID.shard())
.set<5>(s.plan.untilLSN)
.set<7>(s.lastSeenLSN)
.set<8>(s.recordsDelivered)
.set<9>(s.bytesDelivered);
}
}
}} // namespace facebook::logdevice
| 36.740657 | 80 | 0.640219 | mateuszp4925 |
d794055586616506d67f160ec44bc998aa11ba79 | 3,283 | hpp | C++ | libH/DynamicBuffer.hpp | pauljeremyturner/gizmod | 537b8c25360d907b1fde631336ccf723f38d4312 | [
"Apache-2.0"
] | null | null | null | libH/DynamicBuffer.hpp | pauljeremyturner/gizmod | 537b8c25360d907b1fde631336ccf723f38d4312 | [
"Apache-2.0"
] | null | null | null | libH/DynamicBuffer.hpp | pauljeremyturner/gizmod | 537b8c25360d907b1fde631336ccf723f38d4312 | [
"Apache-2.0"
] | null | null | null | /**
*********************************************************************
*************************************************************************
***
*** \file DynamicBuffer.hpp
*** \brief DynamicBuffer class header
***
*****************************************
*****************************************
**/
/*
Copyright (c) 2007, Tim Burrell
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 __DynamicBuffer_h
#define __DynamicBuffer_h
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <vector>
//////////////////////////////////////////////////////////////////////////////
// Namespace
///////////////////////////////////////
namespace H {
//////////////////////////////////////////////////////////////////////////////
// Typedefs, enums, etc
///////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// DynamicBuffer Class Definition
///////////////////////////////////////
/**
* \class DynamicBuffer
* \brief Implementation of a simple, highly efficient, dynamic buffer
*
* Nothing in STL can currently be used as a buffer efficiently
* This uses realloc, and memcpy to be as fast as possible
**/
template <class DataType>
class DynamicBuffer {
public:
// public functions
void addToBuffer(const DataType * AddBuf, size_t BufLen); ///< Add data to the buffer
void clear(); ///< Clear the buffer's contents
const DataType * getBuffer() const; ///< Get the buffer
size_t length() const; ///< Get the buffer length
// construction / deconstruction
DynamicBuffer(); ///< Default Constructor
virtual ~DynamicBuffer(); ///< Destructor
private:
// private member variables
size_t mLength; ///< Length of the buffer
DataType * mBuffer; ///< The buffer itself
};
//////////////////////////////////////////////////////////////////////////////
// DynamicBufferConverter Class Definition
///////////////////////////////////////
/**
* \class DynamicBufferConverter
* \brief Convert a Dynamic buffer to an array of structures or classes
**/
template <class DataType, class ConvertTo>
class DynamicBufferConverter {
public:
// public functions
static void convert(std::vector<ConvertTo> & ConvertedVector, DynamicBuffer<DataType> const & Buffer); ///< Convert Buffer to a vector objects contained in the buffer
// construction / deconstruction
DynamicBufferConverter(); ///< Default Constructor
virtual ~DynamicBufferConverter(); ///< Destructor
private:
// private member variables
};
//////////////////////////////////////////////////////////////////////////////
} // end namespace
#include "DynamicBuffer.cpp"
//////////////////////////////////////////////////////////////////////////////
#endif // __DynamicBuffer_h
| 29.576577 | 169 | 0.531221 | pauljeremyturner |
d794cbf393baa2ab9a80a630412bb6f889659d0e | 794 | cpp | C++ | C++/5328 The K Weakest Rows in a Matrix.cpp | wr786/Key-to-LeetCode | edc1c1ec5ee9c268422cd857e27e5b9fbfae6fee | [
"Apache-2.0"
] | 4 | 2020-01-12T01:20:42.000Z | 2020-10-11T07:24:31.000Z | C++/5328 The K Weakest Rows in a Matrix.cpp | wr786/Key-to-LeetCode | edc1c1ec5ee9c268422cd857e27e5b9fbfae6fee | [
"Apache-2.0"
] | null | null | null | C++/5328 The K Weakest Rows in a Matrix.cpp | wr786/Key-to-LeetCode | edc1c1ec5ee9c268422cd857e27e5b9fbfae6fee | [
"Apache-2.0"
] | 1 | 2021-09-14T14:14:55.000Z | 2021-09-14T14:14:55.000Z | class Solution {
private:
struct row{
int idx;
int cnt;
};
public:
static bool cmp(row A, row B) {
if(A.cnt != B.cnt) return A.cnt < B.cnt;
else return A.idx < B.idx;
}
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<row> matIdx;
int m = mat.size(), n = mat[0].size();
for(int i=0; i<m; i++) {
row curRow; curRow.cnt = 0; curRow.idx = i;
matIdx.push_back(curRow);
for(int j=0; j<n; j++) {
if(mat[i][j]) matIdx[i].cnt++;
else break;
}
}
sort(matIdx.begin(), matIdx.end(), cmp);
vector<int> ret;
for(int i=0; i<k; i++)
ret.push_back(matIdx[i].idx);
return ret;
}
}; | 27.37931 | 63 | 0.462217 | wr786 |
d79522152a50cc75e855e4561f8aa7bfb0178618 | 5,875 | cpp | C++ | ident.cpp | samee/oalex | cacdd0bf744f3092e721e7e0a48a4ef0d6194fe8 | [
"Apache-2.0"
] | null | null | null | ident.cpp | samee/oalex | cacdd0bf744f3092e721e7e0a48a4ef0d6194fe8 | [
"Apache-2.0"
] | null | null | null | ident.cpp | samee/oalex | cacdd0bf744f3092e721e7e0a48a4ef0d6194fe8 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020-2021 The oalex 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
https://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"ident.h"
#include<algorithm>
#include<cctype>
#include<vector>
#include "segment.h"
#include "runtime/diags.h"
#include "runtime/util.h"
using oalex::WholeSegment;
using std::all_of;
using std::string;
using std::string_view;
using std::vector;
size_t std::hash<oalex::Ident>::operator()(const oalex::Ident& ident) const {
std::string s;
for(char ch : ident.orig_) if(ch != '_') s += tolower(ch);
// Maybe memoize s as a member of Ident if this becomes a bottleneck.
return hash_helper(s);
}
namespace oalex {
bool operator==(const Ident& a, const Ident& b) {
size_t i=0, j=0;
while(i<a.orig_.size() && j<b.orig_.size()) {
char ai = a.orig_[i], bj = b.orig_[j];
if(ai == '_') { ++i; continue; }
if(bj == '_') { ++j; continue; }
if(tolower(ai) != tolower(bj)) return false;
++i; ++j;
}
return i==a.orig_.size() && j==b.orig_.size();
}
// This allows us to use std::map.
bool operator<(const Ident& a, const Ident& b) {
size_t i=0, j=0;
while(i<a.orig_.size() && j<b.orig_.size()) {
char ai = tolower(a.orig_[i]), bj = tolower(b.orig_[j]);
if(ai == '_') { ++i; continue; }
if(bj == '_') { ++j; continue; }
if(ai != bj) return ai < bj;
++i; ++j;
}
return i==a.orig_.size() && j!=b.orig_.size();
}
const size_t kMaxIdentLen = 100;
// Note: this returns false for an empty string.
static bool hasAlnum(const string& s) {
for(char ch : s) if(isalnum(ch)) return true;
return false;
}
// TODO use LocPair
Ident Ident::parseFromString(DiagsDest ctx, string s, size_t stPos) {
const size_t enPos = stPos + s.size();
if(!hasAlnum(s))
return Error(ctx, stPos, enPos, "Identifier must have a digit or letter");
if(s[0] == '_' || s.back() == '_')
return Error(ctx, stPos, enPos,
"Identifiers with leading or trailing underscores"
" are not supported for forward compatibility");
if(isdigit(s[0]))
return Error(ctx, stPos, stPos+1, "Identifiers cannot start with a digit");
for(size_t j=1; j<s.size(); ++j) if(s[j] == '_' && s[j-1] == '_')
return Error(ctx, j+stPos-1, j+stPos+1,
"Consecutive underscores are not allowed for "
"forward compatibility");
Ident rv;
rv.orig_ = std::move(s);
rv.stPos_ = stPos;
rv.enPos_ = enPos;
return rv;
}
static bool isIdentChar(char ch) { return ch=='_' || isalnum(ch); }
Ident Ident::parse(InputDiags& ctx, size_t& i) {
const Input& input = ctx.input;
size_t l;
for(l=0; input.sizeGt(i+l); ++l) {
if(l >= kMaxIdentLen) Fatal(ctx, i, i+l, "Identifier too long");
if(!isIdentChar(input[i+l])) break;
}
const Ident rv = parseFromString(ctx, input.substr(i,l), i);
if(rv) i += l;
return rv;
}
Ident Ident::parse(DiagsDest ctx, const WholeSegment& s) {
if(s->size() > kMaxIdentLen)
return Error(ctx, s.stPos, s.enPos, "Identifier too long");
for(size_t i=0; i<s->size(); ++i) if(!isIdentChar(s.data[i]))
return Error(ctx, s.stPos+i, s.stPos+i+1, "Invalid identifier character");
return parseFromString(ctx, *s, s.stPos);
}
Ident Ident::parseGenerated(string s) {
if(s.empty()) return Ident{};
InputDiags ctx{Input{s}};
size_t i = 0;
Ident rv = Ident::parse(ctx, i);
if(!ctx.diags.empty()) Bug("Couldn't parse generated ident '{}'", s);
return rv;
}
template <class Cb>
auto splitAt(string_view s, Cb isSeparator) -> vector<string> {
vector<string> rv;
size_t i=0, j;
for(j=0; j<s.size(); ++j) {
ssize_t r = isSeparator(j);
if(r < 0) continue;
rv.emplace_back(s.substr(i, j-i));
i = j+r;
if(r > 1) j += r-1; // Skip over separator.
}
rv.emplace_back(s.substr(i));
return rv;
}
static auto underscoreSplit(string_view s) {
return splitAt(s, [&](size_t i) { return ssize_t(s[i]=='_' ? 1 : -1); });
}
static auto splitLettersAndDigits(string_view s) {
return splitAt(s, [&](size_t i) {
return (i > 0 && isdigit(s[i-1]) != isdigit(s[i])) ? 0 : -1;
});
}
static bool allCaps(string_view s) {
return all_of(s.begin(), s.end(), isupper);
}
static string lower(string s) {
for(char& ch : s) ch = tolower(ch);
return s;
}
static auto splitBeforeCaps(string_view s) {
return splitAt(s, [&](size_t i) {
return (i > 0 && isupper(s[i])) ? 0 : -1;
});
}
static
auto splitWords(string_view s) -> vector<string> {
vector<string> rv;
for(const auto& word : underscoreSplit(s)) {
for(const auto& word_piece : splitLettersAndDigits(word)) {
if(allCaps(word_piece)) rv.push_back(word_piece);
else for(const auto& word_piece_2 : splitBeforeCaps(word_piece))
rv.push_back(word_piece_2);
}
}
return rv;
}
string Ident::toSnakeCase() const {
string rv;
for(auto& word : splitWords(orig_)) {
if(!rv.empty()) rv += "_";
rv += lower(word);
}
return rv;
}
string Ident::toUCamelCase() const {
string rv;
for(auto& word : splitWords(orig_)) {
word = lower(std::move(word));
if(!word.empty()) word[0] = toupper(word[0]);
rv += word;
}
return rv;
}
string Ident::toLCamelCase() const {
string rv;
for(auto& word : splitWords(orig_)) {
word = lower(std::move(word));
if(!rv.empty() && !word.empty()) word[0] = toupper(word[0]);
rv += word;
}
return rv;
}
} // namespace oalex
| 28.519417 | 79 | 0.627404 | samee |
d795d6647e1567e716f37186159709709e885437 | 4,102 | cpp | C++ | src/Nature/World.cpp | agruzdev/OgreNature | 3a9b2429255841ac64eb6286bc88b3c49b857b75 | [
"MIT"
] | null | null | null | src/Nature/World.cpp | agruzdev/OgreNature | 3a9b2429255841ac64eb6286bc88b3c49b857b75 | [
"MIT"
] | null | null | null | src/Nature/World.cpp | agruzdev/OgreNature | 3a9b2429255841ac64eb6286bc88b3c49b857b75 | [
"MIT"
] | null | null | null | /**
* @file World.cpp
*
* Copyright (c) 2015 by Gruzdev Alexey
*
* Code covered by the MIT License
* The authors make no representations about the suitability of this software
* for any purpose. It is provided "as is" without express or implied warranty.
*/
#include "World.h"
#include <OgreSceneManager.h>
#include <OgreTexture.h>
#include <OgreTextureManager.h>
#include <OgreSceneNode.h>
#include <OgreEntity.h>
#include <OgreMatrix3.h>
#include <OgreMatrix4.h>
#include "Ground.h"
#include "EternalForest.h"
#include <OgreSubEntity.h>
static Ogre::AxisAlignedBox TransformBox(const Ogre::AxisAlignedBox & box, const Ogre::Vector3 & translate, const Ogre::Vector3 & scale, const Ogre::Quaternion & rotation)
{
Ogre::Matrix4 transformMatrix;
transformMatrix.makeTransform(translate, scale, rotation);
Ogre::Vector3 min = transformMatrix.transformAffine(box.getMinimum());
Ogre::Vector3 max = transformMatrix.transformAffine(box.getMaximum());
Ogre::Real mx, my, mz, Mx, My, Mz;
std::tie(mx, Mx) = std::minmax(min[0], max[0]);
std::tie(my, My) = std::minmax(min[1], max[1]);
std::tie(mz, Mz) = std::minmax(min[2], max[2]);
return Ogre::AxisAlignedBox(mx, my, mz, Mx, My, Mz);
}
World::World(const std::string & name, Ogre::SceneManager* sceneManager):
mName(name), mSceneManager(sceneManager)
{
std::shared_ptr<Ogre::Image> heightMapImage = std::make_shared<Ogre::Image>();
heightMapImage->load("terrain.jpg", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
mGround = std::make_unique<Ground>("Ground", mSceneManager);
mGround->LoadFromHeightMap(heightMapImage, mSceneManager->getRootSceneNode());
Ogre::Vector3 groundScale = Ogre::Vector3(0.27f, 0.27f, 1.0f);
Ogre::Quaternion groundOrientation;
groundOrientation.FromAngleAxis(Ogre::Radian(Ogre::Degree(-90)), Ogre::Vector3::UNIT_X);
mGroundNode = mGround->GetNode();
mGroundNode->setScale(groundScale);
mGroundNode->setOrientation(groundOrientation);
Ogre::AxisAlignedBox bounds = mGround->GetLocalSpaceBounds();
bounds.setMinimumZ(1.0f);
bounds.setMaximumZ(2.0f);
mForest = std::make_unique<EternalForest>(mSceneManager, this, mGround.get(), TransformBox(bounds, Ogre::Vector3::ZERO, groundScale, groundOrientation));
}
//-------------------------------------------------------
World::~World()
{
//empty
}
//-------------------------------------------------------
std::tuple<bool, Ogre::Vector3, Ogre::Entity*> World::GetIntersection(const Ogre::Ray & ray) const
{
//transform world space to local space
Ogre::Matrix4 groundInvWorldMat;
groundInvWorldMat.makeInverseTransform(mGroundNode->getPosition(), mGroundNode->getScale(), mGroundNode->getOrientation());
Ogre::Matrix4 groundInvWorldMatNoTrans;
groundInvWorldMatNoTrans.makeInverseTransform(Ogre::Vector3::ZERO, mGroundNode->getScale(), mGroundNode->getOrientation());
Ogre::Ray localSpaceRay;
localSpaceRay.setOrigin(groundInvWorldMat.transformAffine(ray.getOrigin()));
localSpaceRay.setDirection(groundInvWorldMatNoTrans.transformAffine(ray.getDirection()).normalisedCopy());
auto hit = mGround->GetIntersectionLocalSpace(localSpaceRay);
if (hit.first)
{
Ogre::Matrix4 groundWorldMat;
groundWorldMat.makeTransform(mGroundNode->getPosition(), mGroundNode->getScale(), mGroundNode->getOrientation());
return std::make_tuple(true, groundWorldMat.transformAffine(hit.second), nullptr);
}
return std::make_tuple(false, Ogre::Vector3::ZERO, nullptr);
}
//-------------------------------------------------------
void World::Update(float time)
{
if (nullptr != mForest.get())
{
mForest->Update(time);
}
}
//-------------------------------------------------------
float World::GetGroundHeightAt(float x, float z) const
{
Ogre::Ray ray;
ray.setOrigin(Ogre::Vector3(x, 1000.0f, z));
ray.setDirection(Ogre::Vector3(0.0f, -1.0f, 0.0f));
auto hit = GetIntersection(ray);
return std::get<0>(hit) ? std::get<1>(hit)[1] : std::numeric_limits<float>::infinity();
} | 37.633028 | 171 | 0.678937 | agruzdev |
d796054b8782828e095321bcd41be9a8769c825f | 916 | cpp | C++ | 2nd/036_valid_sudoku.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 2nd/036_valid_sudoku.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 2nd/036_valid_sudoku.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
typedef vector<char>::size_type sz_t;
bool isValidSudoku(vector<vector<char> >& board) {
const int len = board.size();
vector<bool> tmp(len, false);
vector<vector<bool> > cols(len, tmp);
vector<vector<bool> > squares(len, tmp);
for (sz_t i = 0; i < len; ++i) {
vector<bool> row(len, false);
for (sz_t j = 0; j < len; ++j) {
char c = board[i][j];
if (c == '.')
continue;
c -= '1';
if (row[c] || cols[j][c] || squares[i/3*3+j/3][c])
return false;
row[c] = true;
cols[j][c] = true;
squares[i/3*3+j/3][c] = true;
}
}
return true;
}
};
int main(void)
{
return 0;
}
| 25.444444 | 66 | 0.437773 | buptlxb |
d7974f9b8bc4ea2a35b5fe46ce61e6768b7e1ef4 | 1,545 | cpp | C++ | RandomDistribution_Viz/source/lines.cpp | AkashBujju/Practice_Excercises | 850ad69e8f77f5e34428f7264ca94fc54605b351 | [
"MIT"
] | null | null | null | RandomDistribution_Viz/source/lines.cpp | AkashBujju/Practice_Excercises | 850ad69e8f77f5e34428f7264ca94fc54605b351 | [
"MIT"
] | null | null | null | RandomDistribution_Viz/source/lines.cpp | AkashBujju/Practice_Excercises | 850ad69e8f77f5e34428f7264ca94fc54605b351 | [
"MIT"
] | null | null | null | #include "lines.h"
#define GLM_FORCE_RADIANS
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
Lines::Lines(GLint program) {
this->program = program;
}
void Lines::add(glm::vec3 position, glm::vec3 color, float length, float angle) {
int current_index = positions.size();
float vertices[] = {
-length / 2.0f, 0, 0,
+length / 2.0f, 0, 0,
};
positions.push_back(position);
colors.push_back(color);
vaos.push_back(0);
lengths.push_back(length);
angles.push_back(angle);
glGenVertexArrays(1, &vaos[current_index]);
glGenBuffers(1, &vbo);
glBindVertexArray(vaos[current_index]);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6, vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
}
void Lines::draw() {
for(unsigned int i = 0; i < positions.size(); ++i) {
glUseProgram(program);
int position_loc = glGetUniformLocation(program, "u_pos");
glUniform3fv(position_loc, 1, glm::value_ptr(positions[i]));
int color_loc = glGetUniformLocation(program, "u_color");
glUniform3fv(color_loc, 1, glm::value_ptr(colors[i]));
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, positions[i]);
model = glm::rotate(model, glm::radians(angles[i]), glm::vec3(0, 0, 1));
int model_loc = glGetUniformLocation(program, "u_model");
glUniformMatrix4fv(model_loc, 1, GL_FALSE, glm::value_ptr(model));
glBindVertexArray(vaos[i]);
glDrawArrays(GL_LINES, 0, 2);
}
}
| 29.150943 | 81 | 0.713916 | AkashBujju |
d7995fb778b95744265d062bd09f483c53c1d7b1 | 1,055 | cpp | C++ | 数据结构/AC自动机/acwing_1285_2.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | 3 | 2020-11-16T08:58:30.000Z | 2020-11-16T08:58:33.000Z | 数据结构/AC自动机/acwing_1285_2.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | 数据结构/AC自动机/acwing_1285_2.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
using namespace std;
const int N = 1e6 + 10;
int tr[N][26], f[N];
int ne[N];
int q[N];
char str[N];
int id[210];
int n, idx;
void insert(int x) {
int p = 0;
for (int i = 0; str[i]; i++) {
int t = str[i] - 'a';
if (!tr[p][t]) tr[p][t] = ++idx;
p = tr[p][t];
f[p]++;
}
id[x] = p;
}
void build() {
int hh = 0, tt = -1;
for (int i = 0; i < 26; i++)
if (tr[0][i]) q[++tt] = tr[0][i];
while (hh <= tt) {
int t = q[hh++];
for (int i = 0; i < 26; i++) {
int c = tr[t][i];
if (!c) tr[t][i] = tr[ne[t]][i];
else {
ne[c] = tr[ne[t]][i];
q[++tt] = c;
}
}
}
}
void solve() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> str;
insert(i);
}
build();
for (int i = idx - 1; i >= 0; i --) f[ne[q[i]]] += f[q[i]];
for (int i = 0; i < n; i++) cout << f[id[i]] << endl;
}
int main() {
solve();
return 0;
} | 18.508772 | 63 | 0.363981 | tempure |
d799cae8443546a563b3de0ca369c06ae2845345 | 109 | cpp | C++ | CREP/logger.cpp | martinschonger/aerdg | d28df9fc9e2e0780f6e492e378320ed004e516ea | [
"MIT"
] | null | null | null | CREP/logger.cpp | martinschonger/aerdg | d28df9fc9e2e0780f6e492e378320ed004e516ea | [
"MIT"
] | null | null | null | CREP/logger.cpp | martinschonger/aerdg | d28df9fc9e2e0780f6e492e378320ed004e516ea | [
"MIT"
] | null | null | null | #include "logger.h"
crep::log::logger crep::log::logger_instance;
// Copyright (c) 2019 Martin Schonger | 21.8 | 46 | 0.706422 | martinschonger |
d7a2ed0f2ad4cf14b853b500b8a966e8f06b2cd8 | 4,515 | cpp | C++ | PercularityEngine/SceneWindow.cpp | DLorenzoLaguno17/provisional-engine | 95ad1eeea7298f5557a9b17479ea31b0cdfd5d49 | [
"MIT"
] | null | null | null | PercularityEngine/SceneWindow.cpp | DLorenzoLaguno17/provisional-engine | 95ad1eeea7298f5557a9b17479ea31b0cdfd5d49 | [
"MIT"
] | null | null | null | PercularityEngine/SceneWindow.cpp | DLorenzoLaguno17/provisional-engine | 95ad1eeea7298f5557a9b17479ea31b0cdfd5d49 | [
"MIT"
] | 1 | 2019-11-11T10:58:19.000Z | 2019-11-11T10:58:19.000Z | #include "Application.h"
#include "ModuleRenderer3D.h"
#include "ModuleScene.h"
#include "ModuleWindow.h"
#include "ModuleInput.h"
#include "ModuleResourceManager.h"
#include "ModuleCamera3D.h"
#include "SceneWindow.h"
#include "ComponentCamera.h"
#include "GameObject.h"
#include "mmgr/mmgr.h"
#include "ComponentTransform.h"
#include "ComponentMesh.h"
#include "ResourceMesh.h"
#include "ResourceModel.h"
#include "Tree.h"
SceneWindow::SceneWindow(char* name, bool active) : UIElement(name, active) {}
// Show scene window
void SceneWindow::Update()
{
// Imgui
ImGui::Begin("Scene", &active, ImGuiWindowFlags_NoScrollbar| ImGuiWindowFlags_NoScrollWithMouse);
windowPosition.x = ImGui::GetWindowPos().x;
windowPosition.y = ImGui::GetWindowPos().y;
windowSize.x = ImGui::GetContentRegionAvail().x;
windowSize.y = ImGui::GetContentRegionAvail().y;
ImGui::SameLine( windowSize.x/2 - 60.0f);
if (ImGui::Button("Play"))
App->scene->Play();
ImGui::SameLine();
if (ImGui::Button("Pause"))
App->scene->Pause();
ImGui::SameLine();
if (ImGui::Button("Exit Game"))
App->scene->ExitGame();
// Check if the scene window has been resized
if (windowSize.x != last_windowSize.x || windowSize.y != last_windowSize.y)
last_windowSize = windowSize;
ImGui::Image((void*)App->renderer3D->GetTexColorBuffer(), ImVec2(windowSize.x, windowSize.x/App->renderer3D->GetCamera()->GetAspectRatio()), ImVec2(0, 1), ImVec2(1, 0));
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ModelUUID"))
{
std::string model = *(std::string*)payload->Data;
std::string file = ASSETS_MODEL_FOLDER + model;
uint UUID = App->res_manager->ImportFile(file.c_str(), RESOURCE_TYPE::MODEL, true);
ResourceModel* resource = (ResourceModel*)App->res_manager->GetResourceFromMap(UUID);
if (resource) resource->GenerateModelInstance();
else LOG("ERROR: Could not find model resource %s", model);
}
ImGui::EndDragDropTarget();
}
ImGui::End();
if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_DOWN &&
(App->input->GetMouseX() > windowPosition.x && App->input->GetMouseX() < windowPosition.x + windowSize.x) &&
(App->input->GetMouseY() > windowPosition.y && App->input->GetMouseY() < windowPosition.y + windowSize.y))
{
OnClick();
}
}
void SceneWindow::OnClick()
{
//WARNING!! HARDCODE ALERT: There's a margin in both axes, between the window border and the texture (in both axis)
//and that made the ray tracing lose precision, that's why I made slight substractions in the mousePos values (-5,-30)
vec2 mousePos(float(App->input->GetMouseX() - windowPosition.x - 5), float(App->input->GetMouseY() - windowPosition.y -25- 30));
mousePos.x = -1.0 + 2.0f*(mousePos.x / windowSize.x);
mousePos.y = 1.0 - 2.0f*(mousePos.y / (windowSize.x / App->renderer3D->GetCamera()->GetAspectRatio()));
App->camera->OnClick(mousePos);
GameObject* clickedObject = SelectObject();
if (App->input->GetKey(SDL_SCANCODE_LCTRL) != KEY_REPEAT)
{
App->scene->selectedNodes.clear();
App->scene->selected = clickedObject;
}
App->scene->selectedNodes.push_back(clickedObject);
}
GameObject* SceneWindow::SelectObject() const
{
GameObject* ret = nullptr;
if (App->scene->sceneTree == nullptr) return ret;
LineSegment ray = *App->camera->GetLastRay();
std::map<float,const GameObject*> objects;
App->scene->sceneTree->CollectChilldren(ray, objects);
float nearHit, farHit;
for (int i = 0; i < App->scene->nonStaticObjects.size(); ++i)
if (App->scene->nonStaticObjects[i]->aabb.Intersects(ray, nearHit, farHit))
objects[nearHit] = App->scene->nonStaticObjects[i];
std::map<float, const GameObject*>::iterator it;
for (it = objects.begin(); it != objects.end(); ++it)
{
ComponentMesh* mesh = (ComponentMesh*)it->second->GetComponent(COMPONENT_TYPE::MESH);
if (mesh)
{
LineSegment localRay = ray;
localRay.Transform(it->second->transform->GetGlobalTransform().Inverted());
for (uint v = 0; v < mesh->resource_mesh->num_indices; v += 3)
{
uint indexA = mesh->resource_mesh->indices[v];
float3 a(mesh->resource_mesh->vertices[indexA]);
uint indexB = mesh->resource_mesh->indices[v+1];
float3 b(mesh->resource_mesh->vertices[indexB]);
uint indexC = mesh->resource_mesh->indices[v+2] ;
float3 c(mesh->resource_mesh->vertices[indexC]);
Triangle triangle(a, b, c);
if (localRay.Intersects(triangle, nullptr, nullptr))
return (GameObject*)it->second;
}
}
}
return ret;
} | 32.717391 | 170 | 0.70454 | DLorenzoLaguno17 |
d7a71b95957b8d06395211472a760c49b84b8cc3 | 5,631 | cpp | C++ | src/gpu/vk/GrVkAttachment.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | src/gpu/vk/GrVkAttachment.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | src/gpu/vk/GrVkAttachment.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/vk/GrVkAttachment.h"
#include "src/gpu/vk/GrVkGpu.h"
#include "src/gpu/vk/GrVkImage.h"
#include "src/gpu/vk/GrVkImageView.h"
#include "src/gpu/vk/GrVkUtil.h"
#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)
GrVkAttachment::GrVkAttachment(
GrVkGpu* gpu, SkISize dimensions, UsageFlags supportedUsages, const GrVkImageInfo& info,
sk_sp<GrBackendSurfaceMutableStateImpl> mutableState, sk_sp<const GrVkImageView> view,
SkBudgeted budgeted)
: GrAttachment(gpu, dimensions, supportedUsages, info.fSampleCount, info.fProtected),
GrVkImage(gpu, info, std::move(mutableState), GrBackendObjectOwnership::kOwned),
fView(std::move(view)) {
this->registerWithCache(budgeted);
}
GrVkAttachment::GrVkAttachment(
GrVkGpu* gpu, SkISize dimensions, UsageFlags supportedUsages, const GrVkImageInfo& info,
sk_sp<GrBackendSurfaceMutableStateImpl> mutableState, sk_sp<const GrVkImageView> view,
GrBackendObjectOwnership ownership, GrWrapCacheable cacheable)
: GrAttachment(gpu, dimensions, supportedUsages, info.fSampleCount, info.fProtected),
GrVkImage(gpu, info, std::move(mutableState), ownership),
fView(std::move(view)) {
this->registerWithCacheWrapped(cacheable);
}
sk_sp<GrVkAttachment> GrVkAttachment::MakeStencil(
GrVkGpu* gpu, SkISize dimensions, int sampleCnt, VkFormat format) {
VkImageUsageFlags vkUsageFlags =
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
return GrVkAttachment::Make(
gpu, dimensions, UsageFlags::kStencilAttachment, sampleCnt, format, vkUsageFlags,
GrProtected::kNo, SkBudgeted::kYes);
}
sk_sp<GrVkAttachment> GrVkAttachment::MakeMSAA(
GrVkGpu* gpu, SkISize dimensions, int numSamples, VkFormat format, GrProtected isProtected) {
SkASSERT(numSamples > 1);
VkImageUsageFlags vkUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
VK_IMAGE_USAGE_TRANSFER_DST_BIT;
return GrVkAttachment::Make(
gpu, dimensions, UsageFlags::kColorAttachment, numSamples, format, vkUsageFlags, isProtected,
SkBudgeted::kYes);
}
sk_sp<GrVkAttachment> GrVkAttachment::Make(
GrVkGpu* gpu, SkISize dimensions, UsageFlags attachmentUsages, int sampleCnt, VkFormat format,
VkImageUsageFlags vkUsageFlags, GrProtected isProtected, SkBudgeted budgeted) {
GrVkImage::ImageDesc imageDesc;
imageDesc.fImageType = VK_IMAGE_TYPE_2D;
imageDesc.fFormat = format;
imageDesc.fWidth = dimensions.width();
imageDesc.fHeight = dimensions.height();
imageDesc.fLevels = 1;
imageDesc.fSamples = sampleCnt;
imageDesc.fImageTiling = VK_IMAGE_TILING_OPTIMAL;
imageDesc.fUsageFlags = vkUsageFlags;
imageDesc.fIsProtected = isProtected;
GrVkImageInfo info;
if (!GrVkImage::InitImageInfo(gpu, imageDesc, &info)) {
return nullptr;
}
GrVkImageView::Type viewType;
if (attachmentUsages & UsageFlags::kStencilAttachment) {
// If we have stencil usage than we should have any other usages
SkASSERT(attachmentUsages == UsageFlags::kStencilAttachment);
viewType = GrVkImageView::kStencil_Type;
} else {
viewType = GrVkImageView::kColor_Type;
}
sk_sp<const GrVkImageView> imageView = GrVkImageView::Make(
gpu, info.fImage, format, viewType, info.fLevelCount, info.fYcbcrConversionInfo);
if (!imageView) {
GrVkImage::DestroyImageInfo(gpu, &info);
return nullptr;
}
sk_sp<GrBackendSurfaceMutableStateImpl> mutableState(
new GrBackendSurfaceMutableStateImpl(info.fImageLayout, info.fCurrentQueueFamily));
return sk_sp<GrVkAttachment>(new GrVkAttachment(
gpu, dimensions, attachmentUsages, info, std::move(mutableState), std::move(imageView),
budgeted));
}
sk_sp<GrAttachment> GrVkAttachment::MakeWrapped(
GrVkGpu* gpu, SkISize dimensions, const GrVkImageInfo& info,
sk_sp<GrBackendSurfaceMutableStateImpl> mutableState, UsageFlags attachmentUsages,
GrWrapOwnership ownership, GrWrapCacheable cacheable) {
GrVkImageView::Type viewType;
if (attachmentUsages & UsageFlags::kStencilAttachment) {
// If we have stencil usage than we should not have any other usages
SkASSERT(attachmentUsages == UsageFlags::kStencilAttachment);
viewType = GrVkImageView::kStencil_Type;
} else {
viewType = GrVkImageView::kColor_Type;
}
sk_sp<const GrVkImageView> imageView = GrVkImageView::Make(
gpu, info.fImage, info.fFormat, viewType, info.fLevelCount, info.fYcbcrConversionInfo);
if (!imageView) {
return nullptr;
}
GrBackendObjectOwnership backendOwnership = kBorrow_GrWrapOwnership == ownership
? GrBackendObjectOwnership::kBorrowed
: GrBackendObjectOwnership::kOwned;
return sk_sp<GrVkAttachment>(new GrVkAttachment(
gpu, dimensions, attachmentUsages, info, std::move(mutableState), std::move(imageView),
backendOwnership, cacheable));
}
GrVkAttachment::~GrVkAttachment() {
// should have been released or abandoned first
SkASSERT(!fView);
}
void GrVkAttachment::onRelease() {
this->releaseImage();
fView.reset();
GrAttachment::onRelease();
}
void GrVkAttachment::onAbandon() {
this->releaseImage();
fView.reset();
GrAttachment::onAbandon();
}
GrVkGpu* GrVkAttachment::getVkGpu() const {
SkASSERT(!this->wasDestroyed());
return static_cast<GrVkGpu*>(this->getGpu());
}
| 37.291391 | 99 | 0.736636 | NearTox |
92e1223f3817914e2fb6944af06d56106b34527d | 4,397 | cpp | C++ | Core/Contents/Source/PolyConfig.cpp | cartman300/Polycode | b6fe41c6123281db3caee3c11f655de79df6fbfb | [
"MIT"
] | 839 | 2015-01-01T10:47:04.000Z | 2022-03-29T00:16:15.000Z | Core/Contents/Source/PolyConfig.cpp | cartman300/Polycode | b6fe41c6123281db3caee3c11f655de79df6fbfb | [
"MIT"
] | 124 | 2015-01-03T22:46:04.000Z | 2020-12-23T00:33:56.000Z | Core/Contents/Source/PolyConfig.cpp | cartman300/Polycode | b6fe41c6123281db3caee3c11f655de79df6fbfb | [
"MIT"
] | 192 | 2015-01-04T17:49:07.000Z | 2022-03-13T22:42:38.000Z | /*
Copyright (C) 2011 by Ivan Safrin
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 "PolyConfig.h"
#include "tinyxml.h"
using namespace Polycode;
Config::Config() {
}
Config::~Config() {
}
void Config::loadConfig(const String& configNamespace, const String& fileName) {
TiXmlDocument doc(fileName.c_str());
Logger::log("Loading config: %s\n", fileName.c_str());
if(!doc.LoadFile()) {
Logger::log("Error loading config file...\n");
Logger::log("Error: %s\n", doc.ErrorDesc());
return;
}
TiXmlElement *rootElement = doc.RootElement();
TiXmlNode *pChild;
ConfigEntry *entry;
for(pChild = rootElement->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
TiXmlElement *pChildElement = pChild->ToElement();
if (!pChildElement) continue; // Skip comment nodes
entry = getEntry(configNamespace, pChild->Value());
entry->stringVal = pChildElement->GetText();
entry->numVal = atof(pChildElement->GetText());
entry->isString = true;
entry->configNamespace = configNamespace;
}
}
void Config::saveConfig(const String& configNamespace, const String& fileName) {
TiXmlDocument doc;
TiXmlElement* node;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild( decl );
TiXmlElement * root = new TiXmlElement( "PolyConfig" );
doc.LinkEndChild( root );
for(int i=0; i < entries.size(); i++) {
if(entries[i]->configNamespace == configNamespace) {
node = new TiXmlElement(entries[i]->key.c_str());
if(entries[i]->isString)
node->LinkEndChild( new TiXmlText(entries[i]->stringVal.c_str()));
else
node->LinkEndChild( new TiXmlText(String::NumberToString(entries[i]->numVal).c_str()));
root->LinkEndChild( node);
}
}
doc.SaveFile(fileName.c_str());
}
ConfigEntry *Config::getEntry(const String& configNamespace, const String& key) {
for(int i=0; i < entries.size(); i++) {
ConfigEntry *entry = entries[i];
if(entry->key == key && entry->configNamespace == configNamespace) {
return entry;
}
}
ConfigEntry *newEntry = new ConfigEntry();
newEntry->key = key;
newEntry->isString = false;
newEntry->numVal = 0;
newEntry->configNamespace = configNamespace;
entries.push_back(newEntry);
return newEntry;
}
void Config::setStringValue(const String& configNamespace, const String& key, const String& value) {
getEntry(configNamespace, key)->stringVal = value;
getEntry(configNamespace, key)->isString = true;
}
void Config::setNumericValue(const String& configNamespace, const String& key, Number value) {
getEntry(configNamespace, key)->numVal = value;
getEntry(configNamespace, key)->isString = false;
}
Number Config::getNumericValue(const String& configNamespace, const String& key) {
return getEntry(configNamespace, key)->numVal;
}
const String& Config::getStringValue(const String& configNamespace, const String& key) {
return getEntry(configNamespace, key)->stringVal;
}
void Config::setBoolValue(const String& configNamespace, const String& key, bool value) {
getEntry(configNamespace, key)->stringVal = (!value ? "false" : "true");
getEntry(configNamespace, key)->isString = true;
}
bool Config::getBoolValue(const String& configNamespace, const String& key) {
const String& str = getEntry(configNamespace, key)->stringVal;
if (str == "true" || str == "1") {
return true;
}
return false;
}
| 32.330882 | 100 | 0.719127 | cartman300 |
92e35d77999f0d3cba5e741bb2ce049a3c121222 | 1,253 | cpp | C++ | Cashbox/workspacewindow.cpp | NikitaSyromiatnikov/Cashbox | 6e40a33e3dfa1e4e3f0c6e75a00f118a7190184f | [
"MIT"
] | 1 | 2021-12-14T15:31:37.000Z | 2021-12-14T15:31:37.000Z | Cashbox/workspacewindow.cpp | NikitaSyromiatnikov/Cashbox | 6e40a33e3dfa1e4e3f0c6e75a00f118a7190184f | [
"MIT"
] | null | null | null | Cashbox/workspacewindow.cpp | NikitaSyromiatnikov/Cashbox | 6e40a33e3dfa1e4e3f0c6e75a00f118a7190184f | [
"MIT"
] | null | null | null | #include "workspacewindow.hpp"
#include "ui_workspacewindow.h"
#include "order.hpp"
#include <iostream>
WorkspaceWindow::WorkspaceWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::WorkspaceWindow)
{
ui->setupUi(this);
this->Storage = new SQLStorage("./dirname");
this->Storage->open();
std::vector<Order> orders = Storage->getAllOrders();
for(size_t i = 0; i < orders.size(); i++)
this->ui->listWidget->addItem(QString::fromStdString(orders[i].date));
}
WorkspaceWindow::~WorkspaceWindow()
{
delete Storage;
delete ui;
}
void WorkspaceWindow::on_AddNewPushButtom_clicked()
{
Order order;
order.cashier = "default";
order.date = Storage->currentDateTime();
order.items = ui->comboBox->itemText(1).toStdString();
order.price = 10.9;
if(this->Storage->addNewOrder(order))
{
std::vector<Order> orders = Storage->getAllOrders();
ui->listWidget->clear();
for(size_t i = 0; i < orders.size(); i++)
this->ui->listWidget->addItem(QString::fromStdString(orders[i].date));
}
}
void WorkspaceWindow::on_RemovePushButton_clicked()
{
const QString& date = ui->listWidget->currentItem()->text();
this->Storage->removeOrder(date);
}
| 25.571429 | 82 | 0.65842 | NikitaSyromiatnikov |
92e49808cd8a062db5e0b90f1cd3533e962668ab | 2,487 | cpp | C++ | print_center_fix/src/amxx_module.cpp | d3m37r4/Print-Center-Fix | f0afaf84b57f68b924c966c461311c4500ede8f8 | [
"MIT"
] | 2 | 2021-01-12T11:53:42.000Z | 2021-01-12T11:53:42.000Z | print_center_fix/src/amxx_module.cpp | d3m37r4/Print-Center-Fix | f0afaf84b57f68b924c966c461311c4500ede8f8 | [
"MIT"
] | null | null | null | print_center_fix/src/amxx_module.cpp | d3m37r4/Print-Center-Fix | f0afaf84b57f68b924c966c461311c4500ede8f8 | [
"MIT"
] | null | null | null | // ***********************************************************************
// Author : the_hunter
// Created : 04-01-2020
//
// Last Modified By : the_hunter
// Last Modified On : 04-01-2020
// ***********************************************************************
#include <print_center_fix/amxx_module.h>
#include <metamod/metamod_config.h>
#include <metamod/utils.h>
#include <print_center_fix/hook.h>
/// <summary>
/// </summary>
bool AmxxModule::init()
{
return get_module_info("amxmodx_mm");
}
/// <summary>
/// </summary>
Hook* AmxxModule::hook_client_print(const client_print_func trampoline, const bool enable) const
{
#ifdef _WIN32
const auto mask = "xxxxxx????x";
const auto pattern = "\xFF\x73\x08\xFF\x37\xE8\x00\x00\x00\x00\x83";
const auto call_opcode_address = find_pattern(pattern, mask, 0x5);
#else
const auto mask = "x????xxxxxxx";
const auto pattern = "\xE8\x00\x00\x00\x00\x8B\x44\x24\x1C\x83\xC4\x20";
const auto call_opcode_address = find_pattern(pattern, mask, 0x0);
#endif
if (!call_opcode_address) {
MetaUtils::log_console("[%s] Could not find UTIL_ClientPrint function.", META_PLUGIN_LOG_TAG);
return nullptr;
}
const auto relative_call_address = *reinterpret_cast<uintptr_t*>(call_opcode_address + 0x1);
const auto client_print_address = call_opcode_address + 0x1 + relative_call_address + sizeof(uintptr_t);
auto hook = new Hook(client_print_address, reinterpret_cast<uintptr_t>(trampoline));
if (enable) hook->enable();
return hook;
}
Hook* AmxxModule::hook_client_say_text(const client_say_text_func trampoline, const bool enable) const
{
#ifdef _WIN32
const auto mask = "xxxx????xxx";
const auto pattern = "\x56\xFF\x30\xE8\x00\x00\x00\x00\x83\xC4\x0C";
const auto call_opcode_address = find_pattern(pattern, mask, 0x3);
#else
const auto mask = "xxxxxxxxxxxxx";
const auto pattern = "\xCA\x89\x74\x24\x08\x89\x4C\x24\x04\x89\x04\x24\xE8";
const auto call_opcode_address = find_pattern(pattern, mask, 0xC);
#endif
if (!call_opcode_address) {
MetaUtils::log_console("[%s] Could not find UTIL_ClientSayText function.", META_PLUGIN_LOG_TAG);
return nullptr;
}
const auto relative_call_address = *reinterpret_cast<uintptr_t*>(call_opcode_address + 0x1);
const auto client_say_text_address = call_opcode_address + 0x1 + relative_call_address + sizeof(uintptr_t);
auto hook = new Hook(client_say_text_address, reinterpret_cast<uintptr_t>(trampoline));
if (enable) hook->enable();
return hook;
}
| 33.608108 | 108 | 0.698834 | d3m37r4 |
92e6d96a9d85fb9705951a282461c2fd5d579a21 | 2,601 | cpp | C++ | source/games/blood/src/controls.cpp | alexey-lysiuk/Raze | 690994ea1e6b105d4fc55d6b81ffda5e26e68c36 | [
"RSA-MD"
] | null | null | null | source/games/blood/src/controls.cpp | alexey-lysiuk/Raze | 690994ea1e6b105d4fc55d6b81ffda5e26e68c36 | [
"RSA-MD"
] | null | null | null | source/games/blood/src/controls.cpp | alexey-lysiuk/Raze | 690994ea1e6b105d4fc55d6b81ffda5e26e68c36 | [
"RSA-MD"
] | null | null | null | #pragma once
//-------------------------------------------------------------------------
/*
Copyright (C) 2020 Christoph Oelckers & Mitchell Richters
This file is part of Raze.
Raze is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h" // Must come before everything else!
#include "blood.h"
#include "gamestate.h"
#include "inputstate.h"
#include "gamestruct.h"
#include "razemenu.h"
BEGIN_BLD_NS
static InputPacket gInput;
void UpdatePlayerSpriteAngle(PLAYER* pPlayer);
void doslopetilting(PLAYER* pPlayer, double const scaleAdjust);
void GameInterface::GetInput(ControlInfo* const hidInput, double const scaleAdjust, InputPacket* packet)
{
if (paused || M_Active())
{
gInput = {};
return;
}
PLAYER* pPlayer = &gPlayer[myconnectindex];
InputPacket input {};
ApplyGlobalInput(gInput, hidInput);
processMovement(&input, &gInput, hidInput, scaleAdjust);
if (!SyncInput() && gamestate == GS_LEVEL)
{
// Perform unsynchronised angle/horizon if not dead.
if (gView->pXSprite->health != 0)
{
pPlayer->angle.applyinput(input.avel, &pPlayer->input.actions, scaleAdjust);
pPlayer->horizon.applyinput(input.horz, &pPlayer->input.actions, scaleAdjust);
doslopetilting(pPlayer, scaleAdjust);
}
pPlayer->angle.processhelpers(scaleAdjust);
pPlayer->horizon.processhelpers(scaleAdjust);
UpdatePlayerSpriteAngle(pPlayer);
}
if (packet)
{
*packet = gInput;
gInput = {};
}
}
//---------------------------------------------------------------------------
//
// This is called from InputState::ClearAllInput and resets all static state being used here.
//
//---------------------------------------------------------------------------
void GameInterface::clearlocalinputstate()
{
gInput = {};
}
END_BLD_NS
| 29.556818 | 104 | 0.622068 | alexey-lysiuk |
92e771760fc9390b56477a0aa7acc817b86b65b3 | 45,199 | cpp | C++ | src/backends/cl/test/ClCreateWorkloadTests.cpp | korabelnikov/armnn | 8c3259fa007d43fcc5ea56fe6928526dbe79f3c0 | [
"MIT"
] | null | null | null | src/backends/cl/test/ClCreateWorkloadTests.cpp | korabelnikov/armnn | 8c3259fa007d43fcc5ea56fe6928526dbe79f3c0 | [
"MIT"
] | null | null | null | src/backends/cl/test/ClCreateWorkloadTests.cpp | korabelnikov/armnn | 8c3259fa007d43fcc5ea56fe6928526dbe79f3c0 | [
"MIT"
] | null | null | null | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "ClContextControlFixture.hpp"
#include "ClWorkloadFactoryHelper.hpp"
#include <backendsCommon/MemCopyWorkload.hpp>
#include <aclCommon/test/CreateWorkloadClNeon.hpp>
#include <aclCommon/ArmComputeTensorUtils.hpp>
#include <cl/ClTensorHandle.hpp>
#include <cl/ClWorkloadFactory.hpp>
#include <cl/workloads/ClWorkloads.hpp>
#include <cl/workloads/ClWorkloadUtils.hpp>
boost::test_tools::predicate_result CompareIClTensorHandleShape(IClTensorHandle* tensorHandle,
std::initializer_list<unsigned int> expectedDimensions)
{
return CompareTensorHandleShape<IClTensorHandle>(tensorHandle, expectedDimensions);
}
BOOST_FIXTURE_TEST_SUITE(CreateWorkloadCl, ClContextControlFixture)
template <armnn::DataType DataType>
static void ClCreateActivationWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateActivationWorkloadTest<ClActivationWorkload, DataType>(factory, graph);
// Checks that inputs/outputs are as we expect them (see definition of CreateActivationWorkloadTest).
ActivationQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {1, 1}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {1, 1}));
}
BOOST_AUTO_TEST_CASE(CreateActivationFloatWorkload)
{
ClCreateActivationWorkloadTest<armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateActivationFloat16Workload)
{
ClCreateActivationWorkloadTest<armnn::DataType::Float16>();
}
template <typename WorkloadType,
typename DescriptorType,
typename LayerType,
armnn::DataType DataType>
static void ClCreateElementwiseWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateElementwiseWorkloadTest<WorkloadType, DescriptorType, LayerType, DataType>(factory, graph);
// Checks that inputs/outputs are as we expect them (see definition of CreateElementwiseWorkloadTest).
DescriptorType queueDescriptor = workload->GetData();
auto inputHandle1 = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto inputHandle2 = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[1]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle1, {2, 3}));
BOOST_TEST(CompareIClTensorHandleShape(inputHandle2, {2, 3}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {2, 3}));
}
BOOST_AUTO_TEST_CASE(CreateAdditionFloatWorkload)
{
ClCreateElementwiseWorkloadTest<ClAdditionWorkload,
AdditionQueueDescriptor,
AdditionLayer,
armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateAdditionFloat16Workload)
{
ClCreateElementwiseWorkloadTest<ClAdditionWorkload,
AdditionQueueDescriptor,
AdditionLayer,
armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateSubtractionFloatWorkload)
{
ClCreateElementwiseWorkloadTest<ClSubtractionWorkload,
SubtractionQueueDescriptor,
SubtractionLayer,
armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateSubtractionFloat16Workload)
{
ClCreateElementwiseWorkloadTest<ClSubtractionWorkload,
SubtractionQueueDescriptor,
SubtractionLayer,
armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateMultiplicationFloatWorkloadTest)
{
ClCreateElementwiseWorkloadTest<ClMultiplicationWorkload,
MultiplicationQueueDescriptor,
MultiplicationLayer,
armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateMultiplicationFloat16WorkloadTest)
{
ClCreateElementwiseWorkloadTest<ClMultiplicationWorkload,
MultiplicationQueueDescriptor,
MultiplicationLayer,
armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateMultiplicationUint8WorkloadTest)
{
ClCreateElementwiseWorkloadTest<ClMultiplicationWorkload,
MultiplicationQueueDescriptor,
MultiplicationLayer,
armnn::DataType::QAsymmU8>();
}
BOOST_AUTO_TEST_CASE(CreateDivisionFloatWorkloadTest)
{
ClCreateElementwiseWorkloadTest<ClDivisionFloatWorkload,
DivisionQueueDescriptor,
DivisionLayer,
armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateDivisionFloat16WorkloadTest)
{
ClCreateElementwiseWorkloadTest<ClDivisionFloatWorkload,
DivisionQueueDescriptor,
DivisionLayer,
armnn::DataType::Float16>();
}
template <typename WorkloadType,
typename DescriptorType,
armnn::DataType DataType>
static void ClCreateElementwiseUnaryWorkloadTest(armnn::UnaryOperation op)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateElementwiseUnaryWorkloadTest<WorkloadType, DescriptorType, DataType>(factory, graph, op);
DescriptorType queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {2, 3}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {2, 3}));
}
BOOST_AUTO_TEST_CASE(CreateRsqrtFloat32WorkloadTest)
{
ClCreateElementwiseUnaryWorkloadTest<ClRsqrtWorkload, RsqrtQueueDescriptor, armnn::DataType::Float32>(
UnaryOperation::Rsqrt);
}
template <typename BatchNormalizationWorkloadType, armnn::DataType DataType>
static void ClCreateBatchNormalizationWorkloadTest(DataLayout dataLayout)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateBatchNormalizationWorkloadTest<BatchNormalizationWorkloadType, DataType>
(factory, graph, dataLayout);
// Checks that inputs/outputs are as we expect them (see definition of CreateBatchNormalizationWorkloadTest).
BatchNormalizationQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
switch (dataLayout)
{
case DataLayout::NHWC:
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, { 2, 4, 4, 3 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, { 2, 4, 4, 3 }));
break;
default: // NCHW
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, { 2, 3, 4, 4 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, { 2, 3, 4, 4 }));
}
}
BOOST_AUTO_TEST_CASE(CreateBatchNormalizationFloatNchwWorkload)
{
ClCreateBatchNormalizationWorkloadTest<ClBatchNormalizationFloatWorkload,
armnn::DataType::Float32>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateBatchNormalizationFloat16NchwWorkload)
{
ClCreateBatchNormalizationWorkloadTest<ClBatchNormalizationFloatWorkload,
armnn::DataType::Float16>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateBatchNormalizationFloatNhwcWorkload)
{
ClCreateBatchNormalizationWorkloadTest<ClBatchNormalizationFloatWorkload,
armnn::DataType::Float32>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreateBatchNormalizationNhwcFloat16NhwcWorkload)
{
ClCreateBatchNormalizationWorkloadTest<ClBatchNormalizationFloatWorkload,
armnn::DataType::Float16>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreateConvertFp16ToFp32Workload)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateConvertFp16ToFp32WorkloadTest<ClConvertFp16ToFp32Workload>(factory, graph);
ConvertFp16ToFp32QueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {1, 3, 2, 3}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {1, 3, 2, 3}));
BOOST_TEST((inputHandle->GetTensor().info()->data_type() == arm_compute::DataType::F16));
BOOST_TEST((outputHandle->GetTensor().info()->data_type() == arm_compute::DataType::F32));
}
BOOST_AUTO_TEST_CASE(CreateConvertFp32ToFp16Workload)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateConvertFp32ToFp16WorkloadTest<ClConvertFp32ToFp16Workload>(factory, graph);
ConvertFp32ToFp16QueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {1, 3, 2, 3}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {1, 3, 2, 3}));
BOOST_TEST((inputHandle->GetTensor().info()->data_type() == arm_compute::DataType::F32));
BOOST_TEST((outputHandle->GetTensor().info()->data_type() == arm_compute::DataType::F16));
}
template <typename Convolution2dWorkloadType, typename armnn::DataType DataType>
static void ClConvolution2dWorkloadTest(DataLayout dataLayout)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateConvolution2dWorkloadTest<ClConvolution2dWorkload, DataType>(factory,
graph,
dataLayout);
TensorShape inputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({2, 3, 8, 16})
: std::initializer_list<unsigned int>({2, 8, 16, 3});
TensorShape outputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({2, 2, 2, 10})
: std::initializer_list<unsigned int>({2, 2, 10, 2});
// Checks that outputs and inputs are as we expect them (see definition of CreateConvolution2dWorkloadTest).
Convolution2dQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST((inputHandle->GetShape() == inputShape));
BOOST_TEST((outputHandle->GetShape() == outputShape));
}
BOOST_AUTO_TEST_CASE(CreateConvolution2dFloatNchwWorkload)
{
ClConvolution2dWorkloadTest<ClConvolution2dWorkload, armnn::DataType::Float32>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateConvolution2dFloatNhwcWorkload)
{
ClConvolution2dWorkloadTest<ClConvolution2dWorkload, armnn::DataType::Float32>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreateConvolution2dFloat16NchwWorkload)
{
ClConvolution2dWorkloadTest<ClConvolution2dWorkload, armnn::DataType::Float16>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateConvolution2dFloat16NhwcWorkload)
{
ClConvolution2dWorkloadTest<ClConvolution2dWorkload, armnn::DataType::Float16>(DataLayout::NHWC);
}
template <typename DepthwiseConvolutionWorkloadType, typename armnn::DataType DataType>
static void ClDepthwiseConvolutionWorkloadTest(DataLayout dataLayout)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateDepthwiseConvolution2dWorkloadTest<DepthwiseConvolutionWorkloadType, DataType>
(factory, graph, dataLayout);
// Checks that inputs/outputs are as we expect them (see definition of CreateDepthwiseConvolution2dWorkloadTest).
DepthwiseConvolution2dQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
TensorShape inputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({ 2, 2, 5, 5 })
: std::initializer_list<unsigned int>({ 2, 5, 5, 2 });
TensorShape outputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({ 2, 2, 5, 5 })
: std::initializer_list<unsigned int>({ 2, 5, 5, 2 });
BOOST_TEST((inputHandle->GetShape() == inputShape));
BOOST_TEST((outputHandle->GetShape() == outputShape));
}
BOOST_AUTO_TEST_CASE(CreateDepthwiseConvolutionFloat32NhwcWorkload)
{
ClDepthwiseConvolutionWorkloadTest<ClDepthwiseConvolutionWorkload, DataType::Float32>(DataLayout::NHWC);
}
template <typename Convolution2dWorkloadType, typename armnn::DataType DataType>
static void ClDirectConvolution2dWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateDirectConvolution2dWorkloadTest<ClConvolution2dWorkload, DataType>(factory, graph);
// Checks that outputs and inputs are as we expect them (see definition of CreateDirectConvolution2dWorkloadTest).
Convolution2dQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {2, 3, 6, 6}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {2, 2, 6, 6}));
}
BOOST_AUTO_TEST_CASE(CreateDirectConvolution2dFloatWorkload)
{
ClDirectConvolution2dWorkloadTest<ClConvolution2dWorkload, armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateDirectConvolution2dFloat16Workload)
{
ClDirectConvolution2dWorkloadTest<ClConvolution2dWorkload, armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateDirectConvolution2dUint8Workload)
{
ClDirectConvolution2dWorkloadTest<ClConvolution2dWorkload, armnn::DataType::QAsymmU8>();
}
template <typename FullyConnectedWorkloadType, typename armnn::DataType DataType>
static void ClCreateFullyConnectedWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload =
CreateFullyConnectedWorkloadTest<FullyConnectedWorkloadType, DataType>(factory, graph);
// Checks that outputs and inputs are as we expect them (see definition of CreateFullyConnectedWorkloadTest).
FullyConnectedQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {3, 1, 4, 5}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {3, 7}));
}
BOOST_AUTO_TEST_CASE(CreateFullyConnectedFloatWorkloadTest)
{
ClCreateFullyConnectedWorkloadTest<ClFullyConnectedWorkload, armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateFullyConnectedFloat16WorkloadTest)
{
ClCreateFullyConnectedWorkloadTest<ClFullyConnectedWorkload, armnn::DataType::Float16>();
}
template <typename NormalizationWorkloadType, typename armnn::DataType DataType>
static void ClNormalizationWorkloadTest(DataLayout dataLayout)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateNormalizationWorkloadTest<NormalizationWorkloadType, DataType>(factory, graph, dataLayout);
// Checks that inputs/outputs are as we expect them (see definition of CreateNormalizationWorkloadTest).
NormalizationQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
TensorShape inputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({3, 5, 5, 1})
: std::initializer_list<unsigned int>({3, 1, 5, 5});
TensorShape outputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({3, 5, 5, 1})
: std::initializer_list<unsigned int>({3, 1, 5, 5});
BOOST_TEST((inputHandle->GetShape() == inputShape));
BOOST_TEST((outputHandle->GetShape() == outputShape));
}
BOOST_AUTO_TEST_CASE(CreateNormalizationFloat32NchwWorkload)
{
ClNormalizationWorkloadTest<ClNormalizationFloatWorkload, armnn::DataType::Float32>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateNormalizationFloat16NchwWorkload)
{
ClNormalizationWorkloadTest<ClNormalizationFloatWorkload, armnn::DataType::Float16>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateNormalizationFloat32NhwcWorkload)
{
ClNormalizationWorkloadTest<ClNormalizationFloatWorkload, armnn::DataType::Float32>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreateNormalizationFloat16NhwcWorkload)
{
ClNormalizationWorkloadTest<ClNormalizationFloatWorkload, armnn::DataType::Float16>(DataLayout::NHWC);
}
template <typename armnn::DataType DataType>
static void ClPooling2dWorkloadTest(DataLayout dataLayout)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreatePooling2dWorkloadTest<ClPooling2dWorkload, DataType>(factory, graph, dataLayout);
TensorShape inputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({3, 2, 5, 5})
: std::initializer_list<unsigned int>({3, 5, 5, 2});
TensorShape outputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({3, 2, 2, 4})
: std::initializer_list<unsigned int>({3, 2, 4, 2});
// Check that inputs/outputs are as we expect them (see definition of CreatePooling2dWorkloadTest).
Pooling2dQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST((inputHandle->GetShape() == inputShape));
BOOST_TEST((outputHandle->GetShape() == outputShape));
}
BOOST_AUTO_TEST_CASE(CreatePooling2dFloatNchwWorkload)
{
ClPooling2dWorkloadTest<armnn::DataType::Float32>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreatePooling2dFloatNhwcWorkload)
{
ClPooling2dWorkloadTest<armnn::DataType::Float32>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreatePooling2dFloat16NchwWorkload)
{
ClPooling2dWorkloadTest<armnn::DataType::Float16>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreatePooling2dFloat16NhwcWorkload)
{
ClPooling2dWorkloadTest<armnn::DataType::Float16>(DataLayout::NHWC);
}
static void ClCreatePreluWorkloadTest(const armnn::TensorShape& inputShape,
const armnn::TensorShape& alphaShape,
const armnn::TensorShape& outputShape,
armnn::DataType dataType)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreatePreluWorkloadTest<ClPreluWorkload>(factory,
graph,
inputShape,
alphaShape,
outputShape,
dataType);
// Checks that outputs and inputs are as we expect them (see definition of CreatePreluWorkloadTest).
PreluQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto alphaHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[1]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST((inputHandle->GetShape() == inputShape));
BOOST_TEST((alphaHandle->GetShape() == alphaShape));
BOOST_TEST((outputHandle->GetShape() == outputShape));
}
BOOST_AUTO_TEST_CASE(CreatePreluFloat16Workload)
{
ClCreatePreluWorkloadTest({ 1, 4, 1, 2 }, { 5, 4, 3, 1 }, { 5, 4, 3, 2 }, DataType::Float16);
}
BOOST_AUTO_TEST_CASE(CreatePreluFloatWorkload)
{
ClCreatePreluWorkloadTest({ 1, 4, 1, 2 }, { 5, 4, 3, 1 }, { 5, 4, 3, 2 }, DataType::Float32);
}
BOOST_AUTO_TEST_CASE(CreatePreluUint8Workload)
{
ClCreatePreluWorkloadTest({ 1, 4, 1, 2 }, { 5, 4, 3, 1 }, { 5, 4, 3, 2 }, DataType::QAsymmU8);
}
template <typename armnn::DataType DataType>
static void ClCreateReshapeWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateReshapeWorkloadTest<ClReshapeWorkload, DataType>(factory, graph);
// Checks that outputs and inputs are as we expect them (see definition of CreateReshapeWorkloadTest).
ReshapeQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {4, 1}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {1, 4}));
}
BOOST_AUTO_TEST_CASE(CreateReshapeFloatWorkload)
{
ClCreateReshapeWorkloadTest<armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateReshapeFloat16Workload)
{
ClCreateReshapeWorkloadTest<armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateReshapeUint8Workload)
{
ClCreateReshapeWorkloadTest<armnn::DataType::QAsymmU8>();
}
template <typename SoftmaxWorkloadType, typename armnn::DataType DataType>
static void ClSoftmaxWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateSoftmaxWorkloadTest<SoftmaxWorkloadType, DataType>(factory, graph);
// Checks that inputs/outputs are as we expect them (see definition of ClSoftmaxFloatWorkload).
SoftmaxQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {4, 1}));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, {4, 1}));
}
BOOST_AUTO_TEST_CASE(CreateSoftmaxFloatWorkloadTest)
{
ClSoftmaxWorkloadTest<ClSoftmaxFloatWorkload, armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateSoftmaxFloat16WorkloadTest)
{
ClSoftmaxWorkloadTest<ClSoftmaxFloatWorkload, armnn::DataType::Float16>();
}
template <typename armnn::DataType DataType>
static void ClSplitterWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateSplitterWorkloadTest<ClSplitterWorkload, DataType>(factory, graph);
// Checks that outputs are as we expect them (see definition of CreateSplitterWorkloadTest).
SplitterQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, {5, 7, 7}));
auto outputHandle1 = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[1]);
BOOST_TEST(CompareIClTensorHandleShape(outputHandle1, {2, 7, 7}));
auto outputHandle2 = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[2]);
BOOST_TEST(CompareIClTensorHandleShape(outputHandle2, {2, 7, 7}));
auto outputHandle0 = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(outputHandle0, {1, 7, 7}));
}
BOOST_AUTO_TEST_CASE(CreateSplitterFloatWorkload)
{
ClSplitterWorkloadTest<armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateSplitterFloat16Workload)
{
ClSplitterWorkloadTest<armnn::DataType::Float16>();
}
template <typename armnn::DataType DataType>
static void ClSplitterConcatTest()
{
// Tests that it is possible to decide which output of the splitter layer
// should be lined to which input of the concat layer.
// We test that is is possible to specify 0th output
// of the splitter to be the 1st input to the concat and the 1st output of the splitter to be 0th input
// of the concat.
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workloads =
CreateSplitterConcatWorkloadTest<ClSplitterWorkload, ClConcatWorkload, DataType>
(factory, graph);
auto wlSplitter = std::move(workloads.first);
auto wlConcat = std::move(workloads.second);
//Checks that the index of inputs/outputs matches what we declared on InputDescriptor construction.
armnn::ClSubTensorHandle* sOut0 = dynamic_cast<armnn::ClSubTensorHandle*>(wlSplitter->GetData().m_Outputs[0]);
armnn::ClSubTensorHandle* sOut1 = dynamic_cast<armnn::ClSubTensorHandle*>(wlSplitter->GetData().m_Outputs[1]);
armnn::ClSubTensorHandle* mIn0 = dynamic_cast<armnn::ClSubTensorHandle*>(wlConcat->GetData().m_Inputs[0]);
armnn::ClSubTensorHandle* mIn1 = dynamic_cast<armnn::ClSubTensorHandle*>(wlConcat->GetData().m_Inputs[1]);
BOOST_TEST(sOut0);
BOOST_TEST(sOut1);
BOOST_TEST(mIn0);
BOOST_TEST(mIn1);
//Fliped order of inputs/outputs.
bool validDataPointers = (sOut0 == mIn1) && (sOut1 == mIn0);
BOOST_TEST(validDataPointers);
//Also make sure that the inputs are subtensors of one tensor and outputs are sub tensors of another tensor.
bool validSubTensorParents = (mIn0->GetTensor().parent() == mIn1->GetTensor().parent())
&& (sOut0->GetTensor().parent() == sOut1->GetTensor().parent());
BOOST_TEST(validSubTensorParents);
}
BOOST_AUTO_TEST_CASE(CreateSplitterConcatFloatWorkload)
{
ClSplitterConcatTest<armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateSplitterConcatFloat16Workload)
{
ClSplitterConcatTest<armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateSingleOutputMultipleInputs)
{
// Test that it is possible to assign multiple (two) different layers to each of the outputs of a splitter layer.
// We create a splitter with two outputs. That each of those outputs is used by two different activation layers.
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
std::unique_ptr<ClSplitterWorkload> wlSplitter;
std::unique_ptr<ClActivationWorkload> wlActiv0_0;
std::unique_ptr<ClActivationWorkload> wlActiv0_1;
std::unique_ptr<ClActivationWorkload> wlActiv1_0;
std::unique_ptr<ClActivationWorkload> wlActiv1_1;
CreateSplitterMultipleInputsOneOutputWorkloadTest<ClSplitterWorkload,
ClActivationWorkload, armnn::DataType::Float32>(factory, graph, wlSplitter, wlActiv0_0, wlActiv0_1,
wlActiv1_0, wlActiv1_1);
//Checks that the index of inputs/outputs matches what we declared on InputDescriptor construction.
armnn::ClSubTensorHandle* sOut0 = dynamic_cast<armnn::ClSubTensorHandle*>(wlSplitter->GetData().m_Outputs[0]);
armnn::ClSubTensorHandle* sOut1 = dynamic_cast<armnn::ClSubTensorHandle*>(wlSplitter->GetData().m_Outputs[1]);
armnn::ClSubTensorHandle* activ0_0Im = dynamic_cast<armnn::ClSubTensorHandle*>(wlActiv0_0->GetData().m_Inputs[0]);
armnn::ClSubTensorHandle* activ0_1Im = dynamic_cast<armnn::ClSubTensorHandle*>(wlActiv0_1->GetData().m_Inputs[0]);
armnn::ClSubTensorHandle* activ1_0Im = dynamic_cast<armnn::ClSubTensorHandle*>(wlActiv1_0->GetData().m_Inputs[0]);
armnn::ClSubTensorHandle* activ1_1Im = dynamic_cast<armnn::ClSubTensorHandle*>(wlActiv1_1->GetData().m_Inputs[0]);
BOOST_TEST(sOut0);
BOOST_TEST(sOut1);
BOOST_TEST(activ0_0Im);
BOOST_TEST(activ0_1Im);
BOOST_TEST(activ1_0Im);
BOOST_TEST(activ1_1Im);
bool validDataPointers = (sOut0 == activ0_0Im) && (sOut0 == activ0_1Im) &&
(sOut1 == activ1_0Im) && (sOut1 == activ1_1Im);
BOOST_TEST(validDataPointers);
}
#if defined(ARMNNREF_ENABLED)
// This test unit needs the reference backend, it's not available if the reference backend is not built
BOOST_AUTO_TEST_CASE(CreateMemCopyWorkloadsCl)
{
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
CreateMemCopyWorkloads<IClTensorHandle>(factory);
}
#endif
template <typename L2NormalizationWorkloadType, typename armnn::DataType DataType>
static void ClL2NormalizationWorkloadTest(DataLayout dataLayout)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload =
CreateL2NormalizationWorkloadTest<L2NormalizationWorkloadType, DataType>(factory, graph, dataLayout);
// Checks that inputs/outputs are as we expect them (see definition of CreateNormalizationWorkloadTest).
L2NormalizationQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
TensorShape inputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({ 5, 20, 50, 67 })
: std::initializer_list<unsigned int>({ 5, 50, 67, 20 });
TensorShape outputShape = (dataLayout == DataLayout::NCHW) ? std::initializer_list<unsigned int>({ 5, 20, 50, 67 })
: std::initializer_list<unsigned int>({ 5, 50, 67, 20 });
BOOST_TEST((inputHandle->GetShape() == inputShape));
BOOST_TEST((outputHandle->GetShape() == outputShape));
}
BOOST_AUTO_TEST_CASE(CreateL2NormalizationFloatNchwWorkload)
{
ClL2NormalizationWorkloadTest<ClL2NormalizationFloatWorkload, armnn::DataType::Float32>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateL2NormalizationFloatNhwcWorkload)
{
ClL2NormalizationWorkloadTest<ClL2NormalizationFloatWorkload, armnn::DataType::Float32>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreateL2NormalizationFloat16NchwWorkload)
{
ClL2NormalizationWorkloadTest<ClL2NormalizationFloatWorkload, armnn::DataType::Float16>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateL2NormalizationFloat16NhwcWorkload)
{
ClL2NormalizationWorkloadTest<ClL2NormalizationFloatWorkload, armnn::DataType::Float16>(DataLayout::NHWC);
}
template <typename LstmWorkloadType>
static void ClCreateLstmWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateLstmWorkloadTest<LstmWorkloadType>(factory, graph);
LstmQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[1]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, { 2, 2 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, { 2, 4 }));
}
BOOST_AUTO_TEST_CASE(CreateLSTMWorkloadFloatWorkload)
{
ClCreateLstmWorkloadTest<ClLstmFloatWorkload>();
}
template <typename ResizeWorkloadType, typename armnn::DataType DataType>
static void ClResizeWorkloadTest(DataLayout dataLayout)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateResizeBilinearWorkloadTest<ResizeWorkloadType, DataType>(factory, graph, dataLayout);
auto queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
switch (dataLayout)
{
case DataLayout::NHWC:
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, { 2, 4, 4, 3 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, { 2, 2, 2, 3 }));
break;
case DataLayout::NCHW:
default:
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, { 2, 3, 4, 4 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, { 2, 3, 2, 2 }));
}
}
BOOST_AUTO_TEST_CASE(CreateResizeFloat32NchwWorkload)
{
ClResizeWorkloadTest<ClResizeWorkload, armnn::DataType::Float32>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateResizeFloat16NchwWorkload)
{
ClResizeWorkloadTest<ClResizeWorkload, armnn::DataType::Float16>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateResizeUint8NchwWorkload)
{
ClResizeWorkloadTest<ClResizeWorkload, armnn::DataType::QAsymmU8>(DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(CreateResizeFloat32NhwcWorkload)
{
ClResizeWorkloadTest<ClResizeWorkload, armnn::DataType::Float32>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreateResizeFloat16NhwcWorkload)
{
ClResizeWorkloadTest<ClResizeWorkload, armnn::DataType::Float16>(DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(CreateResizeUint8NhwcWorkload)
{
ClResizeWorkloadTest<ClResizeWorkload, armnn::DataType::QAsymmU8>(DataLayout::NHWC);
}
template <typename MeanWorkloadType, typename armnn::DataType DataType>
static void ClMeanWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateMeanWorkloadTest<MeanWorkloadType, DataType>(factory, graph);
// Checks that inputs/outputs are as we expect them (see definition of CreateMeanWorkloadTest).
MeanQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
// The first dimension (batch size) in both input and output is singular thus it has been reduced by ACL.
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, { 1, 3, 7, 4 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, { 1, 4 }));
}
BOOST_AUTO_TEST_CASE(CreateMeanFloat32Workload)
{
ClMeanWorkloadTest<ClMeanWorkload, armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateMeanFloat16Workload)
{
ClMeanWorkloadTest<ClMeanWorkload, armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateMeanUint8Workload)
{
ClMeanWorkloadTest<ClMeanWorkload, armnn::DataType::QAsymmU8>();
}
template <typename ConcatWorkloadType, armnn::DataType DataType>
static void ClCreateConcatWorkloadTest(std::initializer_list<unsigned int> outputShape,
unsigned int concatAxis)
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateConcatWorkloadTest<ConcatWorkloadType, DataType>(factory, graph, outputShape, concatAxis);
ConcatQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle0 = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto inputHandle1 = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[1]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle0, { 2, 3, 2, 5 }));
BOOST_TEST(CompareIClTensorHandleShape(inputHandle1, { 2, 3, 2, 5 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, outputShape));
}
BOOST_AUTO_TEST_CASE(CreateConcatDim0Float32Workload)
{
ClCreateConcatWorkloadTest<ClConcatWorkload, armnn::DataType::Float32>({ 4, 3, 2, 5 }, 0);
}
BOOST_AUTO_TEST_CASE(CreateConcatDim1Float32Workload)
{
ClCreateConcatWorkloadTest<ClConcatWorkload, armnn::DataType::Float32>({ 2, 6, 2, 5 }, 1);
}
BOOST_AUTO_TEST_CASE(CreateConcatDim3Float32Workload)
{
ClCreateConcatWorkloadTest<ClConcatWorkload, armnn::DataType::Float32>({ 2, 3, 2, 10 }, 3);
}
BOOST_AUTO_TEST_CASE(CreateConcatDim0Uint8Workload)
{
ClCreateConcatWorkloadTest<ClConcatWorkload, armnn::DataType::QAsymmU8>({ 4, 3, 2, 5 }, 0);
}
BOOST_AUTO_TEST_CASE(CreateConcatDim1Uint8Workload)
{
ClCreateConcatWorkloadTest<ClConcatWorkload, armnn::DataType::QAsymmU8>({ 2, 6, 2, 5 }, 1);
}
BOOST_AUTO_TEST_CASE(CreateConcatDim3Uint8Workload)
{
ClCreateConcatWorkloadTest<ClConcatWorkload, armnn::DataType::QAsymmU8>({ 2, 3, 2, 10 }, 3);
}
template <typename SpaceToDepthWorkloadType, typename armnn::DataType DataType>
static void ClSpaceToDepthWorkloadTest()
{
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateSpaceToDepthWorkloadTest<SpaceToDepthWorkloadType, DataType>(factory, graph);
SpaceToDepthQueueDescriptor queueDescriptor = workload->GetData();
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[0]);
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, { 1, 2, 2, 1 }));
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, { 1, 1, 1, 4 }));
}
BOOST_AUTO_TEST_CASE(CreateSpaceToDepthFloat32Workload)
{
ClSpaceToDepthWorkloadTest<ClSpaceToDepthWorkload, armnn::DataType::Float32>();
}
BOOST_AUTO_TEST_CASE(CreateSpaceToDepthFloat16Workload)
{
ClSpaceToDepthWorkloadTest<ClSpaceToDepthWorkload, armnn::DataType::Float16>();
}
BOOST_AUTO_TEST_CASE(CreateSpaceToDepthQAsymm8Workload)
{
ClSpaceToDepthWorkloadTest<ClSpaceToDepthWorkload, armnn::DataType::QAsymmU8>();
}
BOOST_AUTO_TEST_CASE(CreateSpaceToDepthQSymm16Workload)
{
ClSpaceToDepthWorkloadTest<ClSpaceToDepthWorkload, armnn::DataType::QSymmS16>();
}
template <armnn::DataType DataType>
static void ClCreateStackWorkloadTest(const std::initializer_list<unsigned int>& inputShape,
const std::initializer_list<unsigned int>& outputShape,
unsigned int axis,
unsigned int numInputs)
{
armnn::Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateStackWorkloadTest<ClStackWorkload, DataType>(factory,
graph,
TensorShape(inputShape),
TensorShape(outputShape),
axis,
numInputs);
// Check inputs and output are as expected
StackQueueDescriptor queueDescriptor = workload->GetData();
for (unsigned int i = 0; i < numInputs; ++i)
{
auto inputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Inputs[i]);
BOOST_TEST(CompareIClTensorHandleShape(inputHandle, inputShape));
}
auto outputHandle = boost::polymorphic_downcast<IClTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST(CompareIClTensorHandleShape(outputHandle, outputShape));
}
BOOST_AUTO_TEST_CASE(CreateStackFloat32Workload)
{
ClCreateStackWorkloadTest<armnn::DataType::Float32>({ 3, 4, 5 }, { 3, 4, 2, 5 }, 2, 2);
}
BOOST_AUTO_TEST_CASE(CreateStackFloat16Workload)
{
ClCreateStackWorkloadTest<armnn::DataType::Float16>({ 3, 4, 5 }, { 3, 4, 2, 5 }, 2, 2);
}
BOOST_AUTO_TEST_CASE(CreateStackUint8Workload)
{
ClCreateStackWorkloadTest<armnn::DataType::QAsymmU8>({ 3, 4, 5 }, { 3, 4, 2, 5 }, 2, 2);
}
template <typename QuantizedLstmWorkloadType>
static void ClCreateQuantizedLstmWorkloadTest()
{
using namespace armnn::armcomputetensorutils;
using boost::polymorphic_downcast;
Graph graph;
ClWorkloadFactory factory =
ClWorkloadFactoryHelper::GetFactory(ClWorkloadFactoryHelper::GetMemoryManager());
auto workload = CreateQuantizedLstmWorkloadTest<QuantizedLstmWorkloadType>(factory, graph);
QuantizedLstmQueueDescriptor queueDescriptor = workload->GetData();
IAclTensorHandle* inputHandle = polymorphic_downcast<IAclTensorHandle*>(queueDescriptor.m_Inputs[0]);
BOOST_TEST((inputHandle->GetShape() == TensorShape({2, 2})));
BOOST_TEST((inputHandle->GetDataType() == arm_compute::DataType::QASYMM8));
IAclTensorHandle* cellStateInHandle = polymorphic_downcast<IAclTensorHandle*>(queueDescriptor.m_Inputs[1]);
BOOST_TEST((cellStateInHandle->GetShape() == TensorShape({2, 4})));
BOOST_TEST((cellStateInHandle->GetDataType() == arm_compute::DataType::QSYMM16));
IAclTensorHandle* outputStateInHandle = polymorphic_downcast<IAclTensorHandle*>(queueDescriptor.m_Inputs[2]);
BOOST_TEST((outputStateInHandle->GetShape() == TensorShape({2, 4})));
BOOST_TEST((outputStateInHandle->GetDataType() == arm_compute::DataType::QASYMM8));
IAclTensorHandle* cellStateOutHandle = polymorphic_downcast<IAclTensorHandle*>(queueDescriptor.m_Outputs[0]);
BOOST_TEST((cellStateOutHandle->GetShape() == TensorShape({2, 4})));
BOOST_TEST((cellStateOutHandle->GetDataType() == arm_compute::DataType::QSYMM16));
IAclTensorHandle* outputStateOutHandle = polymorphic_downcast<IAclTensorHandle*>(queueDescriptor.m_Outputs[1]);
BOOST_TEST((outputStateOutHandle->GetShape() == TensorShape({2, 4})));
BOOST_TEST((outputStateOutHandle->GetDataType() == arm_compute::DataType::QASYMM8));
}
BOOST_AUTO_TEST_CASE(CreateQuantizedLstmWorkload)
{
ClCreateQuantizedLstmWorkloadTest<ClQuantizedLstmWorkload>();
}
BOOST_AUTO_TEST_SUITE_END()
| 42.802083 | 120 | 0.725613 | korabelnikov |
92e95f025b5887936a67bf9913ed6a443e047415 | 6,588 | cpp | C++ | hackerearth/circ_jan_19/x.cpp | tuket/challenges | 456979020c78dfcae2f8681245000bb64a6aaf38 | [
"Unlicense"
] | null | null | null | hackerearth/circ_jan_19/x.cpp | tuket/challenges | 456979020c78dfcae2f8681245000bb64a6aaf38 | [
"Unlicense"
] | null | null | null | hackerearth/circ_jan_19/x.cpp | tuket/challenges | 456979020c78dfcae2f8681245000bb64a6aaf38 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
#include <array>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <algorithm>
using namespace std;
int N;
int canAdd, canRemove;
vector<string> G;
vector<array<float, 4>> P;
unordered_set<size_t> sols;
default_random_engine randEng;
uniform_int_distribution<int> randDist;
int randMutation()
{
return randDist(randEng);
}
struct Pos
{
char x, y;
bool operator==(const Pos& o)const
{
return x == o.x && y == o.y;
}
bool isValid()const
{
return x >= 0 && y >= 0 && x < N && y < N;
}
};
struct Sol;
namespace std
{
template <>
struct hash<Pos>
{
size_t operator()(const Pos& p)const
{
size_t x = p.x;
size_t y = p.y;
return x + N * y;
}
};
}
vector<Pos> empties;
vector<Pos> fulls;
vector<Pos> starts;
vector<Pos> endings;
int NEF;
struct Table
{
Table() {}
Table(int C, int N)
: C(C)
, N(N)
{
v.resize(C*N*N);
}
float& operator()(int c, int x, int y)
{
return v[x + N*(y + N*c)];
}
void reset()
{
fill(v.begin(), v.end(), 0.f);
float prob = 1.f / starts.size();
for(const Pos& p : starts)
{
operator()(0, p.x, p.y) = prob;
}
}
void compC(const Sol& sol, int c);
float eval(const Sol& sol)
{
reset();
for(int c=1; c<C; c++)
compC(sol, c);
float res = 0;
for(const Pos& p : endings)
res += operator()(C-1, p.x, p.y);
return res;
}
int C, N;
vector<float> v;
};
Table MP;
struct Sol
{
vector<Pos> toAdd;
vector<Pos> toRemove;
void mutate()
{
int mut = randMutation();
if(mut < empties.size())
{
const Pos& p = empties[mut];
auto it = find(toAdd.begin(), toAdd.end(), p);
if(it == toAdd.end())
if(toAdd.size() < canAdd)
toAdd.push_back(p);
else
toAdd.pop_back();
else
toAdd.erase(it);
}
else
{
mut -= empties.size();
const Pos& p = fulls[mut];
auto it = find(toRemove.begin(), toRemove.end(), p);
if(it == toRemove.end())
if(toRemove.size() < canRemove)
toRemove.push_back(p);
else
toRemove.pop_back();
else
toRemove.erase(it);
}
}
vector<string> G;
float evaluate()
{
this->G = ::G;
for(const Pos& p : toAdd)
this->G[p.y][p.x] = 'X';
for(const Pos& p : toRemove)
this->G[p.y][p.x] = '.';
float val = MP.eval(*this);
return val;
}
bool isValid(int x, int y)const
{
return //x >= 0 && y >= 0 && x <= N && y <= N &&
G[y][x] != 'X';
}
bool isFinal(int x, int y)const
{
return G[y][x] == 'B';
}
vector<string> getResult()const
{
return this->G;
}
};
void Table::compC(const Sol& sol, int c)
{
float probRight = P[c-1][0];
float probUp = P[c-1][1];
float probLeft = P[c-1][2];
float probDown = P[c-1][3];
for(int y=0; y<N; y++)
for(int x=0; x<N; x++)
{
float prob = operator()(c-1, x, y);
if(prob == 0)
continue;
if(sol.isFinal(x, y))
{
operator()(c, x, y) += prob;
continue;
}
// right
if(x != N-1 && sol.isValid(x+1, y))
operator()(c, x+1, y) += prob * probRight;
else
operator()(c, x, y) += prob * probRight;
// up
if(y != 0 && sol.isValid(x, y-1))
operator()(c, x, y-1) += prob * probUp;
else
operator()(c, x, y) += prob * probUp;
// left
if(x != 0 && sol.isValid(x-1, y))
operator()(c, x-1, y) += prob * probLeft;
else
operator()(c, x, y) += prob * probLeft;
// down
if(y != N-1 && sol.isValid(x, y+1))
operator()(c, x, y+1) += prob * probDown;
else
operator()(c, x, y) += prob * probDown;
}
}
namespace std
{
template <>
struct hash<Sol>
{
size_t operator()(const Sol& o)const
{
std::size_t seed = 423423;
for(const Pos& x : o.toAdd)
{
size_t a = hash<Pos>()(x);
seed ^= a + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
for(const Pos& x : o.toRemove)
{
size_t a = hash<Pos>()(x);
seed ^= a + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
}
Sol bestSol;
float bestVal;
int main()
{
cin >> N;
cin >> canAdd >> canRemove;
string s;
getline(cin, s);
G.resize(N);
for(int i=0; i<N; i++)
{
getline(cin, G[i]);
}
array<float, 4> p;
while(cin >> p[0])
{
cin >> p[1] >> p[2] >> p[3];
P.push_back(p);
}
int cLim = ((60-N)*(60-N)*2000) / (50*50);
int C = min(cLim, (int)P.size());
int STEPS = 450000 / C;
MP = Table(C, N);
for(char y=0; y<N; y++)
for(char x=0; x<N; x++)
{
char c = G[y][x];
Pos p {x, y};
if(c == '.')
empties.push_back(p);
else if(c == 'X')
fulls.push_back(p);
else if(c == 'A')
starts.push_back(p);
else if(c == 'B')
endings.push_back(p);
}
NEF = empties.size() + fulls.size();
randEng.seed(536553);
randDist = uniform_int_distribution<int>(0, NEF-1);
bestVal = bestSol.evaluate();
sols.insert(hash<Sol>()(bestSol));
Sol sol = bestSol;
for(int i=0; i<STEPS; i++)
{
sol.mutate();
size_t solHash = hash<Sol>()(sol);
float val = sol.evaluate();
if(val > bestVal)
{
bestSol = sol;
bestVal = val;
}
sols.insert(solHash);
/*
cerr << i << endl;
cerr << "toAdd: ";
for(const Pos& p : sol.toAdd)
cerr << "(" << (int)p.x << ", " << (int)p.y << ") ";
cerr << endl << "toEnd: ";
for(const Pos& p : sol.toRemove)
cerr << "(" << (int)p.x << ", " << (int)p.y << ") ";
cerr << endl;
cerr << "val: " << val << "/" << bestVal << endl;*/
}
auto solG = bestSol.getResult();
for(int i=0; i<N; i++)
{
cout << solG[i] << endl;
}
} | 21.320388 | 64 | 0.442319 | tuket |
92eb192df0aff204185f971a82458852fd7cb357 | 1,022 | cpp | C++ | MainMenu.cpp | matheusvms/pongcpp | b0d1f399e9e7658e78d11ca7d89a5ac1b98c3a16 | [
"MIT"
] | null | null | null | MainMenu.cpp | matheusvms/pongcpp | b0d1f399e9e7658e78d11ca7d89a5ac1b98c3a16 | [
"MIT"
] | null | null | null | MainMenu.cpp | matheusvms/pongcpp | b0d1f399e9e7658e78d11ca7d89a5ac1b98c3a16 | [
"MIT"
] | null | null | null | //
// Created by sofia on 06/12/2020.
//
#include "stdafx.h"
#include "MainMenu.h"
MainMenu::MenuResult MainMenu::Show(sf::RenderWindow& window)
{
//Load menu image from file
sf::Texture texture;
texture.loadFromFile("mainmenu.png");
sf::Sprite sprite(texture);
//Setup clickable regions
//Play menu item coordinates
window.draw(sprite);
window.display();
return GetMenuResponse(window);
}
MainMenu::MenuResult MainMenu::GetMenuResponse(sf::RenderWindow& window)
{
sf::Event menuEvent;
while(true)
{
while(window.pollEvent(menuEvent))
{
if (menuEvent.type == sf::Event::KeyPressed) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
return Play;
}
}
if (menuEvent.type == sf::Event::KeyPressed) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
return Exit;
}
}
}
}
}
| 20.857143 | 73 | 0.55773 | matheusvms |
92ebc98550df801b4d4d1d7d600c5c880b8d6560 | 2,865 | cpp | C++ | src/shape_drawer.cpp | THE-FYP/MoonAdditions | 659eb22d2217fd5870e8e1ead797a2175d314337 | [
"MIT"
] | 10 | 2017-08-11T08:51:05.000Z | 2022-03-22T10:21:38.000Z | src/shape_drawer.cpp | THE-FYP/MoonAdditions | 659eb22d2217fd5870e8e1ead797a2175d314337 | [
"MIT"
] | 1 | 2020-06-14T16:08:50.000Z | 2020-06-14T16:08:50.000Z | src/shape_drawer.cpp | THE-FYP/MoonAdditions | 659eb22d2217fd5870e8e1ead797a2175d314337 | [
"MIT"
] | 7 | 2017-09-22T17:20:02.000Z | 2020-07-26T17:47:10.000Z | // MIT License
// Copyright (c) 2012 DK22Pac
// Copyright (c) 2017 FYP
// 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 "pch.h"
#include "shape_drawer.h"
#include "lua_texture.h"
#include "lua_shape.h"
void Shape::draw() const
{
auto shape = _shape.lock();
if (shape)
{
auto tex = _texture.lock();
RwEngineInstance->dOpenDevice.fpRenderStateSet(rwRENDERSTATETEXTURERASTER, tex ? tex->getRwTexture()->raster : nullptr);
RwEngineInstance->dOpenDevice.fpRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)_enableAlpha);
RwEngineInstance->dOpenDevice.fpRenderStateSet(rwRENDERSTATESRCBLEND, (void*)_srcBlend);
RwEngineInstance->dOpenDevice.fpRenderStateSet(rwRENDERSTATEDESTBLEND, (void*)_dstBlend);
auto vertices = const_cast<RwIm2DVertex*>(static_cast<const RwIm2DVertex*>(shape->getVertices().data()));
RwEngineInstance->dOpenDevice.fpIm2DRenderPrimitive(_primType, vertices, shape->getVertices().size());
}
}
void ShapeDrawer::drawShapes()
{
if (!_drawingQueue.empty())
{
RenderStateData data;
storeRenderStates(data);
Drawer<Shape>::draw();
restoreRenderStates(data);
}
}
void ShapeDrawer::storeRenderStates(RenderStateData& rsData) const
{
auto rsGet = RwEngineInstance->dOpenDevice.fpRenderStateGet;
rsGet(rwRENDERSTATETEXTURERASTER, &rsData._TEXTURERASTER);
rsGet(rwRENDERSTATEVERTEXALPHAENABLE, &rsData._VERTEXALPHAENABLE);
rsGet(rwRENDERSTATESRCBLEND, &rsData._SRCBLEND);
rsGet(rwRENDERSTATEDESTBLEND, &rsData._DESTBLEND);
}
void ShapeDrawer::restoreRenderStates(const RenderStateData& rsData)
{
auto rsSet = RwEngineInstance->dOpenDevice.fpRenderStateSet;
rsSet(rwRENDERSTATETEXTURERASTER, rsData._TEXTURERASTER);
rsSet(rwRENDERSTATEVERTEXALPHAENABLE, rsData._VERTEXALPHAENABLE);
rsSet(rwRENDERSTATESRCBLEND, rsData._SRCBLEND);
rsSet(rwRENDERSTATEDESTBLEND, rsData._DESTBLEND);
}
| 39.246575 | 122 | 0.784642 | THE-FYP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.