hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fc826aee74ffc0649076ce046a283b385db9bbfc | 1,488 | cpp | C++ | dev/Gems/CryLegacy/Code/Source/CryAISystem/PersonalLog.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/CryLegacy/Code/Source/CryAISystem/PersonalLog.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/CryLegacy/Code/Source/CryAISystem/PersonalLog.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "CryLegacy_precompiled.h"
#include "PersonalLog.h"
void PersonalLog::AddMessage(const EntityId entityId, const char* message)
{
if (m_messages.size() + 1 > 20)
{
m_messages.pop_front();
}
m_messages.push_back(message);
if (gAIEnv.CVars.OutputPersonalLogToConsole)
{
const char* name = "(null)";
if (IEntity* entity = gEnv->pEntitySystem->GetEntity(entityId))
{
name = entity->GetName();
}
gEnv->pLog->Log("Personal Log [%s] %s", name, message);
}
#ifdef CRYAISYSTEM_DEBUG
if (IEntity* entity = gEnv->pEntitySystem->GetEntity(entityId))
{
if (IAIObject* ai = entity->GetAI())
{
IAIRecordable::RecorderEventData recorderEventData(message);
ai->RecordEvent(IAIRecordable::E_PERSONALLOG, &recorderEventData);
}
}
#endif
}
| 30.367347 | 85 | 0.672715 | jeikabu |
fc82d0036df81fb62197e707b6316d2f8db37882 | 2,182 | hpp | C++ | src/sysc/packages/boost/config/compiler/hp_acc.hpp | veeYceeY/systemc | 1bd5598ed1a8cf677ebb750accd5af485bc1085a | [
"Apache-2.0"
] | 194 | 2019-07-25T21:27:23.000Z | 2022-03-22T00:08:06.000Z | src/sysc/packages/boost/config/compiler/hp_acc.hpp | veeYceeY/systemc | 1bd5598ed1a8cf677ebb750accd5af485bc1085a | [
"Apache-2.0"
] | 24 | 2019-12-03T18:26:07.000Z | 2022-02-17T09:38:25.000Z | src/sysc/packages/boost/config/compiler/hp_acc.hpp | veeYceeY/systemc | 1bd5598ed1a8cf677ebb750accd5af485bc1085a | [
"Apache-2.0"
] | 64 | 2019-08-02T19:28:25.000Z | 2022-03-30T10:21:22.000Z | // (C) Copyright John Maddock 2001 - 2003.
// (C) Copyright Jens Maurer 2001 - 2003.
// (C) Copyright Aleksey Gurtovoy 2002.
// (C) Copyright David Abrahams 2002 - 2003.
// (C) Copyright Toon Knapen 2003.
// 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://www.boost.org for most recent version.
// HP aCC C++ compiler setup:
#if (__HP_aCC <= 33100)
# define SC_BOOST_NO_INTEGRAL_INT64_T
# define SC_BOOST_NO_OPERATORS_IN_NAMESPACE
# if !defined(_NAMESPACE_STD)
# define SC_BOOST_NO_STD_LOCALE
# define SC_BOOST_NO_STRINGSTREAM
# endif
#endif
#if (__HP_aCC <= 33300)
// member templates are sufficiently broken that we disable them for now
# define SC_BOOST_NO_MEMBER_TEMPLATES
# define SC_BOOST_NO_DEPENDENT_NESTED_DERIVATIONS
# define SC_BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE
#endif
#if (__HP_aCC <= 33900) || !defined(SC_BOOST_STRICT_CONFIG)
# define SC_BOOST_NO_UNREACHABLE_RETURN_DETECTION
# define SC_BOOST_NO_TEMPLATE_TEMPLATES
# define SC_BOOST_NO_SWPRINTF
# define SC_BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS
# define SC_BOOST_NO_IS_ABSTRACT
// std lib config should set this one already:
//# define SC_BOOST_NO_STD_ALLOCATOR
#endif
// optional features rather than defects:
#if (__HP_aCC >= 33900)
# define SC_BOOST_HAS_LONG_LONG
# define SC_BOOST_HAS_PARTIAL_STD_ALLOCATOR
#endif
#if (__HP_aCC >= 50000 ) && (__HP_aCC <= 53800 ) || (__HP_aCC < 31300 )
# define SC_BOOST_NO_MEMBER_TEMPLATE_KEYWORD
#endif
#define SC_BOOST_NO_MEMBER_TEMPLATE_FRIENDS
#define SC_BOOST_COMPILER "HP aCC version " SC_BOOST_STRINGIZE(__HP_aCC)
//
// versions check:
// we don't support HP aCC prior to version 0:
#if __HP_aCC < 33000
# error "Compiler not supported or configured - please reconfigure"
#endif
//
// last known and checked version is 0:
#if (__HP_aCC > 53800)
# if defined(SC_BOOST_ASSERT_CONFIG)
# error "Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
| 30.732394 | 94 | 0.754354 | veeYceeY |
fc877512a8e7717a036ba3b43217ac2c1cdffa46 | 24,317 | cpp | C++ | core/StarcraftBot/BWSAL_0.9.12/BasicAIModule/Sparcraft/source/Display.cpp | dtdannen/LUiGi-2 | 6e31f7178a48ffb886475fc59d6469d8262874c9 | [
"MIT"
] | null | null | null | core/StarcraftBot/BWSAL_0.9.12/BasicAIModule/Sparcraft/source/Display.cpp | dtdannen/LUiGi-2 | 6e31f7178a48ffb886475fc59d6469d8262874c9 | [
"MIT"
] | null | null | null | core/StarcraftBot/BWSAL_0.9.12/BasicAIModule/Sparcraft/source/Display.cpp | dtdannen/LUiGi-2 | 6e31f7178a48ffb886475fc59d6469d8262874c9 | [
"MIT"
] | null | null | null | #include "Display.h"
#ifdef USING_VISUALIZATION_LIBRARIES
using namespace SparCraft;
#ifdef WIN32
// disable vsync in windows
#include "glext/wglext.h"
#include "glext/glext.h"
#include "glfont/glfont.h"
typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALFARPROC)( int );
PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0;
#endif
PixelPerfectGLFont font;
GLuint fontID = 0;
Display::Display(const int mw, const int mh)
: windowSizeX(1280)
, windowSizeY(720)
, mapWidth(mw)
, mapHeight(mh)
, bl(false)
, br(false)
, bu(false)
, bd(false)
, zoomX(0)
, zoomY(0)
, drawResults(false)
, started(false)
{
playerTypes[0] = 0;
playerTypes[1] = 0;
textureSizes = std::vector<Position>(BWAPI::UnitTypes::allUnitTypes().size() + 10);
if(SDL_Init(SDL_INIT_VIDEO) != 0)
{
throw std::runtime_error("Unable to initialise SDL");
}
}
Display::~Display()
{
SDL_Quit();
}
void Display::OnStart()
{
if (started)
{
return;
}
mapPixelWidth = mapWidth * 32;
mapPixelHeight = mapHeight * 32;
cameraX = 400 - windowSizeX / 2;
cameraY = 400 - windowSizeY / 2;
#ifdef WIN32
PROC p = wglGetProcAddress("wglSwapIntervalEXT");
#endif
//(*wglGetProcAddress("wglSwapIntervalEXT"));
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
screen = SDL_SetVideoMode(windowSizeX, windowSizeY, 32, SDL_OPENGL);
SDL_WM_SetCaption("SparCraft Visualization", 0);
// enable alpha blending for transparency
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable( GL_BLEND );
// load the unit textures for later use
LoadTextures();
// load the font
std::stringstream fontFile;
#ifdef WIN32
fontFile << imageDir << "fonts\\couriernew.glf";
#else
fontFile << imageDir << "fonts/couriernew.glf";
#endif
font.Create(fontFile.str(), 99);
#ifdef WIN32
setVSync(0);
#endif
started = true;
}
void Display::SetImageDir(const std::string & filename)
{
imageDir = filename;
}
#ifdef WIN32
void Display::setVSync(int interval)
{
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)wglGetProcAddress( "wglSwapIntervalEXT" );
if( wglSwapIntervalEXT )
{
if(wglSwapIntervalEXT(interval))
{
//puts("VSync changed");
}
else
{
//puts("VSync change failed");
}
}
else
{
//puts("VSync change unsupported");
}
}
#endif
void Display::SetState(const GameState & s)
{
state = s;
}
void Display::SetResults(const IDType & player, const std::vector<std::vector<std::string> > & r)
{
results[player] = r;
}
void Display::SetParams(const IDType & player, const std::vector<std::vector<std::string> > & p)
{
params[player] = p;
}
void Display::SetExpDesc(const std::vector<std::vector<std::string> > & d)
{
exp = d;
}
void Display::SetPlayerTypes(const IDType & p1, const IDType & p2)
{
playerTypes[0] = p1;
playerTypes[1] = p2;
}
void Display::OnFrame()
{
// Handle input events
HandleEvents();
// Render the frame
glClear(GL_COLOR_BUFFER_BIT);
RenderMainMap();
RenderMinimap();
RenderTextOverlay();
RenderInformation();
SDL_GL_SwapBuffers();
}
void Display::HandleEvents()
{
// Handle SDL events
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
{
const bool pressed(event.key.state == SDL_PRESSED);
switch(event.key.keysym.sym)
{
case SDLK_LEFT: bl = pressed; break;
case SDLK_RIGHT: br = pressed; break;
case SDLK_UP: bu = pressed; break;
case SDLK_DOWN: bd = pressed; break;
}
}
break;
case SDL_MOUSEBUTTONDOWN:
{
const int2 minimapSize(mapWidth,mapHeight);
const int2 minimapLocation(0,windowSizeY-minimapSize.y);
const int2 mouse(event.button.x - minimapLocation.x, event.button.y - minimapLocation.y);
if(mouse.x >= 0 && mouse.x < mapWidth && mouse.y >= 0 && mouse.y < mapHeight)
{
cameraX = mouse.x * 32 - windowSizeX/2;
cameraY = mouse.y * 32 - windowSizeY/2;
}
if(event.button.button == SDL_BUTTON_WHEELUP)
{
zoomX += 128;
zoomY += 72;
}
else if(event.button.button == SDL_BUTTON_WHEELDOWN)
{
zoomX -= 128;
zoomY -= 72;
}
}
break;
case SDL_QUIT:
System::FatalError("Visualization Shut Down");
}
}
// Move the camera
const int cameraSpeed(32);
if(bl) cameraX -= cameraSpeed;
if(br) cameraX += cameraSpeed;
if(bu) cameraY -= cameraSpeed;
if(bd) cameraY += cameraSpeed;
cameraX = std::max(0, std::min(cameraX, mapPixelWidth-windowSizeX));
cameraY = std::max(0, std::min(cameraY, mapPixelHeight-windowSizeY));
}
void Display::RenderMainMap()
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
{
glOrtho(0,windowSizeX-zoomX,windowSizeY-zoomY,0,-1,1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
{
glTranslatef(static_cast<float>(-cameraX),static_cast<float>(-cameraY),0);
const int vx0(cameraX), vx1(cameraX+windowSizeX-zoomX);
const int vy0(cameraY), vy1(cameraY+windowSizeY-zoomY);
RenderTerrain( std::max(vx0>>3,0), std::max(vy0>>3,0),
std::min((vx1>>3) + 1, mapWidth*4),
std::min((vy1>>3) + 1, mapHeight*4));
RenderUnits();
BOOST_FOREACH (const Shape & shape, shapes)
{
shape.OnRender();
}
}
glPopMatrix();
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
glPopAttrib();
}
void Display::RenderMinimap()
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glOrtho(0,windowSizeX,0,windowSizeY,-1,1);
glBegin(GL_QUADS);
glVertex2i(0,0);
glVertex2i(mapWidth+1,0);
glVertex2i(mapWidth+1,mapHeight+1);
glVertex2i(0,mapHeight+1);
glEnd();
glLoadIdentity();
glOrtho(0,mapPixelWidth,mapPixelHeight,0,-1,1);
glViewport(0,0,mapWidth,mapHeight);
RenderTerrain(0,0,mapWidth*4,mapHeight*4);
BOOST_FOREACH (const Shape & shape, shapes)
{
shape.OnRender();
}
RenderUnits();
// Render outline around viewport on minimap
{
const int vpx0(cameraX), vpx1(vpx0 + windowSizeX - zoomX);
const int vpy0(cameraY), vpy1(vpy0 + windowSizeY - zoomY);
glColor3f(1,1,1);
glBegin(GL_LINE_STRIP);
glVertex2i(vpx0,vpy0);
glVertex2i(vpx1,vpy0);
glVertex2i(vpx1,vpy1);
glVertex2i(vpx0,vpy1);
glVertex2i(vpx0,vpy0);
glEnd();
}
glPopMatrix();
glPopAttrib();
}
void Display::RenderTextOverlay()
{
int size = 15;
/*
std::stringstream ss;
ss << "Game Frame: " << state.getTime();
std::stringstream ss2;
ss2 << "Game Seconds: " << state.getTime() / 24;
glColor3f(0.0, 1.0, 0.0);
DrawText(700, 5 , size, "Game Time");
glColor3f(1.0, 1.0, 1.0);
DrawText(700, 20, size, ss.str());
DrawText(700, 35, size, ss2.str());*/
DrawParameters(5, 3);
DrawSearchResults(5, 150);
DrawExperiment(675, 5);
}
void Display::DrawSearchResults(int x, int y)
{
int size = 11;
int spacing = 3;
int colwidth = 175;
int playerspacing = 350;
// Player 1 Settings
// Player 2 Settings
if (results[0].size() > 0)
{
glColor3f(1.0, 0.0, 0.0);
DrawText(x, y , size, "Player 1 Search Results");
glColor3f(1.0, 1.0, 1.0);
for (size_t r(0); results[0].size() > 0 && r<results[0][0].size(); ++r)
{
DrawText(x, y+((r+1)*(size+spacing)), size, results[0][0][r]);
DrawText(x+colwidth, y+((r+1)*(size+spacing)), size, results[0][1][r]);
}
}
// Player 2 Settings
if (results[1].size() > 0)
{
x += playerspacing;
glColor3f(0.0, 1.0, 0.0);
DrawText(x, y , size, "Player 2 Search Results");
glColor3f(1.0, 1.0, 1.0);
for (size_t r(0); results[1].size() > 0 && r<results[1][0].size(); ++r)
{
DrawText(x, y+((r+1)*(size+spacing)), size, results[1][0][r]);
DrawText(x+colwidth, y+((r+1)*(size+spacing)), size, results[1][1][r]);
}
}
}
void Display::DrawParameters(int x, int y)
{
int size = 11;
int spacing = 3;
int colwidth = 175;
int playerspacing = 350;
// Player 1 Settings
if (params[0].size() > 0)
{
glColor3f(1.0, 0.0, 0.0);
DrawText(x, y , size, "Player 1 Settings");
glColor3f(1.0, 1.0, 1.0);
for (size_t p(0); params[0].size() > 0 && p<params[0][0].size(); ++p)
{
DrawText(x, y+((p+1)*(size+spacing)), size, params[0][0][p]);
DrawText(x+colwidth, y+((p+1)*(size+spacing)), size, params[0][1][p]);
}
}
if (params[1].size() > 0)
{
// Player 2 Settings
x += playerspacing;
glColor3f(0.0, 1.0, 0.0);
DrawText(x, y , size, "Player 2 Settings");
glColor3f(1.0, 1.0, 1.0);
for (size_t p(0); params[1].size() > 0 && p<params[1][0].size(); ++p)
{
DrawText(x, y+((p+1)*(size+spacing)), size, params[1][0][p]);
DrawText(x+colwidth, y+((p+1)*(size+spacing)), size, params[1][1][p]);
}
}
}
void Display::DrawExperiment(int x, int y)
{
int size = 11;
int spacing = 3;
int colwidth = 100;
int playerspacing = 350;
// Player 1 Settings
glColor3f(1.0, 0.0, 0.0);
DrawText(x, y , size, "Experiment Progress");
glColor3f(1.0, 1.0, 1.0);
for (size_t p(0); p<exp[0].size(); ++p)
{
DrawText(x, y+((p+1)*(size+spacing)), size, exp[0][p]);
DrawText(x+colwidth, y+((p+1)*(size+spacing)), size, exp[1][p]);
}
}
void Display::RenderInformation()
{
static const float3 factionColors[12] =
{
float3(1,0,0), float3(0,1,0), float3(0,1,0.5f), float3(0.5f,0,1),
float3(1,0.5f,0), float3(0.5f,0.25f,0), float3(1,1,1), float3(1,1,0),
float3(0,0,0), float3(0,0,0), float3(0,0,0), float3(0,1,1)
};
glPushAttrib(GL_ALL_ATTRIB_BITS);
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
{
glOrtho(0,windowSizeX,windowSizeY,0,-1,1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
{
for (IDType p(0); p<Constants::Num_Players; ++p)
{
for (IDType u(0); u<Constants::Max_Units; ++u)
{
int barHeight = 12;
const Unit & unit(state.getUnitDirect(p, u));
const Position pos(1000+170*p, 40+barHeight*u);
const BWAPI::UnitType type(unit.type());
const int x0(pos.x());
const int x1(pos.x() + 150);
const int y0(pos.y());
const int y1(pos.y() + 15);
// draw the unit HP box
double percHP = (double)unit.currentHP() / (double)unit.maxHP();
int w = 150;
int h = barHeight;
int cw = (int)(w * percHP);
int xx = pos.x() - w/2;
int yy = pos.y() - h - (y1-y0)/2;
if (unit.isAlive())
{
glColor4f(factionColors[p].x, factionColors[p].y, factionColors[p].z, 0.75);
glBegin(GL_QUADS);
glVertex2i(xx,yy);
glVertex2i(xx+cw,yy);
glColor4f(0.2f, 0.2f, 0.2f, 0.75);
glVertex2i(xx+cw,yy+h);
glColor4f(factionColors[p].x, factionColors[p].y, factionColors[p].z, 0.75);
glVertex2i(xx,yy+h);
glEnd();
}
if (unit.ID() < 255)
{
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, unit.type().getID() );
// draw the unit to the screen
glColor4f(1, 1, 1, 1);
glBegin( GL_QUADS );
glTexCoord3d(0.0,0.0,.5); glVertex2i(xx, yy);
glTexCoord3d(0.0,1.0,.5); glVertex2i(xx, yy+h);
glTexCoord3d(1.0,1.0,.5); glVertex2i(xx+h,yy+h);
glTexCoord3d(1.0,0.0,.5); glVertex2i(xx+h, yy);
glEnd();
glDisable( GL_TEXTURE_2D );
}
}
}
}
glPopMatrix();
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
glPopAttrib();
}
void Display::RenderTerrain(int wx0, int wy0, int wx1, int wy1)
{
int dX = 1280;
int dY = 800;
for (int x(0); x<mapPixelWidth; x+=dX)
{
for (int y(0); y<mapPixelHeight; y+=dY)
{
//glBegin(GL_QUADS);
glEnable( GL_TEXTURE_2D );
// bind the correct tecture based on this unit
glBindTexture( GL_TEXTURE_2D, 4 );
// draw the unit to the screen
glColor4f(1.0, 1.0, 1.0, 1.0);
glBegin( GL_QUADS );
glTexCoord3d(0.0,0.0,.5); glVertex2i(x, y);
glTexCoord3d(1.0,0.0,.5); glVertex2i(x, y+dY);
glTexCoord3d(1.0,1.0,.5); glVertex2i(x+dX, y+dY);
glTexCoord3d(0.0,1.0,.5); glVertex2i(x+dX, y);
glEnd();
glDisable( GL_TEXTURE_2D );
}
}
glEnable( GL_TEXTURE_2D );
// bind the correct tecture based on this unit
glBindTexture( GL_TEXTURE_2D, 19 );
// draw the unit to the screen
glColor4f(0.0, 0.0, 0.0, 0.75f);
glBegin( GL_QUADS );
glTexCoord3d(0.0,0.0,.5); glVertex2i(0, 0);
glTexCoord3d(1.0,0.0,.5); glVertex2i(mapPixelWidth, 0);
glTexCoord3d(1.0,1.0,.5); glVertex2i(mapPixelWidth, mapPixelHeight);
glTexCoord3d(0.0,1.0,.5); glVertex2i(0, mapPixelHeight);
glEnd();
glDisable( GL_TEXTURE_2D );
}
void Display::RenderUnits()
{
for (IDType u(0); u<state.numNeutralUnits(); ++u)
{
const Unit & unit(state.getNeutralUnit(u));
RenderUnit(unit);
}
for (IDType p(0); p<Constants::Num_Players; ++p)
{
for (IDType u(0); u<state.prevNumUnits(p); ++u)
{
const Unit & unit(state.getUnit(p, u));
RenderUnit(unit);
}
}
}
void Display::RenderUnit(const Unit & unit)
{
static const float3 factionColors[12] =
{
float3(1,0,0), float3(0,1,0), float3(0,1,0.5f), float3(0.5f,0,1),
float3(1,0.5f,0), float3(0.5f,0.25f,0), float3(1,1,1), float3(1,1,0),
float3(0,0,0), float3(0,0,0), float3(0,0,0), float3(0,1,1)
};
glColor4f(1, 1, 1, 1);
const int healthBoxHeight = 4;
const Position pos(unit.currentPosition(state.getTime()));
const BWAPI::UnitType type(unit.type());
const int tx(textureSizes[type.getID()].x()/2);
const int ty(textureSizes[type.getID()].y()/2);
// unit box will be a square due to having square textures
const int x0(pos.x() - type.dimensionUp());
const int x1(pos.x() + type.dimensionDown());
const int y0(pos.y() - type.dimensionUp());
const int y1(pos.y() + type.dimensionDown());
const int tx0(pos.x() - tx);
const int tx1(pos.x() + tx);
const int ty0(pos.y() - ty);
const int ty1(pos.y() + ty);
// if the unit can move right now draw its move
if (unit.previousActionTime() == state.getTime())
{
const UnitAction & move = unit.previousAction();
if (move.type() == UnitActionTypes::MOVE)
{
glColor4f(1, 1, 1, 0.75);
glBegin(GL_LINES);
glVertex2i(pos.x(), pos.y());
glVertex2i(unit.pos().x(), unit.pos().y());
glEnd( );
}
else if (move.type() == UnitActionTypes::ATTACK)
{
const Unit & target(state.getUnit(state.getEnemy(unit.player()), move.index()));
const Position targetPos(target.currentPosition(state.getTime()));
glColor4f(factionColors[unit.player()].x, factionColors[unit.player()].y, factionColors[unit.player()].z, 0.75);
glBegin(GL_LINES);
glVertex2i(pos.x(), pos.y());
glVertex2i(targetPos.x(), targetPos.y());
glEnd( );
/*glColor4f(1.0, 0.0, 0.0, 0.25);
glBegin(GL_QUADS);
glVertex2i(targetPos.x()-type.dimensionUp(),targetPos.y()-type.dimensionUp());
glVertex2i(targetPos.x()-type.dimensionUp(),targetPos.y()+type.dimensionUp());
glVertex2i(targetPos.x()+type.dimensionUp(),targetPos.y()+type.dimensionUp());
glVertex2i(targetPos.x()+type.dimensionUp(),targetPos.y()-type.dimensionUp());
glEnd();*/
}
else if (move.type() == UnitActionTypes::HEAL)
{
const Unit & target(state.getUnit(unit.player(), move.index()));
const Position targetPos(target.currentPosition(state.getTime()));
glColor4f(factionColors[unit.player()].x, factionColors[unit.player()].y, factionColors[unit.player()].z, 0.75);
glBegin(GL_LINES);
glVertex2i(pos.x(), pos.y());
glVertex2i(targetPos.x(), targetPos.y());
glEnd( );
/*glColor4f(0.0, 1.0, 0.0, 0.25);
glBegin(GL_QUADS);
glVertex2i(targetPos.x()-type.dimensionUp(),targetPos.y()-type.dimensionUp());
glVertex2i(targetPos.x()-type.dimensionUp(),targetPos.y()+type.dimensionUp());
glVertex2i(targetPos.x()+type.dimensionUp(),targetPos.y()+type.dimensionUp());
glVertex2i(targetPos.x()+type.dimensionUp(),targetPos.y()-type.dimensionUp());
glEnd();*/
}
}
// draw the unit's texture
glEnable( GL_TEXTURE_2D );
glColor4f(1, 1, 1, 0.75);
glBindTexture( GL_TEXTURE_2D, unit.type().getID() );
glBegin( GL_QUADS );
glTexCoord3d(0.0,0.0,.5); glVertex2i(tx0,ty0);
glTexCoord3d(1.0,0.0,.5); glVertex2i(tx1,ty0);
glTexCoord3d(1.0,1.0,.5); glVertex2i(tx1,ty1);
glTexCoord3d(0.0,1.0,.5); glVertex2i(tx0,ty1);
glEnd();
glDisable( GL_TEXTURE_2D );
if (unit.player() == Players::Player_None)
{
return;
}
// draw the unit HP box
double percHP = (double)unit.currentHP() / (double)unit.maxHP();
int cw = (int)((x1-x0) * percHP);
int xx = pos.x() - (x1-x0)/2;
int yy = pos.y() - healthBoxHeight - (y1-y0)/2 - 5;
glColor4f(factionColors[unit.player()].x, factionColors[unit.player()].y, factionColors[unit.player()].z, 0.75);
glBegin(GL_QUADS);
glVertex2i(xx,yy);
glVertex2i(xx+cw,yy);
glVertex2i(xx+cw,yy+healthBoxHeight);
glVertex2i(xx,yy+healthBoxHeight);
glEnd();
// draw the unit energy box
if (unit.currentEnergy() > 0)
{
double percEnergy = (double)unit.currentEnergy() / (double)Constants::Starting_Energy;
cw = (int)((x1-x0) * percEnergy);
xx = pos.x() - (x1-x0)/2;
yy = pos.y() - healthBoxHeight*2 - (y1-y0)/2 - 5;
glColor4f(0.0, 1.0, 0.0, 0.75);
glBegin(GL_QUADS);
glVertex2i(xx,yy);
glVertex2i(xx+cw,yy);
glVertex2i(xx+cw,yy+healthBoxHeight);
glVertex2i(xx,yy+healthBoxHeight);
glEnd();
}
// draw attack radius
glColor4f(0.2f, 0.2f, 0.2f, 0.25);
int radius = unit.canHeal() ? unit.healRange() : unit.range();
//DrawCircle((float)pos.x(), (float)pos.y(), (float)radius, 60);
}
void Display::DrawText(const int & x, const int & y, const int & size, const std::string & text)
{
glEnable( GL_TEXTURE_2D );
glPushAttrib(GL_ALL_ATTRIB_BITS);
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
{
glOrtho(0,windowSizeX,windowSizeY,0,-1,1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
{
font.Begin();
font.TextOut(text, x, y, 0);
}
glPopMatrix();
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
glPopAttrib();
glDisable( GL_TEXTURE_2D );
}
void Display::DrawCircle(float cx, float cy, float r, int num_segments) const
{
float theta = 2 * (float)3.1415926 / float(num_segments);
float c = cosf(theta);//precalculate the sine and cosine
float s = sinf(theta);
float t;
float x = r;//we start at angle = 0
float y = 0;
glBegin(GL_LINE_LOOP);
for(int ii = 0; ii < num_segments; ii++)
{
glVertex2f(x + cx, y + cy);//output vertex
//apply the rotation matrix
t = x;
x = c * x - s * y;
y = s * t + c * y;
}
glEnd();
}
float3 Display::GetWalkTileColor(int x, int y) const
{
return ((x + y) % 2) == 0 ? float3(0.0f, 0.0f, 0.0f) : float3(0.05f, 0.05f, 0.05f);
}
void Display::LoadTextures()
{
std::stringstream ss;
#ifdef WIN32
ss << imageDir << "ground\\ground" << 2 << ".png";
#else
ss << imageDir << "ground/ground" << 2 << ".png";
#endif
std::vector<GLuint> textures(BWAPI::UnitTypes::allUnitTypes().size());
glGenTextures( BWAPI::UnitTypes::allUnitTypes().size(), &textures[0] );
LoadTexture(4, ss.str().c_str());
BOOST_FOREACH (BWAPI::UnitType type, BWAPI::UnitTypes::allUnitTypes())
{
LoadTexture(type.getID(), getTextureFileName(type).c_str());
}
}
void Display::LoadTexture(int textureNumber, const char * fileName)
{
struct stat buf;
if (stat(fileName, &buf) == -1)
{
return;
}
// GLuint texture; // This is a handle to our texture object
SDL_Surface *surface; // This surface will tell us the details of the image
GLenum texture_format;
GLint nOfColors;
if ( (surface = IMG_Load(fileName)) )
{
// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 )
{
//printf("warning: image.bmp's width is not a power of 2\n");
}
// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 )
{
//printf("warning: image.bmp's height is not a power of 2\n");
}
// get the number of channels in the SDL surface
nOfColors = surface->format->BytesPerPixel;
if (nOfColors == 4) // contains an alpha channel
{
//printf("Contains Alpha\n");
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGBA;
else
texture_format = GL_BGRA;
}
else if (nOfColors == 3) // no alpha channel
{
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGB;
else
texture_format = GL_BGR;
}
else
{
printf("warning: the image is not truecolor.. this will probably break\n");
// this error should not go unhandled
}
// Have OpenGL generate a texture object handle for us
// Bind the texture object
glBindTexture( GL_TEXTURE_2D, textureNumber );
// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// Edit the texture object's image data using the information SDL_Surface gives us
glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, surface->w, surface->h, 0, texture_format, GL_UNSIGNED_BYTE, surface->pixels );
textureSizes[textureNumber] = Position(surface->w, surface->h);
}
else
{
printf("SDL could not load image: %s\n", SDL_GetError());
//SDL_Quit();
}
// Free the SDL_Surface only if it was successfully created
if ( surface )
{
//printf("Loaded Image %s\n", fileName);
SDL_FreeSurface( surface );
}
}
void Display::LoadMapTexture(SparCraft::Map * map, int textureNumber)
{
if (!map)
{
return;
}
unsigned int * data = map->getRGBATexture();
glBindTexture( GL_TEXTURE_2D, textureNumber );
// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// Edit the texture object's image data using the information SDL_Surface gives us
glTexImage2D( GL_TEXTURE_2D, 0, 4, map->getWalkTileWidth(), map->getWalkTileHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, data );
delete [] data;
}
void Shape::OnRender() const
{
glColor3fv(color);
if(points.size() == 1)
{
glBegin(GL_POINTS);
glVertex2iv(points[0]);
glEnd();
}
else if(points.size() == 2)
{
glBegin(GL_LINES);
glVertex2iv(points[0]);
glVertex2iv(points[1]);
glEnd();
}
else
{
glBegin(solid ? GL_TRIANGLE_FAN : GL_LINE_STRIP);
BOOST_FOREACH (const int2 & point, points)
{
glVertex2iv(point);
}
// If not solid, close the outline
if(!solid)
{
glVertex2iv(points[0]);
}
glEnd();
}
}
const std::string Display::getTextureFileName(const BWAPI::UnitType type) const
{
std::stringstream image;
#ifdef WIN32
image << imageDir << "units\\" << type.getName() << ".png";
#else
image << imageDir << "units/" << type.getName() << ".png";
#endif
std::string filename = image.str();
for (size_t i(0); i<filename.size(); ++i)
{
if (filename[i] == ' ')
{
filename[i] = '_';
}
}
return filename;
}
/*void Display::RenderTextOverlay()
{
static const float texCharWidth(8.0f/256);
static const float texCharHeight(14.0f/256);
glPushAttrib(GL_ALL_ATTRIB_BITS);
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
{
glOrtho(0,windowSizeX,windowSizeY,0,-1,1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,texFont);
glBegin(GL_QUADS);
BOOST_FOREACH (const TextElement & element, textElements)
{
glColor3fv(element.color);
int x(element.position.x);
BOOST_FOREACH(char ch, element.text)
{
const float s0((ch % 32) * texCharWidth), s1(s0 + texCharWidth);
const float t0((ch / 32) * texCharHeight), t1(t0 + texCharHeight);
const int x0(x), x1(x0 + 8);
const int y0(element.position.y), y1(y0 + 14);
x = x1;
glTexCoord2f(s0,t0); glVertex2i(x0,y0);
glTexCoord2f(s1,t0); glVertex2i(x1,y0);
glTexCoord2f(s1,t1); glVertex2i(x1,y1);
glTexCoord2f(s0,t1); glVertex2i(x0,y1);
}
}
glEnd();
}
glPopMatrix();
}
glPopAttrib();
}*/
#endif | 24.889458 | 124 | 0.628655 | dtdannen |
fc87c7685cc79f6c4db4aebcc9f186b25c85e353 | 3,963 | cpp | C++ | src/x11/atoms.cpp | HughJass/polybar | a78edc667b2c347898787348c27322710d357ce6 | [
"MIT"
] | 6,283 | 2019-05-06T01:10:56.000Z | 2022-03-31T23:42:59.000Z | src/x11/atoms.cpp | HughJass/polybar | a78edc667b2c347898787348c27322710d357ce6 | [
"MIT"
] | 997 | 2019-05-05T20:09:11.000Z | 2022-03-31T22:58:40.000Z | src/x11/atoms.cpp | HughJass/polybar | a78edc667b2c347898787348c27322710d357ce6 | [
"MIT"
] | 506 | 2019-05-08T18:36:25.000Z | 2022-03-25T03:04:39.000Z | #include "x11/atoms.hpp"
#include <xcb/xcb.h>
#include <xcb/xcb_atom.h>
xcb_atom_t _NET_SUPPORTED;
xcb_atom_t _NET_CURRENT_DESKTOP;
xcb_atom_t _NET_ACTIVE_WINDOW;
xcb_atom_t _NET_WM_NAME;
xcb_atom_t _NET_WM_DESKTOP;
xcb_atom_t _NET_WM_VISIBLE_NAME;
xcb_atom_t _NET_WM_WINDOW_TYPE;
xcb_atom_t _NET_WM_WINDOW_TYPE_DOCK;
xcb_atom_t _NET_WM_WINDOW_TYPE_NORMAL;
xcb_atom_t _NET_WM_PID;
xcb_atom_t _NET_WM_STATE;
xcb_atom_t _NET_WM_STATE_STICKY;
xcb_atom_t _NET_WM_STATE_SKIP_TASKBAR;
xcb_atom_t _NET_WM_STATE_ABOVE;
xcb_atom_t _NET_WM_STATE_MAXIMIZED_VERT;
xcb_atom_t _NET_WM_STRUT;
xcb_atom_t _NET_WM_STRUT_PARTIAL;
xcb_atom_t WM_PROTOCOLS;
xcb_atom_t WM_DELETE_WINDOW;
xcb_atom_t _XEMBED;
xcb_atom_t _XEMBED_INFO;
xcb_atom_t MANAGER;
xcb_atom_t WM_STATE;
xcb_atom_t _NET_SYSTEM_TRAY_OPCODE;
xcb_atom_t _NET_SYSTEM_TRAY_ORIENTATION;
xcb_atom_t _NET_SYSTEM_TRAY_VISUAL;
xcb_atom_t _NET_SYSTEM_TRAY_COLORS;
xcb_atom_t WM_TAKE_FOCUS;
xcb_atom_t Backlight;
xcb_atom_t BACKLIGHT;
xcb_atom_t _XROOTPMAP_ID;
xcb_atom_t _XSETROOT_ID;
xcb_atom_t ESETROOT_PMAP_ID;
xcb_atom_t _COMPTON_SHADOW;
xcb_atom_t _NET_WM_WINDOW_OPACITY;
xcb_atom_t WM_HINTS;
// clang-format off
cached_atom ATOMS[36] = {
{"_NET_SUPPORTED", sizeof("_NET_SUPPORTED") - 1, &_NET_SUPPORTED},
{"_NET_CURRENT_DESKTOP", sizeof("_NET_CURRENT_DESKTOP") - 1, &_NET_CURRENT_DESKTOP},
{"_NET_ACTIVE_WINDOW", sizeof("_NET_ACTIVE_WINDOW") - 1, &_NET_ACTIVE_WINDOW},
{"_NET_WM_NAME", sizeof("_NET_WM_NAME") - 1, &_NET_WM_NAME},
{"_NET_WM_DESKTOP", sizeof("_NET_WM_DESKTOP") - 1, &_NET_WM_DESKTOP},
{"_NET_WM_VISIBLE_NAME", sizeof("_NET_WM_VISIBLE_NAME") - 1, &_NET_WM_VISIBLE_NAME},
{"_NET_WM_WINDOW_TYPE", sizeof("_NET_WM_WINDOW_TYPE") - 1, &_NET_WM_WINDOW_TYPE},
{"_NET_WM_WINDOW_TYPE_DOCK", sizeof("_NET_WM_WINDOW_TYPE_DOCK") - 1, &_NET_WM_WINDOW_TYPE_DOCK},
{"_NET_WM_WINDOW_TYPE_NORMAL", sizeof("_NET_WM_WINDOW_TYPE_NORMAL") - 1, &_NET_WM_WINDOW_TYPE_NORMAL},
{"_NET_WM_PID", sizeof("_NET_WM_PID") - 1, &_NET_WM_PID},
{"_NET_WM_STATE", sizeof("_NET_WM_STATE") - 1, &_NET_WM_STATE},
{"_NET_WM_STATE_STICKY", sizeof("_NET_WM_STATE_STICKY") - 1, &_NET_WM_STATE_STICKY},
{"_NET_WM_STATE_SKIP_TASKBAR", sizeof("_NET_WM_STATE_SKIP_TASKBAR") - 1, &_NET_WM_STATE_SKIP_TASKBAR},
{"_NET_WM_STATE_ABOVE", sizeof("_NET_WM_STATE_ABOVE") - 1, &_NET_WM_STATE_ABOVE},
{"_NET_WM_STATE_MAXIMIZED_VERT", sizeof("_NET_WM_STATE_MAXIMIZED_VERT") - 1, &_NET_WM_STATE_MAXIMIZED_VERT},
{"_NET_WM_STRUT", sizeof("_NET_WM_STRUT") - 1, &_NET_WM_STRUT},
{"_NET_WM_STRUT_PARTIAL", sizeof("_NET_WM_STRUT_PARTIAL") - 1, &_NET_WM_STRUT_PARTIAL},
{"WM_PROTOCOLS", sizeof("WM_PROTOCOLS") - 1, &WM_PROTOCOLS},
{"WM_DELETE_WINDOW", sizeof("WM_DELETE_WINDOW") - 1, &WM_DELETE_WINDOW},
{"_XEMBED", sizeof("_XEMBED") - 1, &_XEMBED},
{"_XEMBED_INFO", sizeof("_XEMBED_INFO") - 1, &_XEMBED_INFO},
{"MANAGER", sizeof("MANAGER") - 1, &MANAGER},
{"WM_STATE", sizeof("WM_STATE") - 1, &WM_STATE},
{"_NET_SYSTEM_TRAY_OPCODE", sizeof("_NET_SYSTEM_TRAY_OPCODE") - 1, &_NET_SYSTEM_TRAY_OPCODE},
{"_NET_SYSTEM_TRAY_ORIENTATION", sizeof("_NET_SYSTEM_TRAY_ORIENTATION") - 1, &_NET_SYSTEM_TRAY_ORIENTATION},
{"_NET_SYSTEM_TRAY_VISUAL", sizeof("_NET_SYSTEM_TRAY_VISUAL") - 1, &_NET_SYSTEM_TRAY_VISUAL},
{"_NET_SYSTEM_TRAY_COLORS", sizeof("_NET_SYSTEM_TRAY_COLORS") - 1, &_NET_SYSTEM_TRAY_COLORS},
{"WM_TAKE_FOCUS", sizeof("WM_TAKE_FOCUS") - 1, &WM_TAKE_FOCUS},
{"Backlight", sizeof("Backlight") - 1, &Backlight},
{"BACKLIGHT", sizeof("BACKLIGHT") - 1, &BACKLIGHT},
{"_XROOTPMAP_ID", sizeof("_XROOTPMAP_ID") - 1, &_XROOTPMAP_ID},
{"_XSETROOT_ID", sizeof("_XSETROOT_ID") - 1, &_XSETROOT_ID},
{"ESETROOT_PMAP_ID", sizeof("ESETROOT_PMAP_ID") - 1, &ESETROOT_PMAP_ID},
{"_COMPTON_SHADOW", sizeof("_COMPTON_SHADOW") - 1, &_COMPTON_SHADOW},
{"_NET_WM_WINDOW_OPACITY", sizeof("_NET_WM_WINDOW_OPACITY") - 1, &_NET_WM_WINDOW_OPACITY},
{"WM_HINTS", sizeof("WM_HINTS") - 1, &WM_HINTS},
};
// clang-format on
| 47.746988 | 110 | 0.779208 | HughJass |
fc882ee71b7b5a6472f4a9c219234fdc0880cf1d | 7,593 | cpp | C++ | Source/Applications/BakerApp.cpp | Marsel24/fonline | 83c10c315ea6f2c5ce6a83a608f287d9c619fa9d | [
"MIT"
] | null | null | null | Source/Applications/BakerApp.cpp | Marsel24/fonline | 83c10c315ea6f2c5ce6a83a608f287d9c619fa9d | [
"MIT"
] | null | null | null | Source/Applications/BakerApp.cpp | Marsel24/fonline | 83c10c315ea6f2c5ce6a83a608f287d9c619fa9d | [
"MIT"
] | null | null | null | // __________ ___ ______ _
// / ____/ __ \____ / (_)___ ___ / ____/___ ____ _(_)___ ___
// / /_ / / / / __ \/ / / __ \/ _ \ / __/ / __ \/ __ `/ / __ \/ _ \
// / __/ / /_/ / / / / / / / / / __/ / /___/ / / / /_/ / / / / / __/
// /_/ \____/_/ /_/_/_/_/ /_/\___/ /_____/_/ /_/\__, /_/_/ /_/\___/
// /____/
// FOnline Engine
// https://fonline.ru
// https://github.com/cvet/fonline
//
// MIT License
//
// Copyright (c) 2006 - present, Anton Tsvetinskiy aka cvet <cvet@tut.by>
//
// 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.
//
// Todo: sound and video preprocessing move to baker
#include "Common.h"
#include "EffectBaker.h"
#include "FileSystem.h"
#include "ImageBaker.h"
#include "Log.h"
#include "ModelBaker.h"
#include "ProtoManager.h"
#include "Settings.h"
#include "StringUtils.h"
#include "Testing.h"
#include "Version_Include.h"
static GlobalSettings Settings;
#ifndef FO_TESTING
int main(int argc, char** argv)
#else
static int main_disabled(int argc, char** argv)
#endif
{
CatchExceptions("FOnlineBaker", FO_VERSION);
LogToFile("FOnlineBaker.log");
Settings.ParseArgs(argc, argv);
try
{
DiskFileSystem::MakeDirTree(Settings.ResourcesOutput);
bool set_res_dir_ok = DiskFileSystem::SetCurrentDir(Settings.ResourcesOutput);
RUNTIME_ASSERT(set_res_dir_ok);
// Content
if (!Settings.ContentEntry.empty())
{
WriteLog("Bake content.\n");
FileManager content_files;
for (const string& dir : Settings.ContentEntry)
{
WriteLog("Add content entry '{}'.\n", dir);
content_files.AddDataSource(dir, true);
}
// Protos
ProtoManager proto_mngr;
proto_mngr.LoadProtosFromFiles(content_files);
UCharVec data = proto_mngr.GetProtosBinaryData();
RUNTIME_ASSERT(!data.empty());
DiskFile protos_file = DiskFileSystem::OpenFile("Protos.fobin", true);
RUNTIME_ASSERT(protos_file);
bool protos_write_ok = protos_file.Write(data.data(), (uint)data.size());
RUNTIME_ASSERT(protos_write_ok);
// Dialogs
// Todo: add dialogs verification during baking
bool del_dialogs_ok = DiskFileSystem::DeleteDir("Dialogs");
RUNTIME_ASSERT(del_dialogs_ok);
FileCollection dialogs = content_files.FilterFiles("fodlg");
while (dialogs.MoveNext())
{
File file = dialogs.GetCurFile();
DiskFile dlg_file = DiskFileSystem::OpenFile(_str("Dialogs/{}.fodlg", file.GetName()), true);
RUNTIME_ASSERT(dlg_file);
bool dlg_file_write_ok = dlg_file.Write(file.GetBuf(), file.GetFsize());
RUNTIME_ASSERT(dlg_file_write_ok);
}
// Texts
// LanguagePack lang;
// lang.LoadFromFiles(content_files);
// Raw Texts
// Texts.fobin
}
// Resources
if (!Settings.ResourcesEntry.empty())
{
WriteLog("Bake resources.\n");
map<string, vector<string>> res_packs;
for (const string& re : Settings.ResourcesEntry)
{
StrVec re_splitted = _str(re).split(',');
RUNTIME_ASSERT(re_splitted.size() == 2);
res_packs[re_splitted[0]].push_back(re_splitted[1]);
}
for (const auto& kv : res_packs)
{
const string& pack_name = kv.first;
FileManager res_files;
for (const string& path : kv.second)
{
WriteLog("Add resource pack '{}' entry '{}'.\n", pack_name, path);
res_files.AddDataSource(path, true);
}
FileCollection resources = res_files.FilterFiles("");
if (pack_name != "_Raw")
{
WriteLog("Create resources '{}' from files {}...\n", pack_name, resources.GetFilesCount());
// Bake files
map<string, UCharVec> baked_files;
{
ImageBaker image_baker(Settings, resources);
ModelBaker model_baker(resources);
EffectBaker effect_baker(resources);
image_baker.AutoBakeImages();
model_baker.AutoBakeModels();
effect_baker.AutoBakeEffects();
image_baker.FillBakedFiles(baked_files);
model_baker.FillBakedFiles(baked_files);
effect_baker.FillBakedFiles(baked_files);
}
// Write to disk
bool del_res_ok = DiskFileSystem::DeleteDir(_str("Pack_{}", pack_name));
RUNTIME_ASSERT(del_res_ok);
for (const auto& kv : baked_files)
{
DiskFile res_file = DiskFileSystem::OpenFile(_str("Pack_{}/{}", pack_name, kv.first), true);
RUNTIME_ASSERT(res_file);
bool res_file_write_ok = res_file.Write(kv.second.data(), (uint)kv.second.size());
RUNTIME_ASSERT(res_file_write_ok);
}
}
else
{
WriteLog("Copy raw resource files {}...\n", resources.GetFilesCount());
bool del_raw_ok = DiskFileSystem::DeleteDir("Raw");
RUNTIME_ASSERT(del_raw_ok);
while (resources.MoveNext())
{
File file = resources.GetCurFile();
DiskFile raw_file = DiskFileSystem::OpenFile(_str("Raw/{}", file.GetPath()), true);
RUNTIME_ASSERT(raw_file);
bool raw_file_write_ok = raw_file.Write(file.GetBuf(), file.GetFsize());
RUNTIME_ASSERT(raw_file_write_ok);
}
}
}
}
}
catch (std::exception& ex)
{
ReportException(ex);
return 1;
}
return 0;
}
| 39.341969 | 117 | 0.539313 | Marsel24 |
fc8a7ab0cae187e0fa4842574676f7b29c924e63 | 843 | cpp | C++ | libhpx/process/allreduce_actions.cpp | luglio/hpx5 | 6cbeebb8e730ee9faa4487dba31a38e3139e1ce7 | [
"BSD-3-Clause"
] | 1 | 2019-11-05T21:11:32.000Z | 2019-11-05T21:11:32.000Z | libhpx/process/allreduce_actions.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | null | null | null | libhpx/process/allreduce_actions.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | 3 | 2019-06-21T07:05:43.000Z | 2020-11-21T15:24:04.000Z | // =============================================================================
// High Performance ParalleX Library (libhpx)
//
// Copyright (c) 2013-2017, Trustees of Indiana University,
// All rights reserved.
//
// This software may be modified and distributed under the terms of the BSD
// license. See the COPYING file for details.
//
// This software was created at the Indiana University Center for Research in
// Extreme Scale Technologies (CREST).
// =============================================================================
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <libhpx/action.h>
#include <libhpx/collective.h>
#include <libhpx/debug.h>
#include "allreduce.h"
static int _allreduce_bcast_comm_handler(allreduce_t *r, void *value,
size_t bytes) {
}
| 25.545455 | 80 | 0.558719 | luglio |
fc8be0f362f7f6205147245cf71f563e2072da42 | 10,700 | cpp | C++ | AcfDetect/acfDetect.cpp | Ewenwan/RVAF | 4f6dd3e3fa0ca55b43582995b8eff83c864163eb | [
"BSD-2-Clause"
] | 22 | 2017-08-23T04:46:08.000Z | 2021-11-08T08:51:59.000Z | AcfDetect/acfDetect.cpp | Ewenwan/RVAF | 4f6dd3e3fa0ca55b43582995b8eff83c864163eb | [
"BSD-2-Clause"
] | 1 | 2017-08-23T12:31:24.000Z | 2017-08-23T13:42:09.000Z | AcfDetect/acfDetect.cpp | P-Chao/RVAF | 3b7ad68cf1bc4003d9c5ccd62ac45b7d4103fc2a | [
"BSD-2-Clause"
] | 12 | 2017-10-10T01:52:12.000Z | 2020-01-05T14:02:55.000Z | /*
* acfDetect.cpp
* for VisualStudio & opencv3.0.0
*
* Created on: Aug 2, 2015
* Author: Peng Chao
*
*/
#include <stdio.h>
#include <vector>
#include <opencv2\opencv.hpp>
#include "acfDetect.h"
#include "chnsPyramid.h"
#include "disp.h"
#include <glog\logging.h>
using namespace std;
/// One of the @link comparison_functors comparison functors@endlink.
template<typename _Tp>
struct greater : public binary_function<_Tp, _Tp, bool>{
bool operator()(const _Tp& __x, const _Tp& __y) const{
return __x > __y; }
};
namespace pc{
static void SuppressResult(vector<DetectResult>& ri, vector<DetectResult>& ro, float nms = 0.65f);
AcfDetector::AcfDetector(char* path)
{
uint32_t size;
FILE *fp = fopen(path, "rb+");
if(fp == NULL )
{
LOG(FATAL) << "Open detector error!";
fprintf(stderr, "Open detector error\n");
exit(1);
}
fread(&this->nTreeNodes, 4, 1, fp);
fread(&this->nTrees, 4, 1, fp);
size = this->nTreeNodes * this->nTrees;
this->fids = new uint32_t[size];
this->thrs = new float[size];
this->child = new uint32_t[size];
this->hs = new float[size];
this->weights = new float[size];
this->depth = new uint32_t[size];
fread(this->fids, size * 4, 1, fp);
fread(this->thrs, size * 4, 1, fp);
fread(this->child, size * 4, 1, fp);
fread(this->hs, size * 4, 1, fp);
fread(this->weights, size * 4, 1, fp);
fread(this->depth, size * 4, 1, fp);
fread(&this->treeDepth, 4, 1, fp);
fread(&this->stride, 4, 1, fp);
fread(&this->cascThr, 4, 1, fp);
fread(&this->modelHt, 4, 1, fp);
fread(&this->modelWd, 4, 1, fp);
fread(&this->modelPadHt, 4, 1, fp);
fread(&this->modelPadWd, 4, 1, fp);
fclose(fp);
}
void AcfDetector::Open(char* path)
{
uint32_t size;
FILE *fp = fopen(path, "rb+");
if (fp == NULL)
{
LOG(FATAL) << "Open detector error!";
fprintf(stderr, "Open detector error\n");
exit(1);
}
fread(&this->nTreeNodes, 4, 1, fp);
fread(&this->nTrees, 4, 1, fp);
size = this->nTreeNodes * this->nTrees;
this->fids = new uint32_t[size];
this->thrs = new float[size];
this->child = new uint32_t[size];
this->hs = new float[size];
this->weights = new float[size];
this->depth = new uint32_t[size];
fread(this->fids, size * 4, 1, fp);
fread(this->thrs, size * 4, 1, fp);
fread(this->child, size * 4, 1, fp);
fread(this->hs, size * 4, 1, fp);
fread(this->weights, size * 4, 1, fp);
fread(this->depth, size * 4, 1, fp);
fread(&this->treeDepth, 4, 1, fp);
fread(&this->stride, 4, 1, fp);
fread(&this->cascThr, 4, 1, fp);
fread(&this->modelHt, 4, 1, fp);
fread(&this->modelWd, 4, 1, fp);
fread(&this->modelPadHt, 4, 1, fp);
fread(&this->modelPadWd, 4, 1, fp);
fclose(fp);
}
AcfDetector::~AcfDetector()
{
delete [] this->fids;
delete [] this->thrs;
delete [] this->child;
delete [] this->hs;
delete [] this->weights;
delete [] this->depth;
}
inline void GetChild(float* chns1, uint32_t* cids, uint32_t* fids,
float* thrs, uint32_t offset, uint32_t& k0, uint32_t& k)
{
float ftr = chns1[cids[fids[k]]];
k = (ftr < thrs[k]) ? 1 : 2;
k0 = k += k0 * 2;
k += offset;
}
void AcfDetector::Detect(Channels& chns, int32_t shrink, vector<DetectResult>& result, float epipolarLine)
{
// Get dimensions and constants
const int32_t height = chns.gradMag.size().height;
const int32_t width = chns.gradMag.size().width;
const int32_t nChns = 10;
const int32_t height1 = (int32_t)ceil(float(height * shrink - modelPadHt + 1) / stride);
const int32_t width1 = (int32_t)ceil(float(width * shrink - modelPadWd + 1) / stride);
// Construct cids array
int32_t nFtrs = modelPadHt / shrink * modelPadWd / shrink * nChns;
uint32_t *cids = new uint32_t[nFtrs];
int32_t m = 0;
for(int32_t z = 0; z < nChns; z++)
{
for(int32_t c = 0; c < modelPadWd / shrink; c++)
{
for(int32_t r = 0; r < modelPadHt / shrink; r++)
{
cids[m++] = z * width * height + r * width + c;
}
}
}
int SearchLine = -1;
if (epipolarLine > 0){
SearchLine = (epipolarLine + 0.5) / stride;
if (SearchLine < 0 && SearchLine <= height1){
SearchLine = -1;
}
}
// Apply classifier to each patch
#if(USE_OPENMP == -1)
int32_t c;
#pragma omp parallel for private(c) num_threads(3)
for(c = 0; c < width1; c++)
#else
for(int32_t c = 0; c < width1; c++)
#endif
{
for(int32_t r = 0; r < height1; r++)
{
if (SearchLine > 0){
if (r < SearchLine){
continue;
}
if (r > SearchLine){
break;
}
}
float h = 0, *chns1 = chns.data + (r * stride / shrink) * width + (c * stride / shrink);
if(treeDepth == 1)
{
// specialized case for treeDepth==1
for(uint32_t t = 0; t < nTrees; t++)
{
uint32_t offset = t * nTreeNodes, k = offset, k0 = 0;
GetChild(chns1, cids, fids, thrs, offset, k0, k);
h += hs[k];
if(h <= cascThr)
{
break;
}
}
}
else if(treeDepth == 2)
{ // specialized case for treeDepth==2
for(uint32_t t = 0; t < nTrees; t++)
{
uint32_t offset = t * nTreeNodes, k = offset, k0 = 0;
GetChild(chns1, cids, fids, thrs, offset, k0, k);
GetChild(chns1, cids, fids, thrs, offset, k0, k);
h += hs[k];
if(h <= cascThr)
{
break;
}
}
}
else if(treeDepth > 2)
{
// specialized case for treeDepth>2
for(uint32_t t = 0; t < nTrees; t++)
{
uint32_t offset = t * nTreeNodes, k = offset, k0 = 0;
for(uint32_t i = 0; i < treeDepth; i++)
{
GetChild(chns1, cids, fids, thrs, offset, k0, k);
}
h += hs[k];
if(h <= cascThr)
{
break;
}
}
}
else
{
// general case (variable tree depth)
for(uint32_t t = 0; t < nTrees; t++)
{
uint32_t offset = t * nTreeNodes, k = offset, k0 = k;
while(child[k])
{
float ftr = chns1[cids[fids[k]]];
k = (ftr < thrs[k]) ? 1 : 0;
k0 = k = child[k0] - k + offset;
}
h += hs[k];
if(h <= cascThr)
{
break;
}
}
}
if(h > cascThr)
{
DetectResult res;
res.cs = c * stride;
res.modelWd = modelWd;
res.modelHt = modelHt;
res.rs = r * stride;
res.hs = h;
#if(USE_OPENMP == -1)
#pragma omp critical (result)
{
result.push_back(res);
}
#else
result.push_back(res);
#endif
}
}
}
delete [] cids;
}
void AcfDetectImg(Mat& img, PyramidOpt& opt, AcfDetector& detector, vector<DetectResult>& result, float nms)
{
Pyramid pyramid;
vector<DetectResult> res;
int32_t shiftX, shiftY;
ChnsPyramid(img, opt, pyramid);
result.clear();
#if(USE_OPENMP == 1)
int32_t i;
#pragma omp parallel for private(i) num_threads(3)
for(i = 0; i < pyramid.nScales; i++)
#else
for(int32_t i = 0; i < pyramid.nScales; i++)
#endif
{
vector<DetectResult> r0;
detector.Detect(pyramid.data[i], opt.chnsOpt.shrink, r0);
shiftX = (detector.modelPadWd - detector.modelWd) / 2 - opt.pad.width;
shiftY = (detector.modelPadHt - detector.modelHt) / 2 - opt.pad.height;
for(uint32_t j = 0; j < r0.size(); j++)
{
DetectResult r = r0[j];
r.cs = (r.cs + shiftX) / pyramid.scalesWd[i];
r.rs = (r.rs + shiftY) / pyramid.scalesHt[i];
r.modelWd = detector.modelWd / pyramid.scales[i];
r.modelHt = detector.modelHt / pyramid.scales[i];
r.scaleindex = i;
#if(USE_OPENMP == 1)
#pragma omp critical (result)
#endif
{
res.push_back(r);
}
}
}
for(uint32_t i = 0; i < pyramid.data.size(); i++)
{
ChnsDataRelease(pyramid.data[i]);
}
SuppressResult(res, result, nms);
}
// AcfDetectImg Function For Stereo Vision Application
void AcfDetectImgScale(Mat& img, PyramidOpt& opt, AcfDetector& detector, vector<DetectResult>& result,
int scaleindex, float epipolarLine, float nms)
{
Pyramid pyramid;
vector<DetectResult> res;
int32_t shiftX, shiftY;
ChnsPyramidScale(img, opt, pyramid, scaleindex);
result.clear();
#if(USE_OPENMP == 1)
int32_t i;
#pragma omp parallel for private(i) num_threads(3)
for (i = 0; i < pyramid.nScales; i++)
#else
for (int32_t i = 0; i < pyramid.nScales; i++)
#endif
{
if (epipolarLine > 0){
shiftY = (detector.modelPadHt - detector.modelHt) / 2 - opt.pad.height;
epipolarLine = pyramid.scalesHt[scaleindex] * epipolarLine - shiftY;
}
vector<DetectResult> r0;
detector.Detect(pyramid.data[i], opt.chnsOpt.shrink, r0, epipolarLine);
shiftX = (detector.modelPadWd - detector.modelWd) / 2 - opt.pad.width;
shiftY = (detector.modelPadHt - detector.modelHt) / 2 - opt.pad.height;
for (uint32_t j = 0; j < r0.size(); j++)
{
DetectResult r = r0[j];
r.cs = (r.cs + shiftX) / pyramid.scalesWd[scaleindex];
r.rs = (r.rs + shiftY) / pyramid.scalesHt[scaleindex];
r.modelWd = detector.modelWd / pyramid.scales[scaleindex];
r.modelHt = detector.modelHt / pyramid.scales[scaleindex];
r.scaleindex = scaleindex;
#if(USE_OPENMP == 1)
#pragma omp critical (result)
#endif
{
res.push_back(r);
}
}
}
for (uint32_t i = 0; i < pyramid.data.size(); i++)
{
ChnsDataRelease(pyramid.data[i]);
}
SuppressResult(res, result, nms);
}
void SuppressResult(vector<DetectResult>& ri, vector<DetectResult>& ro, float nms)
{
bool* kp = new bool[ri.size()];
float* as = new float[ri.size()];
float* xs = new float[ri.size()];
float* xe = new float[ri.size()];
float* ys = new float[ri.size()];
float* ye = new float[ri.size()];
// For each i suppress all j st j > i and area-overlap > overlap
std::sort(ri.begin(), ri.end(), greater<DetectResult>());
for(uint32_t i = 0; i < ri.size(); i++)
{
kp[i] = true;
as[i] = ri[i].modelWd * ri[i].modelHt;
xs[i] = ri[i].cs;
xe[i] = xs[i] + ri[i].modelWd;
ys[i] = ri[i].rs;
ye[i] = ys[i] + ri[i].modelHt;
}
for(uint32_t i = 0; i < ri.size(); i++)
{
if(kp[i] == 0)
{
continue;
}
for(uint32_t j = i + 1; j < ri.size(); j++)
{
if(kp[j] == false)
{
continue;
}
float iw = min(xe[i], xe[j]) - max(xs[i], xs[j]);
if(iw <= 0)
{
continue;
}
float ih = min(ye[i], ye[j]) - max(ys[i], ys[j]);
if(ih <= 0)
{
continue;
}
float u = min(as[i], as[j]);
float o = iw * ih / u;
if(o > nms)
{
kp[j] = false;
}
}
}
for(uint32_t i = 0; i < ri.size(); i++)
{
if(kp[i] == true)
{
ro.push_back(ri[i]);
}
}
delete [] kp;
delete [] as;
}
} | 24.044944 | 109 | 0.573551 | Ewenwan |
fc8c3b670af0d9055a5985eb3a9501ce91d7936b | 3,561 | cpp | C++ | src/system/keyboard.cpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | 2 | 2017-12-10T10:59:48.000Z | 2017-12-13T04:11:14.000Z | src/system/keyboard.cpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | null | null | null | src/system/keyboard.cpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | null | null | null |
#include"keyboard.hpp"
#if defined(__linux__)
#include<cstdio>
#include<termios.h>
#include<unistd.h>
#include<fcntl.h>
namespace utility
{
namespace system
{
namespace keyboard
{
char read_one_char() noexcept
{
using std::getchar;
static termios __old, __new;
tcgetattr(STDIN_FILENO, &__old);
__new = __old;
__new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &__new);
char __res = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &__old);
return __res;
}
int kbhit() noexcept
{
using std::ungetc;
using std::getchar;
struct termios __old, __new;
int __res;
int __old_fcntl;
tcgetattr(STDIN_FILENO, &__old);
__new = __old;
__new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &__new);
__old_fcntl = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, __old_fcntl | O_NONBLOCK);
__res = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &__old);
fcntl(STDIN_FILENO, F_SETFL, __old_fcntl);
if(__res != EOF)
{
ungetc(__res, stdin);
return 1;
}
return 0;
}
}
}
}
#elif defined(__WIN32) || defined(__WIN64)
#include<conio.h>
#include<cstdio>
namespace utility
{
namespace system
{
namespace keyboard
{
int kbhit() noexcept
{
return ::_kbhit();
}
char read_one_char() noexcept
{
while(!keyboard::kbhit())
{ }
return getch();
}
}
}
}
#endif // ! system specific
namespace utility
{
namespace system
{
namespace keyboard
{
keyboard_key keyboard_one_step() noexcept
{
char __char = read_one_char();
if(__char == char{0x1B})
{
if(!keyboard::kbhit())
{ return keyboard_key::esc;}
if(keyboard::read_one_char() == '[')
{
if(!keyboard::kbhit())
{ return keyboard_key::unknown;}
__char = keyboard::read_one_char();
switch(__char)
{
case 'A':
return keyboard_key::up_arrow;
case 'B':
return keyboard_key::down_arrow;
case 'C':
return keyboard_key::right_arrow;
case 'D':
return keyboard_key::left_arrow;
case 'F':
return keyboard_key::end;
case 'H':
return keyboard_key::home;
case '2':
if(!keyboard::kbhit() || keyboard::read_one_char() != '~')
{ return keyboard_key::unknown;}
return keyboard_key::insert;
case '3':
if(!keyboard::kbhit() || keyboard::read_one_char() != '~')
{ return keyboard_key::unknown;}
return keyboard_key::del;
case '5':
if(!keyboard::kbhit() || keyboard::read_one_char() != '~')
{ return keyboard_key::unknown;}
return keyboard_key::page_up;
case '6':
if(!keyboard::kbhit() || keyboard::read_one_char() != '~')
{ return keyboard_key::unknown;}
return keyboard_key::page_down;
default:
return keyboard_key::unknown;
}
}
}
return static_cast<keyboard_key>(__char);
}
}
}
}
| 22.826923 | 74 | 0.508846 | SakuraLife |
fc8cae25931eb5d02501e6c69c2e012d9290587e | 33,137 | cpp | C++ | Ca3DE/Server/Server.cpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | Ca3DE/Server/Server.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | Ca3DE/Server/Server.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#include "Server.hpp"
#include "ServerWorld.hpp"
#include "ClientInfo.hpp"
#include "../GameInfo.hpp"
#include "../NetConst.hpp"
#include "../PlayerCommand.hpp"
#include "ConsoleCommands/Console.hpp"
#include "ConsoleCommands/ConsoleStringBuffer.hpp"
#include "ConsoleCommands/ConsoleInterpreter.hpp"
#include "ConsoleCommands/ConVar.hpp"
#include "ConsoleCommands/ConFunc.hpp"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
extern "C"
{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <errno.h>
#define WSAECONNRESET ECONNRESET
#define WSAEMSGSIZE EMSGSIZE
#define WSAEWOULDBLOCK EWOULDBLOCK
#endif
extern WinSockT* g_WinSock;
extern ConVarT Options_ServerPortNr;
static unsigned long GlobalClientNr;
static ServerT* ServerPtr=NULL;
static ConVarT ServerRCPassword("sv_rc_password", "", ConVarT::FLAG_MAIN_EXE, "The password the server requires for remote console access.");
int ServerT::ConFunc_changeLevel_Callback(lua_State* LuaState)
{
if (!ServerPtr) return luaL_error(LuaState, "The local server is not available.");
std::string NewWorldName=(lua_gettop(LuaState)<1) ? "" : luaL_checkstring(LuaState, 1);
std::string PathName ="Games/" + ServerPtr->m_GameInfo.GetName() + "/Worlds/" + NewWorldName + ".cw";
if (NewWorldName=="")
{
// changeLevel() or changeLevel("") was called, so change into the (implicit) "no map loaded" state.
// First disconnect from / drop all the clients.
// Note that this is a bit different from calling DropClient() for everyone though.
for (unsigned long ClNr=0; ClNr<ServerPtr->ClientInfos.Size(); ClNr++)
{
ClientInfoT* ClInfo=ServerPtr->ClientInfos[ClNr];
if (ClInfo->ClientState==ClientInfoT::Zombie) continue;
NetDataT NewReliableMsg;
NewReliableMsg.WriteByte (SC1_DropClient);
NewReliableMsg.WriteLong (ClInfo->EntityID);
NewReliableMsg.WriteString("Server has been stopped (map unloaded).");
ClInfo->ReliableDatas.PushBack(NewReliableMsg.Data);
// The client was disconnected, but it goes into a zombie state for a few seconds to make sure
// any final reliable message gets resent if necessary.
// The time-out will finally remove the zombie entirely when its zombie-time is over.
ClInfo->ClientState =ClientInfoT::Zombie;
ClInfo->TimeSinceLastMessage=0.0;
}
delete ServerPtr->World;
ServerPtr->World =NULL;
ServerPtr->WorldName="";
ServerPtr->GuiCallback.OnServerStateChanged("idle");
return 0;
}
// changeLevel("mapname") was called, so perform a proper map change.
CaServerWorldT* NewWorld=NULL;
try
{
NewWorld=new CaServerWorldT(PathName.c_str(), ServerPtr->m_ModelMan, ServerPtr->m_GuiRes);
}
catch (const WorldT::LoadErrorT& E) { return luaL_error(LuaState, E.Msg); }
delete ServerPtr->World;
ServerPtr->World =NewWorld;
ServerPtr->WorldName=NewWorldName;
// Stati der verbundenen Clients auf MapTransition setzen.
for (unsigned long ClientNr=0; ClientNr<ServerPtr->ClientInfos.Size(); ClientNr++)
{
ClientInfoT* ClInfo=ServerPtr->ClientInfos[ClientNr];
if (ClInfo->ClientState==ClientInfoT::Zombie) continue;
// A player entity will be assigned and the SC1_WorldInfo message be sent in the main loop.
ClInfo->InitForNewWorld(0);
}
Console->Print("Level changed on server.\n");
ServerPtr->GuiCallback.OnServerStateChanged("maploaded");
return 0;
}
static ConFuncT ConFunc_changeLevel("changeLevel", ServerT::ConFunc_changeLevel_Callback, ConFuncT::FLAG_MAIN_EXE, "Makes the server load a new level.");
// This console function is called at any time (e.g. when we're NOT thinking)...
/*static*/ int ServerT::ConFunc_runMapCmd_Callback(lua_State* LuaState)
{
if (!ServerPtr) return luaL_error(LuaState, "The local server is not available.");
if (!ServerPtr->World) return luaL_error(LuaState, "There is no world loaded in the local server.");
// ServerPtr->World->GetScriptState_OLD().DoString(luaL_checkstring(LuaState, 1));
// return 0;
return luaL_error(LuaState, "Sorry, this function is not implemented at this time.");
}
static ConFuncT ConFunc_runMapCmd("runMapCmd", ServerT::ConFunc_runMapCmd_Callback, ConFuncT::FLAG_MAIN_EXE,
"Runs the given command string in the context of the current map/entity script.");
ServerT::ServerT(const GameInfoT& GameInfo, const GuiCallbackI& GuiCallback_, ModelManagerT& ModelMan, cf::GuiSys::GuiResourcesT& GuiRes)
: ServerSocket(g_WinSock->GetUDPSocket(Options_ServerPortNr.GetValueInt())),
m_GameInfo(GameInfo),
WorldName(""),
World(NULL),
GuiCallback(GuiCallback_),
m_ModelMan(ModelMan),
m_GuiRes(GuiRes)
{
if (ServerSocket==INVALID_SOCKET) throw InitErrorT(cf::va("Unable to obtain UDP socket on port %i.", Options_ServerPortNr.GetValueInt()));
assert(ServerPtr==NULL);
ServerPtr=this; // TODO: Turn the ServerT class into a singleton?
}
ServerT::~ServerT()
{
for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++)
delete ClientInfos[ClientNr];
delete World;
World=NULL;
assert(ServerPtr==this);
ServerPtr=NULL;
assert(ServerSocket!=INVALID_SOCKET);
closesocket(ServerSocket);
ServerSocket=INVALID_SOCKET;
}
void ServerT::MainLoop()
{
// Bestimme die FrameTime des letzten Frames
float FrameTime=float(Timer.GetSecondsSinceLastCall());
if (FrameTime<0.0001f) FrameTime=0.0001f;
if (FrameTime> 10.0f) FrameTime= 10.0f;
// Check Client Time-Outs
for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++)
{
ClientInfos[ClientNr]->TimeSinceLastMessage+=FrameTime;
if (ClientInfos[ClientNr]->ClientState==ClientInfoT::Zombie)
{
if (ClientInfos[ClientNr]->TimeSinceLastMessage>6.0)
{
delete ClientInfos[ClientNr];
ClientInfos[ClientNr]=ClientInfos[ClientInfos.Size()-1];
ClientInfos.DeleteBack();
ClientNr--;
continue;
}
}
else // Online oder Wait4MapInfoACK
{
if (ClientInfos[ClientNr]->TimeSinceLastMessage>120.0)
{
DropClient(ClientNr, "Timed out!");
ClientInfos[ClientNr]->TimeSinceLastMessage=300.0; // Don't bother with zombie state
}
}
}
// Warte, bis wir neue Packets bekommen oder das Frame zu Ende geht
fd_set ReadabilitySocketSet;
timeval TimeOut;
TimeOut.tv_sec =0;
TimeOut.tv_usec=10*1000;
#if defined(_WIN32) && defined(__WATCOMC__)
#pragma warning 555 9;
#endif
FD_ZERO(&ReadabilitySocketSet);
FD_SET(ServerSocket, &ReadabilitySocketSet);
#if defined(_WIN32) && defined(__WATCOMC__)
#pragma warning 555 4;
#endif
// select() bricht mit der Anzahl der lesbar gewordenen Sockets ab, 0 bei TimeOut oder SOCKET_ERROR im Fehlerfall.
const int Result=select(int(ServerSocket+1), &ReadabilitySocketSet, NULL, NULL, &TimeOut);
if (Result==SOCKET_ERROR)
{
Console->Print(cf::va("ERROR: select() returned WSA fail code %u\n", WSAGetLastError()));
}
else if (Result!=0)
{
// In dieser Schleife werden solange die Packets der Clients abgeholt, bis keine mehr da sind (would block).
unsigned long MaxPacketsCount=20;
while (MaxPacketsCount--)
{
try
{
NetDataT InData;
NetAddressT SenderAddress=InData.Receive(ServerSocket);
if (GameProtocol1T::IsIncomingMessageOutOfBand(InData))
{
ProcessConnectionLessPacket(InData, SenderAddress);
}
else
{
// ClientNr des Absenders heraussuchen
unsigned long ClientNr;
for (ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++)
if (SenderAddress==ClientInfos[ClientNr]->ClientAddress) break;
// Prüfe ClientNr
if (ClientNr>=ClientInfos.Size())
{
Console->Warning(cf::va("Client %s is not connected! Packet ignored!\n", SenderAddress.ToString()));
// Hier evtl. ein bad / disconnect / kick packet schicken?
continue;
}
// Was Zombies senden, interessiert uns nicht mehr
if (ClientInfos[ClientNr]->ClientState==ClientInfoT::Zombie) continue;
// Es ist eine gültige Nachricht (eines Online- oder Wait4MapInfoACK-Client) - bearbeite sie!
GlobalClientNr=ClientNr;
assert(ServerPtr==this);
ClientInfos[ClientNr]->TimeSinceLastMessage=0.0; // Do not time-out
ClientInfos[ClientNr]->GameProtocol.ProcessIncomingMessage(InData, ProcessInGamePacketHelper);
}
}
catch (const NetDataT::WinSockAPIError& E)
{
if (E.Error==WSAEWOULDBLOCK)
{
// Break the while-loop, there is no point in trying to receive further messages right now.
// (This is also the reason why we cannot test E.Error in a switch-case block here.)
break;
}
// Deal with other errors that don't have to break the while-loop above.
switch (E.Error)
{
case WSAECONNRESET:
{
// Receiving this error indicates that a previous send operation resulted in an ICMP "Port Unreachable" message.
// This in turn occurs whenever a client disconnected without us having received the proper disconnect message.
// If we did nothing here, this message would be received until we stopped sending more messages to the client,
// that is, until we got rid of the client due to time-out.
// Try to find the offending client, and drop it.
bool FoundOffender=false;
for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++)
if (E.Address==ClientInfos[ClientNr]->ClientAddress)
{
if (ClientInfos[ClientNr]->ClientState!=ClientInfoT::Zombie)
DropClient(ClientNr, "ICMP message: client port unreachable!");
// Don't bother with the zombie state, rather remove this client entirely right now.
delete ClientInfos[ClientNr];
ClientInfos[ClientNr]=ClientInfos[ClientInfos.Size()-1];
ClientInfos.DeleteBack();
FoundOffender=true;
break;
}
if (!FoundOffender)
{
// If at all, this should happen only occassionally, e.g. because we sent something to a client
// that was removed in the time-out check above.
Console->Warning(cf::va("Indata.Receive() returned ECONNRESET from unknown address %s.\n", E.Address.ToString()));
}
break;
}
case WSAEMSGSIZE:
{
Console->Warning(cf::va("Sv: InData.Receive() returned WSA fail code %u (WSAEMSGSIZE). Sender %s. Packet ignored.\n", E.Error, E.Address.ToString()));
break;
}
default:
{
Console->Warning(cf::va("Sv: InData.Receive() returned WSA fail code %u. Sender %s. Packet ignored.\n", E.Error, E.Address.ToString()));
break;
}
}
}
}
}
// Prüfe, ob das ServerTicInterval schon um ist, und führe ggf. einen "ServerTic" aus.
/* TimeSinceLastServerTic+=FrameTime;
if (TimeSinceLastServerTic<ServerTicInterval-0.001)
{
// Das ServerTicInterval ist noch nicht rum!
// Falls wir nicht alleine (dedicated) laufen, mache sofort mit dem Client weiter.
if (!ServerOnly) return true;
// Andernfalls (dedicated), verschlafe den Rest des ServerTicIntervals oder bis ein Netzwerk-Paket eingeht.
fd_set ReadabilitySocketSet;
timeval TimeOut;
const float RemainingSeconds=ServerTicInterval-TimeSinceLastServerTic;
TimeOut.tv_sec =RemainingSeconds; // Nachkomma-Anteil wird abgeschnitten
TimeOut.tv_usec=(RemainingSeconds-float(TimeOut.tv_sec))*1000000.0;
#pragma warning 555 9;
FD_ZERO(&ReadabilitySocketSet);
FD_SET(ServerSocket, &ReadabilitySocketSet);
#pragma warning 555 4;
// select() bricht mit der Anzahl der lesbar gewordenen Sockets ab, 0 bei TimeOut oder SOCKET_ERROR im Fehlerfall.
// Wie auch immer - wir ignorieren den Rückgabewert.
select(ServerSocket+1, &ReadabilitySocketSet, NULL, NULL, &TimeOut);
return true;
} */
if (World)
{
// Überführe die ServerWorld über die Zeit 'FrameTime' in den nächsten Zustand.
// Beachte: Es werden u.a. alle bis hierhin eingegangenen PlayerCommands verarbeitet.
// Das ist wichtig für die Prediction, weil wir unten beim Senden mit den Sequence-Nummern des Game-Protocols
// bestätigen, daß wir alles bis zur bestätigten Sequence-Nummer gesehen UND VERARBEITET haben!
// Insbesondere muß dieser Aufruf daher zwischen dem Empfangen der PlayerCommand-Packets und dem Senden der
// nächsten Delta-Update-Messages liegen (WriteClientDeltaUpdateMessages()).
World->Think(FrameTime /*TimeSinceLastServerTic*/, ClientInfos);
// TimeSinceLastServerTic=0;
// All pending player commands have been processed, now clean them up for the next frame.
for (unsigned int ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++)
{
ClientInfoT* CI = ClientInfos[ClientNr];
ArrayT<PlayerCommandT>& PPCs = CI->PendingPlayerCommands;
if (PPCs.Size() == 0) continue;
CI->PreviousPlayerCommand = PPCs[PPCs.Size() - 1];
PPCs.Overwrite();
}
// If a client has newly joined the game:
// - create a human player entity for it,
// - send it the related world info message.
for (unsigned int ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++)
{
ClientInfoT* CI = ClientInfos[ClientNr];
if (CI->ClientState == ClientInfoT::Wait4MapInfoACK && CI->EntityID == 0)
{
CI->EntityID = World->InsertHumanPlayerEntity(CI->PlayerName, CI->ModelName, ClientNr);
if (CI->EntityID == 0)
{
DropClient(ClientNr, "Inserting the player entity failed.");
continue;
}
// The client remains in Wait4MapInfoACK state until it has ack'ed this message.
NetDataT NewReliableMsg;
NewReliableMsg.WriteByte (SC1_WorldInfo);
NewReliableMsg.WriteString(m_GameInfo.GetName());
NewReliableMsg.WriteString(WorldName);
NewReliableMsg.WriteLong (CI->EntityID);
CI->ReliableDatas.PushBack(NewReliableMsg.Data);
}
}
// Update the connected clients according to the new (now current) world state.
for (unsigned long ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++)
{
ClientInfoT* CI = ClientInfos[ClientNr];
// Prepare reliable BaseLine messages for newly created entities that the client
// does not yet know about. CI->BaseLineFrameNr is the server frame number up to
// which the client has received and acknowledged all BaseLines. That is, BaseLine
// messages are created for entities whose BaseLineFrameNr is larger than that.
//
// Note that after this, no further entities can be added to the world in the
// *current* frame, but only in the next!
CI->BaseLineFrameNr = World->WriteClientNewBaseLines(CI->BaseLineFrameNr, CI->ReliableDatas);
// Update the client's frame info corresponding to the the current server frame.
World->UpdateFrameInfo(*CI);
}
}
// Sende die aufgestauten ReliableData und die hier "dynamisch" erzeugten UnreliableData
// (bestehend aus den Delta-Update-Messages (FrameInfo+EntityUpdates)) an die für sie bestimmten Empfänger.
for (unsigned long ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++)
{
ClientInfoT* CI = ClientInfos[ClientNr];
ClientInfos[ClientNr]->TimeSinceLastUpdate+=FrameTime;
// Only send something after a minimum interval.
if (CI->TimeSinceLastUpdate < 0.05) continue;
NetDataT UnreliableData;
if (World && CI->ClientState != ClientInfoT::Zombie)
{
World->WriteClientDeltaUpdateMessages(*CI, UnreliableData);
}
try
{
// Note that we intentionally also send to clients in Wait4MapInfoACK and Zombie
// states, in order to keep the handling (with possible re-transfers) of reliable
// data going.
// TODO: Für Zombies statt rel.+unrel. Data nur leere Buffer übergeben! VORHER aber die DropMsg in ServerT::DropClient SENDEN!
CI->GameProtocol.GetTransmitData(CI->ReliableDatas, UnreliableData.Data).Send(ServerSocket, CI->ClientAddress);
}
catch (const GameProtocol1T::MaxMsgSizeExceeded& /*E*/) { Console->Warning(cf::va("(ClientNr==%u, EntityID==%u) caught a GameProtocol1T::MaxMsgSizeExceeded exception!", ClientNr, CI->EntityID)); }
catch (const NetDataT::WinSockAPIError& E ) { Console->Warning(cf::va("caught a NetDataT::WinSockAPIError exception (error %u)!", E.Error)); }
catch (const NetDataT::MessageLength& E ) { Console->Warning(cf::va("caught a NetDataT::MessageLength exception (wanted %u, actual %u)!", E.Wanted, E.Actual)); }
CI->ReliableDatas.Clear();
CI->TimeSinceLastUpdate = 0;
}
}
void ServerT::DropClient(unsigned long ClientNr, const char* Reason)
{
// Calling code should not try to drop a client what has been dropped before and thus is in zombie state already.
assert(ClientInfos[GlobalClientNr]->ClientState!=ClientInfoT::Zombie);
// Broadcast reliable DropClient message to everyone, including the client to be dropped.
// This messages includes the entity ID and the reason for the drop.
for (unsigned long ClNr=0; ClNr<ClientInfos.Size(); ClNr++)
{
NetDataT NewReliableMsg;
NewReliableMsg.WriteByte (SC1_DropClient);
NewReliableMsg.WriteLong (ClientInfos[ClientNr]->EntityID);
NewReliableMsg.WriteString(Reason);
ClientInfos[ClNr]->ReliableDatas.PushBack(NewReliableMsg.Data);
// TODO: HIER DIE MESSAGE AUCH ABSENDEN!
// KANN DANN UNTEN IN DER HAUPTSCHLEIFE FÜR ZOMBIES DIE REL+UNREL. DATA KOMPLETT UNTERDRUECKEN!
}
Console->Print(cf::va("Dropped client %u (EntityID %u, PlayerName '%s'). Reason: %s\n", ClientNr, ClientInfos[ClientNr]->EntityID, ClientInfos[ClientNr]->PlayerName.c_str(), Reason));
// The server world will clean-up the client's now abandoned human player entity at
// ClientInfos[ClientNr]->EntityID automatically, as no (non-zombie) client is referring to it any longer.
// From the view of the remaining clients this is the same as with any other entity that has been deleted.
// The client was disconnected, but it goes into a zombie state for a few seconds to make sure
// any final reliable message gets resent if necessary.
// The time-out will finally remove the zombie entirely when its zombie-time is over.
ClientInfos[ClientNr]->ClientState =ClientInfoT::Zombie;
ClientInfos[ClientNr]->TimeSinceLastMessage=0.0;
}
void ServerT::ProcessConnectionLessPacket(NetDataT& InData, const NetAddressT& SenderAddress)
{
unsigned long PacketID=InData.ReadLong();
// Die Antwort auf ein "connection-less" Packet beginnt mit 0xFFFFFFFF, gefolgt von der PacketID,
// sodaß das Rückpacket unten nur noch individuell beendet werden muß.
NetDataT OutData;
OutData.WriteLong(0xFFFFFFFF);
OutData.WriteLong(PacketID);
// Der Typ dieser Nachricht entscheidet, wie es weitergeht
try
{
switch (InData.ReadByte())
{
case CS0_NoOperation:
// Packet is a "no operation" request, thus we won't accomplish anything
Console->Print("PCLP: Packet evaluated to NOP.\n");
break;
case CS0_Ping:
Console->Print("PCLP: Acknowledging inbound ping.\n");
OutData.WriteByte(SC0_ACK);
OutData.Send(ServerSocket, SenderAddress);
break;
case CS0_Connect:
{
// Connection request
Console->Print(cf::va("PCLP: Got a connection request from %s\n", SenderAddress.ToString()));
if (World==NULL)
{
Console->Print("No world loaded.\n");
OutData.WriteByte(SC0_NACK);
OutData.WriteString("No world loaded on server.");
OutData.Send(ServerSocket, SenderAddress);
break;
}
// Prüfe, ob wir die IP-Adr. und Port-Nr. des Clients schon haben, d.h. ob der Client schon connected ist.
// (Dann hat z.B. der Client schonmal einen connection request geschickt, aber unser Acknowledge niemals erhalten,
// oder wir haben seinen Disconnected-Request nicht erhalten und er versucht nun vor dem TimeOut einen neuen Connect.)
unsigned long ClientNr;
for (ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++)
if (SenderAddress==ClientInfos[ClientNr]->ClientAddress) break;
if (ClientNr<ClientInfos.Size())
{
Console->Print("Already listed.\n");
OutData.WriteByte(SC0_NACK);
OutData.WriteString("Already listed. Wait for timeout and try again.");
OutData.Send(ServerSocket, SenderAddress);
break;
}
if (ClientInfos.Size()>=32)
{
Console->Print("Server is full.\n");
OutData.WriteByte(SC0_NACK);
OutData.WriteString("Server is full.");
OutData.Send(ServerSocket, SenderAddress);
break;
}
const char* PlayerName=InData.ReadString();
const char* ModelName =InData.ReadString();
if (PlayerName==NULL || ModelName==NULL || InData.ReadOfl)
{
Console->Print("Bad player or model name.\n");
OutData.WriteByte(SC0_NACK);
OutData.WriteString("Bad player or model name.");
OutData.Send(ServerSocket, SenderAddress);
break;
}
ClientInfoT* CI = new ClientInfoT(SenderAddress, PlayerName, ModelName);
ClientInfos.PushBack(CI);
// A player entity will be assigned and the SC1_WorldInfo message be sent in the main loop.
// Dem Client bestätigen, daß er im Spiel ist und ab sofort in-game Packets zu erwarten hat.
OutData.WriteByte(SC0_ACK);
OutData.WriteString(m_GameInfo.GetName());
OutData.Send(ServerSocket, SenderAddress);
Console->Print(CI->PlayerName + " joined.\n");
break;
}
case CS0_Info:
// Dem Client Server-Infos schicken
Console->Print(cf::va("PCLP: Got an information request from %s\n", SenderAddress.ToString()));
OutData.WriteByte(SC0_NACK);
OutData.WriteString("Information is not yet available!");
OutData.Send(ServerSocket, SenderAddress);
break;
case CS0_RemoteConsoleCommand:
{
const char* Password=InData.ReadString(); if (!Password) break;
const char* Command =InData.ReadString(); if (!Command ) break;
// Make sure that at least 500ms pass between two successive remote commands.
;
Console->Print(cf::va("Remote console command received from %s: %s\n", SenderAddress.ToString(), Command));
// Make sure that the sv_rc_password is set (must be done in the config.lua file).
if (ServerRCPassword.GetValueString()=="")
{
Console->Print("Server rcon password not set.\n");
OutData.WriteByte(SC0_RccReply);
OutData.WriteString("Server rcon password not set.\n");
OutData.Send(ServerSocket, SenderAddress);
break;
}
// Make sure that the received password is valid.
if (Password!=ServerRCPassword.GetValueString())
{
Console->Print(cf::va("Invalid password \"%s\".\n", Password));
OutData.WriteByte(SC0_RccReply);
OutData.WriteString("Invalid password.\n");
OutData.Send(ServerSocket, SenderAddress);
break;
}
// Begin to temporarily redirect all console output.
cf::ConsoleStringBufferT RedirCon;
cf::ConsoleI* OldCon=Console;
Console=&RedirCon;
// Ok, it has been a valid remote console command - process it.
ConsoleInterpreter->RunCommand(Command);
// End of temporarily redirected output.
std::string Output=RedirCon.GetBuffer();
Console=OldCon;
Console->Print(Output);
// Send result to sender (wrt. max. network packet size, limit the string length to 1024-16 though).
if (Output.length()>1024-16) Output=std::string(Output, 0, 1024-16-4)+"...\n";
OutData.WriteByte(SC0_RccReply);
OutData.WriteString(Output.c_str());
OutData.Send(ServerSocket, SenderAddress);
break;
}
default:
Console->Print(cf::va("PCLP: WARNING: Unknown packet type received! Sender: %s\n", SenderAddress.ToString()));
}
}
catch (const NetDataT::WinSockAPIError& E) { Console->Warning(cf::va("PCLP: Answer failed (WSA error %u)!\n", E.Error)); }
catch (const NetDataT::MessageLength& E) { Console->Warning(cf::va("PCLP: Answer too long (wanted %u, actual %u)!\n", E.Wanted, E.Actual)); }
}
void ServerT::ProcessInGamePacketHelper(NetDataT& InData, unsigned long LastIncomingSequenceNr)
{
// The LastIncomingSequenceNr is unused now.
ServerPtr->ProcessInGamePacket(InData);
}
void ServerT::ProcessInGamePacket(NetDataT& InData)
{
// We can only get here when the client who sent the message is not listed as a zombie,
// and therefore (consequently) the World pointer must be valid, too.
assert(ClientInfos[GlobalClientNr]->ClientState!=ClientInfoT::Zombie);
assert(World);
// TODO: Wasn't it much easier to simply catch Array-index-out-of-bounds exceptions here?
while (!InData.ReadOfl && !(InData.ReadPos>=InData.Data.Size()))
{
char MessageType=InData.ReadByte();
switch (MessageType)
{
case CS1_PlayerCommand:
{
PlayerCommandT PlayerCommand;
const unsigned int PlCmdNr = InData.ReadLong();
PlayerCommand.FrameTime = InData.ReadFloat();
PlayerCommand.Keys = InData.ReadLong();
PlayerCommand.DeltaHeading = InData.ReadWord();
PlayerCommand.DeltaPitch = InData.ReadWord();
// PlayerCommand.DeltaBank = InData.ReadWord();
if (InData.ReadOfl) return; // Ignore the rest of the message!
// PlayerCommand-Messages eines Clients, der im Wait4MapInfoACK-State ist, gehören idR zur vorher gespielten World.
// Akzeptiere PlayerCommand-Messages daher erst (wieder), wenn der Client vollständig online ist.
if (ClientInfos[GlobalClientNr]->ClientState!=ClientInfoT::Online) break;
ClientInfos[GlobalClientNr]->PendingPlayerCommands.PushBack(PlayerCommand);
assert(ClientInfos[GlobalClientNr]->LastPlayerCommandNr < PlCmdNr);
ClientInfos[GlobalClientNr]->LastPlayerCommandNr = PlCmdNr;
break;
}
case CS1_Disconnect:
{
DropClient(GlobalClientNr, "He/She left the game.");
return; // Ignore the rest of the message!
}
case CS1_SayToAll:
{
const char* InMsg=InData.ReadString();
// Console messages seem to be a popular choice for attackers.
// Thus guard against problems.
if (InMsg==NULL || InData.ReadOfl)
{
Console->Print(cf::va("Bad say message from: %s\n", ClientInfos[GlobalClientNr]->PlayerName.c_str()));
break;
}
std::string OutMessage=ClientInfos[GlobalClientNr]->PlayerName+": "+InMsg;
// Limit the length of the message wrt. max. network packet size.
if (OutMessage.length()>1024-16) OutMessage=std::string(OutMessage, 0, 1024-16-4)+"...\n";
for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++)
{
// TODO: Statt hier ClientState!=Zombie abzufragen, lieber in DropClient schon die Drop-Message SENDEN,
// und beim Senden in der Hauptschleife für Zombies leere Buffer für rel. + unrel. Data übergeben!
if (ClientInfos[ClientNr]->ClientState!=ClientInfoT::Zombie)
{
NetDataT NewReliableMsg;
NewReliableMsg.WriteByte (SC1_ChatMsg);
NewReliableMsg.WriteString(OutMessage);
ClientInfos[ClientNr]->ReliableDatas.PushBack(NewReliableMsg.Data);
}
}
break;
}
case CS1_WorldInfoACK:
{
const char* ClientWorldName=InData.ReadString();
if (InData.ReadOfl || ClientWorldName==NULL || strlen(ClientWorldName)==0)
{
// UploadMap();
// Im Moment bei einem Fehler beim Client-WorldChange den Client einfach rausschmeißen!
DropClient(GlobalClientNr, "Failure on world change!");
return; // Ignore the rest of the message!
}
if (ClientWorldName==WorldName) ClientInfos[GlobalClientNr]->ClientState=ClientInfoT::Online;
break;
}
case CS1_FrameInfoACK:
{
const unsigned long LKFR=InData.ReadLong();
if (InData.ReadOfl) return; // Ignore the rest of the message!
ClientInfos[GlobalClientNr]->LastKnownFrameReceived=LKFR;
break;
}
default:
Console->Print(cf::va("WARNING: Unknown in-game message type '%3u' received!\n", MessageType));
Console->Print(cf::va(" Sender: %s\n", ClientInfos[GlobalClientNr]->PlayerName.c_str()));
return; // Ignore the rest of the message!
}
}
}
| 42.159033 | 204 | 0.600235 | dns |
475acc180a8a8ecd7f6d0ee5c09eca216228a616 | 477 | cpp | C++ | src/os/mock_os_functions.cpp | juruen/cavalieri | c3451579193fc8f081b6228ae295b463a0fd23bd | [
"MIT"
] | 54 | 2015-01-14T21:11:56.000Z | 2021-06-27T13:29:40.000Z | src/os/mock_os_functions.cpp | juruen/cavalieri | c3451579193fc8f081b6228ae295b463a0fd23bd | [
"MIT"
] | null | null | null | src/os/mock_os_functions.cpp | juruen/cavalieri | c3451579193fc8f081b6228ae295b463a0fd23bd | [
"MIT"
] | 10 | 2015-07-15T05:09:34.000Z | 2019-01-10T07:32:02.000Z | #include <os/mock_os_functions.h>
#include <algorithm>
ssize_t mock_os_functions::recv(int, void *buf, size_t len, int) {
auto min = std::min(len, buffer.size());
std::copy(buffer.begin(), buffer.begin() + min, static_cast<char*>(buf));
return min;
}
ssize_t mock_os_functions::write(int, void *buf, size_t count) {
auto min = std::min(count, buffer.capacity());
auto pbuf = static_cast<char*>(buf);
buffer.insert(buffer.end(), pbuf, pbuf + min);
return min;
}
| 29.8125 | 75 | 0.685535 | juruen |
475b396719f1106cc50c18ca28a10e414a6d9012 | 1,809 | cpp | C++ | hydrogels/theory/models/_cxx/engine.cpp | debeshmandal/brownian | bc5b2e00a04d11319c85e749f9c056b75b450ff7 | [
"MIT"
] | 3 | 2020-05-13T01:07:30.000Z | 2021-02-12T13:37:23.000Z | hydrogels/theory/models/_cxx/engine.cpp | debeshmandal/brownian | bc5b2e00a04d11319c85e749f9c056b75b450ff7 | [
"MIT"
] | 24 | 2020-06-04T13:48:57.000Z | 2021-12-31T18:46:52.000Z | hydrogels/theory/models/_cxx/engine.cpp | debeshmandal/brownian | bc5b2e00a04d11319c85e749f9c056b75b450ff7 | [
"MIT"
] | 1 | 2020-07-23T17:15:23.000Z | 2020-07-23T17:15:23.000Z | #include <Python.h>
#include "functions.hpp"
#include "utils.hpp"
static PyObject*
engine_addNumbers(PyObject* self, PyObject* args) {
// declare variables
double n1, n2, result;
// parse arguments
if (!PyArg_ParseTuple(args, "dd", &n1, &n2)) {
return NULL;
};
// function here
result = addNumbers(n1, n2);
// return correct Type
return PyFloat_FromDouble(result);
};
static PyObject*
engine_vectorNorm(PyObject* self, PyObject* args) {
PyObject* py_vect;
if (!PyArg_ParseTuple(args, "O", &py_vect)) {
return NULL;
}
std::vector<double> vect = listTupleToVector_Double(py_vect);
double result = vectorNorm(vect);
return PyFloat_FromDouble(result);
};
// Define docstrings
PyDoc_STRVAR(engine_docs, "Package for running iterative numerical simulations");
PyDoc_STRVAR(engine_addNumbers_docs, "addNumbers(n1 : number, n2 : number) -> float: add two numbers together\n");
PyDoc_STRVAR(engine_vectorNorm_docs, "vectorNorm(vector : list) -> float: returns the magnitude of a 1D Vector");
// Create list of PyMethodDefs
static PyMethodDef EngineFunctions[] = {
{
"addNumbers",
(PyCFunction)engine_addNumbers,
METH_VARARGS,
engine_addNumbers_docs
},
{
"vectorNorm",
(PyCFunction)engine_vectorNorm,
METH_VARARGS,
engine_vectorNorm_docs
},
{NULL, NULL, 0, NULL} /* Sentinel */
};
// Create the Module
static struct PyModuleDef enginemodule = {
PyModuleDef_HEAD_INIT,
"engine", /* module name */
engine_docs, /* documentation */
-1, /* Leave this as -1 */
EngineFunctions /* function list */
};
// Export module when __init__ is called
PyMODINIT_FUNC
PyInit_engine(void) {
return PyModule_Create(&enginemodule);
};
| 25.842857 | 114 | 0.669431 | debeshmandal |
475ee9725fc5adaa535dd74ba7df3dbd495ff209 | 5,667 | cpp | C++ | src/coroutine.cpp | raitechnology/aekv | 0c5cc2effbe6fc7a76a62b3094a09face327fe0a | [
"Apache-2.0"
] | null | null | null | src/coroutine.cpp | raitechnology/aekv | 0c5cc2effbe6fc7a76a62b3094a09face327fe0a | [
"Apache-2.0"
] | null | null | null | src/coroutine.cpp | raitechnology/aekv | 0c5cc2effbe6fc7a76a62b3094a09face327fe0a | [
"Apache-2.0"
] | null | null | null |
/* derived from: https://github.com/cloudwu/coroutine */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include <stdint.h>
#include <aekv/coroutine.h>
#if __APPLE__ && __MACH__
#include <sys/ucontext.h>
#else
#include <ucontext.h>
#endif
static const size_t STACK_SIZE = (10*1024*1024);
extern "C" {
typedef struct coroutine_s {
coroutine_func_t func;
void * ud;
ucontext_t ctx;
schedule_t * sch;
size_t cap,
size;
char * stack;
size_t id;
const char * name;
int status;
} coroutine_t;
typedef struct schedule_s {
char stack[ STACK_SIZE ] __attribute__((__aligned__( 128 )));
ucontext_t main;
size_t nco,
cap,
used;
coroutine_t * running;
coroutine_t ** co;
} schedule_t;
}
static inline void *aligned_malloc( size_t sz ) {
#ifdef _ISOC11_SOURCE
return ::aligned_alloc( 128, sz ); /* >= RH7 */
#else
return ::memalign( 128, sz ); /* RH5, RH6.. */
#endif
}
struct Coroutine : public coroutine_s {
void * operator new( size_t, void *ptr ) { return ptr; }
void operator delete( void *ptr ) { free( ptr ); }
Coroutine( schedule_t *s, coroutine_func_t f, void *user_data, size_t i,
const char *nm, char *stk = NULL, size_t stk_cap = 0 ) {
this->func = f;
this->ud = user_data;
this->sch = s;
this->cap = stk_cap;
this->size = 0;
this->stack = stk;
this->id = i;
this->name = nm;
this->status = COROUTINE_READY;
}
~Coroutine() {
if ( this->stack != NULL ) free( this->stack );
}
};
struct Schedule : public schedule_s {
void * operator new( size_t, void *ptr ) { return ptr; }
void operator delete( void *ptr ) { free( ptr ); }
Schedule() {
this->nco = 0;
this->cap = 0;
this->used = 0;
this->running = NULL;
this->co = NULL;
}
~Schedule() {
for ( size_t i = 0; i < this->cap; i++ ) {
if ( this->co[ i ] != NULL )
delete (Coroutine *) this->co[ i ];
}
free( this->co );
}
Coroutine *new_coroutine( coroutine_func_t func, void *user_data,
const char *name ) {
if ( this->used == this->cap )
this->resize_coro( this->cap + 16 );
size_t j = this->nco;
Coroutine * c = NULL;
for ( size_t i = 0; i < this->cap; i++ ) {
if ( j >= this->cap )
j = 0;
c = (Coroutine *) this->co[ j ];
if ( c == NULL || c->status == COROUTINE_DEAD )
break;
}
this->nco = j + 1;
this->used++;
if ( c == NULL ) {
void *p = malloc( sizeof( *c ) );
c = new ( p ) Coroutine( this, func, user_data, j, name );
this->co[ j ] = c;
return c;
}
return new ( c ) Coroutine( this, func, user_data, j, name,
c->stack, c->cap );
}
void resize_coro( size_t n ) {
size_t cur = this->cap * sizeof( this->co[ 0 ] ),
sz = n * sizeof( this->co[ 0 ] );
this->co = (coroutine_t **) realloc( this->co, sz );
memset( &this->co[ this->cap ], 0, sz - cur );
this->cap = n;
}
};
extern "C" {
schedule_t *
coroutine_open( void )
{
return new ( aligned_malloc( sizeof( Schedule ) ) ) Schedule();
}
void
coroutine_close( schedule_t *sched )
{
delete (Schedule *) sched;
}
coroutine_t *
coroutine_new( schedule_t *sched, coroutine_func_t func, void *user_data,
const char *name )
{
return ((Schedule *) sched)->new_coroutine( func, user_data, name );
}
static uint32_t uint_upper( void *p ) { return ((uintptr_t) p ) >> 32; }
static uint32_t uint_lower( void *p ) { return ((uintptr_t) p ); }
static void * uint_toptr( uintptr_t i, uintptr_t j ) {
return (void *) ( ( i << 32 ) | j );
}
static void
mainfunc( uint32_t i, uint32_t j )
{
Coroutine * c = (Coroutine *) uint_toptr( i, j );
Schedule * s = (Schedule *) c->sch;
c->func( c, c->ud );
c->status = COROUTINE_DEAD;
s->used--;
s->running = NULL;
}
void
coroutine_resume( coroutine_t *co )
{
Coroutine * c = (Coroutine *) co;
Schedule * s = (Schedule *) c->sch;
switch ( c->status ) {
case COROUTINE_READY:
getcontext( &c->ctx );
c->ctx.uc_stack.ss_sp = s->stack;
c->ctx.uc_stack.ss_size = STACK_SIZE;
c->ctx.uc_link = &s->main;
c->sch->running = c;
c->status = COROUTINE_RUNNING;
makecontext( &c->ctx, (void ( * )( void )) mainfunc, 2,
uint_upper( c ), uint_lower( c ) );
swapcontext( &s->main, &c->ctx );
break;
case COROUTINE_SUSPEND:
memcpy( s->stack + STACK_SIZE - c->size, c->stack, c->size );
s->running = c;
c->status = COROUTINE_RUNNING;
swapcontext( &s->main, &c->ctx );
break;
default:
assert( 0 );
}
}
static void
_save_stack( Coroutine *c, char *top )
{
char dummy = 0;
if ( c->cap < (size_t) ( top - &dummy ) ) {
c->cap = top - &dummy;
c->stack = (char *) realloc( c->stack, c->cap );
}
c->size = top - &dummy;
memcpy( c->stack, &dummy, c->size );
}
void
coroutine_yield( coroutine_t *co )
{
Coroutine * c = (Coroutine *) co;
Schedule * s = (Schedule *) c->sch;
_save_stack( c, s->stack + STACK_SIZE );
c->status = COROUTINE_SUSPEND;
s->running = NULL;
swapcontext( &c->ctx, &s->main );
}
int
coroutine_status( coroutine_t *co )
{
return co->status;
}
coroutine_t *
coroutine_running( schedule_t *sched )
{
return sched->running;
}
const char *
coroutine_name( coroutine_t *co )
{
return co->name;
}
}
| 24.114894 | 74 | 0.556203 | raitechnology |
476035f1a5f85ea33f3730d25bc046f6d95450c4 | 6,510 | cpp | C++ | thirdparty/ULib/tests/ulib/http2/hdecode.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/tests/ulib/http2/hdecode.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/tests/ulib/http2/hdecode.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // hdecode.cpp
#include <ulib/utility/http2.h>
#undef PACKAGE
#define PACKAGE "hdecode"
#define ARGS "[dump file...]" // The file contains a dump of HPACK octets
#define U_OPTIONS \
"purpose 'simple HPACK decoder'\n" \
"option e expect-error 1 '<ERR>' ''\n" \
"option d decoding-spec 1 'Spec format: <letter><size>' ''\n" \
"option t table-size 1 'Default table size: 4096' ''\n"
#include <ulib/application.h>
#define WRT(buf, len) cout.write(buf, len)
#define OUT(msg) cout.write(msg, strlen(msg))
class Application : public UApplication {
public:
Application()
{
U_TRACE(5, "Application::Application()")
}
~Application()
{
U_TRACE(5, "Application::~Application()")
}
/*
static bool print(UStringRep* key, void* value)
{
U_TRACE(5, "Application::print(%V,%p)", key, value)
OUT("\n");
WRT(key->data(), key->size());
OUT(": ");
WRT(((UStringRep*)value)->data(), ((UStringRep*)value)->size());
U_RETURN(true);
}
*/
static void TST_decode(const UString& content, const UString& spec, int exp)
{
U_TRACE(5, "Application::TST_decode(%V,%V,%d)", content.rep, spec.rep, exp)
bool cut, resize;
int32_t index_cut = 0;
const char* pspec = spec.data();
uint32_t len = 0, sz = 0, clen = content.size();
unsigned char* cbuf = (unsigned char*)content.data();
UHashMap<UString>* table = &(UHTTP2::pConnection->itable);
UHTTP2::HpackDynamicTable* idyntbl = &(UHTTP2::pConnection->idyntbl);
OUT("Decoded header list:\n");
/**
* Spec format: <letter><size>
*
* d - decode <size> bytes from the dump
* p - decode a partial block of <size> bytes
* r - resize the dynamic table to <size> bytes
*
* The last empty spec decodes the rest of the dump
*/
do {
cut =
resize = false;
switch (*pspec)
{
case '\0': len = clen; break;
case 'r': resize = true; // resize the dynamic table to <size> bytes
case 'p': cut = true; // decode a partial block of <size> bytes
case 'd': len = atoi(++pspec); break;
default: U_ERROR("Invalid spec");
}
if (*pspec != '\0') pspec = strchr(pspec, ',') + 1;
if (resize) UHTTP2::setHpackDynTblCapacity(idyntbl, len);
else
{
UHTTP2::nerror =
UHTTP2::hpack_errno = 0;
UHTTP2::index_ptr = 0;
UHTTP2::decodeHeaders(table, idyntbl, cbuf-index_cut, cbuf+len);
U_INTERNAL_DUMP("UHTTP2::hpack_errno = %d UHTTP2::nerror = %d cut = %b len = %u", UHTTP2::hpack_errno, UHTTP2::nerror, cut, len)
if (exp &&
exp == UHTTP2::hpack_errno)
{
return;
}
index_cut = 0;
if (cut)
{
if (UHTTP2::nerror == UHTTP2::COMPRESSION_ERROR)
{
if (UHTTP2::index_ptr)
{
uint32_t advance = UHTTP2::index_ptr - cbuf;
U_INTERNAL_DUMP("UHTTP2::index_ptr = %p advance = %u", UHTTP2::index_ptr, advance)
if (len > advance) index_cut = (len - advance);
}
if (index_cut == 0) index_cut = (sz += len);
}
else
{
if (UHTTP2::index_ptr)
{
uint32_t advance = UHTTP2::index_ptr - cbuf;
U_INTERNAL_DUMP("UHTTP2::index_ptr = %p advance = %u", UHTTP2::index_ptr, advance)
if (len < advance) index_cut = (len - advance);
}
}
U_INTERNAL_DUMP("index_cut = %d", index_cut)
}
else
{
if (UHTTP2::nerror != 0 &&
UHTTP2::hpack_errno == 0)
{
return;
}
}
cbuf += len;
clen -= len;
}
}
while (clen > 0);
OUT("\n\n");
}
void run(int argc, char* argv[], char* env[])
{
U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env)
UApplication::run(argc, argv, env);
// manage arg
UString filename = UString(argv[optind]);
if (filename.empty()) U_ERROR("missing argument");
UString content = UFile::contentOf(filename);
if (content.empty()) U_ERROR("empty file");
// manage options
int exp = 0;
UString spec;
UHTTP2::btest = true;
UHTTP2::ctor();
if (UApplication::isOptions())
{
spec = opt['d'];
UString tmp = opt['t'];
if (tmp)
{
UHTTP2::pConnection->idyntbl.hpack_capacity =
UHTTP2::pConnection->idyntbl.hpack_max_capacity =
UHTTP2::pConnection->odyntbl.hpack_capacity =
UHTTP2::pConnection->odyntbl.hpack_max_capacity = tmp.strtoul();
}
tmp = opt['e'];
if (tmp)
{
for (int i = 0; i < 11; ++i)
{
if (tmp.equal(UHTTP2::hpack_error[i].str, 3))
{
exp = UHTTP2::hpack_error[i].value;
goto next;
}
}
U_ERROR("Unknown error");
}
}
next: TST_decode(content, spec, exp);
U_INTERNAL_DUMP("UHTTP2::hpack_errno = %d exp = %d", UHTTP2::hpack_errno, exp)
/*
UHashMap<UString>* table = &(UHTTP2::pConnection->itable);
if (table->empty() == false)
{
UHTTP2::bhash = true;
table->callForAllEntrySorted(print);
UHTTP2::bhash = false;
}
*/
cout.write(U_CONSTANT_TO_PARAM("Dynamic Table (after decoding):"));
UHTTP2::printHpackInputDynTable();
if (UHTTP2::hpack_errno != 0)
{
char buffer[256];
cerr.write(buffer, u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("main: hpack result: %s (%d)\n"), UHTTP2::hpack_strerror(), UHTTP2::hpack_errno));
}
if (UHTTP2::hpack_errno != exp) UApplication::exit_value = 1;
}
private:
#ifndef U_COVERITY_FALSE_POSITIVE
U_DISALLOW_COPY_AND_ASSIGN(Application)
#endif
};
U_MAIN
| 25.529412 | 166 | 0.5 | liftchampion |
4761271200d0d82dd4c939d76cc840c052adcab1 | 2,112 | hpp | C++ | test/test01_server.hpp | correlllab/isaac_ros_service | a13630f1a2ca52f8f37b3086b9d07504719c0269 | [
"MIT"
] | null | null | null | test/test01_server.hpp | correlllab/isaac_ros_service | a13630f1a2ca52f8f37b3086b9d07504719c0269 | [
"MIT"
] | null | null | null | test/test01_server.hpp | correlllab/isaac_ros_service | a13630f1a2ca52f8f37b3086b9d07504719c0269 | [
"MIT"
] | null | null | null | #ifndef TSTSVR1_H
#define TSTSVR1_H
/* ### NOTES ###
*/
#include <cstdlib>
#include <iostream>
#include <thread>
#include <utility>
#include <boost/asio.hpp>
#include <queue>
#include <string>
#include <vector>
#include <memory>
#include <set>
#include <algorithm>
#include <boost/array.hpp>
#include "../helpers/helper.hpp"
#include "../src/Connection.hpp"
using std::queue;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::set;
using std::max;
using boost::shared_ptr;
using boost::make_shared;
// using boost::connection;
const int /*---*/ max_length = 1024;
extern const bool _DEBUG;
/*************** class ServiceBridge_Server Declaration **************************************************************/
/***** ServiceBridge_Server *****/
class ServiceBridge_Server{
/***** Public *****/ public:
/*** Functions ***/
/* Setup */
bool /*-----*/ parse_service_file( string fullPath );
size_t /*---*/ how_many_services();
vector<string> get_served_ROS_topic_names();
size_t /*---*/ init_server();
/* Send / Receive */
bool serve_loop( double spinHz = 100.0 );
bool accept_all();
/* Create / Destroy */
ServiceBridge_Server();
ServiceBridge_Server( string fullPath , size_t nThreadP = 2 , u_short port_ = 8000 );
~ServiceBridge_Server();
/*** Vars ***/
/* ASIO */
b_asio::io_service /*-*/ scheduler;
b_asio::io_service::work dispatcher;
tcp::acceptor /*------*/ receiver;
tcp::socket /*--------*/ sock;
/* Threading */
size_t /*-------------------------*/ NthreadsPerTopic ,
MtotalThreads ,
numServices ;
// boost::thread_group /*------------*/ threadPool;
vector<boost::shared_ptr<boost::thread>> threads;
/* Networking */
set<string> /*---------------------------*/ serviceNames;
status_t /*------------------------------*/ status;
string /*--------------------------------*/ ip;
u_short /*-------------------------------*/ port;
vector<shared_ptr<ServiceQueue<xfer_type>>> services;
vector<Connection> /*--------------------*/ connections;
/*** END ***/ };
#endif | 22.468085 | 119 | 0.567235 | correlllab |
4761cb66b4f2de03bc45edd28436658709e15eb6 | 132,416 | cpp | C++ | tools/objc2winmd/objc2winmd.cpp | crossmob/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 6,717 | 2015-08-06T18:04:37.000Z | 2019-05-04T12:38:51.000Z | tools/objc2winmd/objc2winmd.cpp | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 2,711 | 2015-08-06T18:41:09.000Z | 2019-04-29T12:14:23.000Z | tools/objc2winmd/objc2winmd.cpp | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 1,021 | 2015-08-06T18:08:56.000Z | 2019-04-14T06:50:57.000Z | //******************************************************************************
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "stdafx.h"
#include <fstream>
#include <clang-c/Index.h>
#include <iostream>
CXChildVisitResult ASTVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data);
CXChildVisitResult IsForwardDeclarationVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data);
void HandleClassRef(CXCursor cursor, std::shared_ptr<ClangObjectModel::ComponentInfo>& component);
void HandleProtocolRef(CXCursor cursor, std::shared_ptr<ClangObjectModel::ComponentInfo>& component);
extern "C" unsigned int g_MaxErrors = 1;
extern "C" const std::string g_winrtClassPrefix = "RT";
ClangHelpers::SDKParameters g_sdkParameters;
ClangObjectModel::GlobalData g_globalData;
extern "C" const string g_commonConvertors = "CommonConvertors";
extern "C" const string g_NSDateConvertor = "NSDateConvertor";
extern "C" const string g_NSURLConvertor = "NSURLConvertor";
extern "C" const string g_notificationCenter = "NotificationCenter";
extern "C" const std::string g_copyrightNotice =
"//******************************************************************************\n"
"//\n"
"// Copyright (c) Microsoft Corporation. All rights reserved.\n"
"//\n"
"// This code is licensed under the MIT License (MIT).\n"
"//\n"
"// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"
"// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"
"// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"
"// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"
"// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"
"// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n"
"// THE SOFTWARE.\n"
"//\n"
"//******************************************************************************\n\n";
std::string getFullContainerName(std::string name) {
return "Windows.Foundation.Collections." + name;
}
std::string generateRTFactoryName(const std::shared_ptr<ClangObjectModel::InterfaceInfo> iface) {
std::string rtFactoryName = g_winrtClassPrefix + iface->name;
if (iface->isActivatableStaticOnlyFactory()) {
rtFactoryName += "Statics";
} else {
rtFactoryName += "Factory";
}
return rtFactoryName;
}
std::string generateFactoryMethodName(const std::string& objCSelectorName) {
std::vector<std::string> tokens;
Helpers::splitString(objCSelectorName, tokens, ":");
std::string ret;
for (auto s : tokens) {
if (ret.size() > 0) {
ret += "_";
}
ret += s;
}
return "CreateInstance_" + ret;
}
//
// These functions work on objective c types and do conversions:
//
std::string generateDelegateParamList(const std::vector<std::shared_ptr<ClangObjectModel::TypeInfo>>& delegateParams,
bool includeIdlDecorations = true) {
std::string paramList;
if (delegateParams.size() > 0) {
paramList =
Helpers::addSeparators(delegateParams,
[&](const std::shared_ptr<ClangObjectModel::TypeInfo> t) {
std::string typeName;
if (includeIdlDecorations) {
if (t->hasBaseWinRTRepresentation()) {
typeName = TypeConvertor::WinrtType(t, true, true);
} else {
typeName = TypeConvertor::WinrtType(t, false, true);
if (ClangHelpers::isInterface(t->getTypeSpelling())) {
typeName = ClangHelpers::generateResolvedTypeName(typeName, t->getSDKName(), true);
}
}
} else {
// This needs to stay objective C type.
// This is the input argument to the wrapper block which gets passed to objective C land.
// (The wrapper block internally calls into the user provided closure/lambda)
if (t->isHeterogeneous) {
auto it =
g_globalData.currentComponent->heterogeneousContainers.find(t->getTypeSpelling(true));
typeName = it->second->objCContainerName;
} else {
typeName = t->getTypeSpelling();
}
if (t->isContainer()) {
typeName += "*";
}
}
typeName += " ";
std::string parameter = typeName + t->getTypeName();
if (includeIdlDecorations) {
parameter = t->annotation + " " + parameter;
}
return parameter;
},
", ");
}
return paramList;
}
// We're expecting our type to be coming in as a winRT type and we want to map into ObjC to
// call down to the library implementation:
std::string marshalToObjC(const std::shared_ptr<ClangObjectModel::ParameterInfo> paramInfo) {
if (paramInfo->typeInfo->typeKind == CXType_BlockPointer) {
string delegateParamNameListForWinRT = ClangHelpers::getDelegateParamNameListForWinRT(paramInfo);
std::string blockType = "^(" + generateDelegateParamList(paramInfo->delegateParams, false) + ")";
if (paramInfo->marshallDelegateAsAsync) {
if (paramInfo->asyncInfo->returnTypes.size() < 2) {
return blockType + " { spAsyncWorker->setResult(" + delegateParamNameListForWinRT + ");}";
} else {
string resolvedImplName =
ClangHelpers::generateResolvedTypeName(paramInfo->asyncInfo->implName, paramInfo->asyncInfo->sdkName, false, "");
string localVarName = "_" + paramInfo->asyncInfo->implName;
return blockType + " { spAsyncWorker->setResult(^" + resolvedImplName + "*() {ComPtr<" + resolvedImplName + "> " +
localVarName + " = Make<" + resolvedImplName + ">(); (" + localVarName + ".Get())->Init(" +
delegateParamNameListForWinRT + "); return " + localVarName + ".Detach();}());}";
}
} else {
string comPtrType = ClangHelpers::generateDelegateName(paramInfo->delegateParams);
comPtrType = ClangHelpers::generateResolvedTypeName("I" + comPtrType, paramInfo->typeInfo->getSDKName(), false);
string comPtrName = "_" + paramInfo->typeInfo->getTypeName();
return blockType + " { " + "ComPtr<" + comPtrType + "> " + comPtrName + "; " + comPtrName + ".Attach(" +
paramInfo->typeInfo->getTypeName() + "); " + "THROW_NS_IF_FAILED(" + comPtrName + "->Invoke(" +
delegateParamNameListForWinRT + ")); }";
}
}
if (paramInfo->typeInfo->isContainer()) {
return TypeConvertor::GetObjCTypeCreatorName(paramInfo->typeInfo) + "(" + paramInfo->typeInfo->getTypeName() + ")";
}
if (paramInfo->typeInfo->getTypeSpelling() == "NSString*" || paramInfo->typeInfo->getTypeSpelling() == "NSString *") {
return "hstrToNSStr(" + paramInfo->typeInfo->getTypeName() + ")";
}
if (paramInfo->typeInfo->isNSDateType()) {
return g_commonConvertors + "::convertWinRTToNSDate(" + paramInfo->typeInfo->getTypeName() + ")";
}
if (paramInfo->typeInfo->isNSURLType()) {
return g_commonConvertors + "::convertWinRT" + paramInfo->typeInfo->getTypeSpelling(true) + "ToNSURL(" +
paramInfo->typeInfo->getTypeName() + ")";
}
if (paramInfo->typeInfo->getSymbolKind() == ClangObjectModel::JSONType) {
return g_commonConvertors + "::convertPropertySetToNSDictionary(" + paramInfo->typeInfo->getTypeName() + ")";
}
if (ClangHelpers::isInterface(paramInfo->typeInfo->getTypeSpelling())) {
// we have an interface
// TODO: Find a better way to do this.
// Casting an interface to the runtime class is unsafe, but we are well aware that we just have one instantiation of the interface.
// Also, this hack works because getInnerObject is non-virtual.
std::string resolvedType =
ClangHelpers::generateResolvedTypeName(g_winrtClassPrefix + TypeConvertor::WinrtType(paramInfo->typeInfo, true),
paramInfo->typeInfo->getSDKName(),
false,
"");
return "((" + resolvedType + "*)" + paramInfo->typeInfo->getTypeName() + ")->getInnerObject()";
}
// Do not change this order, every delegateCallbackProtocol is a protocol but not the other way around.
if (ClangHelpers::isDelegateCallbackProtocol(paramInfo->typeInfo->getTypeSpelling())) {
return "[[" + Helpers::Trim(Helpers::baseType(paramInfo->typeInfo->getTypeSpelling(), true)) + " alloc] initWith:" +
paramInfo->typeInfo->getTypeName() + "]";
} else if (ClangHelpers::isProtocol(paramInfo->typeInfo->getTypeSpelling())) {
return "dynamic_cast<GetInnerObject*>(" + paramInfo->typeInfo->getTypeName() + ")->getInnerObject()";
}
if (paramInfo->typeInfo->typeKind == CXType_Enum) {
return "(" + paramInfo->typeInfo->getTypeSpelling() + ")" + paramInfo->typeInfo->getTypeName();
}
return paramInfo->typeInfo->getTypeName();
}
std::string marshalWinRTToObjcInLocalVar(const std::shared_ptr<ClangObjectModel::ParameterInfo> paramInfo) {
return "id " + paramInfo->typeInfo->generateObjcLocalVarName() + " = " + marshalToObjC(paramInfo);
}
string getParamList(std::vector<shared_ptr<ClangObjectModel::ParameterInfo>>& params, bool generateForIDL) {
return Helpers::addSeparators(
params,
[&](const std::shared_ptr<ClangObjectModel::ParameterInfo> p) {
std::string parameter;
if (p->typeInfo->typeKind == CXType_BlockPointer) {
parameter = ClangHelpers::generateDelegateName(p->delegateParams) + "* " + p->typeInfo->getTypeName();
string prefix = (generateForIDL ? "" : "I");
parameter = ClangHelpers::generateResolvedTypeName(prefix + parameter, p->typeInfo->getSDKName(), generateForIDL);
} else {
parameter = TypeConvertor::WinrtType(p->typeInfo, p->typeInfo->hasBaseWinRTRepresentation(), generateForIDL);
if (ClangHelpers::isInterface(p->typeInfo->getTypeSpelling()) || ClangHelpers::isProtocol(p->typeInfo->getTypeSpelling())) {
parameter = ClangHelpers::generateResolvedTypeName("I" + parameter, p->typeInfo->getSDKName(), generateForIDL);
}
parameter += " " + p->typeInfo->getTypeName();
}
if (generateForIDL) {
parameter = p->typeInfo->annotation + " " + parameter;
}
return parameter;
},
", ",
[&](auto val) {
bool fGenerateParam = true;
if (val->typeInfo->typeKind == CXType_BlockPointer && val->marshallDelegateAsAsync) {
fGenerateParam = false;
}
return fGenerateParam;
});
}
std::string generateParamList(const std::shared_ptr<ClangObjectModel::MethodInfo> method,
bool generateForIDL,
bool generateReturnType = true,
bool generateForFactory = false) {
// The first parameter is the name:
std::string paramList;
if (method->params.size() > 0) {
paramList = getParamList(method->params, generateForIDL);
}
// Generate return param:
std::string asyncReturnParam;
if (method->isAsync) {
string resolvedImplNameForIDL;
string resolvedImplNameForRuntime;
std::shared_ptr<ClangObjectModel::TypeInfo> retType;
for (const auto& p : method->params) {
if (p->marshallDelegateAsAsync) {
if (generateForIDL) {
resolvedImplNameForIDL = ClangHelpers::getResolvedAsyncImplName(p->asyncInfo, "", true);
if (!resolvedImplNameForIDL.empty()) {
asyncReturnParam =
"[out] [retval] Windows.Foundation.IAsyncOperation<" + resolvedImplNameForIDL + ">** __returnValue";
} else {
asyncReturnParam = "[out] [retval] Windows.Foundation.IAsyncAction** __returnValue";
}
} else {
resolvedImplNameForRuntime = ClangHelpers::getResolvedAsyncImplName(p->asyncInfo, "", false);
if (!resolvedImplNameForRuntime.empty()) {
asyncReturnParam = "ABI::Windows::Foundation::IAsyncOperation<" + resolvedImplNameForRuntime + ">** __returnValue";
} else {
asyncReturnParam = "ABI::Windows::Foundation::IAsyncAction** __returnValue";
}
}
break;
}
}
}
string returnParam;
if (generateReturnType) {
if (!asyncReturnParam.empty()) {
method->returnType->typeInfo->setTypeName("__originalReturnValue");
method->returnType->typeInfo->annotation = "[out]";
}
string returnVar = method->returnType->typeInfo->getTypeName();
std::string prefix = generateForFactory ? "" : "I";
if (method->returnType->typeInfo->typeKind != CXType_Void) {
returnParam = TypeConvertor::WinrtType(method->returnType->typeInfo,
method->returnType->typeInfo->hasBaseWinRTRepresentation(),
generateForIDL);
if (ClangHelpers::isInterface(method->returnType->typeInfo->getTypeSpelling()) ||
ClangHelpers::isProtocol(method->returnType->typeInfo->getTypeSpelling())) {
returnParam = ClangHelpers::generateResolvedTypeName(prefix + returnParam,
method->returnType->typeInfo->getSDKName(),
generateForIDL);
}
returnParam += "* " + returnVar;
if (generateForIDL) {
returnParam = method->returnType->typeInfo->annotation + " " + returnParam;
}
if (!asyncReturnParam.empty()) {
returnParam = returnParam + ", " + asyncReturnParam;
}
}
}
if (returnParam.empty()) {
returnParam = asyncReturnParam;
}
if (paramList.size() && returnParam.size()) {
paramList += ", " + returnParam;
} else if (returnParam.size()) {
paramList = returnParam;
}
return paramList;
}
std::string generateEnums(const std::shared_ptr<ClangObjectModel::TypeInfo>& typeInfo) {
stringstream ss;
ss << "[version(1.0)]" << std::endl;
ss << "[v1_enum]" << std::endl;
ss << "enum " << typeInfo->getTypeSpelling() << "{" << std::endl;
std::string enumConstantDecl = "";
for (auto item : typeInfo->enumConstants) {
if (!enumConstantDecl.empty()) {
enumConstantDecl += ",\n";
}
enumConstantDecl += " " + item.first + " = " + std::to_string(item.second);
}
ss << enumConstantDecl << std::endl << "};" << std::endl;
return ss.str();
}
std::string generateInterfaceIdl(const std::string& IDLInterfaceName,
const std::string& prefix,
const std::string& suffix,
const std::vector<std::shared_ptr<ClangObjectModel::MethodInfo>>& methods,
bool isInitMethod = false) {
stringstream ss;
ss << Helpers::annotate("uuid", Helpers::newUuid());
ss << Helpers::annotate("version", "1.0");
ss << "interface " << prefix << IDLInterfaceName << suffix << " : IInspectable {" << std::endl;
for (const auto& method : methods) {
std::string methodName;
if (isInitMethod) {
methodName = generateFactoryMethodName(method->objectiveCSelector);
} else {
methodName = method->getMethodNameForIdl();
}
ss << " " << method->idlAnnotation << "HRESULT " << methodName << "(" << generateParamList(method, true, true, isInitMethod)
<< ");" << std::endl;
}
ss << "}" << std::endl << std::endl;
return ss.str();
}
std::string generateInterfaceForAsyncClassIdl(const std::string& IDLInterfaceName,
const std::string& prefix,
const std::vector<std::shared_ptr<ClangObjectModel::MethodInfo>>& methods) {
stringstream ss;
ss << Helpers::annotate("uuid", Helpers::newUuid());
ss << Helpers::annotate("version", "1.0");
ss << "interface " << prefix << IDLInterfaceName << " : IInspectable {" << std::endl;
for (const auto& method : methods) {
std::string methodName = method->getMethodNameForIdl();
ss << " " << method->idlAnnotation << "HRESULT " << methodName << "(" << generateParamList(method, true, true, false) << ");"
<< std::endl;
}
ss << "}" << std::endl << std::endl;
return ss.str();
}
std::string generateAsyncClassIdl(const std::shared_ptr<ClangObjectModel::InterfaceInfo> iface) {
stringstream ss;
ss << generateInterfaceForAsyncClassIdl(iface->name, "I", iface->instanceMethods);
// Now generate the runtime class:
ss << "[marshaling_behavior(agile)]" << std::endl;
ss << "[threading(both)]" << std::endl;
ss << Helpers::annotate("version", "1.0");
ss << "runtimeclass " << iface->GetIdlRuntimeClassName() << " {" << std::endl;
string fullyQualifiedName = ClangHelpers::generateResolvedTypeName("I" + iface->name, iface->getSDKName(), true);
ss << " [default] interface " << fullyQualifiedName << ";" << std::endl;
ss << "}" << std::endl << std::endl;
return ss.str();
}
std::string generateClassIdl(const std::shared_ptr<ClangObjectModel::InterfaceInfo> iface) {
stringstream ss;
ss << generateInterfaceIdl(iface->name, "I", "", iface->instanceMethods, false);
if (iface->parameterizedInitMethods.size() > 0) {
ss << generateInterfaceIdl(iface->name, "I", "Factory", iface->parameterizedInitMethods, true);
}
if (iface->classMethods.size() > 0) {
ss << generateInterfaceIdl(iface->name, "I", "Statics", iface->classMethods);
}
// Now generate the runtime class:
// Note: The following is required by anything that subclasses windows.ui.xaml.controls.contentcontrol
// However, it is "good practice" to put on all runtimeclasses even though it doesn't effect runtime behaviour.
ss << "[marshaling_behavior(agile)]" << std::endl;
ss << "[threading(both)]" << std::endl;
if (iface->hasDefaultInitializer) {
ss << Helpers::annotate("activatable", "1.0");
}
if (iface->parameterizedInitMethods.size() > 0) {
ss << Helpers::annotate("activatable", "I" + iface->name + "Factory, 1.0");
}
if (iface->classMethods.size() > 0) {
ss << Helpers::annotate("static", "I" + iface->name + "Statics, 1.0");
}
string composableRuntimeClass;
// If the interface derives from a UIElement (something in objCSuperClasses), we create a composable class that
// derives from Xaml.Controls.ContentControl instead of implementing an IUIElement WinRT Interface.
std::shared_ptr<ClangObjectModel::InterfaceInfo> uiElementInterface = iface->GetUIElementBaseClass();
if (uiElementInterface != nullptr) {
composableRuntimeClass = " : " + uiElementInterface->GetIdlRuntimeClassName();
}
ss << Helpers::annotate("version", "1.0");
ss << "runtimeclass " << iface->GetIdlRuntimeClassName() << composableRuntimeClass << " {" << std::endl;
std::shared_ptr<ClangObjectModel::InterfaceInfo> interfaceIter = iface;
while (interfaceIter != nullptr && interfaceIter != uiElementInterface) {
string defaultInterface = (iface->name == interfaceIter->name ? "[default] " : "");
string fullyQualifiedName = ClangHelpers::generateResolvedTypeName("I" + interfaceIter->name, interfaceIter->getSDKName(), true);
ss << " " << defaultInterface << "interface " << fullyQualifiedName << ";" << std::endl;
for (const auto& protocol : interfaceIter->getProtocolsImplemented()) {
fullyQualifiedName = ClangHelpers::generateResolvedTypeName("I" + protocol->name, protocol->getSDKName(), true);
ss << " interface " << fullyQualifiedName << ";" << std::endl;
}
interfaceIter = interfaceIter->GetBaseClass();
}
ss << "}" << std::endl << std::endl;
return ss.str();
}
std::string generateClassIdl(const std::shared_ptr<ClangObjectModel::ProtocolInfo> protocol) {
stringstream ss;
ss << generateInterfaceIdl(protocol->name, "I", "", protocol->instanceMethods, false);
return ss.str();
}
void dumpFile(const std::string& name, const std::string& data, const std::string& path) {
std::string outputFile = path + "\\" + name;
FILE* f;
// TODO: include wil macros.
errno_t err = fopen_s(&f, outputFile.c_str(), "w");
if (err != 0) {
printf("Failed to open output file %s", outputFile.c_str());
exit(-1);
}
fwrite(data.c_str(), 1, data.size(), f);
fclose(f);
}
std::string generateDelegateIdl(const std::shared_ptr<ClangObjectModel::DelegateInfo> delegateInfo) {
stringstream ss;
ss << Helpers::annotate("uuid", Helpers::newUuid());
ss << Helpers::annotate("version", "1.0");
ss << "delegate" << std::endl;
ss << "HRESULT " << delegateInfo->name << "(" + generateDelegateParamList(delegateInfo->params) + ");" << std::endl;
return ss.str();
}
std::string generateIAsyncOperationSpecialization() {
stringstream ss;
for (const auto& asyncClass : g_globalData.currentComponent->asyncClasses) {
if (asyncClass->returnTypes.size() != 0) {
if (ClangHelpers::isInterface(asyncClass->implName)) {
ss << "declare {" << std::endl;
ss << " interface Windows.Foundation.IAsyncOperation<" << Helpers::baseType(asyncClass->implName) << "*>;" << std::endl;
ss << "}" << std::endl;
}
}
}
return ss.str();
}
std::string generateAppDelegateDecl() {
stringstream ss;
ss << "#import <Foundation/Foundation.h>\n";
ss << "#import <UIKit/UIKit.h>\n\n";
ss << "@interface _" << g_globalData.applicationDelegateInfo->ifaceInfo->name << " : NSObject<UIApplicationDelegate>\n";
ss << "@end\n";
return ss.str();
}
std::string generateObjCSelectorSignature(const std::shared_ptr<ClangObjectModel::MethodInfo> methodInfo) {
std::string signature = methodInfo->objectiveCSignature;
size_t pos = signature.find(';');
if (pos != signature.npos) {
signature = signature.substr(0, pos);
}
return Helpers::replace(signature, ";", "");
}
std::string generateAppDelegateCreator() {
std::string appDelegateCreator;
if (g_globalData.applicationDelegateInfo->allocatorMethod == nullptr &&
g_globalData.applicationDelegateInfo->initializerMethod == nullptr) {
// use [[interface alloc] init]
appDelegateCreator = "[[" + g_globalData.applicationDelegateInfo->ifaceInfo->name + " alloc] init]";
} else if (g_globalData.applicationDelegateInfo->allocatorMethod != nullptr &&
g_globalData.applicationDelegateInfo->initializerMethod != nullptr) {
if (g_globalData.applicationDelegateInfo->allocatorMethod != g_globalData.applicationDelegateInfo->initializerMethod) {
// use [[interface allocatorMethod] initializerMethod]
appDelegateCreator = "[[" + g_globalData.applicationDelegateInfo->ifaceInfo->name + " " +
g_globalData.applicationDelegateInfo->allocatorMethod->name + "] " +
g_globalData.applicationDelegateInfo->initializerMethod->name + "]";
} else {
appDelegateCreator = "[" + g_globalData.applicationDelegateInfo->ifaceInfo->name + " " +
g_globalData.applicationDelegateInfo->allocatorMethod->name + "]";
}
} else if (g_globalData.applicationDelegateInfo->allocatorMethod != nullptr) {
// use [[interface allocatorMethod] init]
appDelegateCreator = "[[" + g_globalData.applicationDelegateInfo->ifaceInfo->name + " " +
g_globalData.applicationDelegateInfo->allocatorMethod->name + "] init]";
} else {
// use [[interface alloc] initializerMethod]
appDelegateCreator = "[[" + g_globalData.applicationDelegateInfo->ifaceInfo->name + " alloc] " +
g_globalData.applicationDelegateInfo->initializerMethod->name + "]";
}
return appDelegateCreator;
}
std::string generateMsgSendUsingLocals(const std::shared_ptr<ClangObjectModel::MethodInfo> method) {
if (method->params.size() == 0) {
return method->name;
}
std::string msgSend;
// get the method selectors.
std::vector<std::string> tokens;
tokenize(method->objectiveCSelector, tokens, ":", "", "\"", "", "\\", false, true);
assert(tokens.size() == method->params.size());
// Generate msg send.
for (unsigned int i = 0; i < method->params.size(); i++) {
std::string value = method->params[i]->typeInfo->generateObjcLocalVarName();
if (i > 0) {
msgSend += " ";
}
msgSend += tokens[i] + ":" + value;
}
return msgSend;
}
std::string generateMsgSend(const std::shared_ptr<ClangObjectModel::MethodInfo> method, bool pureObjC = false) {
if (method->params.size() == 0) {
return method->name;
}
std::string msgSend;
// get the method selectors.
std::vector<std::string> tokens;
tokenize(method->objectiveCSelector, tokens, ":", "", "\"", "", "\\", false, true);
assert(tokens.size() == method->params.size());
for (unsigned int i = 0; i < method->params.size(); i++) {
std::string value = pureObjC ? method->params[i]->typeInfo->getTypeName() : marshalToObjC(method->params[i]);
if (i > 0) {
msgSend += " ";
}
msgSend += tokens[i] + ":" + value;
}
return msgSend;
}
std::string generateObjCSelectorCall(const std::shared_ptr<ClangObjectModel::MethodInfo> methodInfo) {
stringstream ss;
ss << "[" << generateAppDelegateCreator() << " " << generateMsgSend(methodInfo, true) << "];";
return ss.str();
}
std::string generateAppDelegateMethodImpl() {
stringstream ss;
for (const auto methodInfo : g_globalData.applicationDelegateInfo->ifaceInfo->instanceMethods) {
// Generate signature
ss << generateObjCSelectorSignature(methodInfo) << " {\n";
ss << " return " << generateObjCSelectorCall(methodInfo) << "\n";
ss << "}\n\n";
}
for (const auto methodInfo : g_globalData.applicationDelegateInfo->ifaceInfo->classMethods) {
// Generate signature
ss << generateObjCSelectorSignature(methodInfo) << "{\n";
ss << " return " << generateObjCSelectorCall(methodInfo) << "\n";
ss << "}\n\n";
}
return ss.str();
}
std::string generateAppDelegateImpl() {
stringstream ss;
ss << "#import <" << g_globalData.applicationDelegateInfo->ifaceInfo->getSDKName() << "/"
<< g_globalData.applicationDelegateInfo->ifaceInfo->SDKHeaderFile << ".h>" << endl;
ss << "#import \"" << g_sdkParameters.rootNameSpace << "_" << g_globalData.applicationDelegateInfo->ifaceInfo->name << ".h\"" << endl
<< endl;
ss << "@implementation _" << g_globalData.applicationDelegateInfo->ifaceInfo->name << "\n\n";
ss << generateAppDelegateMethodImpl();
ss << "@end\n";
return ss.str();
}
std::string generateIdl(const std::shared_ptr<ClangObjectModel::ComponentInfo> component) {
stringstream ss;
for (const auto& dep : ClangObjectModel::GlobalData::defaultDependentIdls) {
ss << "import \"" << dep << "\";" << std::endl;
}
for (auto& iface : component->ifaces) {
if (iface.second->DerivesFromUIElement()) {
ss << "import \"" << iface.second->GetUIElementBaseClass()->GetIdlFileName() << "\";" << std::endl;
break;
}
}
std::string additionalIncludes;
for (const auto& ref : component->referencedIDLs) {
if (ClangObjectModel::GlobalData::defaultDependentIdls.find(ref) != ClangObjectModel::GlobalData::defaultDependentIdls.end()) {
continue;
}
ss << "import \"" << ref << "\";" << std::endl;
std::string header = ref.substr(0, ref.rfind(".idl"));
std::string headerNameInclude = "#include \\\"" + header + ".h\\\"";
// Forward declaration in headers get transformed to import in IDL.
// So our IDLs are not immune to cyclic dependencies. The problem we encounter because of this is:
// If there are three files a.idl, b.idl and c.idl such that:
// a.idl has:
// import "b.idl";
// import "c.idl";
//
// b.idl has:
// import "a.idl";
// import "c.idl";
//
// We see that the generated a.h and b.h files do not contain any include reference for c.h.
// This causes undefined symbol errors.
// To solve this, we use cpp_quote to include the headers.
// This has a benign effect of duplicate header inclusion in the generated .h file.
// But the headers have #pragma once and so this is harmless.
additionalIncludes += "cpp_quote(\"" + headerNameInclude + "\")\n";
}
ss << std::endl;
// Additional imports to ensure that all required headers are included
if (!additionalIncludes.empty()) {
ss << additionalIncludes << std::endl;
}
ss << "namespace " << ClangHelpers::generateNamespaceString(component->getSDKName(), ".") << " {" << std::endl << std::endl;
for (const auto& ref : component->referencedInterfaces) {
// The format of referencedInterfaces is:
// "SDKName.HeaderFileName.InterfaceName"
std::string name;
size_t pos1 = ref.find_last_of(".");
size_t pos2 = ref.find_last_of(".", pos1 - 1);
// Everything after pos1 is the name of the interface:
name = ref.substr(pos1 + 1, ref.length() - pos1 - 1);
ss << "interface " << ref.substr(0, pos2 + 1) + "I" + name << ";" << std::endl;
ss << "runtimeclass " << name << ";" << std::endl;
}
for (const auto& ref : component->referencedProtocols) {
// The format of referencedProtocols is:
// "SDKName.HeaderFileName.ProtocolName"
std::string name;
size_t pos1 = ref.find_last_of(".");
size_t pos2 = ref.find_last_of(".", pos1 - 1);
// Everything after pos1 is the name of the interface:
name = ref.substr(pos1 + 1, ref.length() - pos1 - 1);
ss << "interface " << ref.substr(0, pos2 + 1) + "I" + name << ";" << std::endl;
}
// forward declarations
for (const auto& ifaceMap : component->ifaces) {
auto iface = ifaceMap.second;
ss << "interface I" << iface->name << ";" << std::endl;
ss << "runtimeclass " << iface->GetIdlRuntimeClassName() << ";" << std::endl;
if (iface->parameterizedInitMethods.size() > 0) {
ss << "interface I" << iface->name << "Factory;" << std::endl;
}
if (iface->classMethods.size() > 0) {
ss << "interface I" << iface->name << "Statics;" << std::endl;
}
}
for (const auto& protocolMap : component->protocols) {
auto protocol = protocolMap.second;
ss << "interface I" << protocol->name << ";" << std::endl;
}
ss << std::endl;
// Generate component level Enums
for (const auto enumItem : component->enums) {
ss << generateEnums(enumItem.second) << std::endl;
}
// Generate delegate declarations.
for (const auto delMap : component->delegates) {
ss << generateDelegateIdl(delMap.second) << std::endl;
}
for (const auto& asyncClass : component->asyncClasses) {
if (asyncClass->synthesizedInterface != nullptr) {
ss << generateAsyncClassIdl(asyncClass->synthesizedInterface);
}
}
// Specialize IAsyncOperation for generated runtime classes only
ss << generateIAsyncOperationSpecialization() << std::endl;
for (const auto& protocolMap : component->protocols) {
ss << generateClassIdl(protocolMap.second);
}
for (const auto& ifaceMap : component->ifaces) {
ss << generateClassIdl(ifaceMap.second);
}
ss << "}" << std::endl << std::endl;
return ss.str();
}
std::string generateFactoryMethodBody(const std::shared_ptr<ClangObjectModel::MethodInfo> methodInfo,
const std::shared_ptr<ClangObjectModel::InterfaceInfo> iface,
const std::string paramName) {
stringstream ss;
ss << " *" << paramName << " = Make<" << ClangHelpers::generateNamespaceString(iface->getSDKName(), "::")
<< "::" << g_winrtClassPrefix << iface->name << ">(";
std::string argNameList;
for (const auto& param : methodInfo->params) {
if (argNameList.size() > 0) {
argNameList.append(", ");
}
argNameList.append(param->typeInfo->getTypeName());
}
ss << argNameList << ").Detach();" << std::endl;
ss << " return *" << paramName << " != nullptr ? S_OK : E_OUTOFMEMORY;" << std::endl;
return ss.str();
}
std::string generateABIBoundaryStart() {
std::stringstream ss;
ss << " return ExceptionBoundary([&]() {" << endl;
return ss.str();
}
std::string generateABIBoundaryEnd() {
std::stringstream ss;
ss << " });" << endl;
return ss.str();
}
std::string generateClassFactory(const std::shared_ptr<ClangObjectModel::InterfaceInfo> iface) {
stringstream ss;
auto classNameStr = "RuntimeClass_" + ClangHelpers::generateNamespaceString(iface->getSDKName(), "_") + "_" + iface->name;
// The class factory:
std::string factoryName = generateRTFactoryName(iface);
std::string interfaceNames = "";
if (iface->classMethods.size() > 0) {
interfaceNames += ClangHelpers::generateResolvedTypeName("I" + iface->name + "Statics", iface->getSDKName());
}
if (iface->parameterizedInitMethods.size() > 0) {
if (interfaceNames.size() > 0) {
interfaceNames += ", ";
}
interfaceNames += ClangHelpers::generateResolvedTypeName("I" + iface->name + "Factory", iface->getSDKName());
}
ss << "class " << factoryName << " : public ActivationFactory<" << interfaceNames << "> {" << std::endl;
// Add the comment for the hack to correctly expose Nil as a class type instead of a nullptr.
ss << std::endl;
if (iface->parameterizedInitMethods.size() != 0 || iface->classMethods.size() != 0) {
ss << "// Runtime.h defines Nil as ((Class)_OBJC_NULL_PTR), which results in an error for InspectableClassStatic" << std::endl;
ss << "// which expects Nil as a CPP class. If Nil is undefined, the push and pop below are NOP." << std::endl;
ss << "#pragma push_macro(\"Nil\")" << std::endl;
ss << "#undef Nil" << std::endl;
ss << " InspectableClassStatic(" << classNameStr << ", BaseTrust)" << std::endl;
ss << "#pragma pop_macro(\"Nil\")" << std::endl;
}
ss << std::endl << "public:" << std::endl;
ss << " " << factoryName << "() {" << std::endl;
ss << " }" << std::endl << std::endl;
std::string paramName = iface->name;
if (iface->hasDefaultInitializer) {
// default constructor:
std::string runtimeClass = ClangHelpers::generateResolvedTypeName(g_winrtClassPrefix + Helpers::baseType(iface->name, true),
iface->getSDKName(),
false,
"");
std::string ABIInterface =
ClangHelpers::generateResolvedTypeName("I" + Helpers::baseType(iface->name, true), iface->getSDKName(), false);
std::transform(paramName.begin(), paramName.end(), paramName.begin(), ::tolower);
ss << " STDMETHODIMP ActivateInstance(IInspectable** " << paramName << ") override {" << std::endl;
ss << generateABIBoundaryStart();
ss << ClangHelpers::generateCallToIslandWoodInit();
ss << " return MakeAndInitialize<" << runtimeClass << ">(" << paramName << ");" << endl;
ss << generateABIBoundaryEnd();
ss << " }" << std::endl;
ss << std::endl;
}
// parameterized constructors
for (const auto& method : iface->parameterizedInitMethods) {
ss << " STDMETHODIMP " << generateFactoryMethodName(method->objectiveCSelector) << "(" << generateParamList(method, false, false)
<< ", " << ClangHelpers::generateResolvedTypeName("I" + iface->name, iface->getSDKName()) << "** " << paramName << ") override {"
<< std::endl;
ss << generateABIBoundaryStart();
ss << ClangHelpers::generateCallToIslandWoodInit();
ss << generateFactoryMethodBody(method, iface, paramName);
ss << generateABIBoundaryEnd();
ss << " }" << std::endl;
}
for (const auto& method : iface->classMethods) {
ss << " STDMETHODIMP " << method->getMethodNameForRuntimeClass() << "(" << generateParamList(method, false) << ") override {"
<< std::endl;
bool usesDelegateProtocols = false;
for (unsigned int i = 0; i < method->params.size(); i++) {
auto it = iface->usedDelegateTypes.find(method->params[i]->typeInfo->getTypeSpelling());
if (it != iface->usedDelegateTypes.end()) {
usesDelegateProtocols = true;
break;
}
}
// code to initialize local vars, if any.
std::stringstream localVarsCode;
// code to save vars, if any.
std::stringstream saveVarsCode;
// code to set the return variable.
std::string returnVarCode;
if (usesDelegateProtocols) {
if (!method->returnType->typeInfo->isInterface()) {
Helpers::Errors::WriteError(nullptr, "Marshalling delegates is not supported.", false);
} else {
std::vector<std::shared_ptr<ClangObjectModel::TypeInfo>> localVarsToSave;
for (unsigned int i = 0; i < method->params.size(); i++) {
auto it = iface->usedDelegateTypes.find(method->params[i]->typeInfo->getTypeSpelling());
if (it != iface->usedDelegateTypes.end()) {
localVarsToSave.push_back(method->params[i]->typeInfo);
}
// Code for marshalling an objective-C type to local var..
localVarsCode << " " + marshalWinRTToObjcInLocalVar(method->params[i]) << ";" << endl;
}
string callStr = "[" + iface->name + " " + generateMsgSendUsingLocals(method) + "]";
// TODO: Make this more robust and avoid name collisions.
string tempVar = "_temp";
localVarsCode << " auto " << tempVar << " = "
<< TypeConvertor::getWRLConvertorFuncForType(method->returnType->typeInfo, callStr) + ";" << endl;
if (!localVarsToSave.empty()) {
for (const auto& typeInfo : localVarsToSave) {
saveVarsCode << tempVar + "->" + typeInfo->generateMemberVarName() + " = " + typeInfo->generateObjcLocalVarName()
<< ";" << endl;
}
}
returnVarCode = " *" + method->returnType->typeInfo->getTypeName() + " = " + tempVar + ";";
}
} else if (method->returnType->typeInfo->typeKind != CXType_Void) {
string callStr = "[" + iface->name + " " + generateMsgSend(method) + "]";
returnVarCode = "*" + method->returnType->typeInfo->getTypeName() + " = ";
returnVarCode = returnVarCode + TypeConvertor::getWRLConvertorFuncForType(method->returnType->typeInfo, callStr) + ";";
} else {
string callStr = "[" + iface->name + " " + generateMsgSend(method) + "]";
returnVarCode = callStr + ";";
}
ss << generateABIBoundaryStart();
ss << ClangHelpers::generateCallToIslandWoodInit();
ss << localVarsCode.str() << std::endl;
ss << saveVarsCode.str() << std::endl;
ss << " " << returnVarCode << std::endl;
ss << " return S_OK;" << std::endl;
ss << generateABIBoundaryEnd();
ss << " }" << std::endl;
}
ss << "};" << std::endl;
return ss.str();
}
string generateAsyncClassInitMethod(const shared_ptr<ClangObjectModel::AsyncClassInfo>& asyncInfo) {
stringstream ss;
string paramsString = Helpers::addSeparators(asyncInfo->returnTypes, [&](const std::shared_ptr<ClangObjectModel::TypeInfo> t) {
std::string parameter;
if (t->typeKind == CXType_BlockPointer) {
Helpers::Errors::WriteError(nullptr, "Block within another block is not yet supported", false);
} else {
parameter = TypeConvertor::WinrtType(t, t->hasBaseWinRTRepresentation());
if (ClangHelpers::isInterface(t->getTypeSpelling()) || ClangHelpers::isProtocol(t->getTypeSpelling())) {
parameter = ClangHelpers::generateResolvedTypeName("I" + parameter, t->getSDKName());
}
parameter += " " + t->getTypeName();
}
return parameter;
});
ss << " public:" << endl;
ss << " void Init(" << paramsString << ") {" << endl;
for (auto item : asyncInfo->returnTypes) {
if (item->isComType()) {
ss << " "
<< "_" << ClangHelpers::getSynthesizedAsyncClassPropertyName(item) << ".Attach(" << item->getTypeName() << ");" << endl;
} else {
ss << " "
<< "_" << ClangHelpers::getSynthesizedAsyncClassPropertyName(item) << " = " << item->getTypeName() << ";" << endl;
}
}
ss << " }" << endl;
ss << endl;
return ss.str();
}
string generateAsyncClassInstanceMethod(shared_ptr<ClangObjectModel::MethodInfo> method) {
stringstream ss;
ss << " STDMETHODIMP " << method->getMethodNameForRuntimeClass() << "(" << generateParamList(method, false) << ") override {"
<< std::endl;
// getter method.
if (method->returnType->typeInfo->isComType()) {
string varName = "_" + ClangHelpers::getSynthesizedAsyncClassPropertyName(method->returnType->typeInfo);
ss << " auto comPtr" << varName << " = " << varName << ";" << endl;
ss << " *" << method->returnType->typeInfo->getTypeName() << " = comPtr" << varName << ".Detach();" << endl;
} else {
ss << " *" << method->returnType->typeInfo->getTypeName() << " = _"
<< ClangHelpers::getSynthesizedAsyncClassPropertyName(method->returnType->typeInfo) << ";" << endl;
}
ss << " return S_OK;" << endl;
ss << " }" << endl;
ss << endl;
return ss.str();
}
std::string generateInstanceMethod(const std::string classNamePrefix, std::shared_ptr<ClangObjectModel::MethodInfo> method) {
std::stringstream ss;
ss << "STDMETHODIMP " << classNamePrefix << method->getMethodNameForRuntimeClass() << "(" << generateParamList(method, false) << ") {"
<< std::endl;
ss << generateABIBoundaryStart();
// Run through all its parameters, for any delegate type we need to increment its reference count as ObjC blocks do not
// capture non-ObjC types. This count will be decremented after the delegate is invoked.
for (auto param : method->params) {
if (param->delegateParams.size() && !param->marshallDelegateAsAsync) {
// This is a delegate parameter.
string comPtrType = ClangHelpers::generateDelegateName(param->delegateParams);
comPtrType = ClangHelpers::generateResolvedTypeName("I" + comPtrType, param->typeInfo->getSDKName(), false);
string comPtrName = "comPtr_" + param->typeInfo->getTypeName();
ss << " // This is a workaround for clang bug wherein non-objC types are not captured by ObjC blocks." << endl;
ss << " // The incremented ref count will be decremented when we actually invoke the input delegate" << endl;
ss << " ComPtr<" << comPtrType << "> " << comPtrName << " = " << param->typeInfo->getTypeName() << ";" << endl;
ss << " " << comPtrName << ".Detach();" << endl;
}
}
std::string returnInfo;
if (method->returnType->typeInfo->typeKind != CXType_Void) {
returnInfo = "*" + method->returnType->typeInfo->getTypeName() + " = ";
}
std::string objCCall = "";
if (!method->isAsync) {
std::string callString = "[_obj " + generateMsgSend(method) + "]";
objCCall = TypeConvertor::getWRLConvertorFuncForType(method->returnType->typeInfo, callString);
if (!objCCall.empty()) {
ss << " " << returnInfo << objCCall << ";" << std::endl;
ss << " return S_OK;" << std::endl;
} else {
ss << " return E_NOTIMPL;" << std::endl;
}
} else {
std::shared_ptr<ClangObjectModel::AsyncClassInfo> asyncInfo;
for (const auto& p : method->params) {
if (p->marshallDelegateAsAsync) {
asyncInfo = p->asyncInfo;
break;
}
}
if (asyncInfo == nullptr) {
Helpers::Errors::WriteError(nullptr, "No async info found", false);
}
ss << " *__returnValue = nullptr;" << std::endl;
ss << " ComPtr<" << asyncInfo->name.c_str() << "> spAsyncWorker = Make<" << asyncInfo->name.c_str() << ">();" << std::endl;
string callString = "[_obj " + generateMsgSend(method) + "]";
if (returnInfo.empty()) {
ss << " " << callString << ";" << endl;
} else {
string objCCall = TypeConvertor::getWRLConvertorFuncForType(method->returnType->typeInfo, callString);
ss << " " << returnInfo << objCCall << ";" << endl;
}
ss << " *__returnValue = spAsyncWorker.Detach();" << std::endl;
ss << " return S_OK;" << std::endl;
}
ss << generateABIBoundaryEnd();
ss << "}" << std::endl;
return ss.str();
}
std::string generateClass(const std::shared_ptr<ClangObjectModel::InterfaceInfo> iface) {
stringstream ss;
std::string classNamePrefix = g_winrtClassPrefix + iface->name + "::";
if (iface->hasDefaultInitializer) {
// default constructor:
ss << classNamePrefix << g_winrtClassPrefix << iface->name << "() {" << std::endl;
ss << " _obj = [[" << iface->name << " alloc] init];" << std::endl;
ss << "}" << std::endl;
}
// default make:
ss << classNamePrefix << g_winrtClassPrefix << iface->name << "(" << iface->name << "* obj) {" << std::endl;
ss << " _obj = [obj retain];" << std::endl;
ss << "}" << std::endl;
// default destructor
ss << classNamePrefix << "~" << g_winrtClassPrefix << iface->name << "() {" << std::endl;
ss << " [_obj release];" << std::endl;
for (const auto& typeInfo : iface->usedDelegateTypes) {
ss << " [" << typeInfo.second->generateMemberVarName() << " release];" << std::endl;
}
ss << "}" << std::endl;
// default accessor for inner object
ss << "id " << classNamePrefix << "getInnerObject() {" << std::endl;
ss << " return _obj;" << std::endl;
ss << "}" << std::endl;
// parameterized constructors if any:
if (iface->parameterizedInitMethods.size() > 0) {
for (const auto& method : iface->parameterizedInitMethods) {
ss << classNamePrefix << g_winrtClassPrefix << iface->name << "(" << generateParamList(method, false, false) << ") {"
<< std::endl;
ss << " _obj = [[" << iface->name << " alloc] " << generateMsgSend(method) << "];" << std::endl;
ss << "}" << std::endl;
}
}
// For composable objects RuntimeClassInitialize is where we create the composable COM object.
if (iface->DerivesFromUIElement()) {
// NOTE: The following is very specific to UI elements which all will derive from Windows.UI.Xaml.Controls.ContentControl;
ss << "STDMETHODIMP " << classNamePrefix << "RuntimeClassInitialize() {" << std::endl;
ss << " ComPtr<ABI::Windows::UI::Xaml::Controls::IContentControlFactory> baseFactory;" << std::endl;
ss << " ComPtr<IInspectable> inner;" << std::endl;
ss << " ComPtr<IInspectable> thisInspectable;" << endl;
ss << " ComPtr<ABI::Windows::UI::Xaml::Controls::IContentControl> instance;" << std::endl;
ss << " "
"RETURN_IF_FAILED(ABI::Windows::Foundation::GetActivationFactory(HStringReference(RuntimeClass_Windows_UI_Xaml_Controls_"
"ContentControl).Get(), &baseFactory));"
<< std::endl;
ss << " RETURN_IF_FAILED(QueryInterface(IID_PPV_ARGS(&thisInspectable)));" << endl;
ss << " RETURN_IF_FAILED(baseFactory->CreateInstance(thisInspectable.Get(), &inner, &instance));" << endl;
ss << " RETURN_IF_FAILED(SetComposableBasePointers(inner.Get(), nullptr));" << std::endl;
ss << " auto xamlComObj = [[_obj xamlElement] comObj];" << std::endl;
ss << " // Anchor point in WinRT is (0,0) whereas, in ObjC it is (0.5, 0.5)." << endl;
ss << " // This results in UI elements being rendered at wrong place." << endl;
ss << " // We call setAnchorPoint on the UI element to fix this." << endl;
ss << " [_obj.layer setAnchorPoint:CGPointMake(0,0)];" << endl;
ss << " RETURN_IF_FAILED(instance->put_Content(xamlComObj.Get()));" << std::endl;
ss << " //Save a WeakRef of the Com object with the objective-c object." << endl;
ss << " WeakRef _weakRef;" << endl;
ss << " Microsoft::WRL::AsWeak(this, &_weakRef);" << endl;
ss << " WeakRefWrapper* _weakRefWrapper = [[[WeakRefWrapper alloc] init] autorelease];" << endl;
ss << " _weakRefWrapper.weakRefComObj = _weakRef;" << endl;
ss << " [_obj setWeakRefWrapper : _weakRefWrapper];" << endl;
ss << " return S_OK;" << std::endl;
ss << "}" << std::endl;
}
std::shared_ptr<ClangObjectModel::InterfaceInfo> interfaceIter = iface;
while (interfaceIter != nullptr) {
ss << "// " << ClangHelpers::generateResolvedTypeName("I" + interfaceIter->name, interfaceIter->getSDKName()) << std::endl;
for (const auto& method : interfaceIter->instanceMethods) {
ss << generateInstanceMethod(classNamePrefix, method);
}
for (const auto& protocol : interfaceIter->getProtocolsImplemented()) {
ss << "// " << ClangHelpers::generateResolvedTypeName("I" + protocol->name, protocol->getSDKName()) << std::endl;
for (const auto& method : protocol->instanceMethods) {
ss << generateInstanceMethod(classNamePrefix, method);
}
}
interfaceIter = interfaceIter->GetBaseClass();
}
ss << std::endl;
ss << generateClassFactory(iface) << std::endl;
std::string factoryName = generateRTFactoryName(iface);
if (iface->isActivatableStaticOnlyFactory()) {
// Just some class methods without any constructors
ss << "ActivatableStaticOnlyFactory(" << factoryName << ")" << std::endl;
} else {
ss << "ActivatableClassWithFactory(" << g_winrtClassPrefix << iface->name << ", " << factoryName << ")" << std::endl;
}
return ss.str();
}
std::string generateObjCCreatorFunctions(
const std::unordered_map<std::string, std::shared_ptr<ClangObjectModel::TypeInfo>>& creatorFuncMap) {
stringstream ss;
stringstream forwardDeclareStream;
for (auto ifaceInfo : g_globalData.currentComponent->ifaces) {
std::string rtName = g_winrtClassPrefix + ifaceInfo.first;
ss << "id _GetObjCFor" << rtName << "(IInspectable* val) {\n";
ss << " " << rtName << "* _cls = reinterpret_cast<" << rtName << "*>(val);\n";
ss << " return _cls->getInnerObject();\n";
ss << "}\n\n";
std::string runtimeClass = ClangHelpers::generateResolvedTypeName(g_winrtClassPrefix + Helpers::baseType(ifaceInfo.first, true),
ifaceInfo.second->getSDKName(),
false,
"");
std::string ABIInterface =
ClangHelpers::generateResolvedTypeName("I" + Helpers::baseType(ifaceInfo.first, true), ifaceInfo.second->getSDKName(), false);
ss << "ComPtr<IInspectable> _Get" << rtName << "ForObjC(id obj) {\n";
// NOTE: We need to cast the runtime class to an interface before casting to IInspectable.
// All Winrt interfaces derive from IInspectable. When a runtime class implements/subclasses 2 or more interfaces, we have a
// diamond problem as both interfaces
// derive from IInspectable.
ss << " ComPtr<" << ABIInterface << "> temp = Make<" + runtimeClass + ">(obj);" << std::endl;
ss << " return temp;" << std::endl;
ss << "}\n\n";
}
for (const auto& creatorFunc : creatorFuncMap) {
std::shared_ptr<ClangObjectModel::TypeInfo> typeInfo = creatorFunc.second;
const TypeConvertor::ContainerTypeInfo* ci = TypeConvertor::GetContainerInfo(typeInfo->getTypeSpelling());
if (ci) {
// forward declare the creator methods.
forwardDeclareStream << "id " << creatorFunc.first << "(IInspectable* val);" << std::endl;
ss << "id " << creatorFunc.first << "(IInspectable* val) {" << std::endl;
TypeConvertor::ToObjCTypeConvertor* convertor = ci->toObjCConvertor;
if (convertor) {
ss << convertor->instantiator(typeInfo) << std::endl;
}
ss << "}" << std::endl << std::endl;
} else {
throw std::invalid_argument("Creator functions are to be used only for containers");
}
}
return forwardDeclareStream.str() + "\n" + ss.str();
}
std::string generateHeterogeneousContainerDeclarations(const std::shared_ptr<ClangObjectModel::ComponentInfo>& component) {
stringstream ss;
ss << g_copyrightNotice;
ss << "#pragma once" << std::endl << std::endl;
ss << "#import <UWP/ObjCHelpers.h>" << std::endl;
// Generate the declaration for ObjC creator and the interface definition for the heterogeneous container types.
ss << ContainerTemplates::generateObjCWrapperDeclaration(component) << endl << endl;
ss << ContainerTemplates::generateRTWrapperDeclaration(component) << endl;
return ss.str();
}
std::string generateHeaders(const std::shared_ptr<ClangObjectModel::InterfaceInfo>& iface) {
stringstream ss;
ss << g_copyrightNotice;
ss << "#pragma once" << std::endl << std::endl;
// ComIncludes are required as the generated headers require 'interface' as a type declaration.
ss << "#include <ComIncludes.h>" << std::endl;
ss << "#include \"" << ClangHelpers::generateNamespaceString(g_globalData.currentComponent->getSDKName(), ".") << "."
<< g_globalData.currentComponent->SDKHeaderFile << ".h\"" << std::endl;
ss << "#include <ComIncludes_End.h>" << std::endl;
ss << "#import <" << iface->getSDKName() << "/" << g_globalData.currentComponent->SDKHeaderFile << ".h>" << std::endl << std::endl;
ss << "#include \"" << g_sdkParameters.rootNameSpace << ".h\"" << std::endl;
std::string namespaceName = ClangHelpers::generateNamespaceString(g_globalData.currentComponent->getSDKName(), "{\nnamespace ");
ss << "namespace " << namespaceName << " {" << std::endl;
// dump all forward declarations
std::string decl = "";
for (auto ifaceMap : g_globalData.currentComponent->ifaces) {
if (ifaceMap.first == iface->name) {
continue;
}
decl = g_winrtClassPrefix + ifaceMap.first;
ss << "class " << decl << ";" << std::endl;
}
auto classNameStr =
"RuntimeClass_" + ClangHelpers::generateNamespaceString(g_globalData.currentComponent->getSDKName(), "_") + "_" + iface->name;
// forward declare the ObjC Creator function for this interface.
ss << "id _GetObjCFor" << g_winrtClassPrefix << iface->name << "(IInspectable* val);\n";
// forward declare the WRL Creator function for this interface.
ss << "ComPtr<IInspectable> _Get" << g_winrtClassPrefix << iface->name << "ForObjC(id obj);\n\n";
string implementedInterfaces;
std::shared_ptr<ClangObjectModel::InterfaceInfo> interfaceIter = iface;
while (interfaceIter != nullptr && (g_globalData.objCSuperClasses.find(interfaceIter->name) == g_globalData.objCSuperClasses.end())) {
implementedInterfaces += (implementedInterfaces.empty() ? "" : ", ") +
ClangHelpers::generateResolvedTypeName("I" + interfaceIter->name, interfaceIter->getSDKName());
for (const auto& protocol : interfaceIter->getProtocolsImplemented()) {
implementedInterfaces += ", " + ClangHelpers::generateResolvedTypeName("I" + protocol->name, protocol->getSDKName());
}
interfaceIter = interfaceIter->GetBaseClass();
}
// The class:
ss << "class " << g_winrtClassPrefix << iface->name << " : public RuntimeClass<" << implementedInterfaces
<< (iface->DerivesFromUIElement() ? ", ComposableBase<>" : "") << ">, public GetInnerObject {" << std::endl;
ss << " " << iface->name << "* _obj;" << std::endl;
ss << " InspectableClass(" << classNameStr << ", BaseTrust)" << std::endl;
ss << "public:" << std::endl;
for (const auto& typeInfo : iface->usedDelegateTypes) {
ss << " id " << typeInfo.second->generateMemberVarName() << ";" << std::endl;
}
if (iface->hasDefaultInitializer) {
// default constructor:
ss << " " << g_winrtClassPrefix << iface->name << "();" << std::endl;
}
// default make: This is used for marshalling the objC instance,
// by creating the runtime class instance from Objective C instance.
ss << " " << g_winrtClassPrefix << iface->name << "(" << iface->name << "* obj);" << std::endl;
// default destructor
ss << " ~" << g_winrtClassPrefix << iface->name << "();" << std::endl;
// default accessor for inner object
ss << " id getInnerObject() override;" << std::endl;
if (iface->DerivesFromUIElement()) {
ss << " STDMETHODIMP RuntimeClassInitialize();" << std::endl;
}
// parameterized constructors if any:
if (iface->parameterizedInitMethods.size() > 0) {
for (const auto& method : iface->parameterizedInitMethods) {
ss << " " << g_winrtClassPrefix << iface->name << "(" << generateParamList(method, false, false) << ");" << std::endl;
}
}
interfaceIter = iface;
while (interfaceIter != nullptr) {
ss << " // " << ClangHelpers::generateResolvedTypeName("I" + interfaceIter->name, interfaceIter->getSDKName()) << std::endl;
for (const auto& method : interfaceIter->instanceMethods) {
ss << " STDMETHODIMP " << method->getMethodNameForRuntimeClass() << "(" << generateParamList(method, false) << ") override;"
<< std::endl;
}
for (const auto& protocol : interfaceIter->getProtocolsImplemented()) {
ss << " // " << ClangHelpers::generateResolvedTypeName("I" + protocol->name, protocol->getSDKName()) << std::endl;
for (const auto& method : protocol->instanceMethods) {
ss << " STDMETHODIMP " << method->getMethodNameForRuntimeClass() << "(" << generateParamList(method, false)
<< ") override;" << std::endl;
}
}
interfaceIter = interfaceIter->GetBaseClass();
}
ss << "};" << std::endl;
ss << "}" << std::endl;
// Add as many closing bracket as there are opening brackets in namespaceName
int count = std::count(namespaceName.begin(), namespaceName.end(), '{');
for (int i = 0; i < count; i++) {
ss << "}" << std::endl;
}
return ss.str();
}
string generateObjCDelegateCallbackDeclaration(shared_ptr<ClangObjectModel::ProtocolInfo> delegateCallback) {
stringstream ss;
ss << "#import <Foundation/Foundation.h>" << endl;
ss << "#import <" << delegateCallback->getSDKName() << "/" << delegateCallback->SDKHeaderFile << ".h>" << endl;
ss << endl;
string resolvedName = ClangHelpers::generateResolvedTypeName("I" + delegateCallback->name, delegateCallback->getSDKName());
ss << "@interface " << delegateCallback->name << " : NSObject<" << delegateCallback->name << "> {" << endl;
ss << " ComPtr<" << resolvedName << "> comObj;" << endl;
ss << "}" << endl;
ss << "- (instancetype)initWith:(ComPtr<" << resolvedName << ">)obj;" << endl;
ss << "- (ComPtr<" << resolvedName << ">)getInternalComObj;" << endl;
ss << "@end" << endl;
ss << endl;
return ss.str();
}
string generateObjCDelegateCallbackDefinitions() {
stringstream ss;
for (auto delMap : g_globalData.currentComponent->delegateCallbackProtocolsMap) {
string resolvedName = ClangHelpers::generateResolvedTypeName("I" + delMap.first, g_globalData.currentComponent->getSDKName());
ss << "@implementation " << delMap.first << endl;
ss << "- (instancetype)initWith:(ComPtr<" << resolvedName << ">)obj {" << endl;
ss << " if (self = [super init]) {" << endl;
ss << " comObj = obj;" << endl;
ss << " }" << endl;
ss << " return self;" << endl;
ss << "}" << endl;
ss << endl;
ss << "- (ComPtr<" << resolvedName << ">)getInternalComObj {" << endl;
ss << " return comObj;" << endl;
ss << "}" << endl;
ss << endl;
for (auto instMethod : delMap.second->instanceMethods) {
string objCMethodSignature = instMethod->objectiveCSignature;
size_t pos = objCMethodSignature.find(";");
objCMethodSignature = objCMethodSignature.substr(0, pos);
string returnValue = "";
string returnParam = "";
bool hasReturnType = (instMethod->returnType->typeInfo->typeKind != CXType_Void);
ss << objCMethodSignature << " {" << endl;
if (hasReturnType) {
returnValue = "__winRTReturnValue";
returnParam = ", &" + returnValue;
ss << " " << TypeConvertor::WinrtType(instMethod->returnType->typeInfo) << " " << returnValue << ";" << endl;
}
vector<string> parameters;
string parameterList;
for (unsigned int i = 0; i < instMethod->params.size(); i++) {
const auto& param = instMethod->params[i];
// Get a WRL object for the objective-c object and assign it to a temp.
string temp = "__" + param->typeInfo->getTypeName();
ss << " auto " << temp << " = "
<< TypeConvertor::getWRLConvertorFuncForType(param->typeInfo, param->typeInfo->getTypeName()) << ";" << endl;
bool paramDerivesFromUIElement = false;
string paramTypeName = param->typeInfo->getTypeSpelling(true);
auto paramIface = g_globalData.interfaceMap.find(paramTypeName);
if (paramIface != g_globalData.interfaceMap.end() && paramIface->second->DerivesFromUIElement()) {
paramDerivesFromUIElement = true;
}
// Build up the parameter list for the callback.
parameterList += temp;
if (paramDerivesFromUIElement) {
parameterList += ".Get()";
}
if (i < instMethod->params.size() - 1) {
parameterList += ", ";
}
}
ss << " comObj->" << instMethod->getMethodNameForRuntimeClass() << "(" << parameterList << returnParam << ");" << endl;
if (hasReturnType) {
instMethod->returnType->typeInfo->setTypeName(returnValue);
ss << " return " << marshalToObjC(instMethod->returnType) << ";" << endl;
}
ss << "}" << endl;
ss << endl;
}
ss << "@end" << endl;
}
return ss.str();
}
// Generate the ObjC++ code that acts as the implementation of the runtime classes:
std::string generateClassBindings(const std::shared_ptr<ClangObjectModel::ComponentInfo> component) {
stringstream ss;
ss << g_copyrightNotice;
ss << "#include <ComIncludes.h>" << std::endl;
ss << "#include \"" << ClangHelpers::generateNamespaceString(component->getSDKName(), ".") << "." << component->SDKHeaderFile << ".h\""
<< std::endl;
ss << "#include <windows.foundation.h>" << std::endl;
ss << "#include <wrl.h>" << std::endl;
ss << "#include <wrl/implements.h>" << std::endl;
ss << "#include <wrl/async.h>" << std::endl;
ss << "#include <wrl/module.h>" << std::endl;
ss << "#include <ComIncludes_End.h>" << std::endl << std::endl;
ss << "#import <UWP/ObjCHelpers.h>" << std::endl;
ss << "#include \"" << g_sdkParameters.rootNameSpace << ".h\"" << std::endl;
ss << "#import <" << component->getSDKName() << "/" << component->SDKHeaderFile << ".h>" << std::endl << std::endl;
ss << "#include <Winstring.h>" << endl;
set<string> headerNames;
for (auto iface : component->ifaces) {
std::string headerName =
ClangHelpers::generateNamespaceString(component->getSDKName(), ".") + "." + component->SDKHeaderFile + "." + iface.first + ".h";
headerNames.insert(headerName);
}
for (auto ifaceName : component->referencedInterfaces) {
std::string headerName = ifaceName + ".h";
headerNames.insert(headerName);
}
for (auto protocolName : component->referencedProtocols) {
// We need to include the header of the interface which implements this protocol.
// The format of referencedProtocols is:
// "SDKName.HeaderFileName.ProtocolName"
size_t pos1 = protocolName.find_last_of(".");
size_t pos2 = protocolName.find_last_of(".", pos1 - 1);
// Everything after pos1 is the name of the interface:
protocolName = protocolName.substr(pos1 + 1, protocolName.length() - pos1 - 1);
auto iface = ClangHelpers::getInterfaceImplementingProtocol(protocolName);
string headerName;
if (iface == nullptr) {
// This is a delegate callback protocol.
auto it = g_globalData.delegateCallbackProtocolsMap.find(protocolName);
if (it == g_globalData.delegateCallbackProtocolsMap.end() || it->second->implHeaderName.empty()) {
Helpers::Errors::WriteError(nullptr, "No marshalling code for delegate callback protocol" + protocolName, false);
}
headerName = it->second->implHeaderName;
} else {
headerName =
ClangHelpers::generateNamespaceString(iface->getSDKName(), ".") + "." + iface->SDKHeaderFile + "." + iface->name + ".h";
}
headerNames.insert(headerName);
}
for (auto delegatePair : component->delegateCallbackProtocolsMap) {
if (delegatePair.second->implHeaderName.empty()) {
Helpers::Errors::WriteError(nullptr, "No marshalling code for delegate callback protocol" + delegatePair.first, false);
}
headerNames.insert(delegatePair.second->implHeaderName);
}
// Even the headers corresponding to referenced IDLs need to be included.
for (auto ref : component->referencedIDLs) {
if (ClangObjectModel::GlobalData::defaultDependentIdls.find(ref) != ClangObjectModel::GlobalData::defaultDependentIdls.end()) {
continue;
}
string header = ref.substr(0, ref.rfind(".idl")) + ".h";
headerNames.insert(header);
}
for (auto headerName : headerNames) {
ss << "#import \"" << headerName << "\"" << std::endl;
}
if (component->heterogeneousContainers.size()) {
std::string namespaceString = ClangHelpers::generateNamespaceString(component->getSDKName(), ".");
ss << "#import \"" << namespaceString + "." + component->SDKHeaderFile + "._Containers.h\"\n";
}
ss << std::endl;
ss << "using Microsoft::WRL::ActivationFactory;" << std::endl;
ss << "using Microsoft::WRL::Make;" << std::endl;
ss << "using Microsoft::WRL::RuntimeClass;" << std::endl;
ss << std::endl;
for (const auto& ifaceMap : component->ifaces) {
if (ifaceMap.second->DerivesFromUIElement()) {
auto iface = ifaceMap.second;
ss << "@interface " << iface->name << "(ComObj)" << endl;
ss << " @property (nonatomic, retain) WeakRefWrapper* weakRefWrapper;" << endl;
ss << "@end" << endl;
ss << endl;
ss << "@implementation " << iface->name << "(ComObj)" << endl;
ss << " - (void)setWeakRefWrapper:(WeakRefWrapper*)object { " << endl;
ss << " objc_setAssociatedObject(self, @selector(weakRefWrapper), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC); " << endl;
ss << " }" << endl;
ss << " -(WeakRefWrapper*)weakRefWrapper { " << endl;
ss << " return objc_getAssociatedObject(self, @selector(weakRefWrapper));" << endl;
ss << " }" << endl;
ss << "@end" << endl;
}
}
if (g_globalData.currentComponent->delegateCallbackProtocolsMap.size()) {
ss << generateObjCDelegateCallbackDefinitions() << endl;
}
ss << "namespace " << ClangHelpers::generateNamespaceString(component->getSDKName(), "{\nnamespace ") << " {" << std::endl;
// forward declare any class factories we may be using
for (const auto& ifaceMap : component->ifaces) {
auto iface = ifaceMap.second;
if (iface->classMethods.size() == 0 && iface->parameterizedInitMethods.size() == 0) {
continue;
}
std::string name = generateRTFactoryName(ifaceMap.second);
ss << "class " << name << ";" << std::endl;
}
ss << std::endl;
// Generate our ObjC creator functions.
std::unordered_map<std::string, std::shared_ptr<ClangObjectModel::TypeInfo>> objCCreatorFuncs = component->getObjcCreatorFuncs();
ss << generateObjCCreatorFunctions(objCCreatorFuncs);
// Generate our heterogeneous container type creators.
ss << ContainerTemplates::generateHeterogeneousCreators(g_globalData.currentComponent);
for (const auto& asyncClass : g_globalData.currentComponent->asyncClasses) {
std::string asyncClassName = asyncClass->name;
// Todo: there has to be a better way to do this.
if (asyncClass->synthesizedInterface != nullptr) {
auto synthesizedIface = asyncClass->synthesizedInterface;
string className = synthesizedIface->GetWinrtClassName();
string resolvedInterfaceName = ClangHelpers::generateResolvedTypeName("I" + className, synthesizedIface->getSDKName());
ss << "class " << className << " : public RuntimeClass<" << resolvedInterfaceName << "> {" << endl;
// generate the private member variables for the aggregated types.
for (auto item : asyncClass->returnTypes) {
string typeName = TypeConvertor::WinrtType(item, item->hasBaseWinRTRepresentation());
if (item->isInterface()) {
typeName = ClangHelpers::generateResolvedTypeName("I" + typeName, item->getSDKName());
}
if (item->isComType()) {
typeName = "ComPtr<" + Helpers::baseType(typeName, true) + ">";
}
ss << " " << typeName << " _" << ClangHelpers::getSynthesizedAsyncClassPropertyName(item) << ";" << endl;
}
ss << " InspectableClass(L\"Windows.Foundation.IAsyncOperation<" << resolvedInterfaceName << "*>\", BaseTrust); "
<< std::endl;
for (auto method : synthesizedIface->instanceMethods) {
ss << generateAsyncClassInstanceMethod(method);
}
ss << generateAsyncClassInitMethod(asyncClass);
ss << "};" << endl;
ss << endl;
} else {
ss << "class " << asyncClassName << " : " << std::endl;
ss << " public RuntimeClass<" << std::endl;
ss << " IAsyncAction," << std::endl;
ss << " AsyncBase<IAsyncActionCompletedHandler>> {" << std::endl;
ss << " InspectableClass(InterfaceName_Windows_Foundation_IAsyncAction, BaseTrust);" << std::endl;
ss << "public:" << std::endl;
ss << " " << asyncClassName << "()" << std::endl;
ss << " {" << std::endl;
ss << " Start();" << std::endl;
ss << " }" << std::endl;
ss << " IFACEMETHODIMP put_Completed(IAsyncActionCompletedHandler *pCompleteHandler) override" << std::endl;
ss << " {" << std::endl;
ss << " return AsyncBase::PutOnComplete(pCompleteHandler);" << std::endl;
ss << " }" << std::endl;
ss << " IFACEMETHODIMP get_Completed(IAsyncActionCompletedHandler **ppCompleteHandler) override" << std::endl;
ss << " {" << std::endl;
ss << " return AsyncBase::GetOnComplete(ppCompleteHandler);" << std::endl;
ss << " }" << std::endl;
ss << " void setResult()" << std::endl;
ss << " {" << std::endl;
ss << " FireCompletion();" << std::endl;
ss << " }" << std::endl;
ss << " IFACEMETHODIMP GetResults() override" << std::endl;
ss << " {" << std::endl;
ss << " return AsyncBase::CheckValidStateForResultsCall();" << std::endl;
ss << " }" << std::endl;
ss << " HRESULT OnStart() override" << std::endl;
ss << " {" << std::endl;
ss << " return S_OK;" << std::endl;
ss << " }" << std::endl;
ss << " void OnClose() override {}" << std::endl;
ss << " void OnCancel() override {}" << std::endl;
ss << "};" << std::endl;
ss << std::endl;
}
}
for (const auto& ifaceMap : component->ifaces) {
auto iface = ifaceMap.second;
ss << generateClass(iface) << std::endl;
}
ss << ContainerTemplates::generateObjCMarshallingMethods(component);
ss << ContainerTemplates::generateRTMarshallingMethods(component);
ss << ContainerTemplates::generateRTWrapperDefinitions(component);
ss << "}" << std::endl << "}" << std::endl;
ss << ContainerTemplates::generateObjCWrapperDefinition(component);
return ss.str();
}
bool isOutParameter(std::shared_ptr<ClangObjectModel::TypeInfo> typeInfo) {
bool outParam = false;
switch (typeInfo->typeKind) {
case CXType_Pointer:
outParam = true;
break;
case CXType_ObjCObjectPointer:
outParam = false;
break;
}
return outParam;
}
std::string generateAnnotations(std::shared_ptr<ClangObjectModel::TypeInfo> typeInfo) {
std::string typeSpelling = typeInfo->getTypeSpelling();
std::string annotation;
if (isOutParameter(typeInfo)) {
annotation = "[out]";
} else {
annotation = "[in]";
}
return annotation;
}
CXChildVisitResult DelegateVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
std::shared_ptr<ClangObjectModel::ParameterInfo> param = *((std::shared_ptr<ClangObjectModel::ParameterInfo>*)client_data);
CXCursorKind kind = clang_getCursorKind(cursor);
std::shared_ptr<ClangObjectModel::TypeInfo> typeInfo;
switch (kind) {
case CXCursor_ParmDecl:
// These are the delegate parameters.
typeInfo = make_shared<ClangObjectModel::TypeInfo>();
typeInfo->setTypeName(ClangHelpers::GetCursorSpelling(cursor));
typeInfo->setTypeSpelling(ClangHelpers::GetCursorTypeSpelling(cursor));
if (typeInfo->getTypeName() == "") {
typeInfo->setTypeName("d" + std::to_string(param->delegateParams.size()));
}
typeInfo->cursor = cursor;
typeInfo->SDKname = ClangHelpers::GetCursorSDKName(cursor);
typeInfo->typeKind = clang_getCursorType(cursor).kind;
typeInfo->annotation = generateAnnotations(typeInfo);
if (typeInfo->getTypeSpelling(true) == "NSURL") {
if (!param->paramMetaData->blockParameterHasMetaData(param->delegateParams.size())) {
param->paramMetaData->appendMetaData(ClangObjectModel::MetaDataType_BlockParameter,
-1,
param->delegateParams.size(),
vector<string>({ "StorageFile", "Uri" }));
}
}
param->delegateParams.push_back(std::move(typeInfo));
break;
}
return CXChildVisit_Continue;
}
CXChildVisitResult MethodDeclVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
std::shared_ptr<ClangObjectModel::MethodInfo> methodInfo = *((std::shared_ptr<ClangObjectModel::MethodInfo>*)client_data);
CXCursorKind kind = clang_getCursorKind(cursor);
switch (kind) {
case CXCursor_ParmDecl: {
std::shared_ptr<ClangObjectModel::ParameterInfo> param;
std::string typeSpelling = ClangHelpers::GetCursorTypeSpelling(cursor);
CXType type = clang_getCursorType(cursor);
CXTypeKind typeKind = type.kind;
CXTypeKind canonicalTypeKind = clang_getCanonicalType(type).kind;
// modify the typespelling if this is an enum
if (canonicalTypeKind == CXType_Enum) {
typeSpelling = ClangHelpers::getEnumTypeName(typeSpelling);
}
auto it = g_globalData.currentComponent->typedefDecl.find(typeSpelling);
if (typeKind == CXType_Typedef && it != g_globalData.currentComponent->typedefDecl.end()) {
param = it->second;
} else {
param = make_shared<ClangObjectModel::ParameterInfo>();
param->typeInfo = make_shared<ClangObjectModel::TypeInfo>();
param->typeInfo->cursor = cursor;
param->typeInfo->SDKname = ClangHelpers::GetCursorSDKName(cursor);
param->typeInfo->setTypeSpelling(typeSpelling);
param->typeInfo->typeKind = canonicalTypeKind;
}
param->typeInfo->setTypeName(ClangHelpers::GetCursorSpelling(cursor));
param->typeInfo->sourceLocation = ClangHelpers::GetSourceStartingLocation(cursor);
param->marshallDelegateAsAsync = false;
if (param->typeInfo->typeKind == CXType_BlockPointer) {
if (typeKind != CXType_Typedef) {
// Typedefs are already visited.
clang_visitChildren(param->typeInfo->cursor, DelegateVisitor, ¶m);
}
} else {
param->typeInfo->annotation = generateAnnotations(param->typeInfo);
}
methodInfo->params.push_back(std::move(param));
} break;
case CXCursor_FirstAttr: {
CXCursorKind kind = clang_getCursorKind(cursor);
if (clang_isAttribute(kind)) {
std::string source = ClangHelpers::GetSource(cursor);
if (source == "unavailable" || source == "NS_UNAVAILABLE") {
methodInfo->isUnavailable = true;
}
}
} break;
}
return CXChildVisit_Continue;
}
// Create a ClangObjectModel::MethodInfo entry for one particular combination of possible
// value types for arguments(or return types) having "id" as their type.
// The combination of possible types is provided in the input argument metaDataInfo.
// Arguments:
// methodRef: The original ClangObjectModel::MethodInfo, which will be overloaded based on the combination of data type values.
// methodInfo: The vector which stores all the generated ClangObjectModel::MethodInfo entries.
// metaDataInfo: Stores one particular combination for the possible type values for arguments and return types.
// polymorphNumber: The number of times the method (methodRef) is now overloaded.
void _applyMetaDataInfo(std::shared_ptr<ClangObjectModel::MethodInfo>& methodRef,
std::vector<std::shared_ptr<ClangObjectModel::MethodInfo>>& methodInfos,
std::shared_ptr<ClangObjectModel::MetaDataComments>& metaDataInfo,
int polymorphNumber) {
std::shared_ptr<ClangObjectModel::MethodInfo> method = ClangObjectModel::MethodInfo::CloneMethodInfo(methodRef);
if (!method->isSynthesizedProperty) {
if (method->needsDefaultOverload) {
method->idlAnnotation = "[default_overload]" + method->idlAnnotation;
}
if (method->isOverloaded) {
string methodNameForIdl = method->getMethodNameForIdl();
if (method->returnTypePolymorphId > 0) {
methodNameForIdl += to_string(method->returnTypePolymorphId);
}
method->idlAnnotation += "[overload(\"" + methodNameForIdl + "\")]";
}
}
method->isAsync = metaDataInfo->hasAsyncMetaData();
if (polymorphNumber > 0) {
std::string methodNameForRuntimeClass;
if (method->isSynthesizedProperty) {
methodNameForRuntimeClass = method->getMethodNameForRuntimeClass() + to_string(polymorphNumber);
string methodNameForIDL = method->getMethodNameForIdl() + ::to_string(polymorphNumber);
method->UpdateMethodNameForIDLAndRuntimeClass(methodNameForIDL, methodNameForRuntimeClass);
} else {
methodNameForRuntimeClass = method->name + to_string(polymorphNumber);
method->UpdateMethodNameForIDLAndRuntimeClass(methodNameForRuntimeClass);
}
} else if (!method->isSynthesizedProperty) {
method->UpdateMethodNameForIDLAndRuntimeClass(method->name);
}
method->returnType->typeInfo->ResolveReturnType(metaDataInfo->getReturnMetaData());
for (size_t i = 0; i < method->params.size(); i++) {
if (method->params[i]->delegateParams.size() > 0) {
for (size_t j = 0; j < method->params[i]->delegateParams.size(); j++) {
method->params[i]->delegateParams[j]->ResolveParameterType(metaDataInfo->getBlockParameterMetaData(i, j));
}
} else {
method->params[i]->typeInfo->ResolveParameterType(metaDataInfo->getParameterMetaData(i));
}
}
for (auto param : method->params) {
if (param->typeInfo->typeKind == CXType_BlockPointer) {
if (method->isAsync) {
ClangHelpers::updateAsyncClassInfo(param, method);
} else {
ClangHelpers::updateDelegateInfo(param, method);
}
}
}
methodInfos.push_back(method);
}
// Here we recursively combine all possible values for all the types which may have multiple values.
// This produces a cross product of values for all the types, and for each such cross product, we create
// a ClangObjectModel::MethodInfo entry, which is our API surface for that combination of argument types.
// Arguments:
// methodRef: The original ClangObjectModel::MethodInfo, which will be overloaded based on the combination of data type values.
// methodInfo: The vector which stores all the generated ClangObjectModel::MethodInfo entries.
// metaDataInfo: The entire annotation (ClangObjectModel::MetaDataComments) provided on the ObjC declaration.
// info: Stores one particular combination for the possible type values for arguments and return types.
// currentMetatDataLine: The line number of the input annotation. Each annotation goes on a separate line.
// polymorphNumber: The number of times the method (methodRef) is now overloaded.
int applyMetaDataInfo(std::shared_ptr<ClangObjectModel::MethodInfo>& methodRef,
std::vector<std::shared_ptr<ClangObjectModel::MethodInfo>>& methodInfo,
std::shared_ptr<ClangObjectModel::MetaDataComments>& metaDataInfo,
std::shared_ptr<ClangObjectModel::MetaDataComments>& info,
bool isFromApplicationDelegate,
int currentMetaDataLine = 0,
int polymorphNumber = 0) {
// We do not apply any metadata for methods from the delegate.
// These are generated as is without any modifications.
if (isFromApplicationDelegate) {
std::string metaDataType = metaDataInfo->getMetaDataType(0);
// We do not generate the allocators and initializers for application delegate interface.
// We simply need to know the method name.
if (metaDataType == ClangObjectModel::MetaDataType_DelegateAllocator) {
g_globalData.applicationDelegateInfo->allocatorMethod = methodRef;
} else if (metaDataType == ClangObjectModel::MetaDataType_DelegateInitializer) {
g_globalData.applicationDelegateInfo->initializerMethod = methodRef;
} else if (metaDataType == ClangObjectModel::MetaDataType_DelegateAllocatorAndInitializer) {
g_globalData.applicationDelegateInfo->allocatorMethod = methodRef;
g_globalData.applicationDelegateInfo->initializerMethod = methodRef;
} else {
methodInfo.push_back(methodRef);
}
return 0;
}
int totalMetaDataLines = metaDataInfo->getMetaDataSize();
if (currentMetaDataLine == totalMetaDataLines) {
// we have all the required info
_applyMetaDataInfo(methodRef, methodInfo, info, polymorphNumber);
methodRef->needsDefaultOverload = false;
return polymorphNumber + 1;
}
int currentNumber = polymorphNumber;
int count = metaDataInfo->getTypes(currentMetaDataLine).size();
bool setReturnTypePolymorphId = false;
if (count > 1) {
methodRef->isPolymorphic = true;
bool isMetaDataForReturnType =
(metaDataInfo->getMetaDataType(currentMetaDataLine) == ClangObjectModel::MetaDataType_ReturnType) ||
(metaDataInfo->hasAsyncMetaData() && metaDataInfo->getBlockParameterNumber(currentMetaDataLine) != -1);
if (isMetaDataForReturnType) {
setReturnTypePolymorphId = true;
} else if (!methodRef->isOverloaded) {
methodRef->isOverloaded = true;
methodRef->needsDefaultOverload = true;
}
}
for (int j = 0; j < count; j++) {
if (setReturnTypePolymorphId) {
methodRef->returnTypePolymorphId = j;
if (methodRef->isOverloaded) {
methodRef->needsDefaultOverload = true;
}
}
info->setTypes(currentMetaDataLine, { metaDataInfo->getTypes(currentMetaDataLine)[j] });
info->setMetaDataType(currentMetaDataLine, metaDataInfo->getMetaDataType(currentMetaDataLine));
info->setParameterNumber(currentMetaDataLine, metaDataInfo->getParameterNumber(currentMetaDataLine));
info->setBlockParameterNumber(currentMetaDataLine, metaDataInfo->getBlockParameterNumber(currentMetaDataLine));
currentNumber =
applyMetaDataInfo(methodRef, methodInfo, metaDataInfo, info, isFromApplicationDelegate, currentMetaDataLine + 1, currentNumber);
}
return currentNumber;
}
CXChildVisitResult EnumVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
std::shared_ptr<ClangObjectModel::TypeInfo> enumInfo = *((std::shared_ptr<ClangObjectModel::TypeInfo>*)client_data);
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_EnumConstantDecl) {
std::string constantName = ClangHelpers::GetCursorSpelling(cursor);
long long value = clang_getEnumConstantDeclUnsignedValue(cursor);
if (value & 0xFFFFFFFF00000000) {
// ToDo: IDL enum constants are of type 'int' and cannot marshall enum values greater than 32 bit!!
Helpers::Errors::WriteError(cursor, "Enums with 64bit values are not supported.\n", true);
}
int32_t constantValue = (int32_t)value;
enumInfo->enumConstants.insert({ constantName, constantValue });
} else if (kind == CXCursor_EnumDecl) {
return CXChildVisit_Recurse;
}
return CXChildVisit_Continue;
}
void handleEnums(const CXCursor cursor, std::shared_ptr<ClangObjectModel::ComponentInfo>& component) {
std::shared_ptr<ClangObjectModel::TypeInfo> enumInfo;
std::string spelling = ClangHelpers::GetCursorSpelling(cursor);
if (spelling.empty()) {
// This is unnamed enum.
// We handle it when we get the cursor with the typedef, else unnamed enums are of no use to us as they do not define any type.
return;
}
auto it = g_globalData.enums.find(spelling);
if (it != g_globalData.enums.end()) {
enumInfo = it->second;
if (enumInfo->enumConstants.size() &&
(enumInfo->getSDKName() != component->getSDKName() || enumInfo->SDKHeaderFile != component->SDKHeaderFile)) {
// With enums there is no partial declaration.
// If we have the enum constants then this declaration was already handled.
// The component in which this enum is defined becomes our referenced IDL.
component->referencedIDLs.insert(ClangHelpers::generateNamespaceString(enumInfo->getSDKName(), ".") + "." +
enumInfo->SDKHeaderFile + ".idl");
return;
}
} else {
enumInfo = make_shared<ClangObjectModel::TypeInfo>();
enumInfo->setTypeSpelling(spelling);
enumInfo->typeKind = CXType_Enum;
}
clang_visitChildren(cursor, EnumVisitor, &enumInfo);
if (enumInfo->enumConstants.size() == 0) {
// some weird libclang behavior for the expansion of NS_ENUM macro.
// The same enum is reported in the AST multiple times, one is the actual enum declaration,
// the second is the typedef declaration, and this is the third one with no constants.
// We ignore the third one.
return;
}
// Set this only when we have processed the actual enum declaration.
enumInfo->SDKname = ClangHelpers::GetCursorSDKName(cursor);
enumInfo->SDKHeaderFile = component->SDKHeaderFile;
component->enums.insert({ enumInfo->getTypeSpelling(), enumInfo });
if (it == g_globalData.enums.end()) {
g_globalData.enums.insert({ enumInfo->getTypeSpelling(), enumInfo });
}
}
void _parsePropertyDeclaration(const string& src, const string& propertyName, string& getterName, string& setterName) {
// This could be simplified, but this is the best so far.
std::regex regGetter(
"(?:[\\(])(?:[a-zA-Z0-9_, =:]*)(?:getter{1})(?:[[:s:]]*)(?:={1})(?:[[:s:]]*)([a-zA-Z0-9_]+)(?:[a-zA-Z0-9_, =:]*)(?:[\\)])");
std::smatch matchGetter;
if (std::regex_search(src.begin(), src.end(), matchGetter, regGetter)) {
getterName = matchGetter[1];
} else {
getterName = propertyName;
}
std::regex regSetter(
"(?:[\\(])(?:[a-zA-Z0-9_, =:]*)(?:setter{1})(?:[[:s:]]*)(?:={1})(?:[[:s:]]*)([a-zA-Z0-9_]+)(?:[a-zA-Z0-9_, =:]*)(?:[\\)])");
std::smatch matchSetter;
if (std::regex_search(src.begin(), src.end(), matchSetter, regSetter)) {
setterName = matchSetter[1];
} else {
setterName = propertyName;
// capitalize first letter for the setter
if (setterName[0] >= 'a' && setterName[0] <= 'z') {
setterName[0] = setterName[0] - 'a' + 'A';
}
setterName = "set" + setterName;
}
}
std::shared_ptr<ClangObjectModel::PropertyInfo> HandlePropertyDecl(CXCursor cursor) {
std::string propertyName = ClangHelpers::GetCursorSpelling(cursor);
std::string getterName;
std::string setterName;
string src = ClangHelpers::GetSource(cursor);
// parse the property declaration to find if there are any custom getters and setters.
_parsePropertyDeclaration(src, propertyName, getterName, setterName);
// extract raw comment if any which will be used by the synthesized accessor methods.
std::shared_ptr<ClangObjectModel::MetaDataComments> metadata = std::make_shared<ClangObjectModel::MetaDataComments>(cursor, true);
std::shared_ptr<ClangObjectModel::PropertyInfo> propInfo =
make_shared<ClangObjectModel::PropertyInfo>(propertyName, getterName, setterName, metadata);
return propInfo;
}
std::shared_ptr<ClangObjectModel::MethodInfo> HandleMethodDecl(CXCursor cursor,
const std::string& interfaceOrProtocolName,
std::vector<std::shared_ptr<ClangObjectModel::PropertyInfo>>& properties,
std::shared_ptr<ClangObjectModel::MetaDataComments>& metaDataInfo) {
std::shared_ptr<ClangObjectModel::MethodInfo> method;
std::shared_ptr<ClangObjectModel::PropertyInfo> property;
string methodName = ClangHelpers::GetMethodSpelling(cursor);
cout << "\t\tTranslating " << methodName << std::endl;
for (auto propInfo : properties) {
if (methodName == propInfo->getter->name) {
property = propInfo;
method = propInfo->getter;
method->isSynthesizedProperty = true;
metaDataInfo = propInfo->metadata;
if (metaDataInfo->getMetaDataType(0) != ClangObjectModel::MetaDataType_IgnoreDecl) {
metaDataInfo->setMetaDataType(0, ClangObjectModel::MetaDataType_ReturnType);
}
break;
}
if (methodName == propInfo->setter->name) {
property = propInfo;
method = propInfo->setter;
method->isSynthesizedProperty = true;
metaDataInfo = propInfo->metadata;
if (metaDataInfo->getMetaDataType(0) != ClangObjectModel::MetaDataType_IgnoreDecl) {
metaDataInfo->setMetaDataType(0, ClangObjectModel::MetaDataType_Parameter);
metaDataInfo->setParameterNumber(0, 0);
}
break;
}
}
if (!property) {
method = make_shared<ClangObjectModel::MethodInfo>();
method->name = methodName;
method->isSynthesizedProperty = false;
metaDataInfo = std::make_shared<ClangObjectModel::MetaDataComments>(cursor);
}
if (metaDataInfo->isIgnoredType()) {
return nullptr;
}
method->objectiveCSignature = ClangHelpers::GetSource(cursor);
method->objectiveCSelector = ClangHelpers::GetCursorSpelling(cursor);
method->SDKname = ClangHelpers::GetCursorSDKName(cursor);
method->isAsync = false;
method->displayName = ClangHelpers::GetDisplayName(cursor);
std::string typeSpelling = ClangHelpers::GetCursorResultTypeSpelling(cursor);
CXTypeKind typeKind = clang_getCursorResultType(cursor).kind;
auto typedefIt = g_globalData.currentComponent->typedefDecl.find(typeSpelling);
method->returnType = make_shared<ClangObjectModel::ParameterInfo>();
method->returnType->typeInfo = make_shared<ClangObjectModel::TypeInfo>();
if (typeKind == CXType_Typedef && typedefIt != g_globalData.currentComponent->typedefDecl.end()) {
method->returnType->typeInfo->cursor = typedefIt->second->typeInfo->cursor;
method->returnType->typeInfo->SDKname = typedefIt->second->typeInfo->getSDKName();
method->returnType->typeInfo->setTypeSpelling(typedefIt->second->typeInfo->getTypeSpelling());
method->returnType->typeInfo->typeKind = typedefIt->second->typeInfo->typeKind;
} else {
method->returnType->typeInfo->cursor = cursor;
method->returnType->typeInfo->SDKname = ClangHelpers::GetCursorSDKName(cursor);
method->returnType->typeInfo->setTypeSpelling(typeSpelling);
method->returnType->typeInfo->typeKind = clang_getCursorResultType(cursor).kind;
method->returnType->typeInfo->sourceLocation = ClangHelpers::GetSourceStartingLocation(cursor);
}
if (Helpers::Trim(method->returnType->typeInfo->getTypeSpelling()) == "instancetype") {
method->returnType->typeInfo->setTypeSpelling(interfaceOrProtocolName + "*");
}
method->returnType->marshallDelegateAsAsync = false;
method->returnType->typeInfo->setTypeName("__returnValue");
method->returnType->typeInfo->annotation = "[out] [retval]";
clang_visitChildren(cursor, MethodDeclVisitor, &method);
if (method->returnType->typeInfo->getTypeSpelling(true) == "NSURL" && metaDataInfo->getReturnMetaData().empty()) {
// There is no metadata for the return type.
// Inject our custom metadata.
metaDataInfo->appendMetaData(ClangObjectModel::MetaDataType_ReturnType, -1, -1, vector<string>({ "StorageFile", "Uri" }));
}
// Run through all through the parameters to check if there is any additional metadata info.
for (size_t i = 0; i < method->params.size(); i++) {
auto param = method->params[i];
if (param->paramMetaData != nullptr) {
int n = param->paramMetaData->getMetaDataSize();
for (int line = 0; line < n; line++) {
std::string type = ClangObjectModel::MetaDataType_Parameter;
auto types = param->paramMetaData->getTypes(line);
int blockNumber = param->paramMetaData->getBlockParameterNumber(line);
metaDataInfo->appendMetaData(type, i, blockNumber, types);
}
}
if (param->typeInfo->getTypeSpelling(true) == "NSURL" && !metaDataInfo->parameterHasMetaData(i)) {
// There is no metadata on this parameter.
// Inject our custom meta data.
metaDataInfo->appendMetaData(ClangObjectModel::MetaDataType_Parameter, i, -1, vector<string>({ "StorageFile", "Uri" }));
}
}
return method;
}
CXChildVisitResult ProtocolVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
std::shared_ptr<ClangObjectModel::ProtocolInfo> protoInfo = *((std::shared_ptr<ClangObjectModel::ProtocolInfo>*)client_data);
CXCursorKind kind = clang_getCursorKind(cursor);
switch (kind) {
case CXCursor_FirstRef:
case CXCursor_ObjCClassRef:
break;
case CXCursor_ObjCPropertyDecl: {
std::shared_ptr<ClangObjectModel::PropertyInfo> propInfo = HandlePropertyDecl(cursor);
protoInfo->properties.push_back(propInfo);
} break;
case CXCursor_ObjCClassMethodDecl: {
// NOTE: I think this should work. We just need to test it.
stringstream errorMsg;
errorMsg << "class methods on Protocols is not currently supported: " << std::endl;
Helpers::Errors::WriteError(cursor, errorMsg.str(), true);
} break;
case CXCursor_ObjCInstanceMethodDecl: {
std::shared_ptr<ClangObjectModel::MetaDataComments> metaDataInfo;
std::shared_ptr<ClangObjectModel::MethodInfo> method =
HandleMethodDecl(cursor, protoInfo->name, protoInfo->properties, metaDataInfo);
if (method == nullptr) {
// method is ignored
break;
}
bool isInitMethod = method->name.substr(0, 4) == "init";
if (isInitMethod) {
stringstream errorMsg;
errorMsg << "init methods on Protocols is not currently supported: " << std::endl;
Helpers::Errors::WriteError(cursor, errorMsg.str(), true);
}
applyMetaDataInfo(method,
protoInfo->instanceMethods,
metaDataInfo,
make_shared<ClangObjectModel::MetaDataComments>(*metaDataInfo),
false);
} break;
}
return CXChildVisit_Continue;
}
CXChildVisitResult InterfaceVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
std::shared_ptr<ClangObjectModel::InterfaceInfo> ifaceInfo = *((std::shared_ptr<ClangObjectModel::InterfaceInfo>*)client_data);
CXCursorKind kind = clang_getCursorKind(cursor);
std::string kindSpelling = ClangHelpers::GetString(clang_getCursorKindSpelling(kind));
switch (kind) {
case CXCursor_ObjCClassRef:
break;
case CXCursor_ObjCSuperClassRef: {
ifaceInfo->SetSuperClassFromCursor(cursor);
HandleClassRef(cursor, g_globalData.currentComponent);
break;
}
case CXCursor_ObjCProtocolRef: {
std::string protocolName = ClangHelpers::GetCursorSpelling(cursor);
// Only handle protocols from our framework.
CXCursor cursorRef = clang_getCursorReferenced(cursor);
if (ClangHelpers::isCursorFromProjectHeaders(cursorRef)) {
HandleProtocolRef(cursor, g_globalData.currentComponent);
ifaceInfo->AddProtocolsImplemented(protocolName);
}
break;
}
case CXCursor_ObjCPropertyDecl: {
std::shared_ptr<ClangObjectModel::PropertyInfo> propInfo = HandlePropertyDecl(cursor);
ifaceInfo->properties.push_back(propInfo);
break;
}
case CXCursor_ObjCInstanceMethodDecl:
case CXCursor_ObjCClassMethodDecl: {
std::shared_ptr<ClangObjectModel::MetaDataComments> metaDataInfo;
std::shared_ptr<ClangObjectModel::MethodInfo> method =
HandleMethodDecl(cursor, ifaceInfo->name, ifaceInfo->properties, metaDataInfo);
if (method == nullptr) {
// method is ignored
break;
}
method->SDKHeaderFile = ifaceInfo->SDKHeaderFile;
bool isInitMethod = method->name.substr(0, 4) == "init";
if (isInitMethod) {
if (method->params.size() == 0) {
if (method->isUnavailable) {
ifaceInfo->hasDefaultInitializer = false;
}
break;
} else {
method->returnType->typeInfo->setTypeSpelling(ifaceInfo->name + "*");
}
applyMetaDataInfo(method,
ifaceInfo->parameterizedInitMethods,
metaDataInfo,
make_shared<ClangObjectModel::MetaDataComments>(*metaDataInfo),
ifaceInfo->isApplicationDelegate);
} else {
if (kind == CXCursor_ObjCInstanceMethodDecl) {
applyMetaDataInfo(method,
ifaceInfo->instanceMethods,
metaDataInfo,
make_shared<ClangObjectModel::MetaDataComments>(*metaDataInfo),
ifaceInfo->isApplicationDelegate);
} else {
applyMetaDataInfo(method,
ifaceInfo->classMethods,
metaDataInfo,
make_shared<ClangObjectModel::MetaDataComments>(*metaDataInfo),
ifaceInfo->isApplicationDelegate);
}
}
break;
}
}
return CXChildVisit_Continue;
}
CXChildVisitResult InterfaceCategoryVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
std::shared_ptr<ClangObjectModel::ComponentInfo> component = *((std::shared_ptr<ClangObjectModel::ComponentInfo>*)client_data);
CXCursorKind kind = clang_getCursorKind(cursor);
switch (kind) {
case CXCursor_ObjCClassRef:
std::string name = ClangHelpers::GetCursorSpelling(cursor);
auto it = g_globalData.interfaceMap.find(name);
if (it == g_globalData.interfaceMap.end()) {
// This should never happen.
// we cannot have an interface category before interface declaration.
// Clang will report this as an error.
stringstream errMsg;
errMsg << "Could not find interface declaration for category " << name << ". Please inlcude the header for the category."
<< std::endl;
Helpers::Errors::WriteError(cursor, errMsg.str(), false);
}
clang_visitChildren(parent, InterfaceVisitor, &(it->second));
break;
}
return CXChildVisit_Break;
}
void HandleTypedefDecl(CXCursor cursor) {
CXCursor _cursor = cursor;
std::string typedefSpelling = ClangHelpers::GetCursorTypeSpelling(_cursor);
CXType underlyingType;
CXType typedefType;
CXTypeKind underlyingTypeKind;
std::string underlyingTypeSpelling;
std::shared_ptr<ClangObjectModel::ParameterInfo> param = std::make_shared<ClangObjectModel::ParameterInfo>();
param->typeInfo = make_shared<ClangObjectModel::TypeInfo>();
do {
underlyingType = clang_getTypedefDeclUnderlyingType(_cursor);
typedefType = clang_getCursorType(_cursor);
underlyingTypeKind = underlyingType.kind;
underlyingTypeSpelling = ClangHelpers::GetTypeSpelling(underlyingType);
CXTypeKind canonicalTypeKind = clang_getCanonicalType(underlyingType).kind;
if (canonicalTypeKind == CXType_Enum) {
// This corresponds to type enum, check the actual declaration for unnamed enum.
CXCursor declCursor = clang_getTypeDeclaration(underlyingType);
string declSpelling = ClangHelpers::GetCursorSpelling(declCursor);
if (declSpelling.empty()) {
// This is the typedef corresponding to an unnamed enum.
// Handle the enum here as we will have all the required information here.
handleEnums(_cursor, g_globalData.currentComponent);
}
underlyingTypeSpelling = ClangHelpers::getEnumTypeName(underlyingTypeSpelling);
auto it = g_globalData.enums.find(underlyingTypeSpelling);
if (it != g_globalData.enums.end()) {
param->typeInfo = it->second;
} else {
g_globalData.enums.insert({ underlyingTypeSpelling, param->typeInfo });
}
param->typeInfo->typeKind = CXType_Enum;
break;
} else {
param->typeInfo->typeKind = underlyingTypeKind;
}
if (underlyingTypeKind != CXType_Typedef) {
break;
}
auto it = g_globalData.currentComponent->typedefDecl.find(underlyingTypeSpelling);
if (it == g_globalData.currentComponent->typedefDecl.end()) {
stringstream errMsg;
errMsg << "Typedef " << underlyingTypeSpelling << " used before it is defined. Please inlcude the header for the typedef."
<< std::endl;
Helpers::Errors::WriteError(cursor, errMsg.str(), false);
}
_cursor = it->second->typeInfo->cursor;
} while (underlyingTypeKind == CXType_Typedef);
param->typeInfo->setTypeSpelling(underlyingTypeSpelling);
param->typeInfo->cursor = _cursor;
auto metaDataInfo = std::make_shared<ClangObjectModel::MetaDataComments>(_cursor);
param->paramMetaData = metaDataInfo;
if (param->typeInfo->typeKind != CXType_Enum) {
// This is set when we handle the enum declarations.
param->typeInfo->SDKname = ClangHelpers::GetCursorSDKName(_cursor);
}
if (param->typeInfo->typeKind == CXType_BlockPointer) {
clang_visitChildren(param->typeInfo->cursor, DelegateVisitor, ¶m);
}
g_globalData.currentComponent->typedefDecl.insert({ typedefSpelling, std::move(param) });
}
void HandleClassRef(CXCursor cursor, std::shared_ptr<ClangObjectModel::ComponentInfo>& component) {
std::string ifaceName = ClangHelpers::GetCursorSpelling(cursor);
component->AddReferenceToInterface(ifaceName);
}
void HandleProtocolRef(CXCursor cursor, std::shared_ptr<ClangObjectModel::ComponentInfo>& component) {
std::string protocolName = ClangHelpers::GetCursorSpelling(cursor);
component->AddReferenceToProtocol(protocolName);
}
void HandleReferences(CXCursor cursor, std::shared_ptr<ClangObjectModel::ComponentInfo>& component) {
ClangObjectModel::MetaDataComments metaData(cursor);
if (metaData.isIgnoredType()) {
return;
}
std::shared_ptr<ClangObjectModel::InterfaceInfo> iface;
std::string filePath;
std::string ifaceName;
std::string sdkName;
CXCursorKind kind = clang_getCursorKind(cursor);
switch (kind) {
case CXCursor_ObjCClassRef: {
// This needs to go to unresolved symbols as we do not know what is the IDL file name or the name of the
// internal header which will declare this interface.
HandleClassRef(cursor, component);
break;
}
case CXCursor_EnumDecl: {
filePath = ClangHelpers::GetCursorFileName(cursor);
sdkName = ClangHelpers::GetCursorSDKName(cursor);
char fname[_MAX_FNAME];
Helpers::Errors::Throw_On_Error(_splitpath_s(filePath.c_str(), NULL, 0, NULL, 0, fname, _MAX_FNAME, NULL, 0));
if (sdkName == component->getSDKName() && fname == component->SDKHeaderFile) {
handleEnums(cursor, component);
} else {
component->referencedIDLs.insert(ClangHelpers::generateNamespaceString(sdkName, ".") + "." + fname + ".idl");
}
} break;
case CXCursor_ObjCInterfaceDecl:
HandleClassRef(cursor, component);
break;
case CXCursor_ObjCProtocolDecl:
case CXCursor_ObjCProtocolRef:
HandleProtocolRef(cursor, component);
break;
case CXCursor_TypedefDecl:
HandleTypedefDecl(cursor);
break;
}
}
// Libclang has some weird (buggy?) behaviour with @class <interfaceName>. The cursor for a forward decl is a ObjcInterfaceDecl instead of
// a ObjCClassRef
// In order to differentiate @class <interfacename> from a class with only a defualt initializer (e.g. @interface Foo{}), we need to visit
// the cursor's children,
// which will be ObjCClassRef's.
// If the cursor is a foward decl, the name of the ObjCClassRef will be the same as the parent's cursor.
// If the cursor is a @interface Foo{}, the name of the ObjCClassRef will be different than the parent's cursor (NSObject).
CXChildVisitResult IsForwardDeclarationVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
bool* isForwardDeclaration = (bool*)client_data;
std::string parentName = ClangHelpers::GetCursorSpelling(parent);
std::string cursorName = ClangHelpers::GetCursorSpelling(cursor);
CXCursorKind kind = clang_getCursorKind(cursor);
switch (kind) {
case CXCursor_ObjCClassRef: {
if (parentName == cursorName) {
*isForwardDeclaration = true;
HandleClassRef(cursor, g_globalData.currentComponent);
return CXChildVisit_Break;
}
} break;
case CXCursor_ObjCProtocolRef: {
if (parentName == cursorName) {
*isForwardDeclaration = true;
HandleProtocolRef(cursor, g_globalData.currentComponent);
return CXChildVisit_Break;
}
} break;
}
return CXChildVisit_Continue;
}
void FixUnresolvedReferences(const std::string& referenceName,
bool isInterface,
std::unordered_multimap<std::string, std::shared_ptr<ClangObjectModel::ComponentInfo>> unresolvedMap) {
auto it = unresolvedMap.equal_range(referenceName);
auto componentIt = it.first;
while (componentIt != it.second) {
std::string namespaceString = ClangHelpers::generateNamespaceString(g_globalData.currentComponent->getSDKName(), ".");
if (componentIt->second->SDKHeaderFile != g_globalData.currentComponent->SDKHeaderFile) {
// put header file name in referencedIDLs
componentIt->second->referencedIDLs.insert(namespaceString + "." + g_globalData.currentComponent->SDKHeaderFile + ".idl");
}
if (isInterface) {
// generate the interface header name and put it in referencedInterfaces.
componentIt->second->referencedInterfaces.insert(namespaceString + "." + g_globalData.currentComponent->SDKHeaderFile + "." +
referenceName);
} else {
// generate the interface header name and put it in referencedProtocols.
componentIt->second->referencedProtocols.insert(namespaceString + "." + g_globalData.currentComponent->SDKHeaderFile + "." +
referenceName);
}
componentIt++;
}
unresolvedMap.erase(referenceName);
}
CXChildVisitResult ASTVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
std::string spelling = ClangHelpers::GetCursorSpelling(cursor);
std::string fileName = ClangHelpers::GetCursorFileName(cursor);
std::shared_ptr<ClangObjectModel::ComponentInfo> component = *((std::shared_ptr<ClangObjectModel::ComponentInfo>*)client_data);
if (!ClangHelpers::isCursorFromProjectHeaders(cursor)) {
return CXChildVisit_Continue;
}
if (!clang_Location_isFromMainFile(clang_getCursorLocation(cursor))) {
// These will be added as references
HandleReferences(cursor, component);
return CXChildVisit_Continue;
}
// Note: GetCursorSpelling will be empty for an Extension, which we do not expect to see in public headers.
std::cout << "\tTranslating " << spelling << " in " << fileName << std::endl;
CXCursorKind kind = clang_getCursorKind(cursor);
ClangObjectModel::MetaDataComments metaData(cursor);
if (metaData.isIgnoredType()) {
return CXChildVisit_Continue;
}
switch (kind) {
case CXCursor_EnumDecl:
handleEnums(cursor, component);
break;
case CXCursor_ObjCProtocolDecl: {
std::string protocolName = ClangHelpers::GetCursorSpelling(cursor);
bool isForwardDecl = false;
clang_visitChildren(cursor, IsForwardDeclarationVisitor, &isForwardDecl);
if (!isForwardDecl) {
std::shared_ptr<ClangObjectModel::ProtocolInfo> protocol = make_shared<ClangObjectModel::ProtocolInfo>(protocolName);
protocol->SDKname = ClangHelpers::GetCursorSDKName(cursor);
protocol->SDKHeaderFile = component->SDKHeaderFile;
// TODO: get protocols inheritance hierarchy
clang_visitChildren(cursor, ProtocolVisitor, &protocol);
ClangHelpers::fixMethodNameConflicts(protocol->instanceMethods);
g_globalData.protocolMap.insert({ protocol->name, protocol });
component->protocols.insert({ protocol->name, protocol });
FixUnresolvedReferences(protocolName, false, g_globalData.unresolvedProtocols);
if (metaData.isDelegateCallbackProtocol()) {
protocol->implHeaderName = ClangHelpers::generateNamespaceString(protocol->getSDKName(), ".") + "." +
protocol->SDKHeaderFile + "." + protocol->name + ".h";
component->delegateCallbackProtocolsMap.insert({ protocol->name, protocol });
g_globalData.delegateCallbackProtocolsMap.insert({ protocol->name, protocol });
}
}
} break;
case CXCursor_ObjCInterfaceDecl: {
std::string ifaceName = ClangHelpers::GetCursorSpelling(cursor);
bool isForwardDecl = false;
clang_visitChildren(cursor, IsForwardDeclarationVisitor, &isForwardDecl);
if (!isForwardDecl) {
std::shared_ptr<ClangObjectModel::InterfaceInfo> iface = make_shared<ClangObjectModel::InterfaceInfo>(ifaceName);
iface->isApplicationDelegate = metaData.isApplicationDelegate();
if (iface->isApplicationDelegate) {
g_globalData.applicationDelegateInfo = make_shared<ClangObjectModel::ApplicationDelegateInfo>();
}
if (component->ifaces.find(iface->name) == component->ifaces.end()) {
iface->SDKname = ClangHelpers::GetCursorSDKName(cursor);
iface->SDKHeaderFile = component->SDKHeaderFile;
clang_visitChildren(cursor, InterfaceVisitor, &iface);
ClangHelpers::fixMethodNameConflicts(iface->instanceMethods);
if (iface->isApplicationDelegate) {
g_globalData.applicationDelegateInfo->ifaceInfo = std::move(iface);
} else {
g_globalData.interfaceMap.insert({ iface->name, iface });
component->ifaces.insert({ iface->name, std::move(iface) });
FixUnresolvedReferences(ifaceName, true, g_globalData.unresolvedInterfaces);
}
}
}
} break;
case CXCursor_ObjCCategoryDecl:
clang_visitChildren(cursor, InterfaceCategoryVisitor, &component);
break;
case CXCursor_TypedefDecl:
HandleTypedefDecl(cursor);
break;
}
return CXChildVisit_Continue;
}
#ifdef DEBUG
CXChildVisitResult DumpAST(CXCursor cursor, CXCursor parent, CXClientData client_data) {
int recurse = (int)client_data;
std::string spelling = ClangHelpers::GetCursorSpelling(cursor);
std::string fileName = ClangHelpers::GetCursorFileName(cursor);
CXType type = clang_getCursorType(cursor);
std::string typeSpelling = ClangHelpers::GetTypeSpelling(type);
CXCursorKind kind = clang_getCursorKind(cursor);
std::cout << std::string(recurse, ' ') << fileName << ", " << spelling << ", " << kind << ", " << typeSpelling << ", " << std::endl;
recurse = recurse + 1;
clang_visitChildren(cursor, DumpAST, (CXClientData)recurse);
recurse = recurse - 1;
return CXChildVisit_Continue;
}
#endif
// TODO: Eventually we will want to extend this to all methods (instance, init, etc).
void FindInterfacesUsingDelegateCallbacks() {
for (const auto& comp : g_globalData.components) {
for (const auto& iface : comp->ifaces) {
for (const auto& method : iface.second->classMethods) {
for (const auto& param : method->params) {
string typeName = param->typeInfo->getTypeSpelling(true);
auto it = g_globalData.delegateCallbackProtocolsMap.find(typeName);
if (it != g_globalData.delegateCallbackProtocolsMap.end()) {
iface.second->usedDelegateTypes.insert({ param->typeInfo->getTypeSpelling(), param->typeInfo });
}
}
}
}
}
}
void runTests(std::string outputDir) {
for (auto SDK : g_sdkParameters.SDKHeaderArgMap) {
std::string sdkName = SDK.first;
ClangHelpers::header_argfile& haPair = SDK.second;
ifstream argFile(haPair.second);
std::string s((istreambuf_iterator<char>(argFile)), istreambuf_iterator<char>());
vector<std::string> clangArgs;
tokenize(s, clangArgs, " \n", "", "\"", "", "", false, false);
vector<const char*> clangArgs1;
for_each(clangArgs.begin(), clangArgs.end(), [&clangArgs1](std::string& s) {
if (s != "-MD" && s != "-MMD") {
clangArgs1.push_back(s.c_str());
}
});
ifstream headerFile(haPair.first);
std::string line;
while (getline(headerFile, line)) {
CXIndex idx = clang_createIndex(1, 1);
CXTranslationUnit tu;
tu = clang_parseTranslationUnit(idx, line.c_str(), clangArgs1.data(), clangArgs1.size(), 0, 0, 0);
size_t count = clang_getNumDiagnostics(tu);
for (size_t i = 0; i < count; i++) {
CXDiagnostic diagnostic = clang_getDiagnostic(tu, i);
CXDiagnosticSeverity severity = clang_getDiagnosticSeverity(diagnostic);
if (severity >= CXDiagnostic_Error) {
CXSourceLocation locn = clang_getDiagnosticLocation(diagnostic);
CXCursor cursor = clang_getCursor(tu, locn);
ClangObjectModel::MetaDataComments metaData(cursor);
if (metaData.isIgnoredType()) {
clang_disposeDiagnostic(diagnostic);
continue;
}
CXString diagInfo = clang_getDiagnosticSpelling(diagnostic);
string diagInfoStr = ClangHelpers::GetString(diagInfo);
clang_disposeString(diagInfo);
Helpers::Errors::WriteError(ClangHelpers::GetSourceLocation(locn), diagInfoStr, false);
}
clang_disposeDiagnostic(diagnostic);
}
CXCursor cursor = clang_getTranslationUnitCursor(tu);
std::shared_ptr<ClangObjectModel::ComponentInfo> component = make_shared<ClangObjectModel::ComponentInfo>();
g_globalData.currentComponent = component;
component->SDKname = sdkName;
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
errno_t err = _splitpath_s(line.c_str(), drive, dir, fname, ext);
if (err != 0) {
// TODO: Use wil
stringstream error;
error << "_splitpath_s returned: " << err;
throw new exception(error.str().c_str());
}
component->SDKHeaderFile = fname;
std::cout << "Translating " << line << std::endl;
clang_visitChildren(cursor, ASTVisitor, &component);
g_globalData.components.push_back(component);
#ifdef DEBUG
int recurse = 0;
clang_visitChildren(cursor, DumpAST, (CXClientData)recurse);
#endif
clang_disposeTranslationUnit(tu);
clang_disposeIndex(idx);
}
}
FindInterfacesUsingDelegateCallbacks();
if (g_globalData.applicationDelegateInfo) {
dumpFile(g_sdkParameters.rootNameSpace + "_" + g_globalData.applicationDelegateInfo->ifaceInfo->name + ".mm",
generateAppDelegateImpl(),
outputDir);
dumpFile(g_sdkParameters.rootNameSpace + "_" + g_globalData.applicationDelegateInfo->ifaceInfo->name + ".h",
generateAppDelegateDecl(),
outputDir);
}
std::string rootNamespace = ClangHelpers::generateNamespaceString("", "");
// Generate NSNotificationCenter marshalling code.
if (g_globalData.requiresNSNotificationMarshalling) {
dumpFile(rootNamespace + "._" + g_notificationCenter + ".idl", CommonCodeGenerator::generateNSNotificationCenterIDL(), outputDir);
dumpFile(rootNamespace + "._" + g_notificationCenter + ".mm",
CommonCodeGenerator::generateNSNotificationCenterDefinitions(),
outputDir);
}
dumpFile(g_sdkParameters.rootNameSpace + ".h", CommonCodeGenerator::generateCommonHeader(), outputDir);
dumpFile(g_sdkParameters.rootNameSpace + ".mm", CommonCodeGenerator::generateCommonImplementation(), outputDir);
for (auto delPair : g_globalData.delegateCallbackProtocolsMap) {
string fileName = ClangHelpers::generateNamespaceString(delPair.second->getSDKName(), ".") + "." + delPair.second->SDKHeaderFile +
"." + delPair.second->name + ".h";
dumpFile(fileName, generateObjCDelegateCallbackDeclaration(delPair.second), outputDir);
}
for (auto comp : g_globalData.components) {
g_globalData.currentComponent = comp;
if (comp->ifaces.size() > 0 || comp->protocols.size() > 0 || comp->enums.size() > 0) {
// Fix async class implementor names.
// We are not aware of the header and SDK names when we generate the name, so we fix the name here.
vector<shared_ptr<ClangObjectModel::AsyncClassInfo>> asyncClassesArray(comp->asyncClasses.begin(), comp->asyncClasses.end());
for (auto& asyncClass : asyncClassesArray) {
if (asyncClass->returnTypes.size() == 0) {
asyncClass->name = "_AsyncActionImpl";
} else {
asyncClass->sdkName = comp->getSDKName();
ClangHelpers::generateAsyncClassImplName(asyncClass, comp->SDKHeaderFile);
string classType = ClangHelpers::getResolvedAsyncImplName(asyncClass);
string interfaceType = ClangHelpers::getResolvedAsyncImplName(asyncClass, "I");
string templateString = classType + ", " + interfaceType;
asyncClass->name = "ObjCAsync::AsyncOperationImpl<" + templateString + ">";
}
}
comp->asyncClasses.clear();
comp->asyncClasses.insert(asyncClassesArray.begin(), asyncClassesArray.end());
std::string namespaceString = ClangHelpers::generateNamespaceString(comp->getSDKName(), ".");
dumpFile(namespaceString + "." + comp->SDKHeaderFile + ".idl", generateIdl(comp), outputDir);
dumpFile(namespaceString + "." + comp->SDKHeaderFile + ".mm", generateClassBindings(comp), outputDir);
for (auto iface : comp->ifaces) {
dumpFile(namespaceString + "." + comp->SDKHeaderFile + "." + iface.first + ".h", generateHeaders(iface.second), outputDir);
}
if (comp->heterogeneousContainers.size()) {
dumpFile(namespaceString + "." + comp->SDKHeaderFile + "._Containers.h",
generateHeterogeneousContainerDeclarations(comp),
outputDir);
}
}
comp->clearAll();
}
}
void Usage() {
printf("obj2winmd -r <root name space> -o <output directory> SDK.header SDK.args");
exit(-1);
}
int main(int argc, char** argv) {
std::string outputDir;
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (_stricmp(arg.c_str(), "-o") == 0 && i + 1 < argc) {
i++;
outputDir = argv[i];
continue;
}
if (_stricmp(arg.c_str(), "-r") == 0 && i + 1 < argc) {
i++;
g_sdkParameters.rootNameSpace = argv[i];
continue;
}
if (_stricmp(arg.c_str(), "-MaxErrors") == 0 && i + 1 < argc) {
i++;
try {
g_MaxErrors = std::stoul(argv[i]);
} catch (std::invalid_argument) {
Usage();
} catch (std::out_of_range) {
Usage();
}
continue;
}
// Must be a sdk.args or sdk.headers file. Extract the sdk name
// Convert all backslashes to forward slashes
Helpers::replaceAll(arg, "\\", "/");
size_t indexSlash = arg.find_last_of("/");
size_t indexPeriod = arg.find_last_of('.');
if (indexPeriod == -1 || (indexSlash != -1 && indexPeriod <= indexSlash)) {
Usage();
}
size_t startPos = (indexSlash == -1 ? 0 : indexSlash + 1);
size_t count = indexPeriod - startPos;
std::string sdkName(arg, startPos, count);
if (sdkName.empty()) {
Usage();
}
std::string argFile;
std::string headerFile;
size_t index = arg.find(".args");
if (index != -1) {
argFile = arg;
} else {
index = arg.find(".headers");
if (index != -1) {
headerFile = arg;
}
}
auto it = g_sdkParameters.SDKHeaderArgMap.find(sdkName);
if (it == g_sdkParameters.SDKHeaderArgMap.end()) {
ClangHelpers::header_argfile haPair(headerFile, argFile);
g_sdkParameters.SDKHeaderArgMap[sdkName] = haPair;
} else {
ClangHelpers::header_argfile& haPair = it->second;
if (haPair.first.empty()) {
haPair.first = headerFile;
} else {
haPair.second = argFile;
}
}
}
if (g_sdkParameters.rootNameSpace.empty() || g_sdkParameters.SDKHeaderArgMap.size() == 0 || outputDir.empty()) {
Usage();
}
runTests(outputDir);
int retCode = 0;
if (Helpers::Errors::GetErrorCount()) {
retCode = -1;
}
return retCode;
}
| 45.834545 | 140 | 0.598583 | crossmob |
47636b833a9010110d14e0b9194c2b98f402cc3f | 2,652 | cpp | C++ | raw-examples/my_epoll.cpp | Jayhello/handy-copy | f6b1be65a5372cb42e6479c0b413216a9a689e1f | [
"BSD-2-Clause"
] | null | null | null | raw-examples/my_epoll.cpp | Jayhello/handy-copy | f6b1be65a5372cb42e6479c0b413216a9a689e1f | [
"BSD-2-Clause"
] | null | null | null | raw-examples/my_epoll.cpp | Jayhello/handy-copy | f6b1be65a5372cb42e6479c0b413216a9a689e1f | [
"BSD-2-Clause"
] | null | null | null | //
// Created by root on 18-11-21.
//
/*
* Mainly test for server end.
*/
#include <sys/socket.h>
#include <vector>
#include <iostream>
#include <netinet/in.h>
#include <handy/handy.h>
#include <arpa/inet.h>
using namespace handy;
using namespace std;
/*
* Note: Simple test for max socket num.
*/
void testMaxSockFd(){
vector<int> vecFd(40000);
for (int i = 0; i < vecFd.size(); ++i) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
fatalif(fd<0, "create sock %d, errno: %d, %s:",i+2, errno, strerror(errno));
// create sock 4093, errno: 24, Too many open files:
vecFd[i] = fd;
}
}
sockaddr_in getSockAddr(const string& ip, uint16_t port){
sockaddr_in localAddr;
bzero(&localAddr,sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = inet_addr(ip.data());
localAddr.sin_port = htons(port);
return localAddr;
}
auto lb_process_client = [](int fd){
int count = 0;
char buf[200];
memset(buf, '\0', 200);
for (int i = 0; i < 3; ++i) {
string msg = "server msg: " + to_string(count++);
int len = send(fd, (void*)msg.data(), msg.size(), 0);
if(len < 0){
info("send error, peer close fd");
break;
}
info("send %d", len);
memset(buf, '\0', 200);
len = recv(fd, buf, 200, 0);
if(len < 0){
info("recv error, peer close fd");
break;
}
info("recv %s, len %d", buf, len);
sleep(2);
}
close(fd);
info("process ending, %d", fd);
};
void testServer(){
int sockFd = socket(AF_INET, SOCK_STREAM, 0);
fatalif(sockFd < 0, "socket failed %d %s", errno, strerror(errno));
string ip = "127.0.0.1";
uint16_t port = 8000;
Ip4Addr localAddr(ip, port);
int ret = bind(sockFd, (struct sockaddr*)&localAddr.getAddr(),
sizeof(localAddr.getAddr()));
fatalif(ret < 0, "bind socket failed %d %s", errno, strerror(errno));
ret = listen(sockFd, 100);
fatalif(ret < 0, "listen socket failed %d %s", errno, strerror(errno));
info("now i will sleep 100S");
sleep(100);
ThreadPool tp(5);
while(true){
struct sockaddr_in raddr;
socklen_t rsz = sizeof(raddr);
int cfd = accept(sockFd, (struct sockaddr *) &raddr, &rsz);
fatalif(cfd < 0, "accept failed");
Ip4Addr tmp(raddr);
info("accept a connection from %s", tmp.toString().c_str());
tp.addTask(std::bind(lb_process_client, cfd));
}
}
int main(){
testMaxSockFd();
// testServer();
return 0;
} | 21.737705 | 84 | 0.563725 | Jayhello |
4767a60e01d3a1b0bef6a71f7941455efc452fdf | 1,028 | cpp | C++ | Sid's Levels/Level - 2/Graphs/BFS.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Levels/Level - 2/Graphs/BFS.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Levels/Level - 2/Graphs/BFS.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | class Solution
{
public:
//Function to return Breadth First Traversal of given graph.
void bfsHelper(vector<int> &bfs, bool visited[], vector<int> adj[], int src)
{
queue<int> q;
q.push(src);
visited[src] = true;
while(!q.empty())
{
int cur = q.front();
q.pop();
bfs.push_back(cur);
for(auto it = adj[cur].begin(); it != adj[cur].end(); it++)
{
if(visited[*it] != true)
{
q.push(*it);
visited[*it] = true;
}
}
}
}
vector<int>bfsOfGraph(int V, vector<int> adj[])
{
// Code here
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
vector<int> bfs;
bool visited[V];
for(int i = 0; i < V; i++)
visited[i] = false;
bfsHelper(bfs, visited, adj, 0);
return bfs;
}
};
| 25.7 | 80 | 0.474708 | Tiger-Team-01 |
47692a35ba87389e363a8e763496408888586d82 | 1,463 | cpp | C++ | src/runtime_src/xdp/profile/plugin/vp_base/vp_base_plugin.cpp | houlz0507/XRT-1 | 1b66ba8a5031ac1f694b0686774218c0d7286c52 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/xdp/profile/plugin/vp_base/vp_base_plugin.cpp | houlz0507/XRT-1 | 1b66ba8a5031ac1f694b0686774218c0d7286c52 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/xdp/profile/plugin/vp_base/vp_base_plugin.cpp | houlz0507/XRT-1 | 1b66ba8a5031ac1f694b0686774218c0d7286c52 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2016-2020 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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.
*/
#define XDP_SOURCE
#include "xdp/profile/plugin/vp_base/vp_base_plugin.h"
#include "xdp/profile/device/device_intf.h"
namespace xdp {
XDPPlugin::XDPPlugin() : db(VPDatabase::Instance())
{
// The base class should not add any devices as different plugins
// should not clash with respect to the accessing the hardware.
}
XDPPlugin::~XDPPlugin()
{
for (auto w : writers)
{
delete w ;
}
}
void XDPPlugin::writeAll(bool openNewFiles)
{
// Base functionality is just to have all writers write. Derived
// classes might have to do more.
for (auto w : writers)
{
w->write(openNewFiles) ;
}
}
void XDPPlugin::readDeviceInfo(void* /*device*/)
{
// Since we can have multiple plugins, the default behavior should
// be that the plugin doesn't read any device information
}
}
| 26.6 | 76 | 0.688995 | houlz0507 |
4769892825000c71007faa865c2f0155d8a2bcfc | 1,953 | cc | C++ | Ex05_Prototype/src/1_document_manager/docmanager.cc | kks32/cpp-software-development | 3ce0c66d812d9a166191a1007111501615c97a2c | [
"MIT"
] | 64 | 2015-01-18T17:53:56.000Z | 2022-03-06T11:37:25.000Z | Ex05_Prototype/src/1_document_manager/docmanager.cc | kks32/cpp-software-development | 3ce0c66d812d9a166191a1007111501615c97a2c | [
"MIT"
] | null | null | null | Ex05_Prototype/src/1_document_manager/docmanager.cc | kks32/cpp-software-development | 3ce0c66d812d9a166191a1007111501615c97a2c | [
"MIT"
] | 24 | 2015-03-22T02:00:10.000Z | 2022-01-18T13:17:26.000Z | #include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
const int N = 4; // # of document types + 1
// Prototype
class Document
{
public:
virtual Document* clone() const = 0;
virtual void store() const = 0;
virtual ~Document() { }
};
// Concrete prototypes : xmlDoc, plainDoc, spreadsheetDoc
class xmlDoc : public Document
{
public:
Document* clone() const { return new xmlDoc; }
void store() const { std::cout << "xmlDoc\n"; }
};
class plainDoc : public Document
{
public:
Document* clone() const { return new plainDoc; }
void store() const { std::cout << "plainDoc\n"; }
};
class spreadsheetDoc : public Document
{
public:
Document* clone() const { return new spreadsheetDoc; }
void store() const { std::cout << "spreadsheetDoc\n"; }
};
// makeDocument() calls Concrete Portotype's clone() method
// inherited from Prototype
class DocumentManager {
public:
static Document* makeDocument( int choice );
~DocumentManager(){}
private:
static Document* mDocTypes[N];
};
Document* DocumentManager::mDocTypes[] =
{
0, new xmlDoc, new plainDoc, new spreadsheetDoc
};
Document* DocumentManager::makeDocument( int choice )
{
return mDocTypes[choice]->clone();
}
// for_each op ()
struct Destruct
{
void operator()(Document *a) const {
delete a;
}
};
// Client
int main(int argc, char** argv) {
std::vector<Document*> docs(N);
int choice;
std::cout << "quit(0), xml(1), plain(2), spreadsheet(3): " << std::endl;
while(true) {
std::cout << "Type in your choice (0-3)\n";
std::cin >> choice;
if(choice <= 0 || choice >= N)
break;
docs[choice] = DocumentManager::makeDocument( choice );
}
for(int i = 1; i < docs.size(); ++i)
if(docs[i]) docs[i]->store();
Destruct d;
// this calls Destruct::operator()
std::for_each(docs.begin(), docs.end(), d);
return 0;
}
| 21.461538 | 76 | 0.623144 | kks32 |
476d1350ae2cab66a8a9c2084888ad85656d2015 | 10,118 | cpp | C++ | emulator/src/devices/bus/amiga/zorro/buddha.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/devices/bus/amiga/zorro/buddha.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/devices/bus/amiga/zorro/buddha.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:GPL-2.0+
// copyright-holders:Dirk Best
/***************************************************************************
Buddha
Zorro-II IDE controller
The 'speed' register is used to select the IDE timing according to
the following table (bits 7-5 are used):
0 497ns 7c to select, IOR/IOW after 172ns 2c
1 639ns 9c to select, IOR/IOW after 243ns 3c
2 781ns 11c to select, IOR/IOW after 314ns 4c
3 355ns 5c to select, IOR/IOW after 101ns 1c
4 355ns 5c to select, IOR/IOW after 172ns 2c
5 355ns 5c to select, IOR/IOW after 243ns 3c
6 1065ns 15c to select, IOR/IOW after 314ns 4c
7 355ns 5c to select, IOR/IOW after 101ns 1c
c = clock cycles. This isn't emulated.
***************************************************************************/
#include "emu.h"
#include "buddha.h"
//**************************************************************************
// CONSTANTS / MACROS
//**************************************************************************
#define VERBOSE 1
//**************************************************************************
// DEVICE DEFINITIONS
//**************************************************************************
DEFINE_DEVICE_TYPE(BUDDHA, buddha_device, "buddha", "Buddha IDE controller")
//-------------------------------------------------
// mmio_map - device-specific memory mapped I/O
//-------------------------------------------------
ADDRESS_MAP_START(buddha_device::mmio_map)
AM_RANGE(0x7fe, 0x7ff) AM_READWRITE(speed_r, speed_w)
AM_RANGE(0x800, 0x8ff) AM_READWRITE(ide_0_cs0_r, ide_0_cs0_w)
AM_RANGE(0x900, 0x9ff) AM_READWRITE(ide_0_cs1_r, ide_0_cs1_w)
AM_RANGE(0xa00, 0xaff) AM_READWRITE(ide_1_cs0_r, ide_1_cs0_w)
AM_RANGE(0xb00, 0xbff) AM_READWRITE(ide_1_cs1_r, ide_1_cs1_w)
AM_RANGE(0xf00, 0xf3f) AM_READ(ide_0_interrupt_r)
AM_RANGE(0xf40, 0xf7f) AM_READ(ide_1_interrupt_r)
AM_RANGE(0xfc0, 0xfff) AM_WRITE(ide_interrupt_enable_w)
ADDRESS_MAP_END
//-------------------------------------------------
// device_add_mconfig - add device configuration
//-------------------------------------------------
MACHINE_CONFIG_START(buddha_device::device_add_mconfig)
MCFG_ATA_INTERFACE_ADD("ata_0", ata_devices, nullptr, nullptr, false)
MCFG_ATA_INTERFACE_IRQ_HANDLER(WRITELINE(buddha_device, ide_0_interrupt_w))
MCFG_ATA_INTERFACE_ADD("ata_1", ata_devices, nullptr, nullptr, false)
MCFG_ATA_INTERFACE_IRQ_HANDLER(WRITELINE(buddha_device, ide_1_interrupt_w))
MACHINE_CONFIG_END
//-------------------------------------------------
// rom_region - device-specific ROM region
//-------------------------------------------------
ROM_START( buddha )
ROM_REGION16_BE(0x10000, "bootrom", ROMREGION_ERASEFF)
ROM_DEFAULT_BIOS("v103-17")
ROM_SYSTEM_BIOS(0, "v103-8", "Version 103.8")
ROMX_LOAD("buddha_103-8.rom", 0x0000, 0x8000, CRC(44f81426) SHA1(95555c6690b5c697e1cdca2726e47c1c6c194d7c), ROM_SKIP(1) | ROM_BIOS(1))
ROM_SYSTEM_BIOS(1, "v103-17", "Version 103.17")
ROMX_LOAD("buddha_103-17.rom", 0x0000, 0x8000, CRC(2b7b24e0) SHA1(ec17a58962c373a2892090ec9b1722d2c326d631), ROM_SKIP(1) | ROM_BIOS(2))
ROM_END
const tiny_rom_entry *buddha_device::device_rom_region() const
{
return ROM_NAME( buddha );
}
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// buddha_device - constructor
//-------------------------------------------------
buddha_device::buddha_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) :
device_t(mconfig, BUDDHA, tag, owner, clock),
device_zorro2_card_interface(mconfig, *this),
m_ata_0(*this, "ata_0"),
m_ata_1(*this, "ata_1"),
m_ide_interrupts_enabled(false),
m_ide_0_interrupt(0),
m_ide_1_interrupt(0)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void buddha_device::device_start()
{
set_zorro_device();
save_item(NAME(m_ide_interrupts_enabled));
save_item(NAME(m_ide_0_interrupt));
save_item(NAME(m_ide_1_interrupt));
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void buddha_device::device_reset()
{
m_ide_interrupts_enabled = false;
m_ide_0_interrupt = 0;
m_ide_1_interrupt = 0;
}
//**************************************************************************
// IMPLEMENTATION
//**************************************************************************
void buddha_device::autoconfig_base_address(offs_t address)
{
if (VERBOSE)
logerror("autoconfig_base_address received: 0x%06x\n", address);
if (VERBOSE)
logerror("-> installing buddha\n");
// stop responding to default autoconfig
m_slot->m_space->unmap_readwrite(0xe80000, 0xe8007f);
// buddha registers
m_slot->m_space->install_device(address, address + 0xfff, *this, &buddha_device::mmio_map);
// install autoconfig handler to new location
m_slot->m_space->install_readwrite_handler(address, address + 0x7f,
read16_delegate(FUNC(amiga_autoconfig::autoconfig_read), static_cast<amiga_autoconfig *>(this)),
write16_delegate(FUNC(amiga_autoconfig::autoconfig_write), static_cast<amiga_autoconfig *>(this)), 0xffff);
// install access to the rom space
m_slot->m_space->install_rom(address + 0x1000, address + 0xffff, memregion("bootrom")->base() + 0x1000);
// we're done
m_slot->cfgout_w(0);
}
WRITE_LINE_MEMBER( buddha_device::cfgin_w )
{
if (VERBOSE)
logerror("configin_w (%d)\n", state);
if (state == 0)
{
// setup autoconfig
autoconfig_board_type(BOARD_TYPE_ZORRO2);
autoconfig_board_size(BOARD_SIZE_64K);
autoconfig_link_into_memory(false);
autoconfig_rom_vector_valid(true);
autoconfig_multi_device(false);
autoconfig_8meg_preferred(false);
autoconfig_can_shutup(true);
autoconfig_product(0x00);
autoconfig_manufacturer(0x1212);
autoconfig_serial(0x00000000);
autoconfig_rom_vector(0x1000);
// install autoconfig handler
m_slot->m_space->install_readwrite_handler(0xe80000, 0xe8007f,
read16_delegate(FUNC(amiga_autoconfig::autoconfig_read), static_cast<amiga_autoconfig *>(this)),
write16_delegate(FUNC(amiga_autoconfig::autoconfig_write), static_cast<amiga_autoconfig *>(this)), 0xffff);
}
}
READ16_MEMBER( buddha_device::speed_r )
{
uint16_t data = 0xffff;
if (VERBOSE)
logerror("speed_r %04x [mask = %04x]\n", data, mem_mask);
return data;
}
WRITE16_MEMBER( buddha_device::speed_w )
{
if (VERBOSE)
logerror("speed_w %04x [mask = %04x]\n", data, mem_mask);
}
WRITE_LINE_MEMBER( buddha_device::ide_0_interrupt_w)
{
if (VERBOSE)
logerror("ide_0_interrupt_w (%d)\n", state);
m_ide_0_interrupt = state;
if (m_ide_interrupts_enabled)
m_slot->int2_w(state);
}
WRITE_LINE_MEMBER( buddha_device::ide_1_interrupt_w)
{
if (VERBOSE)
logerror("ide_1_interrupt_w (%d)\n", state);
m_ide_1_interrupt = state;
if (m_ide_interrupts_enabled)
m_slot->int2_w(state);
}
READ16_MEMBER( buddha_device::ide_0_interrupt_r )
{
uint16_t data;
data = m_ide_0_interrupt << 15;
if (VERBOSE && 0)
logerror("ide_0_interrupt_r %04x [mask = %04x]\n", data, mem_mask);
return data;
}
READ16_MEMBER( buddha_device::ide_1_interrupt_r )
{
uint16_t data;
data = m_ide_1_interrupt << 15;
if (VERBOSE && 0)
logerror("ide_1_interrupt_r %04x [mask = %04x]\n", data, mem_mask);
return data;
}
WRITE16_MEMBER( buddha_device::ide_interrupt_enable_w )
{
if (VERBOSE)
logerror("ide_interrupt_enable_w %04x [mask = %04x]\n", data, mem_mask);
// writing any value here enables ide interrupts to the zorro slot
m_ide_interrupts_enabled = true;
}
READ16_MEMBER( buddha_device::ide_0_cs0_r )
{
uint16_t data = m_ata_0->read_cs0((offset >> 1) & 0x07, (mem_mask << 8) | (mem_mask >> 8));
data = (data << 8) | (data >> 8);
if (VERBOSE)
logerror("ide_0_cs0_r(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
return data;
}
WRITE16_MEMBER( buddha_device::ide_0_cs0_w )
{
if (VERBOSE)
logerror("ide_0_cs0_w(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
mem_mask = (mem_mask << 8) | (mem_mask >> 8);
data = (data << 8) | (data >> 8);
m_ata_0->write_cs0((offset >> 1) & 0x07, data, mem_mask);
}
READ16_MEMBER( buddha_device::ide_0_cs1_r )
{
uint16_t data = m_ata_0->read_cs1((offset >> 1) & 0x07, (mem_mask << 8) | (mem_mask >> 8));
data = (data << 8) | (data >> 8);
if (VERBOSE)
logerror("ide_0_cs1_r(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
return data;
}
WRITE16_MEMBER( buddha_device::ide_0_cs1_w )
{
if (VERBOSE)
logerror("ide_0_cs1_w(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
mem_mask = (mem_mask << 8) | (mem_mask >> 8);
data = (data << 8) | (data >> 8);
m_ata_0->write_cs1((offset >> 1) & 0x07, data, mem_mask);
}
READ16_MEMBER( buddha_device::ide_1_cs0_r )
{
uint16_t data = m_ata_1->read_cs0((offset >> 1) & 0x07, (mem_mask << 8) | (mem_mask >> 8));
data = (data << 8) | (data >> 8);
if (VERBOSE)
logerror("ide_1_cs0_r(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
return data;
}
WRITE16_MEMBER( buddha_device::ide_1_cs0_w )
{
if (VERBOSE)
logerror("ide_1_cs0_w(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
mem_mask = (mem_mask << 8) | (mem_mask >> 8);
data = (data << 8) | (data >> 8);
m_ata_1->write_cs0((offset >> 1) & 0x07, data, mem_mask);
}
READ16_MEMBER( buddha_device::ide_1_cs1_r )
{
uint16_t data = m_ata_1->read_cs1((offset >> 1) & 0x07, (mem_mask << 8) | (mem_mask >> 8));
data = (data << 8) | (data >> 8);
if (VERBOSE)
logerror("ide_1_cs1_r(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
return data;
}
WRITE16_MEMBER( buddha_device::ide_1_cs1_w )
{
if (VERBOSE)
logerror("ide_1_cs1_w(%04x) %04x [mask = %04x]\n", offset, data, mem_mask);
mem_mask = (mem_mask << 8) | (mem_mask >> 8);
data = (data << 8) | (data >> 8);
m_ata_1->write_cs1((offset >> 1) & 0x07, data, mem_mask);
}
| 29.327536 | 136 | 0.618996 | rjw57 |
47705c1796084733843018e789d6030866a69d30 | 4,486 | cpp | C++ | source/polyvec/curve-tracer/measure_accuracy_polygon.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 27 | 2020-08-17T17:25:59.000Z | 2022-03-01T05:49:12.000Z | source/polyvec/curve-tracer/measure_accuracy_polygon.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 4 | 2020-08-26T13:54:59.000Z | 2020-09-21T07:19:22.000Z | source/polyvec/curve-tracer/measure_accuracy_polygon.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 5 | 2020-08-26T23:26:48.000Z | 2021-01-04T09:06:07.000Z | // polyvec
#include <polyvec/curve-tracer/measure_accuracy_polygon.hpp>
#include <polyvec/curve-tracer/find-fitting-points.hpp>
#include <polyvec/utils/matrix.hpp>
#include <polyvec/curve-tracer/spline.hpp>
#include <polyvec/utils/directions.hpp>
// remove todo
#include <polyvec/geom.hpp> // nop
#include <polyvec/debug.hpp>
// libc++
#include <cstdlib> // min, max
using namespace polyvec;
using namespace std;
NAMESPACE_BEGIN(polyfit)
NAMESPACE_BEGIN(CurveTracer)
void measure_accuracy_signed_extended_polygon_fit_symmetric(
const mat2x& B, // raster boundary
const vecXi& P, // polygon
const Vertex corner, // corner
AccuracyMeasurement& m,// result
const bool circular
) {
double len_prev = 0.;
if (circular || corner > 0) {
len_prev = (B.col(CircularAt(P, corner - 1)) - B.col(CircularAt(P, corner))).norm();
}
double len_next = 0.;
if (circular || corner < P.size() - 1) {
len_next = (B.col(CircularAt(P, corner + 1)) - B.col(CircularAt(P, corner))).norm();
}
int e_start = corner;
double t_start = 0.;
if (circular || corner > 0) {
e_start = Circular(P, corner - 1);
t_start = (.5 * min(len_prev, len_next)) / len_prev;
}
// i don't think this works for non-circular segments (todo)
int e_end = corner;
double t_end = 0.;
if (circular || corner < P.size() - 1) {
t_end = (.5 * min(len_prev, len_next)) / len_next;
}
// Fitting data
const vec2 p0 = B.col(P(e_start));
const vec2 p1 = B.col(P(e_end));
const vec2 p2 = B.col(CircularAt(P, e_end + 1)); // todo circularity
mat2xi V_fit;
mat2x P_fit;
// (1) find fitting points
find_pixel_centers_for_subpath(B, P, e_start, t_start, e_start, 1., V_fit, &P_fit, circular);
// (1) compute fitting normals
mat2x N_fit(2, P_fit.cols());
for (int i = 0; i < P_fit.cols(); ++i) {
N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(0, i)) - B.col(V_fit(1, i)));
}
// (1) construct edge segment
GlobFitCurve_Line edge0;
edge0.set_points(
p0 + (p1 - p0) * t_start,
p1
);
// (1) test accuracy
AccuracyMeasurement m0 = measure_accuracy(edge0, P_fit, N_fit);
// (2) find fitting points
V_fit.resize(2, 0);
P_fit.resize(2, 0);
find_pixel_centers_for_subpath(B, P, e_end, 0., e_end, t_end, V_fit, &P_fit, circular);
// (2) compute fitting normals
N_fit.resize(2, P_fit.cols());
for (int i = 0; i < P_fit.cols(); ++i) {
N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(0, i)) - B.col(V_fit(1, i)));
}
// (2) construct edge segment
GlobFitCurve_Line edge1;
edge1.set_points(
p1,
p1 + (p2 - p1) * t_end
);
// (2) test accuracy
AccuracyMeasurement m1 = measure_accuracy(edge1, P_fit, N_fit);
new (&m) AccuracyMeasurement;
m.combine(m0);
m.combine(m1);
}
void measure_accuracy_signed_extended_polygon_fit_asymmetric(
const mat2x& B, // raster boundary
const vecXi& P, // polygon
const Vertex corner, // corner
AccuracyMeasurement& m,// result
const bool circular
) {
double t_start = .5;
int e_start = corner;
if (circular || corner > 0) {
e_start = Circular(P, corner - 1);
}
double t_end = .5;
int e_end = corner;
// Fitting data
const vec2 p0 = B.col(P(e_start));
const vec2 p1 = B.col(P(e_end));
const vec2 p2 = B.col(CircularAt(P, e_end + 1)); // todo circularity
mat2xi V_fit;
mat2x P_fit;
// (1) find fitting points
find_pixel_centers_for_subpath(B, P, e_start, t_start, e_start, 1., V_fit, &P_fit, circular);
// (1) compute fitting normals
mat2x N_fit(2, P_fit.cols());
for (int i = 0; i < P_fit.cols(); ++i) {
N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(1, i)) - B.col(V_fit(0, i)));
}
// (1) construct edge segment
GlobFitCurve_Line edge0;
edge0.set_points(
p0 + (p1 - p0) * t_start,
p1
);
// (1) test accuracy
AccuracyMeasurement m0 = measure_accuracy(edge0, P_fit, N_fit);
// (2) find fitting points
V_fit.resize(2, 0);
P_fit.resize(2, 0);
find_pixel_centers_for_subpath(B, P, e_end, 0., e_end, t_end, V_fit, &P_fit, circular);
// (2) compute fitting normals
N_fit.resize(2, P_fit.cols());
for (int i = 0; i < P_fit.cols(); ++i) {
N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(1, i)) - B.col(V_fit(0, i)));
}
// (2) construct edge segment
GlobFitCurve_Line edge1;
edge1.set_points(
p1,
p1 + (p2 - p1) * t_end
);
// (2) test accuracy
AccuracyMeasurement m1 = measure_accuracy(edge1, P_fit, N_fit);
new (&m) AccuracyMeasurement;
m.combine(m0);
m.combine(m1);
}
NAMESPACE_END(CurveTracer)
NAMESPACE_END(polyfit) | 25.488636 | 94 | 0.664958 | ShnitzelKiller |
477282ca9786016074b6ba825d03c81872570987 | 1,941 | hpp | C++ | data-structures-and-algorithms/project-hashmap/tests/test_map_hash.hpp | vampy/university | 9496cb63594dcf1cc2cec8650b8eee603f85fdab | [
"MIT"
] | 6 | 2015-06-22T19:43:13.000Z | 2019-07-15T18:08:41.000Z | data-structures-and-algorithms/project-hashmap/tests/test_map_hash.hpp | vampy/university | 9496cb63594dcf1cc2cec8650b8eee603f85fdab | [
"MIT"
] | null | null | null | data-structures-and-algorithms/project-hashmap/tests/test_map_hash.hpp | vampy/university | 9496cb63594dcf1cc2cec8650b8eee603f85fdab | [
"MIT"
] | 1 | 2015-09-26T09:01:54.000Z | 2015-09-26T09:01:54.000Z | #ifndef TEST_MAP_HASH_H_
#define TEST_MAP_HASH_H_
#include <cassert>
#include <string>
#include "../map_hash.hpp"
using namespace std;
static void testMapHashInit()
{
auto test = new MapHash::Map<int>;
assert(test->isEmpty() == true);
assert(test->containsKey("A") == false);
assert(test->getLength() == 0);
delete test;
}
static void testMapHashCRUD()
{
auto test = new MapHash::Map<int>;
// put/get
assert(test->isEmpty() == true);
test->put("A", 1);
assert(test->isEmpty() == false);
test->put("B", 2);
test->put("C", 3);
assert(test->get("A") == 1);
assert(test->get("B") == 2);
assert(test->get("C") == 3);
assert(test->containsKey("Z") == false);
assert(test->containsKey("a") == false);
assert(test->containsKey("b") == false);
assert(test->containsKey("c") == false);
// remove
assert(test->containsKey("A") == true);
test->remove("A");
assert(test->containsKey("A") == false);
assert(test->containsKey("B") == true);
test->remove("B");
assert(test->containsKey("B") == false);
assert(test->containsKey("C") == true);
test->remove("C");
assert(test->containsKey("C") == false);
assert(test->isEmpty() == true);
delete test;
}
void testMapHashIterator()
{
unsigned int length = 0, test_length = 1200, i;
auto test = new MapHash::Map<int>;
for (i = 0; i < test_length; i++)
{
length++;
test->put(to_string(i), i);
assert(length == test->getLength());
}
auto it = test->getIterator();
length = 0;
while (it->hasNext())
{
auto element = it->next();
assert(element->key == to_string(element->value));
length++;
}
assert(length == test->getLength());
delete it;
delete test;
}
void testMapHash()
{
testMapHashInit();
testMapHashCRUD();
testMapHashIterator();
}
#endif // TEST_MAP_HASH_H_
| 22.056818 | 58 | 0.575992 | vampy |
4773f6d904dd964414634842934b3ac94122ba3d | 1,438 | cpp | C++ | PE/ch07/7.3.cpp | DustOfStars/CppPrimerPlus6 | 391e3ad76eaa99f331981cee72139d83115fc93d | [
"MIT"
] | null | null | null | PE/ch07/7.3.cpp | DustOfStars/CppPrimerPlus6 | 391e3ad76eaa99f331981cee72139d83115fc93d | [
"MIT"
] | null | null | null | PE/ch07/7.3.cpp | DustOfStars/CppPrimerPlus6 | 391e3ad76eaa99f331981cee72139d83115fc93d | [
"MIT"
] | null | null | null | /*
* Here is a structure declaration:
* struct box
* {
* char maker[40];
* float height;
* float width;
* float length;
* float volume;
* };
* a. Write a function that passes a box structure by value and that
* displays the value of each member.
* b. Write a function that passes the address of a box structure and that
* sets the volume member to be the product of the other three
* dimensions.
* c. Write a simple program that uses these two functions.
*/
#include <iostream>
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
void setbox(box *);
void showbox(box);
int main()
{
box abox;
setbox(&abox);
showbox(abox);
return 0;
}
void setbox(box * pbox)
{
using namespace std;
cout << "Enter the maker of the box: ";
cin.getline(pbox->maker, 40);
cout << "Enter the height of the box: ";
cin >> pbox->height;
cout << "Enter the width of the box: ";
cin >> pbox->width;
cout << "Enter the length of the box: ";
cin >> pbox->length;
pbox->volume = pbox->height * pbox->width * pbox->length;
}
void showbox(box abox)
{
using namespace std;
cout << "Maker: " << abox.maker << endl;
cout << "Height: " << abox.height << endl;
cout << "Width: " << abox.width << endl;
cout << "Length: " << abox.length << endl;
cout << "Volume: " << abox.volume << endl;
}
| 23.193548 | 74 | 0.599444 | DustOfStars |
477c043a83046e8df11f1c09270247b327afbaf7 | 525 | hpp | C++ | src/picotorrent/sessionstate.hpp | kamyarpour/picotorrent | bc33ca2f84d95b431ff62bbeb64fcb8f15d94c73 | [
"MIT"
] | 1 | 2020-01-13T23:33:44.000Z | 2020-01-13T23:33:44.000Z | src/picotorrent/sessionstate.hpp | kamyarpour/picotorrent | bc33ca2f84d95b431ff62bbeb64fcb8f15d94c73 | [
"MIT"
] | null | null | null | src/picotorrent/sessionstate.hpp | kamyarpour/picotorrent | bc33ca2f84d95b431ff62bbeb64fcb8f15d94c73 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <memory>
#include <unordered_set>
#include <libtorrent/fwd.hpp>
#include <libtorrent/sha1_hash.hpp>
namespace pt
{
struct SessionState
{
bool isSelected(libtorrent::sha1_hash const& hash);
std::unordered_set<libtorrent::sha1_hash> pauseAfterChecking;
std::unordered_set<libtorrent::sha1_hash> selectedTorrents;
std::unique_ptr<libtorrent::session> session;
std::map<libtorrent::sha1_hash, libtorrent::torrent_handle> torrents;
};
}
| 23.863636 | 77 | 0.712381 | kamyarpour |
4780cee7220596d117c7561435c2612e9579fab3 | 382 | cpp | C++ | exe6.cpp | priya29jps/top-100-code-in-cpp | 22d9328217a7f2ecbd09e62e750d8cad37baf046 | [
"Apache-2.0"
] | null | null | null | exe6.cpp | priya29jps/top-100-code-in-cpp | 22d9328217a7f2ecbd09e62e750d8cad37baf046 | [
"Apache-2.0"
] | null | null | null | exe6.cpp | priya29jps/top-100-code-in-cpp | 22d9328217a7f2ecbd09e62e750d8cad37baf046 | [
"Apache-2.0"
] | null | null | null | //problem in linear search
#include<iostream>
using namespace std;
int linearSearch(int arry[],int n,int key)
{
for(int i=0;i<=n;i++)
if(arry[i]==key){
return i;
}
return -1;
}
int main(){
int n;
cin>>n;
int arry[n];
for(int i=0;i<=n;i++)
{
cin>>arry[i];
}
int key;
cin>>key;
cout<<linearSearch(arry,n,key);
return 0;
}
| 11.9375 | 43 | 0.536649 | priya29jps |
4783265799cbd7bf20ce6043d7246983f38d937c | 16,464 | cc | C++ | tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem_test.cc | eee4017/tensorflow | deba51f80e05775bb4cc83647b475802be58f1e4 | [
"Apache-2.0"
] | null | null | null | tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem_test.cc | eee4017/tensorflow | deba51f80e05775bb4cc83647b475802be58f1e4 | [
"Apache-2.0"
] | null | null | null | tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem_test.cc | eee4017/tensorflow | deba51f80e05775bb4cc83647b475802be58f1e4 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem.h"
#include <fstream>
#include <random>
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/stacktrace_handler.h"
#include "tensorflow/core/platform/test.h"
#define ASSERT_TF_OK(x) ASSERT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x)
#define EXPECT_TF_OK(x) EXPECT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x)
static std::string InitializeTmpDir() {
// This env should be something like `s3://bucket/path`
const char* test_dir = getenv("S3_TEST_TMPDIR");
if (test_dir != nullptr) {
Aws::String bucket, object;
TF_Status* status = TF_NewStatus();
ParseS3Path(test_dir, true, &bucket, &object, status);
if (TF_GetCode(status) != TF_OK) {
TF_DeleteStatus(status);
return "";
}
TF_DeleteStatus(status);
// We add a random value into `test_dir` to ensures that two consecutive
// runs are unlikely to clash.
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distribution;
std::string rng_val = std::to_string(distribution(gen));
return tensorflow::io::JoinPath(std::string(test_dir), rng_val);
} else {
return "";
}
}
static std::string GetLocalLargeFile() {
// This env is used when we want to test against a large file ( ~ 50MB ).
// `S3_TEST_LOCAL_LARGE_FILE` and `S3_TEST_SERVER_LARGE_FILE` must be the same
// file.
static std::string path;
if (path.empty()) {
const char* env = getenv("S3_TEST_LOCAL_LARGE_FILE");
if (env == nullptr) return "";
path = env;
}
return path;
}
static std::string GetServerLargeFile() {
// This env is used when we want to test against a large file ( ~ 50MB ).
// `S3_TEST_LOCAL_LARGE_FILE` and `S3_TEST_SERVER_LARGE_FILE` must be the same
// file.
static std::string path;
if (path.empty()) {
const char* env = getenv("S3_TEST_SERVER_LARGE_FILE");
if (env == nullptr) return "";
Aws::String bucket, object;
TF_Status* status = TF_NewStatus();
ParseS3Path(env, false, &bucket, &object, status);
if (TF_GetCode(status) != TF_OK) {
TF_DeleteStatus(status);
return "";
}
TF_DeleteStatus(status);
path = env;
}
return path;
}
static std::string* GetTmpDir() {
static std::string tmp_dir = InitializeTmpDir();
if (tmp_dir == "")
return nullptr;
else
return &tmp_dir;
}
namespace tensorflow {
namespace {
class S3FilesystemTest : public ::testing::Test {
public:
void SetUp() override {
root_dir_ = io::JoinPath(
*GetTmpDir(),
::testing::UnitTest::GetInstance()->current_test_info()->name());
status_ = TF_NewStatus();
filesystem_ = new TF_Filesystem;
tf_s3_filesystem::Init(filesystem_, status_);
ASSERT_TF_OK(status_) << "Could not initialize filesystem. "
<< TF_Message(status_);
}
void TearDown() override {
TF_DeleteStatus(status_);
tf_s3_filesystem::Cleanup(filesystem_);
delete filesystem_;
}
std::string GetURIForPath(const std::string& path) {
const std::string translated_name =
tensorflow::io::JoinPath(root_dir_, path);
return translated_name;
}
std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile* file)>
GetWriter() {
std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile * file)> writer(
new TF_WritableFile, [](TF_WritableFile* file) {
if (file != nullptr) {
if (file->plugin_file != nullptr) tf_writable_file::Cleanup(file);
delete file;
}
});
writer->plugin_file = nullptr;
return writer;
}
std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile* file)>
GetReader() {
std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile * file)>
reader(new TF_RandomAccessFile, [](TF_RandomAccessFile* file) {
if (file != nullptr) {
if (file->plugin_file != nullptr)
tf_random_access_file::Cleanup(file);
delete file;
}
});
reader->plugin_file = nullptr;
return reader;
}
void WriteString(const std::string& path, const std::string& content) {
auto writer = GetWriter();
tf_s3_filesystem::NewWritableFile(filesystem_, path.c_str(), writer.get(),
status_);
if (TF_GetCode(status_) != TF_OK) return;
tf_writable_file::Append(writer.get(), content.c_str(), content.length(),
status_);
if (TF_GetCode(status_) != TF_OK) return;
tf_writable_file::Close(writer.get(), status_);
if (TF_GetCode(status_) != TF_OK) return;
}
std::string ReadAll(const string& path) {
auto reader = GetReader();
tf_s3_filesystem::NewRandomAccessFile(filesystem_, path.c_str(),
reader.get(), status_);
if (TF_GetCode(status_) != TF_OK) return "";
auto file_size =
tf_s3_filesystem::GetFileSize(filesystem_, path.c_str(), status_);
if (TF_GetCode(status_) != TF_OK) return "";
std::string content;
content.resize(file_size);
auto read = tf_random_access_file::Read(reader.get(), 0, file_size,
&content[0], status_);
if (TF_GetCode(status_) != TF_OK) return "";
if (read >= 0) content.resize(read);
if (file_size != content.size())
TF_SetStatus(
status_, TF_DATA_LOSS,
std::string("expected " + std::to_string(file_size) + " got " +
std::to_string(content.size()) + " bytes")
.c_str());
return content;
}
std::string ReadAllInChunks(const string& path, size_t buffer_size,
bool use_multi_part_download) {
auto reader = GetReader();
auto s3_file =
static_cast<tf_s3_filesystem::S3File*>(filesystem_->plugin_filesystem);
s3_file->use_multi_part_download = use_multi_part_download;
s3_file
->multi_part_chunk_sizes[Aws::Transfer::TransferDirection::DOWNLOAD] =
buffer_size;
tf_s3_filesystem::NewRandomAccessFile(filesystem_, path.c_str(),
reader.get(), status_);
if (TF_GetCode(status_) != TF_OK) return "";
auto file_size =
tf_s3_filesystem::GetFileSize(filesystem_, path.c_str(), status_);
if (TF_GetCode(status_) != TF_OK) return "";
std::size_t part_count = (std::max)(
static_cast<size_t>((file_size + buffer_size - 1) / buffer_size),
static_cast<size_t>(1));
std::unique_ptr<char[]> buffer{new char[buffer_size]};
std::stringstream ss;
uint64_t offset = 0;
uint64_t server_size = 0;
for (size_t i = 0; i < part_count; i++) {
offset = i * buffer_size;
buffer_size =
(i == part_count - 1) ? file_size - server_size : buffer_size;
auto read = tf_random_access_file::Read(reader.get(), offset, buffer_size,
buffer.get(), status_);
if (TF_GetCode(status_) != TF_OK) return "";
if (read > 0) {
ss.write(buffer.get(), read);
server_size += static_cast<uint64_t>(read);
}
if (server_size == file_size) break;
if (read != buffer_size) {
if (read == 0)
TF_SetStatus(status_, TF_OUT_OF_RANGE, "eof");
else
TF_SetStatus(
status_, TF_DATA_LOSS,
("truncated record at " + std::to_string(offset)).c_str());
return "";
}
}
if (file_size != server_size) {
TF_SetStatus(status_, TF_DATA_LOSS,
std::string("expected " + std::to_string(file_size) +
" got " + std::to_string(server_size) + " bytes")
.c_str());
return "";
}
TF_SetStatus(status_, TF_OK, "");
return ss.str();
}
protected:
TF_Filesystem* filesystem_;
TF_Status* status_;
private:
std::string root_dir_;
};
TEST_F(S3FilesystemTest, NewRandomAccessFile) {
const std::string path = GetURIForPath("RandomAccessFile");
const std::string content = "abcdefghijklmn";
WriteString(path, content);
ASSERT_TF_OK(status_);
auto reader = GetReader();
tf_s3_filesystem::NewRandomAccessFile(filesystem_, path.c_str(), reader.get(),
status_);
EXPECT_TF_OK(status_);
std::string result;
result.resize(content.size());
auto read = tf_random_access_file::Read(reader.get(), 0, content.size(),
&result[0], status_);
result.resize(read);
EXPECT_TF_OK(status_);
EXPECT_EQ(content.size(), result.size());
EXPECT_EQ(content, result);
result.clear();
result.resize(4);
read = tf_random_access_file::Read(reader.get(), 2, 4, &result[0], status_);
result.resize(read);
EXPECT_TF_OK(status_);
EXPECT_EQ(4, result.size());
EXPECT_EQ(content.substr(2, 4), result);
}
TEST_F(S3FilesystemTest, NewWritableFile) {
auto writer = GetWriter();
const std::string path = GetURIForPath("WritableFile");
tf_s3_filesystem::NewWritableFile(filesystem_, path.c_str(), writer.get(),
status_);
EXPECT_TF_OK(status_);
tf_writable_file::Append(writer.get(), "content1,", strlen("content1,"),
status_);
EXPECT_TF_OK(status_);
tf_writable_file::Append(writer.get(), "content2", strlen("content2"),
status_);
EXPECT_TF_OK(status_);
tf_writable_file::Flush(writer.get(), status_);
EXPECT_TF_OK(status_);
tf_writable_file::Sync(writer.get(), status_);
EXPECT_TF_OK(status_);
tf_writable_file::Close(writer.get(), status_);
EXPECT_TF_OK(status_);
auto content = ReadAll(path);
EXPECT_TF_OK(status_);
EXPECT_EQ("content1,content2", content);
}
TEST_F(S3FilesystemTest, NewAppendableFile) {
const std::string path = GetURIForPath("AppendableFile");
WriteString(path, "test");
ASSERT_TF_OK(status_);
auto writer = GetWriter();
tf_s3_filesystem::NewAppendableFile(filesystem_, path.c_str(), writer.get(),
status_);
EXPECT_TF_OK(status_);
tf_writable_file::Append(writer.get(), "content", strlen("content"), status_);
EXPECT_TF_OK(status_);
tf_writable_file::Close(writer.get(), status_);
EXPECT_TF_OK(status_);
}
TEST_F(S3FilesystemTest, NewReadOnlyMemoryRegionFromFile) {
const std::string path = GetURIForPath("MemoryFile");
const std::string content = "content";
WriteString(path, content);
ASSERT_TF_OK(status_);
std::unique_ptr<TF_ReadOnlyMemoryRegion,
void (*)(TF_ReadOnlyMemoryRegion * file)>
region(new TF_ReadOnlyMemoryRegion, [](TF_ReadOnlyMemoryRegion* file) {
if (file != nullptr) {
if (file->plugin_memory_region != nullptr)
tf_read_only_memory_region::Cleanup(file);
delete file;
}
});
region->plugin_memory_region = nullptr;
tf_s3_filesystem::NewReadOnlyMemoryRegionFromFile(filesystem_, path.c_str(),
region.get(), status_);
EXPECT_TF_OK(status_);
std::string result(reinterpret_cast<const char*>(
tf_read_only_memory_region::Data(region.get())),
tf_read_only_memory_region::Length(region.get()));
EXPECT_EQ(content, result);
}
TEST_F(S3FilesystemTest, PathExists) {
const std::string path = GetURIForPath("PathExists");
tf_s3_filesystem::PathExists(filesystem_, path.c_str(), status_);
EXPECT_EQ(TF_NOT_FOUND, TF_GetCode(status_)) << TF_Message(status_);
TF_SetStatus(status_, TF_OK, "");
WriteString(path, "test");
ASSERT_TF_OK(status_);
tf_s3_filesystem::PathExists(filesystem_, path.c_str(), status_);
EXPECT_TF_OK(status_);
}
TEST_F(S3FilesystemTest, GetChildren) {
const std::string base = GetURIForPath("GetChildren");
tf_s3_filesystem::CreateDir(filesystem_, base.c_str(), status_);
EXPECT_TF_OK(status_);
const std::string file = io::JoinPath(base, "TestFile.csv");
WriteString(file, "test");
EXPECT_TF_OK(status_);
const std::string subdir = io::JoinPath(base, "SubDir");
tf_s3_filesystem::CreateDir(filesystem_, subdir.c_str(), status_);
EXPECT_TF_OK(status_);
const std::string subfile = io::JoinPath(subdir, "TestSubFile.csv");
WriteString(subfile, "test");
EXPECT_TF_OK(status_);
char** entries;
auto num_entries = tf_s3_filesystem::GetChildren(filesystem_, base.c_str(),
&entries, status_);
EXPECT_TF_OK(status_);
std::vector<std::string> childrens;
for (int i = 0; i < num_entries; ++i) {
childrens.push_back(entries[i]);
}
std::sort(childrens.begin(), childrens.end());
EXPECT_EQ(std::vector<string>({"SubDir", "TestFile.csv"}), childrens);
}
TEST_F(S3FilesystemTest, DeleteFile) {
const std::string path = GetURIForPath("DeleteFile");
WriteString(path, "test");
ASSERT_TF_OK(status_);
tf_s3_filesystem::DeleteFile(filesystem_, path.c_str(), status_);
EXPECT_TF_OK(status_);
}
TEST_F(S3FilesystemTest, CreateDir) {
// s3 object storage doesn't support empty directory, we create file in the
// directory
const std::string dir = GetURIForPath("CreateDir");
tf_s3_filesystem::CreateDir(filesystem_, dir.c_str(), status_);
EXPECT_TF_OK(status_);
const std::string file = io::JoinPath(dir, "CreateDirFile.csv");
WriteString(file, "test");
ASSERT_TF_OK(status_);
TF_FileStatistics stat;
tf_s3_filesystem::Stat(filesystem_, dir.c_str(), &stat, status_);
EXPECT_TF_OK(status_);
EXPECT_TRUE(stat.is_directory);
}
TEST_F(S3FilesystemTest, DeleteDir) {
// s3 object storage doesn't support empty directory, we create file in the
// directory
const std::string dir = GetURIForPath("DeleteDir");
const std::string file = io::JoinPath(dir, "DeleteDirFile.csv");
WriteString(file, "test");
ASSERT_TF_OK(status_);
tf_s3_filesystem::DeleteDir(filesystem_, dir.c_str(), status_);
EXPECT_NE(TF_GetCode(status_), TF_OK);
TF_SetStatus(status_, TF_OK, "");
tf_s3_filesystem::DeleteFile(filesystem_, file.c_str(), status_);
EXPECT_TF_OK(status_);
tf_s3_filesystem::DeleteDir(filesystem_, dir.c_str(), status_);
EXPECT_TF_OK(status_);
TF_FileStatistics stat;
tf_s3_filesystem::Stat(filesystem_, dir.c_str(), &stat, status_);
EXPECT_EQ(TF_GetCode(status_), TF_NOT_FOUND) << TF_Message(status_);
}
TEST_F(S3FilesystemTest, StatFile) {
const std::string path = GetURIForPath("StatFile");
WriteString(path, "test");
ASSERT_TF_OK(status_);
TF_FileStatistics stat;
tf_s3_filesystem::Stat(filesystem_, path.c_str(), &stat, status_);
EXPECT_TF_OK(status_);
EXPECT_EQ(4, stat.length);
EXPECT_FALSE(stat.is_directory);
}
// Test against large file.
TEST_F(S3FilesystemTest, ReadLargeFile) {
auto local_path = GetLocalLargeFile();
auto server_path = GetServerLargeFile();
if (local_path.empty() || server_path.empty()) GTEST_SKIP();
std::ifstream in(local_path, std::ios::binary);
std::string local_content((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
constexpr size_t buffer_size = 50 * 1024 * 1024;
auto server_content = ReadAllInChunks(server_path, buffer_size, true);
ASSERT_TF_OK(status_);
EXPECT_EQ(local_content, server_content);
server_content = ReadAllInChunks(server_path, buffer_size, false);
ASSERT_TF_OK(status_);
EXPECT_EQ(local_content, server_content);
}
} // namespace
} // namespace tensorflow
GTEST_API_ int main(int argc, char** argv) {
tensorflow::testing::InstallStacktraceHandler();
if (!GetTmpDir()) {
std::cerr << "Could not read S3_TEST_TMPDIR env";
return -1;
}
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 34.807611 | 80 | 0.65786 | eee4017 |
4784d18bb6726d8bb62bc800653c711e433dedde | 34 | cpp | C++ | libs/gfxtk_core/src/gfxtk/VertexBufferLayout.cpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | libs/gfxtk_core/src/gfxtk/VertexBufferLayout.cpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | libs/gfxtk_core/src/gfxtk/VertexBufferLayout.cpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | #include "VertexBufferLayout.hpp"
| 17 | 33 | 0.823529 | NostalgicGhoul |
47870e015675b95affca3b32252f7cf0dbf909c0 | 1,635 | cpp | C++ | cpp/src/bitmask/is_element_valid.cpp | sperlingxx/cudf | c681211df6253e1ceee9203658108980e7e93e3c | [
"Apache-2.0"
] | 4,012 | 2018-10-29T00:11:19.000Z | 2022-03-31T19:20:19.000Z | cpp/src/bitmask/is_element_valid.cpp | sperlingxx/cudf | c681211df6253e1ceee9203658108980e7e93e3c | [
"Apache-2.0"
] | 9,865 | 2018-10-29T12:52:07.000Z | 2022-03-31T23:09:21.000Z | cpp/src/bitmask/is_element_valid.cpp | sperlingxx/cudf | c681211df6253e1ceee9203658108980e7e93e3c | [
"Apache-2.0"
] | 588 | 2018-10-29T05:52:44.000Z | 2022-03-28T06:13:09.000Z |
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_view.hpp>
#include <cudf/utilities/bit.hpp>
#include <cudf/utilities/error.hpp>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace detail {
bool is_element_valid_sync(column_view const& col_view,
size_type element_index,
rmm::cuda_stream_view stream)
{
CUDF_EXPECTS(element_index >= 0 and element_index < col_view.size(), "invalid index.");
if (!col_view.nullable()) { return true; }
bitmask_type word;
// null_mask() returns device ptr to bitmask without offset
size_type index = element_index + col_view.offset();
CUDA_TRY(cudaMemcpyAsync(&word,
col_view.null_mask() + word_index(index),
sizeof(bitmask_type),
cudaMemcpyDeviceToHost,
stream.value()));
stream.synchronize();
return static_cast<bool>(word & (bitmask_type{1} << intra_word_index(index)));
}
} // namespace detail
} // namespace cudf
| 34.0625 | 89 | 0.670948 | sperlingxx |
4788a1215a9a1949583f450665725a926e64be85 | 1,367 | cpp | C++ | Source/Runtime/Private/Asset/JointMaskResource.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 410 | 2017-03-03T08:56:54.000Z | 2022-03-29T07:18:46.000Z | Source/Runtime/Private/Asset/JointMaskResource.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 31 | 2017-03-05T11:37:44.000Z | 2021-09-15T21:28:34.000Z | Source/Runtime/Private/Asset/JointMaskResource.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 48 | 2017-03-18T05:28:21.000Z | 2022-03-05T12:27:17.000Z | // Copyright(c) 2017 POLYGONTEK
//
// 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 "Precompiled.h"
#include "Asset/Asset.h"
#include "Asset/Resource.h"
BE_NAMESPACE_BEGIN
OBJECT_DECLARATION("Joint Mask", JointMaskResource, Resource)
BEGIN_EVENTS(JointMaskResource)
END_EVENTS
void JointMaskResource::RegisterProperties() {
}
JointMaskResource::JointMaskResource() {}
JointMaskResource::~JointMaskResource() {}
void JointMaskResource::Rename(const Str &newName) {
}
bool JointMaskResource::Reload() {
/*const Str jointMaskPath = resourceGuidMapper.Get(asset->GetGuid());
JointMask *existingJointMask = jointMaskManager.FindJointMask(jointMaskPath);
if (existingJointMask) {
existingJointMask->Reload();
return true;
}*/
return false;
}
bool JointMaskResource::Save() {
return false;
}
BE_NAMESPACE_END
| 27.34 | 81 | 0.746159 | redchew-fork |
478a0527bdc45ef2cfa205d878d9237ab61ce245 | 1,554 | cpp | C++ | GodGame/GodGame/SDLEngine/Renderers/RendererOpenGL/TextureOpenGL.cpp | NeutralNoise/GodGame | 454c94e361868ca169ca1d9268ad6737fa8e1741 | [
"MIT"
] | null | null | null | GodGame/GodGame/SDLEngine/Renderers/RendererOpenGL/TextureOpenGL.cpp | NeutralNoise/GodGame | 454c94e361868ca169ca1d9268ad6737fa8e1741 | [
"MIT"
] | null | null | null | GodGame/GodGame/SDLEngine/Renderers/RendererOpenGL/TextureOpenGL.cpp | NeutralNoise/GodGame | 454c94e361868ca169ca1d9268ad6737fa8e1741 | [
"MIT"
] | null | null | null | #include "TextureOpenGL.h"
#include <iostream>
#include <GL/glew.h>
//#include <SDL2/SDL.h>
//#include <SDL2/SDL_image.h>
#define STB_IMAGE_IMPLEMENTATION
#include <STB/stb_image.h>
#include "ErrorOpenGL.h"
Texture * TextureOpenGL::LoadTexture(const std::string & path)
{
unsigned char* m_LocalBuffer;
//stbi_set_flip_vertically_on_load(1);
this->file = path;
int m_BPP = 0;
m_LocalBuffer = stbi_load(path.c_str(), &(this->width), &(this->height), &m_BPP, 4);
if (m_BPP >= 4)
this->format = GL_RGBA8;
else
this->format = GL_RGB;
GLCall(glGenTextures(1, &m_textureID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_textureID));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, this->width, this->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer));
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
//SDL_FreeSurface(this->textureData.textureSurface);
return this;
}
void TextureOpenGL::Bind(const UInt32 & slot)
{
GLCall(glActiveTexture(GL_TEXTURE0 + slot));
GLCall(glBindTexture(GL_TEXTURE_2D, m_textureID));
}
void TextureOpenGL::Unbind()
{
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
}
void TextureOpenGL::SetTexure(void * tex)
{
m_textureID = (UInt32)(tex);
}
void * TextureOpenGL::GetTexure()
{
return (void *)m_textureID;
}
| 25.9 | 122 | 0.756113 | NeutralNoise |
478a2e65b1f8dc81c23d45027f87a26a5e7ac065 | 832 | cc | C++ | deprected/src/util/point.cc | RobertWeber1/cli | 5cb67325610be41014403e9342dddbe942511c2b | [
"MIT"
] | null | null | null | deprected/src/util/point.cc | RobertWeber1/cli | 5cb67325610be41014403e9342dddbe942511c2b | [
"MIT"
] | null | null | null | deprected/src/util/point.cc | RobertWeber1/cli | 5cb67325610be41014403e9342dddbe942511c2b | [
"MIT"
] | null | null | null | #include "point.h"
namespace CLI
{
namespace util
{
Point::Point( unsigned int x, unsigned int y )
: _x(x)
, _y(y)
{}
Point::Point( Point const& point )
: _x( point.x() )
, _y( point.y() )
{}
unsigned int Point::x() const
{
return _x;
}
unsigned int Point::y() const
{
return _y;
}
void Point::x( unsigned int new_x )
{
_x = new_x;
}
void Point::y( unsigned int new_y )
{
_y = new_y;
}
void Point::left( unsigned int x_offset )
{
_x -= x_offset ;
}
void Point::right( unsigned int x_offset )
{
_x += x_offset ;
}
void Point::up( unsigned int y_offset )
{
_y -= y_offset ;
}
void Point::down( unsigned int y_offset )
{
_y += y_offset ;
}
void Point::break_line()
{
_x = 0;
_y++;
}
void Point::set( unsigned int new_x, unsigned int new_y )
{
_x = new_x;
_y = new_y;
}
} //namespace util
} //namespace CLI
| 11.093333 | 57 | 0.623798 | RobertWeber1 |
478b6811f16f37bb2bdf56a284e79b54b9b6aa4e | 479 | cpp | C++ | telColorCode.cpp | Engin-Boot/modularity-cpp-univac-os | 36c62a6977eea2e4b14976cd2d45c1bd234102eb | [
"MIT"
] | null | null | null | telColorCode.cpp | Engin-Boot/modularity-cpp-univac-os | 36c62a6977eea2e4b14976cd2d45c1bd234102eb | [
"MIT"
] | null | null | null | telColorCode.cpp | Engin-Boot/modularity-cpp-univac-os | 36c62a6977eea2e4b14976cd2d45c1bd234102eb | [
"MIT"
] | null | null | null | #include "telColorCode.h"
#include<string.h>
using namespace std;
//defination of class
namespace TelCoColorCoder {
MajorColor ColorPair::getMajor() {
return majorColor;
}
MinorColor ColorPair::getMinor() {
return minorColor;
}
string ColorPair::ToString() {
string colorPairStr = MajorColorNames[majorColor];
colorPairStr += " ";
colorPairStr += MinorColorNames[minorColor];
return colorPairStr;
}
}
| 23.95 | 58 | 0.649269 | Engin-Boot |
478bcdd1b72fef6c2dac52463c6c7beaddcb9f7d | 1,804 | cpp | C++ | rel-lib/src/Logger.cpp | sscit/rel | d9e6815012334dfc4c99b8020ae42a9ca9860458 | [
"MIT"
] | 2 | 2020-12-26T20:18:46.000Z | 2021-05-01T03:55:22.000Z | rel-lib/src/Logger.cpp | sscit/rel | d9e6815012334dfc4c99b8020ae42a9ca9860458 | [
"MIT"
] | 2 | 2021-01-04T00:01:51.000Z | 2021-04-07T18:25:10.000Z | rel-lib/src/Logger.cpp | sscit/rel | d9e6815012334dfc4c99b8020ae42a9ca9860458 | [
"MIT"
] | 2 | 2021-01-03T00:32:20.000Z | 2021-01-04T01:06:18.000Z | /* SPDX-License-Identifier: MIT */
/* Copyright (c) 2020-present Stefan Schlichthärle */
#include "Logger.h"
Logger::Logger() : current_loglevel(LogLevel::WARNING) {}
Logger::Logger(std::string const filename) : Logger() {
file_access.open(filename);
}
Logger::~Logger() {
if (file_access.is_open()) file_access.close();
}
void Logger::SetLogLevel(LogLevel const l) { current_loglevel = l; }
LogLevel Logger::GetCurrentLogLevel() const { return current_loglevel; }
std::string Logger::LogLevelToString(LogLevel const l) const {
std::string result;
switch (l) {
case LogLevel::DBUG:
result = "DBUG";
break;
case LogLevel::INFO:
result = "INFO";
break;
case LogLevel::WARNING:
result = "WARNING";
break;
case LogLevel::ERROR:
result = "ERROR";
break;
default:
result = "UNKNOWN_LOGLEVEL";
}
return result;
}
void Logger::LogMessage(LogLevel const loglevel, std::string const message,
std::string const filename = "Unset",
int const line_number = -1) {
std::lock_guard<std::mutex> db_lock(mtx);
if (loglevel <= GetCurrentLogLevel()) {
if (file_access.is_open()) {
file_access << LogLevelToString(loglevel) << ": "
<< "File " << filename << ", Line " << line_number
<< ": ";
file_access << message << std::endl;
file_access.flush();
} else {
std::cout << LogLevelToString(loglevel) << ": "
<< "File " << filename << ", Line " << line_number
<< ": ";
std::cout << message << std::endl;
}
}
}
| 29.57377 | 75 | 0.533259 | sscit |
478c7e0be4858a8dd3ed9cb329da8a316b1a0b30 | 11,045 | cpp | C++ | applications/PfemFluidDynamicsApplication/custom_elements/updated_lagrangian_V_implicit_solid_element.cpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | null | null | null | applications/PfemFluidDynamicsApplication/custom_elements/updated_lagrangian_V_implicit_solid_element.cpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 3 | 2021-08-18T16:12:20.000Z | 2021-09-02T07:36:15.000Z | applications/PfemFluidDynamicsApplication/custom_elements/updated_lagrangian_V_implicit_solid_element.cpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 1 | 2017-05-02T00:52:44.000Z | 2017-05-02T00:52:44.000Z | //
// Project Name: KratosFluidDynamicsApplication $
// Last modified by: $Author: AFranci $
// Date: $Date: February 2016 $
// Revision: $Revision: 0.0 $
//
//
// System includes
// External includes
// Project includes
#include "custom_elements/updated_lagrangian_V_implicit_solid_element.h"
#include "includes/cfd_variables.h"
namespace Kratos
{
/*
* public UpdatedLagrangianVImplicitSolidElement<TDim> functions
*/
template <unsigned int TDim>
Element::Pointer UpdatedLagrangianVImplicitSolidElement<TDim>::Clone(IndexType NewId, NodesArrayType const &rThisNodes) const
{
// return Element::Pointer( BaseType::Clone(NewId,rThisNodes) );
UpdatedLagrangianVImplicitSolidElement NewElement(NewId, this->GetGeometry().Create(rThisNodes), this->pGetProperties());
if (NewElement.mCurrentTotalCauchyStress.size() != this->mCurrentTotalCauchyStress.size())
NewElement.mCurrentTotalCauchyStress.resize(this->mCurrentTotalCauchyStress.size());
for (unsigned int i = 0; i < this->mCurrentTotalCauchyStress.size(); i++)
{
NewElement.mCurrentTotalCauchyStress[i] = this->mCurrentTotalCauchyStress[i];
}
if (NewElement.mCurrentDeviatoricCauchyStress.size() != this->mCurrentDeviatoricCauchyStress.size())
NewElement.mCurrentDeviatoricCauchyStress.resize(this->mCurrentDeviatoricCauchyStress.size());
for (unsigned int i = 0; i < this->mCurrentDeviatoricCauchyStress.size(); i++)
{
NewElement.mCurrentDeviatoricCauchyStress[i] = this->mCurrentDeviatoricCauchyStress[i];
}
if (NewElement.mUpdatedTotalCauchyStress.size() != this->mUpdatedTotalCauchyStress.size())
NewElement.mUpdatedTotalCauchyStress.resize(this->mUpdatedTotalCauchyStress.size());
for (unsigned int i = 0; i < this->mUpdatedTotalCauchyStress.size(); i++)
{
NewElement.mUpdatedTotalCauchyStress[i] = this->mUpdatedTotalCauchyStress[i];
}
if (NewElement.mUpdatedDeviatoricCauchyStress.size() != this->mUpdatedDeviatoricCauchyStress.size())
NewElement.mUpdatedDeviatoricCauchyStress.resize(this->mUpdatedDeviatoricCauchyStress.size());
for (unsigned int i = 0; i < this->mUpdatedDeviatoricCauchyStress.size(); i++)
{
NewElement.mUpdatedDeviatoricCauchyStress[i] = this->mUpdatedDeviatoricCauchyStress[i];
}
NewElement.SetData(this->GetData());
NewElement.SetFlags(this->GetFlags());
return Element::Pointer(new UpdatedLagrangianVImplicitSolidElement(NewElement));
}
template <>
void UpdatedLagrangianVImplicitSolidElement<2>::CalcElasticPlasticCauchySplitted(
ElementalVariables &rElementalVariables, double TimeStep, unsigned int g, const ProcessInfo &rCurrentProcessInfo,
double &Density, double &DeviatoricCoeff, double &VolumetricCoeff) {
mpConstitutiveLaw = this->GetProperties().GetValue(CONSTITUTIVE_LAW);
auto constitutive_law_values =
ConstitutiveLaw::Parameters(this->GetGeometry(), this->GetProperties(), rCurrentProcessInfo);
Flags &constitutive_law_options = constitutive_law_values.GetOptions();
constitutive_law_options.Set(ConstitutiveLaw::COMPUTE_STRESS, true);
constitutive_law_options.Set(ConstitutiveLaw::COMPUTE_CONSTITUTIVE_TENSOR, false);
rElementalVariables.CurrentTotalCauchyStress = this->mCurrentTotalCauchyStress[g];
rElementalVariables.CurrentDeviatoricCauchyStress = this->mCurrentDeviatoricCauchyStress[g];
const Vector &r_shape_functions = row((this->GetGeometry()).ShapeFunctionsValues(), g);
constitutive_law_values.SetShapeFunctionsValues(r_shape_functions);
constitutive_law_values.SetStrainVector(rElementalVariables.SpatialDefRate);
constitutive_law_values.SetStressVector(rElementalVariables.CurrentDeviatoricCauchyStress);
mpConstitutiveLaw->CalculateMaterialResponseCauchy(constitutive_law_values);
Density = mpConstitutiveLaw->CalculateValue(constitutive_law_values, DENSITY, Density);
double poisson_ratio = mpConstitutiveLaw->CalculateValue(constitutive_law_values, POISSON_RATIO, poisson_ratio);
double young_modulus = mpConstitutiveLaw->CalculateValue(constitutive_law_values, YOUNG_MODULUS, young_modulus);
const double time_step = rCurrentProcessInfo[DELTA_TIME];
DeviatoricCoeff = time_step * young_modulus / (2.0 * (1 + poisson_ratio));
VolumetricCoeff =
time_step * poisson_ratio * young_modulus / ((1.0 + poisson_ratio) * (1.0 - 2.0 * poisson_ratio)) +
2.0 / 3.0 * DeviatoricCoeff;
const double current_first_lame = VolumetricCoeff - 2.0 / 3.0 * DeviatoricCoeff;
this->mMaterialDeviatoricCoefficient = DeviatoricCoeff;
this->mMaterialVolumetricCoefficient = VolumetricCoeff;
this->mMaterialDensity = Density;
rElementalVariables.UpdatedDeviatoricCauchyStress[0] = rElementalVariables.CurrentDeviatoricCauchyStress[0];
rElementalVariables.UpdatedDeviatoricCauchyStress[1] = rElementalVariables.CurrentDeviatoricCauchyStress[1];
rElementalVariables.UpdatedDeviatoricCauchyStress[2] = rElementalVariables.CurrentDeviatoricCauchyStress[2];
rElementalVariables.UpdatedTotalCauchyStress[0] = +current_first_lame * rElementalVariables.VolumetricDefRate +
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[0] +
rElementalVariables.CurrentTotalCauchyStress[0];
rElementalVariables.UpdatedTotalCauchyStress[1] = current_first_lame * rElementalVariables.VolumetricDefRate +
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[1] +
rElementalVariables.CurrentTotalCauchyStress[1];
rElementalVariables.UpdatedTotalCauchyStress[2] =
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[2] + rElementalVariables.CurrentTotalCauchyStress[2];
this->SetValue(CAUCHY_STRESS_VECTOR, rElementalVariables.UpdatedTotalCauchyStress);
this->mUpdatedTotalCauchyStress[g] = rElementalVariables.UpdatedTotalCauchyStress;
this->mUpdatedDeviatoricCauchyStress[g] = rElementalVariables.UpdatedDeviatoricCauchyStress;
}
template <>
void UpdatedLagrangianVImplicitSolidElement<3>::CalcElasticPlasticCauchySplitted(
ElementalVariables &rElementalVariables, double TimeStep, unsigned int g, const ProcessInfo &rCurrentProcessInfo,
double &Density, double &DeviatoricCoeff, double &VolumetricCoeff) {
mpConstitutiveLaw = this->GetProperties().GetValue(CONSTITUTIVE_LAW);
auto constitutive_law_values =
ConstitutiveLaw::Parameters(this->GetGeometry(), this->GetProperties(), rCurrentProcessInfo);
Flags &constitutive_law_options = constitutive_law_values.GetOptions();
constitutive_law_options.Set(ConstitutiveLaw::COMPUTE_STRESS, true);
constitutive_law_options.Set(ConstitutiveLaw::COMPUTE_CONSTITUTIVE_TENSOR, false);
rElementalVariables.CurrentTotalCauchyStress = this->mCurrentTotalCauchyStress[g];
rElementalVariables.CurrentDeviatoricCauchyStress = this->mCurrentDeviatoricCauchyStress[g];
const Vector &r_shape_functions = row((this->GetGeometry()).ShapeFunctionsValues(), g);
constitutive_law_values.SetShapeFunctionsValues(r_shape_functions);
constitutive_law_values.SetStrainVector(rElementalVariables.SpatialDefRate);
constitutive_law_values.SetStressVector(rElementalVariables.CurrentDeviatoricCauchyStress);
mpConstitutiveLaw->CalculateMaterialResponseCauchy(constitutive_law_values);
Density = mpConstitutiveLaw->CalculateValue(constitutive_law_values, DENSITY, Density);
double poisson_ratio = mpConstitutiveLaw->CalculateValue(constitutive_law_values, POISSON_RATIO, poisson_ratio);
double young_modulus = mpConstitutiveLaw->CalculateValue(constitutive_law_values, YOUNG_MODULUS, young_modulus);
const double time_step = rCurrentProcessInfo[DELTA_TIME];
DeviatoricCoeff = time_step * young_modulus / (2.0 * (1 + poisson_ratio));
VolumetricCoeff =
time_step * poisson_ratio * young_modulus / ((1.0 + poisson_ratio) * (1.0 - 2.0 * poisson_ratio)) +
2.0 / 3.0 * DeviatoricCoeff;
const double current_first_lame = VolumetricCoeff - 2.0 / 3.0 * DeviatoricCoeff;
this->mMaterialDeviatoricCoefficient = DeviatoricCoeff;
this->mMaterialVolumetricCoefficient = VolumetricCoeff;
this->mMaterialDensity = Density;
rElementalVariables.UpdatedDeviatoricCauchyStress[0] = rElementalVariables.CurrentDeviatoricCauchyStress[0];
rElementalVariables.UpdatedDeviatoricCauchyStress[1] = rElementalVariables.CurrentDeviatoricCauchyStress[1];
rElementalVariables.UpdatedDeviatoricCauchyStress[2] = rElementalVariables.CurrentDeviatoricCauchyStress[2];
rElementalVariables.UpdatedDeviatoricCauchyStress[3] = rElementalVariables.CurrentDeviatoricCauchyStress[3];
rElementalVariables.UpdatedDeviatoricCauchyStress[4] = rElementalVariables.CurrentDeviatoricCauchyStress[4];
rElementalVariables.UpdatedDeviatoricCauchyStress[5] = rElementalVariables.CurrentDeviatoricCauchyStress[5];
rElementalVariables.UpdatedTotalCauchyStress[0] = +current_first_lame * rElementalVariables.VolumetricDefRate +
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[0] +
rElementalVariables.CurrentTotalCauchyStress[0];
rElementalVariables.UpdatedTotalCauchyStress[1] = current_first_lame * rElementalVariables.VolumetricDefRate +
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[1] +
rElementalVariables.CurrentTotalCauchyStress[1];
rElementalVariables.UpdatedTotalCauchyStress[2] = current_first_lame * rElementalVariables.VolumetricDefRate +
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[2] +
rElementalVariables.CurrentTotalCauchyStress[2];
rElementalVariables.UpdatedTotalCauchyStress[3] =
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[3] + rElementalVariables.CurrentTotalCauchyStress[3];
rElementalVariables.UpdatedTotalCauchyStress[4] =
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[4] + rElementalVariables.CurrentTotalCauchyStress[4];
rElementalVariables.UpdatedTotalCauchyStress[5] =
2.0 * DeviatoricCoeff * rElementalVariables.SpatialDefRate[5] + rElementalVariables.CurrentTotalCauchyStress[5];
this->SetValue(CAUCHY_STRESS_VECTOR, rElementalVariables.UpdatedTotalCauchyStress);
this->mUpdatedTotalCauchyStress[g] = rElementalVariables.UpdatedTotalCauchyStress;
this->mUpdatedDeviatoricCauchyStress[g] = rElementalVariables.UpdatedDeviatoricCauchyStress;
}
template class UpdatedLagrangianVImplicitSolidElement<2>;
template class UpdatedLagrangianVImplicitSolidElement<3>;
} // namespace Kratos
| 55.782828 | 125 | 0.759167 | clazaro |
478dafe437dee50cd92e62e59ca5f1548d108f24 | 6,832 | hpp | C++ | src/ns.hpp | MilesLitteral/mtlpp | 0915732f9bb958bea476c19b2d9de3637d857c92 | [
"MIT"
] | 1 | 2022-01-11T05:44:44.000Z | 2022-01-11T05:44:44.000Z | src/ns.hpp | MilesLitteral/mtlpp | 0915732f9bb958bea476c19b2d9de3637d857c92 | [
"MIT"
] | null | null | null | src/ns.hpp | MilesLitteral/mtlpp | 0915732f9bb958bea476c19b2d9de3637d857c92 | [
"MIT"
] | null | null | null | /*
* Copyright 2016-2017 Nikolay Aleksiev. All rights reserved.
* License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE
*/
#pragma once
#include "defines.hpp"
namespace ns
{
struct Handle
{
const void* ptr;
};
class Object
{
public:
inline const void* GetPtr() const { return m_ptr; }
inline operator bool() const { return m_ptr != nullptr; }
protected:
Object();
Object(const Handle& handle);
Object(const Object& rhs);
#if MTLPP_CONFIG_RVALUE_REFERENCES
Object(Object&& rhs);
#endif
virtual ~Object();
Object& operator=(const Object& rhs);
#if MTLPP_CONFIG_RVALUE_REFERENCES
Object& operator=(Object&& rhs);
#endif
inline void Validate() const
{
#if MTLPP_CONFIG_VALIDATE
assert(m_ptr);
#endif
}
const void* m_ptr = nullptr;
};
struct Range
{
inline Range(uint32_t location, uint32_t length) :
Location(location),
Length(length)
{ }
uint32_t Location;
uint32_t Length;
};
class ArrayBase : public Object
{
public:
ArrayBase() { }
ArrayBase(const Handle& handle) : Object(handle) { }
uint32_t GetSize() const;
protected:
void* GetItem(uint32_t index) const;
};
template<typename T>
class Array : public ArrayBase
{
public:
Array() { }
Array(const Handle& handle) : ArrayBase(handle) { }
const T operator[](uint32_t index) const
{
return Handle{ GetItem(index) };
}
T operator[](uint32_t index)
{
return Handle{ GetItem(index) };
}
};
class DictionaryBase : public Object
{
public:
DictionaryBase() { }
DictionaryBase(const Handle& handle) : Object(handle) { }
protected:
};
template<typename KeyT, typename ValueT>
class Dictionary : public DictionaryBase
{
public:
Dictionary() { }
Dictionary(const Handle& handle) : DictionaryBase(handle) { }
};
class String : public Object
{
public:
String() { }
String(const Handle& handle) : Object(handle) { }
String(const char* cstr);
const char* GetCStr() const;
uint32_t GetLength() const;
};
class Error : public Object
{
public:
Error();
Error(const Handle& handle) : Object(handle) { }
String GetDomain() const;
uint32_t GetCode() const;
//@property (readonly, copy) NSDictionary *userInfo;
String GetLocalizedDescription() const;
String GetLocalizedFailureReason() const;
String GetLocalizedRecoverySuggestion() const;
String GetLocalizedRecoveryOptions() const;
//@property (nullable, readonly, strong) id recoveryAttempter;
String GetHelpAnchor() const;
};
class URL : public Object
{
public:
URL();
URL(const String* pString);
URL(const String* pPath);
const char* fileSystemRepresentation() const;
};
class Bundle : public Object
{
// private:
// _NS_CONST(NotificationName, BundleDidLoadNotification);
// _NS_CONST(NotificationName, BundleResourceRequestLowDiskSpaceNotification);
public:
static Bundle* mainBundle();
Bundle(const class String* pPath);
Bundle(const class URL* pURL);
Bundle(const ns::Handle& handle) : ns::Object(handle) { }
Bundle* init(const class String* pPath);
Bundle* init(const class URL* pURL);
Array<Bundle>* allBundles() const;
//Array* allFrameworks() const; //revisit
bool load();
bool unload();
bool isLoaded() const;
bool preflightAndReturnError(class Error** pError) const;
bool loadAndReturnError(class Error** pError);
class URL* bundleURL() const;
class URL* resourceURL() const;
class URL* executableURL() const;
class URL* URLForAuxiliaryExecutable(const class String* pExecutableName) const;
class URL* privateFrameworksURL() const;
class URL* sharedFrameworksURL() const;
class URL* sharedSupportURL() const;
class URL* builtInPlugInsURL() const;
class URL* appStoreReceiptURL() const;
class String* bundlePath() const;
class String* resourcePath() const;
class String* executablePath() const;
class String* pathForAuxiliaryExecutable(const class String* pExecutableName) const;
class String* privateFrameworksPath() const;
class String* sharedFrameworksPath() const;
class String* sharedSupportPath() const;
class String* builtInPlugInsPath() const;
class String* bundleIdentifier() const;
class Dictionary* infoDictionary() const;
class Dictionary* localizedInfoDictionary() const;
class Object* objectForInfoDictionaryKey(const String* pKey);
class String* localizedString(const String* pKey, const String* pValue = nullptr, const String* pTableName = nullptr) const;
class String* LocalizedString(const String* pKey, const String*);
class String* LocalizedStringFromTable(const String* pKey, const String* pTbl, const String*);
class String* LocalizedStringFromTableInBundle(const String* pKey, const String* pTbl, const Bundle* pBdle, const String*);
class String* LocalizedStringWithDefaultValue(const String* pKey, const String* pTbl, const Bundle* pBdle, const String* pVal, const String*);
};
class Data : public Object
{
public:
void* SetMutableBytes();
uint64_t GetLength();
};
}
}
| 32.075117 | 158 | 0.525907 | MilesLitteral |
479bb457a7688a4e84e3b543344618597ad7dbe3 | 9,461 | cpp | C++ | rviz-groovy-devel/src/rviz/default_plugin/odometry_display.cpp | tuw-cpsg/dynamic_mapping | 12c5c9a9e66e16cb451c457d46a4d6cab5e2213b | [
"CC0-1.0"
] | 9 | 2017-12-17T07:43:15.000Z | 2021-10-10T15:03:39.000Z | rviz-groovy-devel/src/rviz/default_plugin/odometry_display.cpp | tuw-cpsg/dynamic_mapping | 12c5c9a9e66e16cb451c457d46a4d6cab5e2213b | [
"CC0-1.0"
] | null | null | null | rviz-groovy-devel/src/rviz/default_plugin/odometry_display.cpp | tuw-cpsg/dynamic_mapping | 12c5c9a9e66e16cb451c457d46a4d6cab5e2213b | [
"CC0-1.0"
] | 6 | 2016-01-27T03:40:58.000Z | 2021-06-15T08:12:14.000Z | /*
* Copyright (c) 2008, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 <boost/bind.hpp>
#include <tf/transform_listener.h>
#include "rviz/frame_manager.h"
#include "rviz/ogre_helpers/arrow.h"
#include "rviz/properties/color_property.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/int_property.h"
#include "rviz/properties/ros_topic_property.h"
#include "rviz/validate_floats.h"
#include "rviz/display_context.h"
#include "odometry_display.h"
namespace rviz
{
OdometryDisplay::OdometryDisplay()
: Display()
, messages_received_(0)
{
topic_property_ = new RosTopicProperty( "Topic", "",
QString::fromStdString( ros::message_traits::datatype<nav_msgs::Odometry>() ),
"nav_msgs::Odometry topic to subscribe to.",
this, SLOT( updateTopic() ));
color_property_ = new ColorProperty( "Color", QColor( 255, 25, 0 ),
"Color of the arrows.",
this, SLOT( updateColor() ));
position_tolerance_property_ = new FloatProperty( "Position Tolerance", .1,
"Distance, in meters from the last arrow dropped, "
"that will cause a new arrow to drop.",
this );
position_tolerance_property_->setMin( 0 );
angle_tolerance_property_ = new FloatProperty( "Angle Tolerance", .1,
"Angular distance from the last arrow dropped, "
"that will cause a new arrow to drop.",
this );
angle_tolerance_property_->setMin( 0 );
keep_property_ = new IntProperty( "Keep", 100,
"Number of arrows to keep before removing the oldest. 0 means keep all of them.",
this );
keep_property_->setMin( 0 );
length_property_ = new FloatProperty( "Length", 1.0,
"Length of each arrow.",
this, SLOT( updateLength() ));
}
OdometryDisplay::~OdometryDisplay()
{
unsubscribe();
clear();
delete tf_filter_;
}
void OdometryDisplay::onInitialize()
{
tf_filter_ = new tf::MessageFilter<nav_msgs::Odometry>( *context_->getTFClient(), fixed_frame_.toStdString(),
5, update_nh_ );
tf_filter_->connectInput( sub_ );
tf_filter_->registerCallback( boost::bind( &OdometryDisplay::incomingMessage, this, _1 ));
context_->getFrameManager()->registerFilterForTransformStatusCheck( tf_filter_, this );
}
void OdometryDisplay::clear()
{
D_Arrow::iterator it = arrows_.begin();
D_Arrow::iterator end = arrows_.end();
for ( ; it != end; ++it )
{
delete *it;
}
arrows_.clear();
if( last_used_message_ )
{
last_used_message_.reset();
}
tf_filter_->clear();
messages_received_ = 0;
setStatus( StatusProperty::Warn, "Topic", "No messages received" );
}
void OdometryDisplay::updateTopic()
{
unsubscribe();
clear();
subscribe();
context_->queueRender();
}
void OdometryDisplay::updateColor()
{
QColor color = color_property_->getColor();
float red = color.redF();
float green = color.greenF();
float blue = color.blueF();
D_Arrow::iterator it = arrows_.begin();
D_Arrow::iterator end = arrows_.end();
for( ; it != end; ++it )
{
Arrow* arrow = *it;
arrow->setColor( red, green, blue, 1.0f );
}
context_->queueRender();
}
void OdometryDisplay::updateLength()
{
float length = length_property_->getFloat();
D_Arrow::iterator it = arrows_.begin();
D_Arrow::iterator end = arrows_.end();
Ogre::Vector3 scale( length, length, length );
for ( ; it != end; ++it )
{
Arrow* arrow = *it;
arrow->setScale( scale );
}
context_->queueRender();
}
void OdometryDisplay::subscribe()
{
if ( !isEnabled() )
{
return;
}
try
{
sub_.subscribe( update_nh_, topic_property_->getTopicStd(), 5 );
setStatus( StatusProperty::Ok, "Topic", "OK" );
}
catch( ros::Exception& e )
{
setStatus( StatusProperty::Error, "Topic", QString( "Error subscribing: " ) + e.what() );
}
}
void OdometryDisplay::unsubscribe()
{
sub_.unsubscribe();
}
void OdometryDisplay::onEnable()
{
subscribe();
}
void OdometryDisplay::onDisable()
{
unsubscribe();
clear();
}
bool validateFloats(const nav_msgs::Odometry& msg)
{
bool valid = true;
valid = valid && validateFloats( msg.pose.pose );
valid = valid && validateFloats( msg.twist.twist );
return valid;
}
void OdometryDisplay::incomingMessage( const nav_msgs::Odometry::ConstPtr& message )
{
++messages_received_;
if( !validateFloats( *message ))
{
setStatus( StatusProperty::Error, "Topic", "Message contained invalid floating point values (nans or infs)" );
return;
}
setStatus( StatusProperty::Ok, "Topic", QString::number( messages_received_ ) + " messages received" );
if( last_used_message_ )
{
Ogre::Vector3 last_position(last_used_message_->pose.pose.position.x, last_used_message_->pose.pose.position.y, last_used_message_->pose.pose.position.z);
Ogre::Vector3 current_position(message->pose.pose.position.x, message->pose.pose.position.y, message->pose.pose.position.z);
Ogre::Quaternion last_orientation(last_used_message_->pose.pose.orientation.w, last_used_message_->pose.pose.orientation.x, last_used_message_->pose.pose.orientation.y, last_used_message_->pose.pose.orientation.z);
Ogre::Quaternion current_orientation(message->pose.pose.orientation.w, message->pose.pose.orientation.x, message->pose.pose.orientation.y, message->pose.pose.orientation.z);
if( (last_position - current_position).length() < position_tolerance_property_->getFloat() &&
(last_orientation - current_orientation).normalise() < angle_tolerance_property_->getFloat() )
{
return;
}
}
Arrow* arrow = new Arrow( scene_manager_, scene_node_, 0.8f, 0.05f, 0.2f, 0.2f );
transformArrow( message, arrow );
QColor color = color_property_->getColor();
arrow->setColor( color.redF(), color.greenF(), color.blueF(), 1.0f );
float length = length_property_->getFloat();
Ogre::Vector3 scale( length, length, length );
arrow->setScale( scale );
arrows_.push_back( arrow );
last_used_message_ = message;
context_->queueRender();
}
void OdometryDisplay::transformArrow( const nav_msgs::Odometry::ConstPtr& message, Arrow* arrow )
{
Ogre::Vector3 position;
Ogre::Quaternion orientation;
if( !context_->getFrameManager()->transform( message->header, message->pose.pose, position, orientation ))
{
ROS_ERROR( "Error transforming odometry '%s' from frame '%s' to frame '%s'",
qPrintable( getName() ), message->header.frame_id.c_str(), qPrintable( fixed_frame_ ));
}
arrow->setPosition( position );
// Arrow points in -Z direction, so rotate the orientation before display.
// TODO: is it safe to change Arrow to point in +X direction?
arrow->setOrientation( orientation * Ogre::Quaternion( Ogre::Degree( -90 ), Ogre::Vector3::UNIT_Y ));
}
void OdometryDisplay::fixedFrameChanged()
{
tf_filter_->setTargetFrame( fixed_frame_.toStdString() );
clear();
}
void OdometryDisplay::update( float wall_dt, float ros_dt )
{
size_t keep = keep_property_->getInt();
if( keep > 0 )
{
while( arrows_.size() > keep )
{
delete arrows_.front();
arrows_.pop_front();
}
}
}
void OdometryDisplay::reset()
{
Display::reset();
clear();
}
} // namespace rviz
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS( rviz::OdometryDisplay, rviz::Display )
| 32.400685 | 218 | 0.653525 | tuw-cpsg |
47a1a30bd4acc32ed3f845e767fda1a52c1cca1f | 3,748 | cpp | C++ | modules/task_3/kulemin_p_linear_vertical_filtration/main.cpp | Stepakrap/pp_2021_autumn | 716803a14183172337d51712fb28fe8e86891a3d | [
"BSD-3-Clause"
] | 1 | 2021-12-09T17:20:25.000Z | 2021-12-09T17:20:25.000Z | modules/task_3/kulemin_p_linear_vertical_filtration/main.cpp | Stepakrap/pp_2021_autumn | 716803a14183172337d51712fb28fe8e86891a3d | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/kulemin_p_linear_vertical_filtration/main.cpp | Stepakrap/pp_2021_autumn | 716803a14183172337d51712fb28fe8e86891a3d | [
"BSD-3-Clause"
] | 3 | 2022-02-23T14:20:50.000Z | 2022-03-30T09:00:02.000Z | // Copyright 2021 Zaytsev Mikhail
#include <gtest/gtest.h>
#include <vector>
#include "./linear_vectrical_filtration.h"
#include <gtest-mpi-listener.hpp>
TEST(Parallel_Matrix_Multiplacition, mRows_Eq_mColumns_50) {
int currentProcess;
MPI_Comm_rank(MPI_COMM_WORLD, ¤tProcess);
std::vector<float> matrix, img;
int height = 50;
int weight = 50;
getKernell(&matrix);
if (currentProcess == 0) {
getRandomImg(&img, weight, height);
}
std::vector<float> globalMatrix = getParallelOperations(matrix, img,
weight, height);
if (currentProcess == 0) {
std::vector<float> referenceMatrix = getSequentialOperations(matrix,
img, weight, height);
ASSERT_EQ(globalMatrix, referenceMatrix);
}
}
TEST(Parallel_Matrix_Multiplacition, mRows_Eq_mColumns_5) {
int currentProcess;
MPI_Comm_rank(MPI_COMM_WORLD, ¤tProcess);
std::vector<float> matrix, img;
int height = 5;
int weight = 5;
getKernell(&matrix);
if (currentProcess == 0) {
getRandomImg(&img, weight, height);
}
std::vector<float> globalMatrix = getParallelOperations(matrix,
img, weight, height);
if (currentProcess == 0) {
std::vector<float> referenceMatrix = getSequentialOperations(matrix,
img, weight, height);
ASSERT_EQ(globalMatrix, referenceMatrix);
}
}
TEST(Parallel_Matrix_Multiplacition, mRows_Eq_mColumns_211) {
int currentProcess;
MPI_Comm_rank(MPI_COMM_WORLD, ¤tProcess);
std::vector<float> matrix, img;
int height = 211;
int weight = 211;
getKernell(&matrix);
if (currentProcess == 0) {
getRandomImg(&img, weight, height);
}
std::vector<float> globalMatrix = getParallelOperations(matrix,
img, weight, height);
if (currentProcess == 0) {
std::vector<float> referenceMatrix = getSequentialOperations(matrix,
img, weight, height);
ASSERT_EQ(globalMatrix, referenceMatrix);
}
}
TEST(Parallel_Matrix_Multiplacition, mRows_Gr_mColumns_150_100) {
int currentProcess;
MPI_Comm_rank(MPI_COMM_WORLD, ¤tProcess);
std::vector<float> matrix, img;
int height = 150;
int weight = 100;
getKernell(&matrix);
if (currentProcess == 0) {
getRandomImg(&img, weight, height);
}
std::vector<float> globalMatrix = getParallelOperations(matrix,
img, weight, height);
if (currentProcess == 0) {
std::vector<float> referenceMatrix = getSequentialOperations(matrix,
img, weight, height);
ASSERT_EQ(globalMatrix, referenceMatrix);
}
}
TEST(Parallel_Matrix_Multiplacition, mRows_Le_mColumns_100_150) {
int currentProcess;
MPI_Comm_rank(MPI_COMM_WORLD, ¤tProcess);
std::vector<float> matrix, img;
int height = 100;
int weight = 150;
getKernell(&matrix);
if (currentProcess == 0) {
getRandomImg(&img, weight, height);
}
std::vector<float> globalMatrix = getParallelOperations(matrix,
img, weight, height);
if (currentProcess == 0) {
std::vector<float> referenceMatrix = getSequentialOperations(matrix,
img, weight, height);
ASSERT_EQ(globalMatrix, referenceMatrix);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 28.610687 | 78 | 0.68143 | Stepakrap |
47a1e56747c70b5c2eee49c012072302a80a848f | 2,670 | cpp | C++ | synthts_et/lib/fsc/fsdata.cpp | martnoumees/synthts_et | 8845b33514edef3e54ae0b45404615704c418142 | [
"Unlicense"
] | 19 | 2015-10-27T22:21:49.000Z | 2022-02-07T11:54:35.000Z | synthts_vr/lib/fsc/fsdata.cpp | ikiissel/synthts_vr | 33f2686dc9606aa95697ac0cf7e9031668bc34e8 | [
"Unlicense"
] | 8 | 2015-10-28T08:38:08.000Z | 2021-03-25T21:26:59.000Z | synthts_vr/lib/fsc/fsdata.cpp | ikiissel/synthts_vr | 33f2686dc9606aa95697ac0cf7e9031668bc34e8 | [
"Unlicense"
] | 11 | 2016-01-03T11:47:08.000Z | 2021-03-17T18:59:54.000Z | #include "stdfsc.h"
#include "fstype.h"
#include "fsdata.h"
#include "fstrace.h"
#include "fsmemory.h"
#include "fsutil.h"
#define __FSDATAMAXOVERHEAD (50*1024) // 50K
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFSData::CFSData()
{
m_pData=0;
m_ipSize=m_ipBufferSize=0;
}
CFSData::CFSData(const CFSData &Data)
{
m_pData=0;
m_ipSize=m_ipBufferSize=0;
operator =(Data);
}
#if defined (__FSCXX0X)
CFSData::CFSData(CFSData &&Data)
{
m_pData=Data.m_pData;
Data.m_pData=0;
m_ipSize=Data.m_ipSize;
Data.m_ipSize=0;
m_ipBufferSize=Data.m_ipBufferSize;
Data.m_ipBufferSize=0;
}
#endif
CFSData::~CFSData()
{
Cleanup();
}
CFSData &CFSData::operator =(const CFSData &Data)
{
if (m_pData!=Data.m_pData) {
SetSize(Data.GetSize());
memcpy(m_pData, Data.m_pData, Data.GetSize());
}
return *this;
}
#if defined (__FSCXX0X)
CFSData &CFSData::operator =(CFSData &&Data)
{
if (m_pData!=Data.m_pData) {
Cleanup();
m_pData=Data.m_pData;
Data.m_pData=0;
m_ipSize=Data.m_ipSize;
Data.m_ipSize=0;
m_ipBufferSize=Data.m_ipBufferSize;
Data.m_ipBufferSize=0;
}
return *this;
}
#endif
void CFSData::Reserve(INTPTR ipSize) {
ASSERT(ipSize>=0);
if (ipSize>m_ipBufferSize) {
m_ipBufferSize=ipSize;
m_pData=FSReAlloc(m_pData, m_ipBufferSize);
}
}
void CFSData::SetSize(INTPTR ipSize, bool bReserveMore){
ASSERT(ipSize>=0);
m_ipSize=FSMAX(ipSize, 0);
if (m_ipSize>m_ipBufferSize) {
Reserve(bReserveMore ? FSMIN(m_ipSize+__FSDATAMAXOVERHEAD, (INTPTR)(1.2*m_ipSize)+20) : m_ipSize);
}
}
void CFSData::FreeExtra(){
if (m_ipBufferSize>m_ipSize) {
m_ipBufferSize=m_ipSize;
m_pData=FSReAlloc(m_pData, m_ipBufferSize);
}
}
void CFSData::Cleanup()
{
if (m_pData) {
FSFree(m_pData);
}
m_pData=0;
m_ipSize=m_ipBufferSize=0;
}
void CFSData::Append(const void *pData, INTPTR ipSize)
{
ASSERT(ipSize>=0);
ipSize=FSMAX(ipSize, 0);
INTPTR ipOldSize=m_ipSize;
SetSize(m_ipSize+ipSize);
memcpy((BYTE *)m_pData+ipOldSize, pData, ipSize);
}
CFSStream &operator<<(CFSStream &Stream, const CFSData &Data)
{
Stream << (UINTPTR)Data.m_ipSize;
Stream.WriteBuf(Data.m_pData, Data.m_ipSize);
return Stream;
}
CFSStream &operator>>(CFSStream &Stream, CFSData &Data)
{
INTPTR ipSize;
Stream >> (UINTPTR &)ipSize;
if (ipSize<0) {
throw CFSFileException(CFSFileException::INVALIDDATA);
}
Data.SetSize(ipSize, false);
Stream.ReadBuf(Data.m_pData, Data.m_ipSize);
return Stream;
}
| 20.697674 | 101 | 0.646816 | martnoumees |
47a1fe5a5547d1bb9969e28fd314231d21f05b9e | 10,508 | cpp | C++ | demo/cpp/color_match.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 57 | 2015-02-16T06:43:24.000Z | 2022-03-16T06:21:36.000Z | demo/cpp/color_match.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 4 | 2016-03-08T09:51:09.000Z | 2021-03-29T10:18:55.000Z | demo/cpp/color_match.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 27 | 2015-03-28T19:55:34.000Z | 2022-01-09T15:03:15.000Z | #include <opencv2/opencv.hpp>
#include <opencv2/ximgproc.hpp>
using namespace std;
using namespace cv;
void createQuaternionImage(InputArray _img, OutputArray _qimg)
{
int type = _img.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
CV_Assert((depth == CV_8U || depth == CV_32F || depth == CV_64F) && _img.dims() == 2 && cn == 3);
vector<Mat> qplane(4);
vector<Mat> plane;
split(_img, plane);
qplane[0] = Mat::zeros(_img.size(), CV_64FC1);
for (int i = 0; i < cn; i++)
plane[i].convertTo(qplane[i + 1], CV_64F);
merge(qplane, _qimg);
}
void qconj(InputArray _img, OutputArray _qimg)
{
int type = _img.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
CV_Assert((depth == CV_32F || depth == CV_64F) && _img.dims() == 2 && cn == 4);
vector<Mat> qplane(4),plane;
split(_img, plane);
qplane[0] = plane[0].clone();
qplane[1] = -plane[1].clone();
qplane[2] = -plane[2].clone();
qplane[3] = -plane[3].clone();
merge(qplane, _qimg);
}
void qunitary(InputArray _img, OutputArray _qimg)
{
int type = _img.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
CV_Assert((depth == CV_32F || depth == CV_64F) && _img.dims() == 2 && cn == 4);
vector<Mat> qplane(4), plane;
split(_img, plane);
qplane[0] = plane[0].clone();
qplane[1] = -plane[1].clone();
qplane[2] = -plane[2].clone();
qplane[3] = -plane[3].clone();
float *ptr0 = qplane[0].ptr<float>(0, 0), *ptr1 = qplane[1].ptr<float>(0, 0);
float *ptr2 = qplane[2].ptr<float>(0, 0), *ptr3 = qplane[3].ptr<float>(0, 0);
int nb = plane[0].rows*plane[0].cols;
for (int i = 0; i < nb; i++, ptr0++, ptr1++, ptr2++, ptr3++)
{
float d = *ptr0 * *ptr0 + *ptr1 * *ptr1 + *ptr2 * *ptr2 + *ptr3 * *ptr3;
d = 1; // sqrt(d);
*ptr0 *= d;
*ptr1 *= d;
*ptr2 *= d;
*ptr3 *= d;
}
merge(qplane, _qimg);
}
void QDFT(InputArray _img, OutputArray _qimg, int flags,bool sideLeft )
{
// CV_INSTRUMENT_REGION()
int type = _img.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
CV_Assert(depth == CV_64F && _img.dims() == 2 && cn == 4);
float c;
if (sideLeft)
c = 1; // Left qdft
else
c = -1; // right qdft
vector<Mat> q;
Mat img;
img = _img.getMat();
CV_Assert(getOptimalDFTSize(img.rows) == img.rows && getOptimalDFTSize(img.cols) == img.cols);
split(img, q);
Mat c1r;
Mat c1i; // Imaginary part of c1 =x'
Mat c2r; // Real part of c2 =y'
Mat c2i; // Imaginary part of c2=z'
c1r = q[0].clone();
c1i = (q[1] + q[2] + q[3]) / sqrt(3);
c2r = (q[2] - q[3]) / sqrt(2);
c2i = c*(q[3] + q[2] - 2 * q[1]) / sqrt(6);
vector<Mat> vc1 = { c1r,c1i }, vc2 = { c2r,c2i };
Mat c1, c2,C1,C2;
merge(vc1, c1);
merge(vc2, c2);
if (flags& DFT_INVERSE)
{
dft(c1, C1, DFT_COMPLEX_OUTPUT| DFT_INVERSE );
dft(c2, C2, DFT_COMPLEX_OUTPUT| DFT_INVERSE );
}
else
{
dft(c1, C1, DFT_COMPLEX_OUTPUT );
dft(c2, C2, DFT_COMPLEX_OUTPUT );
}
split(C1, vc1);
split(C2, vc2);
vector<Mat> qdft(4);
qdft[0] = vc1[0].clone();
qdft[1] = vc1[1] / sqrt(3) - 2*vc2[1]/sqrt(6);
qdft[2] = vc1[1] / sqrt(3) + vc2[0] / sqrt(2) + vc2[1] / sqrt(6);
qdft[3] = c*(vc1[1] / sqrt(3) - vc2[0] / sqrt(2) + vc2[1] / sqrt(6));
Mat dst0;
merge(qdft, dst0);
dst0.copyTo(_qimg);
}
void qmultiply(InputArray src1, InputArray src2, OutputArray dst)
{
int type = src1.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
CV_Assert(depth == CV_64F && src1.dims() == 2 && cn == 4);
type = src2.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
CV_Assert(depth == CV_64F && src2.dims() == 2 && cn == 4);
vector<Mat> q3(4);
if (src1.rows() == src2.rows() && src1.cols() == src2.cols())
{
vector<Mat> q1, q2;
split(src1, q1);
split(src2, q2);
q3[0] = q1[0].mul(q2[0]) - q1[1].mul(q2[1]) - q1[2].mul(q2[2]) - q1[3].mul(q2[3]);
q3[1] = q1[0].mul(q2[1]) + q1[1].mul(q2[0]) + q1[2].mul(q2[3]) - q1[3].mul(q2[2]);
q3[2] = q1[0].mul(q2[2]) - q1[1].mul(q2[3]) + q1[2].mul(q2[0]) + q1[3].mul(q2[1]);
q3[3] = q1[0].mul(q2[3]) + q1[1].mul(q2[2]) - q1[2].mul(q2[1]) + q1[3].mul(q2[0]);
}
else if (src1.rows() == 1 && src1.cols() == 1)
{
vector<Mat> q2;
Vec4d q1 = src1.getMat().at<Vec4d>(0, 0);
split(src2, q2);
q3[0] = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3];
q3[1] = q1[0] * q2[1] + q1[1] * q2[0] + q1[2] * q2[3] - q1[3] * q2[2];
q3[2] = q1[0] * q2[2] - q1[1] * q2[3] + q1[2] * q2[0] + q1[3] * q2[1];
q3[3] = q1[0] * q2[3] + q1[1] * q2[2] - q1[2] * q2[1] + q1[3] * q2[0];
}
else if (src2.rows() == 1 && src2.cols() == 1)
{
vector<Mat> q1;
split(src1, q1);
Vec4d q2 = src2.getMat().at<Vec4d>(0, 0);
q3[0] = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3];
q3[1] = q1[0] * q2[1] + q1[1] * q2[0] + q1[2] * q2[3] - q1[3] * q2[2];
q3[2] = q1[0] * q2[2] - q1[1] * q2[3] + q1[2] * q2[0] + q1[3] * q2[1];
q3[3] = q1[0] * q2[3] + q1[1] * q2[2] - q1[2] * q2[1] + q1[3] * q2[0];
}
else
CV_Assert(src1.rows() == src2.rows() && src1.cols() == src2.cols());
merge(q3, dst);
}
void colorMatchTemplate(InputArray _image, InputArray _templ, OutputArray _result)
{
Mat image = _image.getMat(),imageF;
Mat colorTemplate = _templ.getMat();
int rr = getOptimalDFTSize(image.rows);
int cc = getOptimalDFTSize(image.cols);
rr = max(rr, cc);
cc = getOptimalDFTSize(colorTemplate.rows);
rr = max(rr, cc);
cc = getOptimalDFTSize(colorTemplate.cols);
rr = max(rr, cc);
Mat logo(rr, rr, CV_64FC3, Scalar::all(0));
Mat img = Mat(rr, rr, CV_64FC3, Scalar::all(0));
Scalar x = mean(colorTemplate);
colorTemplate.convertTo(colorTemplate, CV_64F, 1 / 256.),
subtract(colorTemplate, x / 256., colorTemplate);
colorTemplate.copyTo(logo(Rect(0, 0, colorTemplate.cols, colorTemplate.rows)));
image.convertTo(imageF, CV_64F, 1 / 256.);
subtract(imageF, x / 256., imageF);
imageF.copyTo(img(Rect(0, 0, image.cols, image.rows)));
Mat qimg, qlogo;
Mat qimgFFT, qimgIFFT, qlogoFFT;
// Create quaternion image
createQuaternionImage(img, qimg);
createQuaternionImage(logo, qlogo);
// quaternion fourier transform
QDFT(qimg, qimgFFT, 0, true);
QDFT(qimg, qimgIFFT, DFT_INVERSE, true);
QDFT(qlogo, qlogoFFT, 0, false);
double sqrtnn = sqrt(static_cast<int>(qimgFFT.rows*qimgFFT.cols));
qimgFFT /= sqrtnn;
qimgIFFT *= sqrtnn;
qlogoFFT /= sqrtnn;
Mat mu(1, 1, CV_64FC4, Scalar(0, 1, 1, 1));
Mat qtmp, qlogopara, qlogoortho;
qmultiply(mu, qlogoFFT, qtmp);
qmultiply(qtmp, mu, qtmp);
subtract(qlogoFFT, qtmp, qlogopara);
qlogopara = qlogopara / 2;
subtract(qlogoFFT, qlogopara, qlogoortho);
Mat qcross1, qcross2, cqf, cqfi;
qconj(qimgFFT, cqf);
qconj(qimgIFFT, cqfi);
qmultiply(cqf, qlogopara, qcross1);
qmultiply(cqfi, qlogoortho, qcross2);
Mat pwsp = qcross1 + qcross2;
Mat crossCorr, pwspUnitary;
qunitary(pwsp, pwspUnitary);
QDFT(pwspUnitary, crossCorr, DFT_INVERSE, true);
vector<Mat> p;
split(crossCorr, p);
Mat imgcorr = (p[0].mul(p[0]) + p[1].mul(p[1]) + p[2].mul(p[2]) + p[3].mul(p[3]));
sqrt(imgcorr, _result);
}
void AddSlider(String sliderName, String windowName, int minSlider, int maxSlider, int valDefault, int *valSlider, void(*f)(int, void *), void *r)
{
createTrackbar(sliderName, windowName, valSlider, 1, f, r);
setTrackbarMin(sliderName, windowName, minSlider);
setTrackbarMax(sliderName, windowName, maxSlider);
setTrackbarPos(sliderName, windowName, valDefault);
}
struct SliderData {
Mat img;
int thresh;
};
void UpdateThreshImage(int x, void *r)
{
SliderData *p = (SliderData*)r;
Mat dst;
threshold(p->img, dst, p->thresh, 255, THRESH_BINARY);
imshow("Max Quaternion corr",dst);
}
int main(int argc, char *argv[])
{
#define TESTMATCHING
#ifdef TESTMATCHING
Mat imgLogo = imread("c:/p/opencv/samples/data/opencv-logo.png", IMREAD_COLOR);
Mat fruits = imread("c:/p/opencv/samples/data/lena.jpg", IMREAD_COLOR);
// fruits = fruits * 0;
resize(fruits,fruits, Size(), 0.5, 0.5);
Mat img,colorTemplate;
imgLogo(Rect(0, 0, imgLogo.cols, 580)).copyTo(img);
resize(img, colorTemplate, Size(), 0.05, 0.05);
vector<Mat> colorMask(4);
inRange(colorTemplate, Vec3b(255, 255, 255), Vec3b(255, 255, 255), colorMask[0]);
// colorTemplate.setTo(Scalar(0,0,0), colorMask[0]);
inRange(colorTemplate, Vec3b(255, 0, 0), Vec3b(255, 0, 0), colorMask[0]);
inRange(colorTemplate, Vec3b(0, 255, 0), Vec3b(0,255, 0), colorMask[1]);
inRange(colorTemplate, Vec3b( 0, 0,255), Vec3b( 0, 0,255), colorMask[2]);
colorMask[3] = Mat(colorTemplate.size(), CV_8UC3, Scalar(255));
RNG r;
for (int i = 0; i < 16; i++)
{
Point p(i / 4 * 65+10, (i % 4) * 65+10);
Mat newLogo= colorTemplate.clone();
if (i % 3 != 2)
{
newLogo.setTo(Scalar(r.uniform(0, 256), r.uniform(0, 256), r.uniform(0, 256)), colorMask[i % 4]);
newLogo.setTo(Scalar(r.uniform(0, 256), r.uniform(0, 256), r.uniform(0, 256)), colorMask[(i + 1) % 4]);
}
newLogo.copyTo(fruits(Rect(p.x, p.y, colorTemplate.cols, colorTemplate.rows)));
}
#else
Mat fruits = imread("15214713881857319.png", IMREAD_COLOR);
Mat colorTemplate = imread("15214714019776815.png", IMREAD_COLOR);
Mat img= colorTemplate;
#endif
imshow("Image", fruits);
imshow("opencv_logo", colorTemplate);
if (img.empty())
{
cout << "Cannot load image file\n";
return 0;
}
Mat imgcorr;
SliderData p;
colorMatchTemplate(fruits, colorTemplate, imgcorr);
normalize(imgcorr, imgcorr,1,0,NORM_MINMAX);
imgcorr.convertTo(p.img, CV_8U, 255);
imshow("quaternion correlation", imgcorr);
int level = 200;
AddSlider("Level", "quaternion correlation", 0, 255, p.thresh, &p.thresh, UpdateThreshImage, &p);
int code = 0;
while (code != 27)
{
code = waitKey(50);
}
FileStorage fs("corr.yml", FileStorage::WRITE);
fs<<"Image"<< imgcorr;
fs.release();
waitKey(0);
return 0;
}
| 35.026667 | 146 | 0.575752 | berak |
47a81afe6e0e20ccda4eeeec15d1792aed98e01a | 490 | hh | C++ | libqpdf/qpdf/InsecureRandomDataProvider.hh | m-holger/qpdf | f1a9ba0c622deee0ed05004949b34f0126b12b6a | [
"Apache-2.0"
] | null | null | null | libqpdf/qpdf/InsecureRandomDataProvider.hh | m-holger/qpdf | f1a9ba0c622deee0ed05004949b34f0126b12b6a | [
"Apache-2.0"
] | 3 | 2021-11-19T15:59:21.000Z | 2021-12-10T20:44:33.000Z | libqpdf/qpdf/InsecureRandomDataProvider.hh | m-holger/qpdf | f1a9ba0c622deee0ed05004949b34f0126b12b6a | [
"Apache-2.0"
] | null | null | null | #ifndef INSECURERANDOMDATAPROVIDER_HH
#define INSECURERANDOMDATAPROVIDER_HH
#include <qpdf/RandomDataProvider.hh>
class InsecureRandomDataProvider: public RandomDataProvider
{
public:
InsecureRandomDataProvider();
virtual ~InsecureRandomDataProvider() = default;
virtual void provideRandomData(unsigned char* data, size_t len);
static RandomDataProvider* getInstance();
private:
long random();
bool seeded_random;
};
#endif // INSECURERANDOMDATAPROVIDER_HH
| 23.333333 | 68 | 0.783673 | m-holger |
47a9f49ecfd31535be660f54e9576575e7329bb5 | 1,687 | cpp | C++ | aech/src/ecs/engine.cpp | markomijolovic/aech | 6e2ea36146596dff6f92e451a598aab535b03d3c | [
"BSD-3-Clause"
] | 4 | 2021-05-25T13:58:30.000Z | 2021-05-26T20:13:15.000Z | aech/src/ecs/engine.cpp | markomijolovic/aech | 6e2ea36146596dff6f92e451a598aab535b03d3c | [
"BSD-3-Clause"
] | null | null | null | aech/src/ecs/engine.cpp | markomijolovic/aech | 6e2ea36146596dff6f92e451a598aab535b03d3c | [
"BSD-3-Clause"
] | null | null | null | #include "engine.hpp"
#include "camera.hpp"
#include "directional_light.hpp"
#include "light_probe.hpp"
#include "mesh_filter.hpp"
#include "point_light.hpp"
#include "reflection_probe.hpp"
#include "scene_node.hpp"
#include "shading_tags.hpp"
#include "shadow_caster.hpp"
namespace aech {
engine_t::engine_t() noexcept
{
register_component<transform_t>();
register_component<graphics::scene_node_t>();
register_component<camera_t>();
register_component<graphics::mesh_filter_t>();
register_component<graphics::directional_light_t>();
register_component<graphics::point_light_t>();
register_component<graphics::potential_occluder_t>();
register_component<graphics::opaque_t>();
register_component<graphics::transparent_t>();
register_component<graphics::reflection_probe_t>();
register_component<graphics::light_probe_t>();
}
auto engine_t::create_entity() noexcept -> entity_t
{
return m_entity_manager.create_entity();
}
auto engine_t::destroy_entity(entity_t entity) noexcept -> void
{
m_entity_manager.destroy_entity(entity);
m_component_manager.entity_destroyed(entity);
m_system_manager.entity_destroyed(entity);
}
auto engine_t::set_root_node(entity_t root_node) noexcept -> void
{
m_root_node = root_node;
}
auto engine_t::root_node() const noexcept -> entity_t
{
return m_root_node;
}
auto engine_t::add_event_listener(event_id_t event_id, const std::function<void(events::event_t &)> &listener) noexcept -> void
{
m_event_manager.add_listener(event_id, listener);
}
auto engine_t::send_event(events::event_t &event) noexcept -> void
{
m_event_manager.send_event(event);
}
} // namespace aech
| 27.209677 | 127 | 0.760522 | markomijolovic |
47b15c2740bd5087d10242354a76aab58a878d86 | 566 | cpp | C++ | riscv/llvm/3.5/cfe-3.5.0.src/test/Modules/macro-reexport/macro-reexport.cpp | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | null | null | null | riscv/llvm/3.5/cfe-3.5.0.src/test/Modules/macro-reexport/macro-reexport.cpp | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | null | null | null | riscv/llvm/3.5/cfe-3.5.0.src/test/Modules/macro-reexport/macro-reexport.cpp | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 1 | 2021-03-24T06:40:32.000Z | 2021-03-24T06:40:32.000Z | // RUN: rm -rf %t
// RUN: %clang_cc1 -fsyntax-only -DD2 -I. %s -fmodules-cache-path=%t -verify
// RUN: %clang_cc1 -fsyntax-only -DD2 -I. -fmodules %s -fmodules-cache-path=%t -verify
// RUN: %clang_cc1 -fsyntax-only -DC1 -I. %s -fmodules-cache-path=%t -verify
// RUN: %clang_cc1 -fsyntax-only -DC1 -I. -fmodules %s -fmodules-cache-path=%t -verify
#ifdef D2
#include "d2.h"
void f() { return assert(true); } // expected-error {{undeclared identifier 'b'}}
#else
#include "c1.h"
void f() { return assert(true); } // expected-error {{undeclared identifier 'c'}}
#endif
| 40.428571 | 86 | 0.667845 | tangyibin |
47b3777228507d8e607d053d1b53f147fad2659b | 2,420 | cpp | C++ | src/KRAverager.cpp | AFriemann/LowCarb | 073e036a5fd6787943c4cbd76ab388dbd830e7d3 | [
"MIT"
] | null | null | null | src/KRAverager.cpp | AFriemann/LowCarb | 073e036a5fd6787943c4cbd76ab388dbd830e7d3 | [
"MIT"
] | 1 | 2018-12-15T13:57:26.000Z | 2018-12-15T13:57:26.000Z | src/KRAverager.cpp | AFriemann/LowCarb | 073e036a5fd6787943c4cbd76ab388dbd830e7d3 | [
"MIT"
] | null | null | null | /**
* @file KRAverager.cpp
* @author see AUTHORS
* @brief KRAverager definitions file.
*/
#include "KRAverager.hpp"
KRAverager::KRAverager() {}
KRAverager::KRAverager(int threshold){
this->threshold = threshold;
this->use_threshold = true;
}
void KRAverager::add_force_constant_tuple(const double force_constant, const double range){
if (!(this->use_threshold) || range > this->threshold){
this->k_sum += force_constant;
this->r_sum += range;
this->error_sum += force_constant * force_constant;
this->count += 1;
}
}
void KRAverager::add_force_constant_vector(const Eigen::VectorXd &force_constants, const Eigen::VectorXd &ranges) {
for (int i = 0; i < force_constants.rows(); ++i) {
add_force_constant_tuple(force_constants(i), ranges(i));
}
}
double KRAverager::get_average_range() const {
if (this->count > 0){
return this->r_sum / this->count;
} else {
return 0;
}
}
double KRAverager::get_average_force_constant() const {
if (this->count > 0) {
return this->k_sum / this->count;
} else {
return 0;
}
}
double KRAverager::get_error_1() const {
return sqrt(get_error_2());
}
double KRAverager::get_error_2() const {
if (this->count > 0) {
return (
(this->error_sum / this->count)
- get_average_force_constant() * get_average_force_constant()
) / (this->count);
} else {
return 0;
}
}
void KRAveragerCis::add_force_constant_tuple(double k, double r) {
if (r > this->threshold) {
this->count += 1;
this->k_sum += k;
this->r_sum += r;
this->error_sum += k * k;
} else {
this->cis_count += 1;
this->k_cis_sum += k;
this->r_cis_sum += r;
}
}
void KRAveragerCis::add_force_constant_vector(const Eigen::VectorXd & ks, const Eigen::VectorXd & rs) {
for (int i = 0; i < ks.rows(); ++i) {
add_force_constant_tuple(ks(i), rs(i));
}
}
double KRAveragerCis::get_range_cis() const {
if (this->cis_count > 0) {
return this->r_cis_sum / this->cis_count;
} else {
return 0;
}
}
double KRAveragerCis::get_force_constant_cis() const {
if (this->cis_count > 0) {
return this->k_cis_sum / this->cis_count;
} else {
return 0;
}
}
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| 24.444444 | 115 | 0.604959 | AFriemann |
47b4e05940ac5f24462ab393bb1a8a52609d693f | 6,663 | cc | C++ | board.cc | juliusikkala/Pack-Against-The-Machine | 74fdf36ea7e9f0369e5b4a101f5e5aa43817c8ff | [
"MIT"
] | null | null | null | board.cc | juliusikkala/Pack-Against-The-Machine | 74fdf36ea7e9f0369e5b4a101f5e5aa43817c8ff | [
"MIT"
] | null | null | null | board.cc | juliusikkala/Pack-Against-The-Machine | 74fdf36ea7e9f0369e5b4a101f5e5aa43817c8ff | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2019 Julius Ikkala
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 "board.hh"
#include <cmath>
#include <algorithm>
#include <stdexcept>
#include "rect_packer.hh"
namespace
{
int range_overlap(int x1, int w1, int x2, int w2)
{
return std::max(std::min(x1 + w1, x2 + w2) - std::max(x1, x2), 0);
}
int rect_overlap(const board::rect& a, const board::rect& b)
{
return
range_overlap(a.x, a.w, b.x, b.w) * range_overlap(a.y, a.h, b.y, b.h);
}
unsigned hsv_to_rgb(float h, float s, float v)
{
auto f = [h,s,v](int n){
float k = fmod(n+h/60.0, 6.0);
return v - v*s*std::clamp(std::min(k, 4-k), 0.0f, 1.0f);
};
unsigned r = std::clamp(int(f(5)*255.0f), 0, 255);
unsigned g = std::clamp(int(f(3)*255.0f), 0, 255);
unsigned b = std::clamp(int(f(1)*255.0f), 0, 255);
return (r<<24)|(g<<16)|(b<<8)|0xFF;
}
float circle_sequence(unsigned n) {
unsigned denom = n + 1;
denom--;
denom |= denom >> 1;
denom |= denom >> 2;
denom |= denom >> 4;
denom |= denom >> 8;
denom |= denom >> 16;
denom++;
unsigned num = 1 + (n - denom/2)*2;
return num/(float)denom;
}
unsigned generate_color(int id, bool bounds)
{
return hsv_to_rgb(
360*circle_sequence(id),
0.5,
bounds ? 0.7 : 1.0
);
}
}
board::board(int w, int h)
: width(w), height(h), covered(0)
{
}
void board::resize(int w, int h)
{
width = w;
height = h;
}
void board::reset()
{
rects.clear();
covered = 0;
}
void board::place(const rect& r)
{
rects.push_back(r);
covered += r.w * r.h;
}
bool board::can_place(const rect& r) const
{
// Check bounds
if(r.x < 0 || r.y < 0 || r.x + r.w > width || r.y + r.h > height)
return false;
// Check other rects
for(const rect& o: rects)
{
if(rect_overlap(o, r)) return false;
}
return true;
}
double board::coverage() const
{
return covered/(double)(width * height);
}
void board::draw(
sf::RenderWindow& win,
int x, int y,
int w, int h,
bool draw_grid,
sf::Font* number_font
) const
{
// Draw bounds
sf::Color bounds_color(0x3C3C3CFF);
sf::Color background_color(0x303030FF);
sf::Vertex bounds[] = {
sf::Vertex(sf::Vector2f(x, y)),
sf::Vertex(sf::Vector2f(x+w, y)),
sf::Vertex(sf::Vector2f(x+w, y+h)),
sf::Vertex(sf::Vector2f(x, y+h)),
sf::Vertex(sf::Vector2f(x, y))
};
for(sf::Vertex& v: bounds) v.color = background_color;
win.draw(bounds, 4, sf::Quads);
for(sf::Vertex& v: bounds) v.color = bounds_color;
win.draw(bounds, 5, sf::LineStrip);
// Draw grid if asked to
if(draw_grid)
{
for(int gy = 1; gy < height; ++gy)
{
int sy = y + gy * h / height;
sf::Vertex grid_line[] = {
sf::Vertex(sf::Vector2f(x, sy), bounds_color),
sf::Vertex(sf::Vector2f(x + w, sy), bounds_color),
};
win.draw(grid_line, 2, sf::Lines);
}
for(int gx = 1; gx < width; ++gx)
{
int sx = x + gx * w / width;
sf::Vertex grid_line[] = {
sf::Vertex(sf::Vector2f(sx, y), bounds_color),
sf::Vertex(sf::Vector2f(sx, y + h), bounds_color),
};
win.draw(grid_line, 2, sf::Lines);
}
}
// Draw rects
float outline_thickness = w/(float)width*0.2f;
if(outline_thickness < 3.0f) outline_thickness = 0.0f;
float font_size = std::max(w/(float)width*0.5f, 8.0f);
for(const rect& r: rects)
{
sf::Color color(generate_color(r.id, false));
sf::Color outline_color(generate_color(r.id, true));
int fy = height-r.y;
int sx1 = x + r.x * w / width;
int sy1 = y + fy * h / height+(draw_grid ? 1 : 0);
int sx2 = x + (r.x+r.w) * w / width-(draw_grid ? 1 : 0);
int sy2 = y + (fy-r.h) * h / height;
int sw = sx2-sx1;
int sh = sy2-sy1;
sf::RectangleShape rs(sf::Vector2f(sw, sh));
rs.setPosition(sx1, sy1);
rs.setOutlineThickness(-outline_thickness);
rs.setFillColor(color);
rs.setOutlineColor(outline_color);
win.draw(rs);
if(number_font)
{
sf::Text number(std::to_string(r.id), *number_font, font_size);
number.setOutlineColor(sf::Color::Black);
number.setFillColor(sf::Color::White);
number.setOutlineThickness(font_size*0.1f);
number.setPosition(sf::Vector2f(sx1+sx2, sy1+sy2)*0.5f);
sf::FloatRect lb = number.getLocalBounds();
number.setOrigin(lb.left + lb.width*0.5f, lb.top + lb.height*0.5f);
win.draw(number);
}
}
}
/*
void board::draw_debug_edges(
sf::RenderWindow& win,
rect_packer& pack,
int x, int y,
int w, int h
) const
{
// Draw bounds
sf::Color ur_color(0x00FF00FF);
sf::Color bu_color(0xFF0000FF);
for(auto& edge: pack.edges)
{
sf::Color col = edge.up_right_inside ? ur_color : bu_color;
int x1 = edge.x;
int y1 = edge.y;
int x2 = edge.vertical ? edge.x : edge.x + edge.length;
int y2 = edge.vertical ? edge.y + edge.length : edge.y;
y1 = height - y1;
y2 = height - y2;
x1 = x + x1 * w / width;
y1 = y + y1 * h / height;
x2 = x + x2 * w / width;
y2 = y + y2 * h / height;
sf::Vertex grid_line[] = {
sf::Vertex(sf::Vector2f(x1, y1), col),
sf::Vertex(sf::Vector2f(x2, y2), col),
};
win.draw(grid_line, 2, sf::Lines);
}
}
*/
| 27.419753 | 79 | 0.579169 | juliusikkala |
47b518b1abc4f1f490c66a367ee50db7426244af | 2,783 | cpp | C++ | Immortal/Platform/D3D12/GuiLayer.cpp | QSXW/Immortal | 32adcc8609b318752dd97f1c14dc7368b47d47d1 | [
"Apache-2.0"
] | 6 | 2021-09-15T08:56:28.000Z | 2022-03-29T15:55:02.000Z | Immortal/Platform/D3D12/GuiLayer.cpp | DaShi-Git/Immortal | e3345b4ff2a2b9d215c682db2b4530e24cc3b203 | [
"Apache-2.0"
] | null | null | null | Immortal/Platform/D3D12/GuiLayer.cpp | DaShi-Git/Immortal | e3345b4ff2a2b9d215c682db2b4530e24cc3b203 | [
"Apache-2.0"
] | 4 | 2021-12-05T17:28:57.000Z | 2022-03-29T15:55:05.000Z | #include "impch.h"
#include "GuiLayer.h"
#ifndef _UNICODE
#define _UNICODE
#endif
#include <backends/imgui_impl_win32.h>
#include <backends/imgui_impl_dx12.cpp>
#include <backends/imgui_impl_glfw.h>
#include <GLFW/glfw3.h>
#include "Render/Render.h"
#include "Barrier.h"
#include "Event/ApplicationEvent.h"
namespace Immortal
{
namespace D3D12
{
GuiLayer::GuiLayer(SuperRenderContext *superContext) :
context{ dcast<RenderContext*>(superContext)}
{
swapchain = context->GetAddress<Swapchain>();
commandList = context->GetAddress<CommandList>();
queue = context->GetAddress<Queue>();
}
void GuiLayer::OnAttach()
{
Super::OnAttach();
auto &io = ImGui::GetIO();
Vector2 extent = context->Extent();
io.DisplaySize = ImVec2{ extent.x, extent.y };
auto window = context->GetAddress<Window>();
ImGui_ImplWin32_Init(rcast<HWND>(window->Primitive()));
srvDescriptorHeap = context->ShaderResourceViewDescritorHeap();
Descriptor descriptor = context->AllocateShaderVisibleDescriptor();
ImGui_ImplDX12_Init(
*context->GetAddress<Device>(),
context->FrameSize(),
context->Get<DXGI_FORMAT>(),
*srvDescriptorHeap,
descriptor.cpu,
descriptor.gpu
);
}
void GuiLayer::Begin()
{
ImGui_ImplDX12_NewFrame();
ImGui_ImplWin32_NewFrame();
Super::Begin();
}
void GuiLayer::OnEvent(Event &e)
{
if (e.GetType() == Event::Type::WindowResize)
{
auto resize = dcast<WindowResizeEvent *>(&e);
ImGuiIO &io = ImGui::GetIO();
io.DisplaySize = ImVec2{ (float)resize->Width(), (float)resize->Height() };
}
Super::OnEvent(e);
}
void GuiLayer::OnGuiRender()
{
Super::OnGuiRender();
}
void GuiLayer::End()
{
Super::End();
UINT backBufferIdx = Render::CurrentPresentedFrameIndex();
Barrier<BarrierType::Transition> barrier{
context->RenderTarget(backBufferIdx),
D3D12_RESOURCE_STATE_PRESENT,
D3D12_RESOURCE_STATE_RENDER_TARGET
};
commandList->ResourceBarrier(&barrier);
CPUDescriptor rtvDescritor = std::move(context->RenderTargetDescriptor(backBufferIdx));
commandList->ClearRenderTargetView(rtvDescritor, rcast<float *>(&clearColor));
commandList->OMSetRenderTargets(&rtvDescritor, 1, false, nullptr);
commandList->SetDescriptorHeaps(srvDescriptorHeap->AddressOf(), 1);
ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), commandList->Handle());
barrier.Swap();
commandList->ResourceBarrier(&barrier);
auto &io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault(nullptr, rcast<void*>(commandList->Handle()));
}
}
}
}
| 25.3 | 91 | 0.683794 | QSXW |
47b55a245279ee6706aab62df9d1ad31bdf4374b | 1,626 | cpp | C++ | cpp/example/interpolate.cpp | mustafabar/RedSeaInterpolation | 5d40cbc6e54df7a867445e8fadd11f9f1cce8556 | [
"MIT"
] | null | null | null | cpp/example/interpolate.cpp | mustafabar/RedSeaInterpolation | 5d40cbc6e54df7a867445e8fadd11f9f1cce8556 | [
"MIT"
] | null | null | null | cpp/example/interpolate.cpp | mustafabar/RedSeaInterpolation | 5d40cbc6e54df7a867445e8fadd11f9f1cce8556 | [
"MIT"
] | null | null | null | #include "referencefunctions.h"
#include "interpolation.h"
#include <cmath>
#include <iostream>
#include <random>
void print_gradient(const Eigen::Vector3d &grad)
{
for (int i = 0; i < 3; i++) {
std::cout << grad(i) << ' ';
}
std::cout << std::endl;
}
void print_hessian(const Eigen::Matrix3d &hess)
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << hess(i, j) << ' ';
}
std::cout << std::endl;
}
}
RescaledFunction<Polynomial>
computeInterpolationPolynomial(const ReferenceFunction &fun,
const std::array<Point, 2> &corners)
{
InterpolationParameter param;
int c = 0;
for (int k = 0; k < 2; k++) {
for (int j = 0; j < 2; j++) {
for (int i = 0; i < 2; i++) {
Point x(corners[i][0], corners[j][1], corners[k][2]);
param.f[c] = fun(x);
param.dfdx[c] = fun.dx(x);
param.dfdy[c] = fun.dy(x);
param.dfdz[c] = fun.dz(x);
param.d2fdxdy[c] = fun.dxdy(x);
param.d2fdxdz[c] = fun.dxdz(x);
param.d2fdydz[c] = fun.dydz(x);
param.d3fdxdydz[c] = fun.dxdydz(x);
c += 1;
}
}
}
return tricubic_interpolate(param, corners[0], corners[1]);
}
int main()
{
std::array<Point, 2> corners{Point({2, 2, 2}), Point({-1, -1, -1})};
std::array<long, 3> orderArray = {3, 3, 3};
Polynomial fun(orderArray);
auto poly = computeInterpolationPolynomial(fun, corners);
Point x(0.5, 0.6, 0.7);
std::cout << fun(x) << std::endl;
std::cout << poly(x) << std::endl;
print_gradient(fun.grad(x));
print_gradient(poly.grad(x));
return 0;
}
| 23.911765 | 70 | 0.550431 | mustafabar |
47b9faa2f4d833ca5051111bf2f5b494edbebde7 | 17,617 | cpp | C++ | app/source/core/albumwrapper.cpp | iUltimateLP/NXGallery | 0b9085c789478e28b67dcce0f4902f11e135522d | [
"MIT"
] | 38 | 2020-05-10T14:03:25.000Z | 2022-02-17T09:11:21.000Z | app/source/core/albumwrapper.cpp | iUltimateLP/NXGallery | 0b9085c789478e28b67dcce0f4902f11e135522d | [
"MIT"
] | 14 | 2020-05-15T18:47:19.000Z | 2022-03-27T12:06:37.000Z | app/source/core/albumwrapper.cpp | iUltimateLP/NXGallery | 0b9085c789478e28b67dcce0f4902f11e135522d | [
"MIT"
] | null | null | null | /*
NXGallery for Nintendo Switch
Made with love by Jonathan Verbeek (jverbeek.de)
MIT License
Copyright (c) 2020-2021 Jonathan Verbeek
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 "albumwrapper.hpp"
#include "json.hpp"
#include <sys/stat.h>
#include <errno.h>
#include <inttypes.h>
#include <dirent.h>
#include <filesystem>
#include <regex>
using namespace nxgallery::core;
using json = nlohmann::json;
// Needed for compiler
CAlbumWrapper* CAlbumWrapper::singleton = NULL;
// Overwritten == operator to compare CapsAlbumEntry's
inline bool operator==(CapsAlbumEntry lhs, const CapsAlbumEntry rhs)
{
// Just compare by the datetime
return lhs.file_id.datetime.day == rhs.file_id.datetime.day
&& lhs.file_id.datetime.month == rhs.file_id.datetime.month
&& lhs.file_id.datetime.year == rhs.file_id.datetime.year
&& lhs.file_id.datetime.hour == rhs.file_id.datetime.hour
&& lhs.file_id.datetime.minute == rhs.file_id.datetime.minute
&& lhs.file_id.datetime.second == rhs.file_id.datetime.second
&& lhs.file_id.datetime.id == rhs.file_id.datetime.id;
}
CVideoStreamReader::CVideoStreamReader(const CapsAlbumEntry& inAlbumEntry)
: albumEntry(inAlbumEntry)
{
// Open video stream
if (R_FAILED(capsaOpenAlbumMovieStream(&streamHandle, &albumEntry.file_id)))
{
printf("Failed to open video stream!\n");
return;
}
// Initialize the buffer
workBuffer = (unsigned char*)calloc(workBufferSize, sizeof(unsigned char));
// Get the size the stream will be
capsaGetAlbumMovieStreamSize(streamHandle, &streamSize);
}
CVideoStreamReader::~CVideoStreamReader()
{
// Free the read buffer
free(workBuffer);
// Close the stream
capsaCloseAlbumMovieStream(streamHandle);
}
u64 CVideoStreamReader::GetStreamSize()
{
// If the stream size is bigger than INT_MAX, it's probably invalid and we'll return 0
if (streamSize > 0x80000000) return 0;
return streamSize;
}
u64 CVideoStreamReader::Read(char* outBuffer, u64 numBytes)
{
// Calculate a few statistics
u64 remaining = streamSize - bytesRead;
u64 bufferIndex = bytesRead / workBufferSize;
u64 currentOffset = bytesRead % workBufferSize;
u64 readSize = std::min(std::min(numBytes, workBufferSize - currentOffset), remaining);
// Could debug the video stream read progress here
//float percentage = ((float)bytesRead / (float)streamSize) * 100;
//printf("Progress: %f\n", percentage);
// If no data is remaining, exit
if (remaining <= 0) return 0;
// Read the next buffer
Result readResult = 0;
if (bufferIndex != lastBufferIndex)
{
u64 actualSize = 0;
readResult = capsaReadMovieDataFromAlbumMovieReadStream(streamHandle, bufferIndex * workBufferSize, workBuffer, workBufferSize, &actualSize);
lastBufferIndex = bufferIndex;
}
// Copy from the work buffer to the the output buffer
unsigned char* startOutBuffer = workBuffer + currentOffset;
memcpy(outBuffer, startOutBuffer, readSize);
// Keep track of progress
bytesRead += readSize;
// If it worked, return the number of bytes we just read, otherwise return 0
if (R_SUCCEEDED(readResult))
return readSize;
else
{
printf("Error reading movie stream!");
return 0;
}
}
CAlbumWrapper* CAlbumWrapper::Get()
{
// If no singleton is existing, create a new instance
if (!singleton)
{
singleton = new CAlbumWrapper();
}
// Return the instance
return singleton;
}
void CAlbumWrapper::Init()
{
// SD card storage will already be mounted thanks to romfsInitialize()
// Mount the USER partition of the NAND storage by first opening the BIS USER parition
Result r = fsOpenBisFileSystem(&nandFileSystem, FsBisPartitionId_User, "");
if (R_FAILED(r))
{
printf("Error opening BIS USER partition: %d\n", R_DESCRIPTION(r));
return;
}
// Now mount the opened partition to "nand:/"
int rc = fsdevMountDevice("nand", nandFileSystem);
if (rc < 0)
{
printf("Error mounting NAND storage!\n");
}
// Cache the gallery content
CacheGalleryContent();
}
void CAlbumWrapper::Shutdown()
{
// Unmount the NAND storage
int r = fsdevUnmountDevice("nand");
if (r < 0)
{
printf("Error unmounting NAND storage!\n");
}
}
std::string CAlbumWrapper::GetGalleryContent(int page)
{
// Will hold the stringified JSON data
std::string outJSON;
// Holds the stat object we pass along
json statObject;
// Take the time we need so we can display a cool stat
auto startTime = std::chrono::steady_clock::now();
/*
A "gallery content" object should look like this:
{
"path": "/2020/05/04/2020050410190700-02CB906EA538A35643C1E1484C4B947D.jpg",
"takenAt": "1589444763",
"game": "0100000000010000" OR "Super Mario Odyssey",
"storedAt": "nand" / "sd",
"type": "screenshot" / "movie"
}
*/
// New json object which will hold the total response
json finalObject;
// Fill in some data for the frontend
// Calculate the max amount of pages we will have
finalObject["pages"] = (int)ceil((double)cachedAlbumContent.size() / (double)CONTENT_PER_PAGE);
// Get the console's color theme so the frontend can fit
ColorSetId colorTheme;
Result r = setsysGetColorSetId(&colorTheme);
if (R_SUCCEEDED(r))
{
finalObject["theme"] = colorTheme == ColorSetId_Dark ? "dark" : "light";
}
// Will hold the album contents
json jsonArray = json::array();
// Calculate the page range
int pageMin = (page - 1) * CONTENT_PER_PAGE;
int pageMax = page * CONTENT_PER_PAGE;
// Make sure to stay in bounds
if (pageMax >= cachedAlbumContent.size())
pageMax = cachedAlbumContent.size();
// Iterate over the current range for the page
for (int i = pageMin; i < pageMax; i++)
{
// Get the entry off the album content cache
CapsAlbumEntry albumEntry = cachedAlbumContent[i];
// Figure out if this album entry is stored on the NAND of SD by looking at the
// vector this element is in
bool isStoredInNand = albumEntry.file_id.storage != CapsAlbumStorage_Sd;
// The JSON object for this entry of the album
json jsonObj;
jsonObj["id"] = i;
jsonObj["storedAt"] = isStoredInNand ? "nand" : "sd";
// Retrieve the title's name
jsonObj["game"] = GetTitleName(albumEntry.file_id.application_id);
// Retrieve the file size of the file
u64 fileSize;
Result getFileSizeResult = capsaGetAlbumFileSize(&albumEntry.file_id, &fileSize);
if (R_SUCCEEDED(getFileSizeResult))
{
jsonObj["fileSize"] = fileSize;
}
// Create a UNIX-timestamp from the datetime we get from capsa
struct tm createdAt;
createdAt.tm_year = albumEntry.file_id.datetime.year - 1900;
createdAt.tm_mon = albumEntry.file_id.datetime.month - 1;
createdAt.tm_mday = albumEntry.file_id.datetime.day;
createdAt.tm_hour = albumEntry.file_id.datetime.hour;
createdAt.tm_min = albumEntry.file_id.datetime.minute;
createdAt.tm_sec = albumEntry.file_id.datetime.second;
time_t timestamp = mktime(&createdAt);
jsonObj["takenAt"] = timestamp;
// Determine the type by looking at the file extension
if (albumEntry.file_id.content == CapsAlbumFileContents_Movie || albumEntry.file_id.content == CapsAlbumFileContents_ExtraMovie)
{
jsonObj["type"] = "video";
}
else
{
jsonObj["type"] = "screenshot";
}
// Add the filename for downloading
jsonObj["fileName"] = nxgallery::core::CAlbumWrapper::Get()->GetAlbumEntryFilename(i);
// Push this json object to the array
jsonArray.push_back(jsonObj);
}
finalObject["gallery"] = jsonArray;
// Stop the time!
auto endTime = std::chrono::steady_clock::now();
double indexTime = std::chrono::duration_cast<std::chrono::duration<double>>(endTime - startTime).count();
// Attach the stats
statObject["indexTime"] = indexTime;
statObject["numScreenshots"] = screenshotCount;
statObject["numVideos"] = videoCount;
finalObject["stats"] = statObject;
// Stringify the JSON array
outJSON = finalObject.dump();
return outJSON;
}
std::string CAlbumWrapper::GetTitleName(u64 titleId)
{
// Retrieve the control.nacp data for the game where the current album entry was taken
NsApplicationControlData nacpData;
u64 nacpDataSize;
Result getNACPResult = nsGetApplicationControlData(NsApplicationControlSource_Storage, titleId, &nacpData, sizeof(nacpData), &nacpDataSize);
if (R_SUCCEEDED(getNACPResult))
{
// Retrieve the language string for the Switch'es desired language
NacpLanguageEntry* nacpLangEntry;
Result getLangEntryResult = nsGetApplicationDesiredLanguage(&nacpData.nacp, &nacpLangEntry);
// If it worked, we can grab the nacpLangEntry->name which will hold the name of the title
if (R_SUCCEEDED(getLangEntryResult))
{
return nacpLangEntry->name;
}
}
// If the above didn't work, it's probably not a game where this album entry was created
// A list of all system applets mapped to their title ID
// https://switchbrew.org/wiki/Title_list#System_Applets
std::map<u64, const char*> systemTitles;
systemTitles[0x0100000000001000] = "Home Menu"; // qlaunch
systemTitles[0x0100000000001001] = "Auth"; // auth
systemTitles[0x0100000000001002] = "Cabinet"; // cabinet
systemTitles[0x0100000000001003] = "Controller"; // controller
systemTitles[0x0100000000001004] = "DataErase"; // dataErase
systemTitles[0x0100000000001005] = "Error"; // error
systemTitles[0x0100000000001006] = "Net Connect"; // netConnect
systemTitles[0x0100000000001007] = "Player Select"; // playerSelect
systemTitles[0x0100000000001008] = "Keyboard"; // swkbd
systemTitles[0x0100000000001009] = "Mii Editor"; // miiEdit
systemTitles[0x010000000000100A] = "Web Browser"; // web
systemTitles[0x010000000000100B] = "eShop"; // shop
systemTitles[0x010000000000100C] = "Overlay"; // overlayDisp
systemTitles[0x010000000000100D] = "Album"; // photoViewer
systemTitles[0x010000000000100F] = "Offline Web Browser"; // offlineWeb
systemTitles[0x0100000000001010] = "Share"; // loginShare
systemTitles[0x0100000000001011] = "WiFi Web Auth"; // wifiWebAuth
systemTitles[0x0100000000001012] = "Starter"; // starter
systemTitles[0x0100000000001013] = "My Page"; // myPage
// If it's one of the above, lookup the name from the map, otherwise it's Unknown
if (systemTitles.count(titleId))
{
return systemTitles[titleId];
}
else
{
return "Unknown";
}
}
CapsAlbumFileContents CAlbumWrapper::GetAlbumEntryType(int id)
{
return (CapsAlbumFileContents)cachedAlbumContent[id].file_id.content;
}
std::string CAlbumWrapper::GetAlbumEntryFilename(int id)
{
// Get the entry from cache
CapsAlbumEntry albumEntry = cachedAlbumContent[id];
// Get the file and check if it's a video
CapsAlbumFileContents fileType = GetAlbumEntryType(id);
bool isVideo = (fileType == CapsAlbumFileContents_Movie || fileType == CapsAlbumFileContents_ExtraMovie);
std::string extension = isVideo ? ".mp4" : ".jpg";
// Get the title name
std::string titleName = GetTitleName(albumEntry.file_id.application_id);
// Do some regex to replace whitespaces
titleName = std::regex_replace(titleName, std::regex("\\s+"), "_");
// Get the date and form a string
char dateStr[32];
sprintf(dateStr, "%04u%02u%02u_%02u%02u%02u_%02u",
albumEntry.file_id.datetime.year,
albumEntry.file_id.datetime.month,
albumEntry.file_id.datetime.day,
albumEntry.file_id.datetime.hour,
albumEntry.file_id.datetime.minute,
albumEntry.file_id.datetime.second,
albumEntry.file_id.datetime.id);
std::string finalName = titleName + "_" + dateStr + extension;
return finalName;
}
bool CAlbumWrapper::GetFileThumbnail(int id, void* outBuffer, u64 bufferSize, u64* outActualImageSize)
{
// Make sure that ID exists
if (id < 0 || id > cachedAlbumContent.size())
return false;
// Get the content with that ID
CapsAlbumEntry entry = cachedAlbumContent[id];
// Load the thumbnail
Result result = capsaLoadAlbumFileThumbnail(&entry.file_id, outActualImageSize, outBuffer, bufferSize);
if (R_SUCCEEDED(result))
{
return true;
}
else
{
printf("Failed to get thumbnail for file %d: %d-%d\n", id, R_MODULE(result), R_DESCRIPTION(result));
return false;
}
}
bool CAlbumWrapper::GetFileContent(int id, void* outBuffer, u64 bufferSize, u64* outActualFileSize)
{
// Make sure that ID exists
if (id < 0 || id > cachedAlbumContent.size())
return false;
// Get the content with that ID
CapsAlbumEntry entry = cachedAlbumContent[id];
// If it's a screenshot, we can use capsaLoadAlbumFile to retrieve it
if (entry.file_id.content == CapsAlbumFileContents_ScreenShot || entry.file_id.content == CapsAlbumFileContents_ExtraScreenShot)
{
// Load the file content
Result result = capsaLoadAlbumFile(&entry.file_id, outActualFileSize, outBuffer, bufferSize);
if (R_SUCCEEDED(result))
{
return true;
}
else
{
printf("Failed to get file content for file %d: %d-%d\n", id, R_MODULE(result), R_DESCRIPTION(result));
return false;
}
}
else
{
// It's a video, use our movie stream reader
CVideoStreamReader* videoStreamReader = new CVideoStreamReader(entry);
// Get the stream size. Using that we also know how much bytes we need to read in total
*outActualFileSize = videoStreamReader->GetStreamSize();
u64 readLeft = videoStreamReader->GetStreamSize();
// Read until no bytes are left to read
size_t bytesRead = 0;
while (readLeft > 0)
{
// Offset the buffer's pointer accordingly
char* ptr = ((char*)outBuffer) + bytesRead;
u64 readResult = videoStreamReader->Read(ptr, videoStreamReader->GetStreamSize());
bytesRead += readResult;
readLeft -= readResult;
}
// Finished, delete the stream reader
delete videoStreamReader;
// If no bytes are left to read, everything worked fine
return readLeft <= 0;
}
}
void CAlbumWrapper::CacheGalleryContent()
{
// Cache NAND album
CacheAlbum(CapsAlbumStorage_Nand, cachedAlbumContent);
// Cache SD album
CacheAlbum(CapsAlbumStorage_Sd, cachedAlbumContent);
// Reverse the album entries so newest are first
std::reverse(cachedAlbumContent.begin(), cachedAlbumContent.end());
}
void CAlbumWrapper::CacheAlbum(CapsAlbumStorage location, std::vector<CapsAlbumEntry>& outCache)
{
// This uses capsa (Capture Service), which is the libnx service to data from the Switch album
// Get the total amount of files in the album
u64 totalAlbumFileCount;
capsaGetAlbumFileCount(location, &totalAlbumFileCount);
// Get all album files from the album
u64 albumFileCount;
CapsAlbumEntry albumFiles[totalAlbumFileCount];
Result r = capsaGetAlbumFileList(location, &albumFileCount, albumFiles, totalAlbumFileCount);
if (R_FAILED(r))
{
printf("Failed to get album file list for storage %s: %d-%d\n", location == CapsAlbumStorage_Sd ? "SD" : "NAND", R_MODULE(r), R_DESCRIPTION(r));
return;
}
// Add the files from the raw array to the std::vector
for (CapsAlbumEntry entry : albumFiles)
{
// Count
if (entry.file_id.content == CapsAlbumFileContents_Movie || entry.file_id.content == CapsAlbumFileContents_ExtraMovie)
videoCount++;
else
screenshotCount++;
// Add to the cache
outCache.push_back(entry);
}
#ifdef __DEBUG__
printf("Cached %ld album files for %s storage\n", totalAlbumFileCount, location == CapsAlbumStorage_Sd ? "SD" : "NAND");
#endif
}
| 34.611002 | 152 | 0.675768 | iUltimateLP |
47bb95da3c24f525aecff41fd0ef971fad3c6114 | 586 | cpp | C++ | source/chapter_05/listings/listing_05_14_waiting.cpp | ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition | ce2c8fca379508929dfd24dce10eff2c09117999 | [
"MIT"
] | null | null | null | source/chapter_05/listings/listing_05_14_waiting.cpp | ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition | ce2c8fca379508929dfd24dce10eff2c09117999 | [
"MIT"
] | null | null | null | source/chapter_05/listings/listing_05_14_waiting.cpp | ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition | ce2c8fca379508929dfd24dce10eff2c09117999 | [
"MIT"
] | null | null | null | /**
* \file
* listing_05_14_waiting.cpp
*
* \brief
* Using clock() in a time-delay loop.
*/
#include <ctime> // describes clock() function, clock_t type
#include <iostream>
int main()
{
using namespace std;
cout << "Enter the delay time, in seconds: ";
float secs;
cin >> secs;
clock_t delay = secs * CLOCKS_PER_SEC; // convert to clock ticks
cout << "starting\a\n";
clock_t start = clock();
while (clock() - start < delay ) // wait until time passes
{
; // note the semicolon
}
cout << "done \a\n";
return 0;
}
| 20.206897 | 68 | 0.581911 | ShinyGreenRobot |
47bee0a2e539c092ccc7de0698b37716f69b4d28 | 722 | cpp | C++ | benchmark/benchmark.cpp | ortfero/pulse | 08cd78c20f16101b553e4e15f1a04011bb32722c | [
"MIT"
] | null | null | null | benchmark/benchmark.cpp | ortfero/pulse | 08cd78c20f16101b553e4e15f1a04011bb32722c | [
"MIT"
] | null | null | null | benchmark/benchmark.cpp | ortfero/pulse | 08cd78c20f16101b553e4e15f1a04011bb32722c | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <pulse/pulse.hpp>
#include <ubench/ubench.hpp>
struct listener {
}; // listener
using slot_type = void(listener::*)();
bool flag = true;
struct handler: listener {
void slot() {
flag = !flag;
}
}; // handler
int main() {
handler h;
listener* l = &h;
slot_type s = slot_type(&handler::slot);
pulse::source<void()> source;
source.bind(&h, &handler::slot);
auto const member_bench = ubench::run([&]{ (l->*s)(); });
auto const pulse_bench = ubench::run([&]{ source(); });
printf("member_ptr - %.1fns\n", member_bench.time.count());
printf("pulse::signal - %.1fns\n", pulse_bench.time.count());
printf("flag = %s\n", flag ? "true" : "false");
return 0;
}
| 18.05 | 63 | 0.609418 | ortfero |
47bf81bc6c0b6c52ed41b6571e87789df5f4b611 | 5,009 | cpp | C++ | node_modules/ammo.js/bullet/Extras/CDTestFramework/Opcode/Ice/IceHPoint.cpp | Xielifen/three.js-master | 58467f729243d90da4b758b0fe130eb40458bc39 | [
"MIT"
] | 8 | 2015-02-28T15:33:39.000Z | 2019-06-12T19:59:34.000Z | node_modules/ammo.js/bullet/Extras/CDTestFramework/Opcode/Ice/IceHPoint.cpp | Xielifen/three.js-master | 58467f729243d90da4b758b0fe130eb40458bc39 | [
"MIT"
] | null | null | null | node_modules/ammo.js/bullet/Extras/CDTestFramework/Opcode/Ice/IceHPoint.cpp | Xielifen/three.js-master | 58467f729243d90da4b758b0fe130eb40458bc39 | [
"MIT"
] | 5 | 2016-04-13T12:22:36.000Z | 2022-01-14T19:18:52.000Z | /*
* ICE / OPCODE - Optimized Collision Detection
* http://www.codercorner.com/Opcode.htm
*
* Copyright (c) 2001-2008 Pierre Terdiman, pierre@codercorner.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains code for homogeneous points.
* \file IceHPoint.cpp
* \author Pierre Terdiman
* \date April, 4, 2000
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Homogeneous point.
*
* Use it:
* - for clipping in homogeneous space (standard way)
* - to differentiate between points (w=1) and vectors (w=0).
* - in some cases you can also use it instead of Point for padding reasons.
*
* \class HPoint
* \author Pierre Terdiman
* \version 1.0
* \warning No cross-product in 4D.
* \warning HPoint *= Matrix3x3 doesn't exist, the matrix is first casted to a 4x4
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Precompiled Header
#include "Stdafx.h"
using namespace Opcode;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Point Mul = HPoint * Matrix3x3;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Point HPoint::operator*(const Matrix3x3& mat) const
{
return Point(
x * mat.m[0][0] + y * mat.m[1][0] + z * mat.m[2][0],
x * mat.m[0][1] + y * mat.m[1][1] + z * mat.m[2][1],
x * mat.m[0][2] + y * mat.m[1][2] + z * mat.m[2][2] );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HPoint Mul = HPoint * Matrix4x4;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HPoint HPoint::operator*(const Matrix4x4& mat) const
{
return HPoint(
x * mat.m[0][0] + y * mat.m[1][0] + z * mat.m[2][0] + w * mat.m[3][0],
x * mat.m[0][1] + y * mat.m[1][1] + z * mat.m[2][1] + w * mat.m[3][1],
x * mat.m[0][2] + y * mat.m[1][2] + z * mat.m[2][2] + w * mat.m[3][2],
x * mat.m[0][3] + y * mat.m[1][3] + z * mat.m[2][3] + w * mat.m[3][3]);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HPoint *= Matrix4x4
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HPoint& HPoint::operator*=(const Matrix4x4& mat)
{
float xp = x * mat.m[0][0] + y * mat.m[1][0] + z * mat.m[2][0] + w * mat.m[3][0];
float yp = x * mat.m[0][1] + y * mat.m[1][1] + z * mat.m[2][1] + w * mat.m[3][1];
float zp = x * mat.m[0][2] + y * mat.m[1][2] + z * mat.m[2][2] + w * mat.m[3][2];
float wp = x * mat.m[0][3] + y * mat.m[1][3] + z * mat.m[2][3] + w * mat.m[3][3];
x = xp; y = yp; z = zp; w = wp;
return *this;
}
| 56.920455 | 244 | 0.345578 | Xielifen |
47c023f0b5dcfc051c95481e24887c61fe759af6 | 427 | hpp | C++ | comp-project/global.hpp | 180254/TK-lab | 25436df5b93b174b75c89afda7f999b75c448e37 | [
"MIT"
] | 1 | 2017-05-17T09:20:06.000Z | 2017-05-17T09:20:06.000Z | comp-project/global.hpp | 180254/TK-lab | 25436df5b93b174b75c89afda7f999b75c448e37 | [
"MIT"
] | null | null | null | comp-project/global.hpp | 180254/TK-lab | 25436df5b93b174b75c89afda7f999b75c448e37 | [
"MIT"
] | 5 | 2018-06-05T20:00:42.000Z | 2021-11-22T17:53:54.000Z | #pragma once
#define YYDEBUG 0
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include "main.hpp"
#include "node.hpp"
#include "inter.hpp"
#include "error.hpp"
#include "parser.m.hpp"
#include "lexer.hpp"
#define DELETE(ptr) \
{ \
delete ptr; \
ptr = nullptr; \
}
using namespace std;
| 14.724138 | 23 | 0.648712 | 180254 |
47cb9d0b97b1426b29f3e5e58983f1836f85c062 | 5,697 | cpp | C++ | src/server/tests/httpserv.cpp | Ooggle/MUSIC-exclamation-mark | 55f4dd750d57227fac29d887d90e0c8ec2ad7397 | [
"MIT"
] | 7 | 2020-08-28T21:47:54.000Z | 2021-01-01T17:54:27.000Z | src/server/tests/httpserv.cpp | Ooggle/MUSIC-exclamation-mark | 55f4dd750d57227fac29d887d90e0c8ec2ad7397 | [
"MIT"
] | null | null | null | src/server/tests/httpserv.cpp | Ooggle/MUSIC-exclamation-mark | 55f4dd750d57227fac29d887d90e0c8ec2ad7397 | [
"MIT"
] | 1 | 2020-12-26T17:08:54.000Z | 2020-12-26T17:08:54.000Z | #include <unistd.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <string>
#include <vector>
#include "ServeurTcp.h"
int regexTwo(std::string paramsSource);
std::string getRequestLine(ServeurTcp *server) {
uint8_t data = 0;
std::string line = "";
while(data != 0x0A)
{
server->recevoirData(&data, 1);
if(data != 0x0A)
line += data;
}
return line;
}
std::vector<std::string> getRequestHeader(ServeurTcp *server) {
std::vector<std::string> request;
do
{
request.push_back(getRequestLine(server));
/* printf("length: %d\n", request.back().length());
printf("%s\n", request.back().c_str()); */
} while(request.back().length() > 2);
return request;
}
int regexOne(std::string strSource) {
regex_t reg;
// Function call to create regex
if (regcomp(®, "^GET\\s\\/(music|database)(\\?.*)\\sHTTP", REG_EXTENDED) != 0) {
printf("Compilation error.\n");
}
size_t maxGroups = 15;
regmatch_t groupArray[maxGroups];
const char *source = strSource.c_str();
if(regexec(®, source, maxGroups, groupArray, 0) == 0) {
unsigned int g = 0;
for(g = 0; g < maxGroups; g++)
{
if(groupArray[g].rm_so == (size_t)-1)
break; // No more groups
char sourceCopy[strlen(source) + 1];
strcpy(sourceCopy, source);
sourceCopy[groupArray[g].rm_eo] = 0;
/* printf("Group %u: [%2u-%2u]: %s\n",
g, groupArray[g].rm_so, groupArray[g].rm_eo,
sourceCopy + groupArray[g].rm_so); */
}
char sourceCopy[strlen(source) + 1];
strcpy(sourceCopy, source);
sourceCopy[groupArray[2].rm_eo] = 0;
printf("param source: %s\n", sourceCopy + groupArray[2].rm_so);
regexTwo(sourceCopy + groupArray[2].rm_so);
} else {
printf("no pattern found\n");
}
regfree(®);
return 0;
}
int regexTwo(std::string paramsSource) {
regex_t reg;
// create regex
if (regcomp(®, "[?&]+([^=&]+)=([^&]*)", REG_EXTENDED) != 0) {
printf("Compilation error.\n");
}
size_t maxMatches = 5;
size_t maxGroups = 15;
regmatch_t groupArray[maxGroups];
unsigned int m;
const char *source = paramsSource.c_str();
regoff_t last_match = 0;
int Numparams = 0;
while(regexec(®, source + last_match, maxGroups, groupArray, 0) == 0) {
unsigned int g = 0;
Numparams += 1;
for(g = 0; g < maxGroups; g++)
{
if(groupArray[g].rm_so == (size_t)-1)
break; // No more groups
char sourceCopy[strlen(source) + last_match + 1];
strcpy(sourceCopy, source);
sourceCopy[groupArray[g].rm_eo + last_match] = 0;
/*printf("Group %u: [%2u-%2u]: %s\n",
g, groupArray[g].rm_so + last_match, groupArray[g].rm_eo + last_match,
sourceCopy + groupArray[g].rm_so + last_match);*/
}
char sourceParamName[strlen(source) + last_match + 1];
strcpy(sourceParamName, source);
sourceParamName[groupArray[1].rm_eo + last_match] = 0;
char sourceParamValue[strlen(source) + last_match + 1];
strcpy(sourceParamValue, source);
sourceParamValue[groupArray[2].rm_eo + last_match] = 0;
printf("Param %d: %s = %s\n", Numparams, sourceParamName + groupArray[1].rm_so + last_match, sourceParamValue + groupArray[2].rm_so + last_match);
last_match += groupArray[0].rm_so + 1;
}
regfree(®);
return 0;
}
int main()
{
ServeurTcp leServeur;
leServeur.ouvrir("192.168.0.44", 80);
printf("serveur ouvert\n");
leServeur.connecterUnClient();
printf("client connecte\n");
int i = 0;
char getStr[255] = {0};
int getSize = 0;
printf("\n\n");
std::vector<std::string> requestHeader = getRequestHeader(&leServeur);
std::vector<std::pair<std::string, std::string>> URLInfos;
regexOne(requestHeader.at(0).c_str());
printf("request : %s\n", getStr);
// file loading
std::ifstream myFile;
myFile.open("musics/sample.mp3", std::ios_base::out | std::ios_base::app | std::ios_base::binary);
if(!myFile.is_open())
return EXIT_FAILURE;
std::uintmax_t totalFileSize = std::filesystem::file_size("musics/sample.mp3");
printf("file size : %d\n", totalFileSize);
// header sending
printf("sending data...");
std::string header;
// audio/ogg pour ogg et flac, audio/mpeg pour mp3
header = "HTTP/1.1 200 OK\r\n";
header += "Connection: keep-alive\r\n";
header += "Content-Type: audio/mpeg\r\n";
header += "Content-Length: ";
header += std::to_string(totalFileSize);
header += "\r\n";
header += "\r\n";
printf("%s", header.c_str());
leServeur.emettreData((void *)header.c_str(), header.length());
// file sending
int sizeToRead = 5000;
char FileBuffer[totalFileSize];
char lastBuffer[sizeToRead];
std::uintmax_t readedSize = 0;
while(readedSize < totalFileSize)
{
if((readedSize + sizeToRead) > totalFileSize) {
sizeToRead = totalFileSize - readedSize;
}
if(!myFile.read(lastBuffer, sizeToRead))
return EXIT_FAILURE;
leServeur.emettreData((void *)lastBuffer, sizeToRead);
readedSize += sizeToRead;
}
leServeur.deconnecterUnClient();
leServeur.fermer();
sleep(0.5);
return EXIT_SUCCESS;
}
| 27.128571 | 154 | 0.583289 | Ooggle |
47cd1e37825f8e92a0b03115f40569d7b50fb9da | 19,034 | cpp | C++ | src/mayaToAppleseed/src/mtap_common/mtap_mayaScene.cpp | haggi/OpenMaya | 746e0740f480d9ef8d2173f31b3c99b9b0ea0d24 | [
"MIT"
] | 42 | 2015-01-03T15:07:25.000Z | 2021-12-09T03:56:59.000Z | src/mayaToAppleseed/src/mtap_common/mtap_mayaScene.cpp | haggi/OpenMaya | 746e0740f480d9ef8d2173f31b3c99b9b0ea0d24 | [
"MIT"
] | 66 | 2015-01-02T13:28:44.000Z | 2022-03-16T14:00:57.000Z | src/mayaToAppleseed/src/mtap_common/mtap_mayaScene.cpp | haggi/OpenMaya | 746e0740f480d9ef8d2173f31b3c99b9b0ea0d24 | [
"MIT"
] | 12 | 2015-02-07T05:02:17.000Z | 2020-07-10T17:21:44.000Z | //#include <maya/MGlobal.h>
//#include <maya/MSelectionList.h>
//#include <maya/MFnDagNode.h>
//#include <maya/MFnMesh.h>
//
//#include "mtap_mayaScene.h"
//#include "utilities/logging.h"
//#include "utilities/tools.h"
//
//static Logging logger;
//
//
//mtap_MayaScene::mtap_MayaScene()
//{
// this->renderGlobals = nullptr;
// this->getRenderGlobals();
// this->cando_ipr = true;
// this->mtap_renderer.mtap_scene = this;
// this->mtap_renderer.renderGlobals = this->renderGlobals;
// this->mtap_renderer.definePreRender();
// this->userThreadUpdateInterval= 1000;
// this->needsUserThread = false;
//}
//
//mtap_MayaScene::~mtap_MayaScene()
//{
// Logging::debug("~mtap_MayaScene");
//}
//
//void mtap_MayaScene::userThreadProcedure()
//{}
//
//void mtap_MayaScene::transformUpdateCallback(MayaObject *mobj)
//{
// std::shared_ptr<MayaObject> obj = (std::shared_ptr<MayaObject> )mobj;
//
// // instancer elements are a special case. They contain a shape node, but they are updated as a transform
// if( !obj->mobject.hasFn(MFn::kTransform) && (obj->instancerParticleId < 0))
// return;
//
// //Logging::debug(MString("mtap_MayaScene::transformUpdateCallback") + mobj->shortName);
//
// if( obj->instancerParticleId > -1)
// {
// if( obj->origObject == nullptr)
// return;
// }
//
// if( !obj->visible )
// return;
//
// this->mtap_renderer.updateTransform(obj);
//
//}
//
//void mtap_MayaScene::shapeUpdateCallback(MayaObject *mobj)
//{
// std::shared_ptr<MayaObject> obj = (std::shared_ptr<MayaObject> )mobj;
// Logging::debug(MString("mtap_MayaScene::shapeUpdateCallback"));
//
// if( !obj->mobject.hasFn(MFn::kShape))
// return;
//
// if( !obj->visible && !obj->attributes->hasInstancerConnection && !obj->isInstancerObject && !(obj->isCamera()))
// return;
//
// if( !obj->geometryShapeSupported())
// return;
//
// this->mtap_renderer.updateShape(obj);
//}
//
////void mtap_MayaScene::deformUpdateCallback(MayaObject *mobj)
////{
//// std::shared_ptr<MayaObject> obj = (std::shared_ptr<MayaObject> )mobj;
//// Logging::debug(MString("mtap_MayaScene::deformUpdateCallback"));
////
//// if( obj->instanceNumber > 0)
//// return;
////
//// if( !obj->geometryShapeSupported() )
//// return;
////
//// if( !obj->visible)
//// if( !obj->attributes->hasInstancerConnection )
//// {
//// if( obj->mobject.hasFn(MFn::kMesh))
//// {
//// if( !obj->isVisiblityAnimated() )
//// {
//// //MFnMesh meshFn(obj->mobject);
//// //MString meshFullName = makeGoodString(meshFn.fullPathName());
//// //// if obj was visible, delete it from memory.
//// //MString meshInst = meshFullName + "_inst";
//// //std::shared_ptr<ObjectAttributes>att = (std::shared_ptr<ObjectAttributes>)obj->attributes;
//// //std::shared_ptr<MayaObject> assObject = att->assemblyObject;
//// //if( assObject != nullptr)
//// //{
//// //
//// // obj->objectAssembly->object_instances().remove(obj->objectAssembly->object_instances().get_by_name("my_obj_instance"));
//// // obj->objectAssembly->objects().remove(obj->objectAssembly->objects().get_by_name("my_obj_instance"));
//// // obj->objectAssembly->bump_version_id();
//// //
//// //
//// // if( assObject->objectAssembly != nullptr)
//// // {
//// // asr::ObjectInstance *oi = assObject->objectAssembly->object_instances().get_by_name(meshInst.asChar());
//// // if( oi != nullptr)
//// // {
//// // Logging::debug(MString("------ Found and remove a object instance ----") + meshInst);
//// // //oi->release();
//// // //oi->bump_version_id();
//// // }
//// // asr::Object *o = assObject->objectAssembly->objects().get_by_name(meshFullName.asChar());
//// // if( o != nullptr)
//// // {
//// // Logging::debug(MString("------ Found and remove a object ----") + meshFullName);
//// // //o->release();
//// // //o->bump_version_id();
//// // }
//// //
//// // asr::AssemblyInstance *ai = this->mtap_renderer.masterAssembly->assembly_instances().get_by_name( (obj->parent->fullName + "assembly_inst").asChar());
//// // //ai->bump_version_id();
//// // //assObject->objectAssembly->bump_version_id();
//// // }
//// //}
//// return;
//// }
//// }
//// }
//// //this->mtap_renderer.updateDeform(obj);
//// this->mtap_renderer.updateShape(obj);
////}
//
//MayaObject *mtap_MayaScene::mayaObjectCreator(MObject& mobject)
//{
// std::shared_ptr<MayaObject> mobj = new mtap_MayaObject(mobject);
// mobj->scenePtr = this;
// return mobj;
//}
//
//MayaObject *mtap_MayaScene::mayaObjectCreator(MDagPath& objDagPath)
//{
// std::shared_ptr<MayaObject> mobj = new mtap_MayaObject(objDagPath);
// mobj->scenePtr = this;
// return mobj;
//}
//
//void mtap_MayaScene::mayaObjectDeleter(MayaObject *obj)
//{
// std::shared_ptr<MayaObject> mtap_obj = (std::shared_ptr<MayaObject> )obj;
// delete mtap_obj;
// obj = nullptr;
//}
//
//void mtap_MayaScene::getRenderGlobals()
//{
// this->renderGlobals = nullptr;
// mtap_RenderGlobals *tst = new mtap_RenderGlobals();
// this->renderGlobals = tst;
// MayaScene::renderGlobals = renderGlobals;
//}
//
//
//bool mtap_MayaScene::translateShaders(int timeStep)
//{
// Logging::debug("mtap_MayaScene::translateShaders");
// return true;
//}
//
//bool mtap_MayaScene::translateShapes(int timeStep)
//{
// Logging::debug("mtap_MayaScene::translateShapes");
// return true;
//}
//
//bool mtap_MayaScene::doPreRenderJobs()
//{
// Logging::debug("mtap_MayaScene::doPreRenderJobs");
// return true;
//}
//
//bool mtap_MayaScene::doPreFrameJobs()
//{
// Logging::debug("mtap_MayaScene::doPreFrameJobs");
//
// MString result;
// MGlobal::executeCommand(this->renderGlobals->preFrameScript, result, true);
// return true;
//}
//
//bool mtap_MayaScene::doPostFrameJobs()
//{
// Logging::debug("mtap_MayaScene::doPostFrameJobs");
// MString result;
// MGlobal::executeCommand(this->renderGlobals->postFrameScript, result, true);
// return true;
//}
//
//bool mtap_MayaScene::doPostRenderJobs()
//{
// Logging::debug("mtap_MayaScene::doPostRenderJobs");
// return true;
//}
//
//
////
//// for easy findings, put all objects into a map
////
//void mtap_MayaScene::makeMayaObjectMObjMap()
//{
// mayaObjMObjMap.clear();
// std::vector<MayaObject *>::iterator iter = this->objectList.begin();
// for( ;iter != this->objectList.end(); iter++)
// {
// this->mayaObjMObjMap.append((*iter)->mobject, *iter);
// }
//}
//
//std::shared_ptr<MayaObject> mtap_MayaScene::getMayaObjectFromMap(MObject& obj)
//{
// std::shared_ptr<MayaObject> mobj = (std::shared_ptr<MayaObject> )*mayaObjMObjMap.find(obj);
// return mobj;
//}
//
////
//// Check if the selected nodes exist in the scene->MayaObject lists.
////
//void mtap_MayaScene::mobjectListToMayaObjectList(std::vector<MObject>& mObjectList, std::vector<MayaObject *>& mtapObjectList)
//{
// std::vector<MObject>::iterator moIter, moIterFound;
// std::vector<MayaObject *>::iterator mIter;
// std::vector<MObject> cleanMObjectList;
// std::vector<MObject> foundMObjectList;
//
// for( moIter = mObjectList.begin(); moIter != mObjectList.end(); moIter++)
// {
// bool found = false;
// MSelectionList select;
// MString objName = getObjectName(*moIter);
// Logging::debug(MString("Object to modify:") + objName);
// select.add(objName);
// MDagPath dp;
// select.getDagPath(0, dp);
// //dp.extendToShape();
// MObject dagObj = dp.node();
//
// if( (*moIter).hasFn(MFn::kCamera))
// {
// for( mIter = this->camList.begin(); mIter != camList.end(); mIter++)
// {
// MayaObject *mo = *mIter;
// if( dagObj == mo->mobject)
// {
// mtapObjectList.push_back(mo);
// foundMObjectList.push_back(*moIter);
// found = true;
// break;
// }
// }
// if( found )
// continue;
// }
//
// for( mIter = this->objectList.begin(); mIter != objectList.end(); mIter++)
// {
// MayaObject *mo = *mIter;
// if( dagObj == mo->mobject)
// {
// mtapObjectList.push_back(mo);
// foundMObjectList.push_back(*moIter);
// found = true;
// break;
// }
// }
// if( found )
// continue;
// for( mIter = this->lightList.begin(); mIter != lightList.end(); mIter++)
// {
// MayaObject *mo = *mIter;
// if( dagObj == mo->mobject)
// {
// mtapObjectList.push_back(mo);
// foundMObjectList.push_back(*moIter);
// found = true;
// break;
// }
// }
// if( found )
// continue;
// }
//
// for( moIter = mObjectList.begin(); moIter != mObjectList.end(); moIter++)
// {
// bool found = false;
// for( moIterFound = foundMObjectList.begin(); moIterFound != foundMObjectList.end(); moIterFound++)
// {
// if( *moIter == *moIterFound)
// {
// found = true;
// continue;
// }
// }
// if(!found)
// cleanMObjectList.push_back(*moIter);
// }
//
// mObjectList = cleanMObjectList;
//
//}
//
////
//// after idle process has started, this procedure is called. It does:
//// search the mobject in the MayaObject list
//// puts all found objects into a updateList
//// sets the renderer to restart.
//// Then the renderer calls the appleseed updateEntities procedure at the beginning
//// of a new rendering.
////
//
//void mtap_MayaScene::updateInteraciveRenderScene(std::vector<MObject> mobjList)
//{
// std::vector<MayaObject *> mayaObjectList;
// mobjectListToMayaObjectList(mobjList, mayaObjectList);
// std::vector<MayaObject *>::iterator mIter;
// this->mtap_renderer.interactiveUpdateList.clear();
//
// // this here is for all nodes, defined by an mayaObject, all others will be placed into
// // the interactiveUpdateMOList below, e.g. shaders, colors, globals, etc.
// for( mIter = mayaObjectList.begin(); mIter != mayaObjectList.end(); mIter++)
// {
// std::shared_ptr<MayaObject> mo = (std::shared_ptr<MayaObject> )*mIter;
// Logging::debug(MString("updateInteraciveRenderScene: obj: ") + mo->shortName);
// mo->updateObject(); // update transforms
// this->mtap_renderer.interactiveUpdateList.push_back(mo);
// }
//
// this->mtap_renderer.interactiveUpdateMOList.clear();
// for( size_t i = 0; i < mobjList.size(); i++)
// this->mtap_renderer.interactiveUpdateMOList.push_back(mobjList[i]);
//
// if( (this->mtap_renderer.interactiveUpdateList.size() > 0) || (this->mtap_renderer.interactiveUpdateMOList.size() > 0))
// this->mtap_renderer.mtap_controller.status = asr::IRendererController::ReinitializeRendering;
// //this->mtap_renderer.mtap_controller.status = asr::IRendererController::RestartRendering;
//}
//
//void mtap_MayaScene::stopRendering()
//{
// Logging::debug(MString("mtap_MayaScene::stopRendering()"));
// this->mtap_renderer.mtap_controller.status = asr::IRendererController::AbortRendering;
//}
//
//bool mtap_MayaScene::renderImage()
//{
// Logging::debug("mtap_MayaScene::renderImage");
// Logging::debug(MString("Current frame: ") + this->renderGlobals->currentFrame);
//
// this->renderGlobals->getImageName();
//
// this->mtap_renderer.defineScene(this->renderGlobals, this->objectList, this->lightList, this->camList, this->instancerNodeElements);
//
// if( this->renderGlobals->exportSceneFile)
// this->mtap_renderer.writeXML();
//
// this->mtap_renderer.render();
//
// return true;
//}
//
////bool mtap_MayaScene::parseScene()
////{
//// MayaScene::parseScene();
//// postParseCallback();
//// return true;
////}
//
////
//// Here we build the assemblies and add them to the scene
//// Because all assemblies will need an assembly instance, the
//// instances are defined as well.
////
////void mtap_MayaScene::createObjAssembly(std::shared_ptr<MayaObject> obj)
////{
//// //std::shared_ptr<ObjectAttributes>att = (std::shared_ptr<ObjectAttributes>)obj->attributes;
////
//// //if( !obj->visible )
//// // if( !obj->isVisiblityAnimated() && (!obj->isInstanced()) )
//// // if( !att->hasInstancerConnection)
//// // return;
////
//// //if( att->needsOwnAssembly)
//// // obj->objectAssembly = createAssembly(obj);
////}
//
////void mtap_MayaScene::createObjAssemblyInstances(std::shared_ptr<MayaObject> obj)
////{
// //std::shared_ptr<ObjectAttributes>att = (std::shared_ptr<ObjectAttributes>)obj->attributes;
//
// //// instances will be added below only for the original object
// //if( obj->instanceNumber > 0)
// // return;
//
// //if( obj->objectAssembly == nullptr)
// // return;
//
// //if( !obj->visible && !obj->isVisiblityAnimated() && !obj->isInstanced())
// // return;
//
// //// simply add instances for all paths
// //MFnDagNode objNode(obj->mobject);
// //MDagPathArray pathArray;
// //objNode.getAllPaths(pathArray);
//
// //this->mtap_renderer.interactiveAIList.clear();
//
// //for( uint pId = 0; pId < pathArray.length(); pId++)
// //{
// // // if the object itself is not visible and the path is the one of the original shape, ignore it
// // // this way we can hide the original geometry and make only the instances visible
// // if( (!obj->visible) && (pId == 0))
// // continue;
// // MDagPath currentPath = pathArray[pId];
// // if(!IsVisible(currentPath))
// // continue;
// // MString assemblyInstName = currentPath.fullPathName() + "assemblyInstance";
// // Logging::debug(MString("Define assembly instance for obj: ") + obj->shortName + " path " + currentPath.fullPathName() + " assInstName: " + assemblyInstName );
// // asf::auto_release_ptr<asr::AssemblyInstance> ai = asr::AssemblyInstanceFactory::create(
// // assemblyInstName.asChar(),
// // asr::ParamArray(),
// // obj->objectAssembly->get_name());
//
// // this->mtap_renderer.interactiveAIList.push_back(ai.get());
//
// // // if world, then add a global scene scaling.
// // if( obj->shortName == "world")
// // {
// // asf::Matrix4d appMatrix;
// // MMatrix transformMatrix;
// // transformMatrix.setToIdentity();
// // transformMatrix *= this->renderGlobals->sceneScaleMatrix;
// // this->mtap_renderer.MMatrixToAMatrix(transformMatrix, appMatrix);
// // ai->transform_sequence().set_transform(0.0, asf::Transformd::from_local_to_parent(appMatrix));
// // this->mtap_renderer.scenePtr->assembly_instances().insert(ai);
// // continue;
// // }
// // if( this->renderType == MayaScene::IPR)
// // {
// // if( obj->parent != nullptr)
// // {
// // std::shared_ptr<MayaObject> parent = (std::shared_ptr<MayaObject> )obj->parent;
// // if( parent->objectAssembly != nullptr)
// // {
// // Logging::debug(MString("Insert assembly instance ") + obj->shortName + " into parent " + parent->shortName);
// // parent->objectAssembly->assembly_instances().insert(ai);
// // }else{
// // //this->mtap_renderer.scene->assembly_instances().insert(ai);
// // this->mtap_renderer.masterAssembly->assembly_instances().insert(ai);
// // }
// // }else{
// // //this->mtap_renderer.scene->assembly_instances().insert(ai);
// // this->mtap_renderer.masterAssembly->assembly_instances().insert(ai);
// // }
// // }else{
// // //this->mtap_renderer.scene->assembly_instances().insert(ai);
// // this->mtap_renderer.masterAssembly->assembly_instances().insert(ai);
// // }
// //}
////}
//
////bool mtap_MayaScene::postParseCallback()
////{
//// Logging::debug("mtap_MayaScene::postParseCallback");
//
// //std::vector<MayaObject *>::iterator mIter = this->objectList.begin();
// //for(;mIter!=this->objectList.end(); mIter++)
// //{
// // std::shared_ptr<MayaObject> obj = (std::shared_ptr<MayaObject> )*mIter;
// // this->createObjAssembly(obj);
// //}
//
// //// after the definition of all assemblies, there is a least one "world" assembly, this will be our master assembly
// //// where all the lights and other elements will be placed in
// //this->mtap_renderer.defineMasterAssembly();
//
// //// all assemblies need their own assembly instance because assemblies are only created where instances exist.
// //mIter = this->objectList.begin();
// //for(;mIter!=this->objectList.end(); mIter++)
// //{
// // std::shared_ptr<MayaObject> obj = (std::shared_ptr<MayaObject> )*mIter;
// // createObjAssemblyInstances(obj);
// //}
// //
// //int count = 0;
// //mIter = this->instancerNodeElements.begin();
// //for(;mIter!=this->instancerNodeElements.end(); mIter++)
// //{
// // std::shared_ptr<MayaObject> obj = (std::shared_ptr<MayaObject> )*mIter;
//
// // std::shared_ptr<ObjectAttributes>att = (std::shared_ptr<ObjectAttributes>)obj->attributes;
// // MString objname = obj->fullName;
// // if( obj->instancerParticleId < 0)
// // continue;
// // if( obj->origObject == nullptr)
// // continue;
// // if( ((std::shared_ptr<MayaObject> )(obj->origObject))->objectAssembly == nullptr)
// // continue;
//
// // Logging::debug(MString("instancer node element: ") + obj->shortName + " path " + obj->fullName);
// // MString instancerElementName = obj->fullName + "assemblyInstance";
// // asf::auto_release_ptr<asr::AssemblyInstance> ai = asr::AssemblyInstanceFactory::create(
// // instancerElementName.asChar(),
// // asr::ParamArray(),
// // ((std::shared_ptr<MayaObject> )(obj->origObject))->objectAssembly->get_name());
// // this->mtap_renderer.masterAssembly->assembly_instances().insert(ai);
// //}
//
//// return true;
////}
//
//
////asr::Assembly *mtap_MayaScene::getAssembly(std::shared_ptr<MayaObject> obj)
////{
//// return this->mtap_renderer.scenePtr->assemblies().get_by_name(obj->fullName.asChar());
////}
////
////asr::Assembly *mtap_MayaScene::createAssembly(std::shared_ptr<MayaObject> obj)
////{
////
//// Logging::debug(MString("Creating new assembly for: ") + obj->fullName);
//// asf::auto_release_ptr<asr::Assembly> assembly = asr::AssemblyFactory::create( obj->fullName.asChar(), asr::ParamArray());
////
//// asr::Assembly *assemblyPtr = nullptr;
//// asr::Assembly *parentAssembly = nullptr;
////
//// if( this->renderType == MayaScene::IPR)
//// {
//// if( obj->parent != nullptr)
//// {
//// std::shared_ptr<MayaObject> parent = (std::shared_ptr<MayaObject> )obj->parent;
//// parentAssembly = this->getAssembly(parent);
//// if( parentAssembly != nullptr)
//// {
//// Logging::debug(MString("Insert assembly ") + obj->shortName + " into parent " + parent->shortName);
//// parent->objectAssembly->assemblies().insert(assembly);
//// assemblyPtr = parent->objectAssembly->assemblies().get_by_name(obj->fullName.asChar());
//// }else{
//// this->mtap_renderer.scenePtr->assemblies().insert(assembly);
//// assemblyPtr = this->mtap_renderer.scenePtr->assemblies().get_by_name(obj->fullName.asChar());
//// }
//// }else{
//// this->mtap_renderer.scenePtr->assemblies().insert(assembly);
//// assemblyPtr = this->mtap_renderer.scenePtr->assemblies().get_by_name(obj->fullName.asChar());
//// }
//// }else{
//// this->mtap_renderer.scenePtr->assemblies().insert(assembly);
//// assemblyPtr = this->mtap_renderer.scenePtr->assemblies().get_by_name(obj->fullName.asChar());
//// }
////
//// if( this->renderGlobals->assemblySBVH )
//// {
//// if( obj->animated || obj->isShapeConnected() )
//// assemblyPtr->get_parameters().insert_path("acceleration_structure.algorithm", "sbvh");
//// }
////
//// return assemblyPtr;
////}
| 33.569665 | 170 | 0.651571 | haggi |
47cf00fae5011998560ada03737950ac7bb62787 | 10,474 | cpp | C++ | src/vizdoom/src/stringtable.cpp | johny-c/ViZDoom | 6fe0d2470872adbfa5d18c53c7704e6ff103cacc | [
"MIT"
] | 1,102 | 2017-02-02T15:39:57.000Z | 2022-03-23T09:43:29.000Z | src/stringtable.cpp | Leonan8995/Xenomia | 3f3743dd5aff047608ec31fb71186d177812c7df | [
"Unlicense"
] | 339 | 2017-02-17T09:55:38.000Z | 2022-03-29T11:44:01.000Z | src/stringtable.cpp | Leonan8995/Xenomia | 3f3743dd5aff047608ec31fb71186d177812c7df | [
"Unlicense"
] | 331 | 2017-02-02T15:34:42.000Z | 2022-03-23T02:42:24.000Z | /*
** stringtable.cpp
** Implements the FStringTable class
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <string.h>
#include <stddef.h>
#include "stringtable.h"
#include "cmdlib.h"
#include "m_swap.h"
#include "w_wad.h"
#include "i_system.h"
#include "sc_man.h"
#include "c_dispatch.h"
#include "v_text.h"
#include "gi.h"
// PassNum identifies which language pass this string is from.
// PassNum 0 is for DeHacked.
// PassNum 1 is for * strings.
// PassNum 2+ are for specific locales.
struct FStringTable::StringEntry
{
StringEntry *Next;
char *Name;
BYTE PassNum;
char String[];
};
FStringTable::FStringTable ()
{
for (int i = 0; i < HASH_SIZE; ++i)
{
Buckets[i] = NULL;
}
}
FStringTable::~FStringTable ()
{
FreeData ();
}
void FStringTable::FreeData ()
{
for (int i = 0; i < HASH_SIZE; ++i)
{
StringEntry *entry = Buckets[i], *next;
Buckets[i] = NULL;
while (entry != NULL)
{
next = entry->Next;
M_Free (entry);
entry = next;
}
}
}
void FStringTable::FreeNonDehackedStrings ()
{
for (int i = 0; i < HASH_SIZE; ++i)
{
StringEntry *entry, *next, **pentry;
for (pentry = &Buckets[i], entry = *pentry; entry != NULL; )
{
next = entry->Next;
if (entry->PassNum != 0)
{
*pentry = next;
M_Free (entry);
}
else
{
pentry = &entry->Next;
}
entry = next;
}
}
}
#include "doomerrors.h"
void FStringTable::LoadStrings (bool enuOnly)
{
int lastlump, lump;
int i, j;
FreeNonDehackedStrings ();
lastlump = 0;
while ((lump = Wads.FindLump ("LANGUAGE", &lastlump)) != -1)
{
j = 0;
if (!enuOnly)
{
LoadLanguage (lump, MAKE_ID('*',0,0,0), true, ++j);
for (i = 0; i < 4; ++i)
{
LoadLanguage (lump, LanguageIDs[i], true, ++j);
LoadLanguage (lump, LanguageIDs[i] & MAKE_ID(0xff,0xff,0,0), true, ++j);
LoadLanguage (lump, LanguageIDs[i], false, ++j);
}
}
// Fill in any missing strings with the default language
LoadLanguage (lump, MAKE_ID('*','*',0,0), true, ++j);
}
}
void FStringTable::LoadLanguage (int lumpnum, DWORD code, bool exactMatch, int passnum)
{
static bool errordone = false;
const DWORD orMask = exactMatch ? 0 : MAKE_ID(0,0,0xff,0);
DWORD inCode = 0;
StringEntry *entry, **pentry;
DWORD bucket;
int cmpval;
bool skip = true;
code |= orMask;
FScanner sc(lumpnum);
sc.SetCMode (true);
while (sc.GetString ())
{
if (sc.Compare ("["))
{ // Process language identifiers
bool donot = false;
bool forceskip = false;
skip = true;
sc.MustGetString ();
do
{
size_t len = sc.StringLen;
if (len != 2 && len != 3)
{
if (len == 1 && sc.String[0] == '~')
{
donot = true;
sc.MustGetString ();
continue;
}
if (len == 1 && sc.String[0] == '*')
{
inCode = MAKE_ID('*',0,0,0);
}
else if (len == 7 && stricmp (sc.String, "default") == 0)
{
inCode = MAKE_ID('*','*',0,0);
}
else
{
sc.ScriptError ("The language code must be 2 or 3 characters long.\n'%s' is %lu characters long.",
sc.String, len);
}
}
else
{
inCode = MAKE_ID(tolower(sc.String[0]), tolower(sc.String[1]), tolower(sc.String[2]), 0);
}
if ((inCode | orMask) == code)
{
if (donot)
{
forceskip = true;
donot = false;
}
else
{
skip = false;
}
}
sc.MustGetString ();
} while (!sc.Compare ("]"));
if (donot)
{
sc.ScriptError ("You must specify a language after ~");
}
skip |= forceskip;
}
else
{ // Process string definitions.
if (inCode == 0)
{
// LANGUAGE lump is bad. We need to check if this is an old binary
// lump and if so just skip it to allow old WADs to run which contain
// such a lump.
if (!sc.isText())
{
if (!errordone) Printf("Skipping binary 'LANGUAGE' lump.\n");
errordone = true;
return;
}
sc.ScriptError ("Found a string without a language specified.");
}
bool savedskip = skip;
if (sc.Compare("$"))
{
sc.MustGetStringName("ifgame");
sc.MustGetStringName("(");
sc.MustGetString();
skip |= !sc.Compare(GameTypeName());
sc.MustGetStringName(")");
sc.MustGetString();
}
if (skip)
{ // We're not interested in this language, so skip the string.
sc.MustGetStringName ("=");
sc.MustGetString ();
do
{
sc.MustGetString ();
}
while (!sc.Compare (";"));
skip = savedskip;
continue;
}
FString strName (sc.String);
sc.MustGetStringName ("=");
sc.MustGetString ();
FString strText (sc.String, ProcessEscapes (sc.String));
sc.MustGetString ();
while (!sc.Compare (";"))
{
ProcessEscapes (sc.String);
strText += sc.String;
sc.MustGetString ();
}
// Does this string exist? If so, should we overwrite it?
bucket = MakeKey (strName.GetChars()) & (HASH_SIZE-1);
pentry = &Buckets[bucket];
entry = *pentry;
cmpval = 1;
while (entry != NULL)
{
cmpval = stricmp (entry->Name, strName.GetChars());
if (cmpval >= 0)
break;
pentry = &entry->Next;
entry = *pentry;
}
if (cmpval == 0 && entry->PassNum >= passnum)
{
*pentry = entry->Next;
M_Free (entry);
entry = NULL;
}
if (entry == NULL || cmpval > 0)
{
entry = (StringEntry *)M_Malloc (sizeof(*entry) + strText.Len() + strName.Len() + 2);
entry->Next = *pentry;
*pentry = entry;
strcpy (entry->String, strText.GetChars());
strcpy (entry->Name = entry->String + strText.Len() + 1, strName.GetChars());
entry->PassNum = passnum;
}
}
}
}
// Replace \ escape sequences in a string with the escaped characters.
size_t FStringTable::ProcessEscapes (char *iptr)
{
char *sptr = iptr, *optr = iptr, c;
while ((c = *iptr++) != '\0')
{
if (c == '\\')
{
c = *iptr++;
if (c == 'n')
c = '\n';
else if (c == 'c')
c = TEXTCOLOR_ESCAPE;
else if (c == 'r')
c = '\r';
else if (c == 't')
c = '\t';
else if (c == '\n')
continue;
}
*optr++ = c;
}
*optr = '\0';
return optr - sptr;
}
// Finds a string by name and returns its value
const char *FStringTable::operator[] (const char *name) const
{
if (name == NULL)
{
return NULL;
}
DWORD bucket = MakeKey (name) & (HASH_SIZE - 1);
StringEntry *entry = Buckets[bucket];
while (entry != NULL)
{
int cmpval = stricmp (entry->Name, name);
if (cmpval == 0)
{
return entry->String;
}
if (cmpval == 1)
{
return NULL;
}
entry = entry->Next;
}
return NULL;
}
// Finds a string by name and returns its value. If the string does
// not exist, returns the passed name instead.
const char *FStringTable::operator() (const char *name) const
{
const char *str = operator[] (name);
return str ? str : name;
}
// Find a string by name. pentry1 is a pointer to a pointer to it, and entry1 is a
// pointer to it. Return NULL for entry1 if it wasn't found.
void FStringTable::FindString (const char *name, StringEntry **&pentry1, StringEntry *&entry1)
{
DWORD bucket = MakeKey (name) & (HASH_SIZE - 1);
StringEntry **pentry = &Buckets[bucket], *entry = *pentry;
while (entry != NULL)
{
int cmpval = stricmp (entry->Name, name);
if (cmpval == 0)
{
pentry1 = pentry;
entry1 = entry;
return;
}
if (cmpval == 1)
{
pentry1 = pentry;
entry1 = NULL;
return;
}
pentry = &entry->Next;
entry = *pentry;
}
pentry1 = pentry;
entry1 = entry;
}
// Find a string with the same exact text. Returns its name.
const char *FStringTable::MatchString (const char *string) const
{
for (int i = 0; i < HASH_SIZE; ++i)
{
for (StringEntry *entry = Buckets[i]; entry != NULL; entry = entry->Next)
{
if (strcmp (entry->String, string) == 0)
{
return entry->Name;
}
}
}
return NULL;
}
void FStringTable::SetString (const char *name, const char *newString)
{
StringEntry **pentry, *oentry;
FindString (name, pentry, oentry);
size_t newlen = strlen (newString);
size_t namelen = strlen (name);
// Create a new string entry
StringEntry *entry = (StringEntry *)M_Malloc (sizeof(*entry) + newlen + namelen + 2);
strcpy (entry->String, newString);
strcpy (entry->Name = entry->String + newlen + 1, name);
entry->PassNum = 0;
// If this is a new string, insert it. Otherwise, replace the old one.
if (oentry == NULL)
{
entry->Next = *pentry;
*pentry = entry;
}
else
{
*pentry = entry;
entry->Next = oentry->Next;
M_Free (oentry);
}
}
| 24.35814 | 105 | 0.582776 | johny-c |
47d05694290c4feb5306e4ca153e7f48be286ece | 7,758 | cpp | C++ | sourceCode/fairport/branch/ankopp/samples/nameprop/main.cpp | enrondata/pstsdk | 70701d755f52412f0f21ed216968e314433a324e | [
"Apache-2.0"
] | 6 | 2019-07-11T23:24:55.000Z | 2021-08-03T16:31:12.000Z | sourceCode/fairport/trunk/samples/nameprop/main.cpp | Lingchar/pstsdk | 70701d755f52412f0f21ed216968e314433a324e | [
"Apache-2.0"
] | null | null | null | sourceCode/fairport/trunk/samples/nameprop/main.cpp | Lingchar/pstsdk | 70701d755f52412f0f21ed216968e314433a324e | [
"Apache-2.0"
] | 4 | 2019-04-17T07:08:30.000Z | 2020-10-12T22:35:19.000Z | #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include "pstsdk/util/primitives.h"
#include "pstsdk/ltp/propbag.h"
#include "pstsdk/pst/pst.h"
using namespace std;
using namespace pstsdk;
void pretty_print(const guid& g, bool special)
{
cout << "{" << hex << setw(8) << setfill('0') << g.data1 << "-" << setw(4) << g.data2 << "-" << setfill('0') << setw(4) << g.data3 << "-";
// next two bytes
cout << hex << setw(2) << setfill('0') << (short)g.data4[0] << setw(2) << setfill('0') << (short)g.data4[1] << "-";
// next six bytes
for(int i = 2; i < 8; ++i)
cout << hex << setw(2) << setfill('0')<< (short)g.data4[i];
cout << (special ? "} *" : "}");
}
void pretty_print(const disk::nameid& id)
{
cout << "id/str offset: " << setw(6) << id.id << ", guid idx: " << setw(2) << disk::nameid_get_guid_index(id)
<< ", prop idx: " << setw(4) << disk::nameid_get_prop_index(id)
<< ", is str: " << (disk::nameid_is_string(id) ? "y" : "n");
}
void pretty_print(const disk::nameid_hash_entry& id)
{
cout << "hash value: " << setw(8) << hex << id.hash_base << ", guid idx: " << setw(2) << dec << disk::nameid_get_guid_index(id)
<< ", prop idx: " << setw(4) << disk::nameid_get_prop_index(id)
<< ", is str: " << (disk::nameid_is_string(id) ? "y" : "n");
}
int main()
{
pst p(L"../../test/sample2.pst");
property_bag names(p.get_db()->lookup_node(nid_name_id_map));
//
// dump out the bucket count
//
// The bucket count is stored in property 0x0001
cout << "Bucket Count: " << names.read_prop<slong>(0x1) << endl;
//
// dump out the guid stream
//
// The GUID Stream is a flat array of guid structures, with three
// predefined values. Because of the predefined values, structures
// referencing the GUID stream refer to the first entry as entry "3"
prop_stream guid_stream(names.open_prop_stream(0x2));
guid g;
int i = 3;
cout << endl << "GUID Stream: " << endl;
cout << "[000] ";
pretty_print(ps_none, true);
cout << "\n[001] ";
pretty_print(ps_mapi, true);
cout << "\n[002] ";
pretty_print(ps_public_strings, true);
cout << endl;
while(guid_stream.read((char*)&g, sizeof(g)) != 0)
{
cout << dec << setfill('0') << "[" << setw(3) << i++ << "] ";
pretty_print(g, false);
cout << endl;
}
cout << "* predefined guid, not actually present in guid stream" << endl;
//
// dump out the entry stream
//
// The entry stream is a flat array of nameid structures
prop_stream entry_stream(names.open_prop_stream(0x3));
disk::nameid id;
i = 0;
cout << endl << "Entry Stream: " << endl;
while(entry_stream.read((char*)&id, sizeof(id)) != 0)
{
cout << dec << setfill('0') << "[" << setw(5) << i++ << "] ";
pretty_print(id);
cout << endl;
}
//
// dump out the string stream
//
// The string stream is a series of long values (4 bytes), which give
// the length of the immediately following string, followed by padding
// to an 8 byte boundry, then another long for the next string, etc.
// When structures address into the string stream, they are giving the
// offset of the long value for the length of the string they want to access.
prop_stream sstream(names.open_prop_stream(0x4));
ulong size;
std::vector<char> buffer;
cout << endl << "String Stream (offset, size: string) : " << endl;
while(sstream.read((char*)&size, sizeof(size)) != 0)
{
if(buffer.size() < size)
buffer.resize(size);
sstream.read((char*)&buffer[0], size);
std::wstring val(reinterpret_cast<wchar_t*>(&buffer[0]), size/sizeof(wchar_t));
wcout << setw(6) << ((size_t)sstream.tellg() - size - 4) << ", " << setw(4) << size << ": " << val << endl;
size_t pos = (size_t)sstream.tellg();
pos = (pos + 3L & ~3L);
sstream.seekg(pos);
}
//
// dump out the hash buckets
//
// Each hash bucket is an array of what basically are the same nameid structures
// in the entry array, except the first field contains the crc of the string instead
// of the string offset. For named props based on identifiers the value is identical.
cout << endl << "Buckets:" << endl;
prop_id max_bucket = (prop_id)(0x1000 + names.read_prop<slong>(0x1));
for(prop_id p = 0x1000; p < max_bucket; ++p)
{
cout << "[" << setw(4) << hex << p << "] ";
try
{
prop_stream hash_values(names.open_prop_stream(p));
// calculate the number of values
hash_values.seekg(0, ios_base::end);
size_t size = (size_t)hash_values.tellg();
size_t num = size/sizeof(disk::nameid_hash_entry);
cout << num << (num == 1 ? " entry" : " entries") << endl;
int i = 0;
disk::nameid_hash_entry entry;
hash_values.seekg(0, ios_base::beg);
while(hash_values.read((char*)&entry, sizeof(entry)) != 0)
{
cout << "\t" << dec << setfill('0') << "[" << setw(4) << i++ << "] ";
pretty_print(entry);
cout << endl;
}
}
catch(key_not_found<prop_id>&)
{
// doesn't exist
cout << "Empty" << endl;
}
}
//
// dump out all the named props
//
// Bring it all together. Iterate over the entry stream again, this time
// fetching the proper values from the guid and the string streams.
guid_stream.clear();
guid_stream.seekg(0, ios_base::beg);
entry_stream.clear();
entry_stream.seekg(0, ios_base::beg);
sstream.clear();
sstream.seekg(0, ios_base::beg);
i = 0;
cout << endl << "Named Props: " << endl;
while(entry_stream.read((char*)&id, sizeof(id)) != 0)
{
// read the guid
if(disk::nameid_get_guid_index(id) == 0)
{
g = ps_none;
}
else if(disk::nameid_get_guid_index(id) == 1)
{
g = ps_mapi;
}
else if(disk::nameid_get_guid_index(id) == 2)
{
g = ps_public_strings;
}
else
{
// note how you need to subtract 3 from the guid index to account for the
// three predefined guids not stored in the guid stream
guid_stream.seekg((disk::nameid_get_guid_index(id) - 3) * sizeof(g), ios_base::beg);
guid_stream.read((char*)&g, sizeof(g));
}
cout << "Name Prop 0x" << hex << setw(4) << (0x8000 + disk::nameid_get_prop_index(id)) << endl;
cout << "\t" << dec << disk::nameid_get_guid_index(id) << ": ";
pretty_print(g, false);
cout << endl;
if(disk::nameid_is_string(id))
{
cout << "\tkind: string" << endl;
// read the string
sstream.seekg(id.string_offset, ios_base::beg);
sstream.read((char*)&size, sizeof(size));
if(buffer.size() < size)
buffer.resize(size);
sstream.read((char*)&buffer[0], size);
std::wstring val((wchar_t*)&buffer[0], (wchar_t*)&buffer[size]);
wcout << L"\tname: " << val << endl;
}
else
{
cout << "\tkind: id" << endl;
cout << "\tid: " << id.id << endl;
}
cout << endl;
}
}
| 33.296137 | 143 | 0.526811 | enrondata |
47d13181a98c2598e4a158028c34d03f36fd8823 | 1,036 | cpp | C++ | tests/helics/core/FilterFederateTests.cpp | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 31 | 2017-06-29T19:50:25.000Z | 2019-05-17T14:10:14.000Z | tests/helics/core/FilterFederateTests.cpp | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 511 | 2017-08-18T02:14:00.000Z | 2019-06-18T20:11:02.000Z | tests/helics/core/FilterFederateTests.cpp | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 11 | 2017-10-27T15:03:37.000Z | 2019-05-03T19:35:14.000Z | /*
Copyright (c) 2017-2022,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable
Energy, LLC. See the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "helics/core/FilterFederate.hpp"
#include "gtest/gtest.h"
#include <memory>
using namespace helics;
TEST(FilterFederateTests, constructor_test)
{
FilterFederate a(GlobalFederateId{23}, "name1", GlobalBrokerId{22342}, nullptr);
auto res = a.createFilter(GlobalBrokerId{}, InterfaceHandle{0}, "tey1", "", "", false);
EXPECT_NE(res, nullptr);
}
TEST(FilterFederateTests, constructor_test2)
{
auto a = std::make_unique<FilterFederate>(GlobalFederateId{23},
"name1",
GlobalBrokerId{22342},
nullptr);
auto res = a->createFilter(GlobalBrokerId{}, InterfaceHandle{0}, "tey1", "", "", false);
EXPECT_NE(res, nullptr);
}
| 34.533333 | 96 | 0.640927 | GMLC-TDC |
47d4584ca3bb595c6f631bc4e0efb3c1e688ab7d | 21,357 | cpp | C++ | cc/playground/sum_store-dir/FH_MicroTest.cpp | yangzheng2115/demofaster | 8968db65cf60a68f61c55e1e9becdbf226dc8d36 | [
"MIT"
] | null | null | null | cc/playground/sum_store-dir/FH_MicroTest.cpp | yangzheng2115/demofaster | 8968db65cf60a68f61c55e1e9becdbf226dc8d36 | [
"MIT"
] | null | null | null | cc/playground/sum_store-dir/FH_MicroTest.cpp | yangzheng2115/demofaster | 8968db65cf60a68f61c55e1e9becdbf226dc8d36 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <fstream>
#include <numa.h>
#include <experimental/filesystem>
#include "../../src/device/tracer.h"
#include <stdio.h>
#include <stdlib.h>
#include "../../src/core/faster.h"
#include "../../src/core/address.h"
#include "../../src/device/file_system_disk.h"
#include "../../src/device/null_disk.h"
#include "../../src/core/utility.h"
#define CONTEXT_TYPE 0
#if CONTEXT_TYPE == 0
#include "../../src/device/kvcontext.h"
#elif CONTEXT_TYPE == 2
#include "../../src/device/cvkvcontext.h"
#endif
#define ENABLE_NUMA 1
#define DEFAULT_THREAD_NUM (4)
#define DEFAULT_KEYS_COUNT (1 << 23)
#define DEFAULT_KEYS_RANGE (1 << 30)
#define DEFAULT_STR_LENGTH 256
//#define DEFAULT_KEY_LENGTH 8
#define LOCAL_TYPE 1
bool reading = false;
bool parallellog = true;
#define DEFAULT_STORE_BASE 100000000LLU
using namespace FASTER::api;
using namespace FASTER::core;
using namespace FASTER::device;
using namespace FASTER::environment;
#ifdef _WIN32
typedef hreadPoolIoHandler handler_t;
#else
typedef QueueIoHandler handler_t;
#endif
typedef FileSystemDisk<handler_t, 1073741824ull> disk_t;
using store_t = FasterKv<Key, Value, disk_t>;
//using store_t = FasterKv<Key, Value, FASTER::io::NullDisk>;
size_t init_size = next_power_of_two(DEFAULT_STORE_BASE / 2);
store_t store{init_size, 17179869184, "storage"};
//FasterKv<Key, Value, FASTER::io::NullDisk> store{128, 1073741824, ""};
uint64_t *loads;
std::vector<uint64_t> *localloads;
#if CONTEXT_TYPE == 2
uint64_t *content;
#endif
long total_time;
uint64_t exists = 0;
uint64_t success = 0;
uint64_t failure = 0;
//uint64_t total_count = DEFAULT_KEYS_COUNT;
uint64_t total_count = 60000000;
uint64_t timer_range = default_timer_range;
uint64_t kCheckpointInterval = 1 << 20;
uint64_t kRefreshInterval = 1 << 8;
uint64_t kCompletePendingInterval = 1 << 12;
Guid retoken;
int cd = 0;
int rounds = 0;
int thread_number = DEFAULT_THREAD_NUM;
//int key_range = DEFAULT_KEYS_RANGE;
int key_range = 1000000000;
stringstream *output;
atomic<int> stopMeasure(0);
struct target {
int tid;
uint64_t *insert;
store_t *store;
bool random;
bool firstround;
bool read;
};
pthread_t *workers;
struct target *parms;
void simpleInsert1() {
Tracer tracer;
tracer.startTime();
int inserted = 0;
int j = 0;
auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) {
if (result != Status::Ok) {
printf("Thread %" PRIu32 " reports checkpoint failed.\n",
Thread::id());
} else {
printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n",
Thread::id(), persistent_serial_num);
}
};
//store.StartSession();
for (uint64_t i = 0; i < total_count; i++) {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<UpsertContext> context{ctxt};
};
#if CONTEXT_TYPE == 0
UpsertContext context{i, i};
#elif CONTEXT_TYPE == 2
UpsertContext context(loads[i], 8);
context.reset((uint8_t *) (content + i));
#endif
Status stat = store.Upsert(context, callback, 1);
inserted++;
/*
if (i % kCompletePendingInterval == 0) {
store.CompletePending(false);
} else if (i % kRefreshInterval == 0) {
store.Refresh();
}
*/
}
//store.CompletePending(true);
// Deregister thread from FASTER
//store.StopSession();
cout << inserted << " " << tracer.getRunTime() << endl;
}
void simpleRead() {
uint64_t hit = 0;
uint64_t fail = 0;
for (uint64_t i = 0; i < total_count; i++) {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<ReadContext> context{ctxt};
};
ReadContext context{i};
if (i == 7931739)
int s = 0;
Status result = store.Read(context, callback, 1);
if (result == Status::Ok)
hit++;
else
fail++;
}
cout << hit << " " << fail << endl;
}
void simpleInsert() {
Tracer tracer;
tracer.startTime();
int inserted = 0;
int j = 0;
auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) {
if (result != Status::Ok) {
printf("Thread %" PRIu32 " reports checkpoint failed.\n",
Thread::id());
} else {
printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n",
Thread::id(), persistent_serial_num);
}
};
store.StartSession();
for (int i = 0; i < total_count; i++) {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<UpsertContext> context{ctxt};
};
#if CONTEXT_TYPE == 0
UpsertContext context{loads[i], loads[i]};
#elif CONTEXT_TYPE == 2
UpsertContext context(loads[i], 8);
context.reset((uint8_t *) (content + i));
#endif
Status stat = store.Upsert(context, callback, 1);
inserted++;
if (i % kCheckpointInterval == 0 && i != 0 && j == 0) {
Guid token;
cout << "checkpoint start in" << i << endl;
if (store.Checkpoint(nullptr, hybrid_log_persistence_callback, token))
//if(store.CheckpointIndex(nullptr,token))
//if (store.CheckpointHybridLog(hybrid_log_persistence_callback, token))
//if(store.CheckpointIndex(nullptr,token))
{
if (j == 0)
printf("Calling Checkpoint(), token = %s\n", token.ToString().c_str());
j++;
}
}
if (i % kCompletePendingInterval == 0) {
store.CompletePending(false);
} else if (i % kRefreshInterval == 0) {
store.Refresh();
if (j == 1 && store.CheckpointCheck()) {
cout << i << endl;
cd = i;
break;
}
}
}
//store.CompletePending(true);
// Deregister thread from FASTER
store.StopSession();
cout << inserted << " " << tracer.getRunTime() << endl;
}
void RecoverAndTest(const Guid &index_token, const Guid &hybrid_log_token) {
uint32_t version;
uint64_t hit = 0;
uint64_t fail = 0;
std::vector<Guid> session_ids;
store.Recover(index_token, hybrid_log_token, version, session_ids);
cout << "recover successful" << endl;
for (uint64_t i = 0; i < total_count * 2; i++) {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<ReadContext> context{ctxt};
};
#if CONTEXT_TYPE == 0
ReadContext context{i};
Status result = store.Read(context, callback, 1);
if (result == Status::Ok)
hit++;
else
fail++;
#elif CONTEXT_TYPE == 2
ReadContext context(loads[i]);
Status result = store.Read(context, callback, 1);
if (result == Status::Ok && *(uint64_t *) (context.output_bytes) == total_count - loads[i])
hit++;
else
fail++;
#endif
}
cout << hit << " " << fail << endl;
}
void *checkWorker(void *args) {
int inserted = 0;
int j = 0;
struct target *work = (struct target *) args;
int k = work->tid;
auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) {
if (result != Status::Ok) {
printf("Thread %" PRIu32 " reports checkpoint failed.\n",
Thread::id());
} else {
printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n",
Thread::id(), persistent_serial_num);
}
};
store.StartSession();
s:
for (uint64_t i = 0; i < total_count * 2; i++) {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<UpsertContext> context{ctxt};
};
#if CONTEXT_TYPE == 0
UpsertContext context{i, i};
#elif CONTEXT_TYPE == 2
UpsertContext context(loads[i], 8);
context.reset((uint8_t *) (content + i));
#endif
store.Refresh1();
//Status stat = store.Upsert(context, callback, i);
Status stat = store.UpsertT(context, callback, i, parallellog ? thread_number : 1);
inserted++;
int excepcted = 0;
if (i % kCheckpointInterval == 0 && i != 0 && stopMeasure.compare_exchange_strong(excepcted, 1)) {
Guid token;
cout << "checkpoint start in" << i << endl;
//if (store.CheckpointHybridLog(hybrid_log_persistence_callback, token))
if (store.Checkpoint(nullptr, hybrid_log_persistence_callback, token))
// if(store.CheckpointIndex(nullptr, token))
{
printf("Calling Checkpoint(), token = %s\n", token.ToString().c_str());
cout << "thread id" << k << endl;
}
}
if (i % kCompletePendingInterval == 0) {
store.CompletePending(false);
} else if (i % kRefreshInterval == 0) {
store.Refresh2();
if (stopMeasure.load() == 1 && store.CheckpointCheck()) {
//cout <<"thread id:"<<k<<" end in"<< i << endl;
j++;
if (j == 10) {
j = i;
break;
}
}
}
}
if (!store.CheckpointCheck()) {
cout << work->tid << "fail" << endl;
goto s;
}
//store.CompletePending(true);
store.StopSession();
//output[work->tid] << work->tid << " " << j << endl;
}
void *gcWorker(void *args) {
int inserted = 0;
int j = 0;
struct target *work = (struct target *) args;
int k = work->tid;
store.StartSession();
s:
for (uint64_t i = total_count; i < total_count * 2; i++) {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<UpsertContext> context{ctxt};
};
#if CONTEXT_TYPE == 0
UpsertContext context{i, i};
//UpsertContext context{0, 0};
#elif CONTEXT_TYPE == 2
UpsertContext context(loads[i], 8);
context.reset((uint8_t *) (content + i));
#endif
store.Refresh1();
//Status stat = store.Upsert(context, callback, i);
Status stat = store.UpsertT(context, callback, i, parallellog ? thread_number : 1);
inserted++;
int excepcted = 0;
if (i % kCheckpointInterval == 0 && i != 0 && stopMeasure.compare_exchange_strong(excepcted, 1)) {
Address a;
//if (store.CheckpointHybridLog(hybrid_log_persistence_callback, token))
if (store.GrabageCollecton(a, nullptr, nullptr)) {
cout << "garbage collection begin" << endl;
}
}
if (i % kCompletePendingInterval == 0) {
store.CompletePending(false);
} else if (i % kRefreshInterval == 0) {
store.Refresh2();
if (stopMeasure.load() == 1 && store.Gcflag)
break;
}
}
//store.CompletePending(true);
store.StopSession();
//output[work->tid] << work->tid << " " << j << endl;
}
void multiPoints() {
output = new stringstream[thread_number];
for (int i = 0; i < thread_number; i++) {
pthread_create(&workers[i], nullptr, checkWorker, &parms[i]);
}
for (int i = 0; i < thread_number; i++) {
pthread_join(workers[i], nullptr);
// string outstr = output[i].str();
//cout << outstr;
}
cout << "checkpoint done ..." << endl;
}
void GC() {
output = new stringstream[thread_number];
for (int i = 0; i < thread_number; i++) {
pthread_create(&workers[i], nullptr, gcWorker, &parms[i]);
}
for (int i = 0; i < thread_number; i++) {
pthread_join(workers[i], nullptr);
// string outstr = output[i].str();
//cout << outstr;
}
cout << "garbage collection done ..." << endl;
}
void Permutate() {
for (size_t k = 0; k < thread_number; k++) {
std::random_shuffle(loads + (k) * total_count / thread_number, loads + (k + 1) * total_count / thread_number);
}
}
void *measureWorker(void *args) {
Tracer tracer;
tracer.startTime();
struct target *work = (struct target *) args;
uint64_t hit = 0;
uint64_t fail = 0;
long elipsed;
uint64_t k = work->tid;
auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) {
if (result != Status::Ok) {
printf("Thread %" PRIu32 " reports checkpoint failed.\n",
Thread::id());
} else {
printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n",
Thread::id(), persistent_serial_num);
}
};
store.StartSession();
// while (stopMeasure.load(memory_order_relaxed) == 0) {
#if LOCAL_TYPE == 0
for (uint64_t i = (k) * total_count / thread_number; i < (k + 1) * total_count / thread_number; i++) {
#elif LOCAL_TYPE == 1
for (uint64_t i = 0; i < localloads[k].size(); i++) {
#endif
if (!work->firstround && work->read) {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<ReadContext> context{ctxt};
};
#if CONTEXT_TYPE == 0
uint64_t load;
#if LOCAL_TYPE == 0
load=loads[i];
#elif LOCAL_TYPE == 1
load = localloads[k][i];
#endif
ReadContext context{load};
//ReadContext context{(i + startoff) % total_count};
Status result = store.Read(context, callback, 1);
if (result == Status::Ok)
hit++;
else
fail++;
#elif CONTEXT_TYPE == 2
ReadContext context(loads[i]);
Status result = store.Read(context, callback, 1);
if (result == Status::Ok && *(uint64_t *) (context.output_bytes) == total_count - loads[i])
hit++;
else
fail++;
#endif
} else {
auto callback = [](IAsyncContext *ctxt, Status result) {
CallbackContext<UpsertContext> context{ctxt};
};
uint64_t load;
#if LOCAL_TYPE == 0
if (work->firstround) load = i;
else load = loads[i];
#elif LOCAL_TYPE == 1
load = localloads[k][i];
#endif
#if CONTEXT_TYPE == 0
UpsertContext context{load, load};
//UpsertContext context{(i + startoff) % total_count, (i + startoff) % total_count};
#elif CONTEXT_TYPE == 2
UpsertContext context(loads[i], 8);
context.reset((uint8_t *) (content + i));
#endif
//Status stat = store.Upsert(context, callback, 1);
Status stat = store.UpsertT(context, callback, 1, parallellog ? thread_number : 1);
if (stat == Status::NotFound)
fail++;
else
hit++;
}
/*
if (i % kCompletePendingInterval == 0) {
store.CompletePending(false);
} else if (i % kRefreshInterval == 0) {
store.Refresh();
}
if (i % kCheckpointInterval == 0) {
Guid token;
if (store.Checkpoint(nullptr, hybrid_log_persistence_callback, token))
printf("Thread= %d Calling Checkpoint(), token = %s\n", work->tid, token.ToString().c_str());
}
*/
}
// }
store.StopSession();
//long elipsed;
elipsed = tracer.getRunTime();
output[work->tid] << work->tid << " " << elipsed << " " << hit << endl;
__sync_fetch_and_add(&total_time, elipsed);
__sync_fetch_and_add(&success, hit);
__sync_fetch_and_add(&failure, fail);
}
void prepare() {
cout << "prepare" << endl;
workers = new pthread_t[thread_number];
parms = new struct target[thread_number];
output = new stringstream[thread_number];
for (uint64_t i = 0; i < thread_number; i++) {
parms[i].tid = i;
parms[i].store = &store;
parms[i].insert = (uint64_t *) calloc(total_count / thread_number, sizeof(uint64_t *));
char buf[DEFAULT_STR_LENGTH];
for (int j = 0; j < total_count / thread_number; j++) {
std::sprintf(buf, "%d", i + j * thread_number);
parms[i].insert[j] = j;
}
}
#if CONTEXT_TYPE == 2
content = new uint64_t[total_count];
for (long i = 0; i < total_count; i++) {
content[i] = total_count - loads[i];
}
#endif
}
void finish() {
cout << "finish" << endl;
for (int i = 0; i < thread_number; i++) {
delete[] parms[i].insert;
}
delete[] parms;
delete[] workers;
delete[] output;
#if CONTEXT_TYPE == 2
delete[] content;
#endif
}
void multiWorkers(bool random, bool read, bool firstround = false) {
output = new stringstream[thread_number];
#if ENABLE_NUMA == 1
int num_cpus = numa_num_task_cpus();
int num_sock = numa_max_node() + 1;
numa_set_localalloc();
#endif
Tracer tracer;
tracer.startTime();
/*
for (int i = 0; i < thread_number; i++) {
pthread_create(&workers[i], nullptr, insertWorker, &parms[i]);
}
for (int i = 0; i < thread_number; i++) {
pthread_join(workers[i], nullptr);
}
cout << "Insert " << exists << " " << tracer.getRunTime() << endl;
*/
Timer timer;
timer.start();
for (int i = 0; i < thread_number; i++) {
parms[i].random = random;
parms[i].firstround = firstround;
parms[i].read = read;
pthread_create(&workers[i], nullptr, measureWorker, &parms[i]);
#if ENABLE_NUMA == 1
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
int group_threads = thread_number / num_sock;
int group_cores = num_cpus / num_sock;
CPU_SET(i / group_threads * group_cores + i % group_threads, &cpuset);
pthread_setaffinity_np(workers[i], sizeof(cpu_set_t), &cpuset);
#endif
}
//while (timer.elapsedSeconds() < timer_range) {
// sleep(1);
// }
// stopMeasure.store(1, memory_order_relaxed);
for (int i = 0; i < thread_number; i++) {
pthread_join(workers[i], nullptr);
string outstr = output[i].str();
cout << outstr;
}
cout << "Gathering ..." << endl;
}
int main(int argc, char **argv) {
if (argc > 6) {
thread_number = std::atol(argv[1]);
key_range = std::atol(argv[2]);
total_count = std::atol(argv[3]);
rounds = std::atol(argv[4]);
reading = (std::atoi(argv[5]) == 1 ? true : false);
parallellog = (std::atoi(argv[6]) == 1 ? true : false);
}
cout << " threads: " << thread_number << " range: " << key_range << " count: " << total_count << " time: "
<< timer_range << " reading: " << reading << " parallellog: " << parallellog << endl;
loads = (uint64_t *) calloc(total_count, sizeof(uint64_t));
for (int i = 0; i < total_count; i++) loads[i] = i;
localloads = new std::vector<uint64_t>[thread_number];
for (int i = 0; i < total_count; i++) {
uint64_t hash = Utility::GetHashCode(loads[i]);
hash = hash % init_size;
uint64_t lid = hash / (init_size / thread_number);
localloads[lid].push_back(loads[i]);
}
Permutate();
//UniformGen<uint64_t>::generate(loads, key_range, total_count);
prepare();
if (argc > 7) {
//string str= reinterpret_cast<const char *>(std::atol(argv[5]));
Guid token = Guid::Parse(argv[7]);
RecoverAndTest(token, token);
goto y;
}
// simpleInsert();
cout << "multiinsert" << endl;
multiWorkers(false, false, true);
cout << "operations: " << success << " failure: " << failure << " throughput: "
<< (double) (success + failure) * thread_number / total_time << endl;
//cout << "simple read" << endl;
//simpleRead();
//cout << "simple read" << endl;
//simpleRead();
//cout<<"simple insert"<<endl;
//simpleInsert1();
//cout << "simple read" << endl;
//simpleRead();
#if LOCAL_TYPE == 1
for (size_t k = 0; k < thread_number; k++) {
std::random_shuffle(localloads[k].begin(), localloads[k].end());
}
#endif
for (int i = 0; i < rounds; i++) {
//stopMeasure.store(0);
//multiPoints();
//RecoverAndTest(retoken, retoken);
// Populate();
cout << "after checkpoint multiinsert" << endl;
success = 0;
failure = 0;
total_time = 0;
multiWorkers(false, false);
cout << "operations: " << success << " failure: " << failure << " throughput: "
<< (double) (success + failure) * thread_number / total_time << endl;
success = 0;
failure = 0;
total_time = 0;
cout << "multiinsert" << endl;
multiWorkers(true, reading);
cout << "operations: " << success << " failure: " << failure << " throughput: "
<< (double) (success + failure) * thread_number / total_time << endl;
stopMeasure.store(0);
Tracer tra;
tra.startTime();
//GC();
//cout << tra.getRunTime() << endl;
}
//stopMeasure.store(0);
//GC();
//cout << "simple read" << endl;
//simpleRead();
y:
free(loads);
finish();
return 0;
}
| 31.923767 | 118 | 0.565576 | yangzheng2115 |
47d65eeb0c3253b89dcdee21b395e44f7dd9baf0 | 12,056 | cpp | C++ | dev/Code/CryEngine/CryAISystem/Cover/EntityCoverSampler.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/CryEngine/CryAISystem/Cover/EntityCoverSampler.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/CryEngine/CryAISystem/Cover/EntityCoverSampler.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "EntityCoverSampler.h"
#include "CoverSystem.h"
#include "DebugDrawContext.h"
EntityCoverSampler::EntityCoverSampler()
: m_sampler(0)
, m_currentSide(Left)
, m_lastSort(0ll)
{
}
EntityCoverSampler::~EntityCoverSampler()
{
if (m_sampler)
{
m_sampler->Release();
}
m_sampler = 0;
}
void EntityCoverSampler::Clear()
{
m_queue.clear();
m_lastSort.SetValue(0ll);
}
void EntityCoverSampler::Queue(EntityId entityID, const Callback& callback)
{
m_queue.push_back(QueuedEntity(entityID, callback));
}
void EntityCoverSampler::Cancel(EntityId entityID)
{
if (!m_queue.empty())
{
QueuedEntities::iterator it = m_queue.begin();
QueuedEntities::iterator end = m_queue.end();
if (entityID == m_queue.front().entityID)
{
m_queue.pop_front();
}
else
{
for (; it != end; ++it)
{
QueuedEntity& queued = *it;
if (queued.entityID == entityID)
{
m_queue.erase(it);
break;
}
}
}
}
}
void EntityCoverSampler::Update()
{
FUNCTION_PROFILER(gEnv->pSystem, PROFILE_AI);
CTimeValue now = gEnv->pTimer->GetFrameStartTime();
while (!m_queue.empty())
{
if ((now - m_lastSort).GetMilliSecondsAsInt64() > 1250)
{
if (CAIObject* player = GetAISystem()->GetPlayer())
{
Vec3 center = player->GetPos();
QueuedEntities::iterator it = m_queue.begin();
QueuedEntities::iterator end = m_queue.end();
for (; it != end; ++it)
{
QueuedEntity& queued = *it;
if (IEntity* entity = gEnv->pEntitySystem->GetEntity(queued.entityID))
{
queued.distanceSq = (center - entity->GetWorldPos()).GetLengthSquared2D();
}
else
{
queued.distanceSq = FLT_MAX;
}
}
if (m_queue.front().state != QueuedEntity::Queued)
{
std::sort(m_queue.begin() + 1, m_queue.end(), QueuedEntitySorter());
}
else
{
std::sort(m_queue.begin(), m_queue.end(), QueuedEntitySorter());
}
m_lastSort = now;
}
}
QueuedEntity& queued = m_queue.front();
if (!m_sampler)
{
m_sampler = gAIEnv.pCoverSystem->CreateCoverSampler("Default");
}
assert(m_sampler);
IEntity* entity = gEnv->pEntitySystem->GetEntity(queued.entityID);
assert(entity);
if (queued.state == QueuedEntity::Queued)
{
if (IPhysicalEntity* physicalEntity = entity->GetPhysics())
{
pe_status_nparts nparts;
if (int partCount = physicalEntity->GetStatus(&nparts))
{
AABB localBB(AABB::RESET);
pe_status_pos pp;
primitives::box box;
for (int p = 0; p < partCount; ++p)
{
pp.ipart = p;
pp.flags = status_local;
if (physicalEntity->GetStatus(&pp))
{
if (IGeometry* geometry = pp.pGeomProxy ? pp.pGeomProxy : pp.pGeom)
{
geometry->GetBBox(&box);
Vec3 center = box.center * pp.scale;
Vec3 size = box.size * pp.scale;
center = pp.pos + pp.q * center;
Matrix33 orientationTM = Matrix33(pp.q) * box.Basis.GetTransposed();
localBB.Add(center + orientationTM * Vec3(size.x, size.y, size.z));
localBB.Add(center + orientationTM * Vec3(size.x, size.y, -size.z));
localBB.Add(center + orientationTM * Vec3(size.x, -size.y, size.z));
localBB.Add(center + orientationTM * Vec3(size.x, -size.y, -size.z));
localBB.Add(center + orientationTM * Vec3(-size.x, size.y, size.z));
localBB.Add(center + orientationTM * Vec3(-size.x, size.y, -size.z));
localBB.Add(center + orientationTM * Vec3(-size.x, -size.y, size.z));
localBB.Add(center + orientationTM * Vec3(-size.x, -size.y, -size.z));
}
}
}
Matrix34 worldTM = entity->GetWorldTM();
m_obb = OBB::CreateOBBfromAABB(Matrix33(worldTM), localBB);
float upSign = fsgnf(worldTM.GetColumn2().dot(CoverUp));
m_params.position = worldTM.GetTranslation() + m_obb.m33.TransformVector(m_obb.c) +
(m_obb.m33.GetColumn0() * -m_obb.h.x * upSign) + m_obb.m33.GetColumn2() * -m_obb.h.z * upSign;
Vec3 dir = m_obb.m33.GetColumn0() * upSign;
dir.z = 0.0f;
dir.normalize();
m_params.referenceEntity = entity;
m_params.heightSamplerInterval = 0.25f;
m_params.widthSamplerInterval = 0.25f;
m_params.heightAccuracy = 0.125f;
m_params.limitDepth = 0.5f;
m_params.maxStartHeight = m_params.minHeight;
m_params.maxCurvatureAngleCos = 0.087f; // 85
m_params.limitHeight = m_obb.h.z * 2.125f;
m_params.limitLeft = m_obb.h.y * 1.075f;
m_params.limitRight = m_obb.h.y * 1.075f;
m_params.direction = dir;
m_currentSide = Left;
m_sampler->StartSampling(m_params);
queued.state = QueuedEntity::SamplingLeft;
break;
}
}
// nothing to sample
if (queued.callback)
{
queued.callback(queued.entityID, LastSide, ICoverSystem::SurfaceInfo());
}
m_queue.pop_front();
continue;
}
ICoverSampler::ESamplerState state = m_sampler->Update(0.00025f);
if (gAIEnv.CVars.DebugDrawDynamicCoverSampler)
{
m_sampler->DebugDraw();
}
if (state != ICoverSampler::InProgress)
{
ICoverSystem::SurfaceInfo surfaceInfo;
if (state == ICoverSampler::Finished)
{
surfaceInfo.flags = m_sampler->GetSurfaceFlags();
surfaceInfo.samples = m_sampler->GetSamples();
surfaceInfo.sampleCount = m_sampler->GetSampleCount();
}
if (queued.callback)
{
queued.callback(queued.entityID, (ESide)m_currentSide, surfaceInfo);
}
if (++m_currentSide > LastSide)
{
m_queue.pop_front();
}
else
{
Matrix34 worldTM = entity->GetWorldTM();
float upSign = fsgnf(worldTM.GetColumn2().dot(CoverUp));
switch (m_currentSide)
{
case Right:
{
queued.state = QueuedEntity::SamplingRight;
m_params.position = worldTM.GetTranslation() + m_obb.m33.TransformVector(m_obb.c) +
(m_obb.m33.GetColumn0() * m_obb.h.x * upSign) + m_obb.m33.GetColumn2() * -m_obb.h.z * upSign;
m_params.direction = -m_params.direction;
m_sampler->StartSampling(m_params);
}
break;
case Front:
{
queued.state = QueuedEntity::SamplingFront;
m_params.position = worldTM.GetTranslation() + m_obb.m33.TransformVector(m_obb.c) +
(m_obb.m33.GetColumn1() * m_obb.h.y * upSign) + m_obb.m33.GetColumn2() * -m_obb.h.z * upSign;
/*
FrancescoR: Switching -upSign with (-1 * upSign) to break a Visual Studio 2010
assembly optimization that causes a crash in Profile|64 (It looks to be a compiler bug)
*/
Vec3 dir = -1 * upSign * m_obb.m33.GetColumn1();
dir.z = 0.0f;
dir.normalize();
m_params.limitHeight = m_obb.h.z * 2.125f;
m_params.limitLeft = m_obb.h.x * 1.075f;
m_params.limitRight = m_obb.h.x * 1.075f;
m_params.direction = dir;
m_sampler->StartSampling(m_params);
}
break;
case Back:
{
queued.state = QueuedEntity::SamplingBack;
m_params.position = worldTM.GetTranslation() + m_obb.m33.TransformVector(m_obb.c) +
(m_obb.m33.GetColumn1() * -m_obb.h.y * upSign) + m_obb.m33.GetColumn2() * -m_obb.h.z * upSign;
m_params.direction = -m_params.direction;
m_sampler->StartSampling(m_params);
}
break;
}
}
}
break;
}
if (gAIEnv.CVars.DebugDrawDynamicCoverSampler)
{
DebugDraw();
}
}
void EntityCoverSampler::DebugDraw()
{
CDebugDrawContext dc;
const float fontSize = 1.25f;
const float lineHeight = 11.0f;
float y = 30.0f;
dc->Draw2dLabel(10.0f, y, 1.45f, m_queue.empty() ? Col_DarkGray : Col_DarkSlateBlue, false,
"Entity Cover Sampler Queue (%" PRISIZE_T ")", m_queue.size());
y += lineHeight * 1.45f;
QueuedEntities::const_iterator it = m_queue.begin();
QueuedEntities::const_iterator end = m_queue.end();
for (; it != end; ++it)
{
const QueuedEntity& queued = *it;
const char* side = 0;
const char* name = "<invalid>";
if (IEntity* entity = gEnv->pEntitySystem->GetEntity(queued.entityID))
{
name = entity->GetName();
}
if (queued.state == QueuedEntity::Queued)
{
dc->Draw2dLabel(10.0f, y, 1.25f, Col_Gray, false, "%s", name);
}
else
{
switch (queued.state)
{
case QueuedEntity::SamplingLeft:
side = "left";
break;
case QueuedEntity::SamplingRight:
side = "right";
break;
case QueuedEntity::SamplingFront:
side = "front";
break;
case QueuedEntity::SamplingBack:
side = "back";
break;
default:
assert(0);
break;
}
dc->Draw2dLabel(10.0f, y, 1.25f, Col_BlueViolet, false, "%s: %s", name, side);
}
y += lineHeight * fontSize;
}
}
| 32.76087 | 118 | 0.492618 | crazyskateface |
47d7ca270d873f86db4cc6a614f4d6c07bfd46dc | 536 | cpp | C++ | 0402-Remove K Digits/0402-Remove K Digits.cpp | zhuangli1987/LeetCode-1 | e81788abf9e95e575140f32a58fe983abc97fa4a | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 0401-0500/0402-Remove K Digits/0402-Remove K Digits.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 0401-0500/0402-Remove K Digits/0402-Remove K Digits.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class Solution {
public:
string removeKdigits(string num, int k) {
string result;
vector<char> St;
for (int i : num) {
while (!St.empty() && i < St.back() && k) {
St.pop_back();
--k;
}
St.push_back(i);
}
for (int i = 0; i < St.size() - k; ++i) {
if (result.size() || St[i] != '0') {
result += St[i];
}
}
return result.size() ? result : "0";
}
};
| 23.304348 | 55 | 0.360075 | zhuangli1987 |
c51363e83136d67b82ce6d7ef937ed8359e3b71b | 1,018 | cpp | C++ | c/template/Template_Reverse.cpp | WeAreChampion/notes | 6c0f726d1003e5083d9cf1b75ac6905dc1c19c07 | [
"Apache-2.0"
] | 2 | 2018-11-17T15:36:00.000Z | 2022-03-16T09:01:16.000Z | c/template/Template_Reverse.cpp | WeAreChampion/notes | 6c0f726d1003e5083d9cf1b75ac6905dc1c19c07 | [
"Apache-2.0"
] | null | null | null | c/template/Template_Reverse.cpp | WeAreChampion/notes | 6c0f726d1003e5083d9cf1b75ac6905dc1c19c07 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
template<class Type>
void Reverse(Type array[], int length) {
for(int i = 0; i < length / 2; i++) {
Type temp;
temp = array[i];
array[i] = array[length - 1 - i];
array[length - 1 - i] = temp;
}
}
template<class Type>
void Reverse(Type array[], int start, int end) {
for(int i = start; i <= (end + start) / 2; i++) {
Type temp = array[i];
array[i] = array[start + end - i];
array[start + end - i] = temp;
}
}
template<class Type>
void DispArray(Type array[], int length) {
for(int i = 0; i < length; i++) {
cout<<array[i]<<" ";
}
cout<<endl;
}
void Test()
{
int length = 5;
int array1[] = {1, 2, 3, 4, 5};
Reverse(array1, length);
DispArray(array1, length);
float array2[] = {1.1, 2.1, 3.1, 4.1, 5.1};
Reverse(array2, length);
DispArray(array2, length);
double array3[] = {1.11, 2.11, 3.11, 4.11, 5.11};
Reverse(array3, length);
DispArray(array3, length);
Reverse(array3, 1, 4);
DispArray(array3, length);
}
int main()
{
Test();
return 0;
} | 22.130435 | 50 | 0.600196 | WeAreChampion |
c5149b1ab96144b9c0660b342b4cf0bb4b3ada12 | 19,329 | cpp | C++ | src/freeSurface.cpp | krenzland/FreeSurfaceLBM | 5619edcf318623c3a4feac478db66663687bca94 | [
"MIT"
] | 8 | 2017-12-12T19:39:29.000Z | 2022-02-03T13:37:53.000Z | src/freeSurface.cpp | krenzland/FreeSurfaceLBM | 5619edcf318623c3a4feac478db66663687bca94 | [
"MIT"
] | 1 | 2020-07-23T13:51:06.000Z | 2020-07-23T20:16:56.000Z | src/freeSurface.cpp | krenzland/FreeSurfaceLBM | 5619edcf318623c3a4feac478db66663687bca94 | [
"MIT"
] | 3 | 2019-05-09T07:50:48.000Z | 2020-11-05T12:28:43.000Z | #include "freeSurface.hpp"
#include <iostream>
#include <numeric>
double computeFluidFraction(const std::vector<double> &fluidFraction, const std::vector<flag_t> &flags, int idx,
const std::vector<double> &mass) {
if (flags[idx] == flag_t::EMPTY) {
return 0.0;
} else if (flags[idx] == flag_t::INTERFACE) {
const double vof = fluidFraction[idx];
// in some cases it can be negative or larger than 1, e.g. if the cell is recently filled.
return std::min(1.0, std::max(0.0, vof));
} else {
return 1.0;
}
}
std::array<double, 3> computeSurfaceNormal(const std::vector<double> &fluidFraction, const coord_t &length, const std::vector<double> &mass,
const coord_t &position, const std::vector<flag_t> &flags) {
auto normal = std::array<double, 3>();
// We approximate the surface normal element-wise using central-differences of the fluid
// fraction gradient.
for (size_t dim = 0; dim < normal.size(); ++dim) {
coord_t curPosition = position;
// We need the next and previous neighbour for dimension dim.
curPosition[dim]++;
const auto nextNeighbour = indexForCell(curPosition, length);
curPosition[dim] -= 2;
const auto prevNeighbour = indexForCell(curPosition, length);
const double plusFluidFraction = computeFluidFraction(fluidFraction, flags, nextNeighbour, mass);
const double minusFluidFraction = computeFluidFraction(fluidFraction, flags, prevNeighbour, mass);
normal[dim] = 0.5 * (minusFluidFraction - plusFluidFraction);
}
return normal;
}
void streamMass(const std::vector<double> &distributions, std::vector<double> &fluidFraction, const coord_t &length,
std::vector<double> &mass, const std::vector<neighborhood_t> &neighborhood,
const std::vector<flag_t> &flags) {
#pragma omp parallel for schedule(static)
for (int z = 0; z < length[2] + 2; ++z) {
for (int y = 0; y < length[1] + 2; ++y) {
for (int x = 0; x < length[0] + 2; ++x) {
double deltaMass = 0.0;
const coord_t curCell = coord_t{x, y, z};
const int flagIndex = indexForCell(curCell, length);
// We only consider the mass going into interface cells.
// Empty cells have zero mass, full cells have mass 1.
if (flags[flagIndex] != flag_t::INTERFACE)
continue;
const int fieldIndex = flagIndex * Q;
const double curFluidFraction =
computeFluidFraction(fluidFraction, flags, flagIndex, mass);
for (int i = 0; i < Q; ++i) {
const auto &vel = LATTICEVELOCITIES[i];
const auto neighCell = coord_t{x + vel[0], y + vel[1], z + vel[2]};
const auto neighFlag = indexForCell(neighCell, length);
const auto neighField = neighFlag * Q;
if (neighFlag == flagIndex)
continue;
if (flags[neighFlag] == flag_t::FLUID) {
// Exchange interface and fluid at x + \Delta t e_i (eq. 4.2)
deltaMass += distributions[neighField + inverseVelocityIndex(i)] -
distributions[fieldIndex + i];
} else if (flags[neighFlag] == flag_t::INTERFACE) {
const double neighFluidFraction =
computeFluidFraction(fluidFraction, flags, neighFlag, mass);
// Exchange interface and interface at x + \Delta t e_i (eq. 4.2)
const double s_e =
calculateSE(distributions, flags, curCell, length, i, neighborhood);
deltaMass += s_e * 0.5 * (curFluidFraction + neighFluidFraction);
}
}
mass[flagIndex] += deltaMass; // (eq. 4.4)
}
}
}
}
double calculateSE(const std::vector<double> &distributions, const std::vector<flag_t> &flags,
const coord_t &coord, const coord_t &length, const int curFiIndex,
const std::vector<neighborhood_t> &neighborhood) {
// Returns a slightly different mass exchange depending on the neighbourhood of the cells.
// This reduces the amount of abandoned interface cells.
const auto &vel = LATTICEVELOCITIES[curFiIndex];
const auto neigh = coord_t{coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]};
const int curFlag = indexForCell(coord, length);
const int neighFlag = indexForCell(neigh, length);
const int curCell = curFlag * Q;
const int neighCell = neighFlag * Q;
const int inv = inverseVelocityIndex(curFiIndex);
if (neighborhood[curFlag] == neighborhood[neighFlag]) {
return distributions[neighCell + inv] - distributions[curCell + curFiIndex];
}
if ((neighborhood[neighFlag] == neighborhood_t::STANDARD &&
neighborhood[curFlag] == neighborhood_t::NO_FLUID_NEIGHBORS) ||
(neighborhood[neighFlag] == neighborhood_t::NO_EMPTY_NEIGHBORS &&
(neighborhood[curFlag] == neighborhood_t::STANDARD ||
neighborhood[curFlag] == neighborhood_t::NO_FLUID_NEIGHBORS))) {
return -distributions[curCell + curFiIndex];
}
// Otherwise: (neigh == STANDARD && cur = NO_EMPTY) || (neigh = NO_FLUID && (cur = STANDARD ||
// cur NO_EMPTY)
return distributions[neighCell + inv];
}
void getPotentialUpdates(const std::vector<double> &mass, std::vector<double> &fluidFraction, std::vector<flag_t> &flags,
std::vector<neighborhood_t> &neighborhood, const coord_t &length) {
// Check whether we have to convert the interface to an emptied or fluid cell.
// Doesn't actually update the flags but pushes them to a queue.
// We do this here so we do not have to calculate the density again.
// Offset avoids periodically switching between filled and empty status.
const double offset = 10e-3;
#pragma omp parallel for schedule(guided)
for (int z = 0; z < length[2] + 2; ++z) {
for (int y = 0; y < length[1] + 2; ++y) {
for (int x = 0; x < length[0] + 2; ++x) {
auto coord = coord_t{x, y, z};
const int flagIndex = indexForCell(coord, length);
if (flags[flagIndex] != flag_t::INTERFACE)
continue;
// Eq. 4.7
double curDensity;
if (fluidFraction[flagIndex] != 0.0) {
curDensity = mass[flagIndex] / fluidFraction[flagIndex];
} else {
curDensity = 0.0;
}
if (mass[flagIndex] > (1 + offset) * curDensity) {
flags[flagIndex] = flag_t::INTERFACE_TO_FLUID;
} else if (mass[flagIndex] < -offset * curDensity) {
// Emptied
flags[flagIndex] = flag_t::INTERFACE_TO_EMPTY;
}
if (neighborhood[flagIndex] == neighborhood_t::NO_FLUID_NEIGHBORS &&
mass[flagIndex] < (0.1 * curDensity)) {
flags[flagIndex] = flag_t::INTERFACE_TO_EMPTY;
}
if (neighborhood[flagIndex] == neighborhood_t::NO_EMPTY_NEIGHBORS &&
mass[flagIndex] > (0.9 * curDensity)) {
flags[flagIndex] = flag_t::INTERFACE_TO_FLUID;
}
}
}
}
}
void interpolateEmptyCell(std::vector<double> &distributions, std::vector<double> &mass, std::vector<double> &fluidFraction,
const coord_t &coord, const coord_t &length, const std::vector<flag_t> &flags) {
// Note: We only interpolate cells that are not emptied cells themselves!
const int flagIndex = indexForCell(coord, length);
const int cellIndex = flagIndex * Q;
int numNeighs = 0;
double avgDensity = 0.0;
auto avgVel = std::array<double, 3>{};
for (int i = 0; i < Q; ++i) {
const auto &vel = LATTICEVELOCITIES[i];
const auto neigh = coord_t{coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]};
const int neighFlagIndex = indexForCell(neigh, length);
if (neighFlagIndex == flagIndex)
continue; // Ignore current cell!
// Don't interpolate cells that are emptied or filled.
if (flags[neighFlagIndex] == flag_t::FLUID || flags[neighFlagIndex] == flag_t::INTERFACE ||
flags[neighFlagIndex] == flag_t::INTERFACE_TO_FLUID) {
const int neighDistrIndex = neighFlagIndex * Q;
const double neighDensity = computeDensity(&distributions[neighDistrIndex]);
std::array<double, 3> neighVelocity;
computeVelocity(&distributions[neighDistrIndex], neighDensity, neighVelocity.data());
++numNeighs;
avgDensity += neighDensity;
avgVel[0] += neighVelocity[0];
avgVel[1] += neighVelocity[1];
avgVel[2] += neighVelocity[2];
}
}
// Every former empty cell has at least one interface cell as neighbour, otherwise we have a
// worse problem than division by zero.
assert(numNeighs != 0);
avgDensity /= numNeighs;
avgVel[0] /= numNeighs;
avgVel[1] /= numNeighs;
avgVel[2] /= numNeighs;
fluidFraction[flagIndex] = mass[flagIndex] / avgDensity;
auto feq = std::array<double, 19>{};
computeFeq(avgDensity, avgVel.data(), feq.data());
for (int i = 0; i < Q; ++i) {
distributions[cellIndex + i] = feq[i];
}
}
void flagReinit(std::vector<double> &distributions, std::vector<double> &mass, std::vector<double> &fluidFraction,
const coord_t &length, std::vector<flag_t> &flags) {
// We set up the interface cells around all converted cells.
// It's very important to do this in a way such that the order of conversion doesn't matter.
// First set interface for all filled cells.
#pragma omp parallel for schedule(guided)
for (int z = 1; z < length[2] + 1; ++z) {
for (int y = 1; y < length[1] + 1; ++y) {
for (int x = 1; x < length[0] + 1; ++x) {
const int curFlag = indexForCell(x, y, z, length);
if (flags[curFlag] != flag_t::INTERFACE_TO_FLUID)
continue;
// Find all neighbours of this cell.
for (const auto &vel : LATTICEVELOCITIES) {
coord_t neighbor = {x, y, z};
neighbor[0] += vel[0];
neighbor[1] += vel[1];
neighbor[2] += vel[2];
const int neighFlag = indexForCell(neighbor, length);
if (curFlag == neighFlag)
continue;
// This neighbor is converted to an interface cell iff. it is an empty cell or a
// cell that would
// become an emptied cell.
// We need to remove it from the emptied set, otherwise we might have holes in
// the interface.
if (flags[neighFlag] == flag_t::EMPTY) {
flags[neighFlag] = flag_t::INTERFACE;
mass[neighFlag] = 0.0;
fluidFraction[neighFlag] = 0.0;
// Notice that the new interface cells don't have any valid distributions.
// They are initialised with f^{eq}_i (p_{avg}, v_{avg}), which are the
// average density and
// velocity of all neighbouring fluid and interface cells.
interpolateEmptyCell(distributions, mass, fluidFraction, neighbor, length,
flags);
} else if (flags[neighFlag] == flag_t::INTERFACE_TO_EMPTY) {
// Already is an interface but should not be converted to an empty cell
// later.
flags[neighFlag] = flag_t::INTERFACE;
}
}
}
}
}
// Now we can consider all filled cells!
#pragma omp parallel for schedule(guided)
for (int z = 1; z < length[2] + 1; ++z) {
for (int y = 1; y < length[1] + 1; ++y) {
for (int x = 1; x < length[0] + 1; ++x) {
const int curFlag = indexForCell(x, y, z, length);
// Find all neighbours of this cell.
if (flags[curFlag] != flag_t::INTERFACE_TO_EMPTY)
continue;
for (const auto &vel : LATTICEVELOCITIES) {
coord_t neighbor = {x, y, z};
neighbor[0] += vel[0];
neighbor[1] += vel[1];
neighbor[2] += vel[2];
const int neighFlag = indexForCell(neighbor, length);
if (curFlag == neighFlag)
continue;
// This neighbor is converted to an interface cell iff. it is an empty cell or a
// cell that would
// become an emptied cell.
// We need to remove it from the emptied set, otherwise we might have holes in
// the interface.
if (flags[neighFlag] == flag_t::FLUID) {
flags[neighFlag] = flag_t::INTERFACE;
mass[neighFlag] = computeDensity(&distributions[neighFlag * Q]);
fluidFraction[neighFlag] = 1.0;
// We can reuse the distributions as they are still valid.
}
}
}
}
}
}
enum class update_t { FILLED, EMPTIED };
void distributeSingleMass(const std::vector<double> &distributions, std::vector<double> &mass,
std::vector<double> &massChange, const coord_t &length, const coord_t &coord,
std::vector<flag_t> &flags, std::vector<double> &fluidFraction, const update_t &type) {
// First determine how much mass needs to be redistributed and fix mass of converted cell.
const int flagIndex = indexForCell(coord, length);
double excessMass;
const double density = computeDensity(&distributions[flagIndex * Q]);
if (type == update_t::FILLED) {
// Interface -> Full cell, filled cells have mass and should have a mass equal to their
// density.
excessMass = mass[flagIndex] - density;
#pragma omp atomic
massChange[flagIndex] -= excessMass;
} else {
// Interface -> Empty cell, empty cells should not have any mass so all mass is excess mass.
excessMass = mass[flagIndex];
#pragma omp atomic
massChange[flagIndex] -= excessMass;
}
/* The distribution of excess mass is surprisingly non-trivial.
For a more detailed description, refer to pages 32f. of Thürey's thesis but here's the gist:
We do not distribute the mass uniformly to all neighbouring interface cells but rather
correct for balance.
The reason for this is that the fluid interface moved beyond the current cell.
We rebalance things by weighting the mass updates according to the direction of the interface
normal.
This has to be done in two steps, we first calculate all updated weights, normalize them and
then, in a second step, update the weights.*/
// Step 1: Calculate the unnormalized weights.
const auto normal = computeSurfaceNormal(fluidFraction, length, mass, coord, flags);
std::array<double, 19> weights{};
std::array<double, 19> weightsBackup{}; // Sometimes first weights is all zero.
for (size_t i = 0; i < LATTICEVELOCITIES.size(); ++i) {
const auto &vel = LATTICEVELOCITIES[i];
coord_t neighbor = {coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]};
const int neighFlag = indexForCell(neighbor, length);
if (flagIndex == neighFlag || flags[neighFlag] != flag_t::INTERFACE)
continue;
weightsBackup[i] = 1.0;
const double dotProduct = normal[0] * vel[0] + normal[1] * vel[1] + normal[2] * vel[2];
if (type == update_t::FILLED) {
weights[i] = std::max(0.0, dotProduct);
} else { // EMPTIED
weights[i] = -std::min(0.0, dotProduct);
}
assert(weights[i] >= 0.0);
}
// Step 2: Calculate normalizer (otherwise sum of weights != 1.0)
double normalizer = std::accumulate(weights.begin(), weights.end(), 0.0, std::plus<double>());
if (normalizer == 0.0) {
// Mass cannot be distributed along the normal, distribute to all interface cells equally.
weights = weightsBackup;
normalizer = std::accumulate(weights.begin(), weights.end(), 0.0, std::plus<double>());
}
if (normalizer == 0.0) {
return;
}
// Step 3: Redistribute weights. As non-interface cells have weight 0, we can just loop through
// all cells.
for (size_t i = 0; i < LATTICEVELOCITIES.size(); ++i) {
const auto &vel = LATTICEVELOCITIES[i];
coord_t neighbor = {coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]};
const int neighFlag = indexForCell(neighbor, length);
#pragma omp atomic
massChange[neighFlag] += (weights[i] / normalizer) * excessMass;
}
}
void distributeMass(const std::vector<double> &distributions, std::vector<double> &mass, const coord_t &length,
std::vector<flag_t> &flags, std::vector<double> &fluidFraction) {
// Here we redistribute the excess mass of the cells.
// It is important that we get a copy of the filled/emptied where all converted cells are stored
// and no other cells.
// This excludes emptied cells that are used as interface cells instead!
auto massChange = std::vector<double>(mass.size(), 0.0);
#pragma omp parallel for schedule(guided)
for (int z = 1; z < length[2] + 1; ++z) {
for (int y = 1; y < length[1] + 1; ++y) {
for (int x = 1; x < length[0] + 1; ++x) {
const int curFlag = indexForCell(x, y, z, length);
const coord_t coord = {x, y, z};
if (flags[curFlag] == flag_t::INTERFACE_TO_FLUID) {
distributeSingleMass(distributions, mass, massChange, length, coord,
flags, fluidFraction, update_t::FILLED);
flags[curFlag] = flag_t::FLUID;
} else if (flags[curFlag] == flag_t::INTERFACE_TO_EMPTY) {
distributeSingleMass(distributions, mass, massChange, length, coord,
flags, fluidFraction, update_t::EMPTIED);
flags[curFlag] = flag_t::EMPTY;
}
}
}
}
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < mass.size(); ++i) {
const double curDensity = computeDensity(&distributions[i * Q]);
mass[i] += massChange[i];
fluidFraction[i] = mass[i] / curDensity;
}
} | 47.143902 | 140 | 0.569197 | krenzland |
c515da3d7291436f423257dc94f38d5e3e9913b8 | 2,874 | cpp | C++ | tool/keyinfo.cpp | drypot/san-2.x | 44e626793b1dc50826ba0f276d5cc69b7c9ca923 | [
"MIT"
] | 5 | 2019-12-27T07:30:03.000Z | 2020-10-13T01:08:55.000Z | tool/keyinfo.cpp | drypot/san-2.x | 44e626793b1dc50826ba0f276d5cc69b7c9ca923 | [
"MIT"
] | null | null | null | tool/keyinfo.cpp | drypot/san-2.x | 44e626793b1dc50826ba0f276d5cc69b7c9ca923 | [
"MIT"
] | 1 | 2020-07-27T22:36:40.000Z | 2020-07-27T22:36:40.000Z | /*
keyinfo.cpp
1995.08.18
*/
#include <pub/config.hpp>
#include <pub/common.hpp>
#include <pub/misc.hpp>
LRESULT CALLBACK _export WndProcpcs_main(HWND, UINT, WPARAM, LPARAM);
void pcs_main()
{
HWND hWnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProcpcs_main;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.lpszMenuName = NULL;
wndclass.hbrBackground = get_StockObject(BLACK_BRUSH);
wndclass.lpszClassName = "Winpcs_main";
RegisterClass(&wndclass);
hWnd =
CreateWindow
(
"Winpcs_main",
"Key Info",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);
ShowWindow(hWnd, nCmdShow);
while (get_Message(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
HDC hdcGlobal;
#pragma argsused
BOOL Winpcs_main_Create (HWND hWnd, LPCREATESTRUCT lpCreateStrct)
{
hdcGlobal = get_DC(hWnd);
set_TextColor(hdcGlobal,RGB(200,200,200));
set_BkColor(hdcGlobal,RGB(0,0,0));
return def_true;
}
#pragma argsused
void Winpcs_main_Destory (HWND hWnd)
{
PostQuitMessage(0);
}
#pragma argsused
void Winpcs_main_KeySub (HWND hWnd, UINT vk, BOOL fDown, int cRepeat, UINT flags, char* type)
{
static int y;
char buf[80];
RECT rc;
if (fDown)
{
get_ClientRect(hWnd,&rc);
if (y+20 > rc.bottom)
{
y=0;
InvalidateRect(hWnd,&rc,def_true);
UpdateWindow(hWnd);
}
TextOut(hdcGlobal,5,y,buf,sprintf(buf,"%s vk=%02x scan=%02x fExtended=%x",type,(int)vk,(int)(byte)flags,(int)((flags >> 8)&1)));
y += 20;
}
}
#pragma argsused
void Winpcs_main_Key (HWND hWnd, UINT vk, BOOL fDown, int cRepeat, UINT flags)
{
Winpcs_main_KeySub(hWnd,vk,fDown,cRepeat,flags,"Normal");
}
#pragma argsused
void Winpcs_main_SysKey (HWND hWnd, UINT vk, BOOL fDown, int cRepeat, UINT flags)
{
Winpcs_main_KeySub(hWnd,vk,fDown,cRepeat,flags,"System");
}
void Winpcs_main_Paint(HWND hwnd)
{
PAINTSTRUCT ps;
BeginPaint(hwnd,&ps);
EndPaint(hwnd,&ps);
}
LRESULT CALLBACK __export WndProcpcs_main (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
HANDLE_MSG(hWnd, WM_CREATE, Winpcs_main_Create);
HANDLE_MSG(hWnd, WM_KEYDOWN, Winpcs_main_Key);
HANDLE_MSG(hWnd, WM_KEYUP, Winpcs_main_Key);
HANDLE_MSG(hWnd, WM_SYSKEYDOWN, Winpcs_main_SysKey);
HANDLE_MSG(hWnd, WM_SYSKEYUP, Winpcs_main_SysKey);
HANDLE_MSG(hWnd, WM_PAINT, Winpcs_main_Paint);
HANDLE_MSG(hWnd, WM_DESTROY, Winpcs_main_Destory);
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
| 21.772727 | 134 | 0.691371 | drypot |
c51bd70ec717e6f7785a0665fb5ea391712fc42d | 16,884 | cpp | C++ | tests/TestAppMain.cpp | jakjinak/jj | d1d49cd75a63b7ec2b2497ed061e8c1145ff2eb7 | [
"MIT"
] | null | null | null | tests/TestAppMain.cpp | jakjinak/jj | d1d49cd75a63b7ec2b2497ed061e8c1145ff2eb7 | [
"MIT"
] | null | null | null | tests/TestAppMain.cpp | jakjinak/jj | d1d49cd75a63b7ec2b2497ed061e8c1145ff2eb7 | [
"MIT"
] | null | null | null | #include "jj/gui/application.h"
#include "jj/gui/window.h"
#include "jj/gui/textLabel.h"
#include "jj/gui/textInput.h"
#include "jj/gui/comboBox.h"
#include "jj/gui/tree.h"
#include "jj/gui/button.h"
#include "jj/gui/sizer.h"
#include "jj/stream.h"
#include <sstream>
#include "jj/directories.h"
class myTreeThing : public jj::gui::treeItem_T<myTreeThing>
{
typedef jj::gui::treeItem_T<myTreeThing> base_t;
typedef jj::gui::tree_T<myTreeThing> CTRL;
public:
myTreeThing(CTRL& parent, id_t id) : base_t(parent, id) {}
};
class treetest : public jj::gui::dialog_t
{
jj::gui::tree_T<myTreeThing>* tree;
jj::gui::textInput_t* name, *log;
jj::gui::button_t* add, *remove, *dump;
jj::gui::boxSizer_t* right, *sadd, *srem;
void onAdd(jj::gui::button_t&) {
myTreeThing* i = tree->selected();
if (i == nullptr)
dolog(jjT("Nothing selected, nothing added."));
i->add(name->text());
dolog(jjT("Added [") + name->text() + jjT("]"));
}
void onRemove(jj::gui::button_t&) {
myTreeThing* i = tree->selected();
if (i == nullptr)
{
dolog(jjT("Nothing selected, nothing removed."));
return;
}
if (i->id() == tree->root().id())
{
dolog(jjT("Root selected, nothing removed."));
return;
}
myTreeThing* p = i->parent_item();
if (p == nullptr)
{
dolog(jjT("Something weird happened!"));
return;
}
p->remove(*i);
}
void doDump(myTreeThing& t, jj::string_t& buf) {
buf += t.text();
buf += jjT("{");
for (size_t i = 0; i < t.count(); ++i)
doDump(t.get(i), buf);
buf += jjT("}");
}
void onDump(jj::gui::button_t&) {
jj::string_t buf;
doDump(tree->root(), buf);
dolog(buf);
}
bool beforeSelect(myTreeThing& x, myTreeThing* o) {
dolog(jjT("Querying selection of [") + x.text() + jjT("], previous was [") + (o == nullptr ? jj::string_t(jjT("<NONE>")) : o->text()) + jjT("]"));
if (x.text() == jjT("NEE"))
{
dolog(jjT("VETO!"));
return false;
}
return true;
}
void onSelect(myTreeThing& x, myTreeThing* o) {
dolog(jjT("Selected [") + x.text() + jjT("], previous was [") + (o == nullptr ? jj::string_t(jjT("<NONE>")) : o->text()) + jjT("]"));
}
void onActivate(myTreeThing& x) {
x.bold(!x.bold());
x.bold() ? x.expand() : x.collapse();
}
public:
treetest(jj::gui::topLevelWindow_t& main)
: jj::gui::dialog_t(main, jj::gui::dialog_t::options() << jj::opt::text(jjT("GUI Tree test")) << jj::opt::size(400, 800) << jj::gui::dialog_t::RESIZEABLE)
{
using namespace jj;
using namespace jj::gui;
OnCreateSizer = [this] { return new boxSizer_t(*this, boxSizer_t::HORIZONTAL); };
tree = new tree_T<myTreeThing>(*this, jj::gui::tree_T<myTreeThing>::options() << opt::text(jjT("ROOT")));
tree->BeforeSelect.add(*this, &treetest::beforeSelect);
tree->OnSelect.add(*this, &treetest::onSelect);
tree->OnActivate.add(*this, &treetest::onActivate);
name = new textInput_t(*this, textInput_t::options());
log = new textInput_t(*this, textInput_t::options() << textInput_t::MULTILINE);
add = new button_t(*this, button_t::options() << opt::text(jjT("Add")));
add->OnClick.add(*this, &treetest::onAdd);
remove = new button_t(*this, button_t::options() << opt::text(jjT("Remove")));
remove->OnClick.add(*this, &treetest::onRemove);
dump = new button_t(*this, button_t::options() << opt::text(jjT("Dump")));
dump->OnClick.add(*this, &treetest::onDump);
sizer().add(*tree, sizerFlags_t().proportion(2).expand());
sizer().add(*(right = new jj::gui::boxSizer_t(*this, boxSizer_t::VERTICAL)), sizerFlags_t().proportion(1).expand());
right->add(*(sadd = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().expand());
right->add(*(srem = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().expand());
sadd->add(*name, sizerFlags_t().expand());
sadd->add(*add, sizerFlags_t());
srem->add(*remove, sizerFlags_t());
srem->add(*dump, sizerFlags_t());
right->add(*log, sizerFlags_t().expand().proportion(1));
}
void dolog(const jj::string_t& txt)
{
auto ct = log->text();
if (ct.empty())
log->changeText(txt);
else
log->changeText(txt + jjT('\n') + ct);
}
};
class wnd : public jj::gui::frame_t
{
jj::gui::textInput_t* t1, *t2;
jj::gui::button_t* b1, *b2, *b3, *b4;
jj::gui::boxSizer_t* s1, *s2;
jj::gui::dialog_t* dlg;
void onb1(jj::gui::button_t&) {
if (!o)
return;
if (o->isShown())
o->hide();
else
o->show();
}
void onb2(jj::gui::button_t&) {
if (!o)
return;
o->close();
o = nullptr;
}
static jj::gui::statusBar_t::style_t cycleSB(jj::gui::statusBar_t::style_t style)
{
using namespace jj::gui;
switch (style)
{
case statusBar_t::RAISED:
return statusBar_t::FLAT;
case statusBar_t::FLAT:
return statusBar_t::SUNKEN;
default:
return statusBar_t::RAISED;
}
}
void onb3(jj::gui::button_t&) {
status_bar().style(2, cycleSB(status_bar().style(2)));
}
void onb4(jj::gui::button_t& b) {
if (b.text() == jjT("B4 A"))
b.text(jjT("B4 B"));
else
b.text(jjT("B4 A"));
}
void ontxt(jj::gui::textInput_t& x) {
status_bar().text(x.text());
if (!o)
return;
o->title(x.text());
}
void onradio(jj::gui::menuItem_t& x) {
x.check();
}
public:
wnd(jj::gui::application_t& app)
: jj::gui::frame_t(app, jj::gui::frame_t::options() << jj::opt::text(jjT("First One")) << jj::opt::size(600, 280) << jj::gui::frame_t::NO_MAXIMIZE)
, o(nullptr), dlg(nullptr)
{
using namespace jj;
using namespace jj::gui;
OnCreateSizer = [this] { return new boxSizer_t(*this, boxSizer_t::VERTICAL); };
textLabel_t* st = new textLabel_t(*this, textLabel_t::options() << opt::text(jjT("ST")));
b1 = new button_t(*this, button_t::options() << opt::text(jjT("B1")));
b1->OnClick.add(*this, &wnd::onb1);
b2 = new button_t(*this, button_t::options() << opt::text(jjT("B2")) << button_t::EXACT_FIT);
b2->OnClick.add(*this, &wnd::onb2);
b3 = new button_t(*this, button_t::options() << opt::text(jjT("B3")) << align_t::LEFT << alignv_t::BOTTOM);
b3->OnClick.add(*this, &wnd::onb3);
b4 = new button_t(*this, button_t::options() << opt::text(jjT("B4 A")) << button_t::EXACT_FIT << button_t::NO_BORDER);
b4->OnClick.add(*this, &wnd::onb4);
t1 = new textInput_t(*this, textInput_t::options() << opt::text(jjT("Child")));
t1->OnTextChange.add(*this, &wnd::ontxt);
t2 = new textInput_t(*this, textInput_t::options() << textInput_t::MULTILINE);
comboBox_t* cb = new comboBox_t(*this, { jjT("ABC"), jjT("XYZ"), jjT("123") });
cb->OnSelect.add([this](comboBox_t& x) { t2->changeText(jjT("Selected [") + x.text() + jjT("]")); });
sizer().add(*(s1 = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().proportion(1).expand());
sizer().add(*(s2 = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().proportion(3).expand());
s1->add(*st, sizerFlags_t().border(5));
s1->add(*b1, sizerFlags_t().set(align_t::CENTER));
s1->add(*b2, sizerFlags_t().set(align_t::CENTER));
s1->add(*b3, sizerFlags_t().set(align_t::CENTER).set(sizerFlags_t::EXPAND));
s1->add(*b4, sizerFlags_t().set(align_t::CENTER));
s1->add(*t1, sizerFlags_t().set(align_t::CENTER).proportion(1));
s1->add(*cb, sizerFlags_t().set(align_t::CENTER).proportion(1));
s2->add(*t2, sizerFlags_t().proportion(1).expand());
menu_t* m1, *m2, *m3, *m4, *mt;
menu_bar().append(m1 = new menu_t(*this), jjT("TEST"));
m1->append(menuItem_t::options() << opt::text(jjT("Current Dir"))).lock()->OnClick.add([this](menuItem_t&) {
t2->changeText(jj::directories::current());
});
m1->append(menuItem_t::options() << opt::text(jjT("Program Dir"))).lock()->OnClick.add([this](menuItem_t&) {
t2->changeText(jj::directories::program());
});
m1->append(menuItem_t::options() << opt::text(jjT("Program Path"))).lock()->OnClick.add([this](menuItem_t&) {
t2->changeText(jj::directories::program(true));
});
m1->append(menuItem_t::options() << opt::text(jjT("Home Dir"))).lock()->OnClick.add([this](menuItem_t&) {
t2->changeText(jj::directories::personal());
});
m1->append(menuItem_t::options() << opt::text(jjT("Home Dir2"))).lock()->OnClick.add([this](menuItem_t&) {
t2->changeText(jj::directories::personal(true));
});
m1->append(menuItem_t::SEPARATOR);
auto me = m1->append(menuItem_t::options() << opt::text(jjT("Exit")) << opt::accelerator(keys::accelerator_t(keys::ALT, keys::F4)));
me.lock()->OnClick.add([this](menuItem_t&) {
this->close();
});
menu_bar().append(m2 = new menu_t(*this), menuItem_t::submenu_options() << opt::text(jjT("actions")));
m2->append(m4 = new menu_t(*this), jjT("dialogs"));
auto m41 = m4->append(menuItem_t::options() << menuItem_t::CHECK << opt::text(jjT("generic is modal")));
auto m42 = m4->append(menuItem_t::options() << opt::text(jjT("generic")));
m42.lock()->OnClick.add([this, m41](menuItem_t&) {
this->dlg = new dialog_t(*this, dialog_t::options() << opt::text(jjT("The dialog")));
if (m41.lock()->checked())
this->dlg->show_modal();
else
this->dlg->show();
});
m4->append(menuItem_t::options() << opt::text(jjT("delete generic")))
.lock()->OnClick.add([this](menuItem_t&) {
delete this->dlg;
this->dlg = nullptr;
});
m4->append(menuItem_t::SEPARATOR);
m4->append(menuItem_t::options() << opt::text(jjT("simple")))
.lock()->OnClick.add([this](menuItem_t&) {
dlg::simple_t x(*this, jjT("So tell me now, what u want to do..."), jjT("Question for you"), dlg::simple_t::options() << stock::icon_t::ERR << stock::item_t::CANCEL, {/*stock::item_t::OK, */ stock::item_t::CANCEL, stock::item_t::YES });
modal_result_t result = x.show_modal();
if (result.isStock())
t2->text(jjS(jjT("The result was a stock result ") << int(result.stock())));
else
t2->text(jjS(jjT("The result was a regular result ") << result.regular()));
});
m4->append(menuItem_t::options() << opt::text(jjT("text input")))
.lock()->OnClick.add([this](menuItem_t&) {
dlg::input_t x(*this, jjT("Give me text:"), dlg::input_t::options() << opt::text(jjT("default")));
modal_result_t result = x.show_modal();
if (result == stock::item_t::OK)
t2->text(jjS(jjT("The result was a stock OK: '") << x.text() << jjT("'")));
else if (result == stock::item_t::CANCEL)
t2->text(jjT("The result was a stock CANCEL"));
else if (result.isStock())
t2->text(jjS(jjT("The result was a stock result ") << int(result.stock())));
else
t2->text(jjS(jjT("The result was a regular result ") << result.regular()));
});
m4->append(menuItem_t::options() << opt::text(jjT("password input")))
.lock()->OnClick.add([this](menuItem_t&) {
dlg::input_t x(*this, jjT("Give me password:"), dlg::input_t::options() << dlg::input_t::PASSWORD);
modal_result_t result = x.show_modal();
if (result == stock::item_t::OK)
t2->text(jjS(jjT("The result was a stock OK: '") << x.text() << jjT("'")));
else if (result == stock::item_t::CANCEL)
t2->text(jjT("The result was a stock CANCEL"));
else if (result.isStock())
t2->text(jjS(jjT("The result was a stock result ") << int(result.stock())));
else
t2->text(jjS(jjT("The result was a regular result ") << result.regular()));
});
m4->append(menuItem_t::SEPARATOR);
m4->append(menuItem_t::options() << opt::text(jjT("open")))
.lock()->OnClick.add([this](menuItem_t&) {
dlg::openFile_t x(*this, dlg::openFile_t::options());
if (x.show_modal() == stock::item_t::OK)
t2->text(jjS(jjT("[") << x.file() << jjT("] selected in dialog")));
});
m4->append(menuItem_t::options() << opt::text(jjT("open many")))
.lock()->OnClick.add([this](menuItem_t&) {
dlg::openFile_t x(*this, dlg::openFile_t::options() << dlg::openFile_t::MULTIPLE << dlg::openFile_t::MUST_EXIST);
if (x.show_modal() == stock::item_t::OK)
{
jj::string_t t;
for (const jj::string_t& s : x.files())
t = t + jjT('[') + s + jjT("] ");
if (t.empty())
t = jjT("Nothing ");
t += jjT("selected in dialog");
t2->text(t);
}
});
m4->append(menuItem_t::options() << opt::text(jjT("save")))
.lock()->OnClick.add([this](menuItem_t&) {
dlg::saveFile_t x(*this, dlg::saveFile_t::options() << dlg::saveFile_t::OVERWRITE);
if (x.show_modal() == stock::item_t::OK)
t2->text(jjS(jjT("[") << x.file() << jjT("] selected in dialog")));
});
m4->append(menuItem_t::options() << opt::text(jjT("get dir")))
.lock()->OnClick.add([this](menuItem_t&) {
dlg::selectDir_t x(*this, dlg::selectDir_t::options());
if (x.show_modal() == stock::item_t::OK)
t2->text(jjS(jjT("[") << x.dir() << jjT("] selected in dialog")));
});
m2->append(m3 = new menu_t(*this), jjT("sub"));
auto m22 = m2->append(menuItem_t::options() << opt::text(jjT("M2")) << menuItem_t::CHECK);
m2->append(menuItem_t::options() << opt::text(jjT("M3")) << menuItem_t::CHECK)
.lock()->OnClick.add([this, m22, st](menuItem_t& i) {
menuItem_t& mi = *m22.lock();
mi.enable(i.checked());
jj::string_t txt = mi.text();
if (txt.length() < 15)
{
mi.text(txt + jjT(" X"));
st->text(st->text() + jjT(" X"));
}
else
{
mi.text(txt.substr(0, 2));
st->text(st->text().substr(0, 2));
}
this->layout();
});
m2->append(menuItem_t::SEPARATOR);
m2->append(menuItem_t::options() << opt::text(jjT("M4")));
auto m31 = m3->append(menuItem_t::options() << opt::text(jjT("S1")) << menuItem_t::RADIO);
m31.lock()->OnClick.add(*this, &wnd::onradio);
auto m32 = m3->append(menuItem_t::options() << opt::text(jjT("S2")) << menuItem_t::RADIO);
m32.lock()->OnClick.add(*this, &wnd::onradio);
menu_bar().append(mt = new menu_t(*this), jjT("TESTS"));
mt->append(menuItem_t::options() << opt::text(jjT("Tree test"))).lock()->OnClick.add([this](menuItem_t&) {
treetest x(*this);
x.show_modal();
});
status_bar().set({ {jjT("status"), -1, statusBar_t::RAISED}, {jjT("---"), -2, statusBar_t::FLAT}, {jjT("enjoy"), 60, statusBar_t::SUNKEN} });
layout();
}
~wnd()
{
if (o) o->close();
}
jj::gui::frame_t* o;
};
class app : public jj::gui::application_t
{
wnd* f;
bool ono(jj::gui::topLevelWindow_t&)
{
f->o = nullptr;
return true;
}
virtual bool on_init()
{
//_CrtSetBreakAlloc(5684);
f = new wnd(*this);
f->show();
f->o = new jj::gui::frame_t(*this, jj::gui::frame_t::options() << jj::opt::text(jjT("Child")) << jj::gui::frame_t::NO_MINIMIZE);
f->o->OnClose.add(*this, &app::ono);
f->o->show();
return true;
}
};
app g_app;
| 43.181586 | 252 | 0.529377 | jakjinak |
c51db82bae8d0851f4241bf6ab66fcaeba33b9a9 | 3,424 | cpp | C++ | projects/view3d/textures/texture_base.cpp | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 2 | 2020-11-11T16:19:04.000Z | 2021-01-19T01:53:29.000Z | projects/view3d/textures/texture_base.cpp | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2020-07-27T09:00:21.000Z | 2020-07-27T10:58:10.000Z | projects/view3d/textures/texture_base.cpp | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2021-04-04T01:39:55.000Z | 2021-04-04T01:39:55.000Z | //*********************************************
// Renderer
// Copyright (c) Rylogic Ltd 2012
//*********************************************
#include "pr/view3d/forward.h"
#include "pr/view3d/render/renderer.h"
#include "pr/view3d/textures/texture_base.h"
#include "pr/view3d/textures/texture_manager.h"
namespace pr::rdr
{
// Get the shared handle from a shared resource
HANDLE SharedHandleFromSharedResource(IUnknown* shared_resource)
{
// Get the DXGI resource interface for the shared resource
D3DPtr<IDXGIResource> dxgi_resource;
Throw(shared_resource->QueryInterface(__uuidof(IDXGIResource), (void**)&dxgi_resource.m_ptr));
// Get the handled of the shared resource so that we can open it with our d3d device
HANDLE shared_handle;
Throw(dxgi_resource->GetSharedHandle(&shared_handle));
return shared_handle;
}
// Constructors
TextureBase::TextureBase(TextureManager* mgr, RdrId id, ID3D11Resource* res, ID3D11ShaderResourceView* srv, ID3D11SamplerState* samp, RdrId src_id, char const* name)
:RefCounted<TextureBase>()
,m_res(res, true)
,m_srv(srv, true)
,m_samp(samp, true)
,m_id(id == AutoId ? MakeId(this) : id)
,m_src_id(src_id)
,m_mgr(mgr)
,m_name(name ? name : "")
{
}
TextureBase::TextureBase(TextureManager* mgr, RdrId id, HANDLE shared_handle, RdrId src_id, char const* name)
:TextureBase(mgr, id, nullptr, nullptr, nullptr, src_id, name)
{
// Open the shared resource in our d3d device
D3DPtr<IUnknown> resource;
Renderer::Lock lock(m_mgr->m_rdr);
Throw(lock.D3DDevice()->OpenSharedResource(shared_handle, __uuidof(ID3D11Resource), (void**)&resource.m_ptr));
// Query the resource interface from the resource
Throw(resource->QueryInterface(__uuidof(ID3D11Resource), (void**)&m_res.m_ptr));
}
TextureBase::TextureBase(TextureManager* mgr, RdrId id, IUnknown* shared_resource, RdrId src_id, char const* name)
:TextureBase(mgr, id, SharedHandleFromSharedResource(shared_resource), src_id, name)
{
}
// Returns a description of the current sampler state pointed to by 'm_samp'
SamplerDesc TextureBase::SamDesc() const
{
SamplerDesc desc;
if (m_samp != nullptr) m_samp->GetDesc(&desc);
return desc;
}
void TextureBase::SamDesc(SamplerDesc const& desc)
{
Renderer::Lock lock(m_mgr->m_rdr);
D3DPtr<ID3D11SamplerState> samp_state;
pr::Throw(lock.D3DDevice()->CreateSamplerState(&desc, &samp_state.m_ptr));
m_samp = samp_state;
}
// Set the filtering and address mode for this texture
void TextureBase::SetFilterAndAddrMode(D3D11_FILTER filter, D3D11_TEXTURE_ADDRESS_MODE addrU, D3D11_TEXTURE_ADDRESS_MODE addrV)
{
SamplerDesc desc;
m_samp->GetDesc(&desc);
desc.Filter = filter;
desc.AddressU = addrU;
desc.AddressV = addrV;
Renderer::Lock lock(m_mgr->m_rdr);
D3DPtr<ID3D11SamplerState> samp;
pr::Throw(lock.D3DDevice()->CreateSamplerState(&desc, &samp.m_ptr));
m_samp = samp;
}
// Return the shared handle associated with this texture
HANDLE TextureBase::SharedHandle() const
{
HANDLE handle;
D3DPtr<IDXGIResource> res;
pr::Throw(m_res->QueryInterface(__uuidof(IDXGIResource), (void**)&res.m_ptr));
pr::Throw(res->GetSharedHandle(&handle));
return handle;
}
// Ref counting clean up function
void TextureBase::RefCountZero(RefCounted<TextureBase>* doomed)
{
auto tex = static_cast<TextureBase*>(doomed);
tex->Delete();
}
void TextureBase::Delete()
{
m_mgr->Delete(this);
}
} | 32.923077 | 166 | 0.722255 | psryland |
c51e318a927fd1b3ae31dc7e4b176093e98838dc | 571 | cc | C++ | src/connectivity/network/testing/netemul/runner/format.cc | yanyushr/fuchsia | 98e70672a81a206d235503e398f37b7b65581f79 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | src/connectivity/network/testing/netemul/runner/format.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | src/connectivity/network/testing/netemul/runner/format.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 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 "format.h"
#include <iomanip>
namespace netemul {
namespace internal {
void FormatTime(std::ostream* stream, zx_time_t timestamp) {
if (stream) {
*stream << "[" << std::setfill('0') << std::setw(6)
<< timestamp / 1000000000 << "." << std::setfill('0')
<< std::setw(6) << (timestamp / 1000) % 1000000 << "]";
}
}
} // namespace internal
} // namespace netemul
| 25.954545 | 73 | 0.625219 | yanyushr |
c5210172b004b41944ea57f390439356a017af8a | 12,696 | cpp | C++ | M5StickTest-IoTHub/src/main.cpp | tkopacz/2019M5StickC | 1435fb81c4b2b52315eca82f2c824db5c412d946 | [
"MIT"
] | null | null | null | M5StickTest-IoTHub/src/main.cpp | tkopacz/2019M5StickC | 1435fb81c4b2b52315eca82f2c824db5c412d946 | [
"MIT"
] | null | null | null | M5StickTest-IoTHub/src/main.cpp | tkopacz/2019M5StickC | 1435fb81c4b2b52315eca82f2c824db5c412d946 | [
"MIT"
] | null | null | null | /**
* A simple Azure IoT example for sending telemetry.
* Watchdog
* Interupt on GPIO
* Read almost all parameters from M5StickC
* Commands: start | stop, ledon | ledoff, delay {"ms":1000}
*/
#include <Arduino.h>
#include <M5StickC.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include "Esp32MQTTClient.h"
#include "esp32_rmt.h"
#include "esp_task_wdt.h"
//extern static IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
// Please input the SSID and password of WiFi
char *ssid = "xxxxxxxxxxxx";
char *password = "xxxxxxxxxxxx";
static const char *connectionString = "xxxxxxxxxxxx";
static bool hasIoTHub = false;
int messageCount = 1;
static bool hasWifi = false;
static bool messageSending = true;
static uint64_t send_interval_ms;
int IntervalMs = 10000;//10000;
#define DEVICE_ID "m5stickc01"
#define MESSAGE_MAX_LEN 512
ESP32_RMT rem;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
static int callbackCounter;
IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
IOTHUB_MESSAGE_HANDLE msg;
int receiveContext = 0;
static char propText[1024];
static IOTHUBMESSAGE_DISPOSITION_RESULT ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE message, void *userContextCallback)
{
int *counter = (int *)userContextCallback;
const char *buffer;
size_t size;
MAP_HANDLE mapProperties;
const char *messageId;
const char *correlationId;
const char *userDefinedContentType;
const char *userDefinedContentEncoding;
// Message properties
if ((messageId = IoTHubMessage_GetMessageId(message)) == NULL)
{
messageId = "<null>";
}
if ((correlationId = IoTHubMessage_GetCorrelationId(message)) == NULL)
{
correlationId = "<null>";
}
if ((userDefinedContentType = IoTHubMessage_GetContentTypeSystemProperty(message)) == NULL)
{
userDefinedContentType = "<null>";
}
if ((userDefinedContentEncoding = IoTHubMessage_GetContentEncodingSystemProperty(message)) == NULL)
{
userDefinedContentEncoding = "<null>";
}
// Message content
if (IoTHubMessage_GetByteArray(message, (const unsigned char **)&buffer, &size) != IOTHUB_MESSAGE_OK)
{
(void)printf("unable to retrieve the message data\r\n");
}
else
{
(void)printf("Received Message [%d]\r\n Message ID: %s\r\n Correlation ID: %s\r\n Content-Type: %s\r\n Content-Encoding: %s\r\n Data: <<<%.*s>>> & Size=%d\r\n",
*counter, messageId, correlationId, userDefinedContentType, userDefinedContentEncoding, (int)size, buffer, (int)size);
}
// Retrieve properties from the message
mapProperties = IoTHubMessage_Properties(message);
if (mapProperties != NULL)
{
const char *const *keys;
const char *const *values;
size_t propertyCount = 0;
if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK)
{
if (propertyCount > 0)
{
size_t index;
printf(" Message Properties:\r\n");
for (index = 0; index < propertyCount; index++)
{
(void)printf("\tKey: %s Value: %s\r\n", keys[index], values[index]);
}
(void)printf("\r\n");
}
}
}
/* Some device specific action code goes here... */
(*counter)++;
return IOTHUBMESSAGE_ACCEPTED;
}
static int DeviceMethodCallback(const char *method_name, const unsigned char *payload, size_t size, unsigned char **response, size_t *resp_size, void *userContextCallback)
{
(void)userContextCallback;
printf("\r\nDevice Method called\r\n");
printf("Device Method name: %s\r\n", method_name);
printf("Device Method payload: %.*s\r\n", (int)size, (const char *)payload);
int status = 200;
char *RESPONSE_STRING = "{ \"Response\": \"OK\" }";
if (strcmp(method_name, "start") == 0)
{
messageSending = true;
}
else if (strcmp(method_name, "stop") == 0)
{
messageSending = false;
}
else if (strcmp(method_name, "delay") == 0)
{
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, payload);
// Test if parsing succeeds.
if (error)
{
LogError("deserializeJson() failed: ");
LogError(error.c_str());
RESPONSE_STRING = "\"deserializeJson() failed\"";
status = 500;
}
else
{
IntervalMs = doc["ms"];
LogInfo("IntervalMs:%d", IntervalMs);
}
}
else if (strcmp(method_name, "ledon") == 0)
{
digitalWrite(M5_LED, LOW);
}
else if (strcmp(method_name, "ledoff") == 0)
{
digitalWrite(M5_LED, HIGH);
}
else
{
LogInfo("No method %s found", method_name);
RESPONSE_STRING = "\"No method found\"";
status = 404;
}
printf("\r\nResponse status: %d\r\n", status);
printf("Response payload: %s\r\n\r\n", RESPONSE_STRING);
*resp_size = strlen(RESPONSE_STRING);
if ((*response = (unsigned char *)malloc(*resp_size)) == NULL)
{
status = -1;
}
else
{
(void)memcpy(*response, RESPONSE_STRING, *resp_size);
}
return status;
}
static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContextCallback)
{
//Setup watchdog
esp_task_wdt_reset();
//Passing address to IOTHUB_MESSAGE_HANDLE
IOTHUB_MESSAGE_HANDLE *msg = (IOTHUB_MESSAGE_HANDLE *)userContextCallback;
(void)printf("Confirmation %d result = %s\r\n", callbackCounter, ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
/* Some device specific action code goes here... */
callbackCounter++;
if (result != IOTHUB_CLIENT_CONFIRMATION_OK)
{
esp_restart();
}
//TK:Or caller
IoTHubMessage_Destroy(*msg);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
double vbat = 0.0;
double discharge, charge;
double temp = 0.0;
double bat_p = 0.0;
int16_t accX = 0;
int16_t accY = 0;
int16_t accZ = 0;
int16_t gyroX = 0;
int16_t gyroY = 0;
int16_t gyroZ = 0;
int16_t tempg = 0;
int16_t coIn = 0, coOut = 0;
double coD = 0, vin = 0, iin = 0;
volatile int16_t bRST = 0, bHOME = 0; //Interupt
void IRAM_ATTR isrHOME() {
bHOME = 1;
}
void IRAM_ATTR isrRST() {
bRST = 1;
}
void setup()
{
// initialize the M5StickC object
M5.begin();
M5.Axp.begin();
M5.Axp.EnableCoulombcounter();
M5.Imu.Init();
M5.Lcd.begin();
rem.begin(M5_IR, true);
pinMode(M5_BUTTON_HOME, INPUT_PULLUP);
attachInterrupt(M5_BUTTON_HOME, isrHOME, FALLING);
pinMode(M5_BUTTON_RST, INPUT_PULLUP);
attachInterrupt(M5_BUTTON_RST, isrRST, FALLING);
pinMode(M5_LED, OUTPUT);
digitalWrite(M5_LED, HIGH);
M5.Lcd.setCursor(0, 0, 1);
M5.Lcd.println("WiFi");
Serial.println("Starting connecting WiFi.");
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
M5.Lcd.print(".");
}
hasWifi = true;
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
M5.Lcd.println(WiFi.localIP());
randomSeed(analogRead(0));
Serial.println(" > IoT Hub");
printf("Before platform_init\n");
if (platform_init() != 0)
{
(void)printf("Failed to initialize the platform.\r\n");
M5.Lcd.println("IoT Hub - error");
}
else
{
printf("Before IoTHubClient_LL_CreateFromConnectionString\n");
if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol)) == NULL)
{
(void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
}
else
{
if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
{
(void)printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n");
}
if (IoTHubClient_LL_SetDeviceMethodCallback(iotHubClientHandle, DeviceMethodCallback, &receiveContext) != IOTHUB_CLIENT_OK)
{
(void)printf("ERROR: IoTHubClient_LL_SetDeviceMethodCallback..........FAILED!\r\n");
}
}
}
hasIoTHub = true;
M5.Lcd.println("IoT Hub - OK!");
delay(2000);
send_interval_ms = millis();
}
void loop()
{
if (hasWifi && hasIoTHub)
{
if (messageSending &&
(int)(millis() - send_interval_ms) >= IntervalMs)
{
//Read
vbat = M5.Axp.GetVbatData() * 1.1 / 1000;
charge = M5.Axp.GetIchargeData() / 2;
discharge = M5.Axp.GetIdischargeData() / 2;
temp = -144.7 + M5.Axp.GetTempData() * 0.1;
bat_p = M5.Axp.GetPowerbatData() * 1.1 * 0.5 / 1000;
coIn = M5.Axp.GetCoulombchargeData();
coOut = M5.Axp.GetCoulombdischargeData();
coD = M5.Axp.GetCoulombData();
vin = M5.Axp.GetVinData() * 1.7;
iin = M5.Axp.GetIinData() * 0.625;
M5.Lcd.setCursor(0, 0, 1);
M5.Lcd.printf("vbat:%.3fV\r\n", vbat);
M5.Lcd.printf("icharge:%fmA\r\n", charge);
M5.Lcd.printf("idischg:%fmA\r\n", discharge);
M5.Lcd.printf("temp:%.1fC\r\n", temp);
M5.Lcd.printf("pbat:%.3fmW\r\n", bat_p);
M5.Lcd.printf("CoIn :%d\r\n", coIn);
M5.Lcd.printf("CoOut:%d\r\n", coOut);
M5.Lcd.printf("CoD:%.2fmAh\r\n", coD);
M5.Lcd.printf("Vin:%.3fmV\r\n", vin);
M5.Lcd.printf("Iin:%.3fmA\r\n", iin);
M5.IMU.getGyroData(&gyroX, &gyroY, &gyroZ);
M5.IMU.getAccelData(&accX, &accY, &accZ);
M5.IMU.getTempData(&tempg);
M5.Lcd.printf("%.2f|%.2f\r\n%.2f\r\n", ((float)gyroX) * M5.IMU.gRes, ((float)gyroY) * M5.IMU.gRes, ((float)gyroZ) * M5.IMU.gRes);
M5.Lcd.printf("%.2f|%.2f\r\n%.2f\r\n", ((float)accX) * M5.IMU.aRes, ((float)accY) * M5.IMU.aRes, ((float)accZ) * M5.IMU.aRes);
M5.Lcd.printf("Tempg:%.2fC\r\n", ((float)tempg) / 333.87 + 21.0);
M5.Lcd.printf("CNT:%d\r\n", messageCount);
//bRST = (digitalRead(M5_BUTTON_RST) == LOW);
//bHOME = (digitalRead(M5_BUTTON_HOME) == LOW);
M5.Lcd.printf("%d %d\r\n", bRST, bHOME);
// Send teperature data
char messagePayload[MESSAGE_MAX_LEN];
snprintf(
messagePayload,
MESSAGE_MAX_LEN,
"{"
"\"deviceId\":\"%s\", \"messageId\":%d, "
"\"vbat\":%.3f, \"icharge\":%f, \"idischg\":%f, \"temp\":%.1f, "
"\"pbat\":%.3f, \"CoIn\":%d, \"CoOut\":%d, "
"\"CoD\":%f, \"Vin\":%.3f, \"Iin\":%.3f, "
"\"gyroX\":%.2f, \"gyroY\":%.2f, \"gyroZ\":%.2f, "
"\"accX\":%.2f, \"accY\":%.2f, \"accZ\":%.2f, "
"\"Tempg\":%.2f, "
"\"bRTS\":%d, \"bHOME\":%d"
"}",
DEVICE_ID, messageCount++,
vbat, charge, discharge, temp,
bat_p, coIn, coOut,
coD, vin, iin,
((float)gyroX) * M5.IMU.gRes, ((float)gyroY) * M5.IMU.gRes, ((float)gyroZ) * M5.IMU.gRes,
((float)accX) * M5.IMU.aRes, ((float)accY) * M5.IMU.aRes, ((float)accZ) * M5.IMU.aRes,
((float)tempg) / 333.87 + 21.0,
bRST, bHOME);
Serial.println(messagePayload);
if ((msg = IoTHubMessage_CreateFromByteArray((const unsigned char *)messagePayload, strlen(messagePayload))) == NULL)
{
(void)printf("ERROR: iotHubMessageHandle is NULL!\r\n");
}
else
{
(void)IoTHubMessage_SetMessageId(msg, "MSG_ID");
//(void)IoTHubMessage_SetCorrelationId(msg, "CORE_ID");
(void)IoTHubMessage_SetContentTypeSystemProperty(msg, "application%2Fjson");
(void)IoTHubMessage_SetContentEncodingSystemProperty(msg, "utf-8");
MAP_HANDLE propMap = IoTHubMessage_Properties(msg);
(void)sprintf_s(propText, sizeof(propText), (bRST==1 && bHOME==1) ? "true" : "false");
if (Map_AddOrUpdate(propMap, "valAlert", propText) != MAP_OK)
{
(void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
}
if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, msg, SendConfirmationCallback, &msg) != IOTHUB_CLIENT_OK)
//if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, msg, NULL, NULL) != IOTHUB_CLIENT_OK)
{
(void)printf("ERROR: IoTHubClient_SendEventAsync..........FAILED!\r\n");
}
}
IOTHUB_CLIENT_STATUS status;
IoTHubClient_LL_DoWork(iotHubClientHandle);
ThreadAPI_Sleep(100);
//Wait till
while ((IoTHubClient_LL_GetSendStatus(iotHubClientHandle, &status) == IOTHUB_CLIENT_OK) && (status == IOTHUB_CLIENT_SEND_STATUS_BUSY))
{
IoTHubClient_LL_DoWork(iotHubClientHandle);
ThreadAPI_Sleep(100);
}
//Callback is responsible for destroying message
//IoTHubMessage_Destroy(msg);
ThreadAPI_Sleep(100);
send_interval_ms = millis();
bRST = bHOME = 0;
}
else
{
}
}
IoTHubClient_LL_DoWork(iotHubClientHandle);
ThreadAPI_Sleep(100);
} | 30.446043 | 171 | 0.625236 | tkopacz |
c52424c8d38cf9406241a25a52a4b317ab0f7fb3 | 20,372 | cpp | C++ | CastingEssentials/Modules/CameraTools.cpp | PazerOP/CastingEssentials | d0bd4265233a6fa8d428cdcba326ac0574354a03 | [
"BSD-2-Clause"
] | 30 | 2016-11-13T00:50:34.000Z | 2022-01-28T04:16:19.000Z | CastingEssentials/Modules/CameraTools.cpp | PazerOP/CastingEssentials | d0bd4265233a6fa8d428cdcba326ac0574354a03 | [
"BSD-2-Clause"
] | 92 | 2016-11-11T18:33:02.000Z | 2020-11-14T13:06:56.000Z | CastingEssentials/Modules/CameraTools.cpp | PazerOP/CastingEssentials | d0bd4265233a6fa8d428cdcba326ac0574354a03 | [
"BSD-2-Clause"
] | 12 | 2017-04-27T18:27:20.000Z | 2022-03-16T08:45:35.000Z | #include "CameraTools.h"
#include "Misc/CCvar.h"
#include "Misc/HLTVCameraHack.h"
#include "Modules/Camera/SimpleCameraSmooth.h"
#include "Modules/CameraSmooths.h"
#include "Modules/CameraState.h"
#include "PluginBase/Entities.h"
#include "PluginBase/HookManager.h"
#include "PluginBase/Interfaces.h"
#include "PluginBase/Player.h"
#include "PluginBase/TFDefinitions.h"
#include <client/c_baseplayer.h>
#include <filesystem.h>
#include <shared/gamerules.h>
#include <tier1/KeyValues.h>
#include <tier3/tier3.h>
#include <cdll_int.h>
#include <client/c_baseentity.h>
#include <characterset.h>
#include <functional>
#include <client/hltvcamera.h>
#include <toolframework/ienginetool.h>
#include <util_shared.h>
#include <client/c_baseanimating.h>
#include <vprof.h>
#include <algorithm>
MODULE_REGISTER(CameraTools);
static IClientEntityList* s_ClientEntityList;
static IVEngineClient* s_EngineClient;
CameraTools::CameraTools() :
ce_cameratools_autodirector_mode("ce_cameratools_autodirector_mode", "0", FCVAR_NONE,
"Forces the camera mode to this value while spec_autodirector is enabled. 0 = don't force anything"),
ce_cameratools_force_target("ce_cameratools_force_target", "-1", FCVAR_NONE, "Forces the camera target to this player index."),
ce_cameratools_disable_view_punches("ce_cameratools_disable_view_punches", "0", FCVAR_NONE,
"Disables all view punches (used for recoil effects on some weapons)",
[](IConVar* var, const char*, float) { GetModule()->ToggleDisableViewPunches(static_cast<ConVar*>(var)); }),
ce_cameratools_spec_entindex("ce_cameratools_spec_entindex", [](const CCommand& args) { GetModule()->SpecEntIndex(args); },
"Spectates a player by entindex"),
ce_cameratools_spec_pos("ce_cameratools_spec_pos", [](const CCommand& args) { GetModule()->SpecPosition(args); },
"Moves the camera to a given position and angle."),
ce_cameratools_spec_pos_delta("ce_cameratools_spec_pos_delta", [](const CCommand& args) { GetModule()->SpecPositionDelta(args); },
"Offsets the camera by the given values."),
ce_cameratools_spec_class("ce_cameratools_spec_class", [](const CCommand& args) { GetModule()->SpecClass(args); },
"Spectates a specific class: ce_cameratools_spec_class <team> <class> [index]"),
ce_cameratools_spec_steamid("ce_cameratools_spec_steamid", [](const CCommand& args) { GetModule()->SpecSteamID(args); },
"Spectates a player with the given steamid: ce_cameratools_spec_steamid <steamID>"),
ce_cameratools_spec_index("ce_cameratools_spec_index", [](const CCommand& args) { GetModule()->SpecIndex(args); },
"Spectate a player based on their index in the tournament spectator hud."),
ce_cameratools_smoothto("ce_cameratools_smoothto", &SmoothTo,
"Interpolates between the current camera and a given target: "
"\"ce_cameratools_smoothto <x> <y> <z> <pitch> <yaw> <roll> [duration] [smooth mode] [force]\"\n"
"\tSmooth mode can be either linear or smoothstep, default linear."),
ce_cameratools_show_users("ce_cameratools_show_users", [](const CCommand& args) { GetModule()->ShowUsers(args); },
"Lists all currently connected players on the server.")
{
}
bool CameraTools::CheckDependencies()
{
Modules().Depend<CameraState>();
if (!CheckDependency(Interfaces::GetClientEntityList(), s_ClientEntityList))
return false;
if (!CheckDependency(Interfaces::GetEngineClient(), s_EngineClient))
return false;
if (!Player::CheckDependencies())
{
PluginWarning("Required player helper class for module %s not available!\n", GetModuleName());
return false;
}
return true;
}
void CameraTools::SpecPosition(const Vector& pos, const QAngle& angle, ObserverMode mode, float fov)
{
if (mode == OBS_MODE_FIXED)
{
auto cam = std::make_shared<SimpleCamera>();
cam->m_Origin = pos;
cam->m_Angles = angle;
cam->m_FOV = fov == INFINITY ? 90 : fov;
cam->m_Type = CameraType::Fixed;
CameraState::GetModule()->SetCamera(cam);
}
else if (mode == OBS_MODE_ROAMING)
{
auto cam = std::make_shared<RoamingCamera>();
cam->SetPosition(pos, angle);
if (fov != INFINITY)
cam->SetFOV(fov);
CameraState::GetModule()->SetCamera(cam);
}
else
{
Warning("%s: Programmer error! mode was %i\n", __FUNCTION__, mode);
}
}
float CameraTools::CollisionTest3D(const Vector& startPos, const Vector& targetPos, float scale, const IHandleEntity* ignoreEnt)
{
static constexpr Vector TEST_POINTS[27] =
{
Vector(0, 0, 0),
Vector(0, 0, 0.5),
Vector(0, 0, 1),
Vector(0, 0.5, 0),
Vector(0, 0.5, 0.5),
Vector(0, 0.5, 1),
Vector(0, 1, 0),
Vector(0, 1, 0.5),
Vector(0, 1, 1),
Vector(0.5, 0, 0),
Vector(0.5, 0, 0.5),
Vector(0.5, 0, 1),
Vector(0.5, 0.5, 0),
Vector(0.5, 0.5, 0.5),
Vector(0.5, 0.5, 1),
Vector(0.5, 1, 0),
Vector(0.5, 1, 0.5),
Vector(0.5, 1, 1),
Vector(1, 0, 0),
Vector(1, 0, 0.5),
Vector(1, 0, 1),
Vector(1, 0.5, 0),
Vector(1, 0.5, 0.5),
Vector(1, 0.5, 1),
Vector(1, 1, 0),
Vector(1, 1, 0.5),
Vector(1, 1, 1),
};
const Vector scaleVec(scale);
const Vector mins(targetPos - Vector(scale));
const Vector maxs(targetPos + Vector(scale));
const Vector delta = maxs - mins;
size_t pointsPassed = 0;
for (const auto& testPoint : TEST_POINTS)
{
const Vector worldTestPoint = mins + delta * testPoint;
trace_t tr;
UTIL_TraceLine(startPos, worldTestPoint, MASK_VISIBLE, ignoreEnt, COLLISION_GROUP_NONE, &tr);
if (tr.fraction >= 1)
pointsPassed++;
}
return pointsPassed / float(std::size(TEST_POINTS));
}
void CameraTools::GetSmoothTestSettings(const std::string_view& testsString, SmoothSettings& settings)
{
if (stristr(testsString, "all"sv) != testsString.end())
{
settings.m_TestFOV = true;
settings.m_TestDist = true;
settings.m_TestCooldown = true;
settings.m_TestLOS = true;
}
else
{
settings.m_TestFOV = stristr(testsString, "fov"sv) != testsString.end();
settings.m_TestDist = stristr(testsString, "dist"sv) != testsString.end();
settings.m_TestCooldown = stristr(testsString, "time"sv) != testsString.end();
settings.m_TestLOS = stristr(testsString, "los"sv) != testsString.end();
}
}
void CameraTools::SpecModeChanged(ObserverMode oldMode, ObserverMode& newMode)
{
static ConVarRef spec_autodirector("spec_autodirector");
if (!spec_autodirector.GetBool())
return;
const auto forceMode = ce_cameratools_autodirector_mode.GetInt();
switch (forceMode)
{
case OBS_MODE_NONE:
return;
case OBS_MODE_FIXED:
case OBS_MODE_IN_EYE:
case OBS_MODE_CHASE:
case OBS_MODE_ROAMING:
newMode = (ObserverMode)forceMode;
break;
default:
Warning("Unknown/unsupported value %i for %s\n", forceMode, ce_cameratools_autodirector_mode.GetName());
}
}
void CameraTools::SpecTargetChanged(IClientEntity* oldEnt, IClientEntity*& newEnt)
{
if (auto ent = s_ClientEntityList->GetClientEntity(ce_cameratools_force_target.GetInt()))
newEnt = ent;
}
void CameraTools::ShowUsers(const CCommand& command)
{
std::vector<Player*> red;
std::vector<Player*> blu;
for (Player* player : Player::Iterable())
{
if (player->GetClass() == TFClassType::Unknown)
continue;
switch (player->GetTeam())
{
case TFTeam::Red:
red.push_back(player);
break;
case TFTeam::Blue:
blu.push_back(player);
break;
default:
continue;
}
}
Msg("%i Players:\n", red.size() + blu.size());
for (size_t i = 0; i < red.size(); i++)
ConColorMsg(Color(255, 128, 128, 255), " alias player_red%i \"%s %s\" // %s (%s)\n", i, ce_cameratools_spec_steamid.GetName(), RenderSteamID(red[i]->GetSteamID().ConvertToUint64()).c_str(), red[i]->GetName(), TF_CLASS_NAMES[(int)red[i]->GetClass()]);
for (size_t i = 0; i < blu.size(); i++)
ConColorMsg(Color(128, 128, 255, 255), " alias player_blu%i \"%s %s\" // %s (%s)\n", i, ce_cameratools_spec_steamid.GetName(), RenderSteamID(blu[i]->GetSteamID().ConvertToUint64()).c_str(), blu[i]->GetName(), TF_CLASS_NAMES[(int)blu[i]->GetClass()]);
}
void CameraTools::SpecClass(const CCommand& command)
{
// Usage: <team> <class> [classIndex]
if (command.ArgC() < 3 || command.ArgC() > 4)
{
PluginWarning("%s: Expected either 2 or 3 arguments\n", command.Arg(0));
goto Usage;
}
TFTeam team;
if (!strnicmp(command.Arg(1), "blu", 3))
team = TFTeam::Blue;
else if (!strnicmp(command.Arg(1), "red", 3))
team = TFTeam::Red;
else
{
PluginWarning("%s: Unknown team \"%s\"\n", command.Arg(0), command.Arg(1));
goto Usage;
}
TFClassType playerClass;
if (!stricmp(command.Arg(2), "scout"))
playerClass = TFClassType::Scout;
else if (!stricmp(command.Arg(2), "soldier") || !stricmp(command.Arg(2), "solly"))
playerClass = TFClassType::Soldier;
else if (!stricmp(command.Arg(2), "pyro"))
playerClass = TFClassType::Pyro;
else if (!strnicmp(command.Arg(2), "demo", 4))
playerClass = TFClassType::DemoMan;
else if (!strnicmp(command.Arg(2), "heavy", 5) || !stricmp(command.Arg(2), "hoovy") || !stricmp(command.Arg(2), "pootis"))
playerClass = TFClassType::Heavy;
else if (!stricmp(command.Arg(2), "engineer") || !stricmp(command.Arg(2), "engie"))
playerClass = TFClassType::Engineer;
else if (!stricmp(command.Arg(2), "medic"))
playerClass = TFClassType::Medic;
else if (!stricmp(command.Arg(2), "sniper"))
playerClass = TFClassType::Sniper;
else if (!stricmp(command.Arg(2), "spy") | !stricmp(command.Arg(2), "sphee"))
playerClass = TFClassType::Spy;
else
{
PluginWarning("%s: Unknown class \"%s\"\n", command.Arg(0), command.Arg(2));
goto Usage;
}
int classIndex = -1;
if (command.ArgC() > 3 && !TryParseInteger(command.Arg(3), classIndex))
{
PluginWarning("%s: class index \"%s\" is not an integer\n", command.Arg(0), command.Arg(3));
goto Usage;
}
SpecClass(team, playerClass, classIndex);
return;
Usage:
PluginWarning("Usage: %s\n", ce_cameratools_spec_class.GetHelpText());
}
void CameraTools::SpecClass(TFTeam team, TFClassType playerClass, int classIndex)
{
int validPlayersCount = 0;
Player* validPlayers[MAX_PLAYERS];
for (Player* player : Player::Iterable())
{
if (player->GetTeam() != team || player->GetClass() != playerClass)
continue;
validPlayers[validPlayersCount++] = player;
}
if (validPlayersCount == 0)
return; // Nobody to switch to
// If classIndex was not specified, cycle through the available options
if (classIndex < 0)
{
auto localMode = CameraState::GetModule()->GetLocalObserverMode();
if (localMode == OBS_MODE_FIXED ||
localMode == OBS_MODE_IN_EYE ||
localMode == OBS_MODE_CHASE)
{
Player* spectatingPlayer = Player::AsPlayer(CameraState::GetModule()->GetLocalObserverTarget());
int currentIndex = -1;
for (int i = 0; i < validPlayersCount; i++)
{
if (validPlayers[i] == spectatingPlayer)
{
currentIndex = i;
break;
}
}
classIndex = currentIndex + 1;
}
}
if (classIndex < 0 || classIndex >= validPlayersCount)
classIndex = 0;
SpecPlayer(validPlayers[classIndex]->GetEntity()->entindex());
}
void CameraTools::SpecEntIndex(const CCommand& command)
{
if (command.ArgC() != 2)
{
PluginWarning("%s: Expected 1 argument\n", command.Arg(0));
goto Usage;
}
int index;
if (!TryParseInteger(command.Arg(1), index))
{
PluginWarning("%s: entindex \"%s\" is not an integer\n", command.Arg(0), command.Arg(1));
goto Usage;
}
SpecPlayer(index);
return;
Usage:
PluginWarning("Usage: %s <entindex>\n", command.Arg(0));
}
void CameraTools::SpecPlayer(int playerIndex)
{
Player* player = Player::GetPlayer(playerIndex, __FUNCSIG__);
if (!player)
{
Warning("%s: Unable to find a player with an entindex of %i\n", __FUNCSIG__, playerIndex);
return;
}
if (!player->IsAlive())
{
DevWarning("%s: Not speccing \"%s\" because they are dead (%s)\n", __FUNCTION__, player->GetName());
return;
}
char buf[32];
sprintf_s(buf, "spec_player \"#%i\"", player->GetUserID());
s_EngineClient->ClientCmd(buf);
}
void CameraTools::SmoothTo(const CCommand& cmd)
{
auto cs = CameraState::GetModule();
if (!cs)
{
Warning("%s: Unable to get Camera State module\n", cmd[0]);
return;
}
do
{
if (cmd.ArgC() < 1 || cmd.ArgC() > 10)
break;
const auto& activeCam = cs->GetCurrentCamera();
if (!activeCam)
{
Warning("%s: No current active camera?\n", cmd[0]);
break;
}
const auto& currentPos = activeCam->GetOrigin();
const auto& currentAng = activeCam->GetAngles();
auto startCam = std::make_shared<SimpleCamera>();
{
startCam->m_Angles = activeCam->GetAngles();
startCam->m_Origin = activeCam->GetOrigin();
startCam->m_FOV = activeCam->GetFOV();
}
Vector endCamPos;
QAngle endCamAng;
for (uint_fast8_t i = 0; i < 6; i++)
{
const auto& arg = cmd.ArgC() > i + 1 ? cmd[i + 1] : "?";
auto& param = i < 3 ? endCamPos[i] : endCamAng[i - 3];
if (arg[0] == '?' && arg[1] == '\0')
param = i < 3 ? currentPos[i] : currentAng[i - 3];
else if (!TryParseFloat(arg, param))
{
Warning("%s: Unable to parse \"%s\" (arg %i) as a float\n", cmd[0], arg, i);
break;
}
}
SmoothSettings settings;
if (cmd.ArgC() > 7 && !TryParseFloat(cmd[7], settings.m_DurationOverride))
{
Warning("%s: Unable to parse arg 7 (duration, \"%s\") as a float\n", cmd[0], cmd[7]);
break;
}
if (cmd.ArgC() > 8 && (cmd[8][0] != '?' || cmd[8][1] != '\0'))
{
if (!stricmp(cmd[8], "linear"))
settings.m_InterpolatorOverride = &Interpolators::Linear;
else if (!stricmp(cmd[8], "smoothstep"))
settings.m_InterpolatorOverride = &Interpolators::Smoothstep;
else
Warning("%s: Unrecognized smooth mode %s, defaulting to linear\n", cmd[0], cmd[8]);
}
if (cmd.ArgC() > 9)
GetSmoothTestSettings(cmd[9], settings);
else
{
settings.m_TestFOV = false;
settings.m_TestCooldown = false;
}
auto endCam = std::make_shared<RoamingCamera>();
endCam->SetInputEnabled(false);
endCam->SetPosition(endCamPos, endCamAng);
cs->SetCameraSmoothed(endCam, settings);
return;
} while (false);
Warning("Usage: %s [x] [y] [z] [pitch] [yaw] [roll] [duration] [smooth mode] [tests]\n"
"\tSmooth mode can be either linear or smoothstep.\n"
"\tIf any of the pos/angle parameters are '?' or omitted, they are left untouched.\n"
"\t'?' or omission for duration and smooth mode means use ce_smoothing_ cvars.\n"
"\ttests: default 'dist+los'. Can be 'all', 'none', or combined with '+' (NO SPACES):\n"
"\t\tlos: Don't smooth if we don't have LOS to the target (ce_smoothing_los_)\n"
"\t\tdist: Don't smooth if we're too far away (ce_smoothing_*_distance)\n"
"\t\ttime: Don't smooth if we're still on cooldown (ce_smoothing_cooldown)\n"
"\t\tfov: Don't smooth if target is outside of fov (ce_smoothing_fov)\n"
, cmd[0]);
}
void CameraTools::ToggleDisableViewPunches(const ConVar* var)
{
if (var->GetBool())
{
auto angle = Entities::FindRecvProp("CTFPlayer", "m_vecPunchAngle");
auto velocity = Entities::FindRecvProp("CTFPlayer", "m_vecPunchAngleVel");
if (!angle)
{
PluginWarning("%s: Unable to locate RecvProp for C_TFPlayer::m_vecPunchAngle\n", var->GetName());
return;
}
if (!velocity)
{
PluginWarning("%s: Unable to locate RecvProp for C_TFPlayer::m_vecPunchAngleVel\n", var->GetName());
return;
}
RecvVarProxyFn zeroProxy = [](const CRecvProxyData* pData, void* pStruct, void* pOut)
{
auto outVec = reinterpret_cast<Vector*>(pOut);
outVec->Init(0, 0, 0);
};
m_vecPunchAngleProxy = CreateVariablePusher(angle->m_ProxyFn, zeroProxy);
m_vecPunchAngleVelProxy = CreateVariablePusher(velocity->m_ProxyFn, zeroProxy);
}
else
{
m_vecPunchAngleProxy.Clear();
m_vecPunchAngleVelProxy.Clear();
}
}
void CameraTools::SpecSteamID(const CCommand& command)
{
CCommand newCommand;
if (!ReparseForSteamIDs(command, newCommand))
return;
CSteamID parsed;
if (newCommand.ArgC() != 2)
{
PluginWarning("%s: Expected 1 argument\n", command.Arg(0));
goto Usage;
}
parsed.SetFromString(newCommand.Arg(1), k_EUniverseInvalid);
if (!parsed.IsValid())
{
PluginWarning("%s: Unable to parse steamid\n", command.Arg(0));
goto Usage;
}
for (Player* player : Player::Iterable())
{
if (player->GetSteamID() == parsed)
{
SpecPlayer(player->GetEntity()->entindex());
return;
}
}
Warning("%s: couldn't find a user with the steam id %s on the server\n", command.Arg(0), RenderSteamID(parsed).c_str());
return;
Usage:
PluginWarning("Usage: %s\n", ce_cameratools_spec_steamid.GetHelpText());
}
void CameraTools::SpecIndex(const CCommand& command)
{
if (command.ArgC() != 3)
goto Usage;
TFTeam team;
if (tolower(command.Arg(1)[0]) == 'r')
team = TFTeam::Red;
else if (tolower(command.Arg(1)[0]) == 'b')
team = TFTeam::Blue;
else
goto Usage;
// Create an array of all our players on the specified team
Player* allPlayers[MAX_PLAYERS];
const auto endIter = Player::GetSortedPlayers(team, std::begin(allPlayers), std::end(allPlayers));
const auto playerCount = std::distance(std::begin(allPlayers), endIter);
char* endPtr;
const auto index = std::strtol(command.Arg(2), &endPtr, 0);
if (endPtr == command.Arg(2))
goto Usage; // Couldn't parse index
if (index < 0 || index >= playerCount)
{
if (playerCount < 1)
PluginWarning("%s: No players on team %s\n", command.Arg(0), command.Arg(1));
else
PluginWarning("Specified index \"%s\" for %s, but valid indices for team %s were [0, %i]\n",
command.Arg(2), command.Arg(0), command.Arg(1), playerCount - 1);
return;
}
SpecPlayer(allPlayers[index]->entindex());
return;
Usage:
PluginWarning("Usage: %s <red/blue> <index>\n", command.Arg(0));
}
bool CameraTools::ParseSpecPosCommand(const CCommand& command, Vector& pos, QAngle& ang, ObserverMode& mode,
const Vector& defaultPos, const QAngle& defaultAng, ObserverMode defaultMode) const
{
if (command.ArgC() < 2 || command.ArgC() > 8)
goto PrintUsage;
for (int i = 1; i < 7; i++)
{
const auto arg = i < command.ArgC() ? command.Arg(i) : nullptr;
float& param = i < 4 ? pos[i - 1] : ang[i - 4];
if (!arg || (arg[0] == '?' && arg[1] == '\0'))
{
param = i < 4 ? defaultPos[i - 1] : defaultAng[i - 4];
}
else if (!TryParseFloat(arg, param))
{
PluginWarning("Invalid parameter \"%s\" (arg %i) for %s command\n", command.Arg(i), i - 1, command.Arg(0));
goto PrintUsage;
}
}
mode = defaultMode;
if (command.ArgC() > 7)
{
const auto modeArg = command.Arg(7);
if (!stricmp(modeArg, "fixed"))
mode = OBS_MODE_FIXED;
else if (!stricmp(modeArg, "free"))
mode = OBS_MODE_ROAMING;
else if (modeArg[0] != '?' || modeArg[1] != '\0')
{
PluginWarning("Invalid parameter \"%s\" for mode (expected \"fixed\" or \"free\")\n");
goto PrintUsage;
}
}
return true;
PrintUsage:
PluginMsg(
"Usage: %s x [y] [z] [pitch] [yaw] [roll] [mode]\n"
"\tIf any of the parameters are '?' or omitted, they are left untouched.\n"
"\tMode can be either \"fixed\" or \"free\"\n",
command.Arg(0));
return false;
}
void CameraTools::SpecPosition(const CCommand& command)
{
const auto camState = CameraState::GetModule();
if (!camState)
{
Warning("%s: Failed to get CameraState module\n", command[0]);
return;
}
ObserverMode defaultMode = camState->GetDesiredObserverMode();
if (defaultMode != OBS_MODE_FIXED && defaultMode != OBS_MODE_ROAMING)
defaultMode = OBS_MODE_ROAMING;
const auto activeCam = camState->GetCurrentCamera();
if (!activeCam)
{
Warning("%s: No active camera?\n", command[0]);
return;
}
Vector pos;
QAngle ang;
ObserverMode mode;
if (ParseSpecPosCommand(command, pos, ang, mode, activeCam->GetOrigin(), activeCam->GetAngles(), defaultMode))
SpecPosition(pos, ang, mode);
}
void CameraTools::SpecPositionDelta(const CCommand& command)
{
const auto camState = CameraState::GetModule();
if (!camState)
{
Warning("%s: Failed to get CameraState module\n", command[0]);
return;
}
ObserverMode defaultMode = camState->GetDesiredObserverMode();
if (defaultMode != OBS_MODE_FIXED && defaultMode != OBS_MODE_ROAMING)
defaultMode = OBS_MODE_ROAMING;
const auto activeCam = camState->GetCurrentCamera();
if (!activeCam)
{
Warning("%s: No active camera?\n", command[0]);
return;
}
Vector pos;
QAngle ang;
ObserverMode mode;
if (ParseSpecPosCommand(command, pos, ang, mode, vec3_origin, vec3_angle, defaultMode))
{
pos += activeCam->GetOrigin();
ang += activeCam->GetAngles();
SpecPosition(pos, ang, mode);
}
}
| 28.452514 | 256 | 0.6828 | PazerOP |
c52514166be8497b2091345590192675581da905 | 2,434 | hpp | C++ | Camera.hpp | Adrijaned/oglPlaygorund | ce3c31669263545650efcc4b12dd22e6517ccaa7 | [
"MIT"
] | null | null | null | Camera.hpp | Adrijaned/oglPlaygorund | ce3c31669263545650efcc4b12dd22e6517ccaa7 | [
"MIT"
] | null | null | null | Camera.hpp | Adrijaned/oglPlaygorund | ce3c31669263545650efcc4b12dd22e6517ccaa7 | [
"MIT"
] | null | null | null | //
// Created by adrijarch on 5/11/19.
//
#ifndef OGLPLAYGROUND_CAMERA_HPP
#define OGLPLAYGROUND_CAMERA_HPP
#include <glm/glm.hpp>
/**
* OGL style camera for computing view matrix for use by shaders.
*/
class Camera {
/**
* Position of the camera itself in the source coordinate system.
*/
glm::vec3 position = glm::vec3{0, 0, 0};
/**
* Rotation along the y axis, achieved by moving mouse horizontally.
* Radians normalized in range [0, 2 * PI].
*/
float yaw = 0;
/**
* Rotation in up/down manner, achieved by moving mouse vertically.
* Radians clamped in range [ - PI / 2, PI / 2 ].
*/
float pitch = 0;
/**
* Denotes whether anything in this class has been changed since last
* recalculation of \c target.
* This is handy to speed up calculations in some cases.
* @see viewMatrix
*/
bool dirty = true;
/**
* The last computed view matrix.
* This is handy to speed up calculation in some cases.
* @see dirty
*/
glm::mat4 viewMatrix{1.0f};
public:
/**
* Returns the view matrix from this camera
* @return The view matrix
*/
const glm::mat4 getView();
/**
* Changes the camera yaw by given value in radians.
* Yaw is expected to refer to rotation along the vertical/y axis in clockwise
* manner.
* @param value Value in radians to change yaw by.
* @return self for method chaining.
*/
Camera &changeYaw(float value);
/**
* Changes the camera pitch by given value in radians.
* Pitch is expected to refer to rotation in up/down manner / along the
* horizontal axis ortogonal to direction denoted by yaw, with positive
* numbers used for the up direction.
*
* @warning Resulting pitch value is @b clamped to range @f$
* \left\langle-\frac{\pi}{2},\frac{\pi}{2}\right\rangle
* @f$
* @param value Value in radians to change pitch by.
* @return self for method chaining.
*/
Camera &changePitch(float value);
/**
* Possible directions Camera can move in.
* @see move
*/
enum MovementDirection {
UP, DOWN, FORWARD, BACKWARD, LEFT, RIGHT
};
const glm::vec3 &getPosition() const;
/**
* Moves this camera in given direction relative by current @b yaw.
* @param direction Direction to move into
* @param distance Distance to move by
* @return self for method chaining.
*/
Camera& move(const MovementDirection& direction, float distance);
};
#endif //OGLPLAYGROUND_CAMERA_HPP
| 26.456522 | 80 | 0.672555 | Adrijaned |
c52f1092a61bc918798d7d1d82e3255581c72fa1 | 2,158 | cpp | C++ | dictionary_std_vector/src/dictionary_std_vector.cpp | Arghnews/wordsearch_solver | cf25db64ca3d1facd9191aad075654f124f0d580 | [
"MIT"
] | null | null | null | dictionary_std_vector/src/dictionary_std_vector.cpp | Arghnews/wordsearch_solver | cf25db64ca3d1facd9191aad075654f124f0d580 | [
"MIT"
] | null | null | null | dictionary_std_vector/src/dictionary_std_vector.cpp | Arghnews/wordsearch_solver | cf25db64ca3d1facd9191aad075654f124f0d580 | [
"MIT"
] | null | null | null | #include "wordsearch_solver/dictionary_std_vector/dictionary_std_vector.hpp"
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <range/v3/view/all.hpp>
#include <range/v3/view/transform.hpp>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <ostream>
#include <string>
#include <string_view>
#include <vector>
namespace dictionary_std_vector {
DictionaryStdVector::DictionaryStdVector(
const std::initializer_list<std::string_view>& words)
: DictionaryStdVector(ranges::views::all(words)) {}
DictionaryStdVector::DictionaryStdVector(
const std::initializer_list<std::string>& words)
: DictionaryStdVector(ranges::views::all(words)) {}
DictionaryStdVector::DictionaryStdVector(
const std::initializer_list<const char*>& words)
: DictionaryStdVector(
ranges::views::all(words) |
ranges::views::transform([](const auto string_literal) {
return std::string_view{string_literal};
})) {}
std::size_t DictionaryStdVector::size() const { return dict_.size(); }
bool DictionaryStdVector::empty() const { return dict_.empty(); }
bool DictionaryStdVector::contains(const std::string_view word) const {
return std::binary_search(dict_.begin(), dict_.end(), word);
}
bool DictionaryStdVector::further(const std::string_view word) const {
return this->further_impl(word, dict_.begin(), dict_.end());
}
bool DictionaryStdVector::further_impl(const std::string_view prefix,
const Iterator first,
const Iterator last) const {
assert(last >= first);
const auto it = std::upper_bound(first, last, prefix);
if (it == last) {
return false;
}
const auto& word = *it;
if (word.size() < prefix.size()) {
return false;
}
return std::equal(
prefix.begin(), prefix.end(), word.begin(),
word.begin() +
static_cast<decltype(prefix)::difference_type>(prefix.size()));
}
std::ostream& operator<<(std::ostream& os, const DictionaryStdVector& dsv) {
return os << fmt::format("{}", dsv.dict_);
}
} // namespace dictionary_std_vector
| 30.394366 | 76 | 0.68165 | Arghnews |
c532c00b414b4ddb9685037a54ae024dc92ae6f4 | 3,943 | cpp | C++ | libcaf_core/test/node_id.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | 4 | 2019-05-03T05:38:15.000Z | 2020-08-25T15:23:19.000Z | libcaf_core/test/node_id.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/test/node_id.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2020 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#define CAF_SUITE node_id
#include "caf/node_id.hpp"
#include "caf/test/dsl.hpp"
#include "caf/binary_deserializer.hpp"
#include "caf/binary_serializer.hpp"
using namespace caf;
namespace {
node_id roundtrip(node_id nid) {
byte_buffer buf;
{
binary_serializer sink{nullptr, buf};
if (!sink.apply_object(nid))
CAF_FAIL("serialization failed: " << sink.get_error());
}
if (buf.empty())
CAF_FAIL("serializer produced no output");
node_id result;
{
binary_deserializer source{nullptr, buf};
if (!source.apply_object(result))
CAF_FAIL("deserialization failed: " << source.get_error());
if (source.remaining() > 0)
CAF_FAIL("binary_serializer ignored part of its input");
}
return result;
}
} // namespace
#define CHECK_PARSE_OK(str, ...) \
do { \
CAF_CHECK(node_id::can_parse(str)); \
node_id nid; \
CAF_CHECK_EQUAL(parse(str, nid), none); \
CAF_CHECK_EQUAL(nid, make_node_id(__VA_ARGS__)); \
} while (false)
CAF_TEST(node IDs are convertible from string) {
node_id::default_data::host_id_type hash{{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
}};
auto uri_id = unbox(make_uri("ip://foo:8080"));
CHECK_PARSE_OK("0102030405060708090A0B0C0D0E0F1011121314#1", 1, hash);
CHECK_PARSE_OK("0102030405060708090A0B0C0D0E0F1011121314#123", 123, hash);
CHECK_PARSE_OK("ip://foo:8080", uri_id);
}
#define CHECK_PARSE_FAIL(str) CAF_CHECK(!node_id::can_parse(str))
CAF_TEST(node IDs reject malformed strings) {
// not URIs
CHECK_PARSE_FAIL("foobar");
CHECK_PARSE_FAIL("CAF#1");
// uint32_t overflow on the process ID
CHECK_PARSE_FAIL("0102030405060708090A0B0C0D0E0F1011121314#42949672950");
}
CAF_TEST(node IDs are serializable) {
CAF_MESSAGE("empty node IDs remain empty");
{
node_id nil_id;
CAF_CHECK_EQUAL(nil_id, roundtrip(nil_id));
}
CAF_MESSAGE("hash-based node IDs remain intact");
{
auto tmp = make_node_id(42, "0102030405060708090A0B0C0D0E0F1011121314");
auto hash_based_id = unbox(tmp);
CAF_CHECK_EQUAL(hash_based_id, roundtrip(hash_based_id));
}
CAF_MESSAGE("URI-based node IDs remain intact");
{
auto uri_based_id = make_node_id(unbox(make_uri("foo:bar")));
CAF_CHECK_EQUAL(uri_based_id, roundtrip(uri_based_id));
}
}
| 39.43 | 80 | 0.503677 | jsiwek |
c533328548e5885b901f2ad1f6377d57a4c1c195 | 6,034 | cpp | C++ | code/src/utils/CommandLineParser.cpp | reuqlauQemoN/streamopenacc | c8d74dcea6b28e1038d76ab27fca5c23e21ecead | [
"Apache-1.1"
] | 69 | 2015-07-02T05:25:29.000Z | 2022-01-10T08:54:46.000Z | code/src/utils/CommandLineParser.cpp | xiaguoyang/streamDM-Cpp | 0304d03393f6987596aa445a0506631655297e79 | [
"Apache-1.1"
] | 3 | 2015-08-15T06:42:17.000Z | 2021-05-17T09:30:51.000Z | code/src/utils/CommandLineParser.cpp | xiaguoyang/streamDM-Cpp | 0304d03393f6987596aa445a0506631655297e79 | [
"Apache-1.1"
] | 40 | 2015-07-02T06:03:26.000Z | 2021-12-16T02:07:29.000Z | /*
* Copyright (C) 2015 Holmes Team at HUAWEI Noah's Ark Lab.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "CommandLineParser.h"
#include "../Common.h"
////////////////////////////// CommandLineParser //////////////////////////////
CommandLineParser::CommandLineParser() {
}
CommandLineParser::~CommandLineParser() {
}
/**
* parser command line string:
* 1. smartdm -f file.json
* 2. smartdm "EvaluateHoldOut -l (StreamingMBT) -r (StreamingMBTReader) -a train.txt -t test.txt"
* \param argc command line parameter number
* \param argv command line parameter
* \param param the output data
*/
bool CommandLineParser::parser(int argc, char* argv[], string& taskName, string& taskParam) {
if (argc != 2 && argc != 3) {
LOG_ERROR("Command line arguments error.");
return false;
}
if (argc == 2) {
return parserCommandLine(argv[1], taskName, taskParam);
}
if (argc == 3) {
string param(argv[1]);
string value(argv[2]);
if (param != "-f") {
LOG_ERROR("Command option: smartdm -f file.json");
return false;
}else if (! Utils::checkFileExist(value)) {
LOG_ERROR("File is not existed. %s", value.c_str());
return false;
}else{
return parserJsonFile(argv[1], taskName, taskParam);
}
}
return true;
}
/**
* parser command line string,
* link:
* 1. smartDM "EvaluatePrequential -l (VfdtLearner -sc 0.001 -tc 0.02) -r C45Reader -ds /opt/moa/alan/test/data/DF"
* 2. smartDM "EvaluatePrequential -l (Bagging -l (VfdtLearner -sc 0.001 -tc 0.02) -es 100) -r C45Reader -ds /opt/moa/alan/test/data/DF"
* 3. smartDM "EvaluatePrequential -l (VfdtLearner -sc 0.001 -tc 0.02) -r (C45Reader -ds /opt/moa/alan/test/data/DF)"
*/
bool CommandLineParser::parserCommandLine(
const string& in, string& taskName, string& taskParam) {
// segment "(", ")" with " "
stringstream ss;
for (int i=0; i < in.size(); i++) {
if (in[i] == '(' || in[i] == ')') {
ss << " " << in[i] << " ";
}
else {
ss << in[i];
}
}
string s;
vector<string> vec;
while (getline(ss, s, ' ' )) {
if (s.size() == 0) {
continue;
}
vec.push_back(s);
}
Json::Value jv;
int pos = 0;
string type = "Task";
bool ret = parser(vec, type, pos, jv);
if (!ret) {
return false;
}
taskName = jv["Name"].asString();
taskParam = jv.toStyledString();
return true;
}
/**
* parser json file,
* \param in is json file name.
*
* The file content model is :
*
{
"Task": {
"Name": "EvaluatePrequential",
"-l": {
"Name": "VfdtLearner",
"-sc": "0.001",
"-tc": "0.02"
},
"-r": "C45",
"-ds": "/opt/moa/alan/test/data/DF"
}
}
*
{
"Task": {
"Name": "EvaluatePrequential",
"-l": {
"Name": "Bagging",
"-l": {
"-sc": "0.001",
"-tc": "0.02",
"Name": "VfdtLearner"
}
},
"-r": "C45",
"-ds": "/opt/moa/alan/test/data/DF"
}
}
*
*/
bool CommandLineParser::parserJsonFile(
const string& in, string& taskName, string& taskParam) {
return true;
}
bool CommandLineParser::parser(vector<string>& vec, const string& type,
int& pos, Json::Value& jv) {
CLPFN &names = CLPFN::getInstance();
string className = vec[pos];
jv["Name"] = className;
if (names.data.find(className) == names.data.end()) {
LOG_ERROR("Not defined class: %s .", className.c_str());
return false;
}
auto &classParams = names.data[className];
pos++;
while (pos < vec.size()) {
// check exit condition
if (vec[pos] == ")") {
pos++;
return true;
}
// get name
string name = vec[pos];
if (name[0] != '-') {
LOG_ERROR("Error command line parameter: %s .", name.c_str());
return false;
}
auto iter = classParams.find(name);
if (iter == classParams.end()) {
LOG_ERROR("Not define class parameter, class: %s, parameter: %s .",
className.c_str(), name.c_str());
return false;
}
name = iter->second;
// get value
pos++;
if (pos == vec.size()) {
LOG_ERROR("Require command line parameter value: %s .", name.c_str());
return false;
}
string value = vec[pos];
// check nestling
if (value == "(") {
Json::Value jv2;
pos++;
if (pos+1 == vec.size() ) {
LOG_ERROR("Not enough command line parameter.");
return false;
}
bool ret = parser(vec, name, pos, jv2 );
if (!ret) {
return false;
}
jv[name] = jv2;
}
else {
jv[name] = value;
pos++;
}
}
return true;
}
////////////////////////////// CommandLineParameter ///////////////////////////
CommandLineParameter::CommandLineParameter() {
}
CommandLineParameter::~CommandLineParameter() {
}
string CommandLineParameter::getTaskName() {
return data["Task"]["Name"].asString();
}
string CommandLineParameter::getTaskParameter() {
return data["Task"].toStyledString();
}
////////////////////////////// CLPFN //////////////////////////////////////////
CLPFN::CLPFN() {
}
CLPFN& CLPFN::getInstance() {
static CLPFN instance;
return instance;
}
RegisterCommandLineParameterFullName::RegisterCommandLineParameterFullName(
const string& fullName) {
Json::Value jv;
Json::Reader reader;
reader.parse( fullName, jv );
CLPFN& names = CLPFN::getInstance();
string name = jv["name"].asString();
string type = jv["type"].asString();
Json::Value::Members m = jv["parameter"].getMemberNames();
names.data[name]["Type"] = type;
for (int i=0; i<m.size(); i++) {
names.data[name][m[i]] = jv["parameter"][m[i]].asString();
}
}
| 23.118774 | 136 | 0.592973 | reuqlauQemoN |
c53412834662148177d1887ff675abd21587750b | 519 | hpp | C++ | bullpen_sketch/state.hpp | estriz27/bullpen | 11ee415d7f2b2b211a2c9e34a173e016f298b85c | [
"MIT"
] | null | null | null | bullpen_sketch/state.hpp | estriz27/bullpen | 11ee415d7f2b2b211a2c9e34a173e016f298b85c | [
"MIT"
] | null | null | null | bullpen_sketch/state.hpp | estriz27/bullpen | 11ee415d7f2b2b211a2c9e34a173e016f298b85c | [
"MIT"
] | null | null | null | #ifndef __STATE__
#define __STATE__
#include "person.hpp"
#include <stdlib.h>
#include <vector>
#include <algorithm>
class State{
//Has a vector of class Person
std::vector<Person> people;
public:
State(std::vector<Person> people):people(people){}
std::vector<Person> getInList();
std::vector<Person> getOutList();
Person* getPerson(unsigned int personIndex);
bool isIn(unsigned int personIndex);
void togglePerson(unsigned int personIndex);//calls togglePresent on person at given index
};
#endif
| 21.625 | 92 | 0.739884 | estriz27 |
c535f8431ab336b1c7aa31b25ddd5ee5ce0c85b4 | 21,474 | cpp | C++ | lc7/src/CLC7ColorManager.cpp | phixion/l0phtcrack | 48ee2f711134e178dbedbd925640f6b3b663fbb5 | [
"Apache-2.0",
"MIT"
] | 2 | 2021-10-18T22:14:22.000Z | 2021-11-08T12:52:42.000Z | lc7/src/CLC7ColorManager.cpp | Brute-f0rce/l0phtcrack | 25f681c07828e5e68e0dd788d84cc13c154aed3d | [
"Apache-2.0",
"MIT"
] | null | null | null | lc7/src/CLC7ColorManager.cpp | Brute-f0rce/l0phtcrack | 25f681c07828e5e68e0dd788d84cc13c154aed3d | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-14T06:41:16.000Z | 2022-03-14T06:41:16.000Z | #include"stdafx.h"
#define QT_QTPROPERTYBROWSER_IMPORT
#include"../../external/qtpropertybrowser/src/QtPropertyManager.h"
#undef TR
#define TR
CLC7ColorManager::CLC7ColorManager()
{
TR;
m_currentScreen = qApp->primaryScreen();
ILC7Settings *settings = CLC7App::getInstance()->GetController()->GetSettings();
settings->AddValueChangedListener(this, (void (QObject::*)(QString, const QVariant &))&CLC7ColorManager::slot_settingsValueChanged);
m_default_shades["BASE"] = 0;
m_default_shades["BORDER_COLOR"] = 1;
m_default_shades["BUTTON_BKGD_0"] = 1;
m_default_shades["BUTTON_BKGD_1"] = 3;
m_default_shades["BUTTON_BKGD_PRESSED_0"] = -3;
m_default_shades["BUTTON_BKGD_PRESSED_1"] = 0;
m_default_shades["BUTTON_COLOR_DISABLED"] = 1;
m_default_shades["CHECKBOX_COLOR"] = 4;
m_default_shades["COMBO_SELECTION_BKGD"] = 1;
m_default_shades["CONTROL_BKGD"] = -1;
m_default_shades["CONTROL_BKGD_DISABLED"] = -2;
m_default_shades["DOCKWIDGET_BORDER"] = 2;
m_default_shades["EXTENDED_TAB_WIDGET_CHECKED_0"] = 2;
m_default_shades["EXTENDED_TAB_WIDGET_CHECKED_1"] = 0;
m_default_shades["EXTENDED_TAB_WIDGET_UNCHECKED_0"] = -3;
m_default_shades["EXTENDED_TAB_WIDGET_UNCHECKED_1"] = -1;
m_default_shades["HEADER_BKGD"] = 3;
m_default_shades["HEADER_BORDER"] = 4;
m_default_shades["HIGHLIGHT_BKGD_0"] = -3;
m_default_shades["HIGHLIGHT_BKGD_1"] = 3;
m_default_shades["HIGHLIGHT_CONTROL_BKGD_0"] = -5;
m_default_shades["HIGHLIGHT_CONTROL_BKGD_1"] = -4;
m_default_shades["HIGHLIGHT_CONTROL_BORDER"] = -3;
m_default_shades["HIGHLIGHT_CONTROL_TEXT"] = 4;
m_default_shades["PROGRESS_BKGD_0"] = 3;
m_default_shades["PROGRESS_BKGD_1"] = -3;
m_default_shades["SCROLL_H_BKGD_0"] = -2;
m_default_shades["SCROLL_H_BKGD_1"] = 2;
m_default_shades["SCROLL_HANDLE_H_BKGD_0"] = 2;
m_default_shades["SCROLL_HANDLE_H_BKGD_1"] = 3;
m_default_shades["SCROLL_HANDLE_V_BKGD_0"] = 2;
m_default_shades["SCROLL_HANDLE_V_BKGD_1"] = 3;
m_default_shades["SCROLL_V_BKGD_0"] = -2;
m_default_shades["SCROLL_V_BKGD_1"] = 2;
m_default_shades["SELECT_BKGD_0"] = 4;
m_default_shades["SELECT_BKGD_1"] = 2;
m_default_shades["SEP_COLOR_1"] = 3;
m_default_shades["SHADOW"] = -4;
m_default_shades["SLIDER_COLOR_0"] = 5;
m_default_shades["SLIDER_COLOR_1"] = 4;
m_default_shades["TEXT_DISABLED"] = 2;
m_default_shades["TOOLTIP_BKGD"] = 3;
m_default_shades["WIDGET_BKGD"] = -2;
m_default_shades["WIDGET_DISABLED"] = 1;
m_temporary_dir = CLC7App::getInstance()->GetController()->NewTemporaryDir();
slot_reloadSettings();
m_bNeedsReload = false;
}
CLC7ColorManager::~CLC7ColorManager()
{
TR;
if (!m_temporary_dir.isEmpty())
{
QDir dir(m_temporary_dir);
if (dir.exists())
{
dir.removeRecursively();
}
m_temporary_dir = "";
}
}
ILC7Interface *CLC7ColorManager::GetInterfaceVersion(QString interface_name)
{
if (interface_name == "ILC7ColorManager")
{
return this;
}
return NULL;
}
QIcon CLC7ColorManager::GetMonoColorIcon(QString resource, QColor normal, QColor active, QColor disabled)
{
TR;
if (!normal.isValid())
{
normal = QColor(GetBaseShade("HEADER_BORDER"));
}
if (!active.isValid())
{
active = QColor(GetHighlightShade("BASE"));
}
if (!disabled.isValid())
{
disabled = QColor(GetBaseShade("BORDER_COLOR"));
}
QPixmap pixmap_normal(GetMonoColorPixmapResource(resource, normal));
QPixmap pixmap_active(GetMonoColorPixmapResource(resource, active));
QPixmap pixmap_disabled(GetMonoColorPixmapResource(resource, disabled));
QIcon icon;
icon.addPixmap(pixmap_normal, QIcon::Normal, QIcon::Off);
icon.addPixmap(pixmap_active, QIcon::Active, QIcon::Off);
icon.addPixmap(pixmap_active, QIcon::Selected, QIcon::Off);
icon.addPixmap(pixmap_disabled, QIcon::Disabled, QIcon::Off);
icon.addPixmap(pixmap_normal, QIcon::Normal, QIcon::On);
icon.addPixmap(pixmap_active, QIcon::Active, QIcon::On);
icon.addPixmap(pixmap_active, QIcon::Selected, QIcon::On);
icon.addPixmap(pixmap_disabled, QIcon::Disabled, QIcon::On);
return icon;
}
QMap<QString, int> CLC7ColorManager::GetDefaultShades()
{
TR;
return m_default_shades;
}
QColor CLC7ColorManager::GetDefaultBaseColor()
{
TR;
return QColor("#505050");
}
QColor CLC7ColorManager::GetDefaultHighlightColor()
{
TR;
return QColor("#F27800");
}
void CLC7ColorManager::slot_settingsValueChanged(QString key, const QVariant &val)
{
TR;
if (key.startsWith("_theme_:"))
{
ReloadSettings();
}
}
void CLC7ColorManager::ReloadSettings(void)
{
TR;
if (!m_bNeedsReload)
{
m_bNeedsReload = true;
const bool isGuiThread = (QThread::currentThread() == QCoreApplication::instance()->thread());
if (isGuiThread)
{
slot_reloadSettings();
}
else
{
QTimer::singleShot(0, this, &CLC7ColorManager::slot_reloadSettings);
}
}
}
void CLC7ColorManager::slot_reloadSettings(void)
{
TR;
if (!m_temporary_dir.isEmpty())
{
QDir dir(m_temporary_dir);
if (dir.exists())
{
dir.removeRecursively();
}
m_temporary_dir = "";
}
m_temporary_dir = CLC7App::getInstance()->GetController()->NewTemporaryDir();
ILC7Settings *settings = CLC7App::getInstance()->GetController()->GetSettings();
m_basecolor = settings->value("_theme_:basecolor", GetDefaultBaseColor()).value<QColor>();
m_highlightcolor = settings->value("_theme_:highlightcolor", GetDefaultHighlightColor()).value<QColor>();
m_shades.clear();
#ifdef _DEBUG
foreach(QString key, m_default_shades.keys())
{
m_shades[key] = settings->value(QString("_theme_:shade_") + key, m_default_shades[key]).toInt();
}
#else
m_shades=m_default_shades;
#endif
RecalculateColors();
m_bNeedsReload = false;
}
void CLC7ColorManager::SetBaseColor(QColor color)
{
TR;
m_basecolor = color;
RecalculateColors();
}
QColor CLC7ColorManager::GetBaseColor()
{
TR;
return m_basecolor;
}
void CLC7ColorManager::SetHighlightColor(QColor color)
{
TR;
m_highlightcolor = color;
RecalculateColors();
}
QColor CLC7ColorManager::GetHighlightColor()
{
TR;
return m_highlightcolor;
}
QString CLC7ColorManager::GetTextColor()
{
TR;
return m_textcolor.name(QColor::HexRgb);
}
QString CLC7ColorManager::GetInverseTextColor()
{
TR;
int h, s, l;
m_textcolor.getHsl(&h, &s, &l);
l = 255 - l;
return QColor::fromHsl(h, s, l).name(QColor::HexRgb);
}
static void applyShade(int shade, int &h, int &s, int &l)
{
if (l >= 128)
{
shade = -shade;
}
if (shade > 0)
{
l += ((shade * (255 - l)) / 8);
}
else
{
l += ((shade * l) / 8);
}
}
QString CLC7ColorManager::GetHighlightShade(QString name)
{
TR;
int h, s, l;
m_highlightcolor.getHsl(&h, &s, &l);
int shade = m_shades[name];
applyShade(shade, h, s, l);
return QColor::fromHsl(h, s, l).name(QColor::HexRgb);
}
QString CLC7ColorManager::GetBaseShade(QString name)
{
TR;
int h, s, l;
m_basecolor.getHsl(&h, &s, &l);
int shade = m_shades[name];
applyShade(shade, h, s, l);
return QColor::fromHsl(h, s, l).name(QColor::HexRgb);
}
QString CLC7ColorManager::GetStyleSheet(void)
{
TR;
return m_stylesheet;
}
#ifdef Q_OS_WIN
const float DEFAULT_DPI = 96.0;
#endif //Q_OS_WIN
void CLC7ColorManager::RecalculateColors()
{
TR;
// determine if screen should be hidpi or not
qreal logicaldpi = m_currentScreen->logicalDotsPerInch();
qreal logicalpixelratio = logicaldpi / DEFAULT_DPI;
if (logicalpixelratio >= 1.5)
{
m_size_ratio = 2;
}
else
{
m_size_ratio = 1;
}
int h, s, l;
m_basecolor.getHsl(&h, &s, &l);
if (l < 128)
{
m_textcolor = QColor("#FFFFFF");
}
else
{
m_textcolor = QColor("#000000");
}
// Load stylesheet
QString strStyleSheet;
#ifdef _DEBUG
if (QFile::exists("../../../lc7/resources/darkstyle.qss"))
{
QFile res("../../../lc7/resources/darkstyle.qss");
res.open(QIODevice::ReadOnly);
strStyleSheet = QString::fromLatin1(res.readAll());
}
else
{
#endif
QFile res(":/qdarkstyle/darkstyle.qss");
res.open(QIODevice::ReadOnly);
strStyleSheet = QString::fromLatin1(res.readAll());
#ifdef _DEBUG
}
#endif
// Grab all URLS
QRegExp re_url("url\\(:([^\\)]*)\\)");
int offset = 0;
QStringList urls;
while ((offset = re_url.indexIn(strStyleSheet, offset)) != -1)
{
QString url = re_url.cap(1);
if (!urls.contains(url))
{
urls.append(url);
}
offset += re_url.matchedLength();
}
// Extract resources that match URL to disk, recolor, write out
int pngnum = 0;
foreach(QString url, urls)
{
QPixmap newpixmap = GetHueColorPixmapResource(QString(":") + url);
// Write out pixmap and rewrite url to new pixmap
QString outname = QDir(m_temporary_dir).filePath(QString("%1.png").arg(pngnum));
QFile out(outname);
out.open(QIODevice::WriteOnly);
newpixmap.save(&out, "PNG");
outname = outname.replace("$","\\$");
strStyleSheet = strStyleSheet.replace(QString("url(:%1)").arg(url), QString("url(%1)").arg(outname));
pngnum++;
}
// Text
strStyleSheet = strStyleSheet.replace("##TEXT_COLOR##", GetTextColor());
strStyleSheet = strStyleSheet.replace("##INVERSE_TEXT_COLOR##", GetInverseTextColor());
strStyleSheet = strStyleSheet.replace("##TEXT_DISABLED##", GetBaseShade("TEXT_DISABLED"));
// Widget
strStyleSheet = strStyleSheet.replace("##WIDGET_DISABLED##", GetBaseShade("WIDGET_DISABLED"));
strStyleSheet = strStyleSheet.replace("##WIDGET_BKGD##", GetBaseShade("WIDGET_BKGD"));
// Border
strStyleSheet = strStyleSheet.replace("##BORDER_COLOR##", GetBaseShade("BORDER_COLOR"));
strStyleSheet = strStyleSheet.replace("##DOCKWIDGET_BORDER##", GetBaseShade("DOCKWIDGET_BORDER"));
// Separator
strStyleSheet = strStyleSheet.replace("##SEP_COLOR_1##", GetBaseShade("SEP_COLOR_1"));
strStyleSheet = strStyleSheet.replace("##SEP_COLOR_2##", GetTextColor());
// Control
strStyleSheet = strStyleSheet.replace("##CONTROL_BKGD##", GetBaseShade("CONTROL_BKGD"));
strStyleSheet = strStyleSheet.replace("##CONTROL_BKGD_DISABLED##", GetBaseShade("CONTROL_BKGD_DISABLED"));
// Highlight
strStyleSheet = strStyleSheet.replace("##HIGHLIGHT_COLOR##", GetHighlightShade("BASE"));
strStyleSheet = strStyleSheet.replace("##HIGHLIGHT_CONTROL_TEXT##", GetHighlightShade("HIGHLIGHT_CONTROL_TEXT"));
strStyleSheet = strStyleSheet.replace("##HIGHLIGHT_CONTROL_BORDER##", GetHighlightShade("HIGHLIGHT_CONTROL_BORDER"));
strStyleSheet = strStyleSheet.replace("##HIGHLIGHT_CONTROL_BKGD##", "QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " +
GetHighlightShade("HIGHLIGHT_CONTROL_BKGD_0") + " stop: 1 " + GetHighlightShade("HIGHLIGHT_CONTROL_BKGD_1") + ")");
// Selection
strStyleSheet = strStyleSheet.replace("##HIGHLIGHT_BKGD##", "QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " +
GetHighlightShade("HIGHLIGHT_BKGD_0") + " stop: 1 " + GetHighlightShade("HIGHLIGHT_BKGD_1") + ")");
strStyleSheet = strStyleSheet.replace("##SELECT_BKGD##", "QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " +
GetBaseShade("SELECT_BKGD_0") + " stop: 1 " + GetBaseShade("SELECT_BKGD_1") + ")");
strStyleSheet = strStyleSheet.replace("##SELECT_BKGD_1##", GetBaseShade("SELECT_BKGD_0"));
strStyleSheet = strStyleSheet.replace("##SELECT_BKGD_2##", GetBaseShade("SELECT_BKGD_1"));
strStyleSheet = strStyleSheet.replace("##COMBO_SELECTION_BKGD##", GetBaseShade("COMBO_SELECTION_BKGD"));
// Button
strStyleSheet = strStyleSheet.replace("##BUTTON_BKGD##", "QLinearGradient( x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 " +
GetBaseShade("BUTTON_BKGD_0") + " stop: 1 " + GetBaseShade("BUTTON_BKGD_1") + ")");
strStyleSheet = strStyleSheet.replace("##BUTTON_BKGD_1##", GetBaseShade("BUTTON_BKGD_0"));
strStyleSheet = strStyleSheet.replace("##BUTTON_BKGD_2##", GetBaseShade("BUTTON_BKGD_1"));
strStyleSheet = strStyleSheet.replace("##BUTTON_COLOR_DISABLED##", GetBaseShade("BUTTON_COLOR_DISABLED"));
strStyleSheet = strStyleSheet.replace("##BUTTON_BKGD_PRESSED##", "QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " +
GetBaseShade("BUTTON_BKGD_PRESSED_0") + " stop: 1 " + GetBaseShade("BUTTON_BKGD_PRESSED_1") + ")");
// Checkbox
strStyleSheet = strStyleSheet.replace("##CHECKBOX_COLOR##", GetBaseShade("CHECKBOX_COLOR"));
// Slider
strStyleSheet = strStyleSheet.replace("##SLIDER_COLOR_1##", GetBaseShade("SLIDER_COLOR_0"));
strStyleSheet = strStyleSheet.replace("##SLIDER_COLOR_2##", GetBaseShade("SLIDER_COLOR_1"));
// Tooltip
strStyleSheet = strStyleSheet.replace("##TOOLTIP_BKGD##", GetBaseShade("TOOLTIP_BKGD"));
// Progress
strStyleSheet = strStyleSheet.replace("##PROGRESS_BKGD##", "QLinearGradient(x1:1, y1:0, x2:0, y2:0, stop:0 " +
GetHighlightShade("PROGRESS_BKGD_0") + " stop:1 " + GetHighlightShade("PROGRESS_BKGD_1") + ")");
// Extended Tab Widget
strStyleSheet = strStyleSheet.replace("##EXTENDED_TAB_WIDGET_CHECKED##", "QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " +
GetBaseShade("EXTENDED_TAB_WIDGET_CHECKED_0") + " stop:1 " + GetBaseShade("EXTENDED_TAB_WIDGET_CHECKED_1") + ")");
strStyleSheet = strStyleSheet.replace("##EXTENDED_TAB_WIDGET_UNCHECKED##", "QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " +
GetBaseShade("EXTENDED_TAB_WIDGET_UNCHECKED_0") + " stop:1 " + GetBaseShade("EXTENDED_TAB_WIDGET_UNCHECKED_1") + ")");
// Scrollbar
strStyleSheet = strStyleSheet.replace("##SCROLL_H_BKGD##", "QLinearGradient( x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 " +
GetBaseShade("SCROLL_H_BKGD_0") + " stop: 1 " + GetBaseShade("SCROLL_H_BKGD_1") + ")");
strStyleSheet = strStyleSheet.replace("##SCROLL_V_BKGD##", "QLinearGradient( x1: 1, y1: 0, x2: 0, y2: 0, stop: 0 " +
GetBaseShade("SCROLL_V_BKGD_0") + " stop: 1 " + GetBaseShade("SCROLL_V_BKGD_1") + ")");
strStyleSheet = strStyleSheet.replace("##SCROLL_HANDLE_H_BKGD##", "QLinearGradient( x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 " +
GetBaseShade("SCROLL_HANDLE_H_BKGD_0") + " stop: 1 " + GetBaseShade("SCROLL_HANDLE_H_BKGD_1") + ")");
strStyleSheet = strStyleSheet.replace("##SCROLL_HANDLE_V_BKGD##", "QLinearGradient( x1: 1, y1: 0, x2: 0, y2: 0, stop: 0 " +
GetBaseShade("SCROLL_HANDLE_V_BKGD_0") + " stop: 1 " + GetBaseShade("SCROLL_HANDLE_V_BKGD_1") + ")");
// Headers
strStyleSheet = strStyleSheet.replace("##HEADER_BKGD##", GetBaseShade("HEADER_BKGD"));
strStyleSheet = strStyleSheet.replace("##HEADER_BORDER##", GetBaseShade("HEADER_BORDER"));
// Messages
strStyleSheet = strStyleSheet.replace("##ERROR_BKGD##", "QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ff825b, stop: 1 #f13900)");
strStyleSheet = strStyleSheet.replace("##WARNING_BKGD##", "QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffd65b, stop: 1 #fffd35)");
strStyleSheet = strStyleSheet.replace("##SUCCESS_BKGD##", "QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #79ff6f, stop: 1 #36ff00)");
// Shadow
strStyleSheet = strStyleSheet.replace("##SHADOW##", GetBaseShade("SHADOW"));
m_stylesheet = strStyleSheet;
CLC7App::getInstance()->setStyleSheet(strStyleSheet);
QPalette p;
p.setColor(QPalette::Link, GetHighlightShade("HIGHLIGHT_BKGD_1"));
p.setColor(QPalette::LinkVisited, GetHighlightShade("HIGHLIGHT_BKGD_1"));
CLC7App::getInstance()->setPalette(p);
SetCheckboxPixmap(
GetHueColorPixmapResource(":/QtPropertyManager/checkbox_true.png"),
GetHueColorPixmapResource(":/QtPropertyManager/checkbox_false.png")
);
foreach(QCommandLinkButton *clbutton, m_clbuttons)
{
DoCommandLinkButtonStyling(clbutton);
}
emit sig_RecolorCallback();
}
QPixmap CLC7ColorManager::HueRecolorPixmap(const QPixmap *pixmap, QColor huecolor)
{
TR;
if (!huecolor.isValid())
{
huecolor = GetHighlightColor();
}
QColor defaulthighlightcolor = GetDefaultHighlightColor();
int ldiff = huecolor.lightness() - defaulthighlightcolor.lightness();
int sdiff = huecolor.hslSaturation() - defaulthighlightcolor.hslSaturation();
QPixmap newpixmap;
QImage img = pixmap->toImage();
QImage newImage(img.width(), img.height(), QImage::Format_ARGB32);
QColor oldColor;
QColor newColor;
for (int x = 0; x < newImage.width(); x++){
for (int y = 0; y < newImage.height(); y++){
QColor color = QColor::fromRgba(img.pixel(x, y));
int s = color.hslSaturation();
int l = color.lightness();
if ((s + sdiff) > 255)
s = 255;
else if ((s + sdiff) < 0)
s = 0;
else
s = s + sdiff;
if ((l + ldiff) > 255)
l = 255;
else if ((l + ldiff) < 0)
l = 0;
else
l = l + ldiff;
color.setHsl(huecolor.hslHue(), s, l, color.alpha());
newImage.setPixel(x, y, color.rgba());
}
}
return QPixmap::fromImage(newImage);
}
QPixmap CLC7ColorManager::MonoRecolorPixmap(const QPixmap *pixmap, QColor basecolor)
{
TR;
if (!basecolor.isValid())
{
basecolor = GetBaseColor();
}
QPixmap newpixmap;
QImage img = pixmap->toImage();
QImage newImage(img.width(), img.height(), QImage::Format_ARGB32);
QColor oldColor;
QColor newColor;
for (int x = 0; x < newImage.width(); x++){
for (int y = 0; y < newImage.height(); y++){
QColor color = QColor::fromRgba(img.pixel(x, y));
color.setHsl(basecolor.hue(), basecolor.hslSaturation(), basecolor.lightness(), color.alpha());
newImage.setPixel(x, y, color.rgba());
}
}
return QPixmap::fromImage(newImage);
}
void CLC7ColorManager::reload()
{
TR;
ReloadSettings();
}
QPixmap CLC7ColorManager::GetHueColorPixmap(QPixmap pixmap, QColor huecolor)
{
TR;
return HueRecolorPixmap(&pixmap, huecolor);
}
QPixmap CLC7ColorManager::GetHueColorPixmapResource(QString resource_path, QColor huecolor)
{
TR;
// Use larger pixmap if we have one and need one
if (m_size_ratio == 2)
{
QString rpath(resource_path.left(resource_path.lastIndexOf(".")));
QString rext(resource_path.mid(resource_path.lastIndexOf(".") + 1));
QString res2x = rpath + "@2x." + rext;
QResource res(res2x);
if (res.isValid())
{
resource_path = res2x;
}
}
QPixmap pixmap(resource_path);
return HueRecolorPixmap(&pixmap, huecolor);
}
QPixmap CLC7ColorManager::GetMonoColorPixmap(QPixmap pixmap, QColor basecolor)
{
TR;
return MonoRecolorPixmap(&pixmap, basecolor);
}
QPixmap CLC7ColorManager::GetMonoColorPixmapResource(QString resource_path, QColor basecolor)
{
TR;
// Use larger pixmap if we have one and need one
if (m_size_ratio == 2)
{
QString rpath(resource_path.left(resource_path.lastIndexOf(".")));
QString rext(resource_path.mid(resource_path.lastIndexOf(".") + 1));
QString res2x = rpath + "@2x." + rext;
QResource res(res2x);
if (res.isValid())
{
resource_path = res2x;
}
}
QPixmap pixmap(resource_path);
return MonoRecolorPixmap(&pixmap, basecolor);
}
void CLC7ColorManager::RegisterRecolorCallback(QObject *slot_obj, void (QObject::*slot_method)(void))
{
TR;
connect(this, &CLC7ColorManager::sig_RecolorCallback, slot_obj, slot_method);
}
QGraphicsEffect *CLC7ColorManager::CreateShadowEffect(void)
{
TR;
QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect;
effect->setBlurRadius(6);
effect->setXOffset(3);
effect->setYOffset(3);
effect->setColor(GetBaseShade("SHADOW"));
return effect;
}
void CLC7ColorManager::slot_destroyedCLButton(QObject *object)
{
TR;
m_clbuttons.removeAll((QCommandLinkButton *)object);
}
void CLC7ColorManager::DoCommandLinkButtonStyling(QCommandLinkButton *commandlinkbutton)
{
TR;
QPixmap clpixmap(GetHueColorPixmapResource(":/qss_icons/rc/commandlink.png"));
commandlinkbutton->setIcon(QIcon(clpixmap));
commandlinkbutton->setIconSize(clpixmap.size());
commandlinkbutton->setGraphicsEffect(CreateShadowEffect());
commandlinkbutton->setSizePolicy(commandlinkbutton->sizePolicy().horizontalPolicy(), QSizePolicy::Fixed);
commandlinkbutton->setFixedHeight(20 + (24 * m_size_ratio));
}
void CLC7ColorManager::StyleCommandLinkButton(QCommandLinkButton *commandlinkbutton)
{
TR;
if (!m_clbuttons.contains(commandlinkbutton))
{
m_clbuttons.append(commandlinkbutton);
connect(commandlinkbutton, &QObject::destroyed, this, &CLC7ColorManager::slot_destroyedCLButton);
connect(commandlinkbutton, &QAbstractButton::pressed, this, &CLC7ColorManager::onCommandLinkButtonPressed);
connect(commandlinkbutton, &QAbstractButton::released, this, &CLC7ColorManager::onCommandLinkButtonReleased);
}
DoCommandLinkButtonStyling(commandlinkbutton);
}
void CLC7ColorManager::onCommandLinkButtonPressed()
{
TR;
QCommandLinkButton *commandlinkbutton = (QCommandLinkButton *)QObject::sender();
commandlinkbutton->graphicsEffect()->setEnabled(false);
commandlinkbutton->move(commandlinkbutton->pos() + QPoint(3, 3));
}
void CLC7ColorManager::onCommandLinkButtonReleased()
{
TR;
QCommandLinkButton *commandlinkbutton = (QCommandLinkButton *)QObject::sender();
commandlinkbutton->graphicsEffect()->setEnabled(true);
commandlinkbutton->move(commandlinkbutton->pos() + QPoint(-3, -3));
}
void CLC7ColorManager::slot_screenChanged(QScreen *screen)
{
TR;
m_currentScreen = screen;
RecalculateColors();
}
int CLC7ColorManager::GetSizeRatio(void)
{
TR;
return m_size_ratio;
}
| 29.866481 | 142 | 0.699776 | phixion |
c537dafd6762760c817d86e1c313e8b73f3d8d93 | 946 | inl | C++ | TAO/orbsvcs/orbsvcs/FtRtEvent/Utils/Log.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/orbsvcs/orbsvcs/FtRtEvent/Utils/Log.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/orbsvcs/orbsvcs/FtRtEvent/Utils/Log.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
//
// $Id: Log.inl 97014 2013-04-12 22:47:02Z mitza $
#include "orbsvcs/Log_Macros.h"
#include "orbsvcs/Log_Macros.h"
#include "orbsvcs/Log_Macros.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
namespace TAO_FTRTEC {
#ifndef NDEBUG
ACE_INLINE
void Log::level(unsigned int log_level)
{
log_level_ = log_level;
}
ACE_INLINE
unsigned int Log::level()
{
return log_level_;
}
ACE_INLINE
void Log::hexdump(unsigned int level, const char* buf, size_t len, const ACE_TCHAR* msg)
{
if (Log::log_level_ >= level)
ORBSVCS_HEX_DUMP((LM_DEBUG, buf, len, msg));
}
#else // NDEBUG
ACE_INLINE
Log::Log (unsigned int, const ACE_TCHAR*, ...)
{
}
ACE_INLINE
void Log::level(unsigned int )
{
}
ACE_INLINE
unsigned int Log::level()
{
return 0;
}
ACE_INLINE
void Log::hexdump(unsigned int, const char*, size_t, const ACE_TCHAR*)
{
}
#endif
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 16.892857 | 90 | 0.668076 | cflowe |
c539f8932a5650fab69b759c1a2de0beda728576 | 4,151 | hpp | C++ | include/lemon/deprecated/old_hadoop.hpp | frodofine/lemon | f874857cb8f1851313257b25681ad2a254ada8dc | [
"BSD-3-Clause"
] | 43 | 2018-07-21T22:08:48.000Z | 2022-03-23T22:19:02.000Z | include/lemon/deprecated/old_hadoop.hpp | frodofine/lemon | f874857cb8f1851313257b25681ad2a254ada8dc | [
"BSD-3-Clause"
] | 22 | 2018-08-01T19:13:11.000Z | 2020-06-02T17:04:03.000Z | include/lemon/deprecated/old_hadoop.hpp | frodofine/lemon | f874857cb8f1851313257b25681ad2a254ada8dc | [
"BSD-3-Clause"
] | 9 | 2018-07-21T19:13:55.000Z | 2020-12-22T09:12:43.000Z | #ifndef OLD_HADOOP_HPP
#define OLD_HADOOP_HPP
#include <cassert>
#include <cstdint>
#include <fstream>
#include <string>
#include <vector>
namespace lemon {
namespace deprecated {
class Hadoop {
public:
Hadoop(std::istream& stream) : stream_(stream) { initialize_(); }
bool has_next() { return stream_.peek() != std::char_traits<char>::eof(); }
std::pair<std::vector<char>, std::vector<char>> next() { return read(); }
private:
std::istream& stream_;
std::string marker_ = "";
std::vector<char> key_;
/* Uncomment if a more generic solution is desired....
Loosly based on
https://github.com/azat-archive/hadoop-io-sequence-reader/blob/master/src/reader.cpp,
but entirely rewritten
static uint32_t decode(int8_t ch) {
if (ch >= -112) {
return 1;
} else if (ch < -120) {
return -119 - ch;
}
return -111 - ch;
}
static int64_t read(const char *pos, uint32_t &len) {
if (*pos >= (char)-112) {
len = 1;
return *pos;
} else {
return read_helper(pos, len);
}
}
static int64_t read_helper(const char *pos, uint32_t &len) {
bool neg = *pos < -120;
len = neg ? (-119 - *pos) : (-111 - *pos);
const char *end = pos + len;
int64_t value = 0;
while (++pos < end) {
value = (value << 8) | *(uint8_t *)pos;
}
return neg ? (value ^ -1LL) : value;
}
int64_t read_long() {
char buff[10];
stream_.read(buff, 1);
auto len = decode(*buff);
if (len > 1) {
!stream_.read(buff + 1, len - 1);
}
return read(buff, len);
}
void read_string(char *buffer) {
auto len = read_long();
stream_.read(buffer, len);
}
void initialize() {
stream_.exceptions(std::ifstream::badbit | std::ifstream::failbit);
char buffer[1024];
// Reads the header
stream_.read(buffer, 4);
// Read the Key class
read_string(buffer);
// Read the Value class
read_string(buffer);
auto valueCompression = stream_.get();
auto blockCompression = stream_.get();
if (valueCompression != 0 || blockCompression != 0) {
throw std::runtime_error("Compression not supported");
}
int pairs = read_int();
if (pairs < 0 || pairs > 1024) {
throw std::runtime_error("Invalid pair count");
}
for (size_t i = 0; i < pairs; ++i) {
// Ignore the metadata
read_string(buffer);
read_string(buffer);
}
// Read marker
stream_.read(buffer, 16);
marker_ = std::string(buffer, 16);
} */
void initialize_() {
// Completly skip the header as it is the same in all RCSB Hadoop files
stream_.exceptions(std::ifstream::badbit | std::ifstream::failbit);
char buffer[86];
stream_.read(buffer, 87);
}
int read_int() {
int ret;
stream_.read(reinterpret_cast<char*>(&ret), 4);
return ntohl(ret);
}
std::pair<std::vector<char>, std::vector<char>> read() {
auto sync_check = read_int();
if (sync_check == -1) {
std::vector<char> marker(16);
stream_.read(marker.data(), 16);
// Only valid if using the full version
// assert(std::string(marker.data(), 16) == marker_);
return this->read();
}
auto key_length = read_int();
// Do not check this during runtime as it should all be the same
assert(key_length >= 4);
std::vector<char> key(key_length);
stream_.read(key.data(), key_length);
assert(sync_check >= 8);
// Remove junk characters added by Java Serialization
char junk[4];
stream_.read(junk, 4);
int value_length = sync_check - key_length;
std::vector<char> value(value_length - 4);
stream_.read(value.data(), value_length - 4);
return {key, value};
}
};
}
}
#endif
| 25.623457 | 89 | 0.544929 | frodofine |
c53e98d98e08647802a598c9c84c29967bd12389 | 1,159 | cpp | C++ | c++/srcs/box.cpp | takurooo/heif | d07c0fd06a9ed34d3ad981cc285f50d1a952534c | [
"MIT"
] | null | null | null | c++/srcs/box.cpp | takurooo/heif | d07c0fd06a9ed34d3ad981cc285f50d1a952534c | [
"MIT"
] | null | null | null | c++/srcs/box.cpp | takurooo/heif | d07c0fd06a9ed34d3ad981cc285f50d1a952534c | [
"MIT"
] | null | null | null | // -----------------------------------------
// include
// -----------------------------------------
#include <iostream>
#include "util.h"
#include "fourcc.h"
#include "box.h"
// -----------------------------------------
// define
// -----------------------------------------
// -----------------------------------------
// global value
// -----------------------------------------
// -----------------------------------------
// class/function
// -----------------------------------------
Box::Box()
: m_size(0), m_type(0), m_largesize(0), m_usertype(), m_strat_offset(0)
{
;
}
Box::~Box()
{
;
}
UINT32 Box::GetBoxSize() const
{
return m_size;
}
UINT32 Box::GetBoxType() const
{
return m_type;
}
void Box::ReadBoxHeader(BitStream *p_bitstream)
{
m_size = p_bitstream->Read32Bits();
m_type = p_bitstream->Read32Bits();
if (m_size == 1)
{
m_largesize = p_bitstream->Read64Bits();
}
if (m_type == FOURCC::UUID)
{
for (UINT8 i = 0; i < 16; i++)
{
// m_usertype[i] = p_bitstream->Read8Bits();
m_usertype.push_back(p_bitstream->Read8Bits());
}
}
} | 19.644068 | 75 | 0.397757 | takurooo |
c540bf573606c9af6e567af44d851c02dc0cb358 | 641 | cpp | C++ | Dataset/Leetcode/train/13/918.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/918.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/918.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
int getValue(const char c){
switch(c){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
} return 0;
}
int XXX(string s) {
int res = 0,cur = 0,next = 0;
for(size_t i = 0;i < s.size();++i){
cur = getValue(s[i]);
if(i+1 < s.size()) next = getValue(s[i+1]);
if(cur >= next) res += cur;
else res -= cur;
}
return res;
}
};
| 24.653846 | 55 | 0.413417 | kkcookies99 |
c54393a37db674bfcfe6d7486fac8702e6001909 | 6,356 | cpp | C++ | vs_net/lesson30/Tmatrix.cpp | neozhou2009/nehe-opengl | 9f073e5b092ad8dbcb21393871a2855fe86a65c6 | [
"MIT"
] | 177 | 2017-12-31T04:44:27.000Z | 2022-03-23T10:08:03.000Z | vs_net/lesson30/Tmatrix.cpp | neozhou2009/nehe-opengl | 9f073e5b092ad8dbcb21393871a2855fe86a65c6 | [
"MIT"
] | 2 | 2018-06-28T20:28:33.000Z | 2018-09-09T17:34:44.000Z | vs_net/lesson30/Tmatrix.cpp | neozhou2009/nehe-opengl | 9f073e5b092ad8dbcb21393871a2855fe86a65c6 | [
"MIT"
] | 72 | 2018-01-07T16:41:29.000Z | 2022-03-18T17:57:38.000Z | /*******************************************************************************/
/*********************************21/09/200*************************************/
/**********************Programmer: Dimitrios Christopoulos**********************/
/**********************for the oglchallenge contest*****************************/
/**********************COLLISION CRAZY******************************************/
/*******************************************************************************/
#include "tmatrix.h"
#include "tvector.h"
TMatrix33::TMatrix33() {
_Mx[0][0]=1.0; _Mx[0][1]=0.0; _Mx[0][2]=0.0;
_Mx[1][0]=0.0; _Mx[1][1]=1.0; _Mx[1][2]=0.0;
_Mx[2][0]=0.0; _Mx[2][1]=0.0; _Mx[2][2]=1.0;
}
TMatrix33::TMatrix33(double mx00, double mx01, double mx02,
double mx10, double mx11, double mx12,
double mx20, double mx21, double mx22) {
_Mx[0][0]=mx00; _Mx[0][1]=mx01; _Mx[0][2]=mx02;
_Mx[1][0]=mx10; _Mx[1][1]=mx11; _Mx[1][2]=mx12;
_Mx[2][0]=mx20; _Mx[2][1]=mx21; _Mx[2][2]=mx22;
}
TMatrix33::TMatrix33(double Phi, double Theta, double Psi) {
double c1=cos(Phi), s1=sin(Phi), c2=cos(Theta), s2=sin(Theta), c3=cos(Psi), s3=sin(Psi);
_Mx[0][0]=c2*c3;
_Mx[0][1]=-c2*s3;
_Mx[0][2]=s2;
_Mx[1][0]=s1*s2*c3+c1*s3;
_Mx[1][1]=-s1*s2*s3+c1*c3;
_Mx[1][2]=-s1*c2;
_Mx[2][0]=-c1*s2*c3+s1*s3;
_Mx[2][1]=c1*s2*s3+s1*c3;
_Mx[2][2]=c1*c2;
}
TMatrix33 &TMatrix33::add(const TMatrix33 &m1, const TMatrix33 &m2, TMatrix33 &result) {
result._Mx[0][0] = m1._Mx[0][0] + m2._Mx[0][0];
result._Mx[0][1] = m1._Mx[0][1] + m2._Mx[0][1];
result._Mx[0][2] = m1._Mx[0][2] + m2._Mx[0][2];
result._Mx[1][0] = m1._Mx[1][0] + m2._Mx[1][0];
result._Mx[1][1] = m1._Mx[1][1] + m2._Mx[1][1];
result._Mx[1][2] = m1._Mx[1][2] + m2._Mx[1][2];
result._Mx[2][0] = m1._Mx[2][0] + m2._Mx[2][0];
result._Mx[2][1] = m1._Mx[2][1] + m2._Mx[2][1];
result._Mx[2][2] = m1._Mx[2][2] + m2._Mx[2][2];
return result;
}
TMatrix33 &TMatrix33::subtract(const TMatrix33 &m1, const TMatrix33 &m2, TMatrix33 &result) {
result._Mx[0][0] = m1._Mx[0][0] - m2._Mx[0][0];
result._Mx[0][1] = m1._Mx[0][1] - m2._Mx[0][1];
result._Mx[0][2] = m1._Mx[0][2] - m2._Mx[0][2];
result._Mx[1][0] = m1._Mx[1][0] - m2._Mx[1][0];
result._Mx[1][1] = m1._Mx[1][1] - m2._Mx[1][1];
result._Mx[1][2] = m1._Mx[1][2] - m2._Mx[1][2];
result._Mx[2][0] = m1._Mx[2][0] - m2._Mx[2][0];
result._Mx[2][1] = m1._Mx[2][1] - m2._Mx[2][1];
result._Mx[2][2] = m1._Mx[2][2] - m2._Mx[2][2];
return result;
}
TMatrix33 &TMatrix33::multiply(const TMatrix33 &m1, const TMatrix33 &m2, TMatrix33 &result) {
result._Mx[0][0] = m1._Mx[0][0]*m2._Mx[0][0] + m1._Mx[0][1]*m2._Mx[1][0] + m1._Mx[0][2]*m2._Mx[2][0];
result._Mx[1][0] = m1._Mx[1][0]*m2._Mx[0][0] + m1._Mx[1][1]*m2._Mx[1][0] + m1._Mx[1][2]*m2._Mx[2][0];
result._Mx[2][0] = m1._Mx[2][0]*m2._Mx[0][0] + m1._Mx[2][1]*m2._Mx[1][0] + m1._Mx[2][2]*m2._Mx[2][0];
result._Mx[0][1] = m1._Mx[0][0]*m2._Mx[0][1] + m1._Mx[0][1]*m2._Mx[1][1] + m1._Mx[0][2]*m2._Mx[2][1];
result._Mx[1][1] = m1._Mx[1][0]*m2._Mx[0][1] + m1._Mx[1][1]*m2._Mx[1][1] + m1._Mx[1][2]*m2._Mx[2][1];
result._Mx[2][1] = m1._Mx[2][0]*m2._Mx[0][1] + m1._Mx[2][1]*m2._Mx[1][1] + m1._Mx[2][2]*m2._Mx[2][1];
result._Mx[0][2] = m1._Mx[0][0]*m2._Mx[0][2] + m1._Mx[0][1]*m2._Mx[1][2] + m1._Mx[0][2]*m2._Mx[2][2];
result._Mx[1][2] = m1._Mx[1][0]*m2._Mx[0][2] + m1._Mx[1][1]*m2._Mx[1][2] + m1._Mx[1][2]*m2._Mx[2][2];
result._Mx[2][2] = m1._Mx[2][0]*m2._Mx[0][2] + m1._Mx[2][1]*m2._Mx[1][2] + m1._Mx[2][2]*m2._Mx[2][2];
return result;
}
TMatrix33 &TMatrix33::multiply(const TMatrix33 &m1, const double &scale, TMatrix33 &result) {
result._Mx[0][0] = m1._Mx[0][0] * scale;
result._Mx[0][1] = m1._Mx[0][1] * scale;
result._Mx[0][2] = m1._Mx[0][2] * scale;
result._Mx[1][0] = m1._Mx[1][0] * scale;
result._Mx[1][1] = m1._Mx[1][1] * scale;
result._Mx[1][2] = m1._Mx[1][2] * scale;
result._Mx[2][0] = m1._Mx[2][0] * scale;
result._Mx[2][1] = m1._Mx[2][1] * scale;
result._Mx[2][2] = m1._Mx[2][2] * scale;
return result;
}
TVector &TMatrix33::multiply(const TMatrix33 &m1, const TVector &v, TVector &result) {
result = TVector(
m1._Mx[0][0]*v.X() + m1._Mx[0][1]*v.Y() + m1._Mx[0][2]*v.Z(),
m1._Mx[1][0]*v.X() + m1._Mx[1][1]*v.Y() + m1._Mx[1][2]*v.Z(),
m1._Mx[2][0]*v.X() + m1._Mx[2][1]*v.Y() + m1._Mx[2][2]*v.Z() );
return result;
}
double TMatrix33::determinant() const {
return _Mx[0][0]*(_Mx[1][1]*_Mx[2][2]-_Mx[1][2]*_Mx[2][1])
- _Mx[0][1]*(_Mx[1][0]*_Mx[2][2]-_Mx[1][2]*_Mx[2][0])
+ _Mx[0][2]*(_Mx[1][0]*_Mx[2][1]-_Mx[1][1]*_Mx[2][0]);
}
TMatrix33 &TMatrix33::transpose() {
double t=_Mx[0][2]; _Mx[0][2]=_Mx[2][0]; _Mx[2][0]=t;
t=_Mx[0][1]; _Mx[0][1]=_Mx[1][0]; _Mx[1][0]=t;
t=_Mx[1][2]; _Mx[1][2]=_Mx[2][1]; _Mx[2][1]=t;
return *this;
}
TMatrix33 &TMatrix33::inverse(const TMatrix33 &m1, TMatrix33 &result) {
double det = m1.determinant();
if (fabs(det) < EPSILON) {
result = TMatrix33();
return result;
} else {
result._Mx[0][0] = m1._Mx[1][1]*m1._Mx[2][2] - m1._Mx[1][2]*m1._Mx[2][1];
result._Mx[0][1] = m1._Mx[2][1]*m1._Mx[0][2] - m1._Mx[2][2]*m1._Mx[0][1];
result._Mx[0][2] = m1._Mx[0][1]*m1._Mx[1][2] - m1._Mx[0][2]*m1._Mx[1][1];
result._Mx[1][0] = m1._Mx[1][2]*m1._Mx[2][0] - m1._Mx[1][0]*m1._Mx[2][2];
result._Mx[1][1] = m1._Mx[2][2]*m1._Mx[0][0] - m1._Mx[2][0]*m1._Mx[0][2];
result._Mx[1][2] = m1._Mx[0][2]*m1._Mx[1][0] - m1._Mx[0][0]*m1._Mx[1][2];
result._Mx[2][0] = m1._Mx[1][0]*m1._Mx[2][1] - m1._Mx[1][1]*m1._Mx[2][0];
result._Mx[2][1] = m1._Mx[2][0]*m1._Mx[0][1] - m1._Mx[2][1]*m1._Mx[0][0];
result._Mx[2][2] = m1._Mx[0][0]*m1._Mx[1][1] - m1._Mx[0][1]*m1._Mx[1][0];
return multiply(result, 1.0/det, result);
}
}
TVector TMatrix33::operator*(const TVector &v) const {
TVector tv;
return multiply(*this, v, tv);
}
ostream &TMatrix33::write(ostream &out) const {
return out<<"("<<_Mx[0][0]<<","<<_Mx[0][1]<<","<<_Mx[0][2]<<")"<<endl
<<"("<<_Mx[1][0]<<","<<_Mx[1][1]<<","<<_Mx[1][2]<<")"<<endl
<<"("<<_Mx[2][0]<<","<<_Mx[2][1]<<","<<_Mx[2][2]<<")"<<endl;
}
istream &TMatrix33::read(istream &in) {
char ch;
return in>>ch>>_Mx[0][0]>>ch>>_Mx[0][1]>>ch>>_Mx[0][2]>>ch
>>ch>>_Mx[1][0]>>ch>>_Mx[1][1]>>ch>>_Mx[1][2]>>ch
>>ch>>_Mx[2][0]>>ch>>_Mx[2][1]>>ch>>_Mx[2][2]>>ch;
}
| 21.767123 | 102 | 0.509912 | neozhou2009 |
c54479b8a4b55c8b35b98b297f3c33a6792bb2fa | 40,773 | cxx | C++ | main/slideshow/source/engine/shapes/viewshape.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/slideshow/source/engine/shapes/viewshape.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/slideshow/source/engine/shapes/viewshape.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
// must be first
#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <math.h>
#include <rtl/logfile.hxx>
#include <rtl/math.hxx>
#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/PanoseLetterForm.hpp>
#include <com/sun/star/awt/FontSlant.hpp>
#include <cppuhelper/exc_hlp.hxx>
#include <comphelper/anytostring.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/matrix/b2dhommatrixtools.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>
#include <cppcanvas/vclfactory.hxx>
#include <cppcanvas/basegfxfactory.hxx>
#include "viewshape.hxx"
#include "tools.hxx"
#include <boost/bind.hpp>
using namespace ::com::sun::star;
namespace slideshow
{
namespace internal
{
// TODO(F2): Provide sensible setup for mtf-related attributes (fill mode,
// char rotation etc.). Do that via mtf argument at this object
bool ViewShape::prefetch( RendererCacheEntry& io_rCacheEntry,
const ::cppcanvas::CanvasSharedPtr& rDestinationCanvas,
const GDIMetaFileSharedPtr& rMtf,
const ShapeAttributeLayerSharedPtr& rAttr ) const
{
RTL_LOGFILE_CONTEXT( aLog, "::presentation::internal::ViewShape::prefetch()" );
ENSURE_OR_RETURN_FALSE( rMtf,
"ViewShape::prefetch(): no valid metafile!" );
if( rMtf != io_rCacheEntry.mpMtf ||
rDestinationCanvas != io_rCacheEntry.getDestinationCanvas() )
{
// buffered renderer invalid, re-create
::cppcanvas::Renderer::Parameters aParms;
// rendering attribute override parameter struct. For
// every valid attribute, the corresponding struct
// member is filled, which in the metafile renderer
// forces rendering with the given attribute.
if( rAttr )
{
if( rAttr->isFillColorValid() )
{
// convert RGBColor to RGBA32 integer. Note
// that getIntegerColor() also truncates
// out-of-range values appropriately
aParms.maFillColor =
rAttr->getFillColor().getIntegerColor();
}
if( rAttr->isLineColorValid() )
{
// convert RGBColor to RGBA32 integer. Note
// that getIntegerColor() also truncates
// out-of-range values appropriately
aParms.maLineColor =
rAttr->getLineColor().getIntegerColor();
}
if( rAttr->isCharColorValid() )
{
// convert RGBColor to RGBA32 integer. Note
// that getIntegerColor() also truncates
// out-of-range values appropriately
aParms.maTextColor =
rAttr->getCharColor().getIntegerColor();
}
if( rAttr->isDimColorValid() )
{
// convert RGBColor to RGBA32 integer. Note
// that getIntegerColor() also truncates
// out-of-range values appropriately
// dim color overrides all other colors
aParms.maFillColor =
aParms.maLineColor =
aParms.maTextColor =
rAttr->getDimColor().getIntegerColor();
}
if( rAttr->isFontFamilyValid() )
{
aParms.maFontName =
rAttr->getFontFamily();
}
if( rAttr->isCharScaleValid() )
{
::basegfx::B2DHomMatrix aMatrix;
// enlarge text by given scale factor. Do that
// with the middle of the shape as the center
// of scaling.
aMatrix.translate( -0.5, -0.5 );
aMatrix.scale( rAttr->getCharScale(),
rAttr->getCharScale() );
aMatrix.translate( 0.5, 0.5 );
aParms.maTextTransformation = aMatrix;
}
if( rAttr->isCharWeightValid() )
{
aParms.maFontWeight =
static_cast< sal_Int8 >(
::basegfx::fround(
::std::max( 0.0,
::std::min( 11.0,
rAttr->getCharWeight() / 20.0 ) ) ) );
}
if( rAttr->isCharPostureValid() )
{
aParms.maFontLetterForm =
rAttr->getCharPosture() == awt::FontSlant_NONE ?
rendering::PanoseLetterForm::ANYTHING :
rendering::PanoseLetterForm::OBLIQUE_CONTACT;
}
if( rAttr->isUnderlineModeValid() )
{
aParms.maFontUnderline =
rAttr->getUnderlineMode();
}
}
io_rCacheEntry.mpRenderer = ::cppcanvas::VCLFactory::getInstance().createRenderer( rDestinationCanvas,
*rMtf.get(),
aParms );
io_rCacheEntry.mpMtf = rMtf;
io_rCacheEntry.mpDestinationCanvas = rDestinationCanvas;
// also invalidate alpha compositing bitmap (created
// new renderer, which possibly generates different
// output). Do NOT invalidate, if we're incidentally
// rendering INTO it.
if( rDestinationCanvas != io_rCacheEntry.mpLastBitmapCanvas )
{
io_rCacheEntry.mpLastBitmapCanvas.reset();
io_rCacheEntry.mpLastBitmap.reset();
}
}
return (io_rCacheEntry.mpRenderer.get() != NULL);
}
bool ViewShape::draw( const ::cppcanvas::CanvasSharedPtr& rDestinationCanvas,
const GDIMetaFileSharedPtr& rMtf,
const ShapeAttributeLayerSharedPtr& rAttr,
const ::basegfx::B2DHomMatrix& rTransform,
const ::basegfx::B2DPolyPolygon* pClip,
const VectorOfDocTreeNodes& rSubsets ) const
{
RTL_LOGFILE_CONTEXT( aLog, "::presentation::internal::ViewShape::draw()" );
::cppcanvas::RendererSharedPtr pRenderer(
getRenderer( rDestinationCanvas, rMtf, rAttr ) );
ENSURE_OR_RETURN_FALSE( pRenderer, "ViewShape::draw(): Invalid renderer" );
pRenderer->setTransformation( rTransform );
#if defined(VERBOSE) && OSL_DEBUG_LEVEL > 0
rendering::RenderState aRenderState;
::canvas::tools::initRenderState(aRenderState);
::canvas::tools::setRenderStateTransform(aRenderState,
rTransform);
aRenderState.DeviceColor.realloc(4);
aRenderState.DeviceColor[0] = 1.0;
aRenderState.DeviceColor[1] = 0.0;
aRenderState.DeviceColor[2] = 0.0;
aRenderState.DeviceColor[3] = 1.0;
try
{
rDestinationCanvas->getUNOCanvas()->drawLine( geometry::RealPoint2D(0.0,0.0),
geometry::RealPoint2D(1.0,1.0),
rDestinationCanvas->getViewState(),
aRenderState );
rDestinationCanvas->getUNOCanvas()->drawLine( geometry::RealPoint2D(1.0,0.0),
geometry::RealPoint2D(0.0,1.0),
rDestinationCanvas->getViewState(),
aRenderState );
}
catch( uno::Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
#endif
if( pClip )
pRenderer->setClip( *pClip );
else
pRenderer->setClip();
if( rSubsets.empty() )
{
return pRenderer->draw();
}
else
{
// render subsets of whole metafile
// --------------------------------
bool bRet(true);
VectorOfDocTreeNodes::const_iterator aIter( rSubsets.begin() );
const VectorOfDocTreeNodes::const_iterator aEnd ( rSubsets.end() );
while( aIter != aEnd )
{
if( !pRenderer->drawSubset( aIter->getStartIndex(),
aIter->getEndIndex() ) )
bRet = false;
++aIter;
}
return bRet;
}
}
namespace
{
/// Convert untransformed shape update area to device pixel.
::basegfx::B2DRectangle shapeArea2AreaPixel( const ::basegfx::B2DHomMatrix& rCanvasTransformation,
const ::basegfx::B2DRectangle& rUntransformedArea )
{
// convert area to pixel, and add anti-aliasing border
// TODO(P1): Should the view transform some
// day contain rotation/shear, transforming
// the original bounds with the total
// transformation might result in smaller
// overall bounds.
::basegfx::B2DRectangle aBoundsPixel;
::canvas::tools::calcTransformedRectBounds( aBoundsPixel,
rUntransformedArea,
rCanvasTransformation );
// add antialiasing border around the shape (AA
// touches pixel _outside_ the nominal bound rect)
aBoundsPixel.grow( ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE );
return aBoundsPixel;
}
/// Convert shape unit rect to device pixel.
::basegfx::B2DRectangle calcUpdateAreaPixel( const ::basegfx::B2DRectangle& rUnitBounds,
const ::basegfx::B2DHomMatrix& rShapeTransformation,
const ::basegfx::B2DHomMatrix& rCanvasTransformation,
const ShapeAttributeLayerSharedPtr& pAttr )
{
// calc update area for whole shape (including
// character scaling)
return shapeArea2AreaPixel( rCanvasTransformation,
getShapeUpdateArea( rUnitBounds,
rShapeTransformation,
pAttr ) );
}
}
bool ViewShape::renderSprite( const ViewLayerSharedPtr& rViewLayer,
const GDIMetaFileSharedPtr& rMtf,
const ::basegfx::B2DRectangle& rOrigBounds,
const ::basegfx::B2DRectangle& rBounds,
const ::basegfx::B2DRectangle& rUnitBounds,
int nUpdateFlags,
const ShapeAttributeLayerSharedPtr& pAttr,
const VectorOfDocTreeNodes& rSubsets,
double nPrio,
bool bIsVisible ) const
{
RTL_LOGFILE_CONTEXT( aLog, "::presentation::internal::ViewShape::renderSprite()" );
// TODO(P1): For multiple views, it might pay off to reorg Shape and ViewShape,
// in that all the common setup steps here are refactored to Shape (would then
// have to be performed only _once_ per Shape paint).
if( !bIsVisible ||
rUnitBounds.isEmpty() ||
rOrigBounds.isEmpty() ||
rBounds.isEmpty() )
{
// shape is invisible or has zero size, no need to
// update anything.
if( mpSprite )
mpSprite->hide();
return true;
}
// calc sprite position, size and content transformation
// =====================================================
// the shape transformation for a sprite is always a
// simple scale-up to the nominal shape size. Everything
// else is handled via the sprite transformation
::basegfx::B2DHomMatrix aNonTranslationalShapeTransformation;
aNonTranslationalShapeTransformation.scale( rOrigBounds.getWidth(),
rOrigBounds.getHeight() );
::basegfx::B2DHomMatrix aShapeTransformation( aNonTranslationalShapeTransformation );
aShapeTransformation.translate( rOrigBounds.getMinX(),
rOrigBounds.getMinY() );
const ::basegfx::B2DHomMatrix& rCanvasTransform(
rViewLayer->getSpriteTransformation() );
// area actually needed for the sprite
const ::basegfx::B2DRectangle& rSpriteBoundsPixel(
calcUpdateAreaPixel( rUnitBounds,
aShapeTransformation,
rCanvasTransform,
pAttr ) );
// actual area for the shape (without subsetting, but
// including char scaling)
const ::basegfx::B2DRectangle& rShapeBoundsPixel(
calcUpdateAreaPixel( ::basegfx::B2DRectangle(0.0,0.0,1.0,1.0),
aShapeTransformation,
rCanvasTransform,
pAttr ) );
// nominal area for the shape (without subsetting, without
// char scaling). NOTE: to cancel the shape translation,
// contained in rSpriteBoundsPixel, this is _without_ any
// translational component (fixed along with #121921#).
::basegfx::B2DRectangle aLogShapeBounds;
const ::basegfx::B2DRectangle& rNominalShapeBoundsPixel(
shapeArea2AreaPixel( rCanvasTransform,
::canvas::tools::calcTransformedRectBounds(
aLogShapeBounds,
::basegfx::B2DRectangle(0.0,0.0,1.0,1.0),
aNonTranslationalShapeTransformation ) ) );
// create (or resize) sprite with sprite's pixel size, if
// not done already
const ::basegfx::B2DSize& rSpriteSizePixel(rSpriteBoundsPixel.getRange());
if( !mpSprite )
{
mpSprite.reset(
new AnimatedSprite( mpViewLayer,
rSpriteSizePixel,
nPrio ));
}
else
{
// TODO(F2): when the sprite _actually_ gets resized,
// content needs a repaint!
mpSprite->resize( rSpriteSizePixel );
}
ENSURE_OR_RETURN_FALSE( mpSprite, "ViewShape::renderSprite(): No sprite" );
VERBOSE_TRACE( "ViewShape::renderSprite(): Rendering sprite 0x%X",
mpSprite.get() );
// always show the sprite (might have been hidden before)
mpSprite->show();
// determine center of sprite output position in pixel
// (assumption here: all shape transformations have the
// shape center as the pivot point). From that, subtract
// distance of rSpriteBoundsPixel's left, top edge from
// rShapeBoundsPixel's center. This moves the sprite at
// the appropriate output position within the virtual
// rShapeBoundsPixel area.
::basegfx::B2DPoint aSpritePosPixel( rBounds.getCenter() );
aSpritePosPixel *= rCanvasTransform;
aSpritePosPixel -= rShapeBoundsPixel.getCenter() - rSpriteBoundsPixel.getMinimum();
// the difference between rShapeBoundsPixel and
// rSpriteBoundsPixel upper, left corner is: the offset we
// have to move sprite output to the right, top (to make
// the desired subset content visible at all)
const ::basegfx::B2DSize& rSpriteCorrectionOffset(
rSpriteBoundsPixel.getMinimum() - rNominalShapeBoundsPixel.getMinimum() );
// offset added top, left for anti-aliasing (otherwise,
// shapes fully filling the sprite will have anti-aliased
// pixel cut off)
const ::basegfx::B2DSize aAAOffset(
::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE,
::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE );
// set pixel output offset to sprite: we always leave
// ANTIALIASING_EXTRA_SIZE room atop and to the left, and,
// what's more, for subsetted shapes, we _have_ to cancel
// the effect of the shape renderer outputting the subset
// at its absolute position inside the shape, instead of
// at the origin.
// NOTE: As for now, sprites are always positioned on
// integer pixel positions on screen, have to round to
// nearest integer here, too (fixed along with #121921#)
mpSprite->setPixelOffset(
aAAOffset - ::basegfx::B2DSize(
::basegfx::fround( rSpriteCorrectionOffset.getX() ),
::basegfx::fround( rSpriteCorrectionOffset.getY() ) ) );
// always set sprite position and transformation, since
// they do not relate directly to the update flags
// (e.g. sprite position changes when sprite size changes)
mpSprite->movePixel( aSpritePosPixel );
mpSprite->transform( getSpriteTransformation( rSpriteSizePixel,
rOrigBounds.getRange(),
pAttr ) );
// process flags
// =============
bool bRedrawRequired( mbForceUpdate || (nUpdateFlags & FORCE) );
if( mbForceUpdate || (nUpdateFlags & ALPHA) )
{
mpSprite->setAlpha( (pAttr && pAttr->isAlphaValid()) ?
::basegfx::clamp(pAttr->getAlpha(),
0.0,
1.0) :
1.0 );
}
if( mbForceUpdate || (nUpdateFlags & CLIP) )
{
if( pAttr && pAttr->isClipValid() )
{
::basegfx::B2DPolyPolygon aClipPoly( pAttr->getClip() );
// extract linear part of canvas view transformation
// (linear means: without translational components)
::basegfx::B2DHomMatrix aViewTransform(
mpViewLayer->getTransformation() );
aViewTransform.set( 0, 2, 0.0 );
aViewTransform.set( 1, 2, 0.0 );
// make the clip 2*ANTIALIASING_EXTRA_SIZE larger
// such that it's again centered over the sprite.
aViewTransform.scale(rSpriteSizePixel.getX()/
(rSpriteSizePixel.getX()-2*::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE),
rSpriteSizePixel.getY()/
(rSpriteSizePixel.getY()-2*::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE));
// transform clip polygon from view to device
// coordinate space
aClipPoly.transform( aViewTransform );
mpSprite->clip( aClipPoly );
}
else
mpSprite->clip();
}
if( mbForceUpdate || (nUpdateFlags & CONTENT) )
{
bRedrawRequired = true;
// TODO(P1): maybe provide some appearance change methods at
// the Renderer interface
// force the renderer to be regenerated below, for the
// different attributes to take effect
invalidateRenderer();
}
mbForceUpdate = false;
if( !bRedrawRequired )
return true;
// sprite needs repaint - output to sprite canvas
// ==============================================
::cppcanvas::CanvasSharedPtr pContentCanvas( mpSprite->getContentCanvas() );
return draw( pContentCanvas,
rMtf,
pAttr,
aShapeTransformation,
NULL, // clipping is done via Sprite::clip()
rSubsets );
}
bool ViewShape::render( const ::cppcanvas::CanvasSharedPtr& rDestinationCanvas,
const GDIMetaFileSharedPtr& rMtf,
const ::basegfx::B2DRectangle& rBounds,
const ::basegfx::B2DRectangle& rUpdateBounds,
int nUpdateFlags,
const ShapeAttributeLayerSharedPtr& pAttr,
const VectorOfDocTreeNodes& rSubsets,
bool bIsVisible ) const
{
RTL_LOGFILE_CONTEXT( aLog, "::presentation::internal::ViewShape::render()" );
// TODO(P1): For multiple views, it might pay off to reorg Shape and ViewShape,
// in that all the common setup steps here are refactored to Shape (would then
// have to be performed only _once_ per Shape paint).
if( !bIsVisible )
{
VERBOSE_TRACE( "ViewShape::render(): skipping shape %X", this );
// shape is invisible, no need to update anything.
return true;
}
// since we have no sprite here, _any_ update request
// translates into a required redraw.
bool bRedrawRequired( mbForceUpdate || nUpdateFlags != 0 );
if( (nUpdateFlags & CONTENT) )
{
// TODO(P1): maybe provide some appearance change methods at
// the Renderer interface
// force the renderer to be regenerated below, for the
// different attributes to take effect
invalidateRenderer();
}
mbForceUpdate = false;
if( !bRedrawRequired )
return true;
VERBOSE_TRACE( "ViewShape::render(): rendering shape %X at position (%f,%f)",
this,
rBounds.getMinX(),
rBounds.getMinY() );
// shape needs repaint - setup all that's needed
// ---------------------------------------------
boost::optional<basegfx::B2DPolyPolygon> aClip;
if( pAttr )
{
// setup clip poly
if( pAttr->isClipValid() )
aClip.reset( pAttr->getClip() );
// emulate global shape alpha by first rendering into
// a temp bitmap, and then to screen (this would have
// been much easier if we'd be currently a sprite -
// see above)
if( pAttr->isAlphaValid() )
{
const double nAlpha( pAttr->getAlpha() );
if( !::basegfx::fTools::equalZero( nAlpha ) &&
!::rtl::math::approxEqual(nAlpha, 1.0) )
{
// render with global alpha - have to prepare
// a bitmap, and render that with modulated
// alpha
// -------------------------------------------
const ::basegfx::B2DHomMatrix aTransform(
getShapeTransformation( rBounds,
pAttr ) );
// TODO(P1): Should the view transform some
// day contain rotation/shear, transforming
// the original bounds with the total
// transformation might result in smaller
// overall bounds.
// determine output rect of _shape update
// area_ in device pixel
const ::basegfx::B2DHomMatrix aCanvasTransform(
rDestinationCanvas->getTransformation() );
::basegfx::B2DRectangle aTmpRect;
::canvas::tools::calcTransformedRectBounds( aTmpRect,
rUpdateBounds,
aCanvasTransform );
// pixel size of cache bitmap: round up to
// nearest int
const ::basegfx::B2ISize aBmpSize( static_cast<sal_Int32>( aTmpRect.getWidth() )+1,
static_cast<sal_Int32>( aTmpRect.getHeight() )+1 );
// try to fetch temporary surface for alpha
// compositing (to achieve the global alpha
// blend effect, have to first render shape as
// a whole, then blit that surface with global
// alpha to the destination)
const RendererCacheVector::iterator aCompositingSurface(
getCacheEntry( rDestinationCanvas ) );
if( !aCompositingSurface->mpLastBitmapCanvas ||
aCompositingSurface->mpLastBitmapCanvas->getSize() != aBmpSize )
{
// create a bitmap of appropriate size
::cppcanvas::BitmapSharedPtr pBitmap(
::cppcanvas::BaseGfxFactory::getInstance().createAlphaBitmap(
rDestinationCanvas,
aBmpSize ) );
ENSURE_OR_THROW(pBitmap,
"ViewShape::render(): Could not create compositing surface");
aCompositingSurface->mpDestinationCanvas = rDestinationCanvas;
aCompositingSurface->mpLastBitmap = pBitmap;
aCompositingSurface->mpLastBitmapCanvas = pBitmap->getBitmapCanvas();
}
// buffer aCompositingSurface iterator content
// - said one might get invalidated during
// draw() below.
::cppcanvas::BitmapCanvasSharedPtr pBitmapCanvas(
aCompositingSurface->mpLastBitmapCanvas );
::cppcanvas::BitmapSharedPtr pBitmap(
aCompositingSurface->mpLastBitmap);
// setup bitmap canvas transformation -
// which happens to be the destination
// canvas transformation without any
// translational components.
//
// But then, the render transformation as
// calculated by getShapeTransformation()
// above outputs the shape at its real
// destination position. Thus, we have to
// offset the output back to the origin,
// for which we simply plug in the
// negative position of the left, top edge
// of the shape's bound rect in device
// pixel into aLinearTransform below.
::basegfx::B2DHomMatrix aAdjustedCanvasTransform( aCanvasTransform );
aAdjustedCanvasTransform.translate( -aTmpRect.getMinX(),
-aTmpRect.getMinY() );
pBitmapCanvas->setTransformation( aAdjustedCanvasTransform );
// TODO(P2): If no update flags, or only
// alpha_update is set, we can save us the
// rendering into the bitmap (uh, it's not
// _that_ easy - for a forced redraw,
// e.g. when ending an animation, we always
// get UPDATE_FORCE here).
// render into this bitmap
if( !draw( pBitmapCanvas,
rMtf,
pAttr,
aTransform,
!aClip ? NULL : &(*aClip),
rSubsets ) )
{
return false;
}
// render bitmap to screen, with given global
// alpha. Since the bitmap already contains
// pixel-equivalent output, we have to use the
// inverse view transformation, adjusted with
// the final shape output position (note:
// cannot simply change the view
// transformation here, as that would affect a
// possibly set clip!)
::basegfx::B2DHomMatrix aBitmapTransform( aCanvasTransform );
OSL_ENSURE( aBitmapTransform.isInvertible(),
"ViewShape::render(): View transformation is singular!" );
aBitmapTransform.invert();
const basegfx::B2DHomMatrix aTranslation(basegfx::tools::createTranslateB2DHomMatrix(
aTmpRect.getMinX(), aTmpRect.getMinY()));
aBitmapTransform = aBitmapTransform * aTranslation;
pBitmap->setTransformation( aBitmapTransform );
// finally, render bitmap alpha-modulated
pBitmap->drawAlphaModulated( nAlpha );
return true;
}
}
}
// retrieve shape transformation, _with_ shape translation
// to actual page position.
const ::basegfx::B2DHomMatrix aTransform(
getShapeTransformation( rBounds,
pAttr ) );
return draw( rDestinationCanvas,
rMtf,
pAttr,
aTransform,
!aClip ? NULL : &(*aClip),
rSubsets );
}
// -------------------------------------------------------------------------------------
ViewShape::ViewShape( const ViewLayerSharedPtr& rViewLayer ) :
mpViewLayer( rViewLayer ),
maRenderers(),
mpSprite(),
mbAnimationMode( false ),
mbForceUpdate( true )
{
ENSURE_OR_THROW( mpViewLayer, "ViewShape::ViewShape(): Invalid View" );
}
ViewLayerSharedPtr ViewShape::getViewLayer() const
{
return mpViewLayer;
}
ViewShape::RendererCacheVector::iterator ViewShape::getCacheEntry( const ::cppcanvas::CanvasSharedPtr& rDestinationCanvas ) const
{
// lookup destination canvas - is there already a renderer
// created for that target?
RendererCacheVector::iterator aIter;
const RendererCacheVector::iterator aEnd( maRenderers.end() );
// already there?
if( (aIter=::std::find_if( maRenderers.begin(),
aEnd,
::boost::bind(
::std::equal_to< ::cppcanvas::CanvasSharedPtr >(),
::boost::cref( rDestinationCanvas ),
::boost::bind(
&RendererCacheEntry::getDestinationCanvas,
_1 ) ) ) ) == aEnd )
{
if( maRenderers.size() >= MAX_RENDER_CACHE_ENTRIES )
{
// cache size exceeded - prune entries. For now,
// simply remove the first one, which of course
// breaks for more complex access schemes. But in
// general, this leads to most recently used
// entries to reside at the end of the vector.
maRenderers.erase( maRenderers.begin() );
// ATTENTION: after this, both aIter and aEnd are
// invalid!
}
// not yet in cache - add default-constructed cache
// entry, to have something to return
maRenderers.push_back( RendererCacheEntry() );
aIter = maRenderers.end()-1;
}
return aIter;
}
::cppcanvas::RendererSharedPtr ViewShape::getRenderer( const ::cppcanvas::CanvasSharedPtr& rDestinationCanvas,
const GDIMetaFileSharedPtr& rMtf,
const ShapeAttributeLayerSharedPtr& rAttr ) const
{
// lookup destination canvas - is there already a renderer
// created for that target?
const RendererCacheVector::iterator aIter(
getCacheEntry( rDestinationCanvas ) );
// now we have a valid entry, either way. call prefetch()
// on it, nevertheless - maybe the metafile changed, and
// the renderer still needs an update (prefetch() will
// detect that)
if( prefetch( *aIter,
rDestinationCanvas,
rMtf,
rAttr ) )
{
return aIter->mpRenderer;
}
else
{
// prefetch failed - renderer is invalid
return ::cppcanvas::RendererSharedPtr();
}
}
void ViewShape::invalidateRenderer() const
{
// simply clear the cache. Subsequent getRenderer() calls
// will regenerate the Renderers.
maRenderers.clear();
}
::basegfx::B2DSize ViewShape::getAntialiasingBorder() const
{
ENSURE_OR_THROW( mpViewLayer->getCanvas(),
"ViewShape::getAntialiasingBorder(): Invalid ViewLayer canvas" );
const ::basegfx::B2DHomMatrix& rViewTransform(
mpViewLayer->getTransformation() );
// TODO(F1): As a quick shortcut (did not want to invert
// whole matrix here), taking only scale components of
// view transformation matrix. This will be wrong when
// e.g. shearing is involved.
const double nXBorder( ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE / rViewTransform.get(0,0) );
const double nYBorder( ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE / rViewTransform.get(1,1) );
return ::basegfx::B2DSize( nXBorder,
nYBorder );
}
bool ViewShape::enterAnimationMode()
{
mbForceUpdate = true;
mbAnimationMode = true;
return true;
}
void ViewShape::leaveAnimationMode()
{
mpSprite.reset();
mbAnimationMode = false;
mbForceUpdate = true;
}
bool ViewShape::update( const GDIMetaFileSharedPtr& rMtf,
const RenderArgs& rArgs,
int nUpdateFlags,
bool bIsVisible ) const
{
RTL_LOGFILE_CONTEXT( aLog, "::presentation::internal::ViewShape::update()" );
ENSURE_OR_RETURN_FALSE( mpViewLayer->getCanvas(), "ViewShape::update(): Invalid layer canvas" );
// Shall we render to a sprite, or to a plain canvas?
if( isBackgroundDetached() )
return renderSprite( mpViewLayer,
rMtf,
rArgs.maOrigBounds,
rArgs.maBounds,
rArgs.maUnitBounds,
nUpdateFlags,
rArgs.mrAttr,
rArgs.mrSubsets,
rArgs.mnShapePriority,
bIsVisible );
else
return render( mpViewLayer->getCanvas(),
rMtf,
rArgs.maBounds,
rArgs.maUpdateBounds,
nUpdateFlags,
rArgs.mrAttr,
rArgs.mrSubsets,
bIsVisible );
}
}
}
| 45.556425 | 137 | 0.473009 | Grosskopf |
c544e038a050d0f02a4c8bd73294457099d108a9 | 660 | hpp | C++ | include/SplayLibrary/Core/RenderWindow.hpp | Reiex/SplayLibrary | 94b68f371ea4c662c84dfe2dd0a6d1625b60fb04 | [
"MIT"
] | 1 | 2021-12-14T21:36:39.000Z | 2021-12-14T21:36:39.000Z | include/SplayLibrary/Core/RenderWindow.hpp | Reiex/SplayLibrary | 94b68f371ea4c662c84dfe2dd0a6d1625b60fb04 | [
"MIT"
] | null | null | null | include/SplayLibrary/Core/RenderWindow.hpp | Reiex/SplayLibrary | 94b68f371ea4c662c84dfe2dd0a6d1625b60fb04 | [
"MIT"
] | null | null | null | #pragma once
#include <SplayLibrary/Core/types.hpp>
namespace spl
{
class RenderWindow : public Window
{
public:
RenderWindow(const uvec2& size, const std::string& title);
RenderWindow(const RenderWindow& window) = delete;
RenderWindow(RenderWindow&& window) = delete;
const RenderWindow& operator=(const RenderWindow& window) = delete;
const RenderWindow& operator=(RenderWindow&& window) = delete;
void display();
const Framebuffer& getFramebuffer() const;
~RenderWindow();
private:
virtual bool processEvent(Event*& event);
vec3 _clearColor;
Framebuffer _framebuffer;
};
}
| 20.625 | 71 | 0.680303 | Reiex |
c5460a64ed3932f8d78a3dacd0971d66ec8f8c82 | 5,631 | hpp | C++ | core/include/component/ComponentManager.hpp | Floriantoine/MyHunter_Sfml | 8744e1b03d9d5fb621f9cba7619d9d5dd943e428 | [
"MIT"
] | null | null | null | core/include/component/ComponentManager.hpp | Floriantoine/MyHunter_Sfml | 8744e1b03d9d5fb621f9cba7619d9d5dd943e428 | [
"MIT"
] | null | null | null | core/include/component/ComponentManager.hpp | Floriantoine/MyHunter_Sfml | 8744e1b03d9d5fb621f9cba7619d9d5dd943e428 | [
"MIT"
] | null | null | null |
#pragma once
#include "../assert.hpp"
#include "../types.hpp"
#include "./ComponentBase.hpp"
#include "tools/Chrono.hpp"
#include "tools/jsonTools.hpp"
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
namespace fa {
class ComponentManager {
private:
typedef std::function<void(id_t entityId, const nlohmann::json &)>
factory_function_t;
std::unordered_map<id_t, std::unordered_map<id_t, ComponentBase *>>
_componentLists;
std::unordered_map<std::string, factory_function_t> _componentNamesList;
bool isComponentTypeRegistered(id_t typeId) const;
template <class T> bool isComponentTypeRegistered() const
{
return this->isComponentTypeRegistered(T::getTypeId());
}
std::unordered_map<id_t, ComponentBase *> &getComponentList(id_t typeId);
bool hasComponent(id_t typeId, id_t entityId);
ComponentBase *getComponent(id_t typeId, id_t entityId);
void removeComponent(id_t typeId, id_t entityId);
public:
ComponentManager() = default;
ComponentManager(const ComponentManager &) = delete;
ComponentManager(ComponentManager &&) = delete;
~ComponentManager();
ComponentManager &operator=(const ComponentManager &) = delete;
void clear();
int getComponentCount() const;
std::vector<ComponentBase *> getEntityComponentList(id_t entity);
template <class T>
std::unordered_map<id_t, ComponentBase *> &getComponentList()
{
return this->getComponentList(T::getTypeId());
}
std::vector<std::string> getRegisterComponentNameList()
{
std::vector<std::string> nameList;
for (auto &it: this->_componentNamesList) {
nameList.push_back(it.first);
}
return nameList;
}
void registerComponentName(
const std::string &name, factory_function_t factory)
{
auto it = this->_componentNamesList.find(name);
if (it != this->_componentNamesList.end()) {
std::cout << "component already register for: " << name
<< std::endl;
return;
}
this->_componentNamesList[name] = factory;
}
bool componentNameIsRegister(const std::string &name)
{
auto it = this->_componentNamesList.find(name);
if (it != this->_componentNamesList.end()) {
return true;
}
return false;
}
template <typename... Args>
void addComponent(std::string name, id_t entityId, Args &&...args)
{
auto it = this->_componentNamesList.find(name);
if (it == this->_componentNamesList.end()) {
std::cout << "No Component register for: " << name << std::endl;
return;
}
it->second(entityId, std::forward<Args>(args)...);
}
template <class T, typename... Args>
void addComponent(id_t entityId, Args &&...args)
{
if (this->hasComponent<T>(entityId) != false) {
std::cout << "Entity already has component" << std::endl;
return;
// throw std::overflow_error("Entity already has component");
}
T *component = new T(std::forward<Args>(args)...);
this->getComponentList<T>()[entityId] =
static_cast<ComponentBase *>(component);
}
template <class T, typename... Args>
void addComponentRange(id_t startId, id_t endId, Args &&...args)
{
if (endId < startId)
assert("Bad Range");
for (fa::id_t index = startId; index < endId; index++) {
addComponent<T>(index, std::forward<Args>(args)...);
}
}
template <class T> bool hasComponent(id_t entityId)
{
return this->hasComponent(T::getTypeId(), entityId);
}
template <class T> T *getComponent(id_t entityId)
{
STATIC_ASSERT_IS_COMPONENT(T);
return static_cast<T *>(this->getComponent(T::getTypeId(), entityId));
}
template <class T> void removeComponentRange(id_t startId, id_t endId)
{
if (endId < startId)
assert("Bad Range");
for (fa::id_t index = startId; index < endId; index++) {
this->removeComponent(T::getTypeId(), index);
}
}
template <class T> void removeComponent(id_t entityId)
{
if (this->hasComponent<T>(entityId) == false)
throw std::overflow_error("Entity does not have component");
this->removeComponent(T::getTypeId(), entityId);
}
void removeAllComponents(id_t entityId);
void removeAllComponentsRange(id_t entityIdMin, id_t entityIdMax);
template <class T> void apply(std::function<void(T *)> function)
{
const auto &list = this->getComponentList<T>();
for (auto it = list.begin(), next = it; it != list.end(); it = next) {
next++;
function(static_cast<T *>(it->second));
}
}
template <class T>
void apply(std::function<void(
T *, id_t, const std::unordered_map<id_t, ComponentBase *> &)>
function)
{
if (this->isComponentTypeRegistered<T>()) {
const auto &list = this->getComponentList<T>();
for (auto it = list.begin(), next = it; it != list.end();
it = next) {
next++;
function(static_cast<T *>(it->second), it->first, list);
}
}
}
template <class T>
void apply(id_t entityId, std::function<void(T *)> function)
{
function(static_cast<T *>(this->getComponent<T>(entityId)));
}
};
} // namespace fa | 30.603261 | 78 | 0.604866 | Floriantoine |
c54a1e61064a6e382807f76565563f4de81af472 | 2,104 | hpp | C++ | include/sysmakeshift/detail/transaction.hpp | mbeutel/sysmakeshift | d6451315281b229222cb77f916c36b831acb054c | [
"BSL-1.0"
] | 2 | 2020-11-15T14:09:17.000Z | 2022-01-14T15:20:02.000Z | include/sysmakeshift/detail/transaction.hpp | mbeutel/sysmakeshift | d6451315281b229222cb77f916c36b831acb054c | [
"BSL-1.0"
] | 2 | 2020-02-16T02:20:22.000Z | 2020-02-16T20:49:03.000Z | include/sysmakeshift/detail/transaction.hpp | mbeutel/sysmakeshift | d6451315281b229222cb77f916c36b831acb054c | [
"BSL-1.0"
] | 1 | 2021-09-02T07:44:42.000Z | 2021-09-02T07:44:42.000Z |
#ifndef INCLUDED_SYSMAKESHIFT_DETAIL_TRANSACTION_HPP_
#define INCLUDED_SYSMAKESHIFT_DETAIL_TRANSACTION_HPP_
#include <utility> // for move(), exchange()
#include <type_traits> // for integral_constant<>
namespace sysmakeshift {
namespace detail {
// TODO: Should this be in gsl-lite? B. Stroustrup rightfully claims that `on_success()`, `on_error()`, and `finally()` are the elementary operations here, but
// calling `uncaught_exceptions()` does have a cost, so maybe a transaction is still a useful thing.
template <typename RollbackFuncT>
class transaction_t : private RollbackFuncT
{
private:
bool done_;
public:
constexpr transaction_t(RollbackFuncT&& rollbackFunc)
: RollbackFuncT(std::move(rollbackFunc)), done_(false)
{
}
~transaction_t(void)
{
if (!done_)
{
static_cast<RollbackFuncT&>(*this)();
}
}
constexpr void
commit(void) noexcept
{
done_ = true;
}
constexpr transaction_t(transaction_t&& rhs) // pre-C++17 tax
: RollbackFuncT(std::move(rhs)), done_(std::exchange(rhs.done_, true))
{
}
transaction_t&
operator =(transaction_t&&) = delete;
};
class no_op_transaction_t
{
public:
constexpr void commit(void) noexcept
{
}
no_op_transaction_t(void) noexcept = default;
no_op_transaction_t(no_op_transaction_t&&) = default;
no_op_transaction_t& operator =(no_op_transaction_t&&) = delete;
};
template <typename RollbackFuncT>
constexpr transaction_t<RollbackFuncT>
make_transaction(RollbackFuncT rollbackFunc)
{
return { std::move(rollbackFunc) };
}
template <typename RollbackFuncT>
constexpr transaction_t<RollbackFuncT>
make_transaction(std::true_type /*enableRollback*/, RollbackFuncT rollbackFunc)
{
return { std::move(rollbackFunc) };
}
template <typename RollbackFuncT>
constexpr no_op_transaction_t
make_transaction(std::false_type /*enableRollback*/, RollbackFuncT)
{
return { };
}
} // namespace detail
} // namespace sysmakeshift
#endif // INCLUDED_SYSMAKESHIFT_DETAIL_TRANSACTION_HPP_
| 23.909091 | 163 | 0.710076 | mbeutel |
c54a6db60416ac3dcb710cdfae8fc0cd9c344f24 | 394 | hpp | C++ | common/cxx/adstutil_cxx/include/adstutil_cxx/make_array.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/adstutil_cxx/include/adstutil_cxx/make_array.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/adstutil_cxx/include/adstutil_cxx/make_array.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | #pragma once
#include <array>
namespace adst::common {
template <typename... T>
constexpr auto make_array(T&&... values)
-> std::array<typename std::decay<typename std::common_type<T...>::type>::type, sizeof...(T)>
{
return std::array<typename std::decay<typename std::common_type<T...>::type>::type, sizeof...(T)>{
std::forward<T>(values)...};
}
} // namespace adst::common
| 26.266667 | 102 | 0.64467 | csitarichie |
c54b7a848a2452a52969d35624503c2a453077a4 | 8,895 | cpp | C++ | src/ISOBMFF.cpp | Ultraschall/ultraschall-3 | 7e2479fc0eb877a9b4979bedaf92f95bad627073 | [
"MIT"
] | 11 | 2018-07-08T09:14:22.000Z | 2019-11-08T02:54:42.000Z | src/ISOBMFF.cpp | Ultraschall/ultraschall-3 | 7e2479fc0eb877a9b4979bedaf92f95bad627073 | [
"MIT"
] | 17 | 2018-01-18T23:12:15.000Z | 2019-02-03T07:47:51.000Z | src/ISOBMFF.cpp | Ultraschall/ultraschall-3 | 7e2479fc0eb877a9b4979bedaf92f95bad627073 | [
"MIT"
] | 4 | 2018-03-07T19:38:29.000Z | 2019-01-10T09:04:05.000Z | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) The Ultraschall Project (http://ultraschall.fm)
//
// The MIT License (MIT)
//
// 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 <cstring>
#include "ISOBMFF.h"
#include "Common.h"
#include "FileManager.h"
#include "Marker.h"
#include "PictureUtilities.h"
#define MP4V2_EXPORTS 0
#define MP4V2_NO_STDINT_DEFS 1
#include <mp4v2/mp4v2.h>
namespace ultraschall { namespace reaper { namespace isobmff {
Context* StartTransaction(const UnicodeString& targetName)
{
PRECONDITION_RETURN(targetName.empty() == false, 0);
return new Context(targetName);
}
bool CommitTransaction(Context*& context)
{
PRECONDITION_RETURN(context->IsValid(), false);
const bool success = MP4TagsStore(context->Tags(), context->Target());
SafeDelete(context);
return success;
}
void AbortTransaction(Context*& context)
{
SafeDelete(context);
}
static MP4TagArtworkType QueryArtworkType(const uint8_t* data, const size_t dataSize)
{
PRECONDITION_RETURN(data != nullptr, MP4_ART_UNDEFINED);
PRECONDITION_RETURN(dataSize > 0, MP4_ART_UNDEFINED);
MP4TagArtworkType mp4_format = MP4_ART_UNDEFINED;
switch(QueryPictureFormat(data, dataSize))
{
case PICTURE_FORMAT::JPEG_PICTURE:
{
mp4_format = MP4_ART_JPEG;
break;
}
case PICTURE_FORMAT::PNG_PICTURE:
{
mp4_format = MP4_ART_PNG;
break;
}
default:
{
break;
}
}
return mp4_format;
}
static double QueryDuration(const Context* context)
{
PRECONDITION_RETURN(context != nullptr, -1);
PRECONDITION_RETURN(context->IsValid(), -1);
const uint32_t scale = MP4GetTimeScale(context->Target());
const MP4Duration duration = MP4GetDuration(context->Target());
return static_cast<double>(duration / scale);
}
static std::vector<MP4Chapter_t> ConvertChapters(const MarkerArray& chapterMarkers, const double maxDuration)
{
PRECONDITION_RETURN(chapterMarkers.empty() == false, std::vector<MP4Chapter_t>());
PRECONDITION_RETURN(maxDuration >= 0, std::vector<MP4Chapter_t>());
std::vector<MP4Chapter_t> result;
// mp4v2 library has a define named MP4V2_CHAPTER_TITLE_MAX which is 1023
// However when mp4v2 library is writing Nero chapter in MP4File::AddNeroChapter() the title
// will be further truncated to 255 byte length disregarding any possible utf8 multi-byte characters.
// So we have to take care of properly truncating to that size ourselves beforehand.
// This function does not do so itself but expects such truncated input.
const size_t maxTitleBytes = std::min(255, MP4V2_CHAPTER_TITLE_MAX);
double currentStart = 0;
for(size_t i = 0; i < chapterMarkers.size(); i++)
{
double currentDuration = (i == chapterMarkers.size() - 1) ?
maxDuration :
chapterMarkers[i + 1].Position() - chapterMarkers[i].Position();
// if we run over the total size clients (like VLC) may get confused
if(currentStart + currentDuration > maxDuration)
{
currentDuration = maxDuration - currentStart;
}
MP4Chapter_t currentChapter = {0};
currentChapter.duration = static_cast<uint32_t>(currentDuration * 1000);
const UnicodeString& markerName = chapterMarkers[i].Name();
if(markerName.empty() == false)
{
const size_t markerNameSize = std::min(markerName.size(), maxTitleBytes);
memset(currentChapter.title, 0, (markerNameSize + 1) * sizeof(char));
memmove(currentChapter.title, markerName.c_str(), markerNameSize);
result.push_back(currentChapter);
}
currentStart += currentDuration;
}
return result;
}
bool InsertName(const Context* context, const UnicodeString& name)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(name.empty() == false, false);
return MP4TagsSetName(context->Tags(), name.c_str());
}
bool InsertArtist(const Context* context, const UnicodeString& artist)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(artist.empty() == false, false);
return MP4TagsSetArtist(context->Tags(), artist.c_str());
}
bool InsertAlbum(const Context* context, const UnicodeString& album)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(album.empty() == false, false);
return MP4TagsSetAlbum(context->Tags(), album.c_str());
}
bool InsertReleaseDate(const Context* context, const UnicodeString& releaseDate)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(releaseDate.empty() == false, false);
return MP4TagsSetReleaseDate(context->Tags(), releaseDate.c_str());
}
bool InsertGenre(const Context* context, const UnicodeString& genre)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(genre.empty() == false, false);
return MP4TagsSetGenre(context->Tags(), genre.c_str());
}
bool InsertComments(const Context* context, const UnicodeString& comments)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(comments.empty() == false, false);
return MP4TagsSetComments(context->Tags(), comments.c_str());
}
bool InsertCoverImage(const Context* context, const UnicodeString& file)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(file.empty() == false, false);
bool result = false;
BinaryStream* picture = FileManager::ReadBinaryFile(file);
if(picture != nullptr)
{
MP4TagArtwork mp4ArtWork;
mp4ArtWork.size = static_cast<uint32_t>(picture->DataSize());
mp4ArtWork.data = const_cast<void*>(static_cast<const void*>(picture->Data()));
mp4ArtWork.type = QueryArtworkType(picture->Data(), picture->DataSize());
if(mp4ArtWork.type != MP4_ART_UNDEFINED)
{
bool removedAll = true;
while((context->Tags()->artworkCount > 0) && (true == removedAll))
{
removedAll = MP4TagsRemoveArtwork(context->Tags(), 0);
}
if(true == removedAll)
{
result = MP4TagsAddArtwork(context->Tags(), &mp4ArtWork);
}
}
SafeRelease(picture);
}
return result;
}
bool InsertChapterMarkers(const Context* context, const MarkerArray& markers)
{
PRECONDITION_RETURN(context != nullptr, false);
PRECONDITION_RETURN(context->IsValid() != false, false);
PRECONDITION_RETURN(markers.empty() == false, false);
bool result = false;
const double duration = QueryDuration(context);
if(duration >= 0) // this is safe!
{
std::vector<MP4Chapter_t> chapters = ConvertChapters(markers, duration);
if(chapters.empty() == false)
{
const MP4ChapterType type = MP4SetChapters(
context->Target(), &chapters[0], static_cast<uint32_t>(chapters.size()), MP4ChapterTypeAny);
if(MP4ChapterTypeAny == type)
{
result = true;
}
}
}
return result;
}
}}} // namespace ultraschall::reaper::isobmff
| 33.821293 | 109 | 0.665318 | Ultraschall |
c54d606e4e2bd9db74ad536c7b00ae70bbc1a342 | 3,540 | cpp | C++ | components/events-comp/event_loop.cpp | chegewara/esp32sx-c-plus-wrappers | dcc61fc057d6d07b354b4bd352956240707ca482 | [
"MIT"
] | 3 | 2021-12-15T10:24:08.000Z | 2022-03-10T14:34:10.000Z | components/events-comp/event_loop.cpp | chegewara/esp32sx-c-plus-wrappers | dcc61fc057d6d07b354b4bd352956240707ca482 | [
"MIT"
] | null | null | null | components/events-comp/event_loop.cpp | chegewara/esp32sx-c-plus-wrappers | dcc61fc057d6d07b354b4bd352956240707ca482 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "events.h"
bool EventLoop::default_running = false;
EventLoop::EventLoop() {}
EventLoop::~EventLoop() {}
esp_err_t EventLoop::init(const char* name)
{
if(event_loop != NULL) return ESP_FAIL;
esp_event_loop_args_t event_loop_args = {};
event_loop_args.queue_size = 5;
event_loop_args.task_name = name;
event_loop_args.task_priority = 10;
event_loop_args.task_stack_size = 3 * 1024;
event_loop_args.task_core_id = 1;
return esp_event_loop_create(&event_loop_args, &event_loop);
}
esp_err_t EventLoop::init(const esp_event_loop_args_t* event_loop_args)
{
if(event_loop != NULL) return ESP_FAIL;
return esp_event_loop_create(event_loop_args, &event_loop);
}
esp_err_t EventLoop::deinit()
{
if(event_loop == NULL) return ESP_FAIL;
return esp_event_loop_delete(event_loop);
}
esp_err_t EventLoop::initDefault()
{
esp_err_t err = ESP_OK;
if (!default_running)
{
err = esp_event_loop_create_default();
}
default_running = err == ESP_OK || err == ESP_ERR_INVALID_STATE;
return default_running? ESP_OK : err;
}
esp_err_t EventLoop::deinitDefault()
{
return esp_event_loop_delete_default();
}
esp_err_t EventLoop::run(size_t timeout)
{
if(event_loop == NULL) return ESP_FAIL;
return esp_event_loop_run(event_loop, timeout);
}
esp_err_t EventLoop::registerEvent(esp_event_handler_t event_handler, esp_event_base_t event_base, int32_t event_id, void *event_handler_arg)
{
if(event_loop == NULL) return ESP_FAIL;
return esp_event_handler_instance_register_with(event_loop, event_base, event_id, event_handler, this, NULL);
}
esp_err_t EventLoop::registerEventDefault(esp_event_handler_t event_handler, esp_event_base_t event_base, int32_t event_id, void *event_handler_arg)
{
initDefault();
return esp_event_handler_instance_register(event_base, event_id, event_handler, event_handler_arg, NULL);
}
esp_err_t EventLoop::unregisterEvent(esp_event_base_t event_base, int32_t event_id)
{
if(event_loop == NULL) return ESP_FAIL;
return esp_event_handler_instance_unregister_with(event_loop, event_base, event_id, NULL);
}
esp_err_t EventLoop::unregisterEventDefault(esp_event_base_t event_base, int32_t event_id)
{
return esp_event_handler_instance_unregister(event_base, event_id, NULL);
}
esp_err_t EventLoop::post(esp_event_base_t event_base, int32_t event_id, void *event_data, size_t event_data_size, TickType_t timeout)
{
if(event_loop == NULL) return ESP_FAIL;
return esp_event_post_to(event_loop, event_base, event_id, event_data, event_data_size, timeout);
}
esp_err_t EventLoop::postDefault(esp_event_base_t event_base, int32_t event_id, void *event_data, size_t event_data_size, TickType_t timeout)
{
return esp_event_post(event_base, event_id, event_data, event_data_size, timeout);
}
#if CONFIG_ESP_EVENT_POST_FROM_ISR
esp_err_t EventLoop::postISR(esp_event_base_t event_base, int32_t event_id, BaseType_t *task_unblocked, void *event_data, size_t event_data_size)
{
if(event_loop == NULL) return ESP_FAIL;
return esp_event_isr_post_to(event_loop, event_base, event_id, event_data, event_data_size, task_unblocked);
}
esp_err_t EventLoop::postDefaultISR(esp_event_base_t event_base, int32_t event_id, BaseType_t *task_unblocked, void *event_data, size_t event_data_size)
{
return esp_event_isr_post(event_base, event_id, event_data, event_data_size, task_unblocked);
}
#endif
esp_err_t EventLoop::dump(FILE* file)
{
return esp_event_dump(file);
}
| 32.181818 | 152 | 0.781356 | chegewara |
c54dedd28857f908927db90eab10f5938387c41e | 1,430 | hpp | C++ | cppcache/integration-test/TimeBomb.hpp | alb3rtobr/geode-native | bab0b5238b6b7688645a935bbaa74532f0f4d9b8 | [
"Apache-2.0"
] | null | null | null | cppcache/integration-test/TimeBomb.hpp | alb3rtobr/geode-native | bab0b5238b6b7688645a935bbaa74532f0f4d9b8 | [
"Apache-2.0"
] | null | null | null | cppcache/integration-test/TimeBomb.hpp | alb3rtobr/geode-native | bab0b5238b6b7688645a935bbaa74532f0f4d9b8 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef GEODE_INTEGRATION_TEST_TIMEBOMB_H_
#define GEODE_INTEGRATION_TEST_TIMEBOMB_H_
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>
class TimeBomb {
public:
explicit TimeBomb(const std::chrono::milliseconds& sleep,
std::function<void()> cleanup);
~TimeBomb() noexcept;
void arm();
void disarm();
void run();
protected:
bool enabled_;
std::mutex mutex_;
std::condition_variable cv_;
std::thread thread_;
std::function<void()> callback_;
std::chrono::milliseconds sleep_;
};
#endif // GEODE_INTEGRATION_TEST_TIMEBOMB_H_
| 28.039216 | 75 | 0.739161 | alb3rtobr |
c54e48b694238e9352bda8d66173e8da7373209b | 1,541 | cpp | C++ | shape.cpp | anthony-bartman/Painting-Pixels | ec820fc1fa422c0d4ca10dedfe83d8a9bce61b92 | [
"MIT"
] | null | null | null | shape.cpp | anthony-bartman/Painting-Pixels | ec820fc1fa422c0d4ca10dedfe83d8a9bce61b92 | [
"MIT"
] | null | null | null | shape.cpp | anthony-bartman/Painting-Pixels | ec820fc1fa422c0d4ca10dedfe83d8a9bce61b92 | [
"MIT"
] | null | null | null | /**
* Anthony Bartman
* Dr. Varnell
* Computer Graphics: CS 3210 021
* 05/03/2020
*
* Desc:
* This file handles all of the shape method functions.
*/
#include "shape.h"
/*********************************************************
* Construction / Destruction
*********************************************************/
//Constructor (Shape s;)
shape::shape()
{
//Sets shape color to black
this->color = 0x000000;
}
//Parameterized Constructor (Shape s(red);)
shape::shape(unsigned int color)
{
//Set color (Make it a 24-bit value)
//color &= !(0xFFFFFF00);
this->color = color;
}
//Copy Constructor (Shape s = s1;)
shape::shape(const shape &rhs)
{
//Set color
this->color = rhs.color;
}
//Virtual Destructor
shape::~shape() {}
/*********************************************************
* Assignement Operators
*********************************************************/
//Equals Operator (s1 = s2;)
shape &shape::operator=(const shape &rhs)
{
//Checks if the shape is not equalling itself; for efficiency purposes
if (this != &rhs)
{
//Set color
this->color = rhs.color;
}
}
/*********************************************************
* Utility operations
*********************************************************/
//Dumps shape properties to the output stream
ostream &shape::out(ostream &os) const {
os << this->color << endl;
}
//Read shape properties from a text file
istream &shape::in(istream &is){
int color;
is >> color;
this->color = color;
} | 23.707692 | 74 | 0.491239 | anthony-bartman |
c55a096e83e4da80b2c6fd24b9ba7cd94c0f4319 | 1,139 | cpp | C++ | chapter11/ex09_binary_io.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 124 | 2018-06-23T10:16:56.000Z | 2022-03-19T15:16:12.000Z | chapter11/ex09_binary_io.cpp | therootfolder/stroustrup-ppp | b1e936c9a67b9205fdc9712c42496b45200514e2 | [
"MIT"
] | 23 | 2018-02-08T20:57:46.000Z | 2021-10-08T13:58:29.000Z | chapter11/ex09_binary_io.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 65 | 2019-05-27T03:05:56.000Z | 2022-03-26T03:43:05.000Z | #include "../text_lib/std_lib_facilities.h"
vector<int> binary_in(const string& fname)
// read in a file and store as binary in vector
{
ifstream ifs {fname, ios_base::binary};
if (!ifs) error("can't read from file ", fname);
vector<int> v;
for (int x; ifs.read(as_bytes(x), sizeof(int)); )
v.push_back(x);
return v;
}
void binary_out(const string& fname, const vector<int>& v)
// write out to a file from binary
{
ofstream ofs {fname, ios_base::binary};
if (!ofs) error("could not write to file ", fname);
for (int x : v)
ofs.write(as_bytes(x), sizeof(int));
}
int main()
try {
// open an istream for binary input from a file:
cout << "Please enter input file name\n";
string iname;
cin >> iname;
vector<int> bin = binary_in(iname);
// open an ostream for binary output to a file:
cout << "Please enter output file name\n";
string oname;
cin >> oname;
binary_out(oname, bin);
return 0;
}
catch(exception& e) {
cerr << "Exception: " << e.what() << '\n';
return 1;
}
catch(...) {
cerr << "exception\n";
return 2;
}
| 22.333333 | 58 | 0.604039 | ClassAteam |
c55be2e5e9ee6dc51a87ffc337c01cc48707c056 | 3,284 | cpp | C++ | frame_dropper/src/frame_dropper.cpp | robotics-upo/siar_packages | 2b9b3e7acbc9bc5845b03d63eb18dbc50bfd3c98 | [
"BSD-3-Clause"
] | 3 | 2020-02-06T13:36:38.000Z | 2020-11-10T08:52:23.000Z | frame_dropper/src/frame_dropper.cpp | robotics-upo/siar_packages | 2b9b3e7acbc9bc5845b03d63eb18dbc50bfd3c98 | [
"BSD-3-Clause"
] | null | null | null | frame_dropper/src/frame_dropper.cpp | robotics-upo/siar_packages | 2b9b3e7acbc9bc5845b03d63eb18dbc50bfd3c98 | [
"BSD-3-Clause"
] | 2 | 2017-03-20T16:08:37.000Z | 2018-04-22T04:26:12.000Z | #include <ros/ros.h>
#include <image_transport/image_transport.h>
// OpenCV stuff
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
// OpenCV to ROS stuff
#include <cv_bridge/cv_bridge.h>
class FrameDropper
{
public:
FrameDropper(void) : it(nh)
{
// Resolve the camera topic
cameraTopic = nh.resolveName("in");
imageTopic = cameraTopic+"/rgb/image_raw";
depthTopic = cameraTopic + "/depth_registered/image_raw";
cameraTopic = nh.resolveName("out");
imageOutTopic = cameraTopic+"/rgb/image_raw";
depthOutTopic = cameraTopic + "/depth_registered/image_raw";
// Load parameters
ros::NodeHandle lnh("~");
if(!lnh.getParam("frame_skip", frameSkip))
frameSkip = 3;
if(!lnh.getParam("publish_depth", publish_depth))
publish_depth = false;
if(!lnh.getParam("scale", scale))
scale = 1.0;
if(!lnh.getParam("downsample_depth", downsample_depth))
downsample_depth = true;
// Create subsciber
sub = it.subscribe(imageTopic, 1, &FrameDropper::imageCb, this);
if (publish_depth)
depth_sub = it.subscribe(depthTopic, 1, &FrameDropper::depthCb, this);
// Advertise the new Depth Image
ROS_INFO("Depth topic: %s Depth out topic: %s PUblish depth = %d", depthTopic.c_str(), depthOutTopic.c_str(), publish_depth);
pub = it.advertise(imageOutTopic, 1);
if (publish_depth)
depth_pub = it.advertise(depthOutTopic, 1);
imgCount = 0;
depthCount = 0;
}
~FrameDropper(void)
{
}
void imageCb(const sensor_msgs::ImageConstPtr& msg)
{
imgCount++;
if(imgCount < frameSkip)
{
return;
}
imgCount = 0;
cv_bridge::CvImagePtr img_cv = cv_bridge::toCvCopy(msg, "bgr8");
cv::Mat dst(msg->width * scale,msg->height * scale,img_cv->image.type());
cv::resize(img_cv->image, dst, cv::Size(0,0), scale, scale);
img_cv->image = dst;
sensor_msgs::ImagePtr pt = img_cv->toImageMsg();
pub.publish(pt);
// ROS_ERROR("Img res: %d, %d", pt->height, pt->width);
}
void depthCb(const sensor_msgs::ImageConstPtr& msg)
{
depthCount++;
if(depthCount < frameSkip)
{
return;
}
depthCount = 0;
double scale = downsample_depth?this->scale*0.5:this->scale;
cv_bridge::CvImagePtr img_cv = cv_bridge::toCvCopy(msg, "32FC1");
cv::Mat dst(msg->width * scale,msg->height * scale,img_cv->image.type());
cv::resize(img_cv->image, dst, cv::Size(0,0), scale, scale);
img_cv->image = dst;
sensor_msgs::ImagePtr pt = img_cv->toImageMsg();
depth_pub.publish(pt);
}
protected:
// ROS handler and subscribers
ros::NodeHandle nh;
image_transport::ImageTransport it;
image_transport::Publisher pub;
image_transport::Subscriber sub;
image_transport::Publisher depth_pub;
image_transport::Subscriber depth_sub;
// System params
std::string cameraTopic, imageTopic, imageOutTopic;
std::string depthTopic, depthOutTopic;
int frameSkip;
int imgCount, depthCount;
double scale; // Scaling in the image
bool publish_depth, downsample_depth;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "frame_dropper");
FrameDropper node;
ros::spin();
}
| 26.272 | 129 | 0.654385 | robotics-upo |
c55c929cdfd49640ca3edc33507edc00a4002221 | 22,593 | cpp | C++ | src/OpcUaStackCore/Base/DataMemArray.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 108 | 2018-10-08T17:03:32.000Z | 2022-03-21T00:52:26.000Z | src/OpcUaStackCore/Base/DataMemArray.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 287 | 2018-09-18T14:59:12.000Z | 2022-01-13T12:28:23.000Z | src/OpcUaStackCore/Base/DataMemArray.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 32 | 2018-10-19T14:35:03.000Z | 2021-11-12T09:36:46.000Z | /*
Copyright 2017 Kai Huebl (kai@huebl-sgh.de)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: Kai Huebl (kai@huebl-sgh.de)
*/
#include <cstring>
#include <iostream>
#include "OpcUaStackCore/Base/Log.h"
#include "OpcUaStackCore/Base/DataMemArray.h"
namespace OpcUaStackCore
{
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// DataMemArrayHeader
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
DataMemArrayHeader::DataMemArrayHeader(void)
{
}
DataMemArrayHeader::~DataMemArrayHeader(void)
{
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// DataMemArraySlot
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
DataMemArraySlot::DataMemArraySlot(void)
{
}
DataMemArraySlot::~DataMemArraySlot(void)
{
}
void
DataMemArraySlot::set(const char* buf, uint32_t bufLen)
{
char* mem = (char*)this + sizeof(DataMemArraySlot);
memcpy(mem, buf, bufLen);
}
bool
DataMemArraySlot::get(char* buf, uint32_t& bufLen)
{
if (dataSize_ > bufLen) {
return false;
}
char* mem = (char*)this + sizeof(DataMemArraySlot);
memcpy(buf, mem, dataSize_);
bufLen = dataSize_;
return true;
}
bool
DataMemArraySlot::get(char** buf, uint32_t& bufLen)
{
*buf = (char*)this + sizeof(DataMemArraySlot);
bufLen = dataSize_;
return true;
}
bool
DataMemArraySlot::isStartSlot(void)
{
return type_ == 'S';
}
bool
DataMemArraySlot::isEndSlot(void)
{
return type_ == 'E';
}
bool
DataMemArraySlot::isFreeSlot(void)
{
return type_ == 'F';
}
bool
DataMemArraySlot::isUsedSlot(void)
{
return type_ == 'U';
}
DataMemArraySlot*
DataMemArraySlot::next(void)
{
if (type_ == 'E') return nullptr;
DataMemArraySlot* slot = (DataMemArraySlot*)((char*)this + sizeof(DataMemArraySlot) + memSize() + sizeof(uint32_t));
return slot;
}
DataMemArraySlot*
DataMemArraySlot::last(void)
{
if (type_ == 'S') return nullptr;
uint32_t *memSize = (uint32_t*)((char*)this - sizeof(uint32_t));
DataMemArraySlot* slot = (DataMemArraySlot*)((char*)this - sizeof(uint32_t) - *memSize - sizeof(DataMemArraySlot));
return slot;
}
uint32_t
DataMemArraySlot::dataSize(void)
{
return dataSize_;
}
uint32_t
DataMemArraySlot::paddingSize(void)
{
return paddingSize_;
}
uint32_t
DataMemArraySlot::memSize(void)
{
return dataSize_ + paddingSize_;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// DataMemArray
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
uint32_t DataMemArray::minMemorySize_ = 100;
DataMemArray::DataMemArray(void)
: debug_(true)
, dataMemArrayHeader_(nullptr)
, freeSlotMap_()
, startMemorySize_(10000)
, maxMemorySize_(1000000)
, expandMemorySize_(10000)
{
}
DataMemArray::~DataMemArray(void)
{
clear();
}
void
DataMemArray::startMemorySize(uint32_t startMemorySize)
{
if (startMemorySize < minMemorySize_) {
startMemorySize_ = minMemorySize_;
}
else {
startMemorySize_ = startMemorySize;
}
}
uint32_t
DataMemArray::startMemorySize(void)
{
return startMemorySize_;
}
void
DataMemArray::maxMemorySize(uint32_t maxMemorySize)
{
if (dataMemArrayHeader_ == nullptr) {
if (maxMemorySize < startMemorySize_) {
maxMemorySize_ = startMemorySize_;
expandMemorySize_ = 0;
}
else {
maxMemorySize_ = maxMemorySize;
}
}
else {
if (maxMemorySize < dataMemArrayHeader_->actArraySize_) {
dataMemArrayHeader_->maxMemorySize_ = dataMemArrayHeader_->actArraySize_;
}
else {
dataMemArrayHeader_->maxMemorySize_ = maxMemorySize;
}
}
}
uint32_t
DataMemArray::maxMemorySize(void)
{
if (dataMemArrayHeader_ == nullptr) {
return maxMemorySize_;
}
else {
return dataMemArrayHeader_->maxMemorySize_;
}
}
void
DataMemArray::expandMemorySize(uint32_t expandMemorySize)
{
if (expandMemorySize < (sizeof(DataMemArraySlot) + sizeof(uint32_t))) {
expandMemorySize = (sizeof(DataMemArraySlot) + sizeof(uint32_t));
}
if (dataMemArrayHeader_ == nullptr) {
expandMemorySize_ = expandMemorySize;
}
else {
dataMemArrayHeader_->expandMemorySize_ = expandMemorySize;
}
}
uint32_t
DataMemArray::expandMemorySize(void)
{
return expandMemorySize_;
}
uint32_t
DataMemArray::size(void)
{
if (dataMemArrayHeader_ == nullptr) {
return 0;
}
return dataMemArrayHeader_->actArraySize_;
}
bool
DataMemArray::resize(uint32_t arraySize)
{
if (dataMemArrayHeader_ == nullptr) {
if (!createNewMemory(arraySize)) return false;
return true;
}
if (arraySize == dataMemArrayHeader_->actArraySize_) {
return true;
}
if (arraySize < dataMemArrayHeader_->actArraySize_) {
return decreaseArraySize(arraySize);
}
else {
return increaseArraySize(arraySize);
}
return true;
}
bool
DataMemArray::unset(uint32_t idx)
{
if (dataMemArrayHeader_ == nullptr) {
return false;
}
if (idx >= dataMemArrayHeader_->actArraySize_) {
return false;
}
//
// get slot
//
char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t)));
if (*pos == 0) {
return true;
}
DataMemArraySlot* slot = posToSlot(*pos);
DataMemArraySlot* lastSlot = slot->last();
DataMemArraySlot* nextSlot = slot->next();
//
// release slot
//
uint32_t freeSize = slot->memSize();
if (nextSlot != nullptr && nextSlot->type_ == 'F') {
freeSize += (nextSlot->memSize() + sizeof(DataMemArraySlot) + sizeof(uint32_t));
DataMemArraySlot::Map::iterator it;
it = freeSlotMap_.find(ptrToPos((char*)nextSlot));
freeSlotMap_.erase(it);
}
if (lastSlot != nullptr && lastSlot->type_ == 'F') {
freeSize += (lastSlot->memSize() + sizeof(DataMemArraySlot) + sizeof(uint32_t));
DataMemArraySlot::Map::iterator it;
it = freeSlotMap_.find(ptrToPos((char*)lastSlot));
freeSlotMap_.erase(it);
slot = lastSlot;
}
slot = createNewSlot((char*)slot, 'F', freeSize);
freeSlotMap_.insert(std::make_pair(ptrToPos((char*)slot), slot));
//
// release array element
//
*pos = 0;
return true;
}
bool
DataMemArray::set(uint32_t idx, const char* buf, uint32_t bufLen)
{
if (buf == nullptr) {
return false;
}
if (bufLen == 0) {
return false;
}
if (dataMemArrayHeader_ == nullptr) {
return false;
}
if (idx >= dataMemArrayHeader_->actArraySize_) {
return false;
}
//
// find free memory slot
//
DataMemArraySlot* slot = nullptr;
DataMemArraySlot::Map::iterator it;
for (it = freeSlotMap_.begin(); it != freeSlotMap_.end(); it++) {
DataMemArraySlot* tmpSlot = it->second;
if (tmpSlot->dataSize() >= bufLen) {
slot = tmpSlot;
break;
}
}
if (slot == nullptr) {
if (increaseMemory(bufLen)) {
return set(idx, buf, bufLen);
}
return false;
}
//
// check available memory in slot
//
freeSlotMap_.erase(it);
if ((bufLen + sizeof(DataMemArraySlot) + sizeof(uint32_t)) >= slot->dataSize()) {
// use the entire slot
uint32_t padding = slot->dataSize() - bufLen;
slot = createNewSlot((char*)slot, 'U', bufLen, padding);
}
else {
// split slot
DataMemArraySlot* freeSlot;
uint32_t freeSlotSize = slot->dataSize() - bufLen - sizeof(DataMemArraySlot) - sizeof(uint32_t);
slot = createNewSlot((char*)slot, 'U', bufLen, 0);
freeSlot = createNewSlot((char*)slot + bufLen + sizeof(DataMemArraySlot) + sizeof(uint32_t), 'F', freeSlotSize);
freeSlotMap_.insert(std::make_pair(ptrToPos((char*)freeSlot), freeSlot));
}
//
// set memory and array index
//
slot->set(buf, bufLen);
setIndex(idx, ptrToPos((char*)slot));
return true;
}
bool
DataMemArray::set(uint32_t idx, const std::string& value)
{
return set(idx, value.c_str(), value.length());
}
bool
DataMemArray::get(uint32_t idx, char* buf, uint32_t& bufLen)
{
if (dataMemArrayHeader_ == nullptr) {
return false;
}
if (idx >= dataMemArrayHeader_->actArraySize_) {
return false;
}
char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t)));
if (*pos == 0) {
return false;
}
DataMemArraySlot* slot = posToSlot(*pos);
return slot->get(buf, bufLen);
}
bool
DataMemArray::get(uint32_t idx, char** buf, uint32_t& bufLen)
{
if (dataMemArrayHeader_ == nullptr) {
return false;
}
if (idx >= dataMemArrayHeader_->actArraySize_) {
return false;
}
char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t)));
if (*pos == 0) {
return false;
}
DataMemArraySlot* slot = posToSlot(*pos);
return slot->get(buf, bufLen);
}
bool
DataMemArray::get(uint32_t idx, std::string& value)
{
char *buf;
uint32_t bufLen;
if (!get(idx, &buf, bufLen)) {
return false;
}
value = std::string(buf, bufLen);
return true;
}
bool
DataMemArray::exist(uint32_t idx)
{
if (dataMemArrayHeader_ == nullptr) {
return false;
}
char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t)));
if (*pos == 0) {
return false;
}
return true;
}
void
DataMemArray::clear(void)
{
if (dataMemArrayHeader_ != nullptr) {
char* mem = (char*)dataMemArrayHeader_;
delete [] mem;
dataMemArrayHeader_ = nullptr;
}
freeSlotMap_.clear();
startMemorySize_ = 10000;
maxMemorySize_ = 1000000;
expandMemorySize_ = 10000;
}
void
DataMemArray::log(void)
{
logHeader();
logSlot();
logArray();
}
void
DataMemArray::logHeader(void)
{
if (dataMemArrayHeader_ == nullptr) {
return;
}
Log(Debug, "Header")
.parameter("MaxMemorySize", dataMemArrayHeader_->maxMemorySize_)
.parameter("ExpandMemorySize", dataMemArrayHeader_->expandMemorySize_)
.parameter("ActMemorySize", dataMemArrayHeader_->actMemorySize_)
.parameter("ActArraySize", dataMemArrayHeader_->actArraySize_);
}
void
DataMemArray::logSlot(void)
{
if (dataMemArrayHeader_ == nullptr) {
return;
}
DataMemArraySlot* slot = firstSlot();
if (slot == nullptr) {
return;
}
do {
Log(Debug, "Slot")
.parameter("Type", slot->type_)
.parameter("Pos", ptrToPos((char*)slot))
.parameter("DataSize", slot->dataSize())
.parameter("PaddingSize", slot->paddingSize())
.parameter("MemSize", slot->memSize());
slot = slot->next();
} while (slot != nullptr);
}
void
DataMemArray::logArray(void)
{
if (dataMemArrayHeader_ == nullptr) {
return;
}
char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
for (uint32_t idx = 0; idx < dataMemArrayHeader_->actArraySize_; idx++) {
uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t)));
if (*pos != 0) {
DataMemArraySlot* slot = posToSlot(*pos);
Log(Debug, "Array")
.parameter("Idx", idx)
.parameter("Pos", *pos)
.parameter("Len", slot->dataSize_);
}
}
}
void
DataMemArray::logFreeSlots(void)
{
if (dataMemArrayHeader_ == nullptr) {
return;
}
DataMemArraySlot::Map::iterator it;
for (it = freeSlotMap_.begin(); it != freeSlotMap_.end(); it++) {
DataMemArraySlot* slot = it->second;
Log(Debug, "FreeSlots")
.parameter("Pos", it->first)
.parameter("Len", slot->dataSize());
}
}
bool
DataMemArray::setMemoryBuf(char* memBuf, uint32_t memLen)
{
if (memBuf == nullptr) {
return false;
}
if (dataMemArrayHeader_ != nullptr) {
clear();
}
char* tmpMem = new char [memLen];
memcpy(tmpMem, memBuf, memLen);
dataMemArrayHeader_ = (DataMemArrayHeader*)tmpMem;
//
// create free slot list
//
freeSlotMap_.clear();
DataMemArraySlot* slot = (DataMemArraySlot*)((char*)dataMemArrayHeader_ + sizeof(DataMemArrayHeader));
while (slot->type_ != 'E') {
if (slot->type_ == 'F') {
freeSlotMap_.insert(std::make_pair(ptrToPos((char*)slot), slot));
}
slot = slot->next();
}
return true;
}
bool
DataMemArray::getMemoryBuf(char** memBuf, uint32_t* memLen)
{
if (dataMemArrayHeader_ == nullptr) {
return false;
}
*memBuf = (char*)dataMemArrayHeader_;
*memLen = dataMemArrayHeader_->actMemorySize_;
return true;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// private function
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
DataMemArraySlot*
DataMemArray::posToSlot(uint32_t pos)
{
if (dataMemArrayHeader_ == nullptr) {
return nullptr;
}
return (DataMemArraySlot*)((char*)dataMemArrayHeader_ + pos);
}
uint32_t
DataMemArray::ptrToPos(char* ptr)
{
if (dataMemArrayHeader_ == nullptr) return 0;
return (ptr - (char*)dataMemArrayHeader_);
}
DataMemArraySlot*
DataMemArray::firstSlot(void)
{
if (dataMemArrayHeader_ == nullptr) {
return nullptr;
}
return (DataMemArraySlot*)((char*)dataMemArrayHeader_ + sizeof(DataMemArrayHeader));
}
void
DataMemArray::setIndex(uint32_t idx, uint32_t value)
{
if (dataMemArrayHeader_ == nullptr) {
return;
}
char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t)));
*pos = value;
}
void
DataMemArray::getIndex(uint32_t idx, uint32_t& value)
{
if (dataMemArrayHeader_ == nullptr) {
return;
}
char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t)));
value = *pos;
}
bool
DataMemArray::createNewMemory(uint32_t arraySize)
{
//
// calculate used buffer size
//
// HEAD B-Slot F-Slot E-Slot Array
//
uint32_t usedMemorySize = sizeof(DataMemArrayHeader) +
3*(sizeof(DataMemArraySlot) + sizeof(uint32_t)) +
arraySize * sizeof(char*) +
minMemorySize_;
//
// check max memory size
//
if (maxMemorySize_ != 0 && usedMemorySize > maxMemorySize_) {
Log(Error, "allocate memory error - used memory size is bigger then max memory size")
.parameter("Id", this)
.parameter("UsedMemorySize", usedMemorySize)
.parameter("MaxMemorySize", maxMemorySize_);
return false;
}
//
// calculate actual memory size
//
uint32_t actMemorySize = startMemorySize_;
while (usedMemorySize > actMemorySize) actMemorySize += expandMemorySize_;
uint32_t dataSize = actMemorySize -
sizeof(DataMemArrayHeader) -
(3*(sizeof(DataMemArraySlot) + sizeof(uint32_t))) -
(arraySize * sizeof(uint32_t));
//
// allocate memory and create management structures
//
if (debug_) {
Log(Debug, "create new memory")
.parameter("Id", this)
.parameter("ArraySize", arraySize)
.parameter("MemorySize", actMemorySize)
.parameter("DataSize", dataSize);
}
char* mem = new char[actMemorySize];
memset(mem, 0x0, actMemorySize);
// create header
dataMemArrayHeader_ = (DataMemArrayHeader*)mem;
dataMemArrayHeader_->eye_[0] = 'H';
dataMemArrayHeader_->eye_[1] = 'E';
dataMemArrayHeader_->eye_[2] = 'A';
dataMemArrayHeader_->eye_[3] = 'D';
dataMemArrayHeader_->maxMemorySize_ = maxMemorySize_;
dataMemArrayHeader_->expandMemorySize_ = expandMemorySize_;
dataMemArrayHeader_->actMemorySize_ = actMemorySize;
dataMemArrayHeader_->actArraySize_ = arraySize;
// create start slot
mem += sizeof(DataMemArrayHeader);
createNewSlot(mem, 'S', 0);
// create free slot
mem += sizeof(DataMemArraySlot) + sizeof(uint32_t);
createNewSlot(mem, 'F', dataSize);
freeSlotMap_.insert(std::make_pair(ptrToPos(mem), (DataMemArraySlot*)mem));
// create end slot
mem += sizeof(DataMemArraySlot) + sizeof(uint32_t) + dataSize;
createNewSlot(mem, 'E', 0);
return true;
}
bool
DataMemArray::increaseMemory(uint32_t size)
{
if (dataMemArrayHeader_ == nullptr) {
return false;
}
// calcualte new memory size
uint32_t usedMemorySize = dataMemArrayHeader_->actMemorySize_ + size + sizeof(DataMemArraySlot) + sizeof(uint32_t);
//
// check max memory size
//
if (maxMemorySize_ != 0 && usedMemorySize > dataMemArrayHeader_->maxMemorySize_) {
Log(Error, "increase memory error - used memory size is bigger then max memory size")
.parameter("Id", this)
.parameter("UsedMemorySize", usedMemorySize)
.parameter("MaxMemorySize", dataMemArrayHeader_->maxMemorySize_);
return false;
}
//
// calculate actual memory size
//
uint32_t newMemorySize = dataMemArrayHeader_->actMemorySize_;
while (usedMemorySize > newMemorySize) newMemorySize += expandMemorySize_;
uint32_t diffMemorySize = newMemorySize - dataMemArrayHeader_->actMemorySize_;
uint32_t arrayMemorySize = dataMemArrayHeader_->actArraySize_ * sizeof(uint32_t);
uint32_t headerSlotMemorySize = dataMemArrayHeader_->actMemorySize_ - arrayMemorySize;
//
// create new memory an copy old memory to new memory
//
char* mem = new char [newMemorySize];
memcpy(mem, (char*)dataMemArrayHeader_, headerSlotMemorySize);
memcpy(&mem[newMemorySize-arrayMemorySize], (char*)dataMemArrayHeader_ + headerSlotMemorySize , arrayMemorySize);
delete [] (char*)dataMemArrayHeader_;
dataMemArrayHeader_ = (DataMemArrayHeader*)mem;
dataMemArrayHeader_->actMemorySize_ = newMemorySize;
//
// create new free slot
//
char *endSlotMem = (char*)dataMemArrayHeader_ + headerSlotMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t);
DataMemArraySlot* actSlot = (DataMemArraySlot*)endSlotMem;
DataMemArraySlot* lastSlot = actSlot->last();
if (lastSlot->type_ == 'F') {
uint32_t newSlotSize = lastSlot->dataSize() + diffMemorySize;
actSlot = createNewSlot((char*)lastSlot, 'F', newSlotSize);
createNewSlot((char*)actSlot->next(), 'E', 0);
}
else {
uint32_t newSlotSize = diffMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t);
actSlot = createNewSlot((char*)actSlot, 'F', newSlotSize);
createNewSlot((char*)actSlot->next(), 'E', 0);
}
//
// create free slot list
//
freeSlotMap_.clear();
DataMemArraySlot* slot = (DataMemArraySlot*)((char*)dataMemArrayHeader_ + sizeof(DataMemArrayHeader));
while (slot->type_ != 'E') {
if (slot->type_ == 'F') {
freeSlotMap_.insert(std::make_pair(ptrToPos((char*)slot), slot));
}
slot = slot->next();
}
return true;
}
DataMemArraySlot*
DataMemArray::createNewSlot(char* mem, char type, uint32_t size, uint32_t paddingSize)
{
// create header
DataMemArraySlot* dataMemArraySlot;
dataMemArraySlot = (DataMemArraySlot*)mem;
dataMemArraySlot->eye_[0] = 'S';
dataMemArraySlot->eye_[1] = 'L';
dataMemArraySlot->eye_[2] = 'O';
dataMemArraySlot->eye_[3] = 'T';
dataMemArraySlot->type_ = type;
dataMemArraySlot->dataSize_ = size;
dataMemArraySlot->paddingSize_ = paddingSize;
uint32_t* sizeTag = (uint32_t*)(mem + sizeof(DataMemArraySlot) + dataMemArraySlot->memSize());
*sizeTag = dataMemArraySlot->memSize();
return dataMemArraySlot;
}
bool
DataMemArray::increaseArraySize(uint32_t arraySize)
{
char* memEnd = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t diffMemorySize = (arraySize - dataMemArrayHeader_->actArraySize_) * sizeof(uint32_t);
uint32_t arrayMemorySize = dataMemArrayHeader_->actArraySize_ * sizeof(uint32_t);
uint32_t headerSlotMemorySize = dataMemArrayHeader_->actMemorySize_ - arrayMemorySize;
// get last two slots
char *endSlotMem = (char*)dataMemArrayHeader_ + headerSlotMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t);
DataMemArraySlot* actSlot = (DataMemArraySlot*)endSlotMem;
DataMemArraySlot* lastSlot = actSlot->last();
if (lastSlot->type_ != 'F') {
if (increaseMemory(1)) {
return increaseArraySize(arraySize);
}
return false;
}
if (lastSlot->dataSize() < diffMemorySize) {
if (increaseMemory(1)) {
return increaseArraySize(arraySize);
}
return false;
}
lastSlot->dataSize_ -= diffMemorySize;
DataMemArraySlot* slot = lastSlot->next();
createNewSlot((char*)slot, 'E', 0);
char* mem = (char*)slot + sizeof(DataMemArraySlot) + sizeof(uint32_t);
memset(mem, 0x00, diffMemorySize);
dataMemArrayHeader_->actArraySize_ = arraySize;
return true;
}
bool
DataMemArray::decreaseArraySize(uint32_t arraySize)
{
char* memEnd = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_;
uint32_t diffMemorySize = (dataMemArrayHeader_->actArraySize_ - arraySize) * sizeof(uint32_t);
uint32_t arrayMemorySize = dataMemArrayHeader_->actArraySize_ * sizeof(uint32_t);
uint32_t headerSlotMemorySize = dataMemArrayHeader_->actMemorySize_ - arrayMemorySize;
// remove entries
for (uint32_t idx = arraySize; idx < dataMemArrayHeader_->actMemorySize_; idx++) {
unset(idx);
}
dataMemArrayHeader_->actArraySize_ = arraySize;
//
// move end slot
//
char *endSlotMem = (char*)dataMemArrayHeader_ + headerSlotMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t);
DataMemArraySlot* actSlot = (DataMemArraySlot*)endSlotMem;
DataMemArraySlot* lastSlot = actSlot->last();
if (lastSlot->type_ == 'U') {
lastSlot->paddingSize_ += diffMemorySize;
}
else {
lastSlot->dataSize_ += diffMemorySize;
}
DataMemArraySlot* slot = lastSlot->next();
createNewSlot((char*)slot, 'E', 0);
return true;
}
}
| 24.909592 | 118 | 0.653565 | gianricardo |
c55d3b2b1b9849962d00f948cc8c4610eef73a73 | 426 | cpp | C++ | srcs/tc.common/byte_buffer.cpp | aoziczero/libtc | 7f5afc2324bc91bf38e53b474d80804b48b546a5 | [
"MIT"
] | null | null | null | srcs/tc.common/byte_buffer.cpp | aoziczero/libtc | 7f5afc2324bc91bf38e53b474d80804b48b546a5 | [
"MIT"
] | null | null | null | srcs/tc.common/byte_buffer.cpp | aoziczero/libtc | 7f5afc2324bc91bf38e53b474d80804b48b546a5 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "byte_buffer.hpp"
namespace tc {
namespace buffer {
position::position(void)
: read(0), write(0) {}
position::position(const position& rhs)
: read(rhs.read), write(rhs.write) {}
position& position::operator=(const position& rhs) {
read = rhs.read;
write = rhs.write;
return *this;
}
void position::swap( position& rhs) {
std::swap(read, rhs.read);
std::swap(write, rhs.write);
}
}
} | 17.04 | 52 | 0.673709 | aoziczero |
c55d9db6533c167fc2bf63e3b8a21726e575a300 | 7,205 | cpp | C++ | audioeffect/deps/avs/src/audio_effect/chorus.cpp | commonprogress/mediasoupdemo | 435d9c5cea81fbe2fb979eb10ecc1f9a45302c01 | [
"MIT"
] | 5 | 2020-04-18T15:29:27.000Z | 2020-09-21T02:47:49.000Z | mediasoup-client/deps/avs/src/audio_effect/chorus.cpp | commonprogress/mediasoupdemo | 435d9c5cea81fbe2fb979eb10ecc1f9a45302c01 | [
"MIT"
] | null | null | null | mediasoup-client/deps/avs/src/audio_effect/chorus.cpp | commonprogress/mediasoupdemo | 435d9c5cea81fbe2fb979eb10ecc1f9a45302c01 | [
"MIT"
] | 4 | 2020-05-17T08:15:12.000Z | 2021-08-23T08:47:10.000Z | /*
* Wire
* Copyright (C) 2016 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <re.h>
#include "chorus.h"
#include "avs_audio_effect.h"
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "avs_log.h"
#ifdef __cplusplus
}
#endif
#define PI 3.1415926536
static void* create_chorus_org(int fs_hz, int strength)
{
int period_len;
struct chorus_org_effect* cho = (struct chorus_org_effect*)calloc(sizeof(struct chorus_org_effect),1);
cho->resampler = new webrtc::PushResampler<int16_t>;
cho->resampler->InitializeIfNeeded(fs_hz, fs_hz*UP_FAC, 1);
cho->fs_khz = (fs_hz/1000);
float max_a = MAX_A;
float max_d_ms = MAX_D_MS;
if(strength < 1){
max_a = max_a * 0.5f;
max_d_ms = max_d_ms * 0.75f;
}
float min_a = MIN_A;
float min_d_ms = MIN_D_MS;
if(strength < 1){
max_a = max_a * 0.5f;
min_d_ms = min_d_ms * 0.75f;
}
#if NUM_RAND_ELEM
period_len = (cho->fs_khz * RAND_PERIOD_MS);
int offset = period_len / NUM_RAND_ELEM;
for(int j = 0; j < NUM_RAND_ELEM; j++){
cho->r_elem[j].max_d = max_d_ms * cho->fs_khz;
cho->r_elem[j].min_d = min_d_ms * cho->fs_khz;
cho->r_elem[j].max_a = max_a;
cho->r_elem[j].min_a = min_a;
cho->r_elem[j].cnt = j*offset;
cho->r_elem[j].period_smpls = period_len;
//cho->elem[j].alpha = 0.001; // to do depend on fs
cho->r_elem[j].alpha = 0.0001;
}
#endif
#if NUM_SINE_ELEM
period_len = (cho->fs_khz * SINE_PERIOD_MS);
float d_omega = (2*PI)/period_len;
for(int j = 0; j < NUM_SINE_ELEM; j++){
cho->s_elem[j].max_d = max_d_ms * cho->fs_khz;
cho->s_elem[j].min_d = min_d_ms * cho->fs_khz;
cho->s_elem[j].max_a = max_a;
cho->s_elem[j].min_a = min_a;
cho->s_elem[j].d_omega = d_omega;
cho->s_elem[j].omega = (PI/2)*j;
}
#endif
return (void*)cho;
}
static void free_chorus_org(void *st)
{
struct chorus_org_effect *cho = (struct chorus_org_effect*)st;
delete cho->resampler;
free(cho);
}
static int16_t update_rand_chorus_elem(struct rand_chorus_elem *r_elem, int16_t buf[], int up_fac)
{
r_elem->cnt++;
if(r_elem->cnt > r_elem->period_smpls){
r_elem->d_next = r_elem->min_d + ((float)rand()/RAND_MAX)*(r_elem->max_d-r_elem->min_d);
r_elem->a_next = r_elem->min_a + ((float)rand()/RAND_MAX)*(r_elem->max_a-r_elem->min_a);
r_elem->cnt = 0;
}
r_elem->d += (r_elem->d_next - r_elem->d) * r_elem->alpha;
r_elem->a += (r_elem->a_next - r_elem->a) * r_elem->alpha;
int d = (int)(r_elem->d * (float)up_fac);
int16_t ret = (int16_t)((float)buf[-d] * r_elem->a);
return ret;
}
static int16_t update_sine_chorus_elem(struct sine_chorus_elem *s_elem, int16_t buf[], int up_fac)
{
s_elem->omega += s_elem->d_omega;
s_elem->omega = fmod(s_elem->omega, 2*3.1415926536);
float s = (sin(s_elem->omega) + 1)/2.0;
s_elem->d = s_elem->min_d + s*(s_elem->max_d-s_elem->min_d);
s_elem->a = s_elem->min_a + (1-s)*(s_elem->max_a-s_elem->min_a);
int d = (int)(s_elem->d * (float)up_fac);
int16_t ret = (int16_t)((float)buf[-d] * s_elem->a);
return ret;
}
static float compress(float x)
{
float y = 1/(exp(-3*x)+1.0f);
y = y - 0.5f;
return y;
}
static void chorus_process_org(void *st, int16_t in[], int16_t out[], size_t L)
{
struct chorus_org_effect *cho = (struct chorus_org_effect*)st;
int32_t tmp = 0;
int16_t *ptr;
int hist_size = (MAX_D_MS * cho->fs_khz) * UP_FAC;
float y, sc1 = 1.0f/(32768.0f*2.0f), sc2 = (32768.0f*2.0f);
int L10 = (cho->fs_khz * 10);
int N = (int)L / L10;
if( N * L10 != L || L > (cho->fs_khz * MAX_L_MS)){
error("chorus_process needs 10 ms chunks max %d ms \n", MAX_L_MS);
}
for( int i = 0; i < N; i++){
cho->resampler->Resample( &in[i*L10], L10, &cho->buf[hist_size + i*L10*UP_FAC], L10*UP_FAC);
}
ptr = &cho->buf[hist_size];
for(size_t i = 0; i < L; i++){
tmp = ptr[i * UP_FAC];
#if NUM_RAND_ELEM
for(int j = 0; j < NUM_RAND_ELEM; j++){
tmp += update_rand_chorus_elem(&cho->r_elem[j], &ptr[i * UP_FAC], UP_FAC);
}
#endif
#if NUM_SINE_ELEM
for(int j = 0; j < NUM_SINE_ELEM; j++){
tmp += update_sine_chorus_elem(&cho->s_elem[j], &ptr[i * UP_FAC], UP_FAC);
}
#endif
y = (float)tmp * sc1;
y = compress(y);
y = y * sc2;
out[i] = (int16_t)y;
}
memmove(cho->buf, &cho->buf[L * UP_FAC], hist_size*sizeof(int16_t)); // todo make circular
}
static void* create_chorus_alt(int fs_hz, int strength)
{
struct chorus_alt_effect* cho = (struct chorus_alt_effect*)calloc(sizeof(struct chorus_alt_effect),1);
cho->pse1 = create_pitch_up_shift(fs_hz, 0);
cho->pse2 = create_pitch_down_shift(fs_hz, 0);
return (void*)cho;
}
static void free_chorus_alt(void *st)
{
struct chorus_alt_effect *cho = (struct chorus_alt_effect*)st;
free_pitch_shift(cho->pse1);
free_pitch_shift(cho->pse2);
free(cho);
}
static void chorus_process_alt(void *st, int16_t in[], int16_t out[], size_t L)
{
struct chorus_alt_effect *cho = (struct chorus_alt_effect*)st;
int16_t out1[L], out2[L];
int32_t tmp;
float y, sc1 = 1.0f/(32768.0f*2.0f), sc2 = (32768.0f*2.0f);
size_t L_out;
pitch_shift_process(cho->pse1, in, out1, L, &L_out);
pitch_shift_process(cho->pse2, in, out2, L, &L_out);
for(int i = 0; i < L; i++){
tmp = in[i] + out1[i] + out2[i];
y = (float)tmp * sc1;
y = compress(y);
y = y * sc2;
out[i] = (int16_t)y;
}
}
void* create_chorus(int fs_hz, int strength)
{
struct chorus_effect* cho = (struct chorus_effect*)calloc(sizeof(struct chorus_effect),1);
cho->strength = strength;
if(strength > 0){
cho->st = create_chorus_org(fs_hz, strength - 1);
} else {
cho->st = create_chorus_alt(fs_hz, 0);
}
return (void*)cho;
}
void free_chorus(void *st)
{
struct chorus_effect *cho = (struct chorus_effect*)st;
if(cho->strength > 0){
free_chorus_org(cho->st);
} else {
free_chorus_alt(cho->st);
}
free(cho);
}
void chorus_process(void *st, int16_t in[], int16_t out[], size_t L_in, size_t *L_out)
{
struct chorus_effect *cho = (struct chorus_effect*)st;
if(cho->strength > 0){
chorus_process_org(cho->st, in, out, L_in);
} else {
chorus_process_alt(cho->st, in, out, L_in);
}
*L_out = L_in;
}
| 28.035019 | 106 | 0.618598 | commonprogress |
c5616bc52ef596f1e13ae3119a9f081d71454c08 | 6,722 | cpp | C++ | RogueEngine/Source/LightingSystem.cpp | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | 1 | 2019-06-18T20:07:47.000Z | 2019-06-18T20:07:47.000Z | RogueEngine/Source/LightingSystem.cpp | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | null | null | null | RogueEngine/Source/LightingSystem.cpp | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | null | null | null | /* Start Header ************************************************************************/
/*!
\file LightingSystem.cpp
\project Exale
\author Javier Foo, javier.foo, 440002318 (100%)
\par javier.foo\@digipen.edu
\date 3 April,2020
\brief This file contains the functions definitions for LightingSystem
All content (C) 2020 DigiPen (SINGAPORE) Corporation, all rights
reserved.
Reproduction or disclosure of this file or its contents
without the prior written consent of DigiPen Institute of
Technology is prohibited.
*/
/* End Header **************************************************************************/
#include "Precompiled.h"
#include "LightingSystem.h"
#include "Main.h"
#include "CameraManager.h"
#include "CollisionManager.h"
#include "PickingManager.h"
namespace Rogue
{
LightingSystem::LightingSystem()
: System(SystemID::id_LIGHTINGSYSTEM)
{}
void LightingSystem::Init()
{
REGISTER_LISTENER(SystemID::id_LIGHTINGSYSTEM, LightingSystem::Receive);
// Add components to signature
Signature signature;
signature.set(g_engine.m_coordinator.GetComponentType<LightComponent>());
signature.set(g_engine.m_coordinator.GetComponentType<TransformComponent>());
// Set graphics system signature
g_engine.m_coordinator.SetSystemSignature<LightingSystem>(signature);
m_shader = g_engine.m_coordinator.loadShader("Lighting Shader");
m_uboMatrices = g_engine.m_coordinator.GetSystem<Rogue::GraphicsSystem>()->getUBOMatrices();
m_transformLocation = glGetUniformLocation(m_shader.GetShader(), "transform");
m_pCamera = g_engine.m_coordinator.GetSystem<CameraSystem>();
m_graphicsShader = g_engine.m_coordinator.GetSystem<GraphicsSystem>()->getShader();
m_totalLightsLocation = glGetUniformLocation(m_graphicsShader.GetShader(), "numLights");
GenerateQuadPrimitive(m_VBO, m_VAO, m_EBO);
}
void LightingSystem::Update()
{
}
void LightingSystem::draw(Entity& entity)
{
auto& transform = g_engine.m_coordinator.GetComponent<TransformComponent>(entity);
auto transformMat = glm::mat4(1.0f);
transformMat = glm::translate(transformMat, { transform.GetPosition().x, transform.GetPosition().y, 1.0f });
transformMat = glm::rotate(transformMat, transform.GetRotation(), glm::vec3(0.0f, 0.0f, 1.0f));
transformMat = glm::scale(transformMat, glm::vec3(10.0f));
// model to world, world to view, view to projection
glUniformMatrix4fv(m_transformLocation, 1, GL_FALSE, glm::value_ptr(transformMat));
// Draw the Mesh
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
void LightingSystem::TrueUpdate()
{
//g_engine.m_coordinator.InitTimeSystem("Lighting System");
if (m_entities.size() == 0)
return;
PickingManager::instance().GenerateViewPortAABB(CameraManager::instance().GetCameraPos(), CameraManager::instance().GetCameraZoom());
AABB viewPort = PickingManager::instance().GetViewPortArea();
viewPort += 200;
glUseProgram(m_shader.GetShader());
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBindBuffer(GL_UNIFORM_BUFFER, m_uboMatrices);
//glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), glm::value_ptr(g_engine.GetProjMat()));
//glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(m_pCamera->GetViewMatrix()));
// For all entities
for (auto entity : m_entities)
{
//auto& transform = g_engine.m_coordinator.GetComponent<TransformComponent>(entity);
//if (CollisionManager::instance().DiscretePointVsAABB(transform.GetPosition(), viewPort))
++totalLights;
// AddLights(entity);
if (!g_engine.m_coordinator.GetGameState())
draw(entity);
}
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glUseProgram(0);
glBindVertexArray(0); //Reset
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(m_graphicsShader.GetShader());
glUniform1i(m_totalLightsLocation, totalLights);
// For all entities
for (auto entity : m_entities)
{
--totalLights;
auto& transform = g_engine.m_coordinator.GetComponent<TransformComponent>(entity);
if (CollisionManager::instance().DiscretePointVsAABB(transform.GetPosition(), viewPort))
UpdateShader(entity);
else
ClearLight();
}
glUseProgram(0);
//g_engine.m_coordinator.EndTimeSystem("Lighting System");
}
void LightingSystem::AddLights(Entity& entity)
{
auto& light = g_engine.m_coordinator.GetComponent<LightComponent>(entity);
auto position = g_engine.m_coordinator.GetComponent<TransformComponent>(entity).GetPosition();
LightProperites newLight;
newLight.position = { position.x, position.y, 1.0f };
newLight.ambient = light.getAmbientFactor();
newLight.specular = light.getSpecularFactor();
newLight.radius = light.getRadius();
newLight.tint = light.getTint();
lights[totalLights] = newLight;
}
void LightingSystem::UpdateShader(Entity& entity)
{
auto& light = g_engine.m_coordinator.GetComponent<LightComponent>(entity);
auto position = g_engine.m_coordinator.GetComponent<TransformComponent>(entity).GetPosition();
std::string lightLocation = "light[" + std::to_string(totalLights) + ']';
float ambient = light.getAmbientFactor();
float specular = light.getSpecularFactor();
float radius = light.getRadius();
glm::vec4 tint = light.getTint();
glUniform3f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".position").c_str()), position.x, position.y, 1.0f);
glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".ambient").c_str()), ambient);
glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".specular").c_str()), specular);
glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".radius").c_str()), radius);
glUniform4fv(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".tint").c_str()), 1, glm::value_ptr(tint));
}
void LightingSystem::ClearLight()
{
std::string lightLocation = "light[" + std::to_string(totalLights) + ']';
glm::vec4 tint{};
glUniform3f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".position").c_str()), 0.0f, 0.0f, 1.0f);
glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".ambient").c_str()), 0.0f);
glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".specular").c_str()), 0.0f);
glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".radius").c_str()), 0.0f);
glUniform4fv(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".tint").c_str()), 1, glm::value_ptr(tint));
}
void LightingSystem::Shutdown()
{}
void LightingSystem::Receive(Event& ev)
{}
} | 35.566138 | 135 | 0.728652 | silferysky |
c5618218a5567b0c742550c8da8eb15e33e41a31 | 2,541 | cpp | C++ | src/system/boot/platform/riscv/mmu.cpp | X547/haiku | 87555a1f4f2fdab7617c670ef0b5875698e5db63 | [
"MIT"
] | 2 | 2021-06-05T20:29:57.000Z | 2021-06-20T10:46:56.000Z | src/system/boot/platform/riscv/mmu.cpp | X547/haiku | 87555a1f4f2fdab7617c670ef0b5875698e5db63 | [
"MIT"
] | null | null | null | src/system/boot/platform/riscv/mmu.cpp | X547/haiku | 87555a1f4f2fdab7617c670ef0b5875698e5db63 | [
"MIT"
] | null | null | null | /*
* Copyright 2004-2007, Axel Dörfler, axeld@pinc-software.de.
* Based on code written by Travis Geiselbrecht for NewOS.
*
* Distributed under the terms of the MIT License.
*/
#include "mmu.h"
#include <boot/platform.h>
#include <boot/stdio.h>
#include <boot/kernel_args.h>
#include <boot/stage2.h>
#include <arch/cpu.h>
#include <arch_kernel.h>
#include <kernel.h>
#include <OS.h>
#include <string.h>
extern uint8 gStackEnd;
uint8 *gMemBase = NULL;
size_t gTotalMem = 0;
uint8 *gFreeMem = &gStackEnd;
// #pragma mark -
extern "C" status_t platform_allocate_region(void **_address, size_t size, uint8 protection, bool exactAddress)
{
if (exactAddress)
return B_ERROR;
gFreeMem = (uint8*)(((addr_t)gFreeMem + (B_PAGE_SIZE - 1)) / B_PAGE_SIZE * B_PAGE_SIZE);
*_address = gFreeMem;
gFreeMem += size;
return B_OK;
}
extern "C" status_t platform_free_region(void *address, size_t size)
{
return B_OK;
}
void platform_release_heap(struct stage2_args *args, void *base)
{
}
status_t platform_init_heap(struct stage2_args *args, void **_base, void **_top)
{
void *heap = (void *)gFreeMem;
gFreeMem += args->heap_size;
*_base = heap;
*_top = (void *)((int8 *)heap + args->heap_size);
return B_OK;
}
status_t platform_bootloader_address_to_kernel_address(void *address, addr_t *_result)
{
*_result = (addr_t)address;
return B_OK;
}
status_t platform_kernel_address_to_bootloader_address(addr_t address, void **_result)
{
*_result = (void*)address;
return B_OK;
}
void mmu_init(void)
{
}
void mmu_init_for_kernel(void)
{
// map in a kernel stack
void *stack_address = NULL;
if (platform_allocate_region(&stack_address,
KERNEL_STACK_SIZE + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE, 0, false)
!= B_OK) {
panic("Unabled to allocate a stack");
}
gKernelArgs.cpu_kstack[0].start = (addr_t)stack_address;
gKernelArgs.cpu_kstack[0].size = KERNEL_STACK_SIZE
+ KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE;
dprintf("Kernel stack at %#lx\n", gKernelArgs.cpu_kstack[0].start);
gKernelArgs.physical_memory_range[0].start = (addr_t)gMemBase;
gKernelArgs.physical_memory_range[0].size = gTotalMem;
gKernelArgs.num_physical_memory_ranges = 1;
gKernelArgs.physical_allocated_range[0].start = (addr_t)gMemBase;
gKernelArgs.physical_allocated_range[0].size = gFreeMem - gMemBase;
gKernelArgs.num_physical_allocated_ranges = 1;
gKernelArgs.virtual_allocated_range[0].start = (addr_t)gMemBase;
gKernelArgs.virtual_allocated_range[0].size = gFreeMem - gMemBase;
gKernelArgs.num_virtual_allocated_ranges = 1;
}
| 23.971698 | 111 | 0.748524 | X547 |
c573887528dbd30b420c869862d371f8393ea45f | 3,599 | cpp | C++ | src/gravity/grav3D.cpp | capybaras-only/cholla | e82d88440f530adca00e5acdb9ee0da9ba8874de | [
"MIT"
] | 42 | 2016-07-19T02:07:16.000Z | 2022-02-22T15:20:07.000Z | src/gravity/grav3D.cpp | capybaras-only/cholla | e82d88440f530adca00e5acdb9ee0da9ba8874de | [
"MIT"
] | 34 | 2018-10-23T04:03:25.000Z | 2022-03-24T15:23:36.000Z | src/gravity/grav3D.cpp | capybaras-only/cholla | e82d88440f530adca00e5acdb9ee0da9ba8874de | [
"MIT"
] | 30 | 2016-04-14T17:52:34.000Z | 2022-02-25T15:52:02.000Z | #ifdef GRAVITY
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include"../global.h"
#include "../io.h"
#include"grav3D.h"
#ifdef PARALLEL_OMP
#include "../parallel_omp.h"
#endif
Grav3D::Grav3D( void ){}
void Grav3D::Initialize( Real x_min, Real y_min, Real z_min, Real Lx, Real Ly, Real Lz, int nx, int ny, int nz, int nx_real, int ny_real, int nz_real, Real dx_real, Real dy_real, Real dz_real, int n_ghost_pot_offset, struct parameters *P )
{
//Set Box Size
Lbox_x = Lx;
Lbox_y = Ly;
Lbox_z = Lz;
//Set Box Left boundary positions
xMin = x_min;
yMin = y_min;
zMin = z_min;
//Set uniform ( dx, dy, dz )
dx = dx_real;
dy = dy_real;
dz = dz_real;
//Set Box Total number of cells
nx_total = nx;
ny_total = ny;
nz_total = nz;
//Set Box local domain number of cells
nx_local = nx_real;
ny_local = ny_real;
nz_local = nz_real;
//Local n_cells without ghost cells
n_cells = nx_local*ny_local*nz_local;
//Local n_cells including ghost cells for the potential array
n_cells_potential = ( nx_local + 2*N_GHOST_POTENTIAL ) * ( ny_local + 2*N_GHOST_POTENTIAL ) * ( nz_local + 2*N_GHOST_POTENTIAL );
//Set Initial and dt used for the extrapolation of the potential;
//The first timestep the potetential in not extrapolated ( INITIAL = TRUE )
INITIAL = true;
dt_prev = 0;
dt_now = 0;
#ifdef COSMOLOGY
//Set the scale factor for cosmological simulations to 1,
//This will be changed to the proper value when cosmology is initialized
current_a = 1;
#endif
//Set the average density=0 ( Not Used )
dens_avrg = 0;
//Set the Gravitational Constant ( units must be consistent )
Gconst = GN;
if (strcmp(P->init, "Spherical_Overdensity_3D")==0){
Gconst = 1;
chprintf(" WARNING: Using Gravitational Constant G=1.\n");
}
//Flag too transfer the Potential boundaries
TRANSFER_POTENTIAL_BOUNDARIES = false;
AllocateMemory_CPU();
Initialize_values_CPU();
chprintf( "Gravity Initialized: \n Lbox: %0.2f %0.2f %0.2f \n Local: %d %d %d \n Global: %d %d %d \n",
Lbox_x, Lbox_y, Lbox_z, nx_local, ny_local, nz_local, nx_total, ny_total, nz_total );
chprintf( " dx:%f dy:%f dz:%f\n", dx, dy, dz );
chprintf( " N ghost potential: %d\n", N_GHOST_POTENTIAL);
chprintf( " N ghost offset: %d\n", n_ghost_pot_offset);
#ifdef PARALLEL_OMP
chprintf(" Using OMP for gravity calculations\n");
int n_omp_max = omp_get_max_threads();
chprintf(" MAX OMP Threads: %d\n", n_omp_max);
chprintf(" N OMP Threads per MPI process: %d\n", N_OMP_THREADS);
#endif
Poisson_solver.Initialize( Lbox_x, Lbox_y, Lbox_z, xMin, yMin, zMin, nx_total, ny_total, nz_total, nx_local, ny_local, nz_local, dx, dy, dz );
}
void Grav3D::AllocateMemory_CPU(void)
{
// allocate memory for the density and potential arrays
F.density_h = (Real *) malloc(n_cells*sizeof(Real)); //array for the density
F.potential_h = (Real *) malloc(n_cells_potential*sizeof(Real)); //array for the potential at the n-th timestep
F.potential_1_h = (Real *) malloc(n_cells_potential*sizeof(Real)); //array for the potential at the (n-1)-th timestep
}
void Grav3D::Initialize_values_CPU(void){
//Set initial values to 0.
for (int id=0; id<n_cells; id++){
F.density_h[id] = 0;
}
for (int id_pot=0; id_pot<n_cells_potential; id_pot++){
F.potential_h[id_pot] = 0;
F.potential_1_h[id_pot] = 0;
}
}
void Grav3D::FreeMemory_CPU(void)
{
free(F.density_h);
free(F.potential_h);
free(F.potential_1_h);
Poisson_solver.Reset();
}
#endif //GRAVITY | 27.684615 | 239 | 0.684357 | capybaras-only |
c577745f7b251e3cc806bdab313a588d8658dd06 | 558 | cpp | C++ | gym/102343/A.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | 1 | 2021-07-16T19:59:39.000Z | 2021-07-16T19:59:39.000Z | gym/102343/A.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | gym/102343/A.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#ifdef Adrian
#include "debug.h"
#else
#define debug(...)
#endif
typedef long long ll;
typedef long double ld;
typedef complex<ll> point;
#define F first
#define S second
int main()
{
#ifdef Adrian
freopen("a.txt", "r", stdin);
//freopen("b.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(0), cin.tie(0);
int n,d;
cin>>n>>d;
vector<int>arr(n);
int cant=0;
for(int i=0; i<n; i++)
{
cin>>arr[i];
cant+=arr[i];
}
d/=cant;
for(int i=0; i<n; i++)
cout<<arr[i]*d<<"\n";
return 0;
} | 13.285714 | 42 | 0.605735 | albexl |
c57a3fca23220599107fc435834ed25300d0e4e8 | 3,492 | hpp | C++ | src/transformations.hpp | RedErr404/cprocessing | ab8ef25ea3e4bcd915f9c086b649696866ea77ca | [
"BSD-2-Clause"
] | 12 | 2015-01-12T07:43:22.000Z | 2022-03-08T06:43:20.000Z | src/transformations.hpp | RedErr404/cprocessing | ab8ef25ea3e4bcd915f9c086b649696866ea77ca | [
"BSD-2-Clause"
] | null | null | null | src/transformations.hpp | RedErr404/cprocessing | ab8ef25ea3e4bcd915f9c086b649696866ea77ca | [
"BSD-2-Clause"
] | 7 | 2015-02-09T15:44:10.000Z | 2019-07-07T11:48:10.000Z | #include "cprocessing.hpp"
#ifndef CPROCESSING_TRANSFORMATIONS_
#define CPROCESSING_TRANSFORMATIONS_
using namespace cprocessing;
namespace cprocessing {
/// Applies a translation transformation
void translate (double dx, double dy, double dz);
void translate(double dx, double dy);
/// Applies a scale transformation
void scale (double dx, double dy, double dz);
void scale(double dx, double dy);
/// Applies a uniform scale
inline void scale (double factor) { scale (factor, factor, factor); }
/// Applies a rotation transformation
void rotate (double radians, double axisx, double axisy, double axisz);
inline void rotateX (double radians) { rotate(radians, 1, 0, 0); }
inline void rotateY (double radians) { rotate(radians, 0, 1, 0); }
inline void rotateZ (double radians) { rotate(radians, 0, 0, 1); }
inline void rotate (double radians) { rotateZ(radians); }
/// Resets the transformation to none
void resetMatrix();
/// Fills matrix with the current transformation matrix
void getMatrix (double matrix [16]);
/// Multiplies given matrix by current transformation matrix
void applyMatrix (double matrix [16]);
/// Duplicates the top of the matrix stack
void pushMatrix();
/// Discards the top of the matrix stack
void popMatrix();
/// Creates a viewing transformation given the camera position
/// (eyex,eyey,eyez), the center of the scene (centerx, centery, centerz) and
/// a vector to be used as the up direction (upx, upy, upz). If no args
/// are passed, the standard camera is created.
void camera (double eyeX, double eyeY, double eyeZ,
double centerX, double centerY, double centerZ,
double upX, double upY, double upZ);
void camera ();
/// Loads a perspective projection matrix, where
/// fov is the field-of-view angle (in radians) for vertical direction, aspect
/// is the ratio of width to height, znear is the z-position of nearest clipping
/// plane and zfar is the z-position of nearest farthest plane. If no args are
/// passed, the standard projection is created, i.e, equivalent to
/// perspective(PI/3.0, width/height, cameraZ/10.0, cameraZ*10.0)
/// where cameraZ is ((height/2.0) / tan(PI*60.0/360.0))
void perspective(double fov, double aspect, double znear, double zfar);
void perspective ();
/// Loads an orthogonal projection matrix.
/// The clipping volume in this case is an axes-aligned parallelepiped, where
/// left and right are the minimum and maximum x values, top and bottom are
/// the minimum and maximum y values, and near and far are the minimum and
/// maximum z values. If no parameters are given, the default is used:
/// ortho(0, width, 0, height, -height*2, height*2).
void ortho(double left, double right, double bottom, double top, double near, double far);
void ortho ();
/// Returns the projected space coordinates of object coordinates ox,oy,oz
void screenXYZ (double ox, double oy, double oz,
double& sx, double& sy, double& sz);
inline double screenX (double ox, double oy, double oz) {
double tmpx, tmpy, tmpz;
screenXYZ (ox, oy, oz, tmpx, tmpy, tmpz);
return tmpx;
}
inline double screenY (double ox, double oy, double oz) {
double tmpx, tmpy, tmpz;
screenXYZ (ox, oy, oz, tmpx, tmpy, tmpz);
return tmpy;
}
inline double screenZ (double ox, double oy, double oz) {
double tmpx, tmpy, tmpz;
screenXYZ (ox, oy, oz, tmpx, tmpy, tmpz);
return tmpz;
}
}
#endif | 36.757895 | 91 | 0.702463 | RedErr404 |
c57c25237f51093201dc7a67043e3023da3bc325 | 3,002 | cpp | C++ | aws-cpp-sdk-kafkaconnect/source/model/CustomPluginRevisionSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-kafkaconnect/source/model/CustomPluginRevisionSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-kafkaconnect/source/model/CustomPluginRevisionSummary.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/kafkaconnect/model/CustomPluginRevisionSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace KafkaConnect
{
namespace Model
{
CustomPluginRevisionSummary::CustomPluginRevisionSummary() :
m_contentType(CustomPluginContentType::NOT_SET),
m_contentTypeHasBeenSet(false),
m_creationTimeHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_fileDescriptionHasBeenSet(false),
m_locationHasBeenSet(false),
m_revision(0),
m_revisionHasBeenSet(false)
{
}
CustomPluginRevisionSummary::CustomPluginRevisionSummary(JsonView jsonValue) :
m_contentType(CustomPluginContentType::NOT_SET),
m_contentTypeHasBeenSet(false),
m_creationTimeHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_fileDescriptionHasBeenSet(false),
m_locationHasBeenSet(false),
m_revision(0),
m_revisionHasBeenSet(false)
{
*this = jsonValue;
}
CustomPluginRevisionSummary& CustomPluginRevisionSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("contentType"))
{
m_contentType = CustomPluginContentTypeMapper::GetCustomPluginContentTypeForName(jsonValue.GetString("contentType"));
m_contentTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("creationTime"))
{
m_creationTime = jsonValue.GetString("creationTime");
m_creationTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("description"))
{
m_description = jsonValue.GetString("description");
m_descriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("fileDescription"))
{
m_fileDescription = jsonValue.GetObject("fileDescription");
m_fileDescriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("location"))
{
m_location = jsonValue.GetObject("location");
m_locationHasBeenSet = true;
}
if(jsonValue.ValueExists("revision"))
{
m_revision = jsonValue.GetInt64("revision");
m_revisionHasBeenSet = true;
}
return *this;
}
JsonValue CustomPluginRevisionSummary::Jsonize() const
{
JsonValue payload;
if(m_contentTypeHasBeenSet)
{
payload.WithString("contentType", CustomPluginContentTypeMapper::GetNameForCustomPluginContentType(m_contentType));
}
if(m_creationTimeHasBeenSet)
{
payload.WithString("creationTime", m_creationTime.ToGmtString(DateFormat::ISO_8601));
}
if(m_descriptionHasBeenSet)
{
payload.WithString("description", m_description);
}
if(m_fileDescriptionHasBeenSet)
{
payload.WithObject("fileDescription", m_fileDescription.Jsonize());
}
if(m_locationHasBeenSet)
{
payload.WithObject("location", m_location.Jsonize());
}
if(m_revisionHasBeenSet)
{
payload.WithInt64("revision", m_revision);
}
return payload;
}
} // namespace Model
} // namespace KafkaConnect
} // namespace Aws
| 21.912409 | 121 | 0.747169 | perfectrecall |
c5803d143bab4da00ffd9db701bfe609cde46cd0 | 2,818 | cpp | C++ | tightvnc/server-config-lib/PortMapping.cpp | jjzhang166/qmlvncviewer2 | b888c416ab88b81fe802ab0559bb87361833a0b5 | [
"Apache-2.0"
] | 47 | 2016-08-17T03:18:32.000Z | 2022-01-14T01:33:15.000Z | tightvnc/server-config-lib/PortMapping.cpp | jjzhang166/qmlvncviewer2 | b888c416ab88b81fe802ab0559bb87361833a0b5 | [
"Apache-2.0"
] | 3 | 2018-06-29T06:13:28.000Z | 2020-11-26T02:31:49.000Z | tightvnc/server-config-lib/PortMapping.cpp | jjzhang166/qmlvncviewer2 | b888c416ab88b81fe802ab0559bb87361833a0b5 | [
"Apache-2.0"
] | 15 | 2016-08-17T07:03:55.000Z | 2021-08-02T14:42:02.000Z | // Copyright (C) 2008,2009,2010,2011,2012 GlavSoft LLC.
// All rights reserved.
//
//-------------------------------------------------------------------------
// This file is part of the TightVNC software. Please visit our Web site:
//
// http://www.tightvnc.com/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; 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 "PortMapping.h"
#include "util/StringParser.h"
#include <tchar.h>
#include <stdio.h>
PortMapping::PortMapping()
: m_port(0)
{
}
PortMapping::PortMapping(int nport, PortMappingRect nrect)
: m_port(nport), m_rect(nrect)
{
}
PortMapping::PortMapping(const PortMapping &other)
: m_port(other.m_port), m_rect(other.m_rect)
{
}
PortMapping::~PortMapping()
{
}
PortMapping &PortMapping::operator=(const PortMapping &other)
{
m_port = other.m_port;
m_rect = other.m_rect;
return *this;
}
bool PortMapping::isEqualTo(const PortMapping *other) const
{
return other->m_port == m_port && other->m_rect.isEqualTo(&m_rect);
}
void PortMapping::setPort(int nport)
{
m_port = nport;
}
void PortMapping::setRect(PortMappingRect nrect)
{
m_rect = nrect;
}
int PortMapping::getPort() const
{
return m_port;
}
PortMappingRect PortMapping::getRect() const
{
return m_rect;
}
void PortMapping::toString(StringStorage *string) const
{
//
// Format: [port]:[rect.toString()]
// It means: [port]:[width]x[height]+[x]+[y]
// without square brackets.
//
StringStorage rectString;
m_rect.toString(&rectString);
string->format(_T("%d:%s"), m_port, rectString.getString());
}
bool PortMapping::parse(const TCHAR *str, PortMapping *mapping)
{
int port;
TCHAR c;
PortMappingRect rect;
const TCHAR *rectString = _tcschr(str, _T(':')) + 1;
if (rectString == NULL) {
return false;
}
if ((_stscanf(str, _T("%d%c"), &port, &c) != 2) || (c != _T(':'))) {
return false;
}
if (port < 0) {
return false;
}
if (!PortMappingRect::parse(rectString, &rect)) {
return false;
}
if (mapping != NULL) {
mapping->setPort(port);
mapping->setRect(rect);
}
return true;
}
| 23.483333 | 75 | 0.648332 | jjzhang166 |
c5816c489ad6d191622911f0ed29136689f2752d | 2,767 | cpp | C++ | Eldritch-Source/Code/Libraries/3D/src/D3D9/d3d9vertexdeclaration.cpp | inferno986return/eldritch-mirror | fefdb06f392b3f8c17f0617a1101c503620bc6fd | [
"Zlib",
"Unlicense"
] | 91 | 2015-01-27T22:56:26.000Z | 2022-03-25T13:33:18.000Z | Code/Libraries/3D/src/D3D9/d3d9vertexdeclaration.cpp | rohit-n/Eldritch | b1d2a200eac9c8026e696bdac1f7d2ca629dd38c | [
"Zlib"
] | 2 | 2019-01-04T21:42:26.000Z | 2019-01-06T14:34:08.000Z | Code/Libraries/3D/src/D3D9/d3d9vertexdeclaration.cpp | Neb-Software/mEldritch | 7d07a845b3f04242ddf1f0abbad606c830ac8f20 | [
"Zlib"
] | 21 | 2015-04-06T17:41:17.000Z | 2021-06-15T00:26:18.000Z | #include "core.h"
#include "3d.h"
#include "D3D9/d3d9vertexdeclaration.h"
#include "map.h"
#include "mathcore.h"
#include <d3d9.h>
D3D9VertexDeclaration::D3D9VertexDeclaration( IDirect3DDevice9* pD3DDevice )
: m_D3DDevice( pD3DDevice )
, m_VertexDeclaration( NULL )
, m_VertexSignature( 0 ) {}
D3D9VertexDeclaration::~D3D9VertexDeclaration()
{
SafeRelease( m_VertexDeclaration );
}
void D3D9VertexDeclaration::Initialize( uint VertexSignature )
{
m_VertexSignature = VertexSignature;
uint NumElements = CountBits( VertexSignature );
D3DVERTEXELEMENT9* pVertexElements = new D3DVERTEXELEMENT9[ NumElements + 1 ];
uint Index = 0;
// "if( SIG == ... )" is done so that 0 is acceptable for SIG
#define CREATESTREAM( NUM, SIG, TYPE, USAGE, INDEX ) \
if( SIG == ( VertexSignature & SIG ) ) \
{ \
pVertexElements[ Index ].Stream = (WORD)NUM; \
pVertexElements[ Index ].Offset = 0; \
pVertexElements[ Index ].Type = TYPE; \
pVertexElements[ Index ].Method = D3DDECLMETHOD_DEFAULT; \
pVertexElements[ Index ].Usage = USAGE; \
pVertexElements[ Index ].UsageIndex = INDEX; \
Index++; \
}
CREATESTREAM( Index, VD_POSITIONS, D3DDECLTYPE_FLOAT3, D3DDECLUSAGE_POSITION, 0 );
CREATESTREAM( Index, VD_COLORS, D3DDECLTYPE_D3DCOLOR, D3DDECLUSAGE_COLOR, 0 );
#if USE_HDR
CREATESTREAM( Index, VD_FLOATCOLORS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_COLOR, 0 );
CREATESTREAM( Index, VD_BASISCOLORS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_COLOR, 1 );
CREATESTREAM( Index, VD_BASISCOLORS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_COLOR, 2 );
// For SM2 cards, an alternative way to do HDR colors
CREATESTREAM( Index, VD_FLOATCOLORS_SM2, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TEXCOORD, 1 );
CREATESTREAM( Index, VD_BASISCOLORS_SM2, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TEXCOORD, 2 );
CREATESTREAM( Index, VD_BASISCOLORS_SM2, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TEXCOORD, 3 );
#endif
CREATESTREAM( Index, VD_UVS, D3DDECLTYPE_FLOAT2, D3DDECLUSAGE_TEXCOORD, 0 );
CREATESTREAM( Index, VD_NORMALS, D3DDECLTYPE_FLOAT3, D3DDECLUSAGE_NORMAL, 0 );
CREATESTREAM( Index, VD_TANGENTS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TANGENT, 0 );
CREATESTREAM( Index, VD_BONEINDICES, D3DDECLTYPE_UBYTE4, D3DDECLUSAGE_BLENDINDICES, 0 );
CREATESTREAM( Index, VD_BONEWEIGHTS, D3DDECLTYPE_UBYTE4N, D3DDECLUSAGE_BLENDWEIGHT, 0 );
CREATESTREAM( 0xFF, 0, D3DDECLTYPE_UNUSED, 0, 0 );
#undef CREATESTREAM
m_D3DDevice->CreateVertexDeclaration( pVertexElements, &m_VertexDeclaration );
SafeDelete( pVertexElements );
}
void* D3D9VertexDeclaration::GetDeclaration()
{
return m_VertexDeclaration;
}
uint D3D9VertexDeclaration::GetSignature()
{
return m_VertexSignature;
} | 37.391892 | 90 | 0.733647 | inferno986return |